diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index bac96333203..423ee458e66 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -42,11 +42,12 @@ next to them. | `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) | | `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) | | `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) | -| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg` (115 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (116 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/crop-overlay-*.svg` | Crop overlay glyphs: Rule of Thirds, Grid, Diagonal, Triangle, Golden Ratio and Golden Spiral inside the crop-mark frame | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | +| `assets/icons/spirit-level.svg` | Straighten tool glyph: a spirit level with its vial and bubble under a dotted arc | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/sampler.svg` | Color Sampler tool glyph: a target reticle marking a sampled pixel | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/font-similar.svg`, `assets/icons/font-variable.svg` | Font menu filter glyphs: two waves (Show Similar Fonts) and a T over a slider (Show Variable Fonts), drawn on the 24 px icon grid | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/convert-point.svg` | Convert Point tool glyph: an angle with a square anchor on its apex, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | @@ -58,6 +59,7 @@ next to them. | `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/clip-below.svg`, `assets/icons/clip-release.svg` | Clipping-mask cursors (⌥ over the line between two layers): a hooked arrow onto the layer below; the same with a small "no" badge to release | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/layer-mask.svg`, `assets/icons/adjustment-layer.svg` | Layers panel footer glyphs: Add a mask (a frame around a solid disc) and New Fill or Adjustment Layer (a circle, one half solid), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | +| `assets/icons/vertical-align-{top,middle,bottom}.svg` | Type options-bar alignment glyphs for vertical text: three columns hanging from a top line, centred on a middle line, or standing on a bottom line, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/align-edge-*.svg`, `assets/icons/distribute-*.svg` | Move tool options-bar glyphs: Align (six edges/centres) and Distribute (edges, centres, spacing), a guide line or edge lines with bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/ellipse-dashed.svg` | Elliptical Marquee tool glyph: a dashed horizontal ellipse, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/frame-placeholder.svg` | Frame tool glyph: an empty placeholder frame, crossed corner to corner | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index 434e4b6aa8a..f650cccdda9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1406,17 +1406,17 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1439,7 +1439,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "thiserror 2.0.21", ] @@ -1457,7 +1457,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "bytemuck", "hayro", @@ -1469,7 +1469,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "craft-winprint-gdi", "log", @@ -1483,7 +1483,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1504,7 +1504,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "chrono", "dunce", @@ -1530,7 +1530,7 @@ dependencies = [ [[package]] name = "craft-winprint-gdi" version = "0.1.0" -source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312" +source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f" dependencies = [ "windows-sys 0.61.2", ] @@ -2964,7 +2964,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "bytemuck", "hayro-interpret", @@ -2994,7 +2994,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3012,7 +3012,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3036,7 +3036,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "flate2", "hayro-ccitt", @@ -5618,6 +5618,7 @@ dependencies = [ "crc32fast", "flate2", "imagesize", + "kurbo 0.13.1", "lopdf", "miniz_oxide 0.9.1", "photocraft-affinity", @@ -5766,7 +5767,7 @@ dependencies = [ "photocraft-psd", "photocraft-raster", "rayon", - "skrifa 0.44.0", + "skrifa 0.47.0", ] [[package]] @@ -9472,7 +9473,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49" +source = "git+https://github.com/storytold/winprint.rs?rev=51934db382f225454cf152a8657eb03789be63c4#51934db382f225454cf152a8657eb03789be63c4" dependencies = [ "flate2", "fmt-derive", @@ -10005,7 +10006,6 @@ dependencies = [ "nix", "typed-path", "windows-sys 0.61.2", - "zopfli", ] [[package]] @@ -10020,18 +10020,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zopfli" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zune-core" version = "0.4.12" diff --git a/Cargo.toml b/Cargo.toml index f5fafa868d5..cd2f69a6651 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } @@ -39,13 +39,13 @@ photocraft-tablet = { path = "crates/tablet" } photocraft-ipp = { path = "crates/ipp" } # external -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["raster"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["raster"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -205,7 +205,7 @@ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7 egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README). -hayro = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } diff --git a/apps/photocraft-cli/Cargo.toml b/apps/photocraft-cli/Cargo.toml index 4ddde07142e..7640483f440 100644 --- a/apps/photocraft-cli/Cargo.toml +++ b/apps/photocraft-cli/Cargo.toml @@ -33,7 +33,7 @@ required-features = ["gpu"] photocraft-automation = { path = "../../crates/automation" } photocraft-doc = { workspace = true } photocraft-engine = { workspace = true } -photocraft-io = { workspace = true } +photocraft-io = { workspace = true, features = ["pdf-editable"] } photocraft-raster = { workspace = true } photocraft-format = { path = "../../crates/format" } photocraft-codecs = { workspace = true } diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index a5acb4557b3..ae1e3f8f8fe 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -125,6 +125,10 @@ pub(crate) struct ConvertArgs { /// PDF pages to import, 1-based: "3" or "2-7" (default all) #[arg(long)] pub(crate) pdf_pages: Option, + /// Import PDF paths and embedded-font text as editable layers (experimental; unsupported + /// pages fall back to raster, and embedded fonts may change when edited or reopened) + #[arg(long)] + pub(crate) pdf_editable: bool, #[command(flatten)] pub(crate) gpu: GpuArgs, #[command(flatten)] @@ -504,7 +508,7 @@ pub(crate) fn parse(args: &[OsString]) -> Result { conflict(sub, m, "automation_read_root", "bridge")?; conflict(sub, m, "automation_write_root", "bridge")?; } - if a.bridge.is_some() && (a.automation.automation_read_root.is_some() || a.automation.automation_write_root.is_some()) { + if a.bridge.is_some() && (!a.automation.automation_read_root.is_empty() || a.automation.automation_write_root.is_some()) { return Err(ServerOptionError::BridgeRoots.into_clap(sub)); } if a.bridge.is_some() && (m.value_source("gpu") == Some(ValueSource::CommandLine) || m.value_source("no_gpu") == Some(ValueSource::CommandLine)) diff --git a/apps/photocraft-cli/src/document.rs b/apps/photocraft-cli/src/document.rs index ab9e3cfd35e..5541da11a62 100644 --- a/apps/photocraft-cli/src/document.rs +++ b/apps/photocraft-cli/src/document.rs @@ -46,6 +46,7 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write psd_high_memory_approved: a.approve_high_memory, pdf_dpi: a.pdf_dpi.unwrap_or(300.0), pdf_pages: a.pdf_pages.as_deref().map(parse_pdf_pages).transpose()?, + pdf_editable: a.pdf_editable, ..Default::default() }; let mut o = files::open_with_options(input, &import_opts)?; diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 2cb64e6e551..d99c405eda5 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -167,9 +167,9 @@ fn server_modes_reject_ignored_or_conflicting_options() { for flag in ["--control-token", "--control-token-file"] { server_usage_error(&[sub, flag, "unused"], if sub == "mcp" { "requires --bridge" } else { "requires --port" }); } + server_usage_error(&[sub, "--automation-write-root", ".", "--automation-write-root", "."], "cannot be used multiple times"); for flag in ["--automation-read-root", "--automation-write-root"] { - server_usage_error(&[sub, flag, ".", flag, "."], "cannot be used multiple times"); - server_usage_error(&[sub, &format!("{flag}=")], &format!("a value is required for '{flag} ")); + server_usage_error(&[sub, &format!("{flag}=")], "root needs a non-empty directory"); server_usage_error(&[sub, flag, "--automation-write-root", "."], &format!("a value is required for '{flag} ")); } let transport = if sub == "mcp" { "--bridge" } else { "--port" }; @@ -193,7 +193,7 @@ fn server_validation_does_not_consume_stdio_or_create_files() { let other = d.join("other.token"); let token_flag = format!("--control-token-file={}", token.display()); let other_flag = format!("--control-token-file={}", other.display()); - for tail in [&["stray"][..], &["--automation-read-root", ".", "--automation-read-root", "."], &["--port", "0"], &[&other_flag]] { + for tail in [&["stray"][..], &["--automation-write-root", ".", "--automation-write-root", "."], &["--port", "0"], &[&other_flag]] { let mut child = bin() .current_dir(&d) .args(["serve", "--port", "0", &token_flag]) @@ -1857,6 +1857,120 @@ fn batch_skips_deselect_with_nothing_selected() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn every_configured_read_root_must_be_a_valid_directory() { + let d = tmp("invalid-read-roots"); + let good = d.join("good"); + std::fs::create_dir_all(&good).unwrap(); + let file = d.join("file"); + std::fs::write(&file, b"not a directory").unwrap(); + for sub in ["mcp", "serve"] { + for invalid in [d.join("missing"), file.clone()] { + for roots in [[&good, &invalid], [&invalid, &good]] { + let o = bin() + .arg(sub) + .arg("--automation-read-root") + .arg(roots[0]) + .arg(format!("--automation-read-root={}", roots[1].display())) + .stdin(Stdio::null()) + .output() + .unwrap(); + assert_eq!(o.status.code(), Some(1), "{sub}: {}", String::from_utf8_lossy(&o.stderr)); + assert!(String::from_utf8_lossy(&o.stderr).contains("automation read root")); + assert!(o.stdout.is_empty(), "invalid roots must fail before the server starts"); + } + } + } +} + +#[test] +fn serve_reads_roots_in_order_and_supports_absolute_paths_in_each_root() { + let d = tmp("serve-read-roots"); + let first = d.join("first"); + let second = d.join("second"); + std::fs::create_dir_all(&first).unwrap(); + std::fs::create_dir_all(&second).unwrap(); + write_png(&first.join("shared.png"), 3, 2, 3); + write_png(&second.join("shared.png"), 7, 4, 5); + write_png(&second.join("fallback.png"), 6, 5, 7); + let mut child = bin() + .args(["serve", "--automation-read-root"]) + .arg(&first) + .arg(format!("--automation-read-root={}", second.display())) + .arg("--automation-read-root") + .arg(&first) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + for (id, path) in [(1, "shared.png".into()), (2, "fallback.png".into()), (3, second.join("shared.png").to_string_lossy().into_owned())] { + writeln!(stdin, "{}", json!({"id": id, "method": "doc.open", "params": {"path": path}})).unwrap(); + } + drop(stdin); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + let replies: Vec = String::from_utf8(output.stdout).unwrap().lines().map(|line| serde_json::from_str(line).unwrap()).collect(); + assert_eq!(replies.len(), 3); + for (reply, (width, height)) in replies.iter().zip([(3, 2), (6, 5), (7, 4)]) { + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["width"], width, "{reply}"); + assert_eq!(reply["result"]["height"], height, "{reply}"); + } +} + +#[test] +fn mcp_reads_roots_in_order_with_fallback() { + let d = tmp("mcp-read-roots"); + let first = d.join("first"); + let second = d.join("second"); + std::fs::create_dir_all(&first).unwrap(); + std::fs::create_dir_all(&second).unwrap(); + write_png(&first.join("shared.png"), 3, 2, 3); + write_png(&second.join("shared.png"), 7, 4, 5); + write_png(&second.join("fallback.png"), 6, 5, 7); + let mut child = bin() + .arg("mcp") + .arg(format!("--automation-read-root={}", first.display())) + .arg("--automation-read-root") + .arg(&second) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + let mut send = |value: Value| { + writeln!(stdin, "{value}").unwrap(); + stdin.flush().unwrap(); + }; + let mut recv = |id: u64| -> Value { + loop { + let mut line = String::new(); + assert!(stdout.read_line(&mut line).unwrap() > 0, "server closed"); + let value: Value = serde_json::from_str(&line).unwrap(); + if value["id"] == id { + return value; + } + } + }; + send(json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}})); + assert_eq!(recv(1)["result"]["serverInfo"]["name"], "photocraft"); + send(json!({"jsonrpc":"2.0","method":"notifications/initialized"})); + for (id, path, width) in [(2, "shared.png", 3), (3, "fallback.png", 6)] { + send(json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":"doc_open","arguments":{"path":path}}})); + let reply = recv(id); + assert_ne!(reply["result"]["isError"], true, "{reply}"); + let opened: Value = serde_json::from_str(reply["result"]["content"][0]["text"].as_str().unwrap()).unwrap(); + assert_eq!(opened["width"], width, "{reply}"); + } + let _ = child.kill(); + let _ = child.wait(); +} + /// TIFF Options from the command line (#8827): `--tiff-compression`, `--tiff-transparency on|off` /// and `--tiff-pyramid`; a bad value is a usage error that writes nothing. #[test] diff --git a/apps/photocraft/src/launch_args.rs b/apps/photocraft/src/launch_args.rs index 5e54f84ed8a..83715f8918c 100644 --- a/apps/photocraft/src/launch_args.rs +++ b/apps/photocraft/src/launch_args.rs @@ -286,7 +286,7 @@ mod tests { assert_eq!(parsed.control, Some(50494)); assert_eq!(parsed.auth.control_token.as_deref(), Some("abcd")); assert_eq!(parsed.auth.control_token_file, None); - assert_eq!(parsed.automation.automation_read_root.as_deref(), Some(std::path::Path::new("/r"))); + assert_eq!(parsed.automation.automation_read_root, vec![std::path::PathBuf::from("/r")]); assert_eq!(parsed.automation.automation_write_root.as_deref(), Some(std::path::Path::new("/w"))); assert!(parsed.safe_gpu && parsed.in_window_menus && parsed.new_instance); assert_eq!(parsed.present_mode, Some(PresentMode::AutoNoVsync)); diff --git a/apps/photocraft/src/mac_menu.rs b/apps/photocraft/src/mac_menu.rs index f8a7c8c689c..aea005753e7 100644 --- a/apps/photocraft/src/mac_menu.rs +++ b/apps/photocraft/src/mac_menu.rs @@ -254,7 +254,7 @@ impl Backend for MacMenu { pub fn install(ctx: &egui::Context, app: &photocraft_ui_egui::PhotocraftApp) -> Option { let language = &app.session.prefs().interface.language; let lang = photocraft_ui_egui::i18n::Lang::from_pref(language); - let bar = native_menu::photocraft_layout(&photocraft_ui_egui::menus::menu_items(app), lang, language).bar; + let bar = native_menu::app_layout(app, &photocraft_ui_egui::menus::menu_items(app), lang, language).bar; // Never crash for a menu: if AppKit refuses, keep the in-window menus. let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let mut menu = MacMenu::new(ctx); diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 545fc86eec4..f9c75ffaa1b 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -68,7 +68,7 @@ const OPEN_FILTERS: &[(&str, &[&str])] = &[ ("DPX and Cineon", &["dpx", "cin"]), ("Amiga IFF", &["iff", "lbm", "ilbm"]), ("DICOM", &["dcm", "dicom", "dc3"]), - ("Camera Raw", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]), + ("RAW images", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]), ("Brushes", &["abr"]), ("Gradients", &["grd"]), ("Styles", &["asl"]), @@ -703,9 +703,9 @@ pub fn native(automation: Option) -> let clip_unreadable: Rc> = Rc::default(); let automation_read = automation.clone().map(|workspace| { Box::new(move |path: &str| { - let bytes = workspace.read(path).map_err(|error| error.to_string())?; + let (bytes, save_path) = workspace.read_with_save_path(path).map_err(|error| error.to_string())?; let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string(); - Ok((name, bytes)) + Ok(photocraft_ui_egui::AutomationReadResult { name, bytes, save_path }) }) as photocraft_ui_egui::AutomationReadFn }); let automation_write = automation.clone().map(|workspace| { @@ -763,6 +763,7 @@ pub fn native(automation: Option) -> open_url: Some(Box::new(|url: &str| open::that(url).map_err(|e| e.to_string()))), beep: Some(platform_beep), check_updates: Some(crate::updates::service()), + last_update: Some(crate::updates::last_update), clipboard_set_image: Some({ let clip = clip.clone(); guarded_clipboard_set(move |w: u32, h: u32, px: &[u8]| { diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index fb2188cdabc..a89a1a327eb 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -218,7 +218,9 @@ fn open_filters_keep_literal_extensions_on_windows_and_macos() { #[test] fn native_services_provide_update_transport() { - assert!(native(None).check_updates.is_some()); + let services = native(None); + assert!(services.check_updates.is_some()); + assert!(services.last_update.is_some()); } #[test] diff --git a/apps/photocraft/src/updates.rs b/apps/photocraft/src/updates.rs index a11a7b63c91..50bba88de15 100644 --- a/apps/photocraft/src/updates.rs +++ b/apps/photocraft/src/updates.rs @@ -20,6 +20,19 @@ pub fn service() -> CheckFn { }) } +/// What the last self-update came to, once: `craft-update` removes its records as it reads them. +pub fn last_update() -> Option> { + use craft_update::self_update::{Outcome, current_version, take_outcome}; + let app = &photocraft_ui_egui::UPDATE_APP; + let paths = craft_update::Paths::for_app(app).ok()?; + let version = photocraft_engine::build_info::VERSION; + let running = current_version(app, version).map_or_else(|| version.to_string(), |v| v.to_string()); + match take_outcome(&paths, &running)? { + Outcome::Installed(installed) => Some(Ok(installed.to_string())), + Outcome::Failed(reason) => Some(Err(reason)), + } +} + fn check() -> CheckResult { let http = craft_update::Http::new("PhotoCraft/Update")?; let found = craft_update::check_for_update(&photocraft_ui_egui::UPDATE_APP, &http, photocraft_engine::build_info::VERSION)?; diff --git a/apps/photocraft/tests/it/control_exit_code.rs b/apps/photocraft/tests/it/control_exit_code.rs index 98c32431330..67f2acda475 100644 --- a/apps/photocraft/tests/it/control_exit_code.rs +++ b/apps/photocraft/tests/it/control_exit_code.rs @@ -120,3 +120,49 @@ fn automation_roots_come_from_the_environment_too() { assert!(stderr.contains("cannot configure automation workspace"), "{var}: stderr: {stderr}"); } } + +#[test] +fn invalid_read_root_is_not_hidden_by_another_valid_root() { + let dir = std::env::temp_dir().join(format!("photocraft-control-roots-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let good = dir.to_str().unwrap(); + let missing = dir.join("missing"); + let file = dir.join("not-a-directory"); + std::fs::write(&file, b"not a directory").unwrap(); + for invalid in [&missing, &file] { + for roots in [[good, invalid.to_str().unwrap()], [invalid.to_str().unwrap(), good]] { + let Run { status, stderr } = run_photocraft(&[ + "--control", + "0", + "--control-token", + VALID_TOKEN, + "--automation-read-root", + roots[0], + &format!("--automation-read-root={}", roots[1]), + ]); + assert_eq!(status.code(), Some(2), "every configured read root must be valid: {stderr}"); + assert!(stderr.contains("cannot configure automation workspace"), "stderr: {stderr}"); + } + } + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn empty_missing_and_repeated_write_root_flags_are_usage_errors() { + for flags in [ + vec!["--automation-read-root"], + vec!["--automation-read-root", ""], + vec!["--automation-read-root="], + vec!["--automation-read-root", "--safe-gpu"], + vec!["--automation-write-root"], + vec!["--automation-write-root="], + vec!["--automation-write-root", "work", "--automation-write-root=work"], + vec!["--automation-write-root=", "--automation-write-root=work"], + ] { + let args: Vec<&str> = ["--control", "0", "--control-token", VALID_TOKEN].into_iter().chain(flags).collect(); + let Run { status, stderr } = run_photocraft(&args); + assert_eq!(status.code(), Some(2), "{args:?}: {stderr}"); + assert!(stderr.contains("--automation-"), "stderr: {stderr}"); + assert!(!stderr.contains("cannot configure automation workspace"), "parse errors must fail before opening roots: {stderr}"); + } +} diff --git a/assets/icons/panel-left.svg b/assets/icons/panel-left.svg new file mode 100644 index 00000000000..60642c396f9 --- /dev/null +++ b/assets/icons/panel-left.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/spirit-level.svg b/assets/icons/spirit-level.svg new file mode 100644 index 00000000000..a5bfc047c9d --- /dev/null +++ b/assets/icons/spirit-level.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/assets/icons/vertical-align-bottom.svg b/assets/icons/vertical-align-bottom.svg new file mode 100644 index 00000000000..09931ffd772 --- /dev/null +++ b/assets/icons/vertical-align-bottom.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/assets/icons/vertical-align-middle.svg b/assets/icons/vertical-align-middle.svg new file mode 100644 index 00000000000..019f70872dc --- /dev/null +++ b/assets/icons/vertical-align-middle.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/assets/icons/vertical-align-top.svg b/assets/icons/vertical-align-top.svg new file mode 100644 index 00000000000..c5269fe99ad --- /dev/null +++ b/assets/icons/vertical-align-top.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/contributors/people.toml b/contributors/people.toml index a2ead57598d..618dda5608a 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -315,3 +315,17 @@ sync_github_name = false [people.davidvhk] real_name = "David Vanhoucke" sync_github_name = true + +[people.Luis-0508] +sync_github_name = true + +[people.Kaedo17] +sync_github_name = true + +[people.rmsff] +real_name = "Serikov Roman" +sync_github_name = false + +[people.tomgardenart] +display_name = "Nostella" +sync_github_name = false diff --git a/crates/algo/src/average.rs b/crates/algo/src/average.rs new file mode 100644 index 00000000000..982ec7cb6f6 --- /dev/null +++ b/crates/algo/src/average.rs @@ -0,0 +1,135 @@ +//! Average changes colour, never coverage. Keep the existing RGB conversion and selection +//! weighting; Photoshop RGB8 observations are documented in docs/average-filter.md. +use photocraft_color::{PixelFormat, SampleType}; +use photocraft_geom::Rect; +use photocraft_raster::{Interrupt, Surface, from_rgba_into, to_rgba}; + +use crate::{Ctx, Image}; + +#[derive(Default)] +struct Mean { + sum: [f64; 3], + weight: f64, +} + +impl Mean { + fn add(&mut self, fmt: &PixelFormat, px: &[f32], coverage: f32) { + let rgba = to_rgba(fmt, px); + let w = f64::from(coverage); + for (sum, value) in self.sum.iter_mut().zip(rgba) { + *sum += f64::from(value) * w; + } + self.weight += w; + } + + fn colour(&self) -> Option<[f32; 3]> { + (self.weight > 0.0).then(|| self.sum.map(|s| (s / self.weight) as f32)) + } +} + +fn mix(fmt: &PixelFormat, px: &mut [f32], colour: [f32; 3], coverage: f32) { + if coverage <= 0.0 { + return; + } + let mut rgba = to_rgba(fmt, px); + for (value, mean) in rgba.iter_mut().zip(colour) { + *value += (mean - *value) * coverage; + } + from_rgba_into(fmt, rgba, px); +} + +// Rect's public coordinates can span more than i32::MAX. Reject these before raster helpers +// do their signed coordinate arithmetic, and cap a single operation's sample count. +fn valid_area(area: Rect, channels: usize) -> bool { + area.width() <= i32::MAX as u32 + && area.height() <= i32::MAX as u32 + && u64::from(area.width()).saturating_mul(u64::from(area.height())).saturating_mul(channels as u64) <= 512 * 1024 * 1024 +} + +pub(crate) fn apply(surface: &Surface, area: Rect, selection: Option<&Surface>, ctl: &Interrupt<'_>) -> Option { + let fmt = surface.format(); + let n = fmt.channels(); + if !valid_area(area, n) || ctl.cancelled() { + return None; + } + if area.is_empty() { + return Some(surface.clone()); + } + let mut raw = surface.try_read_region(area).ok()?; + let width = area.width() as usize; + let coverage = |i: usize| selection.map_or(1.0, |s| s.sample_channel(area.x0 + (i % width) as i32, area.y0 + (i / width) as i32, 0)); + let mut mean = Mean::default(); + for (i, px) in raw.chunks_exact(n).enumerate() { + if i % width == 0 && ctl.cancelled() { + return None; + } + mean.add(&fmt, px, coverage(i)); + } + let Some(colour) = mean.colour() else { return Some(surface.clone()) }; + for (i, px) in raw.chunks_exact_mut(n).enumerate() { + if i % width == 0 && ctl.cancelled() { + return None; + } + mix(&fmt, px, colour, coverage(i)); + } + let mut out = surface.clone(); + if ctl.cancelled() { + return None; + } + out.try_write_region(area, &raw).ok()?; + out.prune(); + ctl.progress(1.0); + Some(out) +} + +// The direct kernel API has no selection. Its mean is over the reference bounds, even when +// the requested output is only a tile; the surface dispatcher above also handles selections. +pub(crate) fn kernel(src: &Image, out: Rect, ctx: &Ctx) -> Vec { + let fmt = PixelFormat::new(ctx.mode, SampleType::F32, ctx.alpha); + let n = fmt.channels(); + if src.ch != n || !valid_area(src.rect, n) || !valid_area(out, n) { + return Vec::new(); + } + let read = |x: i32, y: i32| -> Option<&[f32]> { + if !src.rect.contains(x, y) { + return None; + } + let i = (i64::from(y) - i64::from(src.rect.y0)) as usize; + let j = (i64::from(x) - i64::from(src.rect.x0)) as usize; + let start = i.checked_mul(src.rect.width() as usize)?.checked_add(j)?.checked_mul(n)?; + src.data.get(start..start.checked_add(n)?) + }; + let bounds = ctx.bounds.intersect(&src.rect); + let mut mean = Mean::default(); + for y in bounds.y0..bounds.y1 { + for x in bounds.x0..bounds.x1 { + if let Some(px) = read(x, y) { + mean.add(&fmt, px, 1.0); + } + } + } + let len = (out.width() as usize).checked_mul(out.height() as usize).and_then(|s| s.checked_mul(n)); + let Some(len) = len else { return Vec::new() }; + let mut result = Vec::new(); + if result.try_reserve_exact(len).is_err() { + return result; + } + let colour = mean.colour(); + for y in out.y0..out.y1 { + for x in out.x0..out.x1 { + let mut px = [0.0; 5]; + let Some(pixel) = px.get_mut(..n) else { return Vec::new() }; + if let Some(source) = read(x, y) { + pixel.copy_from_slice(source); + } + if let Some(colour) = colour { + mix(&fmt, pixel, colour, 1.0); + } + result.extend_from_slice(pixel); + } + } + result +} + +#[cfg(test)] +mod tests; diff --git a/crates/algo/src/average/tests.rs b/crates/algo/src/average/tests.rs new file mode 100644 index 00000000000..c7158bd7438 --- /dev/null +++ b/crates/algo/src/average/tests.rs @@ -0,0 +1,59 @@ +use super::*; +use photocraft_color::ColorMode; + +#[test] +fn preserves_alpha_and_averages_hidden_rgb_at_each_depth() { + let bounds = Rect::new(0, 0, 2, 1); + for sample in SampleType::ALL { + let fmt = PixelFormat::new(ColorMode::Rgb, sample, true); + let mut surface = Surface::new(fmt); + surface.write_region(bounds, &[1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0]); + let out = apply(&surface, bounds, None, &Interrupt::NONE).unwrap(); + for (i, p) in out.read_region(bounds).as_chunks::<4>().0.iter().enumerate() { + assert!((p[0] - 0.5).abs() <= 1.0 / 255.0); + assert_eq!(p[1], 0.0); + assert!((p[2] - 0.5).abs() <= 1.0 / 255.0); + assert_eq!(p[3], if i == 0 { 1.0 } else { 0.0 }); + } + } +} + +#[test] +fn direct_kernel_uses_reference_bounds_for_each_output_tile() { + let bounds = Rect::new(-1, 0, 1, 1); + let src = Image { rect: bounds, ch: 4, data: vec![1.0, 0.0, 0.0, 0.25, 0.0, 0.0, 1.0, 0.75] }; + let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true }; + assert_eq!(kernel(&src, Rect::new(-1, 0, 0, 1), &ctx), vec![0.5, 0.0, 0.5, 0.25]); + assert_eq!(kernel(&src, Rect::new(0, 0, 1, 1), &ctx), vec![0.5, 0.0, 0.5, 0.75]); +} + +#[test] +fn rejects_extreme_geometry_and_honours_pre_cancel() { + let surface = Surface::new(PixelFormat::RGBA8); + let huge = Rect::new(i32::MIN, 0, i32::MAX, 1); + assert!(apply(&surface, huge, None, &Interrupt::NONE).is_none()); + assert!(apply(&surface, Rect::new(0, 0, 5, 5), None, &Interrupt::cancel_only(&|| true)).is_none()); + assert_eq!(surface.tile_count(), 0); +} + +#[test] +fn soft_selection_weights_the_mean_and_output_mix() { + let bounds = Rect::new(0, 0, 2, 1); + for sample in SampleType::ALL { + let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true)); + surface.write_region(bounds, &[1.0, 0.0, 0.0, 0.25, 0.0, 0.0, 1.0, 0.75]); + let before = surface.read_region(bounds); + let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); + selection.write_region(bounds, &[0.25, 1.0]); + let out = apply(&surface, bounds, Some(&selection), &Interrupt::NONE).unwrap(); + // Unequal coverage makes the mean [0.2, 0, 0.8]. Each pixel then mixes + // toward it using its own coverage, independently of its original alpha. + for (i, expected) in [[0.8, 0.0, 0.2], [0.2, 0.0, 0.8]].iter().enumerate() { + let pixel = out.pixel(i as i32, 0); + for (actual, expected) in pixel.iter().zip(expected) { + assert!((actual - expected).abs() <= 1.0 / 255.0, "{sample:?}: {pixel:?}"); + } + assert_eq!(pixel[3], before[i * 4 + 3]); + } + } +} diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index ad72954a22d..d1c797b228c 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -21,6 +21,7 @@ pub mod art_history; mod artistic; mod artistic_fx; +mod average; mod blur; mod blur2; pub mod camera_raw; @@ -208,6 +209,8 @@ pub enum PolarMode { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "filter", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum FilterParams { + /// Mean colour over the selected area, retaining each pixel's alpha. + Average, /// Radius = Gaussian standard deviation in pixels (0.1–1000). GaussianBlur { radius: f32, @@ -592,7 +595,8 @@ impl FilterParams { FilterParams::Emboss { height, .. } => Halo::Radius(height.abs().ceil() as i32 + 2), FilterParams::FindEdges => Halo::Radius(1), FilterParams::AddNoise { .. } | FilterParams::Solarize | FilterParams::Invert | FilterParams::Desaturate => Halo::Radius(0), - FilterParams::RadialBlur { .. } + FilterParams::Average + | FilterParams::RadialBlur { .. } | FilterParams::Offset { .. } | FilterParams::Twirl { .. } | FilterParams::Pinch { .. } @@ -634,14 +638,16 @@ impl FilterParams { } /// Whether the filter places and sizes its pattern by the canvas even with a selection - /// (Clouds, Fibers): its bounds are then the canvas, and the selection only masks the result. + /// (Clouds, Fibers), or limits its working area to the canvas (Average). The output + /// area is still clipped to the selection; Average also weights its mean by that coverage. pub fn sizes_by_canvas(&self) -> bool { - matches!(self, FilterParams::Clouds { .. } | FilterParams::Fibers { .. }) + matches!(self, FilterParams::Average | FilterParams::Clouds { .. } | FilterParams::Fibers { .. }) } /// Human-readable name. pub fn label(&self) -> &'static str { match self { + FilterParams::Average => "Average", FilterParams::GaussianBlur { .. } => "Gaussian Blur", FilterParams::BoxBlur { .. } => "Box Blur", FilterParams::MotionBlur { .. } => "Motion Blur", @@ -766,6 +772,7 @@ pub struct Ctx { /// the halo, or the bounds for global filters). Returns interleaved samples. pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec { match params { + FilterParams::Average => average::kernel(src, out, ctx), FilterParams::GaussianBlur { radius } => blur::gaussian(src, out, ctx, *radius), FilterParams::BoxBlur { radius } => blur::boxed(src, out, ctx, *radius), FilterParams::MotionBlur { angle, distance } => blur::motion(src, out, ctx, *angle, *distance), @@ -1141,6 +1148,9 @@ fn apply_tiled_with_impl( if area.is_empty() { return Some(out); } + if matches!(params, FilterParams::Average) { + return average::apply(surface, extent.map_or(area, |e| area.intersect(&e)), selection, ctl); + } #[cfg(not(target_arch = "wasm32"))] if prepare_fast_paths && let Some(result) = sharpen::fft::apply(surface, params, area, selection, extent, ctl) { return result; diff --git a/crates/algo/src/liquify.rs b/crates/algo/src/liquify.rs index 40865c09b2c..1788873ccdd 100644 --- a/crates/algo/src/liquify.rs +++ b/crates/algo/src/liquify.rs @@ -112,7 +112,15 @@ fn d_rate() -> f64 { } /// One brush stroke: the tool, its brush options and the points it passed through -/// (`[x, y]` or `[x, y, pressure 0..1]`, document pixels). +/// (`[x, y]`, `[x, y, pressure 0..1]` or `[x, y, pressure 0..1, ms]`, document pixels). +/// +/// A fourth number makes the point *live*: the milliseconds since the previous point, as the +/// interactive dialog records them. A segment ending on a live point follows the pointer exactly +/// (Forward Warp and Push Left also show the motion since their last dab, as a provisional dab +/// taken back before the next point, instead of waiting for the next dab spacing) and the +/// stationary tools work by elapsed time as well as distance, so the brush keeps working at the +/// same speed when it moves slowly or the frame rate changes. Points without it (older strokes, +/// scripts) replay exactly as they always have. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LiquifyStroke { @@ -144,20 +152,28 @@ impl LiquifyStroke { LiquifyStroke { tool, size, density: d_density(), pressure: d_pressure(), rate: d_rate(), points: Vec::new(), amount: None } } - /// Validates the stroke (finite numbers, 2 or 3 per point). + /// Validates the stroke (finite numbers, 2 to 4 per point). pub fn validate(&self) -> Result<(), String> { if !(self.size.is_finite() && self.size >= 1.0 && self.size <= 15000.0) { return Err(format!("brush size {} out of range 1..15000", self.size)); } for p in &self.points { - if !(2..=3).contains(&p.len()) || p.iter().any(|v| !v.is_finite()) { - return Err("stroke points are [x, y] or [x, y, pressure]".into()); + if !(2..=4).contains(&p.len()) || p.iter().any(|v| !v.is_finite()) { + return Err("stroke points are [x, y], [x, y, pressure] or [x, y, pressure, ms]".into()); } } Ok(()) } } +/// Milliseconds of holding a stationary tool still that one full-strength dab stands for (the +/// 30 dabs a second the dialog has always used). +const HELD_DAB_MS: f64 = 1000.0 / 30.0; + +/// Most elapsed time one live point counts for: after a stall (a slow frame, the app in the +/// background) the brush catches up by this much at most instead of lurching. +pub const MAX_LIVE_MS: f64 = 250.0; + /// The displacement field plus the freeze mask, over `bounds` (document pixels). #[derive(Clone, Debug)] pub struct LiquifyField { @@ -172,6 +188,21 @@ pub struct LiquifyField { pub freeze: Vec, /// Where the brush stroke in progress stands, so dab spacing runs on across its segments. cursor: Option, + /// The provisional dab a live Forward Warp / Push Left segment ended with, to take back + /// before the stroke goes on (see [`Self::stroke_segment_live`]). + tail: Option, +} + +/// What a live segment's closing dab overwrote: the displacements `saved` of the nodes in columns +/// `i0..=i1`, one row after another from row `j0`, as they were, and the document rectangle the +/// dab touched. +#[derive(Clone, Debug)] +struct LiveTail { + i0: usize, + j0: usize, + i1: usize, + saved: Vec<[f32; 2]>, + dirty: Rect, } /// Two fields are equal when their displacement and freeze mask are: the stroke cursor is @@ -230,7 +261,7 @@ impl LiquifyField { cell *= 2.0; (w, h) = nodes(cell); } - LiquifyField { bounds, cell, w, h, d: vec![[0.0; 2]; w * h], freeze: vec![0.0; w * h], cursor: None } + LiquifyField { bounds, cell, w, h, d: vec![[0.0; 2]; w * h], freeze: vec![0.0; w * h], cursor: None, tail: None } } /// Document position of node (i, j) (node 0 sits on the first pixel centre). @@ -245,6 +276,27 @@ impl LiquifyField { ((x - f64::from(self.bounds.x0) - 0.5) / self.cell, (y - f64::from(self.bounds.y0) - 0.5) / self.cell) } + /// The field nodes a dab of radius `r` at `c` can touch, as `(i0, j0, i1, j1)` inclusive; + /// `None` when it touches none (off the grid, or a NaN centre). + fn node_span(&self, c: [f64; 2], r: f64) -> Option<(usize, usize, usize, usize)> { + let (gx0, gy0) = self.to_grid(c[0] - r, c[1] - r); + let (gx1, gy1) = self.to_grid(c[0] + r, c[1] + r); + // Decide the overlap in f64, before any conversion to an index: a far-off centre saturated + // `as usize` to `usize::MAX`, which read back as `-1` passed the overlap check. Written so + // that NaN, which fails every comparison, touches nothing (`max`/`min` would hide it). + let (wmax, hmax) = (self.w as f64 - 1.0, self.h as f64 - 1.0); + if !(gx1.ceil() >= 0.0 && gy1.ceil() >= 0.0 && gx0.floor() <= wmax && gy0.floor() <= hmax) { + return None; + } + let (x0, y0) = (gx0.floor().max(0.0), gy0.floor().max(0.0)); + let (x1, y1) = (gx1.ceil().min(wmax), gy1.ceil().min(hmax)); + if !(x0 <= x1 && y0 <= y1) { + return None; + } + // Now 0 <= x0 <= x1 <= w - 1 (and likewise in y): whole numbers that convert exactly. + Some((x0 as usize, y0 as usize, x1 as usize, y1 as usize)) + } + pub fn is_identity(&self) -> bool { self.d.iter().all(|v| v[0] == 0.0 && v[1] == 0.0) } @@ -274,6 +326,7 @@ impl LiquifyField { /// Applies one stroke. Returns the document rectangle whose output changed. pub fn apply_stroke(&mut self, s: &LiquifyStroke) -> Rect { self.cursor = None; + self.tail = None; match s.tool { LiquifyTool::LassoMask => return self.apply_lasso(s), LiquifyTool::ReconstructAll => { @@ -293,11 +346,18 @@ impl LiquifyField { if s.tool.is_global() { return self.bounds; } - let pts: Vec<[f64; 3]> = s.points.iter().filter(|p| p.len() >= 2).map(|p| [p[0], p[1], p.get(2).copied().unwrap_or(1.0)]).collect(); - let Some(&first) = pts.first() else { return Rect::EMPTY }; + // Each point with its live time (the fourth number), if it has one. + let pts: Vec<([f64; 3], Option)> = + s.points.iter().filter(|p| p.len() >= 2).map(|p| ([p[0], p[1], p.get(2).copied().unwrap_or(1.0)], p.get(3).copied())).collect(); + let Some(&(first, _)) = pts.first() else { return Rect::EMPTY }; let mut dirty = self.stroke_begin(s, first); for w in pts.windows(2) { - dirty = dirty.union(&self.stroke_segment(s, w[0], w[1])); + let ((a, _), (b, ms)) = (w[0], w[1]); + let d = match ms { + Some(ms) => self.stroke_segment_live(s, a, b, ms), + None => self.stroke_segment(s, a, b), + }; + dirty = dirty.union(&d); } dirty } @@ -360,6 +420,7 @@ impl LiquifyField { /// callers use this plus [`Self::stroke_segment`] per new point, which is exactly what /// [`Self::apply_stroke`] does with the whole point list. pub fn stroke_begin(&mut self, s: &LiquifyStroke, p: [f64; 3]) -> Rect { + self.tail = None; self.cursor = Some(StrokeCursor { end: [p[0], p[1]], last_dab: [p[0], p[1]], carry: 0.0 }); if s.tool.is_stationary() && !s.tool.is_global() { self.dab(s, [p[0], p[1]], [0.0, 0.0], p[2].clamp(0.0, 1.0), 1.0) } else { Rect::EMPTY } } @@ -370,7 +431,118 @@ impl LiquifyField { /// stationary tool held still dabs once at `b`. When `a` is not where the previous segment /// ended, the stroke starts afresh at `a`. pub fn stroke_segment(&mut self, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3]) -> Rect { - self.walk_segment(s, a, b, true) + let undone = self.undo_tail(); + undone.union(&self.walk_segment(s, a, b, true)) + } + + /// Continues a stroke from `a` to a live point `b` reached `ms` milliseconds after `a` (see + /// [`LiquifyStroke`]), which is what the interactive dialog records for every pointer event. + /// + /// Forward Warp and Push Left walk the segment as [`Self::stroke_segment`] does, so the dabs + /// fall every dab spacing of distance travelled however finely the pointer was sampled. Then + /// what is left of the motion since the last dab is applied as one shorter, *provisional* dab, + /// so the image follows the pointer on every event. That dab is taken back (see + /// [`Self::undo_tail`]) before the next segment, so only the regular dabs stay and a slow and + /// a fast pointer give the same warp, apart from the final partial dab. + /// + /// The stationary tools (Twirl, Pucker, Bloat, Reconstruct, Smooth, Freeze, Thaw) apply the + /// larger of what the elapsed time is worth ([`HELD_DAB_MS`] per full dab, at most + /// [`MAX_LIVE_MS`] per point) and what the distance travelled is worth (as a moving stroke + /// always has), spread evenly along the segment in dabs of at most full strength. Held still, + /// slow or fast, at any frame rate, the brush works continuously at one speed. + pub fn stroke_segment_live(&mut self, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3], ms: f64) -> Rect { + self.walk_segment_live(s, a, b, ms, true) + } + + /// Takes back the provisional closing dab of the last live segment, if any. Returns the + /// document rectangle that changed. + fn undo_tail(&mut self) -> Rect { + let Some(t) = self.tail.take() else { return Rect::EMPTY }; + let n = t.i1 - t.i0 + 1; + for (row, saved) in t.saved.chunks_exact(n).enumerate() { + let at = (t.j0 + row) * self.w + t.i0; + self.d[at..at + n].copy_from_slice(saved); + } + t.dirty + } + + /// [`Self::stroke_segment_live`]; `skip` as in [`Self::walk_segment`]. + fn walk_segment_live(&mut self, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3], ms: f64, skip: bool) -> Rect { + let mut dirty = self.undo_tail(); + if !s.tool.is_stationary() { + dirty = dirty.union(&self.walk_segment(s, a, b, skip)); + // What the dab spacing left over: show it now, and take it back on the next event. + if let Some(cur) = self.cursor + && cur.end == [b[0], b[1]] + { + let delta = [b[0] - cur.last_dab[0], b[1] - cur.last_dab[1]]; + let pressure = b[2].clamp(0.0, 1.0); + // A dab with no strength changes nothing, so there is nothing to take back. + if (delta[0] != 0.0 || delta[1] != 0.0) && pressure > 0.0 && s.pressure > 0.0 { + let r = (s.size / 2.0).max(0.5); + let span = self.node_span(cur.last_dab, r); + let saved = span.map(|(i0, j0, i1, j1)| { + let mut v = Vec::with_capacity((i1 - i0 + 1) * (j1 - j0 + 1)); + for j in j0..=j1 { + v.extend_from_slice(&self.d[j * self.w + i0..=j * self.w + i1]); + } + v + }); + let tail = self.dab(s, cur.last_dab, delta, pressure, 1.0); + if let (Some((i0, j0, i1, _)), Some(saved)) = (span, saved) { + self.tail = Some(LiveTail { i0, j0, i1, saved, dirty: tail }); + } + dirty = dirty.union(&tail); + } + } + return dirty; + } + // A live stroke keeps no spacing state for these tools; the cursor only marks continuity. + self.cursor = Some(StrokeCursor { end: [b[0], b[1]], last_dab: [b[0], b[1]], carry: 0.0 }); + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let len = dx.hypot(dy); + if !len.is_finite() || !b[0].is_finite() || !b[1].is_finite() { + self.cursor = None; + return dirty; + } + let (pa, pb) = (a[2].clamp(0.0, 1.0), b[2].clamp(0.0, 1.0)); + let r = (s.size / 2.0).max(0.5); + let spacing = dab_spacing(r); + let ms = if ms.is_finite() { ms.clamp(0.0, MAX_LIVE_MS) } else { 0.0 }; + // The same strength per distance a moving stationary tool has always had: `moving_weight` + // per dab spacing. + let by_time = ms / HELD_DAB_MS; + let by_distance = len / spacing * moving_weight(r); + let total = by_time.max(by_distance); + if total <= 0.0 { + return dirty; + } + // Enough dabs that none is stronger than a full one or further apart than the spacing. + let n = total.ceil().max((len / spacing).ceil()).max(1.0); + let weight = total / n; + let at = |k: f64| { + let t = (k + 1.0) / n; + ([a[0] + dx * t, a[1] + dy * t], pa + (pb - pa) * t) + }; + let (mut k0, mut k1) = (0.0f64, n - 1.0); + if skip && len > 0.0 { + // Only dabs near the part of the segment that can reach a node (#937). + match self.reachable_span(a, [dx, dy], len, r) { + Some((d0, d1)) => { + k0 = k0.max((d0 / len * n).floor() - 2.0); + k1 = k1.min((d1 / len * n).ceil() + 1.0); + } + None => return dirty, + } + } + if k0 > k1 { + return dirty; + } + for k in (k0 as u64)..=(k1 as u64) { + let (c, p) = at(k as f64); + dirty = dirty.union(&self.dab(s, c, [0.0, 0.0], p, weight)); + } + dirty } /// [`Self::stroke_segment`]; `skip` leaves out the dabs that cannot reach a field node (they @@ -479,16 +651,7 @@ impl LiquifyField { if strength <= 0.0 { return Rect::EMPTY; } - let (gx0, gy0) = self.to_grid(c[0] - r, c[1] - r); - let (gx1, gy1) = self.to_grid(c[0] + r, c[1] + r); - let i0 = gx0.floor().max(0.0) as usize; - let j0 = gy0.floor().max(0.0) as usize; - let i1 = (gx1.ceil().max(-1.0) as isize).min(self.w as isize - 1); - let j1 = (gy1.ceil().max(-1.0) as isize).min(self.h as isize - 1); - if i1 < i0 as isize || j1 < j0 as isize { - return Rect::EMPTY; - } - let (i1, j1) = (i1 as usize, j1 as usize); + let Some((i0, j0, i1, j1)) = self.node_span(c, r) else { return Rect::EMPTY }; // Snapshot of the affected nodes plus a margin (sampling reads around them). let m = ((delta[0].abs().max(delta[1].abs()) + r * 0.2) / self.cell).ceil() as usize + 2; let (si0, sj0) = (i0.saturating_sub(m), j0.saturating_sub(m)); diff --git a/crates/algo/src/liquify/tests.rs b/crates/algo/src/liquify/tests.rs index 1cc360b2c38..80cc8dae2e5 100644 --- a/crates/algo/src/liquify/tests.rs +++ b/crates/algo/src/liquify/tests.rs @@ -138,6 +138,52 @@ fn a_segment_to_a_far_off_point_returns() { f.stroke_segment(&LiquifyStroke::new(LiquifyTool::Bloat, 30.0), [5.0, -1e15, 1.0], [5.0, 1e15, 1.0]); } +/// A timed (live) stroke far off the field leaves it unchanged instead of panicking. The +/// provisional closing dab used to take its node span from a far-off centre: the lower index +/// saturated to `usize::MAX`, read as `-1` it passed the overlap check, and the snapshot then +/// subtracted past zero (debug) or sliced out of range (release). +#[test] +fn a_timed_stroke_far_off_the_field_leaves_it_unchanged() { + let far = [ + // The review's case: valid points, both far off on the right. + vec![vec![1e30, 3.0, 1.0], vec![1e30, 3.25, 1.0, 16.0]], + vec![vec![3.0, 1e30, 1.0], vec![3.25, 1e30, 1.0, 16.0]], + vec![vec![1e30, 1e30, 1.0], vec![1e30, 1e30 + 1e15, 1.0, 16.0]], + vec![vec![-1e30, 3.0, 1.0], vec![-1e30, 3.25, 1.0, 16.0]], + vec![vec![3.0, -1e30, 1.0], vec![3.25, -1e30, 1.0, 16.0]], + vec![vec![f64::MAX, 3.0, 1.0], vec![f64::MAX, 3.25, 1.0, 16.0]], + ]; + use LiquifyTool::*; + for tool in [ForwardWarp, Reconstruct, Smooth, TwirlCw, TwirlCcw, Pucker, Bloat, PushLeft, Freeze, Thaw] { + for points in &far { + let mut s = LiquifyStroke::new(tool, 30.0); + s.points = points.clone(); + s.validate().unwrap(); + let mut f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0); + f.apply_stroke(&s); + let fresh = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0); + assert!(f.d == fresh.d && f.freeze == fresh.freeze, "{tool:?} {points:?} changed the field"); + } + } +} + +/// `node_span` decides off the grid before converting to indices, on every side. +#[test] +fn node_span_rejects_spans_off_the_grid() { + let f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0); + for c in [[1e30, 3.0], [3.0, 1e30], [-1e30, 3.0], [3.0, -1e30], [f64::MAX, f64::MAX], [-f64::MAX, 3.0], [f64::NAN, 3.0], [3.0, f64::INFINITY]] { + assert_eq!(f.node_span(c, 15.0), None, "{c:?}"); + } + // On the grid, and partly off it, the span is the nodes inside it. + let (w, h) = (f.w - 1, f.h - 1); + assert_eq!(f.node_span([12.0, 8.0], 1e6), Some((0, 0, w, h))); + let Some((i0, j0, i1, j1)) = f.node_span([12.0, 8.0], 3.0) else { panic!("a dab on the field touches it") }; + assert!(i0 <= i1 && i1 <= w && j0 <= j1 && j1 <= h, "{:?}", (i0, j0, i1, j1)); + let Some((i0, _, i1, _)) = f.node_span([-10.0, 8.0], 12.0) else { panic!("a dab reaching the left edge touches it") }; + assert_eq!(i0, 0); + assert!(i1 <= w); +} + fn sample(st: SampleType) -> Surface { let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true)); for y in 0..64 { @@ -530,3 +576,217 @@ fn proxy_matches_the_full_render_roughly() { } assert!(bad < 96 * 64 / 50, "{bad}"); } + +// ---- Live strokes: the brush follows the pointer in real time ---- + +/// `path` as live points, one event per `step` px along each leg, `ms` apart. +fn live(path: &[[f64; 2]], step: f64, ms: f64) -> Vec> { + let mut out = vec![vec![path[0][0], path[0][1], 1.0, 0.0]]; + for w in path.windows(2) { + let (a, b) = (w[0], w[1]); + let n = ((b[0] - a[0]).hypot(b[1] - a[1]) / step).ceil().max(1.0) as usize; + for k in 1..=n { + let t = k as f64 / n as f64; + out.push(vec![a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, 1.0, ms]); + } + } + out +} + +fn max_diff(a: &LiquifyField, b: &LiquifyField) -> f32 { + a.d.iter().zip(&b.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max) +} + +/// The user's report: moving the mouse slowly, Liquify only changed the image once every dab +/// spacing (a twentieth of the brush radius, 10 px for a 400 px brush), not with every movement. +/// A live point now applies all the motion up to it, so every pointer event moves the image. +#[test] +fn a_slow_live_drag_moves_the_image_on_every_pointer_event() { + for tool in [LiquifyTool::ForwardWarp, LiquifyTool::PushLeft] { + let s = LiquifyStroke::new(tool, 200.0); // spacing 5 px + let mut f = LiquifyField::new(Rect::new(0, 0, 300, 200), 2.0); + let mut legacy = f.clone(); + let start = [100.0, 100.0, 1.0]; + f.stroke_begin(&s, start); + legacy.stroke_begin(&s, start); + let (mut prev, mut moves, mut legacy_moves) = (start, 0, 0); + // A crawl: half a pixel per event, 20 events (10 px, two spacings). + for k in 1..=20 { + let p = [100.0 + k as f64 * 0.5, 100.0, 1.0]; + let (before, legacy_before) = (f.d.clone(), legacy.d.clone()); + f.stroke_segment_live(&s, prev, p, 16.0); + legacy.stroke_segment(&s, prev, p); + moves += usize::from(f.d != before); + legacy_moves += usize::from(legacy.d != legacy_before); + prev = p; + } + assert_eq!(moves, 20, "{tool:?}: every event moves the image"); + assert!(legacy_moves <= 3, "{tool:?}: the legacy walk only moved it once per spacing ({legacy_moves})"); + // And all the motion is there: the centre has been pushed (almost) as far as the brush went. + let d = f.sample(105.0, 100.0); + let shift = if tool == LiquifyTool::ForwardWarp { -d[0] } else { d[1].abs() }; + assert!(shift > 7.0, "{tool:?}: pushed {shift} px for a 10 px drag"); + } +} + +/// Following the pointer exactly must not bring back #2606's problem (a slow and a fast pointer +/// giving different warps): the two differ by a small fraction of the displacement. +#[test] +fn live_drags_sampled_finely_or_coarsely_agree_closely() { + let path = [[40.0, 40.0], [180.0, 60.0], [200.0, 150.0], [60.0, 160.0]]; + for (tool, size) in [(LiquifyTool::ForwardWarp, 60.0), (LiquifyTool::ForwardWarp, 200.0), (LiquifyTool::PushLeft, 80.0)] { + let field = |step: f64| { + let mut s = LiquifyStroke::new(tool, size); + s.points = live(&path, step, 16.0); + LiquifyField::from_strokes(Rect::new(0, 0, 260, 220), 2.0, &[s]) + }; + let (slow, fast) = (field(0.7), field(25.0)); + let deep = slow.max_displacement(); + let dd = max_diff(&slow, &fast); + assert!(deep > 10.0 && dd < deep * 0.1, "{tool:?} {size}px: slow and fast differ by {dd} px of {deep}"); + } +} + +/// Holding a stationary tool still works by elapsed time, not by how often frames come: one +/// second at 30, 60 or 144 frames a second does the same. +#[test] +fn held_stationary_tools_work_at_the_same_speed_at_any_frame_rate() { + for tool in [LiquifyTool::TwirlCw, LiquifyTool::Bloat, LiquifyTool::Pucker] { + let field = |fps: f64| { + let mut s = LiquifyStroke::new(tool, 80.0); + let frames = fps as usize; // one second + s.points = std::iter::once(vec![100.0, 100.0, 1.0, 0.0]).chain((0..frames).map(|_| vec![100.0, 100.0, 1.0, 1000.0 / fps])).collect(); + LiquifyField::from_strokes(Rect::new(0, 0, 200, 200), 2.0, &[s]) + }; + let (a, b, c) = (field(30.0), field(60.0), field(144.0)); + let deep = a.max_displacement(); + assert!(deep > 3.0, "{tool:?}: a second's hold does something ({deep} px)"); + for (fps, f) in [(60, &b), (144, &c)] { + let dd = max_diff(&a, f); + assert!(dd < deep * 0.08, "{tool:?}: {fps} fps differs from 30 fps by {dd} px of {deep}"); + } + } +} + +/// The other half of the report: a stationary tool crept along slowly did nothing at all (the +/// still-brush timer kept resetting and the distance never reached a dab spacing). Live, it works +/// at least as fast as held still. +#[test] +fn a_creeping_stationary_tool_keeps_working() { + let s = LiquifyStroke::new(LiquifyTool::TwirlCw, 120.0); // spacing 3 px + let mut f = LiquifyField::new(Rect::new(0, 0, 240, 200), 2.0); + f.stroke_begin(&s, [100.0, 100.0, 1.0]); + let mut prev = [100.0, 100.0, 1.0]; + let mut changed = 0; + for k in 1..=30 { + let p = [100.0 + k as f64 * 0.2, 100.0, 1.0]; + let before = f.d.clone(); + f.stroke_segment_live(&s, prev, p, 16.7); + changed += usize::from(f.d != before); + prev = p; + } + assert_eq!(changed, 30, "every frame twirls a little more"); + assert!(f.max_displacement() > 3.0, "half a second of creeping twirls visibly ({})", f.max_displacement()); +} + +/// Live strokes replay to exactly the field the interactive calls built (what OK relies on), and +/// a stall is capped instead of lurching. +#[test] +fn live_strokes_replay_exactly_and_stalls_are_capped() { + for tool in [LiquifyTool::ForwardWarp, LiquifyTool::TwirlCcw, LiquifyTool::Smooth, LiquifyTool::Freeze, LiquifyTool::Reconstruct] { + let mut s = LiquifyStroke::new(tool, 50.0); + s.points = live(&[[30.0, 30.0], [90.0, 70.0], [40.0, 90.0]], 1.3, 9.0); + let mut warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 60.0); + warp.points = vec![vec![40.0, 40.0], vec![80.0, 70.0]]; + let mut f = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&warp)); + let pts: Vec<[f64; 3]> = s.points.iter().map(|p| [p[0], p[1], p[2]]).collect(); + f.stroke_begin(&s, pts[0]); + for (k, w) in pts.windows(2).enumerate() { + f.stroke_segment_live(&s, w[0], w[1], s.points[k + 1][3]); + } + assert_eq!(f, LiquifyField::from_strokes(bounds(), 2.0, &[warp, s]), "{tool:?}"); + } + let s = LiquifyStroke::new(LiquifyTool::Bloat, 60.0); + let (mut stall, mut capped) = (LiquifyField::new(bounds(), 2.0), LiquifyField::new(bounds(), 2.0)); + stall.stroke_segment_live(&s, [50.0, 50.0, 1.0], [50.0, 50.0, 1.0], 60_000.0); + capped.stroke_segment_live(&s, [50.0, 50.0, 1.0], [50.0, 50.0, 1.0], MAX_LIVE_MS); + assert_eq!(stall, capped); + // Hostile values neither panic nor hang. + let mut f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0); + for tool in [LiquifyTool::ForwardWarp, LiquifyTool::Bloat, LiquifyTool::Freeze] { + let s = LiquifyStroke::new(tool, 30.0); + f.stroke_segment_live(&s, [0.0, 0.0, 1.0], [1e15, 0.0, 1.0], 16.0); + f.stroke_segment_live(&s, [5.0, -1e15, 1.0], [5.0, 1e15, 1.0], f64::NAN); + f.stroke_segment_live(&s, [-1e308, 5.0, 1.0], [1e308, 5.0, 1.0], -5.0); + f.stroke_segment_live(&s, [f64::NAN, 3.0, 1.0], [4.0, f64::INFINITY, 1.0], f64::INFINITY); + } + let mut bad = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0); + bad.points = vec![vec![1.0, 2.0, 1.0, 16.0, 9.0]]; + assert!(bad.validate().is_err()); + bad.points = vec![vec![1.0, 2.0, 1.0, 16.0]]; + assert!(bad.validate().is_ok()); +} + +/// Old strokes (no times) replay bit for bit as before: the live path is opt-in per point. +#[test] +fn strokes_without_times_replay_as_before() { + let path = [[20.0, 20.0, 1.0], [62.0, 26.0, 0.6], [70.0, 50.0, 0.9]]; + for tool in [LiquifyTool::ForwardWarp, LiquifyTool::TwirlCw, LiquifyTool::Freeze] { + let mut s = LiquifyStroke::new(tool, 30.0); + s.points = sampled(&path, 7); + let mut f = LiquifyField::new(bounds(), 2.0); + let pts: Vec<[f64; 3]> = s.points.iter().map(|p| [p[0], p[1], p[2]]).collect(); + f.stroke_begin(&s, pts[0]); + for w in pts.windows(2) { + f.stroke_segment(&s, w[0], w[1]); + } + assert_eq!(f, LiquifyField::from_strokes(bounds(), 2.0, &[s]), "{tool:?}"); + } +} + +/// A live segment with no strength changes nothing, so it leaves no provisional dab to take back; +/// with strength it does. No strength is a zero pressure at the point or a zero stroke pressure. +#[test] +fn a_live_segment_without_strength_leaves_nothing_to_take_back() { + for (point_pressure, stroke_pressure, shown) in [(0.0, 100.0, false), (1.0, 0.0, false), (1.0, 100.0, true)] { + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 200.0); + s.pressure = stroke_pressure; + let mut f = LiquifyField::new(Rect::new(0, 0, 300, 200), 2.0); + f.stroke_begin(&s, [100.0, 100.0, point_pressure]); + f.stroke_segment_live(&s, [100.0, 100.0, point_pressure], [100.5, 100.0, point_pressure], 16.0); + let case = format!("point pressure {point_pressure}, stroke pressure {stroke_pressure}"); + assert_eq!(f.tail.is_some(), shown, "{case}"); + assert_eq!(f.is_identity(), !shown, "{case}"); + } +} + +/// The provisional dab of one live segment is taken back before the next: a field reused across two +/// segments has a tail after the first, and none after a second segment that has no strength, which +/// also reports the taken-back area as changed so the caller repaints it. A second segment with +/// strength takes it back too: the result is the same as one segment straight to the same point. +#[test] +fn the_next_live_segment_takes_back_the_provisional_dab() { + let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 200.0); + let field = || { + let mut f = LiquifyField::new(Rect::new(0, 0, 300, 200), 2.0); + f.stroke_begin(&s, [100.0, 100.0, 1.0]); + let first = f.stroke_segment_live(&s, [100.0, 100.0, 1.0], [100.5, 100.0, 1.0], 16.0); + (f, first) + }; + let (mut f, first) = field(); + assert!(f.tail.is_some(), "the first segment leaves a provisional dab"); + assert!(!f.is_identity()); + let undone = f.stroke_segment_live(&s, [100.5, 100.0, 1.0], [100.5, 100.0, 0.0], 16.0); + assert!(!undone.is_empty(), "the taken-back dab is reported as changed"); + assert_eq!(undone.union(&first), undone, "and its area covers what the first segment repainted"); + assert!(f.tail.is_none(), "the next segment took it back"); + assert!(f.is_identity(), "and nothing of it is left in the field"); + + let (mut g, _) = field(); + g.stroke_segment_live(&s, [100.5, 100.0, 1.0], [101.0, 100.0, 1.0], 16.0); + assert!(g.tail.is_some(), "the second segment leaves its own provisional dab"); + let mut direct = LiquifyField::new(Rect::new(0, 0, 300, 200), 2.0); + direct.stroke_begin(&s, [100.0, 100.0, 1.0]); + direct.stroke_segment_live(&s, [100.0, 100.0, 1.0], [101.0, 100.0, 1.0], 16.0); + assert!(g == direct, "the first segment's dab was taken back before the second was applied"); +} diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index daf7a2526af..c91a2611de5 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -219,11 +219,44 @@ pub fn magic_wand(px: &[[f32; 4]], area: Rect, seed: (i32, i32), tolerance: f32, } } if anti_alias { - antialias(&mut m, w, h); + let tol = (tolerance + 1e-3).floor().max(0.0); + let src = m.clone(); + for (i, v) in m.iter_mut().enumerate() { + if src[i] == 0.0 && touches_region(i % w, i / w, w, h, |x, y| src[y * w + x] > 0.0) { + let p = px[i]; + let over = (0..3).map(|c| (p[c] - target[c]).abs() * 255.0).fold(0.0f32, f32::max) - tol; + *v = f32::from(fringe_coverage(over, p[3].min(target[3]) * 255.0)) / 255.0; + } + } } m } +/// How many levels past the tolerance the anti-aliased fringe fades over, from fully selected to +/// nothing. Measured in the reference application (#11776): 3 levels past gives 251, 5 gives +/// 249 and 123 gives 110; a straight fade to zero at 216 levels gives all three. +const FRINGE_LEVELS: f32 = 216.0; + +/// Coverage (0–255) of an anti-aliased fringe pixel: a neighbour of the region whose most +/// different colour channel is `over` levels past the tolerance, and `alpha` (0–255) the lower +/// of its and the clicked pixel's opacity. Photoshop keeps the region itself fully selected and +/// softens only the pixels just outside it, fading with the distance past the tolerance; a +/// neighbour without colour (transparent, next to a shape on its own layer) gets none. +fn fringe_coverage(over: f32, alpha: f32) -> u8 { + let k = (1.0 - over.max(0.0) / FRINGE_LEVELS).clamp(0.0, 1.0) * (alpha / 255.0).clamp(0.0, 1.0); + (k * 255.0).round() as u8 +} + +/// True when one of the 8 neighbours of `(x, y)` (inside a `w` x `h` area) is in the region. +fn touches_region(x: usize, y: usize, w: usize, h: usize, selected: impl Fn(usize, usize) -> bool) -> bool { + (-1i32..=1).any(|dy| { + (-1i32..=1).any(|dx| { + let (nx, ny) = (x as i32 + dx, y as i32 + dy); + (dx, dy) != (0, 0) && nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && selected(nx as usize, ny as usize) + }) + }) +} + /// Straight RGBA8 copy of `area` of a surface, read in parallel bands on native. pub fn rgba8_image(s: &Surface, area: Rect) -> Vec<[u8; 4]> { let (w, h) = (area.width() as usize, area.height() as usize); @@ -266,10 +299,62 @@ impl Region { } } +/// How a wand-style fill measures how far an 8-bit colour is from the clicked one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ColorDistance { + /// The largest difference in any one of R, G and B. + LargestChannel, + /// The spread of `{0, dR, dG, dB}`: changes in the same direction count once, opposite + /// changes add up. Only opaque colours were measured, so a partly transparent seed or pixel + /// uses [`Self::LargestChannel`]. + Spread, +} + +impl ColorDistance { + fn rgb(self, p: [u8; 4], seed: [u8; 4]) -> i32 { + let d = [0, 1, 2].map(|c| p[c] as i32 - seed[c] as i32); + match self { + Self::Spread if p[3] == 255 && seed[3] == 255 => d.iter().fold(0, |m, v| m.max(*v)) - d.iter().fold(0, |m, v| m.min(*v)), + Self::LargestChannel | Self::Spread => d.iter().fold(0, |m, v| m.max(v.abs())), + } + } +} + /// Magic wand on 8-bit pixels: a scanline flood fill (or a global match) that only allocates a /// byte mark per pixel, then anti-aliases just the edges inside the touched bounding box. /// Matches [`magic_wand`] for 8-bit sources. `None` if the seed is outside `area`. pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option { + wand_region_within(img, area, seed, tolerance, contiguous, anti_alias, None) +} + +/// [`wand_region`] whose contiguous fill only passes through pixels at least half selected in +/// `within` (the current selection's coverage over `area`, row-major): Subtract and Intersect +/// grow the region from the seed through the selection only (#11779). A seed outside it finds +/// nothing. A global match (`contiguous` off) ignores `within`. +pub fn wand_region_within( + img: &[[u8; 4]], + area: Rect, + seed: (i32, i32), + tolerance: f32, + contiguous: bool, + anti_alias: bool, + within: Option<&[f32]>, +) -> Option { + wand_region_by(img, area, seed, tolerance, contiguous, anti_alias, within, ColorDistance::LargestChannel) +} + +/// [`wand_region_within`] measuring how far a colour is from the clicked one with `distance`. +#[allow(clippy::too_many_arguments)] +pub fn wand_region_by( + img: &[[u8; 4]], + area: Rect, + seed: (i32, i32), + tolerance: f32, + contiguous: bool, + anti_alias: bool, + within: Option<&[f32]>, + distance: ColorDistance, +) -> Option { if !area.contains(seed.0, seed.1) { return None; } @@ -277,11 +362,16 @@ pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32 if w.checked_mul(h).is_none_or(|n| n > img.len()) { return None; } + let within = within.filter(|_| contiguous).filter(|m| m.len() >= w * h); + let inside = |i: usize| within.is_none_or(|m| m.get(i).is_some_and(|v| *v >= 0.5)); + if !inside((seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize) { + return None; + } let target = img[(seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize]; let tol = (tolerance + 1e-3).floor().max(0.0) as i32; // Copying a selection can leave RGB under zero alpha. Those invisible colours must not // split a transparent region into pieces, as if the copied source were still visible. - let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (0..4).all(|c| (p[c] as i32 - target[c] as i32).abs() <= tol); + let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol); let mut marks = vec![0u8; w * h]; let (mut bx0, mut by0, mut bx1, mut by1) = (usize::MAX, usize::MAX, 0usize, 0usize); if contiguous { @@ -293,10 +383,10 @@ pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32 continue; } let (mut l, mut r) = (x, x); - while l > 0 && marks[row + l - 1] == 0 && similar(img[row + l - 1]) { + while l > 0 && marks[row + l - 1] == 0 && similar(img[row + l - 1]) && inside(row + l - 1) { l -= 1; } - while r + 1 < w && marks[row + r + 1] == 0 && similar(img[row + r + 1]) { + while r + 1 < w && marks[row + r + 1] == 0 && similar(img[row + r + 1]) && inside(row + r + 1) { r += 1; } marks[row + l..=row + r].fill(255); @@ -308,7 +398,7 @@ pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32 let nrow = ny * w; let mut in_run = false; for nx in l..=r { - let ok = marks[nrow + nx] == 0 && similar(img[nrow + nx]); + let ok = marks[nrow + nx] == 0 && similar(img[nrow + nx]) && inside(nrow + nx); if ok && !in_run { stack.push((nx, ny)); } @@ -356,25 +446,11 @@ pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32 let x = x0 + xx; let v = at(x, y); *o = v; - if !anti_alias { - continue; - } - // Same rule as `antialias`: edge pixels blend with their 3×3 neighbourhood; neighbours - // outside the area count as the pixel itself. - let mut sum = 0u32; - let mut edge = false; - for dy in -1i32..=1 { - for dx in -1i32..=1 { - let (nx, ny) = (x as i32 + dx, y as i32 + dy); - let n = if nx < 0 || ny < 0 || nx >= w as i32 || ny >= h as i32 { v } else { at(nx as usize, ny as usize) }; - edge |= n != v; - sum += n as u32; - } - } - if edge { - let avg = sum as f32 / (9.0 * 255.0); - let f = if v > 127 { 0.5 + 0.5 * avg } else { 0.5 * avg }; - *o = (f * 255.0).round() as u8; + // Same rule as `magic_wand`: the region stays fully selected; a pixel just outside + // it gets a fringe by how far its colour is past the tolerance. + if anti_alias && v == 0 && touches_region(x, y, w, h, |nx, ny| at(nx, ny) != 0) { + let p = img[y * w + x]; + *o = fringe_coverage((distance.rgb(p, target) - tol) as f32, f32::from(p[3].min(target[3]))); } } }; @@ -435,32 +511,6 @@ pub fn combine_region(old: Option<&Surface>, new: Option<&Region>, mode: Selecti } } -/// Softens hard mask edges: edge pixels become the 3×3 average. -fn antialias(m: &mut [f32], w: usize, h: usize) { - let src = m.to_vec(); - for y in 0..h { - for x in 0..w { - let i = y * w + x; - let mut sum = 0.0; - let mut cnt = 0.0; - let mut edge = false; - for dy in -1i32..=1 { - for dx in -1i32..=1 { - let (xx, yy) = (x as i32 + dx, y as i32 + dy); - let v = if xx < 0 || yy < 0 || xx >= w as i32 || yy >= h as i32 { src[i] } else { src[yy as usize * w + xx as usize] }; - edge |= v != src[i]; - sum += v; - cnt += 1.0; - } - } - if edge { - // Keep selected pixels mostly selected, add a soft fringe. - m[i] = if src[i] > 0.5 { 0.5 + 0.5 * sum / cnt } else { 0.5 * sum / cnt }; - } - } - } -} - /// Colour Range: coverage falls off linearly with the per-channel colour /// distance; `fuzziness` in levels (0–200). pub fn color_range(px: &[[f32; 4]], color: [f32; 3], fuzziness: f32) -> Vec { @@ -780,10 +830,13 @@ pub fn tone_range(px: &[[f32; 4]], lo: f32, hi: f32, falloff: f32) -> Vec { mod distance; #[cfg(test)] mod ellipse_aa_edge_tests; + mod inverse; mod lasso; mod marquee; mod morphology; +#[cfg(test)] +mod wand_antialias_tests; pub use distance::edt; pub use inverse::inverse_surface; diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs index 4e7bdcbe069..5f02b53a58e 100644 --- a/crates/algo/src/selection/tests.rs +++ b/crates/algo/src/selection/tests.rs @@ -106,7 +106,9 @@ fn wand_contiguous_vs_global() { 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); + // #11776: anti-aliasing keeps the region whole and adds no fringe next to a colour this far + // past the tolerance (white is 245 levels from red, beyond the fringe's fade). + assert_eq!((aa[3 * 20 + 5], aa[3 * 20 + 6]), (1.0, 0.0)); assert!(magic_wand(&px, a, (50, 3), 10.0, true, false).iter().all(|v| *v == 0.0)); } diff --git a/crates/algo/src/selection/wand_antialias_tests.rs b/crates/algo/src/selection/wand_antialias_tests.rs new file mode 100644 index 00000000000..6d435e12cfd --- /dev/null +++ b/crates/algo/src/selection/wand_antialias_tests.rs @@ -0,0 +1,128 @@ +//! The Magic Wand's Anti-alias against the reference measurement (#11776): the region itself +//! stays fully selected, and a one-pixel soft fringe lies only outside it, next to colours just +//! past the tolerance. Document 800 x 600: a solid red rectangle 100,100–300,250 on a transparent +//! layer, and a grey ramp of ten 40 px blocks (grey 100, 105, …, 145) from x 100 at y 350–450, +//! on its own transparent layer or composited on white (Sample All Layers). + +use photocraft_geom::Rect; + +use super::{Region, magic_wand, wand_region}; + +const AREA: Rect = Rect { x0: 0, y0: 0, x1: 800, y1: 600 }; +const W: usize = 800; +const H: usize = 600; + +fn red_rectangle() -> Vec<[u8; 4]> { + let mut img = vec![[0u8; 4]; W * H]; + for y in 100..250 { + for x in 100..300 { + img[y * W + x] = [220, 30, 30, 255]; + } + } + img +} + +/// The grey ramp at y 350–450 on a transparent layer, or on white when `on_white`. +fn ramp(on_white: bool) -> Vec<[u8; 4]> { + let mut img = vec![if on_white { [255u8; 4] } else { [0u8; 4] }; W * H]; + for y in 350..450 { + for b in 0..10u8 { + let g = 100 + 5 * b; + for x in 100 + 40 * b as usize..140 + 40 * b as usize { + img[y * W + x] = [g, g, g, 255]; + } + } + } + img +} + +/// (bounds of every touched pixel, fully selected count, partly selected count). +fn stats(r: &Region) -> (Rect, usize, usize) { + let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); + let (mut full, mut part) = (0, 0); + for y in r.bbox.y0..r.bbox.y1 { + for x in r.bbox.x0..r.bbox.x1 { + let v = (r.at(x, y) * 255.0).round() as u8; + if v == 0 { + continue; + } + (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)); + if v == 255 { full += 1 } else { part += 1 } + } + } + (Rect::new(x0, y0, x1, y1), full, part) +} + +fn coverage(r: &Region, x: i32, y: i32) -> u8 { + (r.at(x, y) * 255.0).round() as u8 +} + +#[test] +fn a_shape_next_to_a_clearly_different_colour_gets_no_fringe() { + let img = red_rectangle(); + for aa in [true, false] { + let r = wand_region(&img, AREA, (150, 150), 32.0, true, aa).unwrap(); + assert_eq!(stats(&r), (Rect::new(100, 100, 300, 250), 30000, 0), "anti-alias {aa}"); + } +} + +#[test] +fn the_grey_ramp_gets_one_nearly_selected_column_past_the_tolerance() { + let img = ramp(false); + // Tolerance 32 from grey 100: blocks 100 to 130 (x 100–380) fully selected; the 135 block + // is 3 levels past it, so its first column is nearly selected. + let r = wand_region(&img, AREA, (110, 400), 32.0, true, true).unwrap(); + let (bounds, full, part) = stats(&r); + assert_eq!((full, part), (280 * 100, 100), "{bounds:?}"); + assert_eq!(bounds, Rect::new(100, 350, 381, 450)); + for y in [350, 400, 449] { + assert_eq!(coverage(&r, 379, y), 255, "the region's last column stays fully selected"); + assert_eq!(coverage(&r, 380, y), 251, "one fringe column of the next block, as measured"); + assert_eq!(coverage(&r, 381, y), 0, "only one column"); + } + // Transparent pixels above and below the ramp have no colour: no fringe there. + assert_eq!(coverage(&r, 200, 349), 0); + assert_eq!(coverage(&r, 200, 450), 0); + // Tolerance 10: x 100–220 plus one partly selected column of the 115 block. + let r = wand_region(&img, AREA, (110, 400), 10.0, true, true).unwrap(); + let (bounds, full, part) = stats(&r); + assert_eq!((bounds, full, part), (Rect::new(100, 350, 221, 450), 120 * 100, 100)); + assert_eq!(coverage(&r, 220, 400), 249, "5 levels past tolerance 10, as measured"); +} + +#[test] +fn anti_alias_off_has_no_partly_selected_pixels() { + let img = ramp(false); + let r = wand_region(&img, AREA, (110, 400), 32.0, true, false).unwrap(); + assert_eq!(stats(&r), (Rect::new(100, 350, 380, 450), 28000, 0)); +} + +#[test] +fn the_8_bit_and_f32_wands_draw_the_same_fringe() { + let img = ramp(false); + let f: Vec<[f32; 4]> = img.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect(); + for (tol, contiguous) in [(32.0, true), (10.0, true), (32.0, false)] { + let r = wand_region(&img, AREA, (110, 400), tol, contiguous, true).unwrap(); + let m = magic_wand(&f, AREA, (110, 400), tol, contiguous, true); + for y in 340..460 { + for x in 90..520 { + let want = (m[y as usize * W + x as usize] * 255.0).round() as u8; + assert_eq!(coverage(&r, x, y), want, "tolerance {tol}, contiguous {contiguous} at {x},{y}"); + } + } + } +} + +#[test] +fn on_the_composite_the_white_around_the_ramp_gets_the_measured_fringe() { + // Sample All Layers: the ramp on white. White is 155 levels from grey 100, 123 past + // tolerance 32; the reference application's fringe there reads 110 (Photoshop 2025, the + // same points; the issue reports 131–177 around the ramp). + let img = ramp(true); + let r = wand_region(&img, AREA, (110, 400), 32.0, true, true).unwrap(); + for (x, y) in [(200, 349), (200, 450), (99, 400), (99, 349)] { + assert_eq!(coverage(&r, x, y), 110, "{x},{y}"); + } + assert_eq!(coverage(&r, 380, 400), 251, "the near-miss block still gets the stronger fringe"); + assert_eq!(coverage(&r, 200, 400), 255, "inside stays fully selected"); +} diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index b1f7bacaae5..5a46b472e9e 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -218,6 +218,72 @@ pub fn quad_size(q: &[[f64; 2]; 4]) -> (f64, f64) { ((len(tl, tr) + len(bl, br)) / 2.0, (len(tl, bl) + len(tr, br)) / 2.0) } +/// How much the depth must change across the quad, as a fraction, for a pair of sides to count as +/// converging. Below this the recovered proportions are dominated by a pixel of click error. +const MIN_FORESHORTENING: f64 = 0.005; +/// How many times larger or smaller than the quad's longest edge an estimated side may be. +const MAX_ESTIMATE_RATIO: f64 = 4.0; +/// How far, as a fraction, one pixel of error on one corner may move the recovered proportions. +/// Quads from a camera model move about 1 %; the issue's measured skewed quad moves 5.3 %. +const MAX_ASPECT_SWING: f64 = 0.1; + +/// The free output size of a Perspective Crop of `q` (TL, TR, BR, BL) in an image centred on +/// `center`: the rectangle the quad shows in perspective, or the quad's longest edges when its +/// sides are too close to parallel to recover that, the estimate would not survive a pixel of +/// click error, or it is implausible. +pub fn quad_free_size(q: &[[f64; 2]; 4], center: [f64; 2]) -> (f64, f64) { + let len = |a: [f64; 2], b: [f64; 2]| (b[0] - a[0]).hypot(b[1] - a[1]); + let [tl, tr, br, bl] = *q; + let (edge_w, edge_h) = (len(tl, tr).max(len(bl, br)), len(tl, bl).max(len(tr, br))); + let near = |v: f64, edge: f64| v.is_finite() && v >= edge / MAX_ESTIMATE_RATIO && v <= edge * MAX_ESTIMATE_RATIO; + match perspective_size(q, center) { + Some((w, h)) if near(w, edge_w) && near(h, edge_h) => (w, h), + _ => (edge_w, edge_h), + } +} + +/// The size [`perspective_estimate`] gives `q`, or `None` when moving any corner one pixel along +/// either axis loses the estimate or swings its proportions by more than [`MAX_ASPECT_SWING`]. +fn perspective_size(q: &[[f64; 2]; 4], center: [f64; 2]) -> Option<(f64, f64)> { + let (width, aspect) = perspective_estimate(q, center)?; + for corner in 0..4 { + for axis in 0..2 { + for step in [-1.0, 1.0] { + let mut nudged = *q; + nudged[corner][axis] += step; + let (_, other) = perspective_estimate(&nudged, center)?; + if (other / aspect - 1.0).abs() > MAX_ASPECT_SWING { + return None; + } + } + } + } + Some((width, width / aspect)) +} + +/// The width and the aspect ratio of the rectangle `q` shows. The width is the largest horizontal +/// scale at a corner of the unit-square-to-quad map, so the nearest part of the quad keeps its +/// detail. The aspect ratio is recovered with the principal point at `center` (Zhang and He, +/// "Whiteboard scanning and image enhancement", 2007). `None` when two sides are nearly parallel, +/// which leaves the focal length undefined. +fn perspective_estimate(q: &[[f64; 2]; 4], [cx, cy]: [f64; 2]) -> Option<(f64, f64)> { + let Homography([a, b, _, d, e, _, g, h, _]) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], *q)?; + if g.abs().min(h.abs()) < MIN_FORESHORTENING { + return None; + } + let (ux, uy, vx, vy) = (a - g * cx, d - g * cy, b - h * cx, e - h * cy); + let focal2 = -(ux * vx + uy * vy) / (g * h); + if !focal2.is_finite() || focal2 <= 0.0 { + return None; + } + let focal = focal2.sqrt(); + let aspect = ux.hypot(uy).hypot(g * focal) / vx.hypot(vy).hypot(h * focal); + let scale_at = |[s, t]: [f64; 2], [x, y]: [f64; 2]| (a - x * g).hypot(d - y * g) / (1.0 + g * s + h * t); + let [tl, tr, br, bl] = *q; + let width = [scale_at([0.0, 0.0], tl), scale_at([1.0, 0.0], tr), scale_at([1.0, 1.0], br), scale_at([0.0, 1.0], bl)].into_iter().fold(0.0, f64::max); + Some((width, aspect)) +} + /// The homography taking the quad `q` (TL, TR, BR, BL) onto the rectangle (0, 0)–(`w`, `h`), corner /// to corner: the inverse of the unit-square-to-quad map (Heckbert, "Fundamentals of Texture /// Mapping and Image Warping", 1989, §2.2.3) scaled to the rectangle. `None` when `q` isn't a diff --git a/crates/automation/src/args.rs b/crates/automation/src/args.rs index 5c6dd666a71..3d382ef4c0a 100644 --- a/crates/automation/src/args.rs +++ b/crates/automation/src/args.rs @@ -10,7 +10,7 @@ use std::ffi::OsString; use std::path::PathBuf; -use clap::builder::NonEmptyStringValueParser; +use clap::builder::{NonEmptyStringValueParser, OsStringValueParser, TypedValueParser}; use clap::error::{ContextKind, ContextValue, ErrorKind}; use clap::parser::ValueSource; use clap::{Arg, ArgMatches, Args, Command}; @@ -34,18 +34,22 @@ pub struct ControlArgs { /// `photocraft-cli` access (#1551); the desktop app adds its own. #[derive(Args)] pub struct AutomationArgs { - /// The folder automation may read from (none without it) - #[arg(long, value_name = "DIR")] - pub automation_read_root: Option, + /// Ordered folders automation may read from; repeat for more roots (none without it) + #[arg(long, value_name = "DIR", value_parser = root_path())] + pub automation_read_root: Vec, /// The folder automation may write to (none without it) - #[arg(long, value_name = "DIR")] + #[arg(long, value_name = "DIR", value_parser = root_path())] pub automation_write_root: Option, } +fn root_path() -> impl TypedValueParser { + OsStringValueParser::new().try_map(|value: OsString| if value.is_empty() { Err("root needs a non-empty directory") } else { Ok(PathBuf::from(value)) }) +} + impl AutomationArgs { /// The roots, opened as capabilities. pub fn workspace(&self) -> Result { - AuthorizedWorkspace::new(self.automation_read_root.as_deref(), self.automation_write_root.as_deref()) + AuthorizedWorkspace::with_read_roots(self.automation_read_root.iter().map(PathBuf::as_path), self.automation_write_root.as_deref()) } } @@ -120,4 +124,40 @@ mod tests { assert_eq!(control_port(bad), Err(NotAPort), "{bad:?}"); } } + + #[derive(clap::Parser)] + struct RootCli { + #[command(flatten)] + automation: AutomationArgs, + } + + #[test] + fn repeated_read_roots_preserve_order_and_write_roots_stay_single() { + use clap::Parser; + let parsed = RootCli::try_parse_from(["test", "--automation-read-root", "first", "--automation-read-root=second"]).unwrap(); + assert_eq!(parsed.automation.automation_read_root, vec![PathBuf::from("first"), PathBuf::from("second")]); + for args in [ + vec!["test", "--automation-write-root", "one", "--automation-write-root=two"], + vec!["test", "--automation-write-root=one", "--automation-write-root", "one"], + vec!["test", "--automation-read-root="], + vec!["test", "--automation-read-root", "--automation-write-root=work"], + vec!["test", "--automation-write-root="], + ] { + assert!(RootCli::try_parse_from(args.clone()).is_err(), "accepted {args:?}"); + } + } + + #[cfg(unix)] + #[test] + fn non_unicode_root_paths_are_preserved_without_lossy_conversion() { + use clap::Parser; + use std::os::unix::ffi::OsStringExt; + let value = OsString::from_vec(b"library-\xff".to_vec()); + let parsed = RootCli::try_parse_from([OsString::from("test"), OsString::from("--automation-read-root"), value.clone()]).unwrap(); + assert_eq!(parsed.automation.automation_read_root, vec![PathBuf::from(value.clone())]); + let mut inline = OsString::from("--automation-read-root="); + inline.push(&value); + let parsed = RootCli::try_parse_from([OsString::from("test"), inline]).unwrap(); + assert_eq!(parsed.automation.automation_read_root, vec![PathBuf::from(value)]); + } } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index db662ada64f..99ff36038bf 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -181,13 +181,13 @@ impl Headless { /// Open a file with custom import options and make it the active document. pub fn open_with_options(&mut self, path: &Path, opts: &photocraft_io::ImportOptions) -> Result { let requested = path.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?; - let mut o = match &self.filesystem { + let (mut o, save_path) = match &self.filesystem { Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: read authority is absent".into())), - Filesystem::TrustedLocal => files::open_with_options(path, opts)?, + Filesystem::TrustedLocal => (files::open_with_options(path, opts)?, Some(requested.to_string())), Filesystem::Workspace(workspace) => { - let bytes = workspace.read(requested)?; + let (bytes, save_path) = workspace.read_with_save_path(requested)?; let name = path.file_name().and_then(|name| name.to_str()).unwrap_or(requested); - files::open_bytes_with_options(name, &bytes, opts)? + (files::open_bytes_with_options(name, &bytes, opts)?, save_path) } }; // Preferences › Raw Defaults › Resolution, as the app's File › Open applies it. @@ -197,7 +197,7 @@ impl Headless { o.document.name = untitled; None } - None => Some(requested.to_string()), + None => save_path, }; let index = self.session.add_document(o.document, path.filter(|_| !o.source_read_only)); if let Some(st) = self.session.active_mut() { diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 2e9348ae385..3db0960e15e 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -413,7 +413,7 @@ fn doc_place_reads_through_the_read_root_and_never_outside_it() { 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")] { + for (path, reason) in [("../outside/logo.png", "parent traversal"), (absolute.as_str(), "must be inside an automation read 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(); @@ -513,7 +513,7 @@ fn doc_replace_smart_object_reads_through_the_read_root_and_never_outside_it() { // 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": absolute}), "must be inside an automation read root"), (json!({"path": "logo.png", "layer": 999_999}), "no such layer"), (json!({}), "needs `path`"), ] { @@ -660,7 +660,7 @@ fn doc_export_data_sets_refuse_collisions_and_import_reads_the_root() { 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}"); + assert!(outside.contains("must be inside an automation read root"), "{outside}"); // Release directory capabilities before cleanup on Windows. drop(h); std::fs::remove_dir_all(base).unwrap(); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 2e34cf6cbe2..0ab39bc6589 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -50,7 +50,8 @@ pub struct DocIndex { #[derive(Debug, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct OpenParams { - /// Path beneath the configured automation read root: relative (forward slashes) or absolute. + /// Path beneath the configured automation read roots: relative (forward slashes, searched + /// in launch order) or absolute. Only a missing file tries the next root. pub path: String, /// Explicitly approve high-memory PSD/PSB imports that fit within the hard memory budget. #[serde(default)] @@ -179,6 +180,7 @@ pub struct SaveParams { /// The extension selects the format. Omit to write back to the document's own file, which /// works only for a PSD, PSB or .pcraft file kept in its own format; any other save needs /// `path`, so a flattened or converted copy never replaces the opened file. + /// A document opened from a different read capability needs an explicit path first. #[serde(default)] pub path: Option, /// Format override as an extension (pcraft, psd, png, jpg, tif, webp, exr, …). diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index ade7ff9707f..f0371699b80 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -33,7 +33,7 @@ struct RootCapability { /// before I/O. #[derive(Clone, Default)] pub struct AuthorizedWorkspace { - read: Option, + read: Vec, write: Option, } @@ -41,34 +41,90 @@ impl AuthorizedWorkspace { /// Open the configured roots as capabilities. Either authority may be /// omitted; omitted authority fails closed. pub fn new(read_root: Option<&Path>, write_root: Option<&Path>) -> Result { - Ok(Self { read: open_root(read_root, "read")?, write: open_root(write_root, "write")? }) + Self::with_read_roots(read_root, write_root) } - /// Read one regular file below the configured read root. + /// Open ordered read capabilities and an independent, optional write capability. + /// Every configured root must be valid; a write root does not also grant reads. + pub fn with_read_roots<'a>(read_roots: impl IntoIterator, write_root: Option<&Path>) -> Result { + let mut read = Vec::new(); + for path in read_roots { + let root = open_root(path, "read", &read)?; + read.push(root); + } + let write = write_root.map(|path| open_root(path, "write", &read)).transpose()?; + Ok(Self { read, write }) + } + + /// Read the first matching regular file, trying roots in their configured order. + /// Only an open that reports NotFound tries the next root. Once opened, errors + /// (including a non-regular file or a failed bounded read) never select another file. pub fn read(&self, path: &str) -> Result, AutomationError> { - let relative = request_path(path, self.read.as_ref())?; - let root = self.read.as_ref().ok_or_else(|| AutomationError::BadRequest(format!("{DENIED}: read authority is absent")))?; - let mut file = root.dir.open(&relative).map_err(|e| file_error("read", path, e))?; + self.read_with_save_path(path).map(|(bytes, _)| bytes) + } + + /// Read bytes and derive a conservative implicit-save request from the same + /// selected capability. A different read root must never redirect an implicit + /// save to a same-named file in the write root. Aliases and nested roots need an + /// explicit Save As; this is not canonical desktop document identity. + pub fn read_with_save_path(&self, path: &str) -> Result<(Vec, Option), AutomationError> { + let (mut file, root) = self.open_read(path)?; let metadata = file.metadata().map_err(|e| file_error("read", path, e))?; if !metadata.is_file() { return Err(AutomationError::BadRequest(format!("automation read path is not a regular file: `{path}`"))); } - read_to_observed_length(&mut file, metadata.len()) + // Retain main's bounded, growth-checked reads while keeping save provenance. + let bytes = read_to_observed_length(&mut file, metadata.len())?; + let save_path = self.write.as_ref().filter(|write| Arc::ptr_eq(&root.dir, &write.dir)).map(|_| path.to_owned()); + Ok((bytes, save_path)) + } + + fn open_read(&self, path: &str) -> Result<(cap_std::fs::File, &RootCapability), AutomationError> { + if self.read.is_empty() { + return Err(AutomationError::BadRequest(format!("{DENIED}: read authority is absent"))); + } + let mut not_found = None; + for root in &self.read { + let Some(relative) = scoped_path(path, root)? else { continue }; + match root.dir.open(&relative) { + Ok(file) => return Ok((file, root)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => not_found = Some(error), + Err(error) => return Err(file_error("read", path, error)), + } + } + match not_found { + Some(error) => Err(file_error("read", path, error)), + None => Err(path_error(path, "absolute paths must be inside an automation read root")), + } } /// Load one `.pcraft` document in directory form — the native on-disk layout — below the - /// read root. `read` serves regular files only (the zip form), so a regular file at the + /// first matching read root. Directory opens never establish an implicit save target. + /// `read` serves regular files only (the zip form), so a regular file at the /// path is reported as `Ok(None)` for the caller to fall back to. pub fn open_pcraft(&self, path: &str) -> Result, AutomationError> { - let relative = request_path(path, self.read.as_ref())?; - let root = self.read.as_ref().ok_or_else(|| AutomationError::BadRequest(format!("{DENIED}: read authority is absent")))?; - let dir = match root.dir.open_dir(&relative) { - Ok(dir) => dir, - Err(e) if e.kind() == std::io::ErrorKind::NotADirectory => return Ok(None), - Err(e) => return Err(file_error("read", path, e)), - }; - let source = DirHandle { dir }; - Ok(Some(photocraft_format::load_bytes_source(&source, &photocraft_format::LoadOptions::default())?)) + if self.read.is_empty() { + return Err(AutomationError::BadRequest(format!("{DENIED}: read authority is absent"))); + } + let mut not_found = None; + for root in &self.read { + let Some(relative) = scoped_path(path, root)? else { continue }; + let dir = match root.dir.open_dir(&relative) { + Ok(dir) => dir, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + not_found = Some(error); + continue; + } + Err(error) if error.kind() == std::io::ErrorKind::NotADirectory => return Ok(None), + Err(error) => return Err(file_error("read", path, error)), + }; + let source = DirHandle { dir }; + return Ok(Some(photocraft_format::load_bytes_source(&source, &photocraft_format::LoadOptions::default())?)); + } + match not_found { + Some(error) => Err(file_error("read", path, error)), + None => Err(path_error(path, "absolute paths must be inside an automation read root")), + } } /// Create or replace one file below the configured write root, crash-safely: the bytes go to @@ -216,8 +272,7 @@ fn read_to_observed_length(reader: &mut impl Read, observed_length: u64) -> Resu } } -fn open_root(path: Option<&Path>, authority: &str) -> Result, AutomationError> { - let Some(path) = path else { return Ok(None) }; +fn open_root(path: &Path, authority: &str, opened: &[RootCapability]) -> Result { if path.as_os_str().is_empty() { return Err(AutomationError::BadRequest(format!("automation {authority} root is empty"))); } @@ -228,27 +283,42 @@ fn open_root(path: Option<&Path>, authority: &str) -> Result) -> Result { + let Some(root) = root else { return relative_path(raw) }; + scoped_path(raw, root)?.ok_or_else(|| path_error(raw, "absolute paths must be inside the automation root")) +} + +/// An absolute prefix mismatch is a noncandidate, whereas a malformed path +/// beneath a matching root is an error. Never turn either into a relative lookup. +fn scoped_path(raw: &str, root: &RootCapability) -> Result, AutomationError> { let path = Path::new(raw); - let Some(root) = root.filter(|_| path.is_absolute()) else { return relative_path(raw) }; + if !path.is_absolute() { + return relative_path(raw).map(Some); + } // Prefer the trusted launch spelling: it can itself contain `..`. Only that // exact granted prefix is exempt; traversal in the remaining request still fails below. - let request = path_beneath_root(path, &root.configured_path) - .or_else(|| path_beneath_root(path, &root.path)) - .ok_or_else(|| path_error(raw, "absolute paths must be inside the automation root"))?; + let Some(request) = path_beneath_root(path, &root.configured_path).or_else(|| path_beneath_root(path, &root.path)) else { + return Ok(None); + }; let rest = request.map(|c| c.as_os_str().to_str().ok_or_else(|| path_error(raw, "path is not UTF-8"))).collect::, _>>()?; - relative_path(&rest.join("/")) + relative_path(&rest.join("/")).map(Some) } /// Strip a granted root prefix without resolving the client path with ambient authority. diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index 17590167268..37508e21171 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -749,6 +749,7 @@ fn documents_filesystem_path_params(id: &str, params: &str) -> bool { | "path.stroke" | "path.toShape" | "type.attachToPath" + | "type.setPathPlacement" | "type.fillPath" | "type.detachFromPath" | "select.toWorkPath" @@ -1075,6 +1076,149 @@ fn absolute_paths_are_checked_against_the_authority_s_own_root() { assert!(none.read(&target.to_string_lossy()).is_err()); } +#[test] +fn ordered_read_roots_keep_write_authority_and_save_provenance_separate() { + let (library, work, _) = roots("multiple-roots"); + std::fs::write(library.join("photo.txt"), b"library").unwrap(); + std::fs::write(work.join("draft.txt"), b"draft").unwrap(); + std::fs::write(library.join("same.txt"), b"first").unwrap(); + std::fs::write(work.join("same.txt"), b"second").unwrap(); + let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path(), library.as_path()], Some(&work)).unwrap(); + assert_eq!(workspace.read_with_save_path("photo.txt").unwrap(), (b"library".to_vec(), None)); + assert_eq!(workspace.read_with_save_path("draft.txt").unwrap(), (b"draft".to_vec(), Some("draft.txt".into()))); + assert_eq!(workspace.read("same.txt").unwrap(), b"first"); + let absolute = work.join("same.txt").to_string_lossy().into_owned(); + assert_eq!(workspace.read_with_save_path(&absolute).unwrap(), (b"second".to_vec(), Some(absolute))); + let reverse = AuthorizedWorkspace::with_read_roots([work.as_path(), library.as_path()], Some(&work)).unwrap(); + assert_eq!(reverse.read("same.txt").unwrap(), b"second"); + // Identical configured spellings share the held handle, including the write grant. + assert!(Arc::ptr_eq(&workspace.read[0].dir, &workspace.read[2].dir)); + assert!(Arc::ptr_eq(&workspace.read[1].dir, &workspace.write.as_ref().unwrap().dir)); + workspace.write("result.txt", b"output").unwrap(); + assert_eq!(std::fs::read(work.join("result.txt")).unwrap(), b"output"); + assert!(!library.join("result.txt").exists()); + assert!(workspace.write(&library.join("photo.txt").to_string_lossy(), b"blocked").is_err()); + assert_eq!(std::fs::read(library.join("photo.txt")).unwrap(), b"library"); + let error = workspace.read("missing.txt").unwrap_err().to_string(); + assert!(error.contains("NotFound"), "{error}"); +} + +#[test] +fn streamed_save_follows_read_provenance_across_ordered_roots() { + let (library, work, _) = roots("stream-provenance"); + std::fs::write(library.join("same.png"), b"library").unwrap(); + std::fs::write(work.join("same.png"), b"work").unwrap(); + std::fs::write(work.join("draft.png"), b"draft").unwrap(); + let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap(); + // Read from the library root: no implicit save, so a streamed save needs an explicit target. + assert_eq!(workspace.read_with_save_path("same.png").unwrap(), (b"library".to_vec(), None)); + // Read from the root that shares the write handle: the streamed save replaces that file only. + let (_, save_path) = workspace.read_with_save_path("draft.png").unwrap(); + let save_path = save_path.unwrap(); + workspace.write_stream(&save_path, &mut |w| w.write_all(b"streamed")).unwrap(); + assert_eq!(std::fs::read(work.join("draft.png")).unwrap(), b"streamed"); + assert!(!library.join("draft.png").exists()); + // An absolute library path never reaches the write root, streamed or not. + assert!(workspace.write_stream(&library.join("same.png").to_string_lossy(), &mut |w| w.write_all(b"blocked")).is_err()); + assert_eq!(std::fs::read(library.join("same.png")).unwrap(), b"library"); + assert_eq!(std::fs::read(work.join("same.png")).unwrap(), b"work"); +} + +#[test] +fn every_read_root_is_validated_and_write_roots_never_imply_reads() { + let (library, work, _) = roots("root-validation"); + std::fs::write(work.join("file.txt"), b"work").unwrap(); + for invalid in [library.join("missing"), work.join("file.txt"), PathBuf::new()] { + assert!(AuthorizedWorkspace::with_read_roots([library.as_path(), invalid.as_path(), work.as_path()], Some(&work)).is_err()); + } + let write_only = AuthorizedWorkspace::with_read_roots(std::iter::empty(), Some(&work)).unwrap(); + assert!(write_only.read("file.txt").is_err()); + assert!(write_only.read(&work.join("file.txt").to_string_lossy()).is_err()); + let read_only = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], None).unwrap(); + assert_eq!(read_only.read_with_save_path("file.txt").unwrap(), (b"work".to_vec(), None)); + assert!(read_only.write("file.txt", b"blocked").is_err()); +} + +#[test] +fn an_earlier_directory_or_invalid_path_never_falls_back_to_a_later_file() { + let (library, work, _) = roots("root-errors"); + std::fs::create_dir(library.join("same.txt")).unwrap(); + std::fs::write(work.join("same.txt"), b"later").unwrap(); + let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap(); + assert!(workspace.read("same.txt").is_err()); + for invalid in ["", "../same.txt", "a/../same.txt", "a\\same.txt", "a//same.txt", "NUL", "same.txt:stream"] { + assert!(workspace.read(invalid).is_err(), "accepted {invalid:?}"); + assert!(workspace.write(invalid, b"blocked").is_err(), "wrote {invalid:?}"); + } + let traversal = library.join("../outside/same.txt"); + assert!(workspace.read(&traversal.to_string_lossy()).is_err()); + assert_eq!(std::fs::read(work.join("same.txt")).unwrap(), b"later"); +} + +#[cfg(unix)] +#[test] +fn multiple_roots_do_not_allow_link_escapes_or_alias_save_back() { + use std::os::unix::fs::symlink; + let (library, work, _) = roots("multi-root-links"); + std::fs::write(work.join("photo.txt"), b"work").unwrap(); + symlink(&work, library.join("escape")).unwrap(); + std::fs::create_dir(work.join("escape")).unwrap(); + std::fs::write(work.join("escape/photo.txt"), b"later").unwrap(); + let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap(); + // Being separately granted does not allow following a link out of the selected root. + assert!(workspace.read("escape/photo.txt").is_err()); + assert_eq!(workspace.read("photo.txt").unwrap(), b"work"); + let alias = library.join("alias"); + symlink(&work, &alias).unwrap(); + let aliased = AuthorizedWorkspace::new(Some(&alias), Some(&work)).unwrap(); + assert_eq!(aliased.read_with_save_path("photo.txt").unwrap(), (b"work".to_vec(), None)); + let nested = AuthorizedWorkspace::new(Some(&work.join("escape")), Some(&work)).unwrap(); + assert_eq!(nested.read_with_save_path("photo.txt").unwrap(), (b"later".to_vec(), None)); + symlink(&library, work.join("escape-write")).unwrap(); + assert!(workspace.write("escape-write/output.txt", b"blocked").is_err()); + assert!(!library.join("output.txt").exists()); +} + +#[cfg(unix)] +#[test] +fn same_root_leaf_link_save_replaces_the_link_without_writing_its_target() { + let (inside, _, workspace) = roots("leaf-link"); + std::fs::write(inside.join("target.txt"), b"target").unwrap(); + std::os::unix::fs::symlink("target.txt", inside.join("link.png")).unwrap(); + let (bytes, save_path) = workspace.read_with_save_path("link.png").unwrap(); + assert_eq!(bytes, b"target"); + workspace.write(&save_path.unwrap(), b"replacement").unwrap(); + assert_eq!(std::fs::read(inside.join("target.txt")).unwrap(), b"target"); + assert_eq!(std::fs::read(inside.join("link.png")).unwrap(), b"replacement"); + assert!(!std::fs::symlink_metadata(inside.join("link.png")).unwrap().file_type().is_symlink()); +} + +#[test] +fn directory_pcraft_uses_ordered_roots_without_falling_back_after_selection() { + let (library, work, _) = roots("pcraft-ordered"); + let save = |root: &Path, name: &str| { + let doc = photocraft_doc::Document::new(name, photocraft_doc::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + photocraft_format::PcraftWriter::new().save_dir(&doc, &root.join("native.pcraft"), &photocraft_format::SaveOptions::default()).unwrap(); + }; + save(&work, "Later"); + let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap(); + assert_eq!(workspace.open_pcraft("native.pcraft").unwrap().unwrap().name, "Later"); + save(&library, "First"); + assert_eq!(workspace.open_pcraft("native.pcraft").unwrap().unwrap().name, "First"); + assert_eq!(workspace.open_pcraft(&work.join("native.pcraft").to_string_lossy()).unwrap().unwrap().name, "Later"); + std::fs::remove_dir_all(library.join("native.pcraft")).unwrap(); + std::fs::write(library.join("native.pcraft"), b"zip placeholder").unwrap(); + assert!(workspace.open_pcraft("native.pcraft").unwrap().is_none()); + std::fs::remove_file(library.join("native.pcraft")).unwrap(); + std::fs::create_dir(library.join("native.pcraft")).unwrap(); + assert!(workspace.open_pcraft("native.pcraft").is_err()); + for invalid in ["../native.pcraft", "a//native.pcraft", "a\\native.pcraft"] { + assert!(workspace.open_pcraft(invalid).is_err()); + } + let write_only = AuthorizedWorkspace::with_read_roots(std::iter::empty(), Some(&work)).unwrap(); + assert!(write_only.open_pcraft("native.pcraft").is_err()); +} + #[test] fn csh_import_requires_inline_data_in_automation() { let id = "shape.presets.importCsh"; diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index e14cbcab394..2c66b134b7a 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -15,5 +15,6 @@ mod native_full_composite; mod native_save_name; mod openraster; mod raw_defaults; +mod read_roots; mod renderer_save; mod smart_filter_authorization; diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index 7b4ce8aae3a..9f791c487f4 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -749,6 +749,49 @@ async fn save_without_path_never_flattens_over_the_opened_file() { cleanup(&dir); } +#[tokio::test(flavor = "multi_thread")] +async fn ordered_read_roots_preserve_save_identity_over_mcp() { + let base = tmp("ordered-read-roots"); + let library = base.join("library"); + let work = base.join("work"); + for (root, width, background) in [(&library, 11, "white"), (&work, 7, "black")] { + std::fs::create_dir_all(root).unwrap(); + let mut fixture = photocraft_automation::Headless::new(); + fixture.command_run("file.new", json!({"width": width, "height": 5, "background": background})).unwrap(); + fixture.command_run("layer.new.layer", json!({"name": "Source marker"})).unwrap(); + let bytes = photocraft_automation::files::save_bytes(&fixture.session.active().unwrap().doc, "same.pcraft", None, &Default::default()).unwrap().0; + std::fs::write(root.join("same.pcraft"), bytes).unwrap(); + } + let original_library = std::fs::read(library.join("same.pcraft")).unwrap(); + let original_work = std::fs::read(work.join("same.pcraft")).unwrap(); + let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(work.as_path())).unwrap(); + let client = connect(PhotocraftMcp::headless_with_workspace(workspace)).await; + + assert_eq!(json_of(&call(&client, "doc_open", json!({"path": "same.pcraft"})).await)["width"], 11); + json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Library edit"}})).await); + let before = json_of(&call(&client, "session_list", json!({})).await); + assert!(before["documents"][0]["path"].is_null()); + assert_eq!(before["documents"][0]["dirty"], true); + let denied = call(&client, "doc_save", json!({})).await; + assert_eq!(denied.is_error, Some(true)); + assert!(text(&denied).contains("pass `path`"), "{}", text(&denied)); + assert_eq!(json_of(&call(&client, "session_list", json!({})).await), before); + assert_eq!(std::fs::read(library.join("same.pcraft")).unwrap(), original_library); + assert_eq!(std::fs::read(work.join("same.pcraft")).unwrap(), original_work); + + json_of(&call(&client, "doc_save", json!({"path": "same.pcraft"})).await); + json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Work edit"}})).await); + assert_eq!(json_of(&call(&client, "doc_save", json!({})).await)["path"], "same.pcraft"); + let reopened = json_of(&call(&client, "doc_open", json!({"path": work.join("same.pcraft").to_string_lossy()})).await); + assert_eq!(reopened["width"], 11); + assert_eq!(json_of(&call(&client, "doc_inspect", json!({})).await)["layers"][0]["name"], "Work edit"); + assert_eq!(json_of(&call(&client, "session_list", json!({})).await)["documents"][0]["dirty"], false); + assert_eq!(std::fs::read(library.join("same.pcraft")).unwrap(), original_library); + assert_ne!(std::fs::read(work.join("same.pcraft")).unwrap(), original_work); + client.cancel().await.unwrap(); + cleanup(&base); +} + #[tokio::test(flavor = "multi_thread")] async fn filesystem_policy_rejects_absolute_and_escaping_paths_before_effects() { let base = tmp("filesystem-policy"); @@ -814,7 +857,7 @@ async fn doc_place_is_capability_scoped() { assert_eq!(placed, 3, "the absolute path beneath the root places as well"); let refused = call(&client, "doc_place", json!({"path": outside.join("outside.png").to_string_lossy()})).await; assert_eq!(refused.is_error, Some(true)); - assert!(text(&refused).contains("must be inside the automation root"), "{}", text(&refused)); + assert!(text(&refused).contains("must be inside an automation read root"), "{}", text(&refused)); let after = json_of(&call(&client, "doc_inspect", json!({})).await)["layers"].as_array().unwrap().len(); assert_eq!(after, placed, "nothing outside the root was placed"); // The ambient command keeps its refusal: the capability-scoped method is the only way in. @@ -847,7 +890,7 @@ async fn doc_replace_smart_object_is_capability_scoped() { assert_ne!(replaced.is_error, Some(true), "{}", text(&replaced)); let refused = call(&client, "doc_replace_smart_object", json!({"path": outside.join("outside.png").to_string_lossy(), "layer": layer})).await; assert_eq!(refused.is_error, Some(true)); - assert!(text(&refused).contains("must be inside the automation root"), "{}", text(&refused)); + assert!(text(&refused).contains("must be inside an automation read root"), "{}", text(&refused)); let ambient = call(&client, "command_run", json!({"id": "layer.smartObjects.replaceContents", "params": {"path": "inside.png", "layer": layer}})).await; assert_eq!(ambient.is_error, Some(true)); assert!(text(&ambient).contains("ambient filesystem paths"), "{}", text(&ambient)); diff --git a/crates/automation/tests/it/read_roots.rs b/crates/automation/tests/it/read_roots.rs new file mode 100644 index 00000000000..c9247f28b0a --- /dev/null +++ b/crates/automation/tests/it/read_roots.rs @@ -0,0 +1,297 @@ +//! Real-document regressions for ordered read roots and independent write authority. + +use std::path::{Path, PathBuf}; + +use photocraft_automation::{AuthorizedWorkspace, Headless, files}; +use photocraft_engine::actions_cmds::Action; +use serde_json::{Value, json}; + +struct Roots { + base: PathBuf, + library: PathBuf, + work: PathBuf, + outside: PathBuf, +} + +impl Roots { + fn new(name: &str) -> Self { + let base = std::env::temp_dir().join(format!("pc-read-roots-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let roots = Self { library: base.join("library"), work: base.join("work"), outside: base.join("outside"), base }; + for root in [&roots.library, &roots.work, &roots.outside] { + std::fs::create_dir_all(root).unwrap(); + } + roots + } + + fn workspace(&self) -> AuthorizedWorkspace { + AuthorizedWorkspace::with_read_roots([self.library.as_path(), self.work.as_path()], Some(self.work.as_path())).unwrap() + } + + fn headless(&self) -> Headless { + Headless::with_workspace(self.workspace()) + } + + fn seed(&self) -> (Vec, Vec) { + let library = layered_bytes(11, "white"); + let work = layered_bytes(7, "black"); + std::fs::write(self.library.join("same.pcraft"), &library).unwrap(); + std::fs::write(self.work.join("same.pcraft"), &work).unwrap(); + (library, work) + } +} + +impl Drop for Roots { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.base); + } +} + +fn layered_bytes(width: u32, background: &str) -> Vec { + let mut headless = Headless::new(); + headless.command_run("file.new", json!({"width": width, "height": 5, "background": background})).unwrap(); + headless.command_run("layer.new.layer", json!({"name": "Source marker"})).unwrap(); + let doc = &headless.session.active().unwrap().doc; + files::save_bytes(doc, "seed.pcraft", None, &Default::default()).unwrap().0 +} + +fn snapshot(headless: &mut Headless) -> (Value, Value, Vec) { + (headless.session_list(), headless.inspect(None).unwrap(), headless.render_png(None, 32).unwrap()) +} + +fn assert_source(headless: &Headless, width: u32, rgba: [u8; 4]) { + let state = headless.session.active().unwrap(); + assert_eq!(state.doc.size.width, width); + assert_eq!(state.doc.size.height, 5); + let preview = photocraft_compose::thumbnail(&state.doc, 32); + assert!(!preview.pixels.is_empty()); + assert!(preview.pixels.as_chunks::<4>().0.iter().all(|pixel| pixel == &rgba), "opened the wrong source pixels"); +} + +fn edit(headless: &mut Headless, name: &str) { + headless.command_run("layer.new.layer", json!({"name": name})).unwrap(); + assert!(headless.session.active().unwrap().is_dirty()); +} + +#[test] +fn library_first_open_cannot_overwrite_same_named_work_until_explicit_save_as() { + let roots = Roots::new("save-identity"); + let (library, work) = roots.seed(); + let mut headless = roots.headless(); + headless.open(Path::new("same.pcraft")).unwrap(); + assert_source(&headless, 11, [255; 4]); + assert!(headless.session.active().unwrap().path.is_none()); + edit(&mut headless, "Library edit"); + + let before = snapshot(&mut headless); + let error = headless.save(None, None, None, &Default::default()).unwrap_err().to_string(); + assert!(error.contains("pass `path`"), "{error}"); + assert_eq!(snapshot(&mut headless), before, "denial must preserve pixels, history, selection, path and dirty revision"); + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library); + assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work); + + // Naming a target is the explicit transition from a library document to a work file. + headless.save(None, Some(Path::new("same.pcraft")), None, &Default::default()).unwrap(); + assert_eq!(headless.session.active().unwrap().path.as_deref(), Some("same.pcraft")); + assert!(!headless.session.active().unwrap().is_dirty()); + assert_ne!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work); + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library); + + edit(&mut headless, "Later work edit"); + assert_eq!(headless.save(None, None, None, &Default::default()).unwrap()["path"], "same.pcraft"); + assert!(!headless.session.active().unwrap().is_dirty()); + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library); + + let mut reopened = roots.headless(); + reopened.open(&roots.work.join("same.pcraft")).unwrap(); + assert_source(&reopened, 11, [255; 4]); + assert_eq!(reopened.inspect(None).unwrap()["layers"][0]["name"], "Later work edit"); +} + +#[test] +fn absolute_path_selects_the_second_read_root_and_allows_its_own_implicit_save() { + let roots = Roots::new("absolute-work"); + let (library, work) = roots.seed(); + let mut headless = roots.headless(); + let path = roots.work.join("same.pcraft"); + headless.open(&path).unwrap(); + assert_source(&headless, 7, [0, 0, 0, 255]); + assert_eq!(headless.session.active().unwrap().path.as_deref(), path.to_str()); + edit(&mut headless, "Absolute work edit"); + assert_eq!(headless.save(None, None, None, &Default::default()).unwrap()["path"], path.to_str().unwrap()); + assert!(!headless.session.active().unwrap().is_dirty()); + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library); + assert_ne!(std::fs::read(&path).unwrap(), work); +} + +#[test] +fn missing_library_file_falls_through_to_a_writable_work_document() { + let roots = Roots::new("relative-work"); + let work = layered_bytes(7, "black"); + std::fs::write(roots.work.join("unique.pcraft"), &work).unwrap(); + let mut headless = roots.headless(); + headless.open(Path::new("unique.pcraft")).unwrap(); + assert_source(&headless, 7, [0, 0, 0, 255]); + assert_eq!(headless.session.active().unwrap().path.as_deref(), Some("unique.pcraft")); + edit(&mut headless, "Relative work edit"); + headless.save(None, None, None, &Default::default()).unwrap(); + assert_ne!(std::fs::read(roots.work.join("unique.pcraft")).unwrap(), work); + assert!(!roots.library.join("unique.pcraft").exists()); +} + +#[test] +fn read_only_roots_can_reopen_exported_work_without_acquiring_write_authority() { + let roots = Roots::new("readonly-reopen"); + let (library, _) = roots.seed(); + { + let mut writer = roots.headless(); + writer.open(Path::new("same.pcraft")).unwrap(); + edit(&mut writer, "Exported for review"); + writer.save(None, Some(Path::new("review.pcraft")), None, &Default::default()).unwrap(); + } + let exported = std::fs::read(roots.work.join("review.pcraft")).unwrap(); + let workspace = AuthorizedWorkspace::with_read_roots([roots.library.as_path(), roots.work.as_path()], None).unwrap(); + let mut reader = Headless::with_workspace(workspace); + for path in [PathBuf::from("review.pcraft"), roots.work.join("review.pcraft")] { + reader.open(&path).unwrap(); + assert_source(&reader, 11, [255; 4]); + assert_eq!(reader.inspect(None).unwrap()["layers"][0]["name"], "Exported for review"); + assert!(reader.session.active().unwrap().path.is_none()); + edit(&mut reader, "Unsaved review edit"); + let before = snapshot(&mut reader); + assert!(reader.save(None, None, None, &Default::default()).is_err()); + let error = reader.save(None, Some(Path::new("review.pcraft")), None, &Default::default()).unwrap_err().to_string(); + assert!(error.contains("write authority is absent"), "{error}"); + assert_eq!(snapshot(&mut reader), before); + } + assert_eq!(std::fs::read(roots.work.join("review.pcraft")).unwrap(), exported); + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library); +} + +#[test] +fn a_write_root_does_not_implicitly_grant_read_access_to_saved_work() { + let roots = Roots::new("write-is-not-read"); + let _ = roots.seed(); + let workspace = AuthorizedWorkspace::with_read_roots([roots.library.as_path()], Some(roots.work.as_path())).unwrap(); + let mut headless = Headless::with_workspace(workspace); + headless.open(Path::new("same.pcraft")).unwrap(); + headless.save(None, Some(Path::new("written.pcraft")), None, &Default::default()).unwrap(); + let before = snapshot(&mut headless); + for path in [PathBuf::from("written.pcraft"), roots.work.join("written.pcraft")] { + assert!(headless.open(&path).is_err()); + assert_eq!(snapshot(&mut headless), before); + } + assert!(roots.work.join("written.pcraft").is_file()); +} + +#[test] +fn flat_export_does_not_arm_implicit_save_for_a_library_document() { + let roots = Roots::new("flat-export"); + let (library, work) = roots.seed(); + let mut headless = roots.headless(); + headless.open(Path::new("same.pcraft")).unwrap(); + edit(&mut headless, "Still unsaved"); + let before = snapshot(&mut headless); + headless.save(None, Some(Path::new("preview.png")), None, &Default::default()).unwrap(); + assert_eq!(snapshot(&mut headless), before, "a flat export must not clear dirty or attach a save path"); + let exported = std::fs::read(roots.work.join("preview.png")).unwrap(); + assert_eq!(photocraft_codecs::decode(&exported).unwrap().dimensions(), (11, 5)); + assert!(headless.save(None, None, None, &Default::default()).is_err()); + assert_eq!(snapshot(&mut headless), before); + assert_eq!(std::fs::read(roots.work.join("preview.png")).unwrap(), exported); + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library); + assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work); +} + +#[test] +fn library_absolute_paths_and_traversal_cannot_be_used_as_save_targets() { + let roots = Roots::new("rejected-writes"); + let (library, work) = roots.seed(); + let canary = layered_bytes(3, "black"); + std::fs::write(roots.outside.join("canary.pcraft"), &canary).unwrap(); + let mut headless = roots.headless(); + headless.open(&roots.library.join("same.pcraft")).unwrap(); + assert!(headless.session.active().unwrap().path.is_none()); + edit(&mut headless, "Must remain unsaved"); + let before = snapshot(&mut headless); + for path in [ + roots.library.join("same.pcraft"), + PathBuf::from("../library/same.pcraft"), + PathBuf::from("../outside/canary.pcraft"), + roots.work.join("..").join("outside").join("canary.pcraft"), + ] { + let error = headless.save(None, Some(&path), None, &Default::default()).unwrap_err().to_string(); + assert!(error.contains("automation path rejected"), "{path:?}: {error}"); + assert_eq!(snapshot(&mut headless), before); + } + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library); + assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work); + assert_eq!(std::fs::read(roots.outside.join("canary.pcraft")).unwrap(), canary); +} + +#[cfg(any(unix, windows))] +#[test] +fn a_work_directory_symlink_cannot_write_into_another_read_root() { + let roots = Roots::new("symlink-write"); + let (library, work) = roots.seed(); + #[cfg(unix)] + std::os::unix::fs::symlink(&roots.library, roots.work.join("library-link")).unwrap(); + #[cfg(windows)] + if let Err(error) = std::os::windows::fs::symlink_dir(&roots.library, roots.work.join("library-link")) { + if error.kind() == std::io::ErrorKind::PermissionDenied { + eprintln!("symlink regression requires Windows symlink permission: {error}"); + return; + } + panic!("create test symlink: {error}"); + } + let mut headless = roots.headless(); + headless.open(Path::new("same.pcraft")).unwrap(); + edit(&mut headless, "Cannot follow the write link"); + let before = snapshot(&mut headless); + for path in ["library-link/same.pcraft", "library-link/new.pcraft"] { + assert!(headless.save(None, Some(Path::new(path)), None, &Default::default()).is_err()); + assert_eq!(snapshot(&mut headless), before); + } + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library); + assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work); + assert!(!roots.library.join("new.pcraft").exists()); +} + +#[test] +fn corrupt_first_match_is_an_error_instead_of_falling_through_to_a_valid_document() { + let roots = Roots::new("corrupt-first"); + let (_, work) = roots.seed(); + let corrupt = b"this is not a native document"; + std::fs::write(roots.library.join("same.pcraft"), corrupt).unwrap(); + let mut headless = roots.headless(); + // The later file is valid, and a failed open must leave this active document intact. + headless.open(&roots.work.join("same.pcraft")).unwrap(); + assert_source(&headless, 7, [0, 0, 0, 255]); + edit(&mut headless, "Existing edit"); + let before = snapshot(&mut headless); + assert!(headless.open(Path::new("same.pcraft")).is_err()); + assert_eq!(snapshot(&mut headless), before); + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), corrupt); + assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work); +} + +#[test] +fn multiple_roots_do_not_grant_ambient_commands_or_nested_action_file_access() { + let roots = Roots::new("ambient-commands"); + let (library, work) = roots.seed(); + let mut headless = roots.headless(); + headless.open(Path::new("same.pcraft")).unwrap(); + let before = snapshot(&mut headless); + let target = roots.work.join("ambient.psd"); + let error = headless.command_run("file.saveACopy", json!({"path": target})).unwrap_err().to_string(); + assert!(error.contains("ambient filesystem paths"), "{error}"); + // A writable destination still cannot be reached through an ambient engine command. + headless.session.actions.list.push(Action::new("Write work", vec![("file.saveACopy".into(), json!({"path": target}))])); + headless.session.actions.list.push(Action::new("Nested write", vec![("actions.play".into(), json!({"action": "Write work"}))])); + let played = headless.command_run("actions.play", json!({"action": "Nested write"})).unwrap(); + assert!(played["failed"].to_string().contains("ambient filesystem paths"), "{played}"); + assert_eq!(snapshot(&mut headless), before); + assert!(!target.exists()); + assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library); + assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work); +} diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index 36dcc4a2ed3..578bf3fc47b 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -2,8 +2,8 @@ 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::{ - BlendMode, Buffer, Effect, FxMaps, FxPaint, GlobalLight, Layer, MAX_REACH, Map, PREPARED_PATTERN_BYTES, Pattern, Placement, PreparedPatterns, Rect, - StrokePosition, psblend, + Bevel, BevelStyle, BlendMode, Buffer, Effect, FxMaps, FxPaint, GlobalLight, Layer, MAX_REACH, Map, PREPARED_PATTERN_BYTES, Pattern, Placement, + PreparedPatterns, Rect, StrokePosition, psblend, }; /// Build every effect map for `layer` from its alpha `shape` over `rect`. @@ -56,6 +56,37 @@ pub(crate) fn build_maps_prepared( 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)], + // Stroke Emboss (#8639): an Inner Bevel of the layer's outline with its Stroke effects + // (the stroked shape's outer edge, inside the stroke too), shading only the strokes, + // over the finished layer, as Photoshop's corpus files show it. Several strokes emboss + // as their union (a 4 px stroke over a 10 px one shades the whole 10 px band). Without + // a stroke it has nothing to emboss. + Effect::BevelEmboss(b) if b.style == BevelStyle::StrokeEmboss => { + let strokes: Vec<&photocraft_doc::StrokeFx> = items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(st) } else { None }).collect(); + let band = strokes.iter().map(|st| stroke_band(&shape, st)).reduce(|mut acc, m| { + for (a, s) in acc.v.iter_mut().zip(&m.v) { + *a = a.max(*s); + } + acc + }); + // Strokes inside the layer shade with the layer, as an Inner Bevel does; one + // reaching outside shades over the finished layer and its backdrop. + bevel_paint[i] = if strokes_inside(&strokes) { BevelPaint::Inner } else { BevelPaint::Both }; + match band { + Some(band) => { + // The shape keeps its own (anti-aliased) edge; the stroke adds what lies outside it. + let outline = Map { w, h, v: shape.v.iter().zip(&band.v).map(|(a, s)| if *a > INSIDE_EPS { *a } else { a.max(*s) }).collect() }; + let mut maps = bevel_maps(&outline, &Bevel { style: BevelStyle::InnerBevel, ..(*b).clone() }, light, tex, patterns).0; + for m in &mut maps { + for (v, s) in m.v.iter_mut().zip(&band.v) { + *v *= s; + } + } + maps + } + None => vec![Map::new(w, h, 0.0), Map::new(w, h, 0.0)], + } + } Effect::BevelEmboss(b) => { let (maps, paint) = bevel_maps(&shape, b, light, tex, patterns); bevel_paint[i] = paint; @@ -148,16 +179,48 @@ pub fn premerges_layer(layer: &Layer) -> bool { } } +/// Coverage of `st`'s band around `shape` (row-major over the same region): its inside part as +/// far in as the inside width, its outside part as far out as the outside width, as the +/// compositor paints them. The shape Stroke Emboss bevels (#8639). +fn stroke_band(shape: &Map, st: &photocraft_doc::StrokeFx) -> Map { + let (in_w, out_w) = stroke_widths(st); + let din = (in_w > 0.0).then(|| dist_inside_by(shape, Metric::Chamfer)); + let metric = if stroke_outside_exact(out_w) { Metric::Euclidean } else { Metric::Chamfer }; + let dout = (out_w > 0.0).then(|| dist_outside_by(shape, metric)); + let mut band = Map::new(shape.w, shape.h, 0.0); + for (i, (b, a)) in band.v.iter_mut().zip(&shape.v).enumerate() { + *b = if *a > INSIDE_EPS { + din.as_ref().and_then(|d| d.get(i)).map_or(0.0, |d| (in_w + 0.5 - d).clamp(0.0, 1.0)) + } else { + dout.as_ref().and_then(|d| d.get(i)).map_or(0.0, |d| (out_w + 0.5 - d).clamp(0.0, 1.0)) + }; + } + band +} + +/// `true` if there are strokes and none reaches outside the layer: Stroke Emboss then shades with +/// the layer, as an Inner Bevel does. +fn strokes_inside(strokes: &[&photocraft_doc::StrokeFx]) -> bool { + !strokes.is_empty() && strokes.iter().all(|st| stroke_widths(st).1 <= 0.0) +} + /// `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 { +pub(super) fn blends_inside(layer: &Layer) -> bool { let blends = |m: BlendMode| m != BlendMode::Normal; + // Stroke Emboss with its strokes wholly inside shades with the layer (`BevelPaint::Inner` in + // `build_maps_prepared`), as an Inner Bevel does; one reaching outside shades over the + // finished layer. + let strokes: Vec<&photocraft_doc::StrokeFx> = + layer.effects.items.iter().filter(|e| e.enabled()).filter_map(|e| if let Effect::Stroke(st) = e { Some(st) } else { None }).collect(); + let stroke_inside = strokes_inside(&strokes); 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) if b.style == BevelStyle::StrokeEmboss => stroke_inside && (blends(b.highlight.blend) || blends(b.shadow.blend)), Effect::BevelEmboss(b) => bevel_geom(b).paint == BevelPaint::Inner && (blends(b.highlight.blend) || blends(b.shadow.blend)), Effect::DropShadow(_) | Effect::OuterGlow(_) => false, }) diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index 4aea00004f0..83cef453ca7 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -1047,3 +1047,69 @@ fn shifting_by_hostile_distances_does_not_overflow() { assert_eq!(s.v.len(), 144); } } + +/// #8639 review: a Stroke Emboss whose stroke lies wholly inside shades with the layer, so its +/// non-Normal highlight or shadow counts as an interior blend, as an Inner Bevel's does; with the +/// stroke reaching outside, or no stroke, it doesn't. +#[test] +fn an_inside_stroke_emboss_counts_as_an_interior_blend() { + let stroke = |position: StrokePosition| { + Effect::Stroke(photocraft_doc::StrokeFx { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + size: 4.0, + position, + paint: photocraft_doc::FxPaint::Color(photocraft_color::Color::BLACK), + overprint: false, + }) + }; + let layer = |effects: Vec| { + let mut l = + photocraft_doc::Layer::new("L", photocraft_doc::LayerContent::Raster(photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8))); + l.effects.items = effects; + l + }; + let emboss = Effect::BevelEmboss(bevel_of(BevelStyle::StrokeEmboss, BevelTechnique::Smooth)); + assert!(super::composite::blends_inside(&layer(vec![stroke(StrokePosition::Inside), emboss.clone()]))); + assert!(!super::composite::blends_inside(&layer(vec![stroke(StrokePosition::Outside), emboss.clone()]))); + assert!(!super::composite::blends_inside(&layer(vec![stroke(StrokePosition::Center), emboss.clone()]))); + assert!(!super::composite::blends_inside(&layer(vec![emboss]))); +} + +/// #8639 review, measured in the reference application: Stroke Emboss bevels the union of every +/// enabled Stroke (a 4 px stroke listed over a 10 px one shades the whole 10 px band), and a +/// stroke at 0 % opacity still has its band embossed over the backdrop. +#[test] +fn stroke_emboss_bevels_every_stroke_even_a_transparent_one() { + let stroke = |size: f32, position: StrokePosition, opacity: f32| { + Effect::Stroke(photocraft_doc::StrokeFx { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, opacity), + size, + position, + paint: photocraft_doc::FxPaint::Color(photocraft_color::Color::BLACK), + overprint: false, + }) + }; + let emboss = Effect::BevelEmboss(bevel_of(BevelStyle::StrokeEmboss, BevelTechnique::Smooth)); + let maps = |effects: Vec| { + let mut l = + photocraft_doc::Layer::new("L", photocraft_doc::LayerContent::Raster(photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8))); + l.effects.items = effects; + let n = l.effects.items.len(); + let m = build_maps(&l, square(60, 20, 40).v, Rect::new(0, 0, 60, 60), &GlobalLight::default(), &no_tex()); + (m.per[n - 1].clone(), m.bevel_paint[n - 1]) + }; + // 7 px above the shape: inside the 10 px band only; the bevel (light from the top) lights it. + let lit = |m: &[Map]| m[0].v[13 * 60 + 30]; + let (two, paint) = maps(vec![stroke(4.0, StrokePosition::Outside, 1.0), stroke(10.0, StrokePosition::Outside, 1.0), emboss.clone()]); + assert!(lit(&two) > 0.1, "{}", lit(&two)); + assert_eq!(paint, BevelPaint::Both); + let (thin, _) = maps(vec![stroke(4.0, StrokePosition::Outside, 1.0), emboss.clone()]); + assert_eq!(lit(&thin), 0.0); + let (clear, _) = maps(vec![stroke(10.0, StrokePosition::Outside, 0.0), emboss.clone()]); + assert!(lit(&clear) > 0.1, "{}", lit(&clear)); + // Inside only when every stroke is. + let (_, inside) = maps(vec![stroke(4.0, StrokePosition::Inside, 1.0), stroke(6.0, StrokePosition::Inside, 1.0), emboss.clone()]); + assert_eq!(inside, BevelPaint::Inner); + let (_, mixed) = maps(vec![stroke(4.0, StrokePosition::Inside, 1.0), stroke(6.0, StrokePosition::Outside, 1.0), emboss]); + assert_eq!(mixed, BevelPaint::Both); +} diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs index c0ae28d3402..d111ab8b57a 100644 --- a/crates/compose/src/extents.rs +++ b/crates/compose/src/extents.rs @@ -1,6 +1,6 @@ use super::content::{render_content, surface_to_buffer}; use super::ctx::Ctx; -use super::{BlendMode, Document, Layer, LayerContent, Rect, advanced, bounds, effects, masks, shape_split}; +use super::{BlendMode, Document, Layer, LayerContent, Rect, adjustment_quantum, advanced, bounds, effects, masks, shape_split}; /// Bounds of a layer's own pixels (union over group children; the canvas /// for fill layers; an artboard's board). @@ -379,11 +379,16 @@ pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option { if !transparent_outside(layer) { return None; } + let m = if effects::has_effects(layer) { effects::margin(layer) } else { 0 }; let own = match &layer.content { - LayerContent::Group(g) if g.artboard.is_none() => { - let mut acc = frame_stroke_bounds(layer, canvas); + // A shapeless group's effects cover the whole layer: `layer_bounds` gives the canvas. + LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => { + // Children up to its effects' reach off the canvas still cast them onto it (group + // effects are built past the canvas). + let near = canvas.inflate(m); + let mut acc = frame_stroke_bounds(layer, near); for c in g.children.iter().filter(|c| c.visible) { - let b = composite_bounds(c, canvas)?; + let b = composite_bounds(c, near)?; if !b.is_empty() { acc = if acc.is_empty() { b } else { acc.union(&b) }; } @@ -396,7 +401,6 @@ pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option { 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)) } @@ -424,23 +428,47 @@ pub fn change_bounds(layer: &Layer, canvas: Rect) -> Option { 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 { +/// The lists holding the groups around a sibling list, outermost first: each list, and the +/// group's index there (empty at the top level). +pub type Ancestors<'a> = [(&'a [Layer], usize)]; + +/// The union of two bounds, either of which may be empty. +fn join(a: Rect, b: Rect) -> Rect { + if a.is_empty() { + b + } else if b.is_empty() { + a + } else { + a.union(&b) + } +} + +/// [`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). 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. +/// - an unclipped adjustment layer, and a pass-through group holding one (see +/// [`adjustment_reach`]). +/// +/// `ancestors` are the lists holding the groups around `layers`, outermost first; `depth` is the +/// document's, which decides whether adjustments round the backdrop ([`adjustment_quantum`]). +/// +/// The result is an **in-place** bound: what changes if the layer changes where it is. For an +/// adjustment it covers the layers beneath it (or its clip base), which don't move with it, so it +/// must never be translated, as a Move drag preview would. Use the context-free [`change_bounds`], +/// which moves with the layer, for that. +pub fn change_bounds_in(layers: &[Layer], k: usize, ancestors: &Ancestors, depth: photocraft_color::SampleType, 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) + if let Some((outer, g)) = ancestors.last() + && let Some(group) = outer.get(*g) && group.blend == BlendMode::PassThrough && !group.clipped && outer.get(g + 1).is_some_and(|above| above.clipped) @@ -450,7 +478,138 @@ pub fn change_bounds_in(layers: &[Layer], k: usize, outer: Option<(&[Layer], usi } return change_bounds(base, canvas); } - change_bounds(layer, canvas) + match &layer.content { + LayerContent::Adjustment(_) => adjustment_reach(layers, k, ancestors, depth, canvas), + LayerContent::Group(g) if layer.blend == BlendMode::PassThrough && !layer.clipped && change_bounds(layer, canvas).is_none() => { + // Its own pixels, plus where each adjustment inside reaches. + let mut acc = composite_bounds(layer, canvas)?; + let mut inner = ancestors.to_vec(); + inner.push((layers, k)); + for (j, c) in g.children.iter().enumerate() { + if matches!(c.content, LayerContent::Adjustment(_)) || matches!(c.content, LayerContent::Group(_)) && c.blend == BlendMode::PassThrough { + acc = join(acc, change_bounds_in(&g.children, j, &inner, depth, canvas)?); + } + } + Some(acc) + } + _ => change_bounds(layer, canvas), + } +} + +/// Where showing, hiding or restyling the unclipped adjustment `layers[k]` can change the +/// document, or `None` for anywhere. It changes only pixels already drawn beneath it in its +/// isolation scope: the visible layers below it, and inside a pass-through group the layers below +/// the group too, up to the top level or the first isolated group (a pass-through group the +/// compositor isolates reaches less, so this still covers it). Adjustments draw no alpha of their +/// own, so what is transparent there stays so. +/// +/// In a 32-bit document it also changes only where its layer mask lets it through (an enabled +/// mask that hides by default at full density, grown by the feather). An integer document rounds +/// the whole backdrop to its levels after every visible adjustment layer, masked or not (#9033), +/// so there the mask bounds nothing. Layers clipped to an adjustment composite atop the adjusted +/// backdrop wherever they draw, and a knockout reveals what lies beneath it: both stay `None`. +pub fn adjustment_reach(layers: &[Layer], k: usize, ancestors: &Ancestors, depth: photocraft_color::SampleType, canvas: Rect) -> Option { + let layer = layers.get(k)?; + if layers.get(k + 1).is_some_and(|above| above.clipped) || layer.advanced.knockout != photocraft_doc::Knockout::None { + return None; + } + let mask = adjustment_quantum(depth).is_none().then(|| adjustment_mask_bounds(layer)).flatten(); + let below = beneath(layers, k, ancestors, canvas); + let reach = match (mask, below) { + (Some(m), Some(b)) => m.intersect(&b).intersect(&canvas), + (Some(m), None) => m.intersect(&canvas), + (None, b) => b?, + }; + // A pass-through group that is a clip base renders isolated while it holds a visible + // adjustment, so showing or hiding the last one switches how the whole group composites: the + // two agree outside `beneath` only up to float rounding. The clipped branch of + // [`change_bounds_in`] covers the group the same way. + if let Some((outer, g)) = ancestors.last() + && let Some(group) = outer.get(*g) + && group.blend == BlendMode::PassThrough + && !group.clipped + && outer.get(g + 1).is_some_and(|above| above.clipped) + { + return Some(join(reach, composite_bounds(group, canvas)?)); + } + Some(reach) +} + +/// Where an adjustment's layer mask can let it through: an enabled mask that hides by default at +/// full density, so outside its painted tiles (grown by its feather, or a vector mask's, since +/// the two multiply) it hides the layer. +fn adjustment_mask_bounds(layer: &Layer) -> Option { + let m = layer.mask.as_ref().filter(|m| m.enabled && m.density >= 1.0)?; + if !m.surface.default_pixel().first().is_some_and(|v| *v <= 0.0) { + return None; + } + let vector = layer.vector_mask.as_ref().filter(|v| v.enabled).map_or(0.0, |v| photocraft_vector::feather::feather_sigma(v.feather)); + let sigma = photocraft_vector::feather::feather_sigma(m.feather).max(vector); + let tiles = m.surface.tile_bounds(); + Some(if sigma > 0.0 { photocraft_vector::feather::grow(tiles, sigma) } else { tiles }) +} + +/// The union of [`composite_bounds`] of the visible layers below `layers[k]`, continuing below a +/// pass-through group into the list holding it; `None` when any may draw anywhere. +fn beneath(layers: &[Layer], k: usize, ancestors: &Ancestors, canvas: Rect) -> Option { + let mut acc = Rect::EMPTY; + for l in layers.get(..k)?.iter().filter(|l| l.visible) { + acc = join(acc, composite_bounds(l, canvas)?); + } + if let Some((&(outer, g), rest)) = ancestors.split_last() + && let Some(group) = outer.get(g) + && group.blend == BlendMode::PassThrough + { + if group.clipped { + return None; + } + // An artboard's background lies beneath its layers. + if let LayerContent::Group(gr) = &group.content + && let Some(ab) = gr.artboard.as_ref().filter(|ab| ab.background.rgba().is_some()) + { + acc = join(acc, ab.rect.intersect(&canvas)); + } + acc = join(acc, beneath(outer, g, rest, canvas)?); + } + Some(acc) +} + +/// Where a layer sits: its sibling list, its index there, and the lists around it ([`Ancestors`]). +pub type Placement<'a> = (&'a [Layer], usize, Vec<(&'a [Layer], usize)>); + +/// Where layer `id` sits in `doc` ([`Placement`]). +pub fn siblings_of(doc: &Document, id: photocraft_doc::LayerId) -> Option> { + fn find<'a>(layers: &'a [Layer], id: photocraft_doc::LayerId, path: &mut Vec<(&'a [Layer], usize)>) -> Option<(&'a [Layer], usize)> { + for (k, l) in layers.iter().enumerate() { + if l.id == id { + return Some((layers, k)); + } + if let Some(c) = l.children() { + path.push((layers, k)); + if let Some(hit) = find(c, id, path) { + return Some(hit); + } + path.pop(); + } + } + None + } + let mut path = Vec::new(); + let (layers, k) = find(&doc.layers, id, &mut path)?; + Some((layers, k, path)) +} + +/// [`change_bounds_in`] of layer `id` where it sits in `doc`, grown by the reach of the effects +/// of the groups around it (a parent's drop shadow), or `None` for anywhere (or no such layer). +/// An in-place bound: never translate it (see [`change_bounds_in`]). +pub fn layer_change_bounds(doc: &Document, id: photocraft_doc::LayerId) -> Option { + let (layers, k, ancestors) = siblings_of(doc, id)?; + let reach = ancestors.iter().filter_map(|(ls, g)| ls.get(*g)).filter(|l| effects::has_effects(l)).fold(0i32, |r, l| r.saturating_add(effects::margin(l))); + // Bounded within that reach of the canvas, not on it: a layer just off the canvas still + // moves a parent's shadow onto it (group effects are built past the canvas). + let canvas = doc.bounds(); + let r = change_bounds_in(layers, k, &ancestors, doc.depth, canvas.inflate(reach))?; + Some(if r.is_empty() { r } else { r.inflate(reach).intersect(&canvas) }) } /// Whether the layer's content is transparent outside its bounds (every surface it draws from diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e93e0818f30..5bc5e723ae1 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -65,8 +65,8 @@ use ctx::{Ctx, prepare_effects}; 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, + Ancestors, Placement, adjustment_reach, change_bounds, change_bounds_in, composite_bounds, effect_outline, effect_source_bounds, effects_frame, + hard_shape_bounds, layer_bounds, layer_change_bounds, paint_bounds, relayout_damage, shape_bounds, siblings_of, soft_shape_frame, transparent_outside, }; #[cfg(test)] use extents::{mask_k, shapeless_stroke_bounds, trim_to_painted}; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 153b038adf5..5278fe18280 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -794,7 +794,7 @@ fn clipped_adjustment_changes_only_its_base() { adj.clipped = true; d.layers.push(adj); assert_eq!(change_bounds(&d.layers[3], canvas), None); - assert_eq!(change_bounds_in(&d.layers, 3, None, canvas), Some(base_rect)); + assert_eq!(change_bounds_in(&d.layers, 3, &[], SampleType::U8, canvas), Some(base_rect)); // Every pixel the toggle changes lies inside those bounds. let shown = render(&d, canvas); d.layers[3].visible = false; @@ -810,24 +810,24 @@ fn clipped_adjustment_changes_only_its_base() { } assert_eq!(changed, base_rect); // Other layers keep their own bounds. - assert_eq!(change_bounds_in(&d.layers, 2, None, canvas), Some(Rect::new(3, 2, 4, 3))); - assert_eq!(change_bounds_in(&d.layers, 9, None, canvas), None); + assert_eq!(change_bounds_in(&d.layers, 2, &[], SampleType::U8, canvas), Some(Rect::new(3, 2, 4, 3))); + assert_eq!(change_bounds_in(&d.layers, 9, &[], SampleType::U8, canvas), None); // Unclipped, or with no base beneath it, it reaches everything. let mut free = d.layers.clone(); free[3].clipped = false; - assert_eq!(change_bounds_in(&free, 3, None, canvas), None); + assert_eq!(change_bounds_in(&free, 3, &[], SampleType::U8, canvas), Some(canvas)); let orphan = vec![d.layers[3].clone()]; - assert_eq!(change_bounds_in(&orphan, 0, None, canvas), None); + assert_eq!(change_bounds_in(&orphan, 0, &[], SampleType::U8, canvas), None); // Clipped layers on an adjustment composite atop the adjusted backdrop. let on_adj = vec![d.layers[0].clone(), Layer::new("lv", LayerContent::Adjustment(Adjustment::Invert)), d.layers[3].clone()]; - assert_eq!(change_bounds_in(&on_adj, 2, None, canvas), None); + assert_eq!(change_bounds_in(&on_adj, 2, &[], SampleType::U8, canvas), None); // A pass-through group holding an adjustment is isolated only while it has visible clipped // layers, so they change whether its adjustment reaches the layers beneath. let mut g = Layer::group("g", vec![solid_layer("in", base_rect, [0.2, 0.4, 0.6, 1.0]), Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]); g.blend = BlendMode::PassThrough; let on_group = vec![d.layers[0].clone(), g, d.layers[3].clone()]; - assert_eq!(change_bounds_in(&on_group, 2, None, canvas), None); + assert_eq!(change_bounds_in(&on_group, 2, &[], SampleType::U8, canvas), None); } /// #6535: a clipped adjustment with no base beneath it, inside a pass-through group, composites @@ -848,12 +848,12 @@ fn orphan_clipped_adjustment_in_pass_through_base_reaches_everything() { let shown = px(&d, 0, 0); d.layers[2].visible = false; assert!(!close4(shown, px(&d, 0, 0)), "the toggle changes pixels outside the group"); - assert_eq!(change_bounds_in(&d.layers, 2, None, canvas), None); + assert_eq!(change_bounds_in(&d.layers, 2, &[], SampleType::U8, canvas), None); assert_eq!(change_bounds(&d.layers[1], canvas), None); // With a base beneath it the clipped adjustment stays inside the group. let LayerContent::Group(g) = &mut d.layers[1].content else { panic!("group") }; g.children.swap(0, 1); - assert_eq!(change_bounds_in(&d.layers, 2, None, canvas), Some(Rect::new(2, 1, 4, 3))); + assert_eq!(change_bounds_in(&d.layers, 2, &[], SampleType::U8, canvas), Some(Rect::new(2, 1, 4, 3))); } /// A pass-through group that is a clip base renders isolated while it holds a visible @@ -880,11 +880,225 @@ fn clipped_adjustment_in_pass_through_clip_base_reaches_its_group() { assert!(!close4(shown, px(&d, 7, 5)), "hiding A changes Q, outside A's base"); let group = Rect::new(2, 1, 8, 6); let LayerContent::Group(g) = &d.layers[2].content else { panic!("group") }; - assert_eq!(change_bounds_in(&g.children, 1, Some((&d.layers, 2)), canvas), Some(group)); + assert_eq!(change_bounds_in(&g.children, 1, &[(&d.layers, 2)], SampleType::U8, canvas), Some(group)); // Not a clip base: the group stays pass-through either way, and A changes only its base. d.layers.truncate(3); let LayerContent::Group(g) = &d.layers[2].content else { panic!("group") }; - assert_eq!(change_bounds_in(&g.children, 1, Some((&d.layers, 2)), canvas), Some(Rect::new(2, 1, 4, 3))); + assert_eq!(change_bounds_in(&g.children, 1, &[(&d.layers, 2)], SampleType::U8, canvas), Some(Rect::new(2, 1, 4, 3))); +} + +/// The composite of `after` equals `before`'s outside `damage`, exactly (as the engine's +/// `unchanged_outside` oracle checks a step's damage). +fn unchanged_outside(before: &Document, after: &Document, damage: Rect) -> bool { + let (x, y) = (render(before, before.bounds()), 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)) +} + +/// `d` with `layers[k]` (or, with `child`, that child of the group there) hidden. +fn hidden_at(d: &Document, k: usize, child: Option) -> Document { + let mut h = d.clone(); + match child { + None => h.layers[k].visible = false, + Some(c) => h.layers[k].children_mut().unwrap()[c].visible = false, + } + h +} + +/// An Invert adjustment whose layer mask reveals only `r`. +fn masked_invert(r: Rect) -> Layer { + let mut adj = Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)); + let mut m = LayerMask::hide_all(); + m.surface.fill_rect(r, &[1.0]); + adj.mask = Some(m); + adj +} + +/// A layer at 37 % opacity, so the backdrop it leaves falls between an integer document's +/// levels (which an adjustment above rounds away). +fn faint_layer(r: Rect) -> Layer { + let mut l = solid_layer("faint", r, [0.2, 0.4, 0.6, 1.0]); + l.opacity = 0.37; + l +} + +/// #9329: in a 32-bit document a masked adjustment changes only under its mask (grown by its +/// feather), even over an opaque Background. +#[test] +fn a_masked_adjustment_changes_only_under_its_mask() { + let canvas = Rect::new(0, 0, 800, 600); + let reveal = Rect::new(520, 330, 560, 370); + for feather in [0.0, 6.0] { + let mut d = Document::with_background("t", Size::new(800, 600), ColorMode::Rgb, SampleType::F32, Color::WHITE); + d.layers.push(faint_layer(Rect::new(100, 100, 700, 500))); + let mut adj = masked_invert(reveal); + adj.mask.as_mut().unwrap().feather = feather; + d.layers.push(adj); + let b = change_bounds_in(&d.layers, 2, &[], SampleType::F32, canvas).expect("bounded by the mask"); + assert!(b.contains_rect(&reveal) && b.width() < canvas.width() && b.height() < canvas.height(), "{b:?}"); + let h = hidden_at(&d, 2, None); + assert_ne!(render(&d, canvas), render(&h, canvas)); + assert!(unchanged_outside(&d, &h, b), "feather {feather}"); + // At full density only: a lower density lets the adjustment through everywhere. + let mut thin = d.clone(); + thin.layers[2].mask.as_mut().unwrap().density = 0.5; + assert_eq!(change_bounds_in(&thin.layers, 2, &[], SampleType::F32, canvas), Some(canvas)); + } +} + +/// #9329: with no Background, an unmasked adjustment reaches only the layers beneath it, in an +/// integer document too (rounding the backdrop leaves transparent pixels transparent). +#[test] +fn an_adjustment_over_small_layers_reaches_only_them() { + let canvas = Rect::new(0, 0, 40, 30); + let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + let (p, q) = (Rect::new(2, 3, 10, 9), Rect::new(20, 12, 30, 25)); + d.layers.push(solid_layer("p", p, [0.2, 0.4, 0.6, 1.0])); + d.layers.push(faint_layer(q)); + d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))); + let k = d.layers.len() - 1; + let b = change_bounds_in(&d.layers, k, &[], SampleType::U8, canvas); + assert_eq!(b, Some(p.union(&q))); + let h = hidden_at(&d, k, None); + assert_ne!(render(&d, canvas), render(&h, canvas)); + assert!(unchanged_outside(&d, &h, b.unwrap())); +} + +/// #9329: over an opaque Background an adjustment reaches the canvas. In an integer document +/// even a masked one does: the backdrop is rounded to the document's levels after every visible +/// adjustment layer (#9033), outside its mask too. +#[test] +fn an_adjustment_over_a_background_reaches_the_canvas() { + let canvas = Rect::new(0, 0, 800, 600); + let reveal = Rect::new(520, 330, 560, 370); + let mut d = doc_white(800, 600); + d.layers.push(faint_layer(Rect::new(100, 100, 700, 500))); + d.layers.push(masked_invert(reveal)); + assert_eq!(change_bounds_in(&d.layers, 2, &[], SampleType::U8, canvas), Some(canvas)); + let h = hidden_at(&d, 2, None); + assert!(!unchanged_outside(&d, &h, reveal), "hiding it re-rounds pixels outside its mask"); + let unmasked = { + let mut u = d.clone(); + u.layers[2].mask = None; + u + }; + assert_eq!(change_bounds_in(&unmasked.layers, 2, &[], SampleType::U8, canvas), Some(canvas)); + assert_eq!(change_bounds_in(&unmasked.layers, 2, &[], SampleType::F32, canvas), Some(canvas)); +} + +/// #9329: inside a pass-through group an adjustment reaches the group's layers beneath it and +/// the layers beneath the group; so does the group itself. +#[test] +fn an_adjustment_in_a_pass_through_group_reaches_below_the_group() { + let canvas = Rect::new(0, 0, 40, 30); + let (p, q) = (Rect::new(2, 3, 10, 9), Rect::new(20, 12, 30, 25)); + let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + d.layers.push(faint_layer(p)); + let mut g = Layer::group("g", vec![solid_layer("q", q, [0.2, 0.4, 0.6, 1.0]), Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]); + g.blend = BlendMode::PassThrough; + d.layers.push(g); + let LayerContent::Group(gc) = &d.layers[1].content else { panic!("group") }; + let b = change_bounds_in(&gc.children, 1, &[(&d.layers, 1)], SampleType::U8, canvas); + assert_eq!(b, Some(p.union(&q))); + let h = hidden_at(&d, 1, Some(1)); + assert_ne!(render(&d, canvas), render(&h, canvas)); + assert!(unchanged_outside(&d, &h, b.unwrap())); + // The group: its own pixels and its adjustment's reach. + assert_eq!(change_bounds(&d.layers[1], canvas), None); + let gb = change_bounds_in(&d.layers, 1, &[], SampleType::U8, canvas); + assert_eq!(gb, Some(p.union(&q))); + assert!(unchanged_outside(&d, &hidden_at(&d, 1, None), gb.unwrap())); +} + +/// #9329: inside an isolated (Normal) group an adjustment reaches only the group's layers +/// beneath it. +#[test] +fn an_adjustment_in_an_isolated_group_stops_at_the_group() { + let canvas = Rect::new(0, 0, 40, 30); + let (p, q) = (Rect::new(2, 3, 10, 9), Rect::new(20, 12, 30, 25)); + let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + d.layers.push(faint_layer(p)); + let mut g = Layer::group("g", vec![faint_layer(q), Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]); + g.blend = BlendMode::Normal; + d.layers.push(g); + let LayerContent::Group(gc) = &d.layers[1].content else { panic!("group") }; + let b = change_bounds_in(&gc.children, 1, &[(&d.layers, 1)], SampleType::U8, canvas); + assert_eq!(b, Some(q)); + let h = hidden_at(&d, 1, Some(1)); + assert_ne!(render(&d, canvas), render(&h, canvas)); + assert!(unchanged_outside(&d, &h, q)); +} + +/// #9329: inside a pass-through artboard an adjustment also reaches the artboard's background, +/// which lies beneath its layers. +#[test] +fn an_adjustment_in_a_pass_through_artboard_reaches_its_background() { + let canvas = Rect::new(0, 0, 40, 30); + let board = Rect::new(4, 3, 24, 20); + let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + let mut ab = Layer::group("board", vec![Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]); + let LayerContent::Group(g) = &mut ab.content else { panic!("group") }; + g.artboard = Some(photocraft_doc::Artboard::new(board)); + d.layers.push(ab); + let LayerContent::Group(gc) = &d.layers[0].content else { panic!("group") }; + let b = change_bounds_in(&gc.children, 0, &[(&d.layers, 0)], SampleType::U8, canvas); + assert_eq!(b, Some(board)); + let h = hidden_at(&d, 0, Some(0)); + assert_ne!(render(&d, canvas), render(&h, canvas)); + assert!(unchanged_outside(&d, &h, board)); +} + +/// A layer just off the left edge of a 40 × 30 canvas, in a group whose drop shadow reaches +/// onto it. +fn shadowed_group_off_the_canvas() -> Layer { + let mut g = Layer::group("g", vec![solid_layer("off", Rect::new(-6, 8, -1, 16), [0.2, 0.4, 0.6, 1.0])]); + g.effects.items.push(Effect::default_drop_shadow()); + g +} + +/// #9329: an adjustment above a group whose pixels lie just off the canvas reaches the group's +/// drop shadow on the canvas. +#[test] +fn an_adjustment_over_a_shadowed_group_off_the_canvas_reaches_the_shadow() { + let canvas = Rect::new(0, 0, 40, 30); + let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + d.layers.push(shadowed_group_off_the_canvas()); + d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))); + let b = change_bounds_in(&d.layers, 1, &[], SampleType::U8, canvas).expect("bounded"); + let h = hidden_at(&d, 1, None); + assert_ne!(render(&d, canvas), render(&h, canvas), "the shadow reaches the canvas"); + assert!(unchanged_outside(&d, &h, b), "{b:?}"); +} + +/// #9329: a layer just off the canvas in a group with a drop shadow changes the shadow on the +/// canvas: [`layer_change_bounds`] grows by the reach of the groups around it. +#[test] +fn a_layer_off_the_canvas_in_a_shadowed_group_bounds_the_shadow() { + let canvas = Rect::new(0, 0, 40, 30); + let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + d.layers.push(shadowed_group_off_the_canvas()); + let id = d.layers[0].children().unwrap()[0].id; + let b = layer_change_bounds(&d, id).expect("bounded"); + let h = hidden_at(&d, 0, Some(0)); + assert_ne!(render(&d, canvas), render(&h, canvas), "the shadow reaches the canvas"); + assert!(unchanged_outside(&d, &h, b), "{b:?}"); +} + +/// #9329: a group with Transparency Shapes Layer off takes the whole layer as its effects' +/// shape, so it draws over the whole canvas, also while it holds an adjustment. +#[test] +fn a_shapeless_group_holding_an_adjustment_reaches_the_canvas() { + let canvas = Rect::new(0, 0, 40, 30); + let q = Rect::new(20, 12, 30, 25); + let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + let mut g = Layer::group("g", vec![solid_layer("q", q, [0.2, 0.4, 0.6, 1.0]), Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]); + g.effects.items.push(Effect::ColorOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), color: Color::BLACK }); + g.advanced.transparency_shapes = false; + d.layers.push(g); + let h = hidden_at(&d, 0, None); + assert!(!unchanged_outside(&d, &h, q.inflate(effects::margin(&d.layers[0]))), "the overlay draws past its layers"); + assert_eq!(composite_bounds(&d.layers[0], canvas), Some(canvas)); + assert_eq!(change_bounds_in(&d.layers, 0, &[], SampleType::U8, canvas), Some(canvas)); } #[test] diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 055444c1e9b..f6c8619f5a8 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -240,7 +240,18 @@ pub enum TextShape { /// (text-space pixels, before the layer transform) by arc length and turned to follow the /// curve. `start` is the arc-length offset (px) of the text origin along the path; `flip` /// puts the text on the other side of the path. - Path { path: super::vector::Subpath, start: f32, flip: bool }, + Path { + path: super::vector::Subpath, + start: f32, + /// Unwrapped arc-length end offset in text-space pixels, measured in the current + /// travel direction (`flip` reverses that direction). It may exceed the path length + /// on closed paths: for a 100 px loop, start 80 and end 120 cross the seam by 20 px. + /// End equal to start is empty; start plus the path length permits one full lap. + /// `None` preserves legacy unbounded clipping and alignment around the start anchor. + #[serde(default, skip_serializing_if = "Option::is_none")] + end: Option, + flip: bool, + }, /// Area type: paragraph text that wraps inside the closed subpaths of `path` (text-space /// pixels, before the layer transform), combined with their path operations and fill rule. /// Text that doesn't fit is hidden, as in a text box. @@ -286,6 +297,15 @@ pub struct TextWarp { #[cfg(test)] mod tests { + /// Ensures `TextShape::Path` serializes backward-compatibly without an `"end"` field when `end` is `None`. + #[test] + fn path_end_is_backward_compatible() { + let shape = super::TextShape::Path { path: Default::default(), start: 2.0, end: None, flip: false }; + let value = serde_json::to_value(&shape).unwrap(); + assert!(value.get("Path").unwrap().get("end").is_none()); + assert_eq!(serde_json::from_value::(value).unwrap(), shape); + } + use super::*; use crate::TextLayer; diff --git a/crates/engine/src/brush_clear_background_tests.rs b/crates/engine/src/brush_clear_background_tests.rs new file mode 100644 index 00000000000..e295e68c0b5 --- /dev/null +++ b/crates/engine/src/brush_clear_background_tests.rs @@ -0,0 +1,71 @@ +//! #11897: the Brush's chosen Clear on the Background paints as Normal. The options bar turns +//! Clear off at the press there (`clear_off_on_background` in ui-egui), so the engine never sees +//! it; a `"mode": "clear"` stroke that does reach the Background is a held `~`, which keeps +//! erasing to the background colour. On a pixel layer Clear still erases, and the Eraser on the +//! Background still paints the background colour. + +use crate::Session; +use serde_json::{Value, json}; + +const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + s.tools.foreground = BLACK; + s.tools.background = GREEN; + s +} + +fn pixel(s: &mut Session, x: i32, y: i32) -> [f32; 4] { + let v = s.execute("document.pixel", json!({"x": x, "y": y})).unwrap(); + let a: Vec = v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap() as f32).collect(); + [a[0], a[1], a[2], a[3]] +} + +fn close(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= 0.02) +} + +/// A hard stroke across (10..30, 10), as the canvas sends it in Clear mode. +fn clear_stroke() -> Value { + json!({"points": [[10, 10], [30, 10]], "size": 8, "hardness": 1.0, "erase": true, "mode": "clear"}) +} + +/// A held `~` on the Background erases to the background colour, as before #11897. +#[test] +fn a_clear_stroke_on_the_background_still_paints_the_background_colour() { + let mut s = session(); + s.execute("paint.stroke", clear_stroke()).unwrap(); + let p = pixel(&mut s, 20, 10); + assert!(close(p, GREEN), "painted {p:?}, not the foreground"); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Brush Tool")); +} + +#[test] +fn a_normal_stroke_on_the_background_paints_the_foreground() { + let mut s = session(); + s.execute("paint.stroke", json!({"points": [[10, 10], [30, 10]], "size": 8, "hardness": 1.0})).unwrap(); + let p = pixel(&mut s, 20, 10); + assert!(close(p, BLACK), "{p:?}"); +} + +#[test] +fn clear_on_a_pixel_layer_still_erases() { + let mut s = session(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": [1.0, 0.0, 0.0, 1.0]})).unwrap(); + s.execute("paint.stroke", clear_stroke()).unwrap(); + let p = pixel(&mut s, 20, 10); + assert!(close(p, WHITE), "erased down to the white Background: {p:?}"); +} + +#[test] +fn the_eraser_on_the_background_still_paints_the_background_colour() { + let mut s = session(); + s.execute("paint.stroke", json!({"points": [[10, 10], [30, 10]], "size": 8, "hardness": 1.0, "erase": true})).unwrap(); + let p = pixel(&mut s, 20, 10); + assert!(close(p, GREEN), "{p:?}"); +} diff --git a/crates/engine/src/canvas_geom.rs b/crates/engine/src/canvas_geom.rs index 93bc4654b9e..ff40ea8a8b1 100644 --- a/crates/engine/src/canvas_geom.rs +++ b/crates/engine/src/canvas_geom.rs @@ -242,9 +242,27 @@ pub(crate) fn transform_doc_marks(doc: &mut Document, a: &Affine) { if let Some(wp) = &mut doc.work_path { *wp = wp.transform(a); } + // A note's icon point maps with the pixels; its popup keeps its size (#11795). Under Image Size + // and Canvas Size it also keeps its offset from the icon, as Photoshop's does. Where it sits + // after a turn or flip wasn't measured, so it keeps today's origin there: the top-left of the + // mapped rectangle. for n in &mut doc.notes { + // An all-zero popup means none is stored (PSD export writes its default one): keep it. + if n.popup == [0.0; 4] { + n.position = map_pt(a, n.position); + continue; + } + let [px, py] = n.position; + let (dx, dy, w, h) = (n.popup[0] - px, n.popup[1] - py, n.popup[2] - n.popup[0], n.popup[3] - n.popup[1]); n.position = map_pt(a, n.position); - n.popup = map_box(a, n.popup); + let [m0, m1, m2, m3, ..] = a.m; + let [x, y] = if m1.abs() < EPS && m2.abs() < EPS && m0 > 0.0 && m3 > 0.0 { + [n.position[0] + dx, n.position[1] + dy] + } else { + let [l, t, ..] = map_box(a, n.popup); + [l, t] + }; + n.popup = [x, y, x + w, y + h]; } for g in &mut doc.measurement.count_groups { for p in &mut g.points { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e320d72f566..782cb637414 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -69,6 +69,10 @@ pub mod comps_cmds; pub mod contour_lib_cmds; #[cfg(test)] mod count_delete_group_tests; +#[cfg(test)] +mod count_history_names_tests; +#[cfg(test)] +mod count_record_label_tests; pub mod cutout_cmds; pub mod distort_cmds; pub mod document_preset_cmds; @@ -98,6 +102,7 @@ pub mod history_select_cmds; pub mod history_source_cmds; pub mod image_cmds; pub mod layer_copy_cmds; +pub mod layer_css_cmds; pub mod layer_label_cmds; pub mod layer_list_cmds; pub mod layer_mask_props_cmds; @@ -114,6 +119,8 @@ pub(super) mod migrate_cmds; pub mod mode_cmds; pub mod multichannel_cmds; pub mod notes_cmds; +#[cfg(test)] +mod notes_stored_values_tests; mod ops; pub mod paint_cmds; mod params; @@ -150,6 +157,8 @@ pub mod type_area_cmds; pub mod type_caret_cmds; pub mod type_cmds; pub mod type_extra_cmds; +#[cfg(test)] +mod type_indexed_mode_tests; pub mod type_mask_cmds; pub mod type_spell_cmds; pub mod type_styles_cmds; @@ -199,9 +208,14 @@ pub fn list_entry(s: &Session, c: &CommandSpec, reason: Option) -> Value /// Other names a command is looked for by, beyond its id and label: the Photoshop tools and /// options it stands for (#5060). `select.rect` is also the Elliptical and Single Row/Column -/// Marquee, which an agent searches for as "ellipse" or "marquee". -pub(crate) const SEARCH_KEYWORDS: &[(&str, &str)] = - &[("select.rect", "Rectangular Marquee, Elliptical Marquee (\"ellipse\":true), ellipse, oval, circle, Single Row/Column Marquee (\"line\")")]; +/// Marquee, which an agent searches for as "ellipse" or "marquee". The RAW Develop filter and +/// RAW Defaults keep Photoshop's "Camera Raw" name as a search alias only: the menus and windows +/// say "RAW Develop" (#12403). +pub(crate) const SEARCH_KEYWORDS: &[(&str, &str)] = &[ + ("select.rect", "Rectangular Marquee, Elliptical Marquee (\"ellipse\":true), ellipse, oval, circle, Single Row/Column Marquee (\"line\")"), + ("filter.cameraRaw", "Camera Raw Filter"), + ("edit.preferences.rawDefaults", "Camera Raw Defaults"), +]; /// [`SEARCH_KEYWORDS`] of command `id`, if it has any. pub fn search_keywords(id: &str) -> Option<&'static str> { @@ -573,6 +587,7 @@ fn build() -> Vec { let add_copy = layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); // The dialog offers Duplicate Layer's own name: only a different one was typed (#9023). let mut typed = None; + let mut shift = (0, 0); let nid = s.edit("Duplicate Layer", |doc, active| { let mut dup = layer_copy(doc, id, add_copy)?; if let Some(name) = name.as_ref().filter(|n| **n != dup.name) { @@ -583,11 +598,12 @@ fn build() -> Vec { // A lone copy joins its original's link group, as in the reference application (#11217). crate::layer_multi_cmds::relink_copies(doc, &[nid])?; if !in_place { - crate::artboard_cmds::place_copy(doc, nid)?; + shift = crate::artboard_cmds::place_copy(doc, nid)?; } *active = Some(nid); Ok(nid) })?; + crate::artboard_cmds::follow_shift(s, shift); if let Some(name) = typed { crate::type_cmds::note_typed_name(s, nid, &name); } @@ -1239,7 +1255,7 @@ fn build() -> Vec { ( "colorLookup", "Color Lookup…", - r##"{"lut":"none|warm|cool|tealOrange|bleachBypass|fadedFilm|dayForNight|monoContrast|crossProcess"="none","file":text,"interpolation":"trilinear|tetrahedral"="trilinear","dither":bool=false,"data":text,"dataEncoding":"text|base64"="text","fileName":text?,"lutFormat":"cube|3dl|look"?} (file: LUT path; data: file text or encoded bytes; lutFormat overrides format detection)"##, + r##"{"lut":"none|warm|cool|tealOrange|bleachBypass|fadedFilm|dayForNight|monoContrast|crossProcess"="none","file":text,"interpolation":"trilinear|tetrahedral"="trilinear","dither":bool=false,"data":text,"dataEncoding":"text|base64"="text","fileName":text,"lutFormat":"auto|cube|3dl|look"="auto"} (file: LUT path; data: file text or encoded bytes; lutFormat overrides format detection, auto detects it)"##, ), ]; for &(kind, label, params) in ADJ { @@ -1392,6 +1408,7 @@ fn build() -> Vec { v.extend(crate::adjust_cmds::specs()); v.extend(crate::layer_menu_cmds::specs()); v.extend(crate::layer_label_cmds::specs()); + v.extend(crate::layer_css_cmds::specs()); v.extend(crate::layer_xmp_cmds::specs()); v.extend(crate::mode_cmds::specs()); v.extend(crate::multichannel_cmds::specs()); diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index 6a18a871f1d..ed5da88e7db 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -334,11 +334,11 @@ fn record_drops_the_steps_of_a_command_that_failed_and_was_taken_back() { 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); + ruled_layer(&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!(s.execute("image.analysis.straightenLayer", json!({"crop": true})).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"); } @@ -500,23 +500,32 @@ fn ruled_background(s: &mut Session, depth: u32) { .unwrap(); } +/// The same, with a pixel layer on top: since #12033 the Background alone greys Straighten Layer +/// out, so the tests that run the command target a layer and pass `crop` explicitly. +fn ruled_layer(s: &mut Session, depth: u32) { + ruled_background(s, depth); + s.execute("layer.new.layer", json!({"name": "Paint"})).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); + ruled_layer(&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(); + // #12033: the crop is asked for, as automation does; the Background it used to default to + // now greys the command out. + s.execute("image.analysis.straightenLayer", json!({"crop": true})).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); + ruled_layer(&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}"); diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index ea3e3278321..f6e1351dad1 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -102,7 +102,7 @@ pub fn selective_from_params(p: &Value, base: Option<&Adjustment>) -> Result) -> Result None, + None | Some("auto") => None, Some("cube") => Some(photocraft_cms::lutfile::Format::Cube), Some("3dl") => Some(photocraft_cms::lutfile::Format::ThreeDl), Some("look") => Some(photocraft_cms::lutfile::Format::Look), - Some(_) => return Err(bad(CMD, "`lutFormat` must be \"cube\", \"3dl\" or \"look\"")), + Some(_) => return Err(bad(CMD, "`lutFormat` must be \"auto\", \"cube\", \"3dl\" or \"look\"")), }; // The parsed table, its label and (for a file) the file as loaded, which a PSD save embeds. let mut loaded: Option<(photocraft_cms::lutfile::LutFile, String, Option)> = None; @@ -139,8 +139,8 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result