mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge upstream main 609e2aa72 into curves follow-up
This commit is contained in:
commit
333566a616
535 files changed
+46228
-3491
No files matched your search
+3
-1
@@ -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) | <https://github.com/rsms/inter> | 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 | <https://github.com/JetBrains/JetBrainsMono> | 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 | <https://github.com/lucide-icons/lucide> (`icons/<name>.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 | <https://github.com/lucide-icons/lucide> (`icons/<name>.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 | <https://github.com/feathericons/feather> 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 |
|
||||
|
||||
Generated
+16
-28
@@ -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"
|
||||
|
||||
+10
-10
@@ -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" }
|
||||
@@ -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 }
|
||||
|
||||
@@ -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<String>,
|
||||
/// 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<Cli, clap::Error> {
|
||||
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))
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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<Value> = 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]
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -254,7 +254,7 @@ impl Backend for MacMenu {
|
||||
pub fn install(ctx: &egui::Context, app: &photocraft_ui_egui::PhotocraftApp) -> Option<native_menu::NativeMenu> {
|
||||
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);
|
||||
|
||||
@@ -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<photocraft_automation::AuthorizedWorkspace>) ->
|
||||
let clip_unreadable: Rc<Cell<bool>> = 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<photocraft_automation::AuthorizedWorkspace>) ->
|
||||
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]| {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<Result<String, String>> {
|
||||
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)?;
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<rect width="18" height="18" x="3" y="3" rx="2" />
|
||||
<path d="M9 3v18" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 284 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<rect x="3" y="10" width="18" height="7" rx="2" />
|
||||
<path d="M8 12v3M16 12v3" />
|
||||
<circle cx="12" cy="13.5" r="1.1" />
|
||||
<path d="M8.5 8.4q3.5-2.6 7 0" stroke-dasharray="0.6 1.6" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 394 B |
@@ -0,0 +1,17 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Type options-bar glyph for vertical text (not from an icon set). -->
|
||||
<path d="M3 20h18" />
|
||||
<path d="M17 4v12" />
|
||||
<path d="M12 10v6" />
|
||||
<path d="M7 7v9" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 395 B |
@@ -0,0 +1,17 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Type options-bar glyph for vertical text (not from an icon set). -->
|
||||
<path d="M3 12h18" />
|
||||
<path d="M17 6v12" />
|
||||
<path d="M12 9v6" />
|
||||
<path d="M7 7v10" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 395 B |
@@ -0,0 +1,17 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<!-- PhotoCraft's own Type options-bar glyph for vertical text (not from an icon set). -->
|
||||
<path d="M3 4h18" />
|
||||
<path d="M17 8v12" />
|
||||
<path d="M12 8v6" />
|
||||
<path d="M7 8v9" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 393 B |
@@ -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
|
||||
@@ -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<Surface> {
|
||||
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<f32> {
|
||||
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;
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
-3
@@ -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<f32> {
|
||||
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;
|
||||
|
||||
+182
-19
@@ -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<f32>,
|
||||
/// Where the brush stroke in progress stands, so dab spacing runs on across its segments.
|
||||
cursor: Option<StrokeCursor>,
|
||||
/// 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<LiveTail>,
|
||||
}
|
||||
|
||||
/// 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<f64>)> =
|
||||
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));
|
||||
|
||||
@@ -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<Vec<f64>> {
|
||||
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");
|
||||
}
|
||||
+103
-50
@@ -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<Region> {
|
||||
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<Region> {
|
||||
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<Region> {
|
||||
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<f32> {
|
||||
@@ -780,10 +830,13 @@ pub fn tone_range(px: &[[f32; 4]], lo: f32, hi: f32, falloff: f32) -> Vec<f32> {
|
||||
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;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<PathBuf>,
|
||||
/// 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<PathBuf>,
|
||||
/// 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<PathBuf>,
|
||||
}
|
||||
|
||||
fn root_path() -> impl TypedValueParser<Value = PathBuf> {
|
||||
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, AutomationError> {
|
||||
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)]);
|
||||
}
|
||||
}
|
||||
@@ -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<Value, AutomationError> {
|
||||
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() {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<String>,
|
||||
/// Format override as an extension (pcraft, psd, png, jpg, tif, webp, exr, …).
|
||||
|
||||
@@ -33,7 +33,7 @@ struct RootCapability {
|
||||
/// before I/O.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct AuthorizedWorkspace {
|
||||
read: Option<RootCapability>,
|
||||
read: Vec<RootCapability>,
|
||||
write: Option<RootCapability>,
|
||||
}
|
||||
|
||||
@@ -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<Self, AutomationError> {
|
||||
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<Item = &'a Path>, write_root: Option<&Path>) -> Result<Self, AutomationError> {
|
||||
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<Vec<u8>, 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<u8>, Option<String>), 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<Option<photocraft_doc::Document>, 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<Option<RootCapability>, AutomationError> {
|
||||
let Some(path) = path else { return Ok(None) };
|
||||
fn open_root(path: &Path, authority: &str, opened: &[RootCapability]) -> Result<RootCapability, AutomationError> {
|
||||
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<Option<RootCapabili
|
||||
} else {
|
||||
std::path::absolute(path).map_err(|e| AutomationError::Io(format!("cannot resolve automation {authority} root `{}`: {e}", path.display())))?
|
||||
};
|
||||
// Reuse the held handle for the same launch spelling, not a second open of it: a root
|
||||
// symlink could otherwise change between the two opens. Only a shared handle lets an
|
||||
// implicit save write where the bytes were read (`read_with_save_path`); aliases do not.
|
||||
if let Some(root) = opened.iter().find(|root| root.configured_path == configured_path) {
|
||||
return Ok(root.clone());
|
||||
}
|
||||
// Resolve trusted configuration once, before opening that exact directory as a capability.
|
||||
let absolute =
|
||||
std::fs::canonicalize(path).map_err(|e| AutomationError::Io(format!("cannot resolve automation {authority} root `{}`: {e}", path.display())))?;
|
||||
let dir = Dir::open_ambient_dir(&absolute, ambient_authority())
|
||||
.map_err(|e| AutomationError::Io(format!("cannot open automation {authority} root `{}`: {e}", path.display())))?;
|
||||
Ok(Some(RootCapability { dir: Arc::new(dir), path: absolute, configured_path }))
|
||||
Ok(RootCapability { dir: Arc::new(dir), path: absolute, configured_path })
|
||||
}
|
||||
|
||||
/// Both root spellings refer to the capability opened at startup. Do not resolve an untrusted
|
||||
/// absolute request using ambient filesystem access: strip a known root first and let cap-std
|
||||
/// resolve the remaining name. New targets and nested export directories need not exist yet.
|
||||
fn request_path(raw: &str, root: Option<&RootCapability>) -> Result<PathBuf, AutomationError> {
|
||||
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<Option<PathBuf>, 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::<Result<Vec<_>, _>>()?;
|
||||
relative_path(&rest.join("/"))
|
||||
relative_path(&rest.join("/")).map(Some)
|
||||
}
|
||||
|
||||
/// Strip a granted root prefix without resolving the client path with ambient authority.
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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;
|
||||
@@ -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));
|
||||
|
||||
@@ -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<u8>, Vec<u8>) {
|
||||
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<u8> {
|
||||
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<u8>) {
|
||||
(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);
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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<Effect>| {
|
||||
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<Effect>| {
|
||||
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);
|
||||
}
|
||||
+176
-17
@@ -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<Rect> {
|
||||
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<Rect> {
|
||||
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<Rect> {
|
||||
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<Rect> {
|
||||
/// 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<Rect> {
|
||||
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<Rect> {
|
||||
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<Rect> {
|
||||
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<Rect> {
|
||||
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<Placement<'_>> {
|
||||
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<Rect> {
|
||||
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
|
||||
|
||||
@@ -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};
|
||||
|
||||
+225
-11
@@ -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<usize>) -> 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]
|
||||
|
||||
+21
-1
@@ -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<f32>,
|
||||
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::<super::TextShape>(value).unwrap(), shape);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
use crate::TextLayer;
|
||||
|
||||
|
||||
@@ -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<f32> = 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:?}");
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<String>) -> 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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
// 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<CommandSpec> {
|
||||
(
|
||||
"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<CommandSpec> {
|
||||
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());
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -102,7 +102,7 @@ pub fn selective_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adj
|
||||
|
||||
/// Color Lookup from params: `"lut"` (a built-in look id or `"none"`), `"file"` (a .cube / .3dl /
|
||||
/// .look path, native only) or `"data"` (file text, or base64 with `"dataEncoding":"base64"`).
|
||||
/// `"lutFormat":"cube|3dl|look"` can supply the format when the file name doesn't identify it.
|
||||
/// `"lutFormat":"cube|3dl|look"` (`"auto"`: detect) can supply the format when the file name doesn't identify it.
|
||||
/// `"interpolation":"trilinear|tetrahedral"`, `"dither":bool`. The table is embedded in the
|
||||
/// layer, as Photoshop does. Unspecified fields keep `base`'s values; a key of the wrong type is an
|
||||
/// error.
|
||||
@@ -119,11 +119,11 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjust
|
||||
return Err(bad(CMD, "`dataEncoding` must be \"text\" or \"base64\""));
|
||||
}
|
||||
let format = match opt_str(CMD, p, "lutFormat")? {
|
||||
None => 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<LutSource>)> = None;
|
||||
@@ -139,8 +139,8 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjust
|
||||
loaded = Some((f, label, None));
|
||||
}
|
||||
}
|
||||
let file_name = opt_str(CMD, p, "fileName")?;
|
||||
if let Some(text) = opt_str(CMD, p, "data")? {
|
||||
let file_name = opt_str(CMD, p, "fileName")?.filter(|s| !s.is_empty());
|
||||
if let Some(text) = opt_str(CMD, p, "data")?.filter(|s| !s.is_empty()) {
|
||||
let file_name = file_name.unwrap_or("lut.cube");
|
||||
let bytes = if encoding == "base64" {
|
||||
photocraft_paint::tile::b64_decode(text).ok_or_else(|| bad(CMD, "`data` is not valid base64"))?
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
//! values the luminosity (0.30 R + 0.59 G + 0.11 B) of the composite in the document's value
|
||||
//! range (0–255 at 8 bits, 0–32768 at 16 bits, 0–1 at 32 bits), integrated density area × mean.
|
||||
//! Lengths and areas are scaled by the measurement scale.
|
||||
//!
|
||||
//! Straighten Layer is offered where the reference application offers it: the ruler line is needed,
|
||||
//! and the target must be a single layer that is not the Background, not a group and not locked in
|
||||
//! place ([`straighten_disabled`], #12033). A hidden target layer keeps the button and is refused
|
||||
//! with [`STRAIGHTEN_HIDDEN_ERROR`] before anything changes.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -138,6 +143,60 @@ fn has_ruler(s: &Session) -> std::result::Result<(), String> {
|
||||
s.active().and_then(|d| d.doc.measurement.ruler).map(|_| ()).ok_or_else(|| "no ruler line".into())
|
||||
}
|
||||
|
||||
/// The reference's alert for Straighten Layer on a hidden target layer (#12033), measured: one
|
||||
/// alert window with an OK button, and the document and its History stay as they were. The button
|
||||
/// is *enabled* for a hidden layer, so this is the command's refusal and not a greyed state; the
|
||||
/// options bar shows the same text through `tl!` (English is the catalog source).
|
||||
pub const STRAIGHTEN_HIDDEN_ERROR: &str = "Could not straighten the layer because the target layer is hidden.";
|
||||
|
||||
/// The enabled check of `image.analysis.straightenLayer`: a ruler line, and a target the reference
|
||||
/// straightens ([`straighten_disabled`], #12033).
|
||||
fn has_straightenable_layer(s: &Session) -> std::result::Result<(), String> {
|
||||
has_ruler(s)?;
|
||||
straighten_disabled(s).map_or(Ok(()), |why| Err(why.into()))
|
||||
}
|
||||
|
||||
/// Why Straighten Layer is greyed out for the current target, `None` when its button is live
|
||||
/// (#12033). Measured with a ruler line drawn: the Background, two or more selected layers, a
|
||||
/// group, a layer with Lock All and a layer with Lock Position all grey it out.
|
||||
///
|
||||
/// Deliberately not here: a hidden target layer keeps the button enabled and is refused by
|
||||
/// [`straighten`] with [`STRAIGHTEN_HIDDEN_ERROR`], and the states the ticket marks *not measured*
|
||||
/// (a layer with a mask, a shape, vector or adjustment layer, artboards, and the lock kinds other
|
||||
/// than Lock All and Lock Position) keep today's behaviour. A document with no active layer keeps
|
||||
/// turning the whole canvas as it does now; an active id the document no longer holds is refused.
|
||||
fn straighten_disabled(s: &Session) -> Option<&'static str> {
|
||||
let st = s.active()?;
|
||||
if st.selected_layers().len() > 1 {
|
||||
return Some("several layers selected");
|
||||
}
|
||||
// The active layer is the one the Layers panel targets; with none, the command turns the
|
||||
// canvas, which the reference was not measured for.
|
||||
let id = st.active_layer?;
|
||||
// An id the document no longer holds: `Session::edit` keeps the *selected* layers valid but
|
||||
// not the active one, so an edit that drops the active layer can leave a stale id behind.
|
||||
// Turning and cropping the whole canvas for a layer that is not there is the worse answer, and
|
||||
// `select_layer` and `restore_layer_selection` both refuse such an id.
|
||||
let Some(layer) = st.doc.layer(id) else {
|
||||
return Some("no active layer");
|
||||
};
|
||||
if st.doc.is_background(id) {
|
||||
return Some("the Background");
|
||||
}
|
||||
if layer.is_group() {
|
||||
return Some("a group");
|
||||
}
|
||||
// Locks inherited from a group count, as they do for the Move tool.
|
||||
let locks = st.doc.effective_locks(id);
|
||||
if locks.all {
|
||||
return Some("the layer is locked");
|
||||
}
|
||||
if locks.position {
|
||||
return Some("the layer's position is locked");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn has_log(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.analysis.log.is_empty() { Err("the Measurement Log is empty".into()) } else { Ok(()) }
|
||||
}
|
||||
@@ -207,7 +266,7 @@ pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
|
||||
Ok(v)
|
||||
}
|
||||
Err(e) => {
|
||||
st.doc = before;
|
||||
let failed = std::mem::replace(&mut st.doc, before);
|
||||
st.active_layer = prior.active;
|
||||
st.selected_layers = prior.selected;
|
||||
st.layer_anchor = anchor;
|
||||
@@ -220,7 +279,9 @@ pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
|
||||
if was_clean {
|
||||
st.saved_revision = st.revision;
|
||||
}
|
||||
st.last_damage = None;
|
||||
// This revision's damage; `Session::dispatch` reports the command's whole span (nothing,
|
||||
// when the inner commands had changed pixels and the restore took them back).
|
||||
st.last_damage = crate::layer_multi_cmds::step_damage(&failed, &st.doc);
|
||||
Err(e)
|
||||
}
|
||||
};
|
||||
@@ -718,6 +779,12 @@ pub fn straighten_angle(r: &Ruler) -> f64 {
|
||||
fn straighten(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = doc(s)?;
|
||||
let r = d.measurement.ruler.ok_or_else(|| EngineError::Other("no ruler line".into()))?;
|
||||
// A hidden target layer keeps its button and gets this alert instead of a rotation (#12033).
|
||||
// Asked before anything is read for the edit, so the document, its History and the ruler line
|
||||
// stay exactly as they were; a layer inside a hidden group is hidden too (#571).
|
||||
if s.active().and_then(|st| st.active_layer).is_some_and(|id| d.path_of(id).is_some_and(|path| !d.shown_at(&path))) {
|
||||
return Err(EngineError::Other(STRAIGHTEN_HIDDEN_ERROR.into()));
|
||||
}
|
||||
let rot = straighten_angle(&r);
|
||||
if rot.abs() < 1e-9 {
|
||||
return Ok(json!({"angle": 0.0}));
|
||||
@@ -796,7 +863,7 @@ fn count_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if gi.is_some_and(|i| i >= group_count) {
|
||||
return Err(bad("count.add", "no such group"));
|
||||
}
|
||||
let n = s.edit("Count", |d, _| {
|
||||
let n = s.edit("Add Count Object", |d, _| {
|
||||
if d.measurement.count_groups.is_empty() {
|
||||
let g = new_group(d, None, None);
|
||||
d.measurement.count_groups.push(g);
|
||||
@@ -846,7 +913,7 @@ fn locate(s: &Session, p: &Value, cmd: &str) -> Result<(usize, usize)> {
|
||||
|
||||
fn count_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (g, i) = locate(s, p, "count.remove")?;
|
||||
s.edit("Count", |d, _| {
|
||||
s.edit("Delete Count Object", |d, _| {
|
||||
d.measurement.count_groups[g].points.remove(i);
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -856,7 +923,7 @@ fn count_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn count_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let to = point(p.get("to")).ok_or_else(|| bad("count.move", "pass `to`: [x, y]"))?;
|
||||
let (g, i) = locate(s, p, "count.move")?;
|
||||
s.edit("Count", |d, _| {
|
||||
s.edit("Drag Count Object", |d, _| {
|
||||
d.measurement.count_groups[g].points[i] = to;
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -881,7 +948,7 @@ fn count_clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn count_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
|
||||
let color = color_of("count.newGroup", p, "color")?;
|
||||
s.edit("New Count Group", |d, _| {
|
||||
s.edit("Add Count Group", |d, _| {
|
||||
let g = new_group(d, name, color);
|
||||
d.measurement.count_groups.push(g);
|
||||
d.measurement.active_count_group = d.measurement.count_groups.len() - 1;
|
||||
@@ -949,8 +1016,24 @@ fn count_set_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let activate = p.get("active").and_then(Value::as_bool) == Some(true) || p.as_object().is_some_and(|o| o.len() == 1 && o.contains_key("group"));
|
||||
let changed = grp != d.measurement.count_groups[g];
|
||||
if changed || (activate && d.measurement.active_count_group != g) {
|
||||
s.edit("Count Group Options", |d, _| {
|
||||
let switches = activate && d.measurement.active_count_group != g;
|
||||
if changed || switches {
|
||||
// One field changed: Photoshop's name for it (#11763). Several fields, or a switch of the
|
||||
// current group (not measured), keep "Count Group Options".
|
||||
let old = &d.measurement.count_groups[g];
|
||||
let fields = [
|
||||
(grp.name != old.name, "Set Count Group Name"),
|
||||
(grp.visible != old.visible, "Set Count Group Visibility"),
|
||||
(grp.color != old.color, "Set Count Draw Color"),
|
||||
(grp.marker_size != old.marker_size, "Set Count Marker Size"),
|
||||
(grp.label_size != old.label_size, "Set Count Font Size"),
|
||||
];
|
||||
let mut one = fields.iter().filter(|(c, _)| *c).map(|(_, l)| *l);
|
||||
let label = match (one.next(), one.next()) {
|
||||
(Some(l), None) if !switches => l,
|
||||
_ => "Count Group Options",
|
||||
};
|
||||
s.edit(label, |d, _| {
|
||||
d.measurement.count_groups[g] = grp;
|
||||
if activate {
|
||||
d.measurement.active_count_group = g;
|
||||
@@ -1018,7 +1101,9 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
other => return Err(bad(CMD, format!("unknown source `{other}` (auto|selection|ruler|count)"))),
|
||||
};
|
||||
// Numbered only once the rows exist, so a failed measurement does not use up a label.
|
||||
let label = format!("Measurement {}", s.analysis.next_measurement + 1);
|
||||
// A count's row is "Count N" (#11775); the number is the shared one.
|
||||
let word = if source == "count" { "Count" } else { "Measurement" };
|
||||
let label = format!("{word} {}", s.analysis.next_measurement + 1);
|
||||
let now = p.get("dateTime").and_then(Value::as_str).map(str::to_string).unwrap_or_else(now_iso);
|
||||
let factor = d.measurement.scale.factor();
|
||||
let mut rows: Vec<Map<String, Value>> = Vec::new();
|
||||
@@ -1297,8 +1382,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"image.analysis.straightenLayer",
|
||||
"Straighten Layer",
|
||||
[],
|
||||
r##"{"crop":bool=(active layer is the Background)} (rotates so the ruler line is level; crop = rotate the canvas and crop to the image)"##,
|
||||
has_ruler,
|
||||
r##"{"crop":bool=(active layer is the Background)} (rotates so the ruler line is level; crop = rotate the canvas and crop to the image; off for the Background, two or more selected layers, a group, Lock All and Lock Position, and a hidden target layer answers "Could not straighten the layer because the target layer is hidden." with nothing changed (#12033))"##,
|
||||
has_straightenable_layer,
|
||||
straighten,
|
||||
true
|
||||
),
|
||||
@@ -1332,5 +1417,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "analysis_straighten_enabled_tests.rs"]
|
||||
mod analysis_straighten_enabled_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -231,10 +231,13 @@ fn straighten_layer_and_image() {
|
||||
assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one history step");
|
||||
assert_eq!(d(&s).size.width, 80);
|
||||
assert!(d(&s).measurement.ruler.is_none());
|
||||
// The Background: rotate the canvas and crop to the image.
|
||||
// The Background used to rotate the canvas and crop it to the image; #12033 greys that state
|
||||
// out, so the same crop now happens on a layer and only when it is asked for.
|
||||
let mut s = session(80, 60, 16);
|
||||
s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [40, 40]})).unwrap();
|
||||
let r = s.execute("image.analysis.straightenLayer", json!({})).unwrap();
|
||||
assert!(!s.is_enabled("image.analysis.straightenLayer"), "the Background is greyed out (#12033)");
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
let r = s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap();
|
||||
assert_eq!(r["cropped"], true);
|
||||
assert_eq!(r["angle"].as_f64().unwrap().abs(), 45.0);
|
||||
let nd = d(&s);
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
//! Straighten Layer's enabled states and its hidden-layer refusal, measured against the reference
|
||||
//! application (#12033).
|
||||
//!
|
||||
//! With a ruler line drawn the reference greys the button out for the Background, two or more
|
||||
//! selected layers, a group, a layer with Lock All and a layer with Lock Position. A hidden target
|
||||
//! layer keeps the button enabled: the click answers an alert ("Could not straighten the layer
|
||||
//! because the target layer is hidden.") and nothing changes. Pixel, text and smart object layers
|
||||
//! stay enabled and are rotated.
|
||||
//!
|
||||
//! A layer with a mask, a shape or vector layer, an adjustment layer, artboards and the other lock
|
||||
//! kinds are *not measured* there: they keep today's behaviour, so the tests below only pin that
|
||||
//! the new check does not reach them.
|
||||
|
||||
use photocraft_doc::LayerId;
|
||||
|
||||
use super::*;
|
||||
|
||||
const CMD: &str = "image.analysis.straightenLayer";
|
||||
|
||||
/// A white document with a Background, as File > New makes one.
|
||||
fn session(w: u32, h: u32) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The same document in CMYK at 16 bits, which the reference also straightens.
|
||||
fn cmyk_16(w: u32, h: u32) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": w, "height": h, "mode": "cmyk", "depth": 16, "background": "white"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// A ruler line to straighten by: without one the command is off for every target.
|
||||
fn rule(s: &mut Session) {
|
||||
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
|
||||
}
|
||||
|
||||
/// A block of opaque pixels on the layer: an empty layer has nothing to transform, which would
|
||||
/// hide the state under test behind "nothing to transform". The colour has the layer's own channel
|
||||
/// count, so it works for RGB, Grayscale and CMYK at 8 and 16 bits alike.
|
||||
fn paint(s: &mut Session, l: LayerId) {
|
||||
s.edit("paint", |doc, _| {
|
||||
let surf = doc.layer_mut(l).unwrap().surface_mut().unwrap();
|
||||
let mut px = vec![0.0; surf.channels()];
|
||||
if let Some(first) = px.first_mut() {
|
||||
*first = 1.0;
|
||||
}
|
||||
if let Some(last) = px.last_mut() {
|
||||
*last = 1.0;
|
||||
}
|
||||
surf.fill_rect(Rect::new(10, 10, 50, 20), &px);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// A new pixel layer with something on it, which `layer.new.layer` makes the active one.
|
||||
fn pixel_layer(s: &mut Session, name: &str) -> LayerId {
|
||||
let l = LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap());
|
||||
paint(s, l);
|
||||
l
|
||||
}
|
||||
|
||||
/// A type layer over the canvas.
|
||||
fn text_layer(s: &mut Session) -> LayerId {
|
||||
LayerId(s.execute("type.create", json!({"x": 40, "y": 50, "text": "Hi", "size": 20})).unwrap()["layer"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A pixel layer turned into a smart object.
|
||||
fn smart_layer(s: &mut Session) -> LayerId {
|
||||
let l = pixel_layer(s, "Smart");
|
||||
s.execute("layer.smartObjects.convertToSmartObject", json!({"layer": l.0})).unwrap();
|
||||
l
|
||||
}
|
||||
|
||||
fn doc_of(s: &Session) -> Arc<Document> {
|
||||
s.active().unwrap().doc.clone()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.past_len()
|
||||
}
|
||||
|
||||
/// A state the reference greys the button out for: the engine says the command is off, so the menu
|
||||
/// item and the options-bar button follow, and a call answered anyway (the CLI, the control channel,
|
||||
/// an action step) is refused as a disabled command rather than run. Nothing is touched: the
|
||||
/// document is the same `Arc`, no History step is added and the ruler line stays.
|
||||
fn assert_greyed(s: &mut Session, what: &str) {
|
||||
let (before, history) = (doc_of(s), steps(s));
|
||||
assert!(!s.is_enabled(CMD), "{what}: the button is greyed out");
|
||||
let e = s.execute(CMD, json!({})).unwrap_err();
|
||||
let disabled = matches!(&e, EngineError::Disabled(id, _) if id == CMD);
|
||||
assert!(disabled, "{what}: refused as a disabled command, got {e}");
|
||||
assert!(Arc::ptr_eq(&before, &doc_of(s)), "{what}: the document was not touched");
|
||||
assert_eq!(steps(s), history, "{what}: no History step");
|
||||
assert!(doc_of(s).measurement.ruler.is_some(), "{what}: the ruler line is still there");
|
||||
}
|
||||
|
||||
/// The angle the ruler line of [`rule`] straightens by.
|
||||
const ROT: f64 = 4.7636;
|
||||
|
||||
#[test]
|
||||
fn the_background_greys_straighten_layer_out() {
|
||||
// Today it rotates the canvas and crops it (800 x 600 becomes 500 x 375); the reference has no
|
||||
// button for it at all.
|
||||
let mut s = session(100, 80);
|
||||
assert!(doc_of(&s).is_background(s.active().unwrap().active_layer.unwrap()), "the Background is the target");
|
||||
rule(&mut s);
|
||||
assert_greyed(&mut s, "the Background");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_selected_layers_grey_straighten_layer_out() {
|
||||
let mut s = session(100, 80);
|
||||
let a = pixel_layer(&mut s, "One");
|
||||
let b = pixel_layer(&mut s, "Two");
|
||||
s.execute("layer.select", json!({"layer": a.0})).unwrap();
|
||||
s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
|
||||
assert_eq!(s.active().unwrap().selected_layers().len(), 2, "both selected");
|
||||
rule(&mut s);
|
||||
assert_greyed(&mut s, "two selected layers");
|
||||
// Back to one layer, the button is live again.
|
||||
s.execute("layer.select", json!({"layer": b.0})).unwrap();
|
||||
assert!(s.is_enabled(CMD), "one selected layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_greys_straighten_layer_out() {
|
||||
let mut s = session(100, 80);
|
||||
pixel_layer(&mut s, "Inner");
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
let g = s.active().unwrap().active_layer.unwrap();
|
||||
assert!(doc_of(&s).layer(g).unwrap().is_group(), "the new group is the target");
|
||||
rule(&mut s);
|
||||
assert_greyed(&mut s, "a group");
|
||||
// A layer inside the group is a layer, so the button is on for it.
|
||||
let inner = doc_of(&s).layer(g).unwrap().children().unwrap()[0].id;
|
||||
s.execute("layer.select", json!({"layer": inner.0})).unwrap();
|
||||
assert!(s.is_enabled(CMD), "a layer in a group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_all_and_lock_position_grey_straighten_layer_out() {
|
||||
// Measured: both grey the button. Today it is enabled and the command fails with
|
||||
// `layer "Colors" is locked`, which is what a greyed button cannot do any more.
|
||||
for key in ["all", "position"] {
|
||||
let mut s = session(100, 80);
|
||||
let l = pixel_layer(&mut s, "Colors");
|
||||
s.execute("layer.setProps", json!({"layer": l.0, "locks": {key: true}})).unwrap();
|
||||
rule(&mut s);
|
||||
assert_greyed(&mut s, &format!("Lock {}", if key == "all" { "All" } else { "Position" }));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_lock_kinds_are_not_reached_by_the_new_check() {
|
||||
// Not measured in the reference, so they keep today's behaviour: the button stays on and the
|
||||
// command answers as it does now.
|
||||
for key in ["transparency", "pixels", "artboard"] {
|
||||
let mut s = session(100, 80);
|
||||
let l = pixel_layer(&mut s, "Colors");
|
||||
s.execute("layer.setProps", json!({"layer": l.0, "locks": {key: true}})).unwrap();
|
||||
rule(&mut s);
|
||||
assert!(s.is_enabled(CMD), "Lock {key}: not measured, still enabled");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_layer_stays_enabled_and_is_refused_with_the_alert() {
|
||||
// The one measured refusal: the button is on, the click shows the alert and nothing changes.
|
||||
let mut s = session(100, 80);
|
||||
let l = pixel_layer(&mut s, "Gone");
|
||||
s.execute("layer.setProps", json!({"layer": l.0, "visible": false})).unwrap();
|
||||
rule(&mut s);
|
||||
let (before, history) = (doc_of(&s), steps(&s));
|
||||
assert!(s.is_enabled(CMD), "a hidden layer keeps the button on");
|
||||
let e = s.execute(CMD, json!({})).unwrap_err();
|
||||
assert_eq!(e.to_string(), STRAIGHTEN_HIDDEN_ERROR, "the reference's alert text");
|
||||
assert!(matches!(e, EngineError::Other(_)), "an alert, not a greyed state: {e}");
|
||||
assert!(Arc::ptr_eq(&before, &doc_of(&s)), "nothing changed");
|
||||
assert_eq!(steps(&s), history, "no History step");
|
||||
assert!(doc_of(&s).measurement.ruler.is_some(), "a straighten that never ran leaves the ruler line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_hidden_with_its_group_is_refused_the_same_way() {
|
||||
// A layer inside a hidden group is hidden, as for the painting tools (#571).
|
||||
let mut s = session(100, 80);
|
||||
let l = pixel_layer(&mut s, "Inner");
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
let g = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("layer.setProps", json!({"layer": g.0, "visible": false})).unwrap();
|
||||
s.execute("layer.select", json!({"layer": l.0})).unwrap();
|
||||
rule(&mut s);
|
||||
let (before, history) = (doc_of(&s), steps(&s));
|
||||
assert!(s.is_enabled(CMD), "the target is a layer, not the group");
|
||||
assert_eq!(s.execute(CMD, json!({})).unwrap_err().to_string(), STRAIGHTEN_HIDDEN_ERROR);
|
||||
assert!(Arc::ptr_eq(&before, &doc_of(&s)));
|
||||
assert_eq!(steps(&s), history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_ruler_line_the_button_stays_greyed_for_every_layer() {
|
||||
let mut s = session(100, 80);
|
||||
pixel_layer(&mut s, "Paint");
|
||||
assert!(!s.is_enabled(CMD), "no ruler line");
|
||||
s.execute("layer.setProps", json!({"layer": s.active().unwrap().active_layer.unwrap().0, "visible": false})).unwrap();
|
||||
assert!(!s.is_enabled(CMD), "a hidden layer without a ruler line stays greyed, not enabled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_active_layer_the_document_no_longer_holds_is_refused() {
|
||||
// `Session::edit` prunes the selected layers but not the active id, so an edit that drops the
|
||||
// active layer can leave one behind (`select_layer` and `restore_layer_selection` both refuse
|
||||
// such an id). The command must then say it is off, not rotate and crop the whole canvas for a
|
||||
// layer that is not there.
|
||||
let mut s = session(100, 80);
|
||||
let l = pixel_layer(&mut s, "Gone");
|
||||
s.edit("drop", |doc, _| {
|
||||
doc.layers.retain(|layer| layer.id != l);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(l), "the target still points at the dropped layer");
|
||||
assert!(doc_of(&s).layer(l).is_none(), "and the document does not hold it");
|
||||
rule(&mut s);
|
||||
assert_greyed(&mut s, "an active layer that is gone");
|
||||
// The destructive case this closes: `crop` asks for the canvas, which would turn and shrink for
|
||||
// a target that no longer exists.
|
||||
let size = (doc_of(&s).size.width, doc_of(&s).size.height);
|
||||
assert!(s.execute(CMD, json!({"crop": true})).is_err());
|
||||
assert_eq!((doc_of(&s).size.width, doc_of(&s).size.height), size, "the canvas kept its size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_visible_layer_still_rotates_without_cropping() {
|
||||
// The pin for the state that stays: the layer turns about the canvas centre, the canvas does not.
|
||||
let mut s = session(100, 80);
|
||||
pixel_layer(&mut s, "Paint");
|
||||
rule(&mut s);
|
||||
let (history, size) = (steps(&s), (doc_of(&s).size.width, doc_of(&s).size.height));
|
||||
assert!(s.is_enabled(CMD), "a layer is what the button is for");
|
||||
let r = s.execute(CMD, json!({})).unwrap();
|
||||
assert_eq!(r["cropped"], false, "{r}");
|
||||
assert!((r["angle"].as_f64().unwrap() - ROT).abs() < 1e-3, "{r}");
|
||||
assert_eq!((doc_of(&s).size.width, doc_of(&s).size.height), size, "the canvas keeps its size");
|
||||
assert_eq!(steps(&s), history + 1, "one History step");
|
||||
assert!(doc_of(&s).measurement.ruler.is_none(), "the ruler line is cleared");
|
||||
assert!(s.undo());
|
||||
assert_eq!((doc_of(&s).size.width, doc_of(&s).size.height), size, "and one Undo takes it back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_text_and_smart_object_layers_stay_enabled_and_rotate() {
|
||||
// Measured, also in a CMYK 16-bit document.
|
||||
type Maker = (&'static str, fn(&mut Session) -> LayerId);
|
||||
let make: [Maker; 3] = [("pixel", |s| pixel_layer(s, "Paint")), ("type", text_layer), ("smart object", smart_layer)];
|
||||
for (what, make_layer) in make {
|
||||
for new in [session as fn(u32, u32) -> Session, cmyk_16] {
|
||||
let mut s = new(100, 80);
|
||||
make_layer(&mut s);
|
||||
rule(&mut s);
|
||||
assert!(s.is_enabled(CMD), "{what}: enabled");
|
||||
let r = s.execute(CMD, json!({}));
|
||||
let r = r.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
assert_eq!(r["cropped"], false, "{what}: rotated, not cropped");
|
||||
assert!((r["angle"].as_f64().unwrap() - ROT).abs() < 1e-3, "{what}: {r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_crop_still_crops_for_automation() {
|
||||
// The `crop` param stays available to automation where the command is enabled.
|
||||
let mut s = session(100, 80);
|
||||
pixel_layer(&mut s, "Paint");
|
||||
rule(&mut s);
|
||||
let r = s.execute(CMD, json!({"crop": true})).unwrap();
|
||||
assert_eq!(r["cropped"], true, "{r}");
|
||||
let d = doc_of(&s);
|
||||
assert!(d.size.width < 100 && d.size.height < 80, "the canvas is rotated and cropped to {:?}", [d.size.width, d.size.height]);
|
||||
}
|
||||
@@ -152,9 +152,11 @@ fn xywh(r: Rect) -> [i64; 4] {
|
||||
/// it puts it right of the board, a [`GAP`] away, sliding further right past any board in the
|
||||
/// way. Moves the copy, layer `id` (just inserted on top of its original), there with its
|
||||
/// contents and grows the canvas to show it; anything that isn't an artboard is left alone.
|
||||
pub(crate) fn place_copy(doc: &mut Document, id: LayerId) -> Result<()> {
|
||||
/// Returns [`fit_canvas`]'s shift (a board already past the origin, as a PSD can hold, re-bases the
|
||||
/// document), for [`follow_shift`].
|
||||
pub(crate) fn place_copy(doc: &mut Document, id: LayerId) -> Result<(i32, i32)> {
|
||||
let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
let Some(r) = l.artboard().map(|a| a.rect) else { return Ok(()) };
|
||||
let Some(r) = l.artboard().map(|a| a.rect) else { return Ok((0, 0)) };
|
||||
let name = l.name.clone();
|
||||
let boards: Vec<Rect> = doc.artboards().iter().filter(|b| b.0 != id).map(|b| b.2.rect).collect();
|
||||
let (y0, y1, w) = (i64::from(r.y0), i64::from(r.y1), i64::from(r.width()));
|
||||
@@ -180,8 +182,7 @@ pub(crate) fn place_copy(doc: &mut Document, id: LayerId) -> Result<()> {
|
||||
let copy = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
crate::commands::translate_layer(&snapshot, copy, dx, 0);
|
||||
crate::vector_cmds::translate_vectors(&snapshot, copy, f64::from(dx), 0.0);
|
||||
fit_canvas(doc);
|
||||
Ok(())
|
||||
Ok(fit_canvas(doc))
|
||||
}
|
||||
|
||||
/// Record a Duplicate's `inPlace` only when a copy (the selection after it) is an artboard: for
|
||||
@@ -203,8 +204,11 @@ pub(crate) fn recorded_duplicate(s: &Session, mut p: Value) -> Value {
|
||||
/// contents, guides, paths…) right/down by its overhang, then the canvas grows to show it. An
|
||||
/// axis whose boards span more than the largest canvas, or a shift that would push pixels past
|
||||
/// the 32-bit range, stays unshifted: the board stays partly off-canvas, as one past the size
|
||||
/// limit does.
|
||||
pub(crate) fn fit_canvas(doc: &mut Document) {
|
||||
/// limit does. Returns the shift, for [`follow_shift`]: `translate_doc` moves the document's own
|
||||
/// geometry, but the session's Color Sampler points and painting symmetry stay behind unless the
|
||||
/// caller passes it on.
|
||||
#[must_use = "pass the shift to `follow_shift`, or the Color Samplers and symmetry stay behind (#9302)"]
|
||||
pub(crate) fn fit_canvas(doc: &mut Document) -> (i32, i32) {
|
||||
let max = i64::from(crate::document_preset_cmds::MAX_DIMENSION);
|
||||
let boards: Vec<Rect> = doc.artboards().iter().map(|b| b.2.rect).collect();
|
||||
// The canvas and every board, per axis (`lo` ≤ 0 is the canvas origin or a board past it).
|
||||
@@ -226,6 +230,20 @@ pub(crate) fn fit_canvas(doc: &mut Document) {
|
||||
// shapes against it, leaving them missing or clipped (#2389).
|
||||
crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes);
|
||||
}
|
||||
(sx, sy)
|
||||
}
|
||||
|
||||
/// Keep the Color Sampler points and the painting symmetry on their pixels after an edit shifted
|
||||
/// the document by `(dx, dy)` to show a board past the origin ([`fit_canvas`]), as Canvas Size's
|
||||
/// sampler map does (#9302). View state: no history step. The canvas only grew, so every point
|
||||
/// stays on it.
|
||||
pub(crate) fn follow_shift(s: &mut Session, (dx, dy): (i32, i32)) {
|
||||
let Some(st) = s.active_mut().filter(|_| (dx, dy) != (0, 0)) else { return };
|
||||
for p in &mut st.color_samplers {
|
||||
*p = [p[0] + f64::from(dx), p[1] + f64::from(dy)];
|
||||
}
|
||||
let a = photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy));
|
||||
st.symmetry = st.symmetry.take().and_then(|sym| sym.transform(&a));
|
||||
}
|
||||
|
||||
fn next_artboard_name(doc: &Document) -> String {
|
||||
@@ -294,7 +312,7 @@ fn new_artboard(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "`takeBackground` must be true or false"))?,
|
||||
};
|
||||
let id = s.edit("New Artboard", |doc, active| {
|
||||
let (id, shift) = s.edit("New Artboard", |doc, active| {
|
||||
let mut g = Layer::group(name.unwrap_or_else(|| next_artboard_name(doc)), vec![]);
|
||||
set_artboard(&mut g, Artboard { rect, background, preset });
|
||||
// Only the first board takes the Background in (decided before the board exists).
|
||||
@@ -303,10 +321,11 @@ fn new_artboard(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if take {
|
||||
move_background_into(doc, id);
|
||||
}
|
||||
fit_canvas(doc);
|
||||
let shift = fit_canvas(doc);
|
||||
*active = Some(id);
|
||||
Ok(id)
|
||||
Ok((id, shift))
|
||||
})?;
|
||||
follow_shift(s, shift);
|
||||
crate::layer_multi_cmds::set_selection(s, vec![id], Some(id), Some(id))?;
|
||||
Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
|
||||
}
|
||||
@@ -344,17 +363,18 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let canvas = d.doc.bounds();
|
||||
let background = if apply_background { background_param(p, cmd)?.unwrap_or_default() } else { ArtboardBackground::White };
|
||||
let rect = s.edit("Artboard from Group", |doc, active| {
|
||||
let (rect, shift) = s.edit("Artboard from Group", |doc, active| {
|
||||
if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) {
|
||||
return Err(EngineError::Other("artboards are made from a top-level layer group".into()));
|
||||
}
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
let rect = crate::layer_multi_cmds::layer_bounds(l).unwrap_or(canvas);
|
||||
set_artboard(l, Artboard { rect, background, preset });
|
||||
fit_canvas(doc);
|
||||
let shift = fit_canvas(doc);
|
||||
*active = Some(id);
|
||||
Ok(rect)
|
||||
Ok((rect, shift))
|
||||
})?;
|
||||
follow_shift(s, shift);
|
||||
crate::layer_multi_cmds::set_selection(s, vec![id], Some(id), Some(id))?;
|
||||
Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
|
||||
}
|
||||
@@ -388,7 +408,7 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps
|
||||
// their bounds on that axis (#9087).
|
||||
let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)];
|
||||
let (gid, rect) = s.edit("Artboard from Layers", |doc, active| {
|
||||
let (gid, rect, shift) = s.edit("Artboard from Layers", |doc, active| {
|
||||
let ids = crate::layer_multi_cmds::top_level(doc, &sel);
|
||||
if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) {
|
||||
return Err(EngineError::Other("select layers that are not in an artboard".into()));
|
||||
@@ -403,10 +423,11 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set_artboard(&mut g, Artboard { rect, background, preset: String::new() });
|
||||
let gid = doc.insert_above(None, g);
|
||||
crate::layer_multi_cmds::check_group_depth(doc, "Artboard from Layers")?;
|
||||
fit_canvas(doc);
|
||||
let shift = fit_canvas(doc);
|
||||
*active = Some(gid);
|
||||
Ok((gid, rect))
|
||||
Ok((gid, rect, shift))
|
||||
})?;
|
||||
follow_shift(s, shift);
|
||||
crate::layer_multi_cmds::set_selection(s, vec![gid], Some(gid), Some(gid))?;
|
||||
Ok(json!({"layer": gid.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
|
||||
}
|
||||
@@ -445,7 +466,7 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
));
|
||||
}
|
||||
};
|
||||
s.edit("Edit Artboard", |doc, _| {
|
||||
let shift = s.edit("Edit Artboard", |doc, _| {
|
||||
if move_contents && (dx, dy) != (0, 0) {
|
||||
let snapshot = doc.clone();
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
@@ -467,9 +488,9 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None if rect.width() != old.rect.width() || rect.height() != old.rect.height() => a.preset.clear(),
|
||||
None => {}
|
||||
}
|
||||
fit_canvas(doc);
|
||||
Ok(())
|
||||
Ok(fit_canvas(doc))
|
||||
})?;
|
||||
follow_shift(s, shift);
|
||||
Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
|
||||
}
|
||||
|
||||
@@ -546,7 +567,7 @@ fn add_beside(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let grown = |len: u32, by: i32| (i64::from(len) + i64::from(by)).clamp(1, 300_000) as u32;
|
||||
let label = if duplicate { "Duplicate Artboard" } else { "New Artboard" };
|
||||
let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true);
|
||||
let (nid, rect) = s.edit(label, |doc, active| {
|
||||
let (nid, rect, (fx, fy)) = s.edit(label, |doc, active| {
|
||||
if (sx, sy) != (0, 0) {
|
||||
crate::image_cmds::translate_doc(doc, cmd, sx, sy)?;
|
||||
doc.size = Size::new(grown(doc.size.width, sx), grown(doc.size.height, sy));
|
||||
@@ -575,10 +596,11 @@ fn add_beside(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set_artboard(&mut g, Artboard { rect, background: src.background, preset: src.preset.clone() });
|
||||
doc.insert_above(Some(id), g)
|
||||
};
|
||||
fit_canvas(doc);
|
||||
let fitted = fit_canvas(doc);
|
||||
*active = Some(nid);
|
||||
Ok((nid, rect))
|
||||
Ok((nid, rect, fitted))
|
||||
})?;
|
||||
follow_shift(s, (sx.saturating_add(fx), sy.saturating_add(fy)));
|
||||
crate::layer_multi_cmds::set_selection(s, vec![nid], Some(nid), Some(nid))?;
|
||||
Ok(json!({"layer": nid.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
|
||||
}
|
||||
|
||||
@@ -723,6 +723,92 @@ fn moving_an_artboard_left_of_or_above_the_origin_grows_the_canvas_there() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Moving or making a board past the canvas origin re-bases the document; the Color Sampler
|
||||
/// points and the painting symmetry shift with it and stay on the same pixels.
|
||||
#[test]
|
||||
fn a_board_past_the_origin_moves_the_color_samplers_and_symmetry_with_the_document() {
|
||||
// #9302: the re-based document moved everything but the Color Sampler points and the
|
||||
// painting symmetry, which then sat on other pixels. They follow, as with Canvas Size.
|
||||
let samplers = |s: &Session| s.active().unwrap().color_samplers.clone();
|
||||
let center = |s: &Session| s.active().unwrap().symmetry.as_ref().and_then(|y| y.preset()).map(|p| p.center);
|
||||
for (cmd, p) in [("layer.translate", json!({"dx": -60, "dy": -30})), ("layer.artboard.set", json!({"x": -50, "y": -20}))] {
|
||||
let mut s = session(8);
|
||||
let gid = board_with_square(&mut s);
|
||||
s.execute("view.colorSamplers.add", json!({"x": 15, "y": 15})).unwrap();
|
||||
s.execute("paint.setSymmetry", json!({"mode": "vertical", "center": [70.0, 20.0]})).unwrap();
|
||||
s.execute("layer.select", json!({"layer": gid.0})).unwrap();
|
||||
s.execute(cmd, p).unwrap();
|
||||
// The board lands at (0, 0) after the document shifted right 50 and down 20; the sampler
|
||||
// is pinned to the canvas, not the board, so it shifts with the document only. Sampler
|
||||
// points sit on pixel centres (#11725): one placed at 15, 15 is stored as 15.5, 15.5.
|
||||
assert_eq!(board_rect(&s, gid.0), Rect::new(0, 0, 40, 40), "{cmd}");
|
||||
assert_eq!(samplers(&s), vec![[65.5, 35.5]], "{cmd}");
|
||||
assert_eq!(center(&s), Some([120.0, 40.0]), "{cmd}: the symmetry stays on its pixels");
|
||||
}
|
||||
// A new board left of the canvas shifts the photo right by its overhang.
|
||||
let mut s = session(8);
|
||||
add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);
|
||||
s.execute("view.colorSamplers.add", json!({"x": 15, "y": 15})).unwrap();
|
||||
s.execute("layer.new.artboard", json!({"rect": [-200, 0, 100, 80]})).unwrap();
|
||||
assert_eq!(samplers(&s), vec![[215.5, 15.5]]);
|
||||
assert!(red_at(&s, 215, 15));
|
||||
// A board made from layers (or a group) left of the canvas shifts by their overhang.
|
||||
for cmd in ["layer.new.artboardFromLayers", "layer.new.artboardFromGroup"] {
|
||||
let mut s = session(8);
|
||||
add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);
|
||||
s.execute("view.colorSamplers.add", json!({"x": 15, "y": 15})).unwrap();
|
||||
add_square(&mut s, Rect::new(-30, 40, -10, 60), [0.0, 0.0, 1.0, 1.0]);
|
||||
if cmd.ends_with("Group") {
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
}
|
||||
s.execute(cmd, json!({})).unwrap();
|
||||
assert_eq!(samplers(&s), vec![[45.5, 15.5]], "{cmd}");
|
||||
assert!(red_at(&s, 45, 15), "{cmd}");
|
||||
}
|
||||
// The "+" button left of a board at the origin shifts by the board and the gap.
|
||||
let mut s = session(8);
|
||||
let gid = board_with_square(&mut s);
|
||||
s.execute("layer.artboard.set", json!({"x": 0, "y": 0})).unwrap();
|
||||
s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap();
|
||||
s.execute("layer.artboard.addBeside", json!({"layer": gid.0, "side": "left"})).unwrap();
|
||||
let by = 40 + GAP;
|
||||
assert_eq!(board_rect(&s, gid.0), Rect::new(by, 0, by + 40, 40));
|
||||
assert_eq!(samplers(&s), vec![[f64::from(by) + 5.5, 5.5]]);
|
||||
assert!(red_at(&s, by + 5, 5));
|
||||
// A board right of the canvas shifts nothing.
|
||||
s.execute("layer.artboard.addBeside", json!({"layer": gid.0, "side": "right"})).unwrap();
|
||||
assert_eq!(samplers(&s), vec![[f64::from(by) + 5.5, 5.5]]);
|
||||
}
|
||||
|
||||
/// Duplicating a board whose document has boards past the origin (one or several selected
|
||||
/// layers) re-bases it; the Color Sampler points shift with the document.
|
||||
#[test]
|
||||
fn duplicating_a_board_beside_one_past_the_origin_moves_the_color_samplers_with_the_document() {
|
||||
// #9302 review: Layer › Duplicate puts the copy right of its board, but `fit_canvas` still
|
||||
// re-bases a document whose boards were already past the origin (as a PSD can hold them).
|
||||
// Single (`layer`) and several selected layers (`duplicate_selected`) both follow the shift.
|
||||
for multi in [false, true] {
|
||||
let mut s = session(8);
|
||||
let gid = board_with_square(&mut s);
|
||||
s.edit("past the origin", |doc, _| {
|
||||
doc.layer_mut(gid).and_then(|l| l.artboard_mut()).unwrap().rect = Rect::new(-40, 10, 0, 50);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sq = add_square(&mut s, Rect::new(60, 10, 80, 30), [1.0, 0.0, 0.0, 1.0]);
|
||||
s.execute("view.colorSamplers.add", json!({"x": 65, "y": 15})).unwrap();
|
||||
if multi {
|
||||
crate::layer_multi_cmds::set_selection(&mut s, vec![gid, sq], Some(gid), Some(gid)).unwrap();
|
||||
s.execute("layer.duplicate", json!({})).unwrap();
|
||||
} else {
|
||||
s.execute("layer.duplicate", json!({"layer": gid.0})).unwrap();
|
||||
}
|
||||
assert_eq!(board_rect(&s, gid.0), Rect::new(0, 10, 40, 50), "multi {multi}: the document shifted right 40");
|
||||
assert_eq!(s.active().unwrap().color_samplers, vec![[105.5, 15.5]], "multi {multi}");
|
||||
assert!(red_at(&s, 105, 15), "multi {multi}: the sampler is still on the square");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_beside_places_a_board_on_each_side_and_alt_duplicates_contents() {
|
||||
// #3033: the Artboard tool's "+" buttons. Board 40×40 at (10, 10) holding a red square.
|
||||
|
||||
@@ -50,6 +50,7 @@ mod steps_layer;
|
||||
mod steps_layer_style;
|
||||
mod steps_lookup;
|
||||
mod steps_make;
|
||||
mod steps_measurement;
|
||||
mod steps_path;
|
||||
mod steps_perspective_warp;
|
||||
mod steps_type_path;
|
||||
@@ -187,6 +188,9 @@ mod layer_props_tests;
|
||||
#[cfg(test)]
|
||||
mod stylize_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod measurement_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod selection_tests;
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ use super::steps_artboard::{artboard_edit_from, artboard_edit_to, artboard_from,
|
||||
use super::steps_channels::{match_color_from, match_color_to, merge_spot_from, merge_spot_to, split_from, split_to, trap_from, trap_to};
|
||||
use super::steps_content_aware::{caf_from, caf_to};
|
||||
use super::steps_direct_adjustments::{gradient_from, gradient_to, replace_from, replace_to};
|
||||
use super::steps_distort::{PINCH, POLAR, SPHERIZE, TWIRL, ZIGZAG, keys_from, keys_to, shear_from, shear_to, wave_from, wave_to};
|
||||
use super::steps_distort::{PINCH, POLAR, SPHERIZE, TWIRL, ZIGZAG, displace_from, displace_to, keys_from, keys_to, shear_from, shear_to, wave_from, wave_to};
|
||||
use super::steps_doc::{
|
||||
align_from, align_to, canvas_size_from, canvas_size_to, close_from, close_to, conditional_from, conditional_to, convert_mode_from, convert_mode_to,
|
||||
crop_from, crop_to, export_from, export_to, image_size_from, image_size_to, merge_visible_from, merge_visible_to, open_from, open_to, paste_from, paste_to,
|
||||
@@ -568,6 +568,7 @@ pub(super) const EVENTS: &[Event] = &[
|
||||
&[F("Hrzn", "horizontal", Kind::Long), F("Vrtc", "vertical", Kind::Long), F("Fl ", "undefinedAreas", Kind::Enum("FlMd", OFFSET_FILL))]
|
||||
),
|
||||
// Distort (#10605): every key in recorded order, Photoshop's limits and defaults.
|
||||
Event { code: "", name: "displace", label: "Displace", ids: &["filter.distort.displace"], from: displace_from, to: displace_to },
|
||||
Event { code: "Shr ", name: "shear", label: "Shear", ids: &["filter.distort.shear"], from: shear_from, to: shear_to },
|
||||
Event {
|
||||
code: "Pnch",
|
||||
@@ -616,6 +617,9 @@ pub(super) const EVENTS: &[Event] = &[
|
||||
Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to },
|
||||
// What Photoshop needs in a written step (process version, the full settings set) is
|
||||
// unverified, so only an imported step saves back, as its recorded descriptor while unedited.
|
||||
// The label is interchange data, not a display name: Save Actions writes it into the step's
|
||||
// dictionary (convert.rs), so it stays Photoshop's wording and a loaded step round-trips. The
|
||||
// menu item and window title come from `lens_cmds` and read "RAW Develop Filter".
|
||||
Event { code: "", name: "Adobe Camera Raw Filter", label: "Camera Raw Filter", ids: &[crate::lens_cmds::RAW], from: camera_raw_from, to: camera_raw_to },
|
||||
// Video, Other, Average and matting (#10607).
|
||||
Event {
|
||||
@@ -893,6 +897,7 @@ pub(super) const EVENTS: &[Event] = &[
|
||||
name: "set",
|
||||
label: "Set",
|
||||
ids: &[
|
||||
super::steps_measurement::SET_SCALE,
|
||||
"select.all",
|
||||
"select.deselect",
|
||||
"select.reselect",
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! #10723: Image › Analysis › Set Measurement Scale › Custom steps, recorded as a Set of the
|
||||
//! document's `measurementScale` property (`docs/atn.md`, "Recorded through the menus").
|
||||
|
||||
use super::*;
|
||||
|
||||
const SET_SCALE: &str = "image.analysis.setMeasurementScale";
|
||||
const SOURCE: &str = "_atnMeasurementScaleDescriptor";
|
||||
|
||||
/// The `T ` object of the measured step, built here independently of the converter.
|
||||
fn scale(class: &str, pixels: i32, logical: f64, units: &str) -> Descriptor {
|
||||
Descriptor::new(class)
|
||||
.with("pixelLength", D::Integer(pixels))
|
||||
.with("logicalLength", D::Double(logical))
|
||||
.with("logicalUnits", D::Text(UnicodeString::new_nul(units)))
|
||||
}
|
||||
|
||||
/// The measured Set: `null` is the `measurementScale` property of the target document.
|
||||
fn recorded(t: Descriptor) -> Descriptor {
|
||||
let target = D::Reference(vec![
|
||||
ReferenceItem::Property { class: class("Prpr"), key: Id::new("measurementScale") },
|
||||
ReferenceItem::Enumerated { class: class("Dcmn"), type_id: Id::new("Ordn"), value: Id::new("Trgt") },
|
||||
]);
|
||||
Descriptor::new("null").with("null", target).with("T ", D::Descriptor(t))
|
||||
}
|
||||
|
||||
fn set_item(d: Descriptor) -> AtnItem {
|
||||
AtnItem { event: AtnEvent::Code(*b"setd"), dictionary: b"Set".to_vec(), descriptor: Some(d), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Load `items` as action "A" through `actions.load`.
|
||||
fn load(items: Vec<AtnItem>) -> (Session, Value) {
|
||||
let file = AtnFile {
|
||||
name: UnicodeString::new_nul("Analysis"),
|
||||
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&atn::write(&file).unwrap())})).unwrap();
|
||||
(s, r)
|
||||
}
|
||||
|
||||
/// Action "A" written by `actions.save` and parsed back.
|
||||
fn saved(s: &mut Session) -> Vec<AtnItem> {
|
||||
let r = s.execute("actions.save", json!({"action": "A"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([]), "{r}");
|
||||
atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap().actions.remove(0).items
|
||||
}
|
||||
|
||||
/// The recorded step loads as a custom scale and saves back byte for byte, whatever class its
|
||||
/// `T ` object was recorded with and in whatever key order.
|
||||
#[test]
|
||||
fn a_recorded_scale_step_loads_and_saves_back_unchanged() {
|
||||
let mut reordered = scale("measurementScale", 50, 2.5, "cm");
|
||||
reordered.items.reverse();
|
||||
for (t, pixels, logical, units) in
|
||||
[(scale("measurementScale", 120, 3.0, "mm"), 120, 3.0, "mm"), (scale("null", 100, 25.4, "inches"), 100, 25.4, "inches"), (reordered, 50, 2.5, "cm")]
|
||||
{
|
||||
let d = recorded(t);
|
||||
let (mut s, r) = load(vec![set_item(d.clone())]);
|
||||
assert_eq!(r["unsupported"], json!([]), "{r}");
|
||||
let (id, p) = &s.actions.list[0].steps[0];
|
||||
assert_eq!(id, SET_SCALE);
|
||||
assert_eq!(
|
||||
(&p["preset"], p["pixelLength"].as_f64(), p["logicalLength"].as_f64(), &p["units"]),
|
||||
(&json!("custom"), Some(f64::from(pixels)), Some(logical), &json!(units)),
|
||||
"{p}"
|
||||
);
|
||||
let back = saved(&mut s);
|
||||
assert_eq!((&back[0].event, back[0].descriptor.as_ref().map(Descriptor::to_bytes)), (&AtnEvent::Code(*b"setd"), Some(d.to_bytes())));
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded step sets the document's scale, as one undoable edit.
|
||||
#[test]
|
||||
fn a_loaded_scale_step_plays_and_undoes() {
|
||||
let (mut s, _) = load(vec![set_item(recorded(scale("measurementScale", 120, 3.0, "mm")))]);
|
||||
s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
|
||||
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
assert_eq!(played["ran"], 1, "{played}");
|
||||
let read = s.execute(SET_SCALE, json!({})).unwrap();
|
||||
assert_eq!(
|
||||
(&read["pixelLength"], &read["logicalLength"], &read["units"], &read["default"]),
|
||||
(&json!(120.0), &json!(3.0), &json!("mm"), &json!(false)),
|
||||
"{read}"
|
||||
);
|
||||
s.execute("history.undo", json!({})).unwrap();
|
||||
assert_eq!(s.execute(SET_SCALE, json!({})).unwrap()["default"], json!(true));
|
||||
}
|
||||
|
||||
/// The step PhotoCraft writes for a native custom scale is the measured form, with `T ` of
|
||||
/// class `measurementScale`, and it loads back without a stored descriptor.
|
||||
#[test]
|
||||
fn a_native_scale_saves_the_measured_form() {
|
||||
let p = json!({"preset": "custom", "pixelLength": 120, "logicalLength": 3, "units": "mm"});
|
||||
let d = export_item(SET_SCALE, &p, "S").and_then(|item| item.descriptor).unwrap();
|
||||
assert_eq!(d, recorded(scale("measurementScale", 120, 3.0, "mm")));
|
||||
let (s, _) = load(vec![set_item(d)]);
|
||||
assert_eq!(s.actions.list[0].steps[0].1, p);
|
||||
// `logicalUnits` is the command's other spelling of `units`, and the preset defaults to custom.
|
||||
let other = json!({"pixelLength": 120, "logicalLength": 3, "logicalUnits": "mm"});
|
||||
assert_eq!(export_item(SET_SCALE, &other, "S").and_then(|item| item.descriptor), Some(recorded(scale("measurementScale", 120, 3.0, "mm"))));
|
||||
}
|
||||
|
||||
/// A native step the event can't hold is refused: reading the scale, the default preset, a
|
||||
/// value left to the current scale, a fractional pixel length (the event stores a long), blank
|
||||
/// units, or another key.
|
||||
#[test]
|
||||
fn settings_the_event_cannot_hold_are_refused() {
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"preset": "default"}),
|
||||
json!({"preset": "query"}),
|
||||
json!({"preset": "custom", "pixelLength": 120, "logicalLength": 3}),
|
||||
json!({"preset": "custom", "logicalLength": 3, "units": "mm"}),
|
||||
json!({"preset": "custom", "pixelLength": 120.5, "logicalLength": 3, "units": "mm"}),
|
||||
json!({"preset": "custom", "pixelLength": 0, "logicalLength": 3, "units": "mm"}),
|
||||
json!({"preset": "custom", "pixelLength": 120, "logicalLength": -1, "units": "mm"}),
|
||||
json!({"preset": "custom", "pixelLength": 120, "logicalLength": 3, "units": " "}),
|
||||
json!({"preset": "custom", "pixelLength": 120, "logicalLength": 3, "units": "mm", "layer": 2}),
|
||||
] {
|
||||
assert!(export_item(SET_SCALE, &p, "S").is_none(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Any other form keeps the reference step: another target, a missing or extra key, values of
|
||||
/// another type, or values the native command refuses.
|
||||
#[test]
|
||||
fn other_forms_keep_the_photoshop_step() {
|
||||
let with = |key: &str, v: D| {
|
||||
let mut t = scale("measurementScale", 120, 3.0, "mm");
|
||||
if let Some(slot) = t.items.iter_mut().find(|(k, _)| k.is(key)) {
|
||||
slot.1 = v;
|
||||
}
|
||||
recorded(t)
|
||||
};
|
||||
let mut missing = scale("measurementScale", 120, 3.0, "mm");
|
||||
missing.items.pop();
|
||||
let mut layer_target = recorded(scale("measurementScale", 120, 3.0, "mm"));
|
||||
layer_target.items[0].1 = D::Reference(vec![
|
||||
ReferenceItem::Property { class: class("Prpr"), key: Id::new("measurementScale") },
|
||||
ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") },
|
||||
]);
|
||||
let forms = [
|
||||
recorded(missing),
|
||||
recorded(scale("measurementScale", 120, 3.0, "mm").with("Scl ", D::Double(1.0))),
|
||||
recorded(scale("measurementScale", 120, 3.0, "mm")).with("Rslt", D::Double(72.0)),
|
||||
layer_target,
|
||||
with("pixelLength", D::Double(120.0)),
|
||||
with("logicalLength", D::Integer(3)),
|
||||
with("logicalLength", D::Double(0.0)),
|
||||
with("pixelLength", D::Integer(-4)),
|
||||
with("logicalUnits", D::Text(UnicodeString::new_nul(" "))),
|
||||
with("logicalUnits", D::Integer(1)),
|
||||
];
|
||||
for d in forms {
|
||||
let (mut s, r) = load(vec![set_item(d.clone())]);
|
||||
assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}");
|
||||
assert_eq!(s.actions.list[0].steps[0].0, PHOTOSHOP_STEP, "{d:?}");
|
||||
assert_eq!(saved(&mut s)[0].descriptor.as_ref().map(Descriptor::to_bytes), Some(d.to_bytes()));
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded step whose scale was changed saves the new scale, not the stale recording; one whose
|
||||
/// recording is damaged still saves its settings.
|
||||
#[test]
|
||||
fn changed_or_damaged_steps_save_their_settings() {
|
||||
let (s, _) = load(vec![set_item(recorded(scale("null", 100, 25.4, "inches")))]);
|
||||
let mut p = s.actions.list[0].steps[0].1.clone();
|
||||
assert!(p.get(SOURCE).is_some(), "{p}");
|
||||
p["units"] = json!("cm");
|
||||
assert_eq!(export_item(SET_SCALE, &p, "S").and_then(|item| item.descriptor), Some(recorded(scale("measurementScale", 100, 25.4, "cm"))));
|
||||
p[SOURCE] = json!("not base64!");
|
||||
assert_eq!(export_item(SET_SCALE, &p, "S").and_then(|item| item.descriptor), Some(recorded(scale("measurementScale", 100, 25.4, "cm"))));
|
||||
}
|
||||
@@ -6,8 +6,8 @@ use super::{AtnEvent, AtnItem, EngineError, Result, Session, Value, bad, json};
|
||||
|
||||
/// Find a supported, unambiguous event for a menu step with no settings.
|
||||
fn menu_event(id: &str) -> Option<&'static Event> {
|
||||
// Camera Raw's ATN mapping requires a verified settings descriptor (#8714).
|
||||
if id == crate::lens_cmds::RAW || (id != "image.imageSize" && !id.starts_with("filter.")) {
|
||||
// Camera Raw (#8714) and recorded Displace require verified settings descriptors.
|
||||
if matches!(id, crate::lens_cmds::RAW | "filter.distort.displace") || (id != "image.imageSize" && !id.starts_with("filter.")) {
|
||||
return None;
|
||||
}
|
||||
EVENTS.iter().find(|e| {
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Photoshop's Distort filter steps (#10605): Pinch, Polar Coordinates, Shear, Spherize, Twirl, Wave and
|
||||
//! ZigZag, each key in recorded order with the limits and defaults Photoshop measures.
|
||||
//! Photoshop's Distort filter steps, with keys in recorded order and measured limits and defaults.
|
||||
|
||||
use super::descriptors::{desc, enm, num, trimmed};
|
||||
use super::descriptors::{code, desc, enm, jstr, num, path_text, path_value, trimmed};
|
||||
use super::events::pixel_target;
|
||||
use super::fields::{Mapped, step};
|
||||
use super::tables::{lookup, lookup_back};
|
||||
use super::{D, Descriptor, Map, Value, json};
|
||||
use super::{D, Descriptor, Id, Map, Value, json};
|
||||
|
||||
/// Whether every key of `d` is one of `keys` (codes compare without their space padding).
|
||||
fn only_keys(d: &Descriptor, keys: &[&str]) -> bool {
|
||||
@@ -39,6 +38,73 @@ fn enum_of(ty: &str) -> impl Fn(&D) -> Option<String> + '_ {
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the measured Windows Displace descriptor has a verified map path and settings.
|
||||
pub(super) fn displace_from(d: &Descriptor) -> Mapped {
|
||||
displace_params(d).map_or(Mapped::Unsupported { harmless: false }, |params| step("filter.distort.displace", params))
|
||||
}
|
||||
|
||||
/// Decode only the measured, byte-preserving Windows descriptor.
|
||||
fn displace_params(d: &Descriptor) -> Option<Value> {
|
||||
if d.class_id != code("null")
|
||||
|| d.items.len() != 5
|
||||
|| d.items.iter().any(|(key, _)| !matches!(key, Id::Code(_)))
|
||||
|| d.get("DspM") != Some(&enm("DspM", "StrF"))
|
||||
|| d.get("UndA") != Some(&enm("UndA", "RptE"))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let scale = |key| match d.get(key) {
|
||||
Some(D::Integer(value)) if (-999..=999).contains(value) => Some(*value),
|
||||
_ => None,
|
||||
};
|
||||
let horizontal = scale("HrzS")?;
|
||||
let vertical = scale("VrtS")?;
|
||||
let wire = d.get("DspF")?;
|
||||
let path = path_text(wire)?;
|
||||
// The shared decoder tolerates malformed lengths and UTF-16 for legacy callers. The
|
||||
// measured form must reproduce every byte, and an embedded NUL is never a file name.
|
||||
if path.contains('\0') || &path_value(&path) != wire {
|
||||
return None;
|
||||
}
|
||||
// An action file is shared like a document, and playback reads this path. Map only a path a
|
||||
// document may name: a local absolute file. Others stay kept steps, so playing a downloaded
|
||||
// set never opens a network share (which sends the user's credentials) or a device.
|
||||
crate::doc_path::resolve_in(&path, None).ok()?;
|
||||
Some(json!({"horizontal":horizontal,"vertical":vertical,"fit":"stretch","undefinedAreas":"repeat","mapPath":path}))
|
||||
}
|
||||
|
||||
/// Write the measured form with native defaults for omitted settings, without dropping
|
||||
/// settings the descriptor cannot represent.
|
||||
pub(super) fn displace_to(_: &str, p: &Value) -> Option<Descriptor> {
|
||||
if !pixel_target(p) || !sets_only(p, &["horizontal", "vertical", "fit", "undefinedAreas", "mapPath", "target"]) {
|
||||
return None;
|
||||
}
|
||||
if p.get("fit").is_some_and(|v| v.as_str() != Some("stretch")) || p.get("undefinedAreas").is_some_and(|v| v.as_str() != Some("repeat")) {
|
||||
return None;
|
||||
}
|
||||
let scale = |key| {
|
||||
let number = match p.get(key) {
|
||||
None => 10.0,
|
||||
Some(value) => value.as_f64()?,
|
||||
};
|
||||
let value = number as i32;
|
||||
((-999..=999).contains(&value) && f64::from(value) == number).then_some(D::Integer(value))
|
||||
};
|
||||
let path = jstr(p, "mapPath")?;
|
||||
// The header carries a u32 byte length, including its 12 bytes and the UTF-16 terminator.
|
||||
if path.is_empty() || path.contains('\0') || path.len() > ((u32::MAX - 14) / 2) as usize {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
desc("null")
|
||||
.with("HrzS", scale("horizontal")?)
|
||||
.with("VrtS", scale("vertical")?)
|
||||
.with("DspM", enm("DspM", "StrF"))
|
||||
.with("UndA", enm("UndA", "RptE"))
|
||||
.with("DspF", path_value(path)),
|
||||
)
|
||||
}
|
||||
|
||||
/// One key of a Distort filter's step, in recorded order.
|
||||
pub(super) enum Key {
|
||||
/// An integer clamped to `min..=max` on import, as Photoshop clamps it; `default` when the
|
||||
|
||||
@@ -1168,6 +1168,8 @@ pub(super) fn set_from(d: &Descriptor) -> Mapped {
|
||||
(Some("Chnl"), Target::Property(p)) if p == "fsel" => selection_from(d),
|
||||
// Quick Mask mode on (`set` of the document's quick-mask property); `clearEvent` turns it off.
|
||||
(Some("Prpr"), Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": true})),
|
||||
// Image › Analysis › Set Measurement Scale › Custom (#10723).
|
||||
(Some("Prpr"), Target::Property(p)) if p == "measurementScale" => super::steps_measurement::from(d),
|
||||
// Layer › New › Layer From Background (Photoshop records the New Layer dialog's values
|
||||
// as a `set` of the Background); values other than the defaults then apply to the layer.
|
||||
(Some("Lyr"), Target::Property(p)) if p == "Bckg" => background_from(d),
|
||||
@@ -1272,6 +1274,7 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
|
||||
let sel = |t: D| desc("null").with("null", fsel.clone()).with("T ", t);
|
||||
Some(match id {
|
||||
"path.set" => return super::steps_path::to(p),
|
||||
super::steps_measurement::SET_SCALE => return super::steps_measurement::to(p),
|
||||
"select.all" => sel(enm("Ordn", "Al ")),
|
||||
"select.deselect" => sel(enm("Ordn", "None")),
|
||||
"select.reselect" => sel(enm("Ordn", "Prvs")),
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Image › Analysis › Set Measurement Scale › Custom, recorded as a Set of the document's
|
||||
//! `measurementScale` property, as `docs/atn.md` ("Recorded through the menus") measures it:
|
||||
//! `T ` holds `pixelLength` (long), `logicalLength` (double) and `logicalUnits` (text) (#10723).
|
||||
|
||||
use super::descriptors::{class, desc, jstr, text};
|
||||
use super::fields::{Mapped, step};
|
||||
use super::{D, Descriptor, Id, ReferenceItem, Value, json};
|
||||
|
||||
/// The native command the step plays as.
|
||||
pub(super) const SET_SCALE: &str = "image.analysis.setMeasurementScale";
|
||||
/// The recorded descriptor, kept when it differs from the one [`to`] would write (the class
|
||||
/// of `T `, key order or ID encodings), so a load and save keeps the step unchanged.
|
||||
const SOURCE: &str = "_atnMeasurementScaleDescriptor";
|
||||
|
||||
/// The custom scale the step sets.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Scale {
|
||||
pixels: i32,
|
||||
logical: f64,
|
||||
units: String,
|
||||
}
|
||||
|
||||
/// `null`: the `measurementScale` property of the target document.
|
||||
fn target() -> D {
|
||||
D::Reference(vec![
|
||||
ReferenceItem::Property { class: class("Prpr"), key: Id::new("measurementScale") },
|
||||
ReferenceItem::Enumerated { class: class("Dcmn"), type_id: Id::new("Ordn"), value: Id::new("Trgt") },
|
||||
])
|
||||
}
|
||||
|
||||
/// Whether `d` has each of `keys` exactly once and nothing else.
|
||||
fn exactly(d: &Descriptor, keys: &[&str]) -> bool {
|
||||
d.items.len() == keys.len() && keys.iter().all(|key| d.items.iter().filter(|(k, _)| k.is(key)).count() == 1)
|
||||
}
|
||||
|
||||
/// The measured form only. A length the native command refuses (not above 0, not finite) or
|
||||
/// blank units keep the step as recorded, so playback can't fail on a step that loaded.
|
||||
fn recorded(d: &Descriptor) -> Option<Scale> {
|
||||
if !exactly(d, &["null", "T "]) || d.get("null")? != &target() {
|
||||
return None;
|
||||
}
|
||||
let D::Descriptor(t) = d.get("T ")? else { return None };
|
||||
if !exactly(t, &["pixelLength", "logicalLength", "logicalUnits"]) {
|
||||
return None;
|
||||
}
|
||||
let (D::Integer(pixels), D::Double(logical), D::Text(units)) = (t.get("pixelLength")?, t.get("logicalLength")?, t.get("logicalUnits")?) else {
|
||||
return None;
|
||||
};
|
||||
let units = String::from_utf16(units.0.strip_suffix(&[0]).unwrap_or(&units.0)).ok()?;
|
||||
(*pixels > 0 && logical.is_finite() && *logical > 0.0 && !units.trim().is_empty()).then_some(Scale { pixels: *pixels, logical: *logical, units })
|
||||
}
|
||||
|
||||
/// The descriptor a step recorded in PhotoCraft saves as; `T ` takes the property's class.
|
||||
fn canonical(scale: &Scale) -> Descriptor {
|
||||
let t = desc("measurementScale")
|
||||
.with("pixelLength", D::Integer(scale.pixels))
|
||||
.with("logicalLength", D::Double(scale.logical))
|
||||
.with("logicalUnits", text(&scale.units));
|
||||
desc("null").with("null", target()).with("T ", D::Descriptor(t))
|
||||
}
|
||||
|
||||
/// Map the measured form; any other stays a complete kept step.
|
||||
pub(super) fn from(d: &Descriptor) -> Mapped {
|
||||
let Some(scale) = recorded(d) else { return Mapped::Unsupported { harmless: false } };
|
||||
let mut p = json!({"preset": "custom", "pixelLength": scale.pixels, "logicalLength": scale.logical, "units": scale.units});
|
||||
if *d != canonical(&scale) {
|
||||
p[SOURCE] = photocraft_paint::tile::b64_encode(&d.to_bytes()).into();
|
||||
}
|
||||
step(SET_SCALE, p)
|
||||
}
|
||||
|
||||
/// A native step the event holds: a custom scale with all three values given, a whole pixel
|
||||
/// length (the event stores a long) and units that aren't blank. A step that reads the scale
|
||||
/// (no params), resets it to the default or leaves a value to the document's current scale
|
||||
/// refuses export: the event can't say any of those.
|
||||
fn native(p: &Value) -> Option<Scale> {
|
||||
let m = p.as_object()?;
|
||||
if m.keys().any(|key| !["preset", "pixelLength", "logicalLength", "units", "logicalUnits", SOURCE].contains(&key.as_str())) {
|
||||
return None;
|
||||
}
|
||||
if !matches!(m.get("preset"), None | Some(Value::Null)) && jstr(p, "preset") != Some("custom") {
|
||||
return None;
|
||||
}
|
||||
let pixels = m.get("pixelLength")?.as_f64().filter(|v| v.is_finite() && *v > 0.0 && v.fract() == 0.0 && *v <= f64::from(i32::MAX))?;
|
||||
let logical = m.get("logicalLength")?.as_f64().filter(|v| v.is_finite() && *v > 0.0)?;
|
||||
// The native command reads `units`, else `logicalUnits`.
|
||||
let units = m.get("units").or_else(|| m.get("logicalUnits")).and_then(Value::as_str).filter(|u| !u.trim().is_empty())?;
|
||||
Some(Scale { pixels: pixels as i32, logical, units: units.to_string() })
|
||||
}
|
||||
|
||||
/// Save the recorded descriptor while the step still sets the same scale, otherwise the
|
||||
/// canonical form of the step's settings.
|
||||
pub(super) fn to(p: &Value) -> Option<Descriptor> {
|
||||
let scale = native(p)?;
|
||||
let source = jstr(p, SOURCE)
|
||||
.and_then(photocraft_paint::tile::b64_decode)
|
||||
.and_then(|bytes| Descriptor::from_bytes(&bytes).ok())
|
||||
.filter(|d| recorded(d).as_ref() == Some(&scale));
|
||||
Some(source.unwrap_or_else(|| canonical(&scale)))
|
||||
}
|
||||
@@ -742,6 +742,7 @@ fn every_mapped_command_exports_and_imports_back() {
|
||||
("filter.other.offset", json!({"horizontal": 10, "vertical": -5, "undefinedAreas": "wrap"})),
|
||||
("filter.blur.blur", json!({})),
|
||||
("file.automate.createDroplet", json!({"path": "/d/Sharpen.pcdroplet", "action": "Sharpen", "set": "Tools", "output": "/d/out", "overrideOpen": true})),
|
||||
("filter.distort.displace", json!({"horizontal":-999,"vertical":999,"fit":"stretch","undefinedAreas":"repeat","mapPath":LOCAL_MAP})),
|
||||
("filter.distort.shear", json!({"points": [[0,0], [0.5,0.25], [1,0]], "undefinedAreas": "repeat"})),
|
||||
("filter.distort.pinch", json!({"amount": -30})),
|
||||
("filter.distort.polarCoordinates", json!({"mode": "polarToRectangular"})),
|
||||
@@ -858,6 +859,7 @@ fn every_mapped_command_exports_and_imports_back() {
|
||||
("type.loadDefaultTypeStyles", json!({})),
|
||||
("type.saveDefaultTypeStyles", json!({})),
|
||||
("image.analysis.recordMeasurements", json!({})),
|
||||
("image.analysis.setMeasurementScale", json!({"preset": "custom", "pixelLength": 120, "logicalLength": 2.5, "units": "mm"})),
|
||||
("layer.videoLayers.insertBlankFrame", json!({})),
|
||||
("layer.videoLayers.duplicateFrame", json!({})),
|
||||
("layer.videoLayers.deleteFrame", json!({})),
|
||||
@@ -3832,13 +3834,16 @@ fn loaded_camera_raw_filter_steps_save_back_unchanged() {
|
||||
assert_eq!(s.actions.list[0].steps[0].0, "filter.cameraRaw");
|
||||
let saved_step = |r: &Value| {
|
||||
let saved = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
|
||||
saved.actions[0].items.first().map(|i| (i.event.clone(), i.descriptor.clone()))
|
||||
saved.actions[0].items.first().map(|i| (i.event.clone(), i.dictionary.clone(), i.descriptor.clone()))
|
||||
};
|
||||
// Strict save, and the Actions panel's save (which skips what can't be written).
|
||||
// Strict save, and the Actions panel's save (which skips what can't be written). The step's
|
||||
// dictionary is stored action data, so it keeps Photoshop's wording and not the menu label
|
||||
// ("RAW Develop Filter"): a loaded step reads the same in Photoshop's Actions panel.
|
||||
for skip in [false, true] {
|
||||
let r = s.execute("actions.save", json!({"action": "A", "skipUnsupported": skip})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([]), "{r}");
|
||||
assert_eq!(saved_step(&r), Some((AtnEvent::name("Adobe Camera Raw Filter"), Some(recorded.clone()))));
|
||||
let expected = (AtnEvent::name("Adobe Camera Raw Filter"), b"Camera Raw Filter".to_vec(), Some(recorded.clone()));
|
||||
assert_eq!(saved_step(&r), Some(expected));
|
||||
}
|
||||
// It plays.
|
||||
s.execute("file.new", json!({"width": 16, "height": 12})).unwrap();
|
||||
@@ -5631,6 +5636,216 @@ fn custom_outside_the_commands_range_is_kept_and_refused() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A local absolute map path on this platform: playback may read only such a path.
|
||||
#[cfg(windows)]
|
||||
const LOCAL_MAP: &str = r"C:\máp.psd";
|
||||
#[cfg(not(windows))]
|
||||
const LOCAL_MAP: &str = "/máp.psd";
|
||||
/// [`LOCAL_MAP`] as a `txtu` path, encoded independently of the production path writer.
|
||||
#[cfg(windows)]
|
||||
const LOCAL_MAP_WIRE: &[u8] = b"txtu\x22\0\0\0\x0b\0\0\0C\0:\0\\\0m\0\xe1\0p\0.\0p\0s\0d\0\0\0";
|
||||
#[cfg(not(windows))]
|
||||
const LOCAL_MAP_WIRE: &[u8] = b"txtu\x1e\0\0\0\x09\0\0\0/\0m\0\xe1\0p\0.\0p\0s\0d\0\0\0";
|
||||
|
||||
/// The selected-map descriptor measured in a Windows Displace recording.
|
||||
fn displace_descriptor(path: D) -> Descriptor {
|
||||
desc("null")
|
||||
.with("HrzS", D::Integer(10))
|
||||
.with("VrtS", D::Integer(10))
|
||||
.with("DspM", enm("DspM", "StrF"))
|
||||
.with("UndA", enm("UndA", "RptE"))
|
||||
.with("DspF", path)
|
||||
}
|
||||
|
||||
/// Preserve the typed path and materialize native defaults when saving sparse steps.
|
||||
#[test]
|
||||
fn recorded_displace_round_trips_text_event_and_typed_path() {
|
||||
let descriptor = displace_descriptor(D::Path(LOCAL_MAP_WIRE.to_vec()));
|
||||
let data = set_of("Maps", vec![("A", vec![item("displace", "Displace", Some(descriptor.clone()))])]);
|
||||
let imported = import(&photocraft_paint::tile::b64_decode(&data).unwrap()).unwrap();
|
||||
assert!(imported.unsupported.is_empty());
|
||||
let (id, params) = &imported.actions[0].steps[0];
|
||||
assert_eq!(id, "filter.distort.displace");
|
||||
assert_eq!(*params, json!({"horizontal":10,"vertical":10,"fit":"stretch","undefinedAreas":"repeat","mapPath":LOCAL_MAP}));
|
||||
let exported = export_item(id, params, "Maps").unwrap();
|
||||
assert_eq!(exported.event, AtnEvent::name("displace"));
|
||||
assert_eq!(exported.descriptor, Some(descriptor.clone()));
|
||||
let minimal = json!({"mapPath":LOCAL_MAP});
|
||||
assert_eq!(export_item(id, &minimal, "Maps").unwrap().descriptor, Some(descriptor.clone()));
|
||||
for key in ["horizontal", "vertical", "fit", "undefinedAreas"] {
|
||||
let mut sparse = params.clone();
|
||||
sparse.as_object_mut().unwrap().remove(key);
|
||||
assert_eq!(export_item(id, &sparse, "Maps").unwrap().descriptor, Some(descriptor.clone()), "{key}");
|
||||
}
|
||||
let custom = json!({"horizontal":-7,"mapPath":LOCAL_MAP});
|
||||
let mut expected = descriptor;
|
||||
expected.items[0].1 = D::Integer(-7);
|
||||
assert_eq!(export_item(id, &custom, "Maps").unwrap().descriptor, Some(expected));
|
||||
}
|
||||
|
||||
/// A shared action file must not make playback open a network share, a device or a path taken
|
||||
/// from the working directory: such a map path stays a kept step with its bytes.
|
||||
#[test]
|
||||
fn displace_map_paths_a_document_may_not_name_stay_kept_steps() {
|
||||
let refused = [r"\\server\share\map.psd", "//server/share/map.psd", r"\\?\UNC\server\share\map.psd", r"\\.\COM1", "file://server/share/map.psd", "map.psd"];
|
||||
let cases: Vec<_> = refused.iter().map(|path| item("displace", "Displace", Some(displace_descriptor(path_value(path))))).collect();
|
||||
let data = set_of("Maps", vec![("A", cases.clone())]);
|
||||
let imported = import(&photocraft_paint::tile::b64_decode(&data).unwrap()).unwrap();
|
||||
assert_eq!(imported.unsupported.len(), cases.len());
|
||||
for ((id, params), expected) in imported.actions[0].steps.iter().zip(cases) {
|
||||
assert_eq!(id, PHOTOSHOP_STEP, "{params}");
|
||||
assert_eq!(export_item(id, params, "Maps").unwrap().descriptor, expected.descriptor);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep unmeasured inputs intact and refuse settings that would be changed by export.
|
||||
#[test]
|
||||
fn unmeasured_displace_stays_opaque_and_lossy_export_is_refused() {
|
||||
assert!(!super::menu_item_commands().contains(&"filter.distort.displace"));
|
||||
let path = r"C:\map.psd";
|
||||
let wire = path_value(path);
|
||||
let descriptor = displace_descriptor(wire.clone());
|
||||
let replace = |key: &str, value: D| {
|
||||
let mut d = descriptor.clone();
|
||||
d.items.iter_mut().find(|(id, _)| id.is(key)).unwrap().1 = value;
|
||||
d
|
||||
};
|
||||
let alter_path = |i: usize, pair: [u8; 2]| {
|
||||
let D::Path(mut bytes) = wire.clone() else { panic!("expected a path") };
|
||||
bytes[i..i + 2].copy_from_slice(&pair);
|
||||
D::Path(bytes)
|
||||
};
|
||||
let mut without_path = descriptor.clone();
|
||||
without_path.items.retain(|(id, _)| !id.is("DspF"));
|
||||
let mut string_key = descriptor.clone();
|
||||
string_key.items[0].0 = Id::Str(b"HrzS".to_vec());
|
||||
let cases = [
|
||||
item("displace", "Displace", None),
|
||||
item("displace", "Displace", Some(without_path)),
|
||||
item("displace", "Displace", Some(string_key)),
|
||||
item("displace", "Displace", Some(descriptor.clone().with("HrzS", D::Integer(10)))),
|
||||
item("displace", "Displace", Some(replace("HrzS", D::Double(10.0)))),
|
||||
item("displace", "Displace", Some(replace("VrtS", D::Integer(1000)))),
|
||||
item("displace", "Displace", Some(replace("DspM", enm("DspM", "Tile")))),
|
||||
item("displace", "Displace", Some(replace("UndA", enm("OtherEnum", "RptE")))),
|
||||
item("displace", "Displace", Some(replace("DspF", D::Alias(vec![1, 2, 3])))),
|
||||
item("displace", "Displace", Some(replace("DspF", alter_path(4, [0, 0])))),
|
||||
item("displace", "Displace", Some(replace("DspF", alter_path(8, [9, 0])))),
|
||||
item("displace", "Displace", Some(replace("DspF", alter_path(12, [0, 0])))),
|
||||
item("displace", "Displace", Some(replace("DspF", alter_path(12, [0, 0xd8])))),
|
||||
item("Dspl", "Displace", Some(descriptor)),
|
||||
];
|
||||
let data = set_of("Maps", vec![("A", cases.to_vec())]);
|
||||
let imported = import(&photocraft_paint::tile::b64_decode(&data).unwrap()).unwrap();
|
||||
assert_eq!(imported.unsupported.len(), cases.len());
|
||||
assert_eq!(imported.actions[0].steps.len(), cases.len());
|
||||
for ((id, params), expected) in imported.actions[0].steps.iter().zip(cases) {
|
||||
assert_eq!(id, PHOTOSHOP_STEP);
|
||||
let exported = export_item(id, params, "Maps").unwrap();
|
||||
assert_eq!(exported.event, expected.event);
|
||||
assert_eq!(exported.descriptor, expected.descriptor);
|
||||
}
|
||||
|
||||
let good = json!({"horizontal":10,"vertical":10,"fit":"stretch","undefinedAreas":"repeat","mapPath":path});
|
||||
for (key, value) in [
|
||||
("horizontal", json!(10.5)),
|
||||
("horizontal", json!(1000)),
|
||||
("vertical", json!(-1000)),
|
||||
("vertical", json!("10")),
|
||||
("fit", json!("tile")),
|
||||
("fit", Value::Null),
|
||||
("undefinedAreas", json!("wrap")),
|
||||
("undefinedAreas", json!(false)),
|
||||
("mapPath", json!("x\0y.psd")),
|
||||
("mapPath", json!("")),
|
||||
("mapLayer", json!(1)),
|
||||
("mapDocument", json!(0)),
|
||||
("target", json!("mask")),
|
||||
] {
|
||||
let mut params = good.clone();
|
||||
params[key] = value;
|
||||
assert!(export_item("filter.distort.displace", ¶ms, "Maps").is_none(), "{params}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Loading needs no map; playback reads it only after authorization and stretches it.
|
||||
#[test]
|
||||
fn recorded_displace_loads_without_map_and_plays_through_the_step_gate() {
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("synthetic-map.psd");
|
||||
let wire = displace_descriptor(path_value(path.to_str().unwrap()));
|
||||
let data = set_of("Maps", vec![("A", vec![item("displace", "Displace", Some(wire))])]);
|
||||
let mut source = Session::new();
|
||||
let loaded = source.execute("actions.load", json!({"data":data})).unwrap();
|
||||
assert_eq!(loaded["unsupported"], json!([]));
|
||||
assert!(!path.exists(), "loading the ATN needs no map");
|
||||
|
||||
let paint_split = |s: &mut Session, side: i32, split: i32, right: [f32; 4]| {
|
||||
s.execute("file.new", json!({"width":side,"height":side})).unwrap();
|
||||
s.edit("Two-tone fixture", |doc, _| {
|
||||
let id = doc.layers[0].id;
|
||||
let surface = doc.layer_mut(id).unwrap().surface_mut().unwrap();
|
||||
surface.fill_rect(Rect::new(0, 0, split, side), &[0.0, 0.0, 0.0, 1.0]);
|
||||
surface.fill_rect(Rect::new(split, 0, side, side), &right);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
// Offset the source edge so the positive shift crosses it within the white part of the map.
|
||||
paint_split(&mut source, 64, 48, [1.0, 0.0, 0.0, 1.0]);
|
||||
source
|
||||
.edit("Bottom edge fixture", |doc, _| {
|
||||
let id = doc.layers[0].id;
|
||||
let surface = doc.layer_mut(id).unwrap().surface_mut().unwrap();
|
||||
surface.fill_rect(Rect::new(0, 48, 64, 64), &[0.0, 1.0, 0.0, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let snapshot = |s: &Session| {
|
||||
let active = s.active().unwrap();
|
||||
(active.revision, active.history.past_len(), photocraft_compose::render(&active.doc, active.doc.bounds()).into_px())
|
||||
};
|
||||
let before = snapshot(&source);
|
||||
let missing = source.execute("actions.play", json!({"action":"A"})).unwrap();
|
||||
assert_eq!(missing["ran"], 0);
|
||||
assert_eq!(missing["failed"]["id"], "filter.distort.displace");
|
||||
assert!(missing["failed"]["error"].as_str().unwrap().contains("cannot read displacement map"));
|
||||
assert_eq!(snapshot(&source), before);
|
||||
|
||||
// Leave the map absent so a read before authorization would report the same I/O failure.
|
||||
source.authorize = Some(|id, p| {
|
||||
if id == "filter.distort.displace" && p["mapPath"].is_string() {
|
||||
return Err(EngineError::Other("test denied the map path".into()));
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
let denied = source.execute("actions.play", json!({"action":"A"})).unwrap();
|
||||
assert_eq!(denied["ran"], 0);
|
||||
assert_eq!(denied["failed"]["id"], "filter.distort.displace");
|
||||
assert!(denied["failed"]["error"].as_str().unwrap().contains("test denied the map path"));
|
||||
assert_eq!(snapshot(&source), before);
|
||||
|
||||
source.authorize = None;
|
||||
let mut map = Session::new();
|
||||
paint_split(&mut map, 16, 8, [1.0, 1.0, 1.0, 1.0]);
|
||||
let encoded = photocraft_io::export(&map.active().unwrap().doc, "psd", &Default::default()).unwrap();
|
||||
std::fs::write(&path, encoded.bytes).unwrap();
|
||||
let played = source.execute("actions.play", json!({"action":"A"})).unwrap();
|
||||
assert_eq!(played["ran"], 1, "{played}");
|
||||
assert!(played.get("failed").is_none(), "{played}");
|
||||
let pixels = snapshot(&source).2;
|
||||
// With stretch, x=38 samples the white half and shifts into red; tiling samples black.
|
||||
assert_eq!(before.2[32 * 64 + 38], [0.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(pixels[32 * 64 + 38], [1.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(pixels[32 * 64 + 20], [0.0, 0.0, 0.0, 1.0]);
|
||||
// The vertical shift crosses into green, then repeats the bottom edge instead of wrapping to red.
|
||||
assert_eq!(before.2[40 * 64 + 38], [0.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(pixels[40 * 64 + 38], [0.0, 1.0, 0.0, 1.0]);
|
||||
assert_eq!(pixels[60 * 64 + 38], [0.0, 1.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
/// The step `d` of Photoshop event `code`, as PhotoCraft loads it.
|
||||
fn distort(code: &str, d: Descriptor) -> Mapped {
|
||||
let event = AtnEvent::Code(code.as_bytes().try_into().unwrap());
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
//! The Background Eraser on a layer with Lock transparent pixels on (#11905): the reference
|
||||
//! application erases to transparency exactly as on an unlocked layer, leaves the lock on and shows
|
||||
//! no alert. Lock image pixels and Lock all still refuse; the Eraser and the Magic Eraser keep their
|
||||
//! own lock behaviour (they paint the background colour).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// White Background plus a normal layer "Target" with a solid red band across it (y 10..30).
|
||||
fn session(depth: u32) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 40, "depth": depth})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Target"})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 0, "y": 10, "width": 64, "height": 20, "antiAlias": false})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn target(s: &Session) -> &Layer {
|
||||
let d = s.active().unwrap();
|
||||
d.doc.layer(d.active_layer.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn alphas(s: &Session) -> Vec<f32> {
|
||||
let surf = target(s).surface().unwrap();
|
||||
(0..40).flat_map(|y| (0..64).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)[3]).collect()
|
||||
}
|
||||
|
||||
fn click() -> Value {
|
||||
json!({"points": [[32, 20]], "size": 20, "hardness": 1, "tolerance": 50})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_on_a_transparency_locked_layer_erases_as_on_an_unlocked_one() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut free = session(depth);
|
||||
free.execute("paint.backgroundEraser", click()).unwrap();
|
||||
let want = alphas(&free);
|
||||
|
||||
let mut s = session(depth);
|
||||
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
|
||||
let h = s.active().unwrap().history.past_len();
|
||||
s.execute("paint.backgroundEraser", click()).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), h + 1, "{depth}-bit: one History step");
|
||||
assert_eq!(target(&s).surface().unwrap().rgba(32, 20)[3], 0.0, "{depth}-bit: erased to transparency");
|
||||
assert_eq!(alphas(&s), want, "{depth}-bit: the same alpha as on an unlocked layer");
|
||||
assert!(target(&s).locks.transparency, "{depth}-bit: the lock stays on");
|
||||
assert_eq!(target(&s).name, "Target", "{depth}-bit: the same layer");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_and_the_live_preview_erase_a_transparency_locked_layer_too() {
|
||||
let mut s = session(8);
|
||||
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
|
||||
let opts = |pts: &[[f64; 2]]| json!({"points": pts, "size": 12, "hardness": 1});
|
||||
let all = [[8.0, 20.0], [32.0, 20.0], [56.0, 20.0]];
|
||||
let mut live = live_background_eraser(&s, &opts(&all[..1])).unwrap();
|
||||
for q in &all[1..] {
|
||||
live.push(&[photocraft_paint::StrokePoint::new(q[0], q[1], 1.0)]).unwrap();
|
||||
}
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
let shown = live.doc.layer(id).unwrap().surface().unwrap().clone();
|
||||
s.execute("paint.backgroundEraser", opts(&all)).unwrap();
|
||||
let surf = target(&s).surface().unwrap();
|
||||
for x in [8, 32, 56] {
|
||||
assert_eq!(surf.rgba(x, 20)[3], 0.0, "({x}, 20) erased");
|
||||
assert_eq!(shown.rgba(x, 20)[3], 0.0, "the preview shows ({x}, 20) erased");
|
||||
}
|
||||
assert_eq!(surf.rgba(32, 5)[3], 0.0, "transparent pixels stay transparent");
|
||||
assert!(target(&s).locks.transparency);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_a_colour_channel_target_the_preview_matches_the_commit_on_a_locked_layer() {
|
||||
// A channel target erases colour channels only (towards the background colour) and never
|
||||
// changes alpha. The commit mixes back without the lock, so the preview must too: at 32 bits
|
||||
// a lock-keeping mix rounds partly transparent pixels differently. The stroke crosses the
|
||||
// band's edge and a half-transparent strip, at half opacity, so every mix case is under the tip.
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = session(depth);
|
||||
s.execute("select.rect", json!({"x": 0, "y": 4, "width": 64, "height": 6, "antiAlias": false})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": "#3a7fd0", "opacity": 37})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
|
||||
let opts = |pts: &[[f64; 2]]| json!({"points": pts, "size": 16, "hardness": 0.5, "opacity": 0.53, "target": {"colors": [1]}});
|
||||
let all = [[8.0, 9.0], [32.0, 10.0], [56.0, 11.0]];
|
||||
let mut live = live_background_eraser(&s, &opts(&all[..1])).unwrap();
|
||||
for q in &all[1..] {
|
||||
live.push(&[photocraft_paint::StrokePoint::new(q[0], q[1], 1.0)]).unwrap();
|
||||
}
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
let shown = live.doc.layer(id).unwrap().surface().unwrap().clone();
|
||||
let before = alphas(&s);
|
||||
s.execute("paint.backgroundEraser", opts(&all)).unwrap();
|
||||
let surf = target(&s).surface().unwrap();
|
||||
assert!(surf.rgba(32, 12)[1] > 0.0, "{depth}-bit: the green channel moved towards the white background");
|
||||
for (x, y) in (0..40).flat_map(|y| (0..64).map(move |x| (x, y))) {
|
||||
assert_eq!(shown.rgba(x, y), surf.rgba(x, y), "{depth}-bit ({x}, {y}): preview = commit");
|
||||
}
|
||||
assert_eq!(alphas(&s), before, "{depth}-bit: alpha untouched");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_pixels_and_lock_all_still_refuse() {
|
||||
for locks in [json!({"pixels": true}), json!({"all": true})] {
|
||||
let mut s = session(8);
|
||||
s.execute("layer.setProps", json!({"locks": locks})).unwrap();
|
||||
let before = alphas(&s);
|
||||
let h = s.active().unwrap().history.past_len();
|
||||
let err = s.execute("paint.backgroundEraser", click()).unwrap_err().to_string();
|
||||
assert!(err.contains("Could not complete your request because the layer \"Target\" is locked"), "{locks}: {err}");
|
||||
assert!(live_background_eraser(&s, &click()).is_err(), "{locks}: the preview refuses too");
|
||||
assert_eq!(alphas(&s), before, "{locks}: nothing erased");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), h, "{locks}: no History step");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_eraser_and_the_magic_eraser_keep_painting_the_background_colour() {
|
||||
// Magic Eraser: the background colour (white by default), still opaque.
|
||||
let mut s = session(8);
|
||||
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
|
||||
s.execute("paint.magicEraser", json!({"x": 32, "y": 20})).unwrap();
|
||||
assert_eq!(target(&s).surface().unwrap().rgba(32, 20), [1.0, 1.0, 1.0, 1.0]);
|
||||
// Eraser: the same.
|
||||
let mut s = session(8);
|
||||
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
|
||||
s.execute("paint.stroke", json!({"erase": true, "points": [[8, 20], [56, 20]], "size": 8, "hardness": 1.0})).unwrap();
|
||||
assert_eq!(target(&s).surface().unwrap().rgba(32, 20), [1.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
@@ -348,7 +348,11 @@ fn apply_auto_erase(brush: &mut BrushSettings, surf: &Surface, start: Option<&St
|
||||
/// The Pencil's brush: the session brush made aliased (every pixel fully painted or untouched,
|
||||
/// dabs on the pixel grid), hard and at full flow, with the options-bar mode.
|
||||
fn pencil_brush(s: &Session, p: &Value) -> Result<BrushSettings> {
|
||||
let mut brush = with_blend_mode(resolve_brush(s, p, "paint.pencil")?, p);
|
||||
pencil_shape(with_blend_mode(resolve_brush(s, p, "paint.pencil")?, p), p)
|
||||
}
|
||||
|
||||
/// `brush` with the Pencil's hard, aliased tip, or the Eraser's Block (`"block": true`).
|
||||
pub(crate) fn pencil_shape(mut brush: BrushSettings, p: &Value) -> Result<BrushSettings> {
|
||||
if flag(p, "block", false) {
|
||||
return block_brush(brush, p);
|
||||
}
|
||||
@@ -832,6 +836,21 @@ fn mixer_load_pixel(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// channel or Quick Mask `target` is refused rather than recolouring the layer instead.
|
||||
fn color_replacement_setup(s: &Session, p: &Value) -> Result<(Stroke, ReplaceSettings, photocraft_doc::LayerId)> {
|
||||
let cmd = "paint.colorReplacement";
|
||||
// The modes and depths the reference application refuses, with its words (#11923). The live
|
||||
// stroke runs this setup too, so it previews nothing in them. 32-bit Grayscale, CMYK and Lab,
|
||||
// Multichannel and Duotone weren't measured and keep painting.
|
||||
if let Some(st) = s.active() {
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
let why = match (st.doc.mode, st.doc.depth) {
|
||||
(ColorMode::Indexed, _) => Some("it does not work with Indexed Color images (convert image to RGB Color mode to edit)."),
|
||||
(ColorMode::Bitmap, _) | (ColorMode::Grayscale, SampleType::U8 | SampleType::U16) => Some("it only works in full color modes."),
|
||||
(ColorMode::Rgb, SampleType::F32) => Some("it does not work with 32 bit per channel images (convert image to 8 or 16 bit per channel to edit)."),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(why) = why {
|
||||
return Err(EngineError::Other(format!("Could not use the Color Replacement tool because {why}")));
|
||||
}
|
||||
}
|
||||
if let Some(t) = p.get("target").filter(|t| t.as_str() != Some("pixels"))
|
||||
&& crate::color_channels::explicit(p, s.active().map_or(0, |st| crate::channel_cmds::color_count(&st.doc)))?.is_none()
|
||||
{
|
||||
@@ -846,7 +865,8 @@ fn color_replacement_setup(s: &Session, p: &Value) -> Result<(Stroke, ReplaceSet
|
||||
mode: parse(p, cmd, "mode")?.unwrap_or(ReplaceMode::Color),
|
||||
sampling: parse(p, cmd, "sampling")?.unwrap_or(Sampling::Continuous),
|
||||
limits: parse(p, cmd, "limits")?.unwrap_or(Limits::Contiguous),
|
||||
tolerance: pct(p, "tolerance", 30.0),
|
||||
// 1..100 %, as the reference's field takes it: 0 and below run as 1 (#11930).
|
||||
tolerance: pct(p, "tolerance", 30.0).max(0.01),
|
||||
anti_alias: flag(p, "antiAlias", true),
|
||||
color: brush.color,
|
||||
background: s.tools.background,
|
||||
@@ -855,9 +875,14 @@ fn color_replacement_setup(s: &Session, p: &Value) -> Result<(Stroke, ReplaceSet
|
||||
Ok((Stroke { brush, points: pts }, rs, id))
|
||||
}
|
||||
|
||||
/// The History state (and recorded step) name of a Color Replacement edit.
|
||||
pub const COLOR_REPLACEMENT_STEP: &str = "Color Replacement Tool";
|
||||
|
||||
fn color_replacement(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (stroke, rs, id) = color_replacement_setup(s, p)?;
|
||||
let dmg = s.edit("Color Replacement", |doc, _| {
|
||||
// The reference application names every click, stroke and Shift+click segment "Color
|
||||
// Replacement Tool" (#11933); the command's label is the same, so recorded actions match.
|
||||
let dmg = s.edit(COLOR_REPLACEMENT_STEP, |doc, _| {
|
||||
let sel = doc.selection.clone();
|
||||
let lock = doc.effective_locks(id).transparency;
|
||||
let surf = paint_surface(doc, id, &json!({}))?;
|
||||
@@ -1340,8 +1365,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
spec!(
|
||||
"paint.colorReplacement",
|
||||
"Color Replacement",
|
||||
r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":0..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?}"##,
|
||||
"Color Replacement Tool",
|
||||
r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":1..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?}"##,
|
||||
crate::commands::has_paintable,
|
||||
color_replacement,
|
||||
true
|
||||
@@ -1381,5 +1406,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "color_replacement_modes_tests.rs"]
|
||||
mod color_replacement_modes_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod mixer_live_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "color_replacement_history_name_tests.rs"]
|
||||
mod color_replacement_history_name_tests;
|
||||
@@ -151,6 +151,7 @@ impl LiveMixer {
|
||||
|
||||
/// Validate the params and capture the document and paint load, without rendering a dab.
|
||||
fn prepare(s: &Session, p: &Value, preview_limits: bool) -> Result<(Self, Vec<StrokePoint>)> {
|
||||
mode_refusal(s)?;
|
||||
let captured = crate::channel_cmds::inject_target(s, CMD, p.clone());
|
||||
let p = &captured;
|
||||
has_paintable(s).map_err(EngineError::Other)?;
|
||||
@@ -168,6 +169,7 @@ impl LiveMixer {
|
||||
sample_all_layers: flag(p, "sampleAllLayers", bm.sample_all_layers) && crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels,
|
||||
clean_after_stroke: flag(p, "cleanAfterStroke", bm.clean_after_stroke),
|
||||
load_after_stroke: flag(p, "loadAfterStroke", bm.load_after_stroke),
|
||||
solid_colors_only: bm.solid_colors_only,
|
||||
};
|
||||
let initial_state = if let Some(value) = p.get("mixerState") {
|
||||
if value.get("spatial").and_then(Value::as_array).is_some_and(|v| v.len() != 4096) {
|
||||
@@ -330,9 +332,26 @@ impl LiveMixer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The reference's alert for a Mixer Brush press in an Indexed Color document (#11958).
|
||||
pub const INDEXED_REFUSAL: &str =
|
||||
"Could not use the Mixer Brush tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit).";
|
||||
/// The reference's alert for a Mixer Brush press in a Bitmap document (#11958).
|
||||
pub const BITMAP_REFUSAL: &str = "Could not use the Mixer Brush tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).";
|
||||
|
||||
/// The Mixer Brush refuses Indexed Color and Bitmap documents before anything is painted, with the
|
||||
/// reference's alert text; other modes (Duotone and Multichannel were not measured) paint as before.
|
||||
fn mode_refusal(s: &Session) -> Result<()> {
|
||||
match s.active().map(|st| st.doc.mode) {
|
||||
Some(photocraft_color::ColorMode::Indexed) => Err(EngineError::Other(INDEXED_REFUSAL.into())),
|
||||
Some(photocraft_color::ColorMode::Bitmap) => Err(EngineError::Other(BITMAP_REFUSAL.into())),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume a matching prepared result or replay without the preview tile cap, then commit one history step.
|
||||
/// The completed stroke also applies the automatic clean/load settings to the stored paint load.
|
||||
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mode_refusal(s)?;
|
||||
let points = parse_points(p, CMD)?;
|
||||
let cached =
|
||||
s.live_commit.take().filter(|live| live.matches(s, CMD, p, &points) && live.mixer.as_ref().is_some_and(|(before, _)| *before == s.tools.mixer));
|
||||
|
||||
@@ -282,7 +282,7 @@ fn mixer_large_tip_retains_off_canvas_paint_and_commits_the_live_result() {
|
||||
#[test]
|
||||
fn mixer_long_segments_are_interpolated_and_replay_matches_live() {
|
||||
let mut s = fixture(PixelFormat::RGBA8);
|
||||
let p = json!({"points":[[20,48],[5020,48]],"seed":71,"size":2,"sampleAllLayers":false,"wet":0,"mix":0,"load":100,"color":"#ff0000"});
|
||||
let p = json!({"points":[[20,48],[5020,48]],"seed":71,"size":2,"sampleAllLayers":false,"wet":0,"mix":0,"load":100,"color":"#ff0000","brush":{"smoothing":{"catchUpOnEnd":true}}});
|
||||
let live = LiveMixer::begin(&s, &p).unwrap();
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
let expected = live.doc.layer(id).unwrap().surface().unwrap().clone();
|
||||
|
||||
@@ -985,7 +985,11 @@ fn mixer_brush_uses_the_brush_mixer_settings() {
|
||||
let mut s = session(200, 30);
|
||||
s.execute("tools.setColors", json!({"foreground": "#ff0000"})).unwrap();
|
||||
// No wet/load params: the brush's Mixer settings (a dry brush with 0 % Load) apply.
|
||||
s.execute("tools.setBrush", json!({"brush": {"pressureSize": false, "spacing": 0.25, "mixer": {"wet": 0, "load": 0, "mix": 0}}})).unwrap();
|
||||
s.execute(
|
||||
"tools.setBrush",
|
||||
json!({"brush": {"pressureSize": false, "spacing": 0.25, "mixer": {"wet": 0, "load": 0, "mix": 0}, "smoothing": {"catchUpOnEnd": true}}}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("paint.mixerBrush", json!({"points": [[5, 15], [195, 15]], "size": 8})).unwrap();
|
||||
assert!(rgba(&s, 10, 15)[3] > 0.95 && rgba(&s, 190, 15)[3] < 0.5, "the brush's 0 % Load dries out");
|
||||
// A param still overrides the brush.
|
||||
|
||||
@@ -136,7 +136,7 @@ pub(crate) use targeting::{
|
||||
Target, channel_surface_for_filter, clear_channel, clear_color_channel, color_restriction, edits_channel, filter_mask_layer, inject_target, invert_region,
|
||||
is_channel_target, is_spot_target, mask_target_enabled, restrict_to_color, routed, target_of, target_surface, targeted_channel,
|
||||
};
|
||||
pub use targeting::{follows_filter_mask, follows_target, gray_target, read_target_surface};
|
||||
pub use targeting::{follows_filter_mask, follows_target, follows_vector_mask_target, gray_target, read_target_surface};
|
||||
pub use tone_target::{ToneTarget, resolve_tone_target};
|
||||
pub(crate) use view::fix_view;
|
||||
pub use view::{ChannelTarget, ChannelView, QuickMaskOptions, color_names, composite_name};
|
||||
|
||||
@@ -187,6 +187,18 @@ pub fn follows_filter_mask(id: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// Edit › Transform's Rotate/Flip presets can turn a targeted vector mask's path (#12283).
|
||||
pub fn follows_vector_mask_target(id: &str) -> bool {
|
||||
matches!(
|
||||
id,
|
||||
"edit.transform.rotate180"
|
||||
| "edit.transform.rotate90Cw"
|
||||
| "edit.transform.rotate90Ccw"
|
||||
| "edit.transform.flipHorizontal"
|
||||
| "edit.transform.flipVertical"
|
||||
)
|
||||
}
|
||||
|
||||
/// The paint and retouch tools that follow the targeted channel or mask.
|
||||
const PAINT_IDS: &[&str] = &[
|
||||
"paint.stroke",
|
||||
@@ -271,6 +283,8 @@ pub(crate) fn inject_target(s: &Session, id: &str, params: Value) -> Value {
|
||||
json!("filterMask")
|
||||
}
|
||||
ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some() => json!("mask"),
|
||||
// Edit › Transform's Rotate/Flip presets turn the targeted vector mask's path (#12283).
|
||||
ChannelTarget::VectorMask if follows_vector_mask_target(id) => json!("vectorMask"),
|
||||
_ => return params,
|
||||
};
|
||||
match params {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! #11933: a Color Replacement click, a drag and a Shift+click segment each add one History state
|
||||
//! named "Color Replacement Tool", on a layer and on the Background with Lock transparent pixels;
|
||||
//! the command's label, which recorded actions show, is the same name.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("tools.setColors", json!({"foreground": "#0000ff"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn last(s: &Session) -> (usize, Option<String>) {
|
||||
let h = &s.active().unwrap().history;
|
||||
(h.past_len(), h.entries().last().map(|e| e.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_click_stroke_and_segment_is_one_color_replacement_tool_state() {
|
||||
for on_background in [false, true] {
|
||||
let mut s = session();
|
||||
if !on_background {
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": "#dc1e1e"})).unwrap();
|
||||
} else {
|
||||
s.execute("edit.fill", json!({"color": "#dc1e1e"})).unwrap();
|
||||
s.execute("layer.lockLayers", json!({"transparency": true})).unwrap();
|
||||
}
|
||||
for points in [json!([[20, 20]]), json!([[20, 50], [80, 50]]), json!([[80, 50], [80, 80]])] {
|
||||
let (n, _) = last(&s);
|
||||
s.execute("paint.colorReplacement", json!({"points": points, "size": 15})).unwrap();
|
||||
assert_eq!(last(&s), (n + 1, Some(COLOR_REPLACEMENT_STEP.to_string())), "{points} (background {on_background})");
|
||||
}
|
||||
}
|
||||
assert_eq!(COLOR_REPLACEMENT_STEP, "Color Replacement Tool");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorded_steps_use_the_same_name() {
|
||||
let spec = crate::commands::find("paint.colorReplacement").expect("the command");
|
||||
assert_eq!(spec.label, COLOR_REPLACEMENT_STEP);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! #11923: the Color Replacement tool refuses RGB/32, Grayscale, Bitmap and Indexed documents with
|
||||
//! the reference application's messages, painting nothing and adding no history; the live stroke
|
||||
//! is refused the same way. RGB/8, RGB/16, CMYK and Lab paint.
|
||||
|
||||
use photocraft_color::{Color, ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Size};
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
const DEPTH_32: &str =
|
||||
"Could not use the Color Replacement tool because it does not work with 32 bit per channel images (convert image to 8 or 16 bit per channel to edit).";
|
||||
const NOT_FULL_COLOR: &str = "Could not use the Color Replacement tool because it only works in full color modes.";
|
||||
const INDEXED: &str = "Could not use the Color Replacement tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit).";
|
||||
|
||||
/// A session with one 64 × 64 document of `mode` and `depth`, filled red.
|
||||
fn session(mode: ColorMode, depth: SampleType) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.add_document(Document::with_background("t", Size::new(64, 64), mode, depth, Color::rgb(220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0)), None);
|
||||
s.tools.foreground = [0.0, 0.0, 1.0, 1.0];
|
||||
s
|
||||
}
|
||||
|
||||
fn stroke() -> Value {
|
||||
json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100})
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.past_len()
|
||||
}
|
||||
|
||||
fn pixels(s: &Session) -> Vec<f32> {
|
||||
let st = s.active().unwrap();
|
||||
let surf = st.doc.layers[0].surface().unwrap();
|
||||
(0..64).flat_map(|y| (0..64).flat_map(move |x| surf.pixel(x, y))).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_modes_say_why_and_paint_nothing() {
|
||||
for (mode, depth, want) in [
|
||||
(ColorMode::Rgb, SampleType::F32, DEPTH_32),
|
||||
(ColorMode::Grayscale, SampleType::U8, NOT_FULL_COLOR),
|
||||
(ColorMode::Grayscale, SampleType::U16, NOT_FULL_COLOR),
|
||||
(ColorMode::Bitmap, SampleType::U8, NOT_FULL_COLOR),
|
||||
(ColorMode::Indexed, SampleType::U8, INDEXED),
|
||||
] {
|
||||
let mut s = session(mode, depth);
|
||||
let (before, n) = (pixels(&s), steps(&s));
|
||||
let err = s.execute("paint.colorReplacement", stroke()).unwrap_err().to_string();
|
||||
assert_eq!(err, want, "{mode:?}/{depth:?}");
|
||||
assert_eq!(pixels(&s), before, "{mode:?}/{depth:?}: nothing painted");
|
||||
assert_eq!(steps(&s), n, "{mode:?}/{depth:?}: no history");
|
||||
// The live stroke previews nothing either.
|
||||
let live = live_color_replacement(&s, &stroke()).err().map(|e| e.to_string());
|
||||
assert_eq!(live.as_deref(), Some(want), "{mode:?}/{depth:?}: live");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_colour_documents_still_paint() {
|
||||
for (mode, depth) in
|
||||
[(ColorMode::Rgb, SampleType::U8), (ColorMode::Rgb, SampleType::U16), (ColorMode::Cmyk, SampleType::U8), (ColorMode::Lab, SampleType::U8)]
|
||||
{
|
||||
let mut s = session(mode, depth);
|
||||
let (before, n) = (pixels(&s), steps(&s));
|
||||
s.execute("paint.colorReplacement", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}"));
|
||||
assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: painted");
|
||||
assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}");
|
||||
assert!(live_color_replacement(&s, &stroke()).is_ok(), "{mode:?}/{depth:?}: live");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! #11763: each Count tool edit gets the reference application's History name. A `count.setGroup`
|
||||
//! that changes exactly one field takes that field's name; several fields at once, or a switch of
|
||||
//! the current group, keep "Count Group Options".
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A 100 × 100 document with one count group holding one marker at 10,10 (its first state is
|
||||
/// "Add Count Object").
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("count.add", json!({"x": 10, "y": 10})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.past_len()
|
||||
}
|
||||
|
||||
/// Run `id` and return the History name of the one step it added.
|
||||
fn named(s: &mut Session, id: &str, p: Value) -> String {
|
||||
let before = steps(s);
|
||||
s.execute(id, p.clone()).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
assert_eq!(steps(s), before + 1, "{id} {p} adds exactly one step");
|
||||
s.active().unwrap().history.undo_label().unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marker_edits_are_add_drag_and_delete_count_object() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
// The first click makes "Count Group 1" too, still one "Add Count Object" step.
|
||||
assert_eq!(named(&mut s, "count.add", json!({"x": 10, "y": 10})), "Add Count Object");
|
||||
assert_eq!(named(&mut s, "count.add", json!({"x": 40, "y": 40})), "Add Count Object");
|
||||
assert_eq!(named(&mut s, "count.move", json!({"x": 10, "y": 10, "to": [20, 20]})), "Drag Count Object");
|
||||
assert_eq!(named(&mut s, "count.remove", json!({"x": 40, "y": 40})), "Delete Count Object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_edits_keep_or_take_their_names() {
|
||||
let mut s = session();
|
||||
assert_eq!(named(&mut s, "count.newGroup", json!({"name": "Leaves"})), "Add Count Group");
|
||||
assert_eq!(named(&mut s, "count.clear", json!({})), "Clear Count");
|
||||
assert_eq!(named(&mut s, "count.deleteGroup", json!({})), "Delete Count Group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_field_change_uses_that_fields_name() {
|
||||
for (p, want) in [
|
||||
(json!({"name": "Seeds"}), "Set Count Group Name"),
|
||||
(json!({"visible": false}), "Set Count Group Visibility"),
|
||||
(json!({"color": "#204080"}), "Set Count Draw Color"),
|
||||
(json!({"markerSize": 5}), "Set Count Marker Size"),
|
||||
(json!({"labelSize": 20}), "Set Count Font Size"),
|
||||
] {
|
||||
let mut s = session();
|
||||
assert_eq!(named(&mut s, "count.setGroup", p.clone()), want, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_fields_at_once_keep_count_group_options() {
|
||||
let mut s = session();
|
||||
assert_eq!(named(&mut s, "count.setGroup", json!({"markerSize": 5, "labelSize": 20})), "Count Group Options");
|
||||
// A field sent with its current value doesn't count as a change.
|
||||
let mut s = session();
|
||||
let name = s.execute("image.analysis.countTool", json!({})).unwrap()["groups"][0]["name"].clone();
|
||||
assert_eq!(named(&mut s, "count.setGroup", json!({"name": name, "markerSize": 6})), "Set Count Marker Size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_the_current_group_keeps_todays_name() {
|
||||
let mut s = session();
|
||||
s.execute("count.newGroup", json!({"name": "Two"})).unwrap();
|
||||
assert_eq!(named(&mut s, "count.setGroup", json!({"group": 0})), "Count Group Options", "only `group`");
|
||||
assert_eq!(named(&mut s, "count.setGroup", json!({"group": 1, "active": true})), "Count Group Options", "`active: true`, no field change");
|
||||
// A field change together with a switch is two changes: today's name too.
|
||||
assert_eq!(named(&mut s, "count.setGroup", json!({"group": 0, "active": true, "visible": false})), "Count Group Options");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_change_adds_no_step_and_bad_params_stay_errors() {
|
||||
let mut s = session();
|
||||
let before = steps(&s);
|
||||
// The current group's own values: nothing changes, no step.
|
||||
s.execute("count.setGroup", json!({"group": 0})).unwrap();
|
||||
assert_eq!(steps(&s), before);
|
||||
for (id, p) in [
|
||||
("count.setGroup", json!({"group": 9, "name": "x"})),
|
||||
("count.setGroup", json!({"markerSize": 2.5})),
|
||||
("count.move", json!({"x": 90, "y": 90, "to": [1, 1]})),
|
||||
("count.remove", json!({"x": 90, "y": 90})),
|
||||
("count.add", json!({"x": 1, "y": 1, "group": 7})),
|
||||
] {
|
||||
assert!(s.execute(id, p.clone()).is_err(), "{id} {p}");
|
||||
assert_eq!(steps(&s), before, "{id} {p} adds no step");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! #11775: Record Measurements labels a Count tool row "Count N"; selection and ruler rows keep
|
||||
//! their labels, and N is the number the row gets today (the shared counter).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn five_counts() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
for i in 0..5 {
|
||||
s.execute("count.add", json!({"x": 10 + 10 * i, "y": 10})).unwrap();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn record(s: &mut Session, source: &str) -> Value {
|
||||
let r = s.execute("image.analysis.recordMeasurements", json!({"source": source})).unwrap();
|
||||
let rows = r["rows"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 1, "{source}: {r}");
|
||||
rows[0]["values"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_count_row_is_labelled_count_n() {
|
||||
for source in ["count", "auto"] {
|
||||
let mut s = five_counts();
|
||||
let row = record(&mut s, source);
|
||||
assert_eq!(row["label"], json!("Count 1"), "{source}: {row}");
|
||||
assert_eq!(row["count"], json!(5), "{source}: {row}");
|
||||
assert_eq!(row["source"], json!("Count Tool"), "{source}: {row}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_rows_keep_their_labels_and_the_counter_is_shared() {
|
||||
let mut s = five_counts();
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
let selection = record(&mut s, "selection");
|
||||
assert_eq!(selection["label"], json!("Measurement 1"), "{selection}");
|
||||
let count = record(&mut s, "count");
|
||||
assert_eq!(count["label"], json!("Count 2"), "{count}");
|
||||
// `auto` picks the selection over the counts, and keeps its label.
|
||||
let auto = record(&mut s, "auto");
|
||||
assert_eq!(auto["source"], json!("Selection"), "{auto}");
|
||||
assert_eq!(auto["label"], json!("Measurement 3"), "{auto}");
|
||||
s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [3, 4]})).unwrap();
|
||||
let ruler = record(&mut s, "ruler");
|
||||
assert_eq!(ruler["label"], json!("Measurement 4"), "{ruler}");
|
||||
let count = record(&mut s, "count");
|
||||
assert_eq!(count["label"], json!("Count 5"), "{count}");
|
||||
}
|
||||
@@ -435,7 +435,7 @@ fn perspective(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
const L: &str = r##"{"strokes":[{"tool":"forwardWarp|reconstruct|smooth|twirlCw|twirlCcw|pucker|bloat|pushLeft|freeze|thaw|lassoMask|reconstructAll","size":px=100,"density":0-100=50,"pressure":0-100=100,"rate":0-100=80,"points":[[x,y,pressure?]…],"amount":%? (twirlCcw: twirlCw reversed, what an Alt-drag with Twirl Clockwise records; reconstructAll; lassoMask: 1 freezes the polygon in points, 0 thaws it)}…],"meshSize":px? (field resolution, px per node; default 2, or 4 above 4 MP),"layer":id?} — strokes replay in order on a fresh field; a selection limits the effect; on a smart object it becomes a smart filter"##;
|
||||
const L: &str = r##"{"strokes":[{"tool":"forwardWarp|reconstruct|smooth|twirlCw|twirlCcw|pucker|bloat|pushLeft|freeze|thaw|lassoMask|reconstructAll","size":px=100,"density":0-100=50,"pressure":0-100=100,"rate":0-100=80,"points":[[x,y,pressure?,ms?]…] (ms: milliseconds since the previous point; a point with it follows the pointer exactly and times the stationary tools in real time, as the dialog records them),"amount":%? (twirlCcw: twirlCw reversed, what an Alt-drag with Twirl Clockwise records; reconstructAll; lassoMask: 1 freezes the polygon in points, 0 thaws it)}…],"meshSize":px? (field resolution, px per node; default 2, or 4 above 4 MP),"layer":id?} — strokes replay in order on a fresh field; a selection limits the effect; on a smart object it becomes a smart filter"##;
|
||||
const P: &str = r##"{"pins":[{"src":[x,y],"dst":[x,y],"rotate":deg?,"depth":n?}…],"mode":"rigid|normal|distort"="normal","density":"fewer|normal|more"="normal","expansion":px=2,"interpolation":"bicubic|bilinear|nearest","layer":id?} — mesh over the opaque region, as-rigid-as-possible; on a smart object it becomes a smart filter"##;
|
||||
const Q: &str = r##"{"planes":[{"src":[[x,y]×4],"dst":[[x,y]×4]}…] (corners clockwise from top-left; corners that coincide in src are linked),"straighten":"horizontal|vertical|auto"?,"interpolation":"bicubic|bilinear|nearest","layer":id?}"##;
|
||||
vec![
|
||||
|
||||
@@ -1267,8 +1267,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_clip,
|
||||
|s, p| paste(s, p, true)
|
||||
),
|
||||
spec!("layer.new.layerViaCopy", "Layer via Copy", &["Layer", "New"], Some("Cmd+J"), "{}", has_doc, |s, _| layer_via(s, false)),
|
||||
spec!("layer.new.layerViaCut", "Layer via Cut", &["Layer", "New"], Some("Cmd+Shift+J"), "{}", has_pixels, |s, _| layer_via(s, true)),
|
||||
spec!("layer.new.layerViaCopy", "Layer Via Copy", &["Layer", "New"], Some("Cmd+J"), "{}", has_doc, |s, _| layer_via(s, false)),
|
||||
spec!("layer.new.layerViaCut", "Layer Via Cut", &["Layer", "New"], Some("Cmd+Shift+J"), "{}", has_pixels, |s, _| layer_via(s, true)),
|
||||
spec!("layer.mergeVisible", "Merge Visible", &["Layer"], Some("Cmd+Shift+E"), "{}", has_doc, |s, _| merge_visible(s)),
|
||||
spec!("image.autoTone", "Auto Tone", &["Image"], Some("Cmd+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "tone")),
|
||||
spec!("image.autoContrast", "Auto Contrast", &["Image"], Some("Cmd+Alt+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "contrast")),
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
//!
|
||||
//! Like Photoshop, both turn a Background layer into a normal layer ("Layer 0") first, since the
|
||||
//! Background can't hold transparency. The Magic Eraser paints the background colour on other
|
||||
//! layers with locked transparency; the Background Eraser refuses them. Both respect the selection,
|
||||
//! work in the layer's own colour model and depth, and are one undo step per click / stroke.
|
||||
//! layers with locked transparency; the Background Eraser erases them to transparency and leaves
|
||||
//! the lock on. Both respect the selection, work in the layer's own colour model and depth, and are
|
||||
//! one undo step per click / stroke.
|
||||
|
||||
use photocraft_algo::selection as sel;
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Layer, LayerContent, LayerId};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_paint::Stroke;
|
||||
@@ -105,7 +107,10 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::NoLayer(id))?;
|
||||
(d.doc.bounds(), sel::rgba8_image(surf, d.doc.bounds()))
|
||||
};
|
||||
let region = sel::wand_region(&img, area, (x, y), tolerance, contiguous, anti_alias);
|
||||
// The reference's colour distance is measured for 8-bit RGB only (#11995).
|
||||
let rgb8 = s.active().is_some_and(|d| d.doc.mode == ColorMode::Rgb && d.doc.depth == SampleType::U8);
|
||||
let distance = if rgb8 { sel::ColorDistance::Spread } else { sel::ColorDistance::LargestChannel };
|
||||
let region = sel::wand_region_by(&img, area, (x, y), tolerance, contiguous, anti_alias, None, distance);
|
||||
drop(img);
|
||||
let Some(region) = region else { return Ok(damage(s, Rect::EMPTY, false)) };
|
||||
let bg = s.tools.background;
|
||||
@@ -137,6 +142,8 @@ fn background_eraser_setup(s: &Session, p: &Value) -> Result<(Stroke, BgEraseSet
|
||||
return Err(bad(CMD, "`points` must be finite canvas coordinates"));
|
||||
}
|
||||
let brush = crate::brush_cmds::resolve_brush(s, p, CMD)?;
|
||||
// The inks a colour was picked as, for a CMYK document (#12352).
|
||||
let picked = |c: [f32; 4]| s.tools.picked_cmyk([c[0], c[1], c[2]]).map(|k| ([c[0], c[1], c[2]], k));
|
||||
let bs = BgEraseSettings {
|
||||
sampling: enum_param(p, CMD, "sampling", Sampling::Continuous, "continuous|once|backgroundSwatch")?,
|
||||
limits: enum_param(p, CMD, "limits", Limits::Contiguous, "discontiguous|contiguous|findEdges")?,
|
||||
@@ -144,16 +151,17 @@ fn background_eraser_setup(s: &Session, p: &Value) -> Result<(Stroke, BgEraseSet
|
||||
protect_foreground: flag(p, "protectForegroundColor", false),
|
||||
foreground: s.tools.foreground,
|
||||
background: s.tools.background,
|
||||
foreground_cmyk: picked(s.tools.foreground),
|
||||
background_cmyk: picked(s.tools.background),
|
||||
};
|
||||
let id = active_pixel_layer(s, p, CMD)?;
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
// Lock transparent pixels is no refusal: the reference application erases to transparency
|
||||
// anyway and leaves the lock on.
|
||||
if let Some(e) = pixels_locked(&d.doc, l) {
|
||||
return Err(e);
|
||||
}
|
||||
if d.doc.effective_locks(id).transparency && !d.doc.is_background(id) && crate::color_channels::target(s, p)?.is_none() {
|
||||
return Err(EngineError::Other(format!("Could not use the Background Eraser because the transparency of layer \"{}\" is locked", l.name)));
|
||||
}
|
||||
Ok((Stroke { brush, points: pts }, bs, id))
|
||||
}
|
||||
|
||||
@@ -234,19 +242,27 @@ pub fn live_background_eraser(s: &Session, p: &Value) -> Result<crate::retouch_c
|
||||
if colors.is_none() {
|
||||
crate::extra_cmds::background_to_layer(&mut doc, id);
|
||||
}
|
||||
let stroke = background_eraser_stroke(&stroke);
|
||||
let mut stroke = background_eraser_stroke(&stroke);
|
||||
// The commit mixes back without the transparency lock (a locked layer is erased too, and a
|
||||
// channel target leaves alpha alone), so the preview does as well; the points go in once the
|
||||
// lock is off.
|
||||
let points = std::mem::take(&mut stroke.points);
|
||||
if let Some(colors) = colors {
|
||||
return crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({"target":colors.params()}), stroke, Some(id), 0, |pre| {
|
||||
let mut live = crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({"target":colors.params()}), stroke, Some(id), 0, |pre| {
|
||||
selected_background_effect(pre, &bs, colors, bg)
|
||||
})?
|
||||
.with_tail_preview();
|
||||
.unlocked();
|
||||
live.push(&points)?;
|
||||
return live.with_tail_preview();
|
||||
}
|
||||
crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({}), stroke, Some(id), 0, |pre| match background_eraser_effect(pre, &bs) {
|
||||
let mut live = crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({}), stroke, Some(id), 0, |pre| match background_eraser_effect(pre, &bs) {
|
||||
Some(effect) => Box::new(effect),
|
||||
// No alpha: the commit erases nothing either.
|
||||
None => Box::new(|_: &mut photocraft_paint::retouch::Region, _: &photocraft_paint::retouch::Footprint| {}),
|
||||
})?
|
||||
.with_tail_preview()
|
||||
.unlocked();
|
||||
live.push(&points)?;
|
||||
live.with_tail_preview()
|
||||
}
|
||||
|
||||
/// Eraser-group command specs.
|
||||
@@ -275,5 +291,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod magic_eraser_tolerance_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
#[path = "background_eraser_transparency_lock_tests.rs"]
|
||||
mod transparency_lock_tests;
|
||||
@@ -0,0 +1,239 @@
|
||||
//! #11995: on 8-bit RGB the Magic Eraser measures Tolerance by the spread of `{0, dR, dG, dB}`, so
|
||||
//! opposite changes in two channels count double. The expected values are the reference
|
||||
//! application's measurements from the issue; the stripes document is drawn at a tenth of the size.
|
||||
|
||||
use photocraft_algo::selection as sel;
|
||||
use photocraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const SEED: [u8; 3] = [200, 40, 40];
|
||||
/// `d` of the patch grid's columns.
|
||||
const GRID: [i32; 8] = [20, 50, 80, 110, 140, 170, 200, 230];
|
||||
|
||||
fn hex([r, g, b]: [u8; 3]) -> String {
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
|
||||
fn document(w: i32, h: i32, depth: u32, background: [u8; 3]) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": w, "height": h, "mode": "rgb", "depth": depth, "background": hex(background)})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn fill(s: &mut Session, [x, y, w, h]: [i32; 4], color: [u8; 3]) {
|
||||
s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h, "antiAlias": false})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": hex(color)})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
}
|
||||
|
||||
fn erase(s: &mut Session, x: i32, y: i32, options: Value) {
|
||||
let mut p = json!({"x": x, "y": y, "antiAlias": false});
|
||||
p.as_object_mut().unwrap().extend(options.as_object().unwrap().clone());
|
||||
s.execute("paint.magicEraser", p).unwrap();
|
||||
}
|
||||
|
||||
fn rgba(s: &Session, x: i32, y: i32) -> [f32; 4] {
|
||||
let d = s.active().unwrap();
|
||||
d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)
|
||||
}
|
||||
|
||||
fn erased(s: &Session, x: i32, y: i32) -> bool {
|
||||
rgba(s, x, y)[3] == 0.0
|
||||
}
|
||||
|
||||
/// Grey (100, 100, 100) with ten-pixel patches along the top: same-direction and opposite changes.
|
||||
fn grey_patches(depth: u32) -> (Session, [(i32, [u8; 3], i32); 4]) {
|
||||
let patches = [(10, [130, 100, 70], 60), (30, [130, 130, 100], 30), (50, [70, 130, 100], 60), (70, [70, 70, 70], 30)];
|
||||
let mut s = document(90, 30, depth, [100, 100, 100]);
|
||||
for (x, color, _) in patches {
|
||||
fill(&mut s, [x, 10, 10, 10], color);
|
||||
}
|
||||
(s, patches)
|
||||
}
|
||||
|
||||
/// Opposite changes count double and same-direction changes once (Tolerance 29, 30, 59, 60).
|
||||
#[test]
|
||||
fn opposite_channel_changes_count_double_around_a_grey_seed() {
|
||||
for tolerance in [29, 30, 59, 60] {
|
||||
let (mut s, patches) = grey_patches(8);
|
||||
erase(&mut s, 0, 0, json!({"tolerance": tolerance, "contiguous": false}));
|
||||
for (x, color, metric) in patches {
|
||||
assert_eq!(erased(&s, x + 5, 15), tolerance >= metric, "tolerance {tolerance}, patch {color:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn grid_colour(row: usize, d: i32) -> [u8; 3] {
|
||||
let [r, g, b] = SEED.map(i32::from);
|
||||
let [r, g, b] = match row {
|
||||
0 => [r - d, g, b],
|
||||
1 => [r + d, g, b],
|
||||
2 => [r, g + d, b],
|
||||
3 => [r, g + d, b + d],
|
||||
_ => [r - d, g + d, b + d],
|
||||
};
|
||||
[r, g, b].map(|v| v.clamp(0, 255) as u8)
|
||||
}
|
||||
|
||||
/// The issue's patch grid around (200, 40, 40): `0` is erased and `x` kept, one row per Tolerance.
|
||||
#[test]
|
||||
fn the_patch_grid_matches_the_measured_table() {
|
||||
const TABLE: [(i32, [&str; 5]); 7] = [
|
||||
(30, ["0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "xxxxxxxx"]),
|
||||
(40, ["0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "0xxxxxxx"]),
|
||||
(60, ["00xxxxxx", "00000000", "00xxxxxx", "00xxxxxx", "0xxxxxxx"]),
|
||||
(100, ["000xxxxx", "00000000", "000xxxxx", "000xxxxx", "00xxxxxx"]),
|
||||
(150, ["00000xxx", "00000000", "00000xxx", "00000xxx", "00xxxxxx"]),
|
||||
(200, ["00000000", "00000000", "0000000x", "0000000x", "000xxxxx"]),
|
||||
(255, ["00000000", "00000000", "00000000", "00000000", "0000xxxx"]),
|
||||
];
|
||||
for (tolerance, rows) in TABLE {
|
||||
let mut s = document(80, 60, 8, SEED);
|
||||
for row in 0..5 {
|
||||
for (col, d) in GRID.into_iter().enumerate() {
|
||||
fill(&mut s, [col as i32 * 10, 10 + row as i32 * 10, 10, 10], grid_colour(row, d));
|
||||
}
|
||||
}
|
||||
erase(&mut s, 0, 0, json!({"tolerance": tolerance, "contiguous": false}));
|
||||
for (row, want) in rows.into_iter().enumerate() {
|
||||
let got: String = (0..8).map(|col| if erased(&s, col * 10 + 5, 15 + row as i32 * 10) { '0' } else { 'x' }).collect();
|
||||
assert_eq!(got, want, "tolerance {tolerance}, row {row}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const RED: [u8; 3] = [220, 30, 30];
|
||||
const GREEN: [u8; 3] = [30, 180, 60];
|
||||
const BLUE: [u8; 3] = [40, 60, 220];
|
||||
const PINK: [u8; 3] = [240, 120, 120];
|
||||
const UPPER_RED: (i32, i32) = (10, 5);
|
||||
const LOWER_RED: (i32, i32) = (10, 22);
|
||||
const WHITE_GAP: (i32, i32) = (10, 15);
|
||||
|
||||
/// The stripes over eight blocks (200, 40 + 20·i, 40), with a white gap cutting the red stripe.
|
||||
fn stripes() -> Session {
|
||||
let mut s = document(80, 60, 8, [255, 255, 255]);
|
||||
for (i, color) in [RED, GREEN, BLUE, PINK].into_iter().enumerate() {
|
||||
fill(&mut s, [i as i32 * 20, 0, 20, 30], color);
|
||||
}
|
||||
fill(&mut s, [0, 14, 20, 2], [255, 255, 255]);
|
||||
for i in 0..8u8 {
|
||||
fill(&mut s, [i32::from(i) * 10, 30, 10, 30], [200, 40 + 20 * i, 40]);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn erased_blocks(s: &Session) -> usize {
|
||||
(0..8).take_while(|i| erased(s, i * 10 + 5, 45)).count()
|
||||
}
|
||||
|
||||
/// Contiguous from block 0: the blocks go one by one, and green and blue survive even at 255.
|
||||
#[test]
|
||||
fn stripes_contiguous_from_block_zero() {
|
||||
for (tolerance, blocks) in
|
||||
[(0, 1), (10, 1), (19, 1), (20, 2), (21, 2), (39, 2), (40, 3), (41, 3), (60, 4), (100, 6), (140, 8), (160, 8), (200, 8), (255, 8)]
|
||||
{
|
||||
let mut s = stripes();
|
||||
erase(&mut s, 5, 45, json!({"tolerance": tolerance}));
|
||||
assert_eq!(erased_blocks(&s), blocks, "tolerance {tolerance}");
|
||||
assert_eq!(8 - (0..8).filter(|i| !erased(&s, i * 10 + 5, 45)).count(), blocks, "tolerance {tolerance}: the erased blocks are consecutive");
|
||||
assert_eq!(erased(&s, 70, 15), tolerance >= 140, "tolerance {tolerance}: pink, reached through blocks 6 and 7");
|
||||
assert_eq!(erased(&s, UPPER_RED.0, UPPER_RED.1), tolerance == 255, "tolerance {tolerance}: upper red, reached through the white gap");
|
||||
if tolerance == 41 || tolerance >= 60 {
|
||||
assert!(erased(&s, LOWER_RED.0, LOWER_RED.1), "tolerance {tolerance}: lower red");
|
||||
}
|
||||
if tolerance < 30 {
|
||||
assert!(!erased(&s, LOWER_RED.0, LOWER_RED.1), "tolerance {tolerance}: lower red");
|
||||
}
|
||||
assert!(!erased(&s, 30, 15), "tolerance {tolerance}: green is kept");
|
||||
assert!(!erased(&s, 50, 15), "tolerance {tolerance}: blue is kept");
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-contiguous from block 0: white goes from Tolerance 220; green and blue never do.
|
||||
#[test]
|
||||
fn stripes_non_contiguous_from_block_zero() {
|
||||
let mut s = stripes();
|
||||
erase(&mut s, 5, 45, json!({"tolerance": 150, "contiguous": false}));
|
||||
assert_eq!(erased_blocks(&s), 8);
|
||||
assert!(erased(&s, UPPER_RED.0, UPPER_RED.1) && erased(&s, LOWER_RED.0, LOWER_RED.1), "both reds");
|
||||
assert!(erased(&s, 70, 15), "pink");
|
||||
assert!(!erased(&s, WHITE_GAP.0, WHITE_GAP.1), "the white gap (metric 215) is kept");
|
||||
assert!(!erased(&s, 30, 15) && !erased(&s, 50, 15), "green and blue");
|
||||
|
||||
let mut s = stripes();
|
||||
erase(&mut s, 5, 45, json!({"tolerance": 220, "contiguous": false}));
|
||||
assert!(erased(&s, WHITE_GAP.0, WHITE_GAP.1), "white is within 220");
|
||||
assert!(!erased(&s, 30, 15) && !erased(&s, 50, 15), "green and blue");
|
||||
}
|
||||
|
||||
/// The fringe uses the same distance: a neighbour the spread rejects is not fully erased, even
|
||||
/// though every one of its channels is within the Tolerance.
|
||||
#[test]
|
||||
fn anti_alias_does_not_erase_a_neighbour_the_spread_rejects() {
|
||||
let (mut s, _) = grey_patches(8);
|
||||
erase(&mut s, 0, 0, json!({"tolerance": 32, "contiguous": false, "antiAlias": true}));
|
||||
assert!(rgba(&s, 15, 15)[3] == 1.0, "the patch's inside is kept");
|
||||
assert!(rgba(&s, 10, 15)[3] > 0.0, "(130, 100, 70) has spread 60, past Tolerance 32");
|
||||
}
|
||||
|
||||
/// Depths the rule was not measured for keep comparing each channel on its own.
|
||||
#[test]
|
||||
fn sixteen_bit_keeps_the_per_channel_limit() {
|
||||
let (mut s, patches) = grey_patches(16);
|
||||
erase(&mut s, 0, 0, json!({"tolerance": 30, "contiguous": false}));
|
||||
for (x, color, _) in patches {
|
||||
assert!(erased(&s, x + 5, 15), "patch {color:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Magic Wand and the Paint Bucket share the fill and keep the per-channel limit.
|
||||
#[test]
|
||||
fn the_magic_wand_and_paint_bucket_keep_the_per_channel_limit() {
|
||||
let (mut s, _) = grey_patches(8);
|
||||
s.execute("select.magicWand", json!({"x": 0, "y": 0, "tolerance": 30, "contiguous": false, "antiAlias": false})).unwrap();
|
||||
let selected = sel::mask_from_surface(s.active().unwrap().doc.selection.as_ref(), Rect::new(0, 0, 90, 30));
|
||||
assert_eq!(selected[15 * 90 + 15], 1.0, "the wand takes (130, 100, 70) at 30");
|
||||
|
||||
let (mut s, _) = grey_patches(8);
|
||||
s.execute("paint.bucket", json!({"x": 0, "y": 0, "tolerance": 30, "contiguous": false, "antiAlias": false, "color": "#ff00ff"})).unwrap();
|
||||
let [r, g, b, _] = rgba(&s, 15, 15);
|
||||
assert_eq!([r, g, b], [1.0, 0.0, 1.0], "the bucket fills (130, 100, 70) at 30");
|
||||
}
|
||||
|
||||
/// A transparent seed still matches every transparent pixel, and alpha still limits the match.
|
||||
#[test]
|
||||
fn the_spread_keeps_the_transparent_and_alpha_handling() {
|
||||
let area = Rect::new(0, 0, 3, 1);
|
||||
let run = |img: [[u8; 4]; 3], tolerance| sel::wand_region_by(&img, area, (0, 0), tolerance, false, false, None, sel::ColorDistance::Spread).unwrap();
|
||||
|
||||
let region = run([[10, 20, 30, 0], [200, 0, 90, 0], [9, 9, 9, 255]], 0.0);
|
||||
assert_eq!((region.at(1, 0), region.at(2, 0)), (1.0, 0.0), "hidden colours don't matter; visible pixels don't match");
|
||||
|
||||
let half = [[100, 100, 100, 200], [100, 100, 100, 100], [100, 100, 100, 170]];
|
||||
let region = run(half, 30.0);
|
||||
assert_eq!((region.at(1, 0), region.at(2, 0)), (0.0, 1.0), "alpha differences stay limited by the Tolerance");
|
||||
}
|
||||
|
||||
/// The spread was measured on opaque colours only: a partly transparent seed or pixel keeps the
|
||||
/// per-channel limit, in the match and in the anti-alias fringe.
|
||||
#[test]
|
||||
fn partly_transparent_colours_keep_the_per_channel_limit() {
|
||||
let area = Rect::new(0, 0, 3, 1);
|
||||
let run = |img: &[[u8; 4]; 3], distance, anti_alias| sel::wand_region_by(img, area, (0, 0), 30.0, false, anti_alias, None, distance).unwrap();
|
||||
|
||||
let opaque = [[100, 100, 100, 255], [130, 100, 70, 255], [9, 9, 9, 255]];
|
||||
assert_eq!(run(&opaque, sel::ColorDistance::Spread, false).at(1, 0), 0.0, "opaque colours use the spread");
|
||||
|
||||
for img in [
|
||||
[[100, 100, 100, 128], [130, 100, 70, 128], [160, 100, 40, 128]],
|
||||
[[100, 100, 100, 255], [130, 100, 70, 250], [160, 100, 40, 250]],
|
||||
[[100, 100, 100, 250], [130, 100, 70, 255], [160, 100, 40, 255]],
|
||||
] {
|
||||
assert_eq!(run(&img, sel::ColorDistance::Spread, false).at(1, 0), 1.0, "{img:?}: every channel is within 30");
|
||||
assert!(run(&img, sel::ColorDistance::Spread, true).at(2, 0) > 0.0, "{img:?}: the third pixel gets a fringe");
|
||||
assert_eq!(run(&img, sel::ColorDistance::Spread, true), run(&img, sel::ColorDistance::LargestChannel, true), "{img:?}: same fringe");
|
||||
}
|
||||
}
|
||||
@@ -215,6 +215,55 @@ fn background_eraser_options() {
|
||||
assert_eq!(alpha(&s, 6, 20), 1.0);
|
||||
}
|
||||
|
||||
/// #12352: in a CMYK document, Protect Foreground Color and Sampling Background Swatch compare
|
||||
/// against the inks the colour was picked as, not what its sRGB stand-in converts back to.
|
||||
#[test]
|
||||
fn background_eraser_compares_against_picked_cmyk_inks() {
|
||||
const STAND_IN: &str = "#00aeef";
|
||||
const CYAN: [f32; 4] = [1.0, 0.0, 0.0, 0.0];
|
||||
let cyan_square = |key: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 48, "mode": "cmyk", "depth": 8})).unwrap();
|
||||
s.execute("tools.setColors", json!({key: STAND_IN, format!("{key}Cmyk"): CYAN})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20, "antiAlias": false})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": STAND_IN})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
assert_eq!(surface(&s).pixel(20, 20)[..4], CYAN, "the square holds the picked inks");
|
||||
s
|
||||
};
|
||||
let stroke = |extra: Value| {
|
||||
let mut p = json!({"points": [[4, 20], [40, 20]], "size": 16, "hardness": 1, "limits": "discontiguous", "tolerance": 1});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
p
|
||||
};
|
||||
let mut s = cyan_square("foreground");
|
||||
s.execute("paint.backgroundEraser", stroke(json!({"sampling": "continuous", "protectForegroundColor": true}))).unwrap();
|
||||
assert_eq!(alpha(&s, 20, 20), 1.0, "the foreground's inks are protected");
|
||||
assert_eq!(alpha(&s, 6, 20), 0.0, "white erased");
|
||||
let mut s = cyan_square("background");
|
||||
s.execute("paint.backgroundEraser", stroke(json!({"sampling": "backgroundSwatch"}))).unwrap();
|
||||
assert_eq!(alpha(&s, 20, 20), 0.0, "the background's inks are erased fully");
|
||||
assert_eq!(alpha(&s, 6, 20), 1.0, "white kept");
|
||||
// Other modes ignore the picked inks: the stand-in is compared as it always was.
|
||||
for mode in ["rgb", "gray", "lab"] {
|
||||
let run = |cmyk: bool| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 48, "mode": mode, "depth": 8})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20, "antiAlias": false})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": STAND_IN})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
let picks = if cmyk { json!({"foregroundCmyk": CYAN, "backgroundCmyk": CYAN}) } else { json!({}) };
|
||||
let mut colors = json!({"foreground": STAND_IN, "background": STAND_IN});
|
||||
colors.as_object_mut().unwrap().extend(picks.as_object().unwrap().clone());
|
||||
s.execute("tools.setColors", colors).unwrap();
|
||||
s.execute("paint.backgroundEraser", stroke(json!({"sampling": "continuous", "protectForegroundColor": true}))).unwrap();
|
||||
s.execute("paint.backgroundEraser", stroke(json!({"points": [[4, 30], [40, 30]], "sampling": "backgroundSwatch"}))).unwrap();
|
||||
surface(&s).clone()
|
||||
};
|
||||
assert!(run(true) == run(false), "{mode}: a CMYK pick changes nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_eraser_fails_gracefully() {
|
||||
let mut s = session("rgb", 8);
|
||||
@@ -230,11 +279,11 @@ fn background_eraser_fails_gracefully() {
|
||||
] {
|
||||
assert!(s.execute("paint.backgroundEraser", p.clone()).is_err(), "{p}");
|
||||
}
|
||||
// A normal layer with locked transparency is refused.
|
||||
// A layer with locked pixels is refused.
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
s.edit("lock", |doc, _| {
|
||||
doc.layer_mut(id).unwrap().locks.transparency = true;
|
||||
doc.layer_mut(id).unwrap().locks.pixels = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
@@ -319,7 +368,7 @@ fn live_background_eraser_matches_the_commit() {
|
||||
fn live_background_eraser_refuses_what_the_command_refuses() {
|
||||
let mut s = session("rgb", 8);
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
|
||||
s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap();
|
||||
let p = json!({"points": [[20, 20]]});
|
||||
assert!(live_background_eraser(&s, &p).is_err());
|
||||
assert!(s.execute("paint.backgroundEraser", p).is_err());
|
||||
|
||||
@@ -74,13 +74,9 @@ pub(crate) fn step_key(s: &Session, what: &str) -> String {
|
||||
/// area, the pixels, and the selection coverage per pixel; results are blended back by coverage,
|
||||
/// and transparency stays locked when the layer locks it. When `p` targets an alpha channel, the
|
||||
/// Quick Mask or the layer mask (`Session::execute` fills that in from the Channels panel), that
|
||||
/// grayscale surface is rewritten instead, as the core filters do (#935).
|
||||
fn map_pixels(s: &mut Session, label: &str, p: &Value, f: impl FnOnce(Rect, &mut [[f32; 4]], &[f32])) -> Result<Value> {
|
||||
map_pixels_in(s, label, p, false, f)
|
||||
}
|
||||
|
||||
/// [`map_pixels`], or with `whole` the whole canvas: `f` still gets the selection coverage, and
|
||||
/// every pixel takes its result in full.
|
||||
/// grayscale surface is rewritten instead, as the core filters do (#935). With `whole` the whole
|
||||
/// canvas is rewritten: `f` still gets the selection coverage, and every pixel takes its result
|
||||
/// in full.
|
||||
fn map_pixels_in(s: &mut Session, label: &str, p: &Value, whole: bool, f: impl FnOnce(Rect, &mut [[f32; 4]], &[f32])) -> Result<Value> {
|
||||
let id = layer_param(s, p)?;
|
||||
let channel = crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels;
|
||||
@@ -275,37 +271,46 @@ fn equalize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Filter › Blur › Average: the selection (or layer) filled with its mean colour.
|
||||
fn average(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
map_pixels(s, "Average", p, |_, px, cover| {
|
||||
let (mut sum, mut wsum, mut asum, mut n) = ([0f64; 3], 0f64, 0f64, 0f64);
|
||||
for (p, &k) in px.iter().zip(cover) {
|
||||
let w = (p[3] * k) as f64;
|
||||
for c in 0..3 {
|
||||
sum[c] += p[c] as f64 * w;
|
||||
}
|
||||
wsum += w;
|
||||
asum += (p[3] * k) as f64;
|
||||
n += k as f64;
|
||||
}
|
||||
if wsum <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let avg = [(sum[0] / wsum) as f32, (sum[1] / wsum) as f32, (sum[2] / wsum) as f32, (asum / n.max(1e-9)) as f32];
|
||||
px.fill(avg);
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- transform presets ----------
|
||||
|
||||
/// The presets' params: like Free Transform, they follow the Channels and Layers panel target.
|
||||
const TRANSFORM_TARGET: &str =
|
||||
r#"{"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask turns alone)}"#;
|
||||
const TRANSFORM_TARGET: &str = r#"{"target":"pixels"|"mask"|"vectorMask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, a vector mask, an alpha channel or the Quick Mask turns alone)}"#;
|
||||
|
||||
/// The active layer's vector mask when the target names it, with its path's control bounds.
|
||||
/// The path tools' Free Transform and `path.transform` reuse those bounds, so a flip mirrors
|
||||
/// anchors and Bézier handles about the same box (#12283).
|
||||
fn targeted_vector_mask(s: &Session, p: &Value) -> Result<Option<(LayerId, [f64; 4])>> {
|
||||
let explicit = p.get("target").and_then(Value::as_str) == Some("vectorMask");
|
||||
let panel = p.get("target").is_none() && s.active().is_some_and(|d| d.channel_view.target == crate::channel_cmds::ChannelTarget::VectorMask);
|
||||
if !explicit && !panel {
|
||||
return Ok(None);
|
||||
}
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?;
|
||||
let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
let vm = l.vector_mask.as_ref().ok_or_else(|| EngineError::Other("the active layer has no vector mask".into()))?;
|
||||
let (x0, y0, x1, y1) = vm.path.control_bounds().ok_or_else(|| EngineError::Other("nothing to transform".into()))?;
|
||||
Ok(Some((id, [x0, y0, x1, y1])))
|
||||
}
|
||||
|
||||
/// Flips and turns about the centre of the box Free Transform would open: with a selection
|
||||
/// limiting the transform it is the selection's own bounds, as in Photoshop, so Select All
|
||||
/// mirrors across the canvas (#6928); otherwise the content's bounds.
|
||||
fn transform_preset(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
|
||||
// A targeted vector mask turns its own path, not the layer's pixels (and whether or not the
|
||||
// mask is linked): reuse `path.transform` for its geometry and History step.
|
||||
if let Some((id, [x0, y0, x1, y1])) = targeted_vector_mask(s, p)? {
|
||||
let (sx, sy) = (x0 + x1, y0 + y1);
|
||||
let (cx, cy) = (sx / 2.0, sy / 2.0);
|
||||
let m: [f64; 6] = match kind {
|
||||
"rotate180" => [-1.0, 0.0, 0.0, -1.0, sx, sy],
|
||||
"rotate90Cw" => [0.0, 1.0, -1.0, 0.0, cx + cy, cy - cx],
|
||||
"rotate90Ccw" => [0.0, -1.0, 1.0, 0.0, cx - cy, cx + cy],
|
||||
"flipHorizontal" => [-1.0, 0.0, 0.0, 1.0, sx, 0.0],
|
||||
_ => [1.0, 0.0, 0.0, -1.0, 0.0, sy],
|
||||
};
|
||||
return s.execute("path.transform", json!({"name": "layer", "layer": id.0, "vectorMask": true, "matrix": m}));
|
||||
}
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
// A targeted alpha channel, the Quick Mask or an unlinked layer mask turns by itself (#2835).
|
||||
let (b, mut params) = match crate::transform_cmds::lone_target(&d.doc, d.active_layer, p)? {
|
||||
@@ -402,7 +407,6 @@ fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result<Value> {
|
||||
let key = step_key(s, "pasteInto");
|
||||
params["coalesce"] = json!(key);
|
||||
params["target"] = json!("pixels");
|
||||
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
|
||||
let r = s.execute("edit.paste", params)?;
|
||||
let id = layer_param(s, &Value::Null)?;
|
||||
s.execute("layer.layerMask.revealAll", json!({"layer": id.0, "coalesce": key}))?;
|
||||
@@ -413,9 +417,9 @@ fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result<Value> {
|
||||
Ok(())
|
||||
});
|
||||
s.coalesce_request = None;
|
||||
// Three revisions: `Session::dispatch` reports what the whole command changed, so only where
|
||||
// the masked paste draws is recomposited (#2901).
|
||||
r2?;
|
||||
// Only where the masked paste draws needs recompositing (#2901).
|
||||
crate::layer_multi_cmds::note_insert(s, &before);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -1119,7 +1123,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_layer,
|
||||
show_only
|
||||
),
|
||||
spec!("filter.blur.average", "Average", &["Filter", "Blur"], None, "{}", has_pixels, average),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ fn equalize_average_and_clouds_edit_the_targeted_channel() {
|
||||
s.tools.foreground = [0.0, 0.0, 0.0, 1.0];
|
||||
s.tools.background = [1.0, 1.0, 1.0, 1.0];
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
|
||||
let p = match target {
|
||||
let mut p = match target {
|
||||
"quickMask" => {
|
||||
s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
|
||||
json!({"seed": 1})
|
||||
@@ -39,6 +39,10 @@ fn equalize_average_and_clouds_edit_the_targeted_channel() {
|
||||
json!({"seed": 1, "target": "mask"})
|
||||
}
|
||||
};
|
||||
// Average has no seed parameter; only Clouds uses it.
|
||||
if cmd == "filter.blur.average" {
|
||||
p.as_object_mut().unwrap().remove("seed");
|
||||
}
|
||||
// Two levels in the target, so Equalize and Average have something to change.
|
||||
let edit_target = json!({ "target": if target == "alpha" { json!({"channel": 0}) } else { json!(target) } });
|
||||
s.edit("levels", |doc, active| {
|
||||
@@ -65,6 +69,18 @@ fn equalize_average_and_clouds_edit_the_targeted_channel() {
|
||||
let case = format!("{cmd} on {target} at {depth}");
|
||||
assert_eq!(layer1, layer0, "{case}: the layer is untouched");
|
||||
assert_ne!(target1, target0, "{case}: the target changed");
|
||||
if cmd == "filter.blur.average" {
|
||||
// The equal-sized halves contribute equally, using their stored sample values.
|
||||
let mean = (f64::from(target0[0]) + f64::from(target0[20])) / 2.0;
|
||||
let tolerance = match depth {
|
||||
8 => 1.0 / 255.0,
|
||||
16 => 1.0 / 65535.0,
|
||||
_ => 1e-6,
|
||||
};
|
||||
for value in &target1 {
|
||||
assert!((f64::from(*value) - mean).abs() <= tolerance, "{case}: {value}, expected {mean}");
|
||||
}
|
||||
}
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{case}");
|
||||
s.undo();
|
||||
assert_eq!(read(&s).1, target0, "{case}: undo restores the target");
|
||||
@@ -449,6 +465,251 @@ fn transform_presets_turn_about_the_selection() {
|
||||
assert_eq!(s.active().unwrap().doc.channels[0].surface.content_bounds(), Rect::new(20, 10, 30, 20));
|
||||
}
|
||||
|
||||
/// A two-knot path whose Bézier handles reach past its anchors on every side, so a flip about
|
||||
/// the anchors' bounds and one about the control bounds differ.
|
||||
fn asymmetric_vector_path() -> photocraft_doc::Path {
|
||||
use photocraft_doc::{Knot, Path, Subpath};
|
||||
use photocraft_geom::Point;
|
||||
Path::new(vec![Subpath {
|
||||
closed: false,
|
||||
knots: vec![
|
||||
Knot { anchor: Point::new(10.0, 20.0), in_ctrl: Point::new(8.0, 18.0), out_ctrl: Point::new(12.0, 22.0), smooth: false },
|
||||
Knot { anchor: Point::new(30.0, 30.0), in_ctrl: Point::new(28.0, 28.0), out_ctrl: Point::new(34.0, 34.0), smooth: false },
|
||||
],
|
||||
op: photocraft_doc::PathOp::Combine,
|
||||
}])
|
||||
}
|
||||
|
||||
fn vector_mask_session(linked: bool, path: photocraft_doc::Path) -> (Session, LayerId) {
|
||||
let mut s = session(8);
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
s.edit("vector mask", |doc, _| {
|
||||
doc.layer_mut(id).unwrap().vector_mask = Some(photocraft_doc::VectorMask { linked, ..photocraft_doc::VectorMask::new(path) });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn mask_path(s: &Session, id: LayerId) -> photocraft_doc::Path {
|
||||
s.active().unwrap().doc.layer(id).unwrap().vector_mask.as_ref().unwrap().path.clone()
|
||||
}
|
||||
|
||||
/// #12283: a targeted vector mask flips its own path about the path's control bounds (anchors and
|
||||
/// handles), on a layer with no pixels, whether the mask is linked or unlinked.
|
||||
#[test]
|
||||
fn transform_presets_flip_a_targeted_vector_mask_about_its_control_bounds() {
|
||||
use photocraft_geom::Point;
|
||||
let xy = |p: Point| (p.x, p.y);
|
||||
for linked in [true, false] {
|
||||
let (mut s, id) = vector_mask_session(linked, asymmetric_vector_path());
|
||||
let before = mask_path(&s, id);
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
s.execute("edit.transform.flipHorizontal", json!({"target": "vectorMask"})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one Transform Path step, linked {linked}");
|
||||
let flipped = mask_path(&s, id);
|
||||
let k = &flipped.subpaths[0].knots;
|
||||
// Bounds are x 8..34, so x' = 42 - x.
|
||||
assert_eq!(xy(k[0].anchor), (32.0, 20.0));
|
||||
assert_eq!(xy(k[0].in_ctrl), (34.0, 18.0));
|
||||
assert_eq!(xy(k[0].out_ctrl), (30.0, 22.0));
|
||||
assert_eq!(xy(k[1].anchor), (12.0, 30.0));
|
||||
assert_eq!(xy(k[1].in_ctrl), (14.0, 28.0));
|
||||
assert_eq!(xy(k[1].out_ctrl), (8.0, 34.0));
|
||||
assert!(s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds().is_empty(), "the empty pixel layer stays empty");
|
||||
// Undo restores the path exactly, redo puts the flip back.
|
||||
s.undo();
|
||||
assert_eq!(mask_path(&s, id), before, "undo");
|
||||
s.redo();
|
||||
assert_eq!(mask_path(&s, id), flipped, "redo");
|
||||
s.undo();
|
||||
// Bounds are y 18..34, so y' = 52 - y.
|
||||
s.execute("edit.transform.flipVertical", json!({"target": "vectorMask"})).unwrap();
|
||||
let k = &mask_path(&s, id).subpaths[0].knots;
|
||||
assert_eq!(xy(k[0].anchor), (10.0, 32.0));
|
||||
assert_eq!(xy(k[0].in_ctrl), (8.0, 34.0));
|
||||
assert_eq!(xy(k[0].out_ctrl), (12.0, 30.0));
|
||||
assert_eq!(xy(k[1].anchor), (30.0, 22.0));
|
||||
assert_eq!(xy(k[1].in_ctrl), (28.0, 24.0));
|
||||
assert_eq!(xy(k[1].out_ctrl), (34.0, 18.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Fractional path centers must not be rounded to the pixel grid, and clockwise and
|
||||
/// counterclockwise presets must move every anchor and handle in the expected direction.
|
||||
#[test]
|
||||
fn transform_presets_rotate_vector_masks_about_fractional_control_bounds() {
|
||||
let path = asymmetric_vector_path().transform(&photocraft_geom::Affine::translate(0.25, 0.5));
|
||||
assert_eq!(path.control_bounds(), Some((8.25, 18.5, 34.25, 34.5)));
|
||||
let cases = [
|
||||
("rotate180", [[(32.25, 32.5), (34.25, 34.5), (30.25, 30.5)], [(12.25, 22.5), (14.25, 24.5), (8.25, 18.5)]]),
|
||||
("rotate90Cw", [[(27.25, 15.5), (29.25, 13.5), (25.25, 17.5)], [(17.25, 35.5), (19.25, 33.5), (13.25, 39.5)]]),
|
||||
("rotate90Ccw", [[(15.25, 37.5), (13.25, 39.5), (17.25, 35.5)], [(25.25, 17.5), (23.25, 19.5), (29.25, 13.5)]]),
|
||||
];
|
||||
for linked in [true, false] {
|
||||
for (kind, expected) in cases {
|
||||
let (mut s, id) = vector_mask_session(linked, path.clone());
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
s.execute(&format!("edit.transform.{kind}"), json!({"target": "vectorMask"})).unwrap();
|
||||
let after = mask_path(&s, id);
|
||||
let actual: Vec<_> =
|
||||
after.subpaths[0].knots.iter().map(|k| [(k.anchor.x, k.anchor.y), (k.in_ctrl.x, k.in_ctrl.y), (k.out_ctrl.x, k.out_ctrl.y)]).collect();
|
||||
assert_eq!(actual, expected, "{kind}, linked {linked}");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one history step");
|
||||
s.undo();
|
||||
assert_eq!(mask_path(&s, id), path, "undo {kind}");
|
||||
s.redo();
|
||||
assert_eq!(mask_path(&s, id), after, "redo {kind}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The explicit path route must not let presets or direct path commands edit a vector mask
|
||||
/// through Lock All, including when that lock comes from a containing group.
|
||||
#[test]
|
||||
fn targeted_vector_mask_transforms_respect_layer_and_group_lock_all() {
|
||||
for inherited in [false, true] {
|
||||
let (mut s, id) = vector_mask_session(true, asymmetric_vector_path());
|
||||
let lock_id = if inherited {
|
||||
let group = LayerId(s.execute("layer.groupLayers", json!({"layer": id.0})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.execute("layer.select", json!({"layer": id.0})).unwrap();
|
||||
group
|
||||
} else {
|
||||
id
|
||||
};
|
||||
s.edit("Lock All", |doc, _| {
|
||||
doc.layer_mut(lock_id).unwrap().locks.all = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
for kind in ["flipHorizontal", "flipVertical", "rotate180", "rotate90Cw", "rotate90Ccw"] {
|
||||
let err = s.execute(&format!("edit.transform.{kind}"), json!({"target": "vectorMask"})).unwrap_err();
|
||||
assert!(err.to_string().contains("locked"), "{kind}: {err}");
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past);
|
||||
}
|
||||
for vector_mask in [true, false] {
|
||||
let err = s.execute("path.transform", json!({"name": "layer", "layer": id.0, "vectorMask": vector_mask, "translateX": 1})).unwrap_err();
|
||||
assert!(err.to_string().contains("locked"), "{err}");
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past);
|
||||
}
|
||||
|
||||
s.edit("Lock Pixels Only", |doc, _| {
|
||||
let locks = &mut doc.layer_mut(lock_id).unwrap().locks;
|
||||
locks.all = false;
|
||||
locks.pixels = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("edit.transform.flipHorizontal", json!({"target": "vectorMask"})).unwrap();
|
||||
assert_ne!(mask_path(&s, id), asymmetric_vector_path(), "pixel-only locks permit mask edits");
|
||||
}
|
||||
}
|
||||
|
||||
/// #12283: a shape layer's path is its content, but it can also carry a separate vector mask. A
|
||||
/// targeted flip moves only the mask; the shape's path and rendered cache stay as they were.
|
||||
#[test]
|
||||
fn a_targeted_vector_mask_on_a_shape_layer_leaves_the_shape_path_and_cache_alone() {
|
||||
let mut s = session(8);
|
||||
let id = LayerId(s.execute("shape.create", json!({"kind": "rect", "rect": [2, 2, 20, 20], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.edit("vector mask", |doc, _| {
|
||||
doc.layer_mut(id).unwrap().vector_mask = Some(photocraft_doc::VectorMask::new(asymmetric_vector_path()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (shape_path, shape_cache) = match &doc(&s).layer(id).unwrap().content {
|
||||
LayerContent::Shape(sh) => (sh.path.clone(), sh.cache.clone()),
|
||||
_ => panic!("a shape layer"),
|
||||
};
|
||||
let mask_before = mask_path(&s, id);
|
||||
assert!(shape_cache.is_some(), "the shape is rendered");
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
|
||||
s.execute("edit.transform.flipHorizontal", json!({"target": "vectorMask"})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one Transform Path step");
|
||||
let LayerContent::Shape(sh) = &doc(&s).layer(id).unwrap().content else { panic!("still a shape layer") };
|
||||
assert_eq!(sh.path, shape_path, "the shape's path is untouched");
|
||||
assert_eq!(sh.cache, shape_cache, "the shape's cache is untouched");
|
||||
let mask_after = mask_path(&s, id);
|
||||
assert_ne!(mask_after, mask_before, "the vector mask moved");
|
||||
assert_eq!((mask_after.subpaths[0].knots[0].anchor.x, mask_after.subpaths[0].knots[0].anchor.y), (32.0, 20.0), "about the mask's bounds");
|
||||
|
||||
s.undo();
|
||||
assert_eq!(mask_path(&s, id), mask_before, "undo restores the mask");
|
||||
let LayerContent::Shape(sh) = &doc(&s).layer(id).unwrap().content else { panic!("still a shape layer") };
|
||||
assert_eq!((sh.path.clone(), sh.cache.clone()), (shape_path, shape_cache), "and leaves the shape alone");
|
||||
s.redo();
|
||||
assert_eq!(mask_path(&s, id), mask_after, "redo flips the mask again");
|
||||
}
|
||||
|
||||
/// The Channels panel's vector-mask target reaches the presets through the engine's target
|
||||
/// injection, without an explicit `target` param.
|
||||
#[test]
|
||||
fn the_channels_panel_vector_mask_target_routes_the_presets() {
|
||||
let (mut s, id) = vector_mask_session(true, asymmetric_vector_path());
|
||||
s.execute("channel.target", json!({"channel": "vectorMask"})).unwrap();
|
||||
s.execute("edit.transform.flipHorizontal", json!({})).unwrap();
|
||||
let k = &mask_path(&s, id).subpaths[0].knots;
|
||||
assert_eq!((k[0].anchor.x, k[0].anchor.y), (32.0, 20.0));
|
||||
}
|
||||
|
||||
/// A targeted vector mask turns alone: the layer's pixels do not move, even when it has some.
|
||||
#[test]
|
||||
fn a_targeted_vector_mask_flip_leaves_layer_pixels_alone() {
|
||||
let mut s = session(8);
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
paint_square(&mut s, Rect::new(2, 2, 6, 6), [1.0, 0.0, 0.0, 1.0]);
|
||||
s.edit("vector mask", |doc, _| {
|
||||
doc.layer_mut(id).unwrap().vector_mask = Some(photocraft_doc::VectorMask::new(asymmetric_vector_path()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = active(&s).surface().unwrap().read_region(Rect::new(0, 0, 40, 30));
|
||||
s.execute("edit.transform.flipHorizontal", json!({"target": "vectorMask"})).unwrap();
|
||||
let after = active(&s).surface().unwrap().read_region(Rect::new(0, 0, 40, 30));
|
||||
assert_eq!(after, before, "the pixels are untouched");
|
||||
assert_eq!(pixel(&s, 2, 2), vec![1.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
/// A whole-layer preset still carries a linked vector mask and leaves an unlinked one in place.
|
||||
#[test]
|
||||
fn a_whole_layer_flip_carries_only_a_linked_vector_mask() {
|
||||
for linked in [true, false] {
|
||||
let mut s = session(8);
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
paint_square(&mut s, Rect::new(2, 2, 6, 6), [1.0, 0.0, 0.0, 1.0]);
|
||||
s.edit("vector mask", |doc, _| {
|
||||
doc.layer_mut(id).unwrap().vector_mask = Some(photocraft_doc::VectorMask { linked, ..photocraft_doc::VectorMask::new(asymmetric_vector_path()) });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = mask_path(&s, id);
|
||||
s.execute("edit.transform.flipHorizontal", json!({})).unwrap();
|
||||
let after = mask_path(&s, id);
|
||||
if linked {
|
||||
assert_ne!(after, before, "a linked vector mask moves with its layer");
|
||||
} else {
|
||||
assert_eq!(after, before, "an unlinked vector mask stays put");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty targeted vector mask is refused before anything is recorded, so history is unchanged.
|
||||
#[test]
|
||||
fn an_empty_targeted_vector_mask_refuses_without_history() {
|
||||
let (mut s, id) = vector_mask_session(true, photocraft_doc::Path::default());
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
let err = s.execute("edit.transform.flipHorizontal", json!({"target": "vectorMask"})).unwrap_err();
|
||||
assert!(err.to_string().contains("nothing to transform"), "{err}");
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past);
|
||||
assert!(s.active().unwrap().doc.layer(id).unwrap().vector_mask.as_ref().unwrap().path.subpaths.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reselect_restores_the_last_selection() {
|
||||
let mut s = session(8);
|
||||
@@ -556,6 +817,52 @@ fn clouds_in_a_selection_are_the_canvas_clouds() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn average_preserves_transparency_and_averages_hidden_colours() {
|
||||
// Photoshop 26.6.1, RGB8 PNG with opaque red and transparent blue halves:
|
||||
// Average produces (128, 0, 128), retaining each pixel's original alpha.
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = session(depth);
|
||||
paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]);
|
||||
paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 0.0]);
|
||||
let bounds = Rect::new(0, 0, 40, 30);
|
||||
let before = active(&s).surface().unwrap().read_region(bounds);
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
s.execute("filter.blur.average", json!({})).unwrap();
|
||||
let after = active(&s).surface().unwrap().read_region(bounds);
|
||||
for (old, new) in before.as_chunks::<4>().0.iter().zip(after.as_chunks::<4>().0) {
|
||||
assert_eq!(new[3], old[3], "depth {depth}: Average must preserve alpha");
|
||||
assert!((new[0] - 0.5).abs() < 0.003 && new[1] == 0.0 && (new[2] - 0.5).abs() < 0.003, "{depth}: {new:?}");
|
||||
}
|
||||
assert_eq!(s.active().unwrap().history.past_len(), steps + 1);
|
||||
s.undo();
|
||||
assert_eq!(active(&s).surface().unwrap().read_region(bounds), before);
|
||||
s.redo();
|
||||
assert_eq!(active(&s).surface().unwrap().read_region(bounds), after);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn average_preserves_partial_alpha_and_pixels_outside_selection() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = session(depth);
|
||||
paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 0.25]);
|
||||
paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 0.75]);
|
||||
s.execute("select.rect", json!({"x": 10, "y": 0, "width": 15, "height": 30})).unwrap();
|
||||
let before: Vec<_> = (0..40).map(|x| pixel(&s, x, 15)).collect();
|
||||
s.execute("filter.blur.average", json!({})).unwrap();
|
||||
for x in 0..40 {
|
||||
let p = pixel(&s, x, 15);
|
||||
assert_eq!(p[3], before[x as usize][3], "depth {depth}, x {x}");
|
||||
if (10..25).contains(&x) {
|
||||
assert!((p[0] - 2.0 / 3.0).abs() < 0.003 && (p[2] - 1.0 / 3.0).abs() < 0.003, "{depth}: {p:?}");
|
||||
} else {
|
||||
assert_eq!(p, before[x as usize]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn average_and_clouds() {
|
||||
let mut s = session(8);
|
||||
|
||||
@@ -24,6 +24,7 @@ mod batch_run;
|
||||
mod export;
|
||||
mod info;
|
||||
mod open;
|
||||
mod open_as_smart_object;
|
||||
mod paths;
|
||||
mod place_steps;
|
||||
mod processing;
|
||||
@@ -50,6 +51,8 @@ pub(crate) use open::{BatchOpen, batch_open_notice, batch_open_params, remember_
|
||||
pub use open::{PLACE_EMBEDDED, open_bytes_as, open_bytes_as_with_options, place_bytes, raw_defaults};
|
||||
pub(crate) use open::{PlaceInput, apply_place, import, import_with_options, tag_exr_colorspace};
|
||||
use open::{approve_memory, close_all, close_others, open_as, place, revert};
|
||||
pub use open_as_smart_object::admit_as_smart_object;
|
||||
use open_as_smart_object::open_as_smart_object;
|
||||
use paths::is_file;
|
||||
#[cfg(test)]
|
||||
use paths::openable_name;
|
||||
@@ -285,6 +288,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
native,
|
||||
open_as
|
||||
),
|
||||
spec!(
|
||||
"file.openAsSmartObject",
|
||||
"Open as Smart Object…",
|
||||
&["File"],
|
||||
None,
|
||||
r##"{"path":str,"confirmDamage":bool=false (a damaged PSD waits for an answer, as File > Open's does)} (opens the file as a new untitled document named "<file name without its last extension>-N" with the file's size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer named after the file) → {document, docId, name, layer, warnings, color, smartObject} (or {held, name, warnings, color, damaged, smartObject} while a prompt waits)"##,
|
||||
native,
|
||||
open_as_smart_object
|
||||
),
|
||||
// One-shot permission for one file, not something to replay later: never journaled or
|
||||
// recorded in an action, since replaying it in another session/on another file would
|
||||
// grant memory use nobody approved (#10897). It also releases the queued source on both
|
||||
@@ -421,6 +433,10 @@ mod tests;
|
||||
#[path = "file_cmds/place_job_tests.rs"]
|
||||
mod place_job_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "file_cmds/open_as_smart_object_tests.rs"]
|
||||
mod open_as_smart_object_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod aces_exr_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -74,9 +74,15 @@ fn import_result(name: &str, bytes: &[u8]) -> Result<photocraft_io::ImportResult
|
||||
/// The one import path every caller shares: allocation checkpoint, native `.pcraft` and format
|
||||
/// dispatch through `photocraft_io::import_with_options`, typed memory refusals, and the
|
||||
/// preview-only refusal wherever the import came from.
|
||||
fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<photocraft_io::ImportResult> {
|
||||
pub(super) fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<photocraft_io::ImportResult> {
|
||||
import_result_for_open(name, bytes, opts).map(|(r, _)| r)
|
||||
}
|
||||
|
||||
/// [`import_result_with`], also telling whether a PSD/PSB had damaged data it recovered from, as
|
||||
/// File › Open's job learns it (`photocraft_io::import_for_open`), so an interactive caller can ask.
|
||||
pub(super) fn import_result_for_open(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<(photocraft_io::ImportResult, bool)> {
|
||||
crate::allocation::checkpoint("importing document")?;
|
||||
let r = photocraft_io::import_with_options(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?;
|
||||
let (r, damaged) = photocraft_io::import_for_open(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?;
|
||||
// Auxiliary imports return only a document and cannot surface the preview's fidelity warning.
|
||||
// Open has its own warning-preserving path; never silently place or process a thumbnail.
|
||||
if r.preview_only {
|
||||
@@ -84,7 +90,7 @@ fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOpti
|
||||
"{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here"
|
||||
)));
|
||||
}
|
||||
Ok(r)
|
||||
Ok((r, damaged))
|
||||
}
|
||||
|
||||
// ---------- close / revert / save a copy / open as ----------
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
//! File › Open as Smart Object… (#11678): a file opens as a new untitled document with the file's
|
||||
//! size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer.
|
||||
//!
|
||||
//! The layer is built as File › Place Embedded builds one (an embedded smart object at the file's own
|
||||
//! size and position `0, 0`) and put into the document before it is admitted, so the opening
|
||||
//! snapshot already shows it.
|
||||
|
||||
use super::open::import_result_for_open;
|
||||
use super::paths::{file_name, read_file, stem, untitled_name};
|
||||
use super::{Affine, Arc, Document, Layer, LayerContent, Result, Session, SmartObject, SmartSource, Value, flattened_checked, json, str_param};
|
||||
use crate::layer_place::Place;
|
||||
|
||||
const CMD: &str = "file.openAsSmartObject";
|
||||
|
||||
/// The history step's name.
|
||||
const LABEL: &str = "Open As Smart Object";
|
||||
|
||||
/// Opens the file as a document holding one embedded smart object. The read, decode and flatten
|
||||
/// run on the job's worker (inline under `execute`); the document is built, given File › Open's
|
||||
/// colour policy and admitted, or held for its profile prompt, when the job is applied. The reply
|
||||
/// has the shape of File › Open's job: `{document, docId, name, layer, warnings, color}`, or
|
||||
/// `{held, name, warnings, color, smartObject}` while the profile prompt waits.
|
||||
pub(super) fn open_as_smart_object(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path", CMD)?.to_string();
|
||||
let name = file_name(&path);
|
||||
let opts = crate::jobs::import_options(s.prefs());
|
||||
// An interactive caller (the app) asks before opening a PSD that had damaged data, as File > Open does.
|
||||
let confirm_damage = p.get("confirmDamage").and_then(Value::as_bool).unwrap_or(false);
|
||||
crate::jobs::run(
|
||||
s,
|
||||
&format!("Opening {name}"),
|
||||
false,
|
||||
move |ctx| {
|
||||
ctx.progress(0.0, "Reading");
|
||||
let bytes = read_file(&path)?;
|
||||
ctx.check()?;
|
||||
ctx.progress(0.05, "Decoding");
|
||||
let (r, damaged) = import_result_for_open(&name, &bytes, &opts)?;
|
||||
ctx.check()?;
|
||||
ctx.progress(0.9, "Flattening");
|
||||
// The file as one image: the smart object's rendered contents.
|
||||
let pixels = flattened_checked(&r.document, r.document.pixel_format(), CMD)?;
|
||||
Ok((path, name, Arc::new(bytes), r, pixels, confirm_damage && damaged))
|
||||
},
|
||||
|s, (path, name, bytes, r, pixels, damaged)| apply(s, &path, &name, bytes, r, pixels, damaged),
|
||||
)
|
||||
}
|
||||
|
||||
fn apply(
|
||||
s: &mut Session,
|
||||
path: &str,
|
||||
file: &str,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
r: photocraft_io::ImportResult,
|
||||
pixels: photocraft_raster::Surface,
|
||||
damaged: bool,
|
||||
) -> Result<Value> {
|
||||
let warnings = r.warnings;
|
||||
let mut src = r.document;
|
||||
super::tag_exr_colorspace(s, file, &mut src);
|
||||
super::raw_defaults(s, &warnings, &mut src);
|
||||
let layer_name = stem(path);
|
||||
// "<name>-1", the next free number while a document with that name is open.
|
||||
let name = untitled_name(&layer_name, |n| s.documents().iter().any(|d| d.doc.name == n) || s.held_open_named(n));
|
||||
|
||||
let mut doc = Document::new(name.clone(), src.size, src.mode, src.depth);
|
||||
doc.resolution_dpi = src.resolution_dpi;
|
||||
doc.icc_profile = src.icc_profile.clone();
|
||||
doc.color_table = src.color_table.clone();
|
||||
doc.duotone = src.duotone.clone();
|
||||
|
||||
// Embedded (not linked): the original file name keeps its extension, so Edit Contents opens it.
|
||||
let source = SmartSource::Embedded { file_name: file.to_string(), bytes };
|
||||
let so = SmartObject::new(source, Affine { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] }, Some(pixels));
|
||||
let layer = Layer::new(layer_name, LayerContent::Smart(so));
|
||||
let layer_id = layer.id;
|
||||
crate::layer_place::insert_new(&mut doc, None, layer, Place::AutoEditable);
|
||||
|
||||
// File › Open's completion: a raw has no embedded profile to ask about; otherwise the profile
|
||||
// prompt holds the document, and without a question the Color Settings policy is applied.
|
||||
let raw = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE));
|
||||
let question = s.color.open_question(&doc).filter(|_| !raw);
|
||||
if damaged || question.is_some() {
|
||||
let held = s.hold_open(doc, false);
|
||||
return Ok(json!({"held": held, "name": name, "warnings": warnings, "color": question, "damaged": damaged, "smartObject": true}));
|
||||
}
|
||||
let color = s.color.open_policy(&mut doc, s.prefs().file_handling.ignore_exif_profile_tag);
|
||||
let index = admit_as_smart_object(s, doc);
|
||||
let id = s.documents().get(index).map(|st| st.doc.id.0);
|
||||
// Admission numbers the document again, so the reply reads the name it was admitted under.
|
||||
let name = s.documents().get(index).map_or(name, |st| st.doc.name.clone());
|
||||
Ok(json!({"document": index, "docId": id, "name": name, "layer": layer_id.0, "warnings": warnings, "color": color, "smartObject": true}))
|
||||
}
|
||||
|
||||
/// Admits a document built by Open as Smart Object (one smart object layer) as an untitled
|
||||
/// document: the opening snapshot already shows the placed layer, is named after it, and the
|
||||
/// history is the single state "Open As Smart Object", as File › Open's is one state.
|
||||
pub fn admit_as_smart_object(s: &mut Session, mut doc: Document) -> usize {
|
||||
let layer_name = doc.layers.first().map(|l| l.name.clone());
|
||||
// The number was free when the file was read, but documents held for their prompts did not count
|
||||
// then, and one of them may have been cancelled since: take the first free one now, as each
|
||||
// document is admitted.
|
||||
if let Some(base) = &layer_name {
|
||||
doc.name = untitled_name(base, |n| s.documents().iter().any(|d| d.doc.name == n));
|
||||
}
|
||||
// Untitled: no path, so Save asks where to save.
|
||||
let index = s.add_document(doc, None);
|
||||
if let Some(st) = s.active_mut() {
|
||||
if let (Some(first), Some(name)) = (st.snapshots.iter_mut().find(|snap| snap.id == 0), layer_name) {
|
||||
first.name = name;
|
||||
}
|
||||
st.history.set_current_label(LABEL);
|
||||
}
|
||||
index
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
//! File › Open as Smart Object… (#11678): a file opens as a new untitled document holding one
|
||||
//! embedded smart object layer.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn tmp(name: &str) -> String {
|
||||
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let d = std::env::temp_dir().join(format!("photocraft-open-as-so-{}-{name}-{id}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// A small PNG with a gradient, so the pixels differ from place to place.
|
||||
fn write_png(dir: &str, name: &str, w: u32, h: u32) -> String {
|
||||
let px: Vec<u8> = (0..h).flat_map(|y| (0..w).flat_map(move |x| [(x * 255 / w) as u8, (y * 255 / h) as u8, ((x + y) % 256) as u8])).collect();
|
||||
let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, px).unwrap();
|
||||
let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
|
||||
let path = join(dir, name);
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
/// A two-layer 16-bit PSD at 300 ppi tagged with Display P3, made with the engine's own save.
|
||||
fn write_psd16(dir: &str, name: &str, w: u32, h: u32) -> String {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": w, "height": h, "depth": 16})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap();
|
||||
s.execute("edit.assignProfile", json!({"profile": "display-p3"})).unwrap();
|
||||
let path = join(dir, name);
|
||||
save_doc(&s.active().unwrap().doc, &path, None).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn imported(path: &str) -> Document {
|
||||
photocraft_io::import(&file_name(path), &std::fs::read(path).unwrap()).unwrap().document
|
||||
}
|
||||
|
||||
fn active(s: &Session) -> &Document {
|
||||
&s.active().unwrap().doc
|
||||
}
|
||||
|
||||
fn names(s: &Session) -> Vec<String> {
|
||||
s.documents().iter().map(|d| d.doc.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// The one layer of the active document, which must be an embedded smart object.
|
||||
fn embedded(s: &Session) -> (String, String, Arc<Vec<u8>>) {
|
||||
let d = active(s);
|
||||
assert_eq!(d.layers.len(), 1, "one layer, not a Background plus a layer");
|
||||
let layer = &d.layers[0];
|
||||
match &layer.content {
|
||||
LayerContent::Smart(so) => match &so.source {
|
||||
SmartSource::Embedded { file_name, bytes } => (layer.name.clone(), file_name.clone(), Arc::clone(bytes)),
|
||||
other => panic!("expected an embedded smart object, got {other:?}"),
|
||||
},
|
||||
_ => panic!("the layer is not a smart object"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_png_opens_as_an_untitled_document_with_one_embedded_smart_object() {
|
||||
let dir = tmp("png");
|
||||
let path = write_png(&dir, "a_test.png", 64, 48);
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
assert_eq!(r["name"], "a_test-1", "{r}");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.name, "a_test-1");
|
||||
assert_eq!(st.path, None, "untitled: Save asks where to save");
|
||||
|
||||
let file = imported(&path);
|
||||
let d = &st.doc;
|
||||
assert_eq!((d.size.width, d.size.height), (64, 48));
|
||||
assert_eq!(d.resolution_dpi, file.resolution_dpi);
|
||||
assert_eq!((d.mode, d.depth), (file.mode, file.depth));
|
||||
assert_eq!(d.icc_profile, file.icc_profile);
|
||||
|
||||
let (layer, original, bytes) = embedded(&s);
|
||||
assert_eq!(layer, "a_test", "named after the file without its extension");
|
||||
assert_eq!(original, "a_test.png", "Edit Contents opens the original file name");
|
||||
assert_eq!(*bytes, std::fs::read(&path).unwrap(), "the file itself is embedded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_smart_object_shows_the_file() {
|
||||
let dir = tmp("pixels");
|
||||
let path = write_png(&dir, "grad.png", 32, 16);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
let want = photocraft_compose::render(&imported(&path), Rect::new(0, 0, 32, 16)).px.clone();
|
||||
let got = photocraft_compose::render(active(&s), Rect::new(0, 0, 32, 16)).px.clone();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_16_bit_psd_keeps_size_resolution_mode_depth_and_profile() {
|
||||
let dir = tmp("psd");
|
||||
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
|
||||
let mut s = Session::new();
|
||||
// The files were measured in the working spaces, where nothing asks; Preserve keeps Display P3.
|
||||
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
|
||||
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
let file = imported(&path);
|
||||
assert_eq!(file.resolution_dpi, 300.0);
|
||||
assert!(file.icc_profile.is_some());
|
||||
let d = active(&s);
|
||||
assert_eq!(d.name, "c.layered-1", "only the last extension is dropped");
|
||||
assert_eq!((d.size.width, d.size.height), (40, 30));
|
||||
assert_eq!(d.resolution_dpi, 300.0);
|
||||
assert_eq!((d.mode, d.depth), (file.mode, file.depth));
|
||||
assert_eq!(d.depth, photocraft_doc::SampleType::U16);
|
||||
assert_eq!(d.icc_profile, file.icc_profile);
|
||||
let (layer, original, _) = embedded(&s);
|
||||
assert_eq!((layer.as_str(), original.as_str()), ("c.layered", "c.layered.psd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_is_the_single_state_open_as_smart_object() {
|
||||
let dir = tmp("history");
|
||||
let path = write_png(&dir, "a_test.png", 16, 16);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.history.entries(), ["Open As Smart Object"], "one state, as File > Open has");
|
||||
assert_eq!(st.snapshots.first().map(|snap| snap.name.as_str()), Some("a_test"), "the opening snapshot is named after the layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_opening_snapshot_shows_the_placed_smart_object() {
|
||||
let dir = tmp("snapshot");
|
||||
let path = write_png(&dir, "a_test.png", 16, 16);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let first = st.snapshots.first().unwrap();
|
||||
assert_eq!(first.doc.layers.len(), 1, "snapshot 0 already holds the smart object");
|
||||
assert!(matches!(first.doc.layers[0].content, LayerContent::Smart(_)));
|
||||
assert_eq!(first.layers.active, Some(first.doc.layers[0].id));
|
||||
assert_eq!(st.active_layer, Some(first.doc.layers[0].id));
|
||||
assert_eq!(st.history.entries(), ["Open As Smart Object"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_number_is_the_next_free_one_and_starts_again_after_they_close() {
|
||||
let dir = tmp("numbers");
|
||||
let path = write_png(&dir, "a_test.png", 8, 8);
|
||||
let mut s = Session::new();
|
||||
for _ in 0..3 {
|
||||
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
}
|
||||
assert_eq!(names(&s), ["a_test-1", "a_test-2", "a_test-3"]);
|
||||
while !s.documents().is_empty() {
|
||||
s.close(0);
|
||||
}
|
||||
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
assert_eq!(names(&s), ["a_test-1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_open_of_the_same_file_is_unchanged() {
|
||||
let dir = tmp("plain");
|
||||
let path = write_png(&dir, "a_test.png", 8, 8);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
open_bytes_as(&mut s, &path, &std::fs::read(&path).unwrap(), None, Some(path.clone())).unwrap();
|
||||
assert_eq!(names(&s), ["a_test-1", "a_test.png"]);
|
||||
assert!(matches!(active(&s).layers[0].content, LayerContent::Raster(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_files_open_one_document_each() {
|
||||
let dir = tmp("several");
|
||||
let a = write_png(&dir, "a_test.png", 8, 8);
|
||||
let b = write_psd16(&dir, "d_other.psd", 12, 10);
|
||||
let mut s = Session::new();
|
||||
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
|
||||
s.execute("file.openAsSmartObject", json!({"path": a})).unwrap();
|
||||
s.execute("file.openAsSmartObject", json!({"path": b})).unwrap();
|
||||
assert_eq!(names(&s), ["a_test-1", "d_other-1"]);
|
||||
for st in s.documents() {
|
||||
assert_eq!(st.doc.layers.len(), 1);
|
||||
assert!(matches!(st.doc.layers[0].content, LayerContent::Smart(_)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_unreadable_file_is_an_error_not_a_crash() {
|
||||
let dir = tmp("bad");
|
||||
let junk = join(&dir, "notes.png");
|
||||
std::fs::write(&junk, b"this is not an image").unwrap();
|
||||
let text = join(&dir, "readme.txt");
|
||||
std::fs::write(&text, b"hello").unwrap();
|
||||
let mut s = Session::new();
|
||||
for path in [join(&dir, "missing.png"), junk, text] {
|
||||
let r = s.execute("file.openAsSmartObject", json!({"path": path}));
|
||||
assert!(r.is_err(), "{path}: {r:?}");
|
||||
}
|
||||
assert!(s.documents().is_empty(), "a failed open leaves no document behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_errors() {
|
||||
let mut s = Session::new();
|
||||
for params in [json!({}), json!({"path": 7}), json!({"path": null})] {
|
||||
let r = s.execute("file.openAsSmartObject", params.clone());
|
||||
assert!(r.is_err(), "{params}: {r:?}");
|
||||
}
|
||||
assert!(s.documents().is_empty());
|
||||
}
|
||||
|
||||
fn job(r: crate::jobs::Started) -> crate::jobs::JobId {
|
||||
match r {
|
||||
crate::jobs::Started::Job(id) => id,
|
||||
crate::jobs::Started::Done(v) => panic!("expected a background job, ran inline: {v}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Poll until job `id` ends (or 60 s pass); returns its event.
|
||||
fn wait_event(s: &mut Session, id: crate::jobs::JobId) -> crate::jobs::JobEvent {
|
||||
let t = std::time::Instant::now();
|
||||
loop {
|
||||
if let Some(e) = s.poll_jobs().into_iter().find(|e| e.id == id) {
|
||||
return e;
|
||||
}
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(60), "job {id:?} did not finish");
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_import_runs_as_a_job_when_started() {
|
||||
let dir = tmp("job");
|
||||
let path = write_png(&dir, "a_test.png", 32, 24);
|
||||
let mut s = Session::new();
|
||||
let id = job(s.start("file.openAsSmartObject", json!({"path": path})).unwrap());
|
||||
assert!(s.documents().is_empty(), "nothing is admitted before the job is applied");
|
||||
let e = wait_event(&mut s, id);
|
||||
let crate::jobs::JobOutcome::Done(v) = &e.outcome else { panic!("{e:?}") };
|
||||
assert!(v["docId"].is_u64(), "{v}");
|
||||
assert_eq!(v["name"], "a_test-1", "{v}");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
embedded(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_colour_policy_matches_file_open() {
|
||||
let dir = tmp("policy");
|
||||
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
|
||||
let settings = json!({"askOnMismatch": false, "policyRgb": "convert"});
|
||||
let mut open = Session::new();
|
||||
open.execute("edit.colorSettings", settings.clone()).unwrap();
|
||||
open.execute("file.openAs", json!({"path": path})).unwrap();
|
||||
let mut so = Session::new();
|
||||
so.execute("edit.colorSettings", settings).unwrap();
|
||||
so.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
let (a, b) = (active(&open), active(&so));
|
||||
assert_eq!(a.icc_profile, b.icc_profile, "Convert is applied as File > Open applies it");
|
||||
assert_eq!((a.mode, a.depth, a.size), (b.mode, b.depth, b.size));
|
||||
assert_eq!(a.resolution_dpi, b.resolution_dpi);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ask_when_opening_holds_the_document_like_file_open() {
|
||||
let dir = tmp("ask");
|
||||
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
assert_eq!(r["color"]["ask"], true, "{r}");
|
||||
assert_eq!(r["smartObject"], true, "{r}");
|
||||
assert!(r["held"].is_u64(), "{r}");
|
||||
assert!(s.documents().is_empty(), "held for the profile prompt, not admitted");
|
||||
let (doc, _) = s.take_held_open(r["held"].as_u64().unwrap()).unwrap();
|
||||
assert_eq!(doc.name, "c.layered-1");
|
||||
assert_eq!(doc.layers.len(), 1);
|
||||
assert!(matches!(doc.layers[0].content, LayerContent::Smart(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reply_flags_a_smart_object_so_a_queued_document_keeps_its_history_label() {
|
||||
let dir = tmp("flag");
|
||||
let path = write_png(&dir, "a_test.png", 16, 12);
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
assert_eq!(r["smartObject"], true, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_psd_is_held_for_confirmation_when_asked_and_opens_otherwise() {
|
||||
let dir = tmp("damaged");
|
||||
let path = join(&dir, "d.psd");
|
||||
std::fs::write(&path, crate::jobs::psd_open_fixture::make_psd(true)).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
|
||||
let r = s.execute("file.openAsSmartObject", json!({"path": path, "confirmDamage": true})).unwrap();
|
||||
assert_eq!(r["damaged"], true, "{r}");
|
||||
assert_eq!(r["smartObject"], true, "{r}");
|
||||
assert!(r["held"].is_u64(), "{r}");
|
||||
assert!(s.documents().is_empty(), "held for the damage prompt, not admitted");
|
||||
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
assert!(r["docId"].is_u64(), "a headless caller opens the recovered content: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_held_for_its_prompt_does_not_share_its_name_with_the_next() {
|
||||
let dir = tmp("held-name");
|
||||
let path = write_psd16(&dir, "a_test.psd", 20, 20);
|
||||
let mut s = Session::new();
|
||||
let first = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
let second = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
assert_eq!(first["name"], "a_test-1");
|
||||
assert_eq!(second["name"], "a_test-2", "the held document's name is taken: {second}");
|
||||
// Both held docs leave the session for the app's queue; admitting them one by one numbers each.
|
||||
let (a, _) = s.take_held_open(first["held"].as_u64().unwrap()).unwrap();
|
||||
let (b, _) = s.take_held_open(second["held"].as_u64().unwrap()).unwrap();
|
||||
admit_as_smart_object(&mut s, a);
|
||||
admit_as_smart_object(&mut s, b);
|
||||
assert_eq!(names(&s), ["a_test-1", "a_test-2"]);
|
||||
let mut t = Session::new();
|
||||
let (c, _) = {
|
||||
let r = t.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
t.take_held_open(r["held"].as_u64().unwrap()).unwrap()
|
||||
};
|
||||
let (d, _) = {
|
||||
t.execute("edit.colorSettings", json!({"askOnMismatch": true})).unwrap();
|
||||
let r = t.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
t.take_held_open(r["held"].as_u64().unwrap()).unwrap()
|
||||
};
|
||||
assert_eq!(c.name, d.name, "taken out of the session, both are named a_test-1 when read");
|
||||
admit_as_smart_object(&mut t, c);
|
||||
admit_as_smart_object(&mut t, d);
|
||||
assert_eq!(names(&t), ["a_test-1", "a_test-2"], "the second takes the next free number when admitted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_hold_frees_its_number_for_the_one_admitted_after_it() {
|
||||
let dir = tmp("cancelled-hold");
|
||||
let path = write_psd16(&dir, "photo.psd", 20, 20);
|
||||
let mut s = Session::new();
|
||||
let first = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
let second = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
assert_eq!((first["name"].as_str(), second["name"].as_str()), (Some("photo-1"), Some("photo-2")));
|
||||
// photo-1 is cancelled while photo-2 waits; photo-2 is admitted with nothing open.
|
||||
s.take_held_open(first["held"].as_u64().unwrap()).unwrap();
|
||||
let (b, _) = s.take_held_open(second["held"].as_u64().unwrap()).unwrap();
|
||||
admit_as_smart_object(&mut s, b);
|
||||
assert_eq!(names(&s), ["photo-1"], "the first free number is taken at admission, with no collision");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reply_names_the_document_as_admitted() {
|
||||
let dir = tmp("reply-name");
|
||||
let path = write_psd16(&dir, "photo.psd", 20, 20);
|
||||
let mut s = Session::new();
|
||||
s.execute("edit.colorSettings", json!({"askOnMismatch": true})).unwrap();
|
||||
let held = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
assert_eq!(held["name"], "photo-1", "{held}");
|
||||
assert!(held["held"].is_u64(), "{held}");
|
||||
// The next open skips the prompt: photo-1 is held, so the number read was 2, but admission takes the first free one.
|
||||
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
|
||||
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
|
||||
assert_eq!(names(&s), ["photo-1"], "{r}");
|
||||
assert_eq!(r["name"], "photo-1", "the reply carries the name the document was admitted under: {r}");
|
||||
}
|
||||
@@ -5,9 +5,12 @@ use photocraft_io::{ImportResult, raw::RawTuning};
|
||||
|
||||
use super::{EngineError, Result, Session, Value, json};
|
||||
|
||||
/// The prior settings of a sidecar, and its crop (in the raw's stored orientation).
|
||||
type Prior = (CameraRaw, Option<photocraft_io::camera_raw_xmp::Crop>);
|
||||
|
||||
/// Read only a bounded regular XMP file. No ambient sidecar reads are granted to gated sessions.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn prior_settings(path: Option<&str>) -> Result<Option<CameraRaw>> {
|
||||
fn prior_settings(path: Option<&str>) -> Result<Option<Prior>> {
|
||||
use std::io::Read;
|
||||
let Some(path) = path else { return Ok(None) };
|
||||
let sidecar = match path.rsplit_once('.') {
|
||||
@@ -31,11 +34,11 @@ fn prior_settings(path: Option<&str>) -> Result<Option<CameraRaw>> {
|
||||
if !report.ignored.is_empty() {
|
||||
return Err(EngineError::Other(format!("{sidecar}: unsupported prior RAW settings: {}", report.ignored.join(", "))));
|
||||
}
|
||||
Ok(Some(settings))
|
||||
Ok(Some((settings, report.crop)))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn prior_settings(path: Option<&str>) -> Result<Option<CameraRaw>> {
|
||||
fn prior_settings(path: Option<&str>) -> Result<Option<Prior>> {
|
||||
if path.is_some() { Err(EngineError::Other("cannot read RAW sidecars on the web".into())) } else { Ok(None) }
|
||||
}
|
||||
|
||||
@@ -67,6 +70,8 @@ pub(super) fn prepare(s: &Session, name: &str, path: Option<&str>, bytes: &[u8])
|
||||
return Err(EngineError::Other("RAW sidecar opening requires a trusted session; no implicit read capability is available".into()));
|
||||
}
|
||||
let prior = prior_settings(path)?;
|
||||
let crop = prior.as_ref().and_then(|(_, crop)| *crop);
|
||||
let prior = prior.map(|(settings, _)| settings);
|
||||
let mut settings = prior.clone().unwrap_or_default();
|
||||
let opts = crate::jobs::import_options(s.prefs());
|
||||
let mut imported = photocraft_io::import_with_options(name, bytes, &opts).map_err(|error| EngineError::Other(format!("{name}: {error}")))?;
|
||||
@@ -87,6 +92,8 @@ pub(super) fn prepare(s: &Session, name: &str, path: Option<&str>, bytes: &[u8])
|
||||
clarity: settings.clarity,
|
||||
texture: settings.texture,
|
||||
dehaze: settings.dehaze,
|
||||
// The sidecar's crop, as the interactive open applies it: before the Camera Raw step.
|
||||
crop,
|
||||
};
|
||||
if tuning != (RawTuning { demosaic: opts.demosaic, ..Default::default() }) {
|
||||
super::open::raw_defaults(s, &imported.warnings, &mut imported.document);
|
||||
|
||||
@@ -734,6 +734,27 @@ fn batch_quiet_raw_applies_prior_settings_and_workflow_without_touching_inputs()
|
||||
assert!(s.batch_open_notices.is_none());
|
||||
}
|
||||
|
||||
/// #9985: quiet RAW opening crops to the sidecar's crop, as the interactive open does.
|
||||
#[test]
|
||||
fn batch_quiet_raw_applies_the_sidecar_crop() {
|
||||
use photocraft_raw::testgen::{DngSpec, mosaic, scene};
|
||||
let dir = tmp("batch-quiet-raw-crop");
|
||||
let path = join(&dir, "raw.dng");
|
||||
let (w, h) = (24, 16);
|
||||
let bytes = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 65535)).build();
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
let crop = photocraft_io::camera_raw_xmp::Crop { top: 0.25, left: 0.125, bottom: 0.75, right: 0.625 };
|
||||
let xmp = photocraft_io::camera_raw_xmp::save_with_crop(&photocraft_algo::camera_raw::CameraRaw::default(), Some(crop));
|
||||
std::fs::write(join(&dir, "raw.xmp"), &xmp).unwrap();
|
||||
let mut s = Session::new();
|
||||
let output = join(&dir, "out");
|
||||
let p = json!({"input":[path],"output":output,"format":"psd","suppressOpenOptions":true,"suppressWarnings":true,"steps":[]});
|
||||
let result = s.execute("file.automate.batch", p).unwrap();
|
||||
assert!(result["errors"].as_array().unwrap().is_empty(), "{result}");
|
||||
let actual = photocraft_io::import("raw.psd", &std::fs::read(join(&output, "raw.psd")).unwrap()).unwrap().document;
|
||||
assert_eq!((actual.size.width, actual.size.height), (12, 8), "the 24x16 frame cropped to x 3..15, y 4..12");
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> String {
|
||||
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
@@ -44,6 +44,16 @@ pub struct CutParts {
|
||||
}
|
||||
|
||||
impl CutParts {
|
||||
/// Selected pixels in source-document coordinates, including soft coverage.
|
||||
pub(crate) fn selected_pixels(&self) -> &Surface {
|
||||
&self.piece
|
||||
}
|
||||
|
||||
/// Whether the floating piece contains a layer mask rather than layer pixels.
|
||||
pub(crate) fn is_mask(&self) -> bool {
|
||||
self.mask
|
||||
}
|
||||
|
||||
/// Split `layer` of `doc` by its selection. With `copy` the selected pixels stay in the layer
|
||||
/// too (the piece is a duplicate). Without, they leave a transparent hole, or on the Background,
|
||||
/// which can't hold transparency, one filled with `background` (Photoshop). Errors without a
|
||||
@@ -340,7 +350,7 @@ pub fn drop_floating(s: &mut Session) -> Result<Value> {
|
||||
|
||||
/// Commands that leave a floating piece floating: its own, and ones that don't touch documents.
|
||||
fn keeps_floating(id: &str) -> bool {
|
||||
matches!(id, "select.float" | "select.drop" | "brush.mixer.sample" | "brush.mixer.load" | "brush.mixer.clean")
|
||||
matches!(id, "select.float" | "select.drop" | "layer.copyToDocument" | "brush.mixer.sample" | "brush.mixer.load" | "brush.mixer.clean")
|
||||
|| ["view.", "window.", "help.", "prefs."].iter().any(|p| id.starts_with(p))
|
||||
}
|
||||
|
||||
|
||||
@@ -221,6 +221,7 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let (from, to) = (&s.documents()[src], &s.documents()[dest]);
|
||||
let (sdoc, ddoc) = (from.doc.clone(), to.doc.clone());
|
||||
let floating = crate::float_cmds::floating(from).cloned();
|
||||
let ids: Vec<LayerId> = match p.get("layers") {
|
||||
None => from.selected_layers(),
|
||||
Some(v) => v
|
||||
@@ -236,6 +237,14 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad("no layers to copy"));
|
||||
}
|
||||
let selection_only = match p.get("selectionOnly") {
|
||||
None => false,
|
||||
Some(Value::Bool(on)) => *on,
|
||||
Some(_) => return Err(bad("`selectionOnly` must be a boolean")),
|
||||
};
|
||||
if selection_only && (ids.len() != 1 || sdoc.selection.is_none()) {
|
||||
return Err(bad("copying selected pixels requires a selection and one pixel layer"));
|
||||
}
|
||||
for (doc, role) in [(&sdoc, "source"), (&ddoc, "destination")] {
|
||||
if !layered(doc.mode) {
|
||||
return Err(EngineError::Other(format!("layers can't be copied with a {:?} {role} document", doc.mode)));
|
||||
@@ -250,7 +259,24 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
copies.text_styles.clone_from(&sdoc.text_styles);
|
||||
for id in &ids {
|
||||
let src_layer = sdoc.layer(*id).ok_or(EngineError::NoLayer(*id))?;
|
||||
let mut l = src_layer.duplicate();
|
||||
let mut l = if selection_only {
|
||||
let parts = match floating.as_ref().filter(|f| f.layer == *id) {
|
||||
Some(f) if f.parts.is_mask() => return Err(bad("a floating layer mask cannot be transferred as selected pixels")),
|
||||
Some(f) => f.parts.clone(),
|
||||
None => std::sync::Arc::new(crate::float_cmds::CutParts::new(&sdoc, *id, true, s.tools.background, false)?),
|
||||
};
|
||||
if parts.selected_pixels().content_bounds().is_empty() {
|
||||
return Err(bad("the selected pixels are empty"));
|
||||
}
|
||||
let mut layer = Layer::new(src_layer.name.clone(), LayerContent::Raster(parts.selected_pixels().clone()));
|
||||
layer.opacity = src_layer.opacity;
|
||||
if let Some(f) = floating.as_ref().filter(|f| f.layer == *id) {
|
||||
crate::commands::translate_layer(&sdoc, &mut layer, f.offset.0, f.offset.1);
|
||||
}
|
||||
layer
|
||||
} else {
|
||||
src_layer.duplicate()
|
||||
};
|
||||
// A dragged Background arrives as an ordinary layer (the destination keeps its own).
|
||||
if sdoc.is_background(*id) {
|
||||
l.name = ddoc.next_layer_name("Layer");
|
||||
@@ -399,7 +425,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
label: "Copy Layers to Document",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"document":index (destination),"layers":[id,…]?=the source's selected layers,"source":index?=active,"center":bool=false (centre on the destination's canvas),"at":[x,y]? (centre the copies on this point),"offset":[dx,dy]?=[0,0] (from their place in the source),"name":str? (one layer: the copy's name)}"##,
|
||||
params: r##"{"document":index (destination),"layers":[id,…]?=the source's selected layers,"source":index?=active,"selectionOnly":bool=false (copy selected pixels from one raster layer),"center":bool=false (centre on the destination's canvas),"at":[x,y]? (centre the copies on this point),"offset":[dx,dy]?=[0,0] (from their place in the source),"name":str? (one layer: the copy's name)}"##,
|
||||
enabled,
|
||||
run: copy_to_document,
|
||||
journal: true,
|
||||
|
||||
@@ -28,6 +28,53 @@ fn copied(r: &Value) -> LayerId {
|
||||
LayerId(r["layers"][0].as_u64().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_only_copy_preserves_source_and_soft_coverage_across_documents() {
|
||||
for depth in [8, 16, 32] {
|
||||
let (mut s, paint) = two_docs(40, 30, depth);
|
||||
s.execute("select.rect", json!({"x": 7, "y": 8, "width": 3, "height": 4})).unwrap();
|
||||
s.execute("layer.setProps", json!({"layer": paint.0, "opacity": 0.4})).unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).selection.as_mut().unwrap().write_pixel(7, 8, &[0.5]);
|
||||
let before = doc(&s, 0).clone();
|
||||
let r = s.execute("layer.copyToDocument", json!({"source": 0, "document": 1, "layers": [paint.0], "selectionOnly": true, "offset": [10, 5]})).unwrap();
|
||||
let id = copied(&r);
|
||||
assert_eq!(bounds(&s, 1, id), Rect::new(17, 13, 20, 17));
|
||||
assert_eq!(*doc(&s, 0), before);
|
||||
let pixel = doc(&s, 1).layer(id).unwrap().surface().unwrap().rgba(17, 13);
|
||||
assert!((doc(&s, 1).layer(id).unwrap().opacity - 0.4).abs() < 1e-6);
|
||||
assert_eq!(&pixel[..3], &[1.0, 0.0, 0.0]);
|
||||
assert!((pixel[3] - 0.5).abs() <= 1.0 / 255.0, "soft selection coverage survives depth conversion");
|
||||
assert!(s.undo());
|
||||
assert_eq!(doc(&s, 1).layers.len(), 1);
|
||||
assert_eq!(*doc(&s, 0), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_only_copy_rejects_a_floating_layer_mask() {
|
||||
let (mut s, paint) = two_docs(40, 30, 8);
|
||||
s.edit("mask", |doc, _| {
|
||||
doc.layer_mut(paint).unwrap().mask = Some(photocraft_doc::LayerMask::reveal_all());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.rect", json!({"x": 7, "y": 8, "width": 3, "height": 4})).unwrap();
|
||||
s.execute("select.float", json!({"dx": 2, "dy": 0, "copy": true, "target": "mask"})).unwrap();
|
||||
let source = doc(&s, 0).clone();
|
||||
assert!(s.execute("layer.copyToDocument", json!({"source": 0, "document": 1, "layers": [paint.0], "selectionOnly": true})).is_err());
|
||||
assert_eq!(*doc(&s, 0), source);
|
||||
assert_eq!(doc(&s, 1).layers.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_only_copy_rejects_missing_selection_and_wrong_parameter_type() {
|
||||
let (mut s, _) = two_docs(40, 30, 8);
|
||||
for option in [json!(true), json!("yes")] {
|
||||
assert!(s.execute("layer.copyToDocument", json!({"document": 1, "selectionOnly": option})).is_err());
|
||||
assert_eq!(doc(&s, 1).layers.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn bounds(s: &Session, i: usize, id: LayerId) -> Rect {
|
||||
crate::layer_multi_cmds::layer_bounds(doc(s, i).layer(id).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Layer › Copy CSS (#9372): CSS for the selected layers, in the form Photoshop writes. The
|
||||
//! command returns the text; the shell puts it on the clipboard.
|
||||
//!
|
||||
//! Each layer is a class named after it (punctuation and spaces become `_`, and a leading digit
|
||||
//! gets a `_` in front). What is written, in this order:
|
||||
//! - a type layer: `font-size`, `font-family`, `color`, `line-height` and `text-align`, from its
|
||||
//! first run and first paragraph;
|
||||
//! - a live rounded rectangle: `border-radius`; a live ellipse: `border-radius: 50%`;
|
||||
//! - a shape or fill layer with a solid colour: `background-color`; any other layer (pixels,
|
||||
//! gradient or pattern fills, smart objects): `background-image`, an image named after it;
|
||||
//! - `opacity` when it isn't 100 %;
|
||||
//! - `position: absolute`, `left` and `top`, and `width` and `height` except for point type;
|
||||
//! - `z-index`, its place in the stack counted from the bottom layer as 1, where a group takes
|
||||
//! two places (its own, and one below its layers for the group's end).
|
||||
//!
|
||||
//! A group writes only its box (the canvas, or its artboard) and z-index, followed by the rule
|
||||
//! of every layer in it, top first. A fill layer without a vector mask and an adjustment layer
|
||||
//! have no rule, and Copy CSS is off when no selected layer has one. Point type is placed as
|
||||
//! Photoshop places it (see [`place_point_text`]).
|
||||
//!
|
||||
//! Not written: strokes (`border`), layer effects (`box-shadow`, `text-shadow`), gradients as
|
||||
//! CSS gradients, blend modes (`mix-blend-mode`), fill opacity, the styles of later runs and
|
||||
//! paragraphs, the corners of a rounded rectangle scaled unequally (elliptical, while it keeps
|
||||
//! one radius per corner), and the geometry of other shapes (live polygons, stars and lines, and
|
||||
//! custom paths), which get the rule of their box.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use photocraft_doc::text::{Orientation, TextAlign, TextShape};
|
||||
use photocraft_doc::{Document, Fill, Layer, LayerContent, LayerId, LiveShape, Path, TextLayer};
|
||||
use photocraft_geom::{Point, Rect};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::CommandSpec;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
pub const ID: &str = "layer.copyCSS";
|
||||
|
||||
fn bad(message: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: ID.into(), msg: message.into() }
|
||||
}
|
||||
|
||||
/// Deepest group nesting followed; deeper layers are left out rather than recursing without end.
|
||||
const MAX_DEPTH: usize = 256;
|
||||
|
||||
fn enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let ids = st.selected_layers();
|
||||
if ids.is_empty() {
|
||||
return Err("no layer selected".into());
|
||||
}
|
||||
// Photoshop greys Copy CSS out for a fill layer without a shape (measured), and for an
|
||||
// adjustment layer, which has nothing to place either.
|
||||
if st.doc.walk().iter().any(|(_, _, l)| ids.contains(&l.id) && has_css(l)) { Ok(()) } else { Err("no selected layer has CSS".into()) }
|
||||
}
|
||||
|
||||
/// Whether a layer can have a rule (one with nothing to place still gets none).
|
||||
fn has_css(l: &Layer) -> bool {
|
||||
match &l.content {
|
||||
LayerContent::Adjustment(_) => false,
|
||||
LayerContent::Fill(_) => l.vector_mask.is_some(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A number as Photoshop writes it in CSS: at most three decimals, no trailing zeros.
|
||||
pub fn number(v: f64) -> String {
|
||||
let v = if v.is_finite() { (v * 1000.0).round() / 1000.0 } else { 0.0 };
|
||||
decimals(v)
|
||||
}
|
||||
|
||||
/// A `left` or `top` as Photoshop writes it: cut after three decimals, not rounded (measured:
|
||||
/// 49.8125 is `49.812px`, 176.5668 is `176.566px`). The nudge keeps 127.1, computed as
|
||||
/// 127.0999…, at `127.1`.
|
||||
pub fn position(v: f64) -> String {
|
||||
let v = if v.is_finite() { (v * 1000.0 + 1e-6).floor() / 1000.0 } else { 0.0 };
|
||||
decimals(v)
|
||||
}
|
||||
|
||||
fn decimals(v: f64) -> String {
|
||||
let s = format!("{v:.3}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" { "0".into() } else { s.to_string() }
|
||||
}
|
||||
|
||||
/// The class name for a layer: its name with every character other than a letter, digit or `_`
|
||||
/// as `_` (a hyphen too, as Photoshop does), and a `_` in front when it starts with a digit,
|
||||
/// which a class selector can't.
|
||||
pub fn class_name(name: &str) -> String {
|
||||
let s: String = name.chars().map(|c| if c.is_alphanumeric() || c == '_' { c } else { '_' }).collect();
|
||||
if s.is_empty() {
|
||||
"layer".into()
|
||||
} else if s.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
format!("_{s}")
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` as a double-quoted CSS string, escaped as CSSOM serializes one: `"` and `\` get a
|
||||
/// backslash, control characters (line breaks among them) become hex escapes, NUL becomes U+FFFD.
|
||||
pub fn quoted(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len() + 2);
|
||||
out.push('"');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\0' => out.push('\u{FFFD}'),
|
||||
'\u{1}'..='\u{1F}' | '\u{7F}' => out.push_str(&format!("\\{:x} ", u32::from(c))),
|
||||
'"' | '\\' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
/// The image Photoshop names after a layer, as a `url()`.
|
||||
fn image(l: &Layer) -> String {
|
||||
format!("url({})", quoted(&format!("{}.png", l.name)))
|
||||
}
|
||||
|
||||
fn rgb(c: &photocraft_color::Color) -> String {
|
||||
let [r, g, b] = c.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
format!("rgb({r}, {g}, {b})")
|
||||
}
|
||||
|
||||
/// Whether `path` is the outline `live` draws: every anchor of one is an anchor of the other,
|
||||
/// within a hundredth of a pixel, in any order or direction (a flipped shape runs the other way).
|
||||
/// A live rectangle scaled unequally keeps one radius per corner, but its path keeps the corners
|
||||
/// it was drawn with, now elliptical, so the two differ.
|
||||
fn draws(live: &LiveShape, path: &Path) -> bool {
|
||||
let anchors = |p: &Path| p.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| k.anchor)).collect::<Vec<_>>();
|
||||
let (have, want) = (anchors(path), anchors(&photocraft_vector::shapes::live_path(live)));
|
||||
let among = |p: &Point, q: &[Point]| q.iter().any(|q| (p.x - q.x).abs() < 0.01 && (p.y - q.y).abs() < 0.01);
|
||||
have.iter().all(|p| among(p, &want)) && want.iter().all(|p| among(p, &have))
|
||||
}
|
||||
|
||||
/// Where Photoshop places point type, from its pixel bounds `pix`, its ink `ink` (`[x0, y0, x1,
|
||||
/// y1]` from its origin, unrounded), its first baseline `baseline` in the same space, the cap
|
||||
/// height `cap` of its font and its size and line height in px. Measured on Arial and Times New
|
||||
/// Roman at 24 and 48 px, with auto and explicit leading:
|
||||
/// - `left` is the pixel left less the ink's offset from the origin ("Hello": 52 − 1.875 =
|
||||
/// `50.125`);
|
||||
/// - without a descender, the line box is centred on the pixels ("Hello", pixels 132–151, line
|
||||
/// 28.8: 141.5 − 14.4 = `127.1`);
|
||||
/// - with one, on half the cap height above the baseline the pixels give ("xyz" in Arial, top
|
||||
/// pixel 187, ink top −12.5625, cap 17.19: 199.5625 − (28.8 + 17.19) / 2 = `176.566`).
|
||||
pub fn place_point_text(pix: Rect, ink: [f64; 4], baseline: f64, cap: f64, size_px: f64, line_height_px: f64) -> Point {
|
||||
let left = f64::from(pix.x0) - ink[0];
|
||||
// An "o" overshoots the baseline by a hair, a "g" by a fifth of the size.
|
||||
let top = if ink[3] - baseline > 0.05 * size_px {
|
||||
f64::from(pix.y0) - (ink[1] - baseline) - (line_height_px + cap) / 2.0
|
||||
} else {
|
||||
(f64::from(pix.y0) + f64::from(pix.y1)) / 2.0 - line_height_px / 2.0
|
||||
};
|
||||
Point::new(left, top)
|
||||
}
|
||||
|
||||
/// [`place_point_text`] for a type layer, from its layout; `None` (placed at its pixels) when
|
||||
/// there is nothing to measure: no pixels or ink, no font, or type that is turned, scaled,
|
||||
/// warped or vertical.
|
||||
fn point_text_origin(t: &TextLayer, pix: Rect, dpi: f32, family: &str, size_pt: f32, line_height: f64) -> Option<Point> {
|
||||
let [a, b, c, d, _, _] = t.transform.m;
|
||||
if pix.is_empty() || a != 1.0 || b != 0.0 || c != 0.0 || d != 1.0 || t.warp.is_some() || t.orientation != Orientation::Horizontal {
|
||||
return None;
|
||||
}
|
||||
let size_px = f64::from(size_pt) * f64::from(dpi) / 72.0;
|
||||
let cap_layer = TextLayer { text: "H".into(), font_family: family.into(), size_pt, ..Default::default() };
|
||||
let mut eng = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let layout = eng.layout(t, dpi);
|
||||
let ink = photocraft_text::render::ink_bounds(&layout)?;
|
||||
let baseline = f64::from(layout.lines.first()?.baseline);
|
||||
let cap_layout = eng.layout(&cap_layer, dpi);
|
||||
let cap = f64::from(cap_layout.lines.first()?.baseline) - photocraft_text::render::ink_bounds(&cap_layout)?[1];
|
||||
// Photoshop works with the line height it writes, three decimals of the size.
|
||||
let line_height_px = (line_height * 1000.0).round() / 1000.0 * size_px;
|
||||
let at = place_point_text(pix, ink, baseline, cap, size_px, line_height_px);
|
||||
(at.x.is_finite() && at.y.is_finite()).then_some(at)
|
||||
}
|
||||
|
||||
/// The box of a group's rule: its artboard, else the canvas (measured: a group holding a 50 × 30
|
||||
/// layer writes the 400 × 300 canvas).
|
||||
fn group_bounds(doc: &Document, l: &Layer) -> Rect {
|
||||
let r = photocraft_doc::comps::position_bounds(l);
|
||||
if r.is_empty() { doc.bounds() } else { r }
|
||||
}
|
||||
|
||||
/// The rule for one layer, `z` its place in the stack from the bottom (1-based); `None` for a
|
||||
/// layer CSS can't describe (adjustments, fill layers without a shape) or one with nothing to
|
||||
/// place. A group's rule is its box alone; [`copy_css`] adds the rules of its layers.
|
||||
pub fn rule(doc: &Document, z: usize, l: &Layer) -> Option<String> {
|
||||
let px_per_pt = f64::from(doc.resolution_dpi.max(1.0)) / 72.0;
|
||||
let mut props: Vec<(&str, String)> = Vec::new();
|
||||
let mut sized = true;
|
||||
let mut bounds = photocraft_doc::comps::position_bounds(l);
|
||||
// Where the rule starts when it isn't where the layer's pixels start.
|
||||
let mut origin: Option<Point> = None;
|
||||
if !has_css(l) {
|
||||
return None;
|
||||
}
|
||||
match &l.content {
|
||||
LayerContent::Adjustment(_) => return None,
|
||||
LayerContent::Group(_) => bounds = group_bounds(doc, l),
|
||||
LayerContent::Text(t) => {
|
||||
let style = t.runs.first().map(|r| &r.style);
|
||||
let size_pt = style.map_or(t.size_pt, |s| s.size_pt);
|
||||
let family = style.map(|s| s.font_family.as_str()).filter(|f| !f.is_empty()).unwrap_or(&t.font_family);
|
||||
let color = style.map_or(t.color, |s| s.color);
|
||||
let paragraph = t.paragraphs.first().map(|p| p.style.clone()).unwrap_or_default();
|
||||
// Auto leading is the paragraph's multiple of the size (1.2 by default).
|
||||
let line_height = match style.and_then(|s| s.leading_pt) {
|
||||
Some(leading) if size_pt > 0.0 => f64::from(leading / size_pt),
|
||||
_ => f64::from(paragraph.auto_leading),
|
||||
};
|
||||
let align = match paragraph.align {
|
||||
TextAlign::Left => "left",
|
||||
TextAlign::Center => "center",
|
||||
TextAlign::Right => "right",
|
||||
_ => "justify",
|
||||
};
|
||||
props.push(("font-size", format!("{}px", number(f64::from(size_pt) * px_per_pt))));
|
||||
props.push(("font-family", quoted(family)));
|
||||
props.push(("color", rgb(&color)));
|
||||
props.push(("line-height", number(line_height)));
|
||||
props.push(("text-align", align.into()));
|
||||
match t.shape {
|
||||
// Photoshop places paragraph text at its box, moved down by an explicit leading,
|
||||
// and sizes it by its text, not the box.
|
||||
TextShape::Box { x, y, .. } => {
|
||||
let at = t.transform.apply(Point::new(f64::from(x), f64::from(y)));
|
||||
let leading = style.and_then(|s| s.leading_pt).map_or(0.0, |v| f64::from(v) * px_per_pt);
|
||||
origin = Some(Point::new(at.x, at.y + leading));
|
||||
}
|
||||
// Point text has no box of its own: only its position.
|
||||
_ => {
|
||||
sized = false;
|
||||
origin = point_text_origin(t, bounds, doc.resolution_dpi.max(1.0), family, size_pt, line_height);
|
||||
}
|
||||
}
|
||||
}
|
||||
LayerContent::Shape(sh) => {
|
||||
// A live rounded rectangle's corners, before the fill as Photoshop writes them: one
|
||||
// value when all four are equal, else top-left, top-right, bottom-right, bottom-left.
|
||||
// Scaled unequally, its corners are elliptical though it keeps one radius each: none.
|
||||
// A live ellipse fills its box, which half the box's size on each axis rounds to.
|
||||
match &sh.live {
|
||||
Some(live @ LiveShape::Rect { radii, .. }) if radii.iter().any(|&r| r > 0.0) && draws(live, &sh.path) => {
|
||||
let px = |r: f64| format!("{}px", number(r.max(0.0)));
|
||||
let all = if radii.iter().all(|&r| r == radii[0]) { px(radii[0]) } else { radii.map(px).join(" ") };
|
||||
props.push(("border-radius", all));
|
||||
}
|
||||
Some(LiveShape::Ellipse { .. }) => props.push(("border-radius", "50%".into())),
|
||||
_ => {}
|
||||
}
|
||||
match &sh.fill {
|
||||
Some(Fill::Solid(c)) => props.push(("background-color", rgb(c))),
|
||||
_ => props.push(("background-image", image(l))),
|
||||
}
|
||||
}
|
||||
LayerContent::Fill(f) => {
|
||||
// Only a fill layer with a vector mask (a shape) gets here: placed at its outline.
|
||||
if bounds.is_empty() {
|
||||
let outline = l.vector_mask.as_ref().and_then(|m| m.path.control_bounds());
|
||||
bounds = outline.map_or(Rect::EMPTY, |(x0, y0, x1, y1)| {
|
||||
Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).intersect(&doc.bounds())
|
||||
});
|
||||
}
|
||||
match f {
|
||||
Fill::Solid(c) => props.push(("background-color", rgb(c))),
|
||||
_ => props.push(("background-image", image(l))),
|
||||
}
|
||||
}
|
||||
_ => props.push(("background-image", image(l))),
|
||||
}
|
||||
if bounds.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if l.opacity < 1.0 {
|
||||
props.push(("opacity", number(f64::from(l.opacity.max(0.0)))));
|
||||
}
|
||||
props.push(("position", "absolute".into()));
|
||||
let at = origin.unwrap_or(Point::new(f64::from(bounds.x0), f64::from(bounds.y0)));
|
||||
props.push(("left", format!("{}px", position(at.x))));
|
||||
props.push(("top", format!("{}px", position(at.y))));
|
||||
if sized {
|
||||
props.push(("width", format!("{}px", number(f64::from(bounds.width())))));
|
||||
props.push(("height", format!("{}px", number(f64::from(bounds.height())))));
|
||||
}
|
||||
props.push(("z-index", z.to_string()));
|
||||
let mut out = format!(".{} {{\n", class_name(&l.name));
|
||||
for (k, v) in props {
|
||||
out.push_str(&format!(" {k}: {v};\n"));
|
||||
}
|
||||
out.push_str("}\n");
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn copy_css(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let p = p.as_object().ok_or_else(|| bad("expected an object"))?;
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let ids = match p.get("layer") {
|
||||
None | Some(Value::Null) => st.selected_layers(),
|
||||
Some(v) => vec![LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be an unsigned integer"))?)],
|
||||
};
|
||||
if ids.is_empty() {
|
||||
return Err(bad("no layer selected"));
|
||||
}
|
||||
let walk = st.doc.walk();
|
||||
for id in &ids {
|
||||
if !walk.iter().any(|(_, _, l)| l.id == *id) {
|
||||
return Err(EngineError::NoLayer(*id));
|
||||
}
|
||||
}
|
||||
let mut z = HashMap::new();
|
||||
stack_places(&st.doc.layers, &mut 0, &mut z, 0);
|
||||
// In Layers panel order, top first: a group, then its layers (measured).
|
||||
let mut picked = Vec::new();
|
||||
panel_order(&st.doc.layers, false, &ids, &mut picked, 0);
|
||||
let rules: Vec<(u64, String)> = picked.into_iter().filter_map(|l| z.get(&l.id).and_then(|&z| rule(&st.doc, z, l)).map(|r| (l.id.0, r))).collect();
|
||||
if rules.is_empty() {
|
||||
return Err(EngineError::Other("Copy CSS needs a pixel, type, shape or group layer with content".into()));
|
||||
}
|
||||
// Photoshop writes a group's rules one after another, with no blank line between them.
|
||||
let css: String = rules.iter().map(|(_, r)| r.as_str()).collect();
|
||||
Ok(json!({"css": css, "layers": rules.iter().map(|(id, _)| id).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Every layer's `z-index`, counted from the bottom: a group's layers come first, after one place
|
||||
/// for the group's end, then the group (measured: Background 1, group end 2, its layer 3, the
|
||||
/// group 4, the layer above it 5).
|
||||
fn stack_places(layers: &[Layer], n: &mut usize, out: &mut HashMap<LayerId, usize>, depth: usize) {
|
||||
for l in layers {
|
||||
if let Some(children) = l.children() {
|
||||
*n += 1;
|
||||
if depth < MAX_DEPTH {
|
||||
stack_places(children, n, out, depth + 1);
|
||||
}
|
||||
}
|
||||
*n += 1;
|
||||
out.insert(l.id, *n);
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers whose rules are copied, top first: the selected ones and everything inside a
|
||||
/// selected group, each once.
|
||||
fn panel_order<'a>(layers: &'a [Layer], inside_picked: bool, ids: &[LayerId], out: &mut Vec<&'a Layer>, depth: usize) {
|
||||
for l in layers.iter().rev() {
|
||||
let take = inside_picked || ids.contains(&l.id);
|
||||
if take {
|
||||
out.push(l);
|
||||
}
|
||||
if let Some(children) = l.children().filter(|_| depth < MAX_DEPTH) {
|
||||
panel_order(children, take, ids, out, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![CommandSpec {
|
||||
id: ID,
|
||||
label: "Copy CSS",
|
||||
menu: &["Layer"],
|
||||
shortcut: None,
|
||||
params: r#"{"layer":id?} (no layer: the selected layers) → {"css": text, "layers": [id…]}; the app puts the text on the clipboard"#,
|
||||
enabled,
|
||||
run: copy_css,
|
||||
journal: false,
|
||||
}]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,346 @@
|
||||
use super::*;
|
||||
use photocraft_doc::Layer;
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
/// A 400 × 300 document at 72 ppi with a 200 × 140 pixel layer at (100, 80) named `name`.
|
||||
fn session(name: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": name})).unwrap();
|
||||
s.edit("paint", |doc, active| {
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(100, 80, 300, 220), &[0.16, 0.35, 0.78, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Photoshop 2025 copies this for a 200 × 140 pixel layer at (100, 80), second from the bottom.
|
||||
#[test]
|
||||
fn a_pixel_layer_copies_as_photoshop_writes_it() {
|
||||
let mut s = session("Box");
|
||||
let r = s.execute(ID, json!({})).unwrap();
|
||||
assert_eq!(
|
||||
r["css"],
|
||||
json!(
|
||||
".Box {\n background-image: url(\"Box.png\");\n position: absolute;\n left: 100px;\n top: 80px;\n width: 200px;\n height: 140px;\n z-index: 2;\n}\n"
|
||||
)
|
||||
);
|
||||
// Photoshop: a name with spaces keeps them in the image name and turns them to `_` in the
|
||||
// class; an opacity under 100 % follows the background.
|
||||
let mut s = session("My Box 2");
|
||||
s.edit("opacity", |doc, active| {
|
||||
doc.layer_mut(active.unwrap()).unwrap().opacity = 128.0 / 255.0;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.starts_with(".My_Box_2 {\n background-image: url(\"My Box 2.png\");\n opacity: 0.502;\n position: absolute;\n"), "{css}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_and_type_layers_describe_their_colour_and_font() {
|
||||
let doc = session("Box").active().unwrap().doc.clone();
|
||||
// Photoshop: a solid colour gives `background-color`. A fill layer is a shape with a vector
|
||||
// mask, placed at its outline; without one it has no rule (Copy CSS is greyed out, measured).
|
||||
let mut fill = Layer::new("Card", LayerContent::Fill(Fill::Solid(photocraft_color::Color::rgb(1.0, 120.0 / 255.0, 30.0 / 255.0))));
|
||||
assert!(rule(&doc, 4, &fill).is_none());
|
||||
fill.vector_mask = Some(photocraft_doc::VectorMask::new(photocraft_vector::shapes::rect(250.0, 200.0, 120.0, 60.0)));
|
||||
assert_eq!(
|
||||
rule(&doc, 4, &fill).unwrap(),
|
||||
".Card {\n background-color: rgb(255, 120, 30);\n position: absolute;\n left: 250px;\n top: 200px;\n width: 120px;\n height: 60px;\n z-index: 4;\n}\n"
|
||||
);
|
||||
// A type layer: size, family, colour, auto leading and alignment, then only its position
|
||||
// (Photoshop writes no size for point text). Its position is where its pixels are.
|
||||
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
|
||||
cache.fill_rect(Rect::new(49, 28, 120, 52), &[0.0, 0.0, 0.0, 1.0]);
|
||||
let text = photocraft_doc::TextLayer {
|
||||
font_family: "Inter".into(),
|
||||
size_pt: 24.0,
|
||||
color: photocraft_color::Color::rgb(0.0, 0.0, 0.0),
|
||||
cache: Some(cache),
|
||||
..Default::default()
|
||||
};
|
||||
let title = Layer::new("Title", LayerContent::Text(text));
|
||||
let css = rule(&doc, 3, &title).unwrap_or_default();
|
||||
assert_eq!(
|
||||
css,
|
||||
".Title {\n font-size: 24px;\n font-family: \"Inter\";\n color: rgb(0, 0, 0);\n line-height: 1.2;\n text-align: left;\n position: absolute;\n left: 49px;\n top: 28px;\n z-index: 3;\n}\n"
|
||||
);
|
||||
// A group's own rule is its box, the canvas.
|
||||
let group = Layer::group("Group 1", Vec::new());
|
||||
assert_eq!(
|
||||
rule(&doc, 5, &group).unwrap(),
|
||||
".Group_1 {\n position: absolute;\n left: 0px;\n top: 0px;\n width: 400px;\n height: 300px;\n z-index: 5;\n}\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// Measured: Layer › Copy CSS on a group holding a 50 × 30 layer "2nd-Box" at (10, 20) writes the
|
||||
/// group's canvas box, then the layer, with no blank line; the group's end takes a place in the
|
||||
/// stack, so the layer is 3 and the group 4 above the Background.
|
||||
#[test]
|
||||
fn a_group_writes_its_box_then_its_layers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "2nd-Box"})).unwrap();
|
||||
s.edit("paint", |doc, active| {
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 20, 60, 50), &[0.16, 0.35, 0.78, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
|
||||
s.edit("paint", |doc, active| {
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(300, 200, 320, 220), &[0.16, 0.35, 0.78, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let group = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.children().is_some()).unwrap().2.id.0;
|
||||
let css = s.execute(ID, json!({"layer": group})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
let rest = css.split_once(' ').unwrap().1;
|
||||
assert_eq!(
|
||||
rest,
|
||||
"{\n position: absolute;\n left: 0px;\n top: 0px;\n width: 400px;\n height: 300px;\n z-index: 4;\n}\n\
|
||||
._2nd_Box {\n background-image: url(\"2nd-Box.png\");\n position: absolute;\n left: 10px;\n top: 20px;\n width: 50px;\n height: 30px;\n z-index: 3;\n}\n"
|
||||
);
|
||||
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.starts_with(".Top {\n") && css.contains(" z-index: 5;\n"), "{css}");
|
||||
}
|
||||
|
||||
/// Measured: Copy CSS is greyed out for a Solid Color fill layer without a shape.
|
||||
#[test]
|
||||
fn copy_css_is_off_for_a_fill_layer_without_a_shape() {
|
||||
let mut s = session("Box");
|
||||
assert!(s.is_enabled(ID));
|
||||
s.execute("layer.newFillLayer.solidColor", json!({})).unwrap();
|
||||
assert!(!s.is_enabled(ID), "a plain fill layer has no CSS");
|
||||
assert!(s.execute(ID, json!({})).is_err());
|
||||
}
|
||||
|
||||
/// Point type as Photoshop placed it (measured: text bounds and pixel bounds from its scripting
|
||||
/// interface, then the copied CSS).
|
||||
#[test]
|
||||
fn point_type_is_placed_as_photoshop_places_it() {
|
||||
let arial_cap = 1467.0 / 2048.0 * 24.0;
|
||||
let times_cap = 1356.0 / 2048.0 * 24.0;
|
||||
let css = |pix: Rect, ink: [f64; 4], cap: f64, size: f64, line_height: f64| {
|
||||
let at = place_point_text(pix, ink, 0.0, cap, size, line_height * size);
|
||||
(position(at.x), position(at.y))
|
||||
};
|
||||
let s = |a: &str, b: &str| (a.to_string(), b.to_string());
|
||||
// "Hello", Arial 24 at (50, 150).
|
||||
assert_eq!(css(Rect::new(52, 132, 104, 151), [1.875, -17.25, 53.71875, 0.1875], arial_cap, 24.0, 1.2), s("50.125", "127.1"));
|
||||
// The same at 48 px.
|
||||
assert_eq!(css(Rect::new(53, 65, 158, 101), [3.75, -34.5, 107.4375, 0.375], arial_cap * 2.0, 48.0, 1.2), s("49.25", "54.2"));
|
||||
// With a 40 pt leading: line-height 1.667.
|
||||
assert_eq!(css(Rect::new(202, 82, 254, 101), [1.875, -17.25, 53.71875, 0.1875], arial_cap, 24.0, 1.667), s("200.125", "71.496"));
|
||||
// "x": no descender.
|
||||
assert_eq!(css(Rect::new(300, 237, 312, 250), [0.1875, -12.5625, 11.8799, 0.0], arial_cap, 24.0, 1.2), s("299.812", "229.1"));
|
||||
// Descenders: "xyz", "xg", "Hg" in Arial, "Hg" and "xg" in Times New Roman.
|
||||
assert_eq!(css(Rect::new(50, 187, 86, 205), [0.1875, -12.5625, 35.71875, 4.875], arial_cap, 24.0, 1.2), s("49.812", "176.566"));
|
||||
assert_eq!(css(Rect::new(330, 237, 354, 255), [0.1875, -12.75, 23.6953, 4.875], arial_cap, 24.0, 1.2), s("329.812", "226.754"));
|
||||
assert_eq!(css(Rect::new(302, 262, 329, 285), [1.875, -17.25, 29.0273, 4.875], arial_cap, 24.0, 1.2), s("300.125", "256.254"));
|
||||
assert_eq!(css(Rect::new(50, 84, 79, 106), [0.375, -15.9375, 28.5, 5.0625], times_cap, 24.0, 1.2), s("49.625", "77.592"));
|
||||
assert_eq!(css(Rect::new(150, 89, 174, 106), [0.1875, -11.0625, 23.5, 5.0625], times_cap, 24.0, 1.2), s("149.812", "77.717"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_are_cut_after_three_decimals() {
|
||||
assert_eq!(position(49.8125), "49.812");
|
||||
assert_eq!(position(141.5 - 14.4), "127.1");
|
||||
assert_eq!(position(100.0), "100");
|
||||
assert_eq!(position(f64::INFINITY), "0");
|
||||
}
|
||||
|
||||
/// Photoshop 2025, paragraph text in a 200 × 120 box at (60, 40) that wraps to two lines whose
|
||||
/// pixels span 156 × 51: `left: 59.937px; top: 36.948px; width: 156px; height: 51px;`. Unlike point
|
||||
/// text it has a size, that of its text (not the box), and it's placed at its box, not where its
|
||||
/// first pixel is; an explicit leading moves it down by that much (36 px: `top: 72.948px`).
|
||||
#[test]
|
||||
fn paragraph_text_is_placed_at_its_box_and_sized_by_its_text() {
|
||||
let doc = session("Box").active().unwrap().doc.clone();
|
||||
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
|
||||
cache.fill_rect(Rect::new(62, 44, 218, 95), &[0.0, 0.0, 0.0, 1.0]);
|
||||
let mut text = photocraft_doc::TextLayer {
|
||||
text: "Hello world this wraps around".into(),
|
||||
font_family: "Inter".into(),
|
||||
size_pt: 24.0,
|
||||
cache: Some(cache),
|
||||
shape: photocraft_doc::text::TextShape::Box { x: 0.0, y: 0.0, width: 200.0, height: 120.0 },
|
||||
transform: photocraft_geom::Affine::translate(60.0, 40.0),
|
||||
..Default::default()
|
||||
};
|
||||
let css = rule(&doc, 3, &Layer::new("Para", LayerContent::Text(text.clone()))).unwrap_or_default();
|
||||
assert_eq!(
|
||||
css,
|
||||
".Para {\n font-size: 24px;\n font-family: \"Inter\";\n color: rgb(0, 0, 0);\n line-height: 1.2;\n text-align: left;\n position: absolute;\n left: 60px;\n top: 40px;\n width: 156px;\n height: 51px;\n z-index: 3;\n}\n"
|
||||
);
|
||||
let style = photocraft_doc::text::CharStyle { font_family: "Inter".into(), size_pt: 24.0, leading_pt: Some(36.0), ..Default::default() };
|
||||
text.runs = vec![photocraft_doc::text::TextRun { len: text.text.len(), style }];
|
||||
let css = rule(&doc, 3, &Layer::new("Para", LayerContent::Text(text))).unwrap_or_default();
|
||||
assert!(
|
||||
css.contains(" line-height: 1.5;\n text-align: left;\n position: absolute;\n left: 60px;\n top: 76px;\n width: 156px;\n height: 51px;\n"),
|
||||
"{css}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_and_names_are_written_as_photoshop_does() {
|
||||
assert_eq!(number(48.9374), "48.937");
|
||||
assert_eq!(number(27.6), "27.6");
|
||||
assert_eq!(number(100.0), "100");
|
||||
assert_eq!(number(-0.0001), "0");
|
||||
assert_eq!(number(f64::NAN), "0");
|
||||
assert_eq!(class_name("My Box 2"), "My_Box_2");
|
||||
assert_eq!(class_name(""), "layer");
|
||||
}
|
||||
|
||||
/// Photoshop 2025: a class can't start with a digit, so a layer named "2nd Box" gets a `_` in
|
||||
/// front; a hyphen becomes `_` like the other punctuation ("-2x" is `._2x`, "my-box" `.my_box`).
|
||||
#[test]
|
||||
fn class_names_never_start_with_a_digit() {
|
||||
for (name, class) in [("2nd Box", "._2nd_Box {\n"), ("-2x", "._2x {\n"), ("my-box", ".my_box {\n")] {
|
||||
let css = session(name).execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.starts_with(class), "{name}: {css}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Names go into quoted CSS strings: a `"`, a backslash or a line break in one is escaped, so the
|
||||
/// string doesn't end early and keeps the name (Photoshop writes them unescaped, which breaks
|
||||
/// the rule). Ordinary names are written as before.
|
||||
#[test]
|
||||
fn names_in_quoted_values_are_escaped() {
|
||||
let css = session("Say \"hi\"").execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.contains(" background-image: url(\"Say \\\"hi\\\".png\");\n"), "{css}");
|
||||
let css = session("a\\b\nc").execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.contains(" background-image: url(\"a\\\\b\\a c.png\");\n"), "{css}");
|
||||
let doc = session("Box").active().unwrap().doc.clone();
|
||||
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
|
||||
cache.fill_rect(Rect::new(49, 28, 120, 52), &[0.0, 0.0, 0.0, 1.0]);
|
||||
let text = photocraft_doc::TextLayer { font_family: "My \"Font\"".into(), size_pt: 24.0, cache: Some(cache), ..Default::default() };
|
||||
let css = rule(&doc, 3, &Layer::new("Title", LayerContent::Text(text))).unwrap_or_default();
|
||||
assert!(css.contains(" font-family: \"My \\\"Font\\\"\";\n"), "{css}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_and_layers_without_css_are_errors() {
|
||||
let mut s = session("Box");
|
||||
assert!(s.execute(ID, json!({"layer": "x"})).is_err());
|
||||
assert!(s.execute(ID, json!({"layer": 999_999})).is_err());
|
||||
assert!(s.execute(ID, json!([])).is_err());
|
||||
s.execute("layer.new.group", json!({})).unwrap();
|
||||
assert!(s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().contains(" width: 400px;\n"), "an empty group writes its box");
|
||||
let mut empty = Session::new();
|
||||
assert!(empty.execute(ID, json!({})).is_err(), "no document");
|
||||
}
|
||||
|
||||
/// A live rounded rectangle gives its corners as Photoshop writes them, before the fill: one
|
||||
/// value when all four are equal, else top-left, top-right, bottom-right, bottom-left; a sharp
|
||||
/// one writes none.
|
||||
#[test]
|
||||
fn a_rounded_rectangle_writes_its_border_radius() {
|
||||
let mut s = session("Box");
|
||||
let id = s.execute("shape.create", json!({"kind": "roundedRect", "rect": [40, 30, 120, 80], "radius": 12, "fill": "#ff0000"})).unwrap()["layer"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.contains(" {\n border-radius: 12px;\n background-color: rgb(255, 0, 0);\n position: absolute;\n"), "{css}");
|
||||
s.execute("shape.edit", json!({"layer": id, "radii": [20, 0, 10.5, 5]})).unwrap();
|
||||
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.contains(" border-radius: 20px 0px 10.5px 5px;\n background-color: rgb(255, 0, 0);\n"), "{css}");
|
||||
s.execute("shape.edit", json!({"layer": id, "radii": [0, 0, 0, 0]})).unwrap();
|
||||
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(!css.contains("border-radius") && css.contains(" background-color: rgb(255, 0, 0);\n"), "{css}");
|
||||
// Scaled 2× on both axes, its corners are twice as round.
|
||||
s.execute("shape.edit", json!({"layer": id, "radii": [12, 12, 12, 12]})).unwrap();
|
||||
s.execute("shape.edit", json!({"layer": id, "transform": [2, 0, 0, 2, 0, 0]})).unwrap();
|
||||
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.contains(" border-radius: 24px;\n background-color: rgb(255, 0, 0);\n"), "{css}");
|
||||
}
|
||||
|
||||
/// Scaled 200 % across and 100 % down, a rounded rectangle's corners are 24 × 12 px ellipses, but
|
||||
/// it keeps one radius per corner (12): no `border-radius` rather than a circular one. A flipped
|
||||
/// one, whose outline runs the other way, keeps its circular corners and writes them.
|
||||
#[test]
|
||||
fn an_unequally_scaled_rounded_rectangle_writes_no_border_radius() {
|
||||
let mut s = session("Box");
|
||||
let create = json!({"kind": "roundedRect", "rect": [40, 30, 120, 80], "radius": 12, "fill": "#ff0000"});
|
||||
let id = s.execute("shape.create", create.clone()).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("shape.edit", json!({"layer": id, "transform": [2, 0, 0, 1, 0, 0]})).unwrap();
|
||||
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(!css.contains("border-radius") && css.contains(" {\n background-color: rgb(255, 0, 0);\n"), "{css}");
|
||||
let flipped = s.execute("shape.create", create).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("shape.edit", json!({"layer": flipped, "transform": [-1, 0, 0, 1, 400, 0]})).unwrap();
|
||||
let css = s.execute(ID, json!({"layer": flipped})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.contains(" {\n border-radius: 12px;\n background-color: rgb(255, 0, 0);\n"), "{css}");
|
||||
}
|
||||
|
||||
/// A live ellipse writes `border-radius: 50%;` where a rounded rectangle writes its radii, so the
|
||||
/// rule draws an ellipse, not a rectangle; other live shapes (a star here) write no geometry.
|
||||
#[test]
|
||||
fn an_ellipse_writes_a_half_border_radius() {
|
||||
let mut s = session("Box");
|
||||
let id = s.execute("shape.create", json!({"kind": "ellipse", "rect": [40, 30, 120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
|
||||
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(css.contains(" {\n border-radius: 50%;\n background-color: rgb(255, 0, 0);\n position: absolute;\n"), "{css}");
|
||||
let star = s.execute("shape.create", json!({"kind": "star", "rect": [40, 30, 120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
|
||||
let css = s.execute(ID, json!({"layer": star})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(!css.contains("border-radius") && css.contains(" {\n background-color: rgb(255, 0, 0);\n"), "{css}");
|
||||
}
|
||||
|
||||
/// `css` without its double-quoted strings (escapes inside them skipped).
|
||||
fn outside_strings(css: &str) -> String {
|
||||
let (mut out, mut quoted, mut escaped) = (String::new(), false, false);
|
||||
for c in css.chars() {
|
||||
match (quoted, escaped, c) {
|
||||
(true, true, _) => escaped = false,
|
||||
(true, false, '\\') => escaped = true,
|
||||
(_, false, '"') => quoted = !quoted,
|
||||
(false, _, _) => out.push(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A name with a comment closer can't end a comment or break the rule: outside the quoted image
|
||||
/// name there is no `*/`, and the class is sanitised.
|
||||
#[test]
|
||||
fn a_comment_closer_in_a_name_stays_inside_the_string() {
|
||||
let css = session("a */ b").execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert!(!outside_strings(&css).contains("*/"), "{css}");
|
||||
assert!(css.starts_with(".a____b {\n background-image: url(\"a */ b.png\");\n"), "{css}");
|
||||
}
|
||||
|
||||
/// Layer effects aren't written: a layer with a drop shadow gives the same rule as without it,
|
||||
/// placed and sized by its pixels, not the shadow.
|
||||
#[test]
|
||||
fn a_layer_with_a_drop_shadow_writes_its_rule_without_the_effect() {
|
||||
let mut s = session("Box");
|
||||
let plain = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
s.edit("fx", |doc, active| {
|
||||
let l = doc.layer_mut(active.unwrap()).unwrap();
|
||||
l.effects.enabled = true;
|
||||
l.effects.items.push(photocraft_doc::effects::Effect::default_drop_shadow());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
assert_eq!(css, plain);
|
||||
assert!(!css.contains("shadow"), "{css}");
|
||||
}
|
||||
|
||||
/// Real point type goes through its layout: "Hello" at a baseline of 150 is placed by its line
|
||||
/// box, which starts above its first pixel (Photoshop: 127.1 for pixels from 132), not at it.
|
||||
#[test]
|
||||
fn point_type_is_placed_by_its_line_box() {
|
||||
let mut s = session("Box");
|
||||
let id = s.execute("type.create", json!({"x": 50, "y": 150, "text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap();
|
||||
let doc = &s.active().unwrap().doc;
|
||||
let pix = photocraft_doc::comps::position_bounds(doc.walk().into_iter().find(|(_, _, l)| l.id.0 == id).unwrap().2);
|
||||
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
|
||||
let value = |key: &str| css.split(&format!(" {key}: ")).nth(1).and_then(|v| v.split("px;").next()).and_then(|v| v.parse::<f64>().ok()).unwrap();
|
||||
let (left, top) = (value("left"), value("top"));
|
||||
assert!((left - 50.0).abs() < 1.0, "left at the origin, within the pixel rounding: {css}");
|
||||
assert!(top < f64::from(pix.y0) - 2.0 && top > 150.0 - 28.8, "top {top} above the pixels at {}: {css}", pix.y0);
|
||||
}
|
||||
@@ -45,10 +45,10 @@ fn edits_preserve_mask_pixels_and_layer_at_all_depths_with_undo_redo() {
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(background));
|
||||
assert_eq!(s.active().unwrap().history.entries().len(), count + 1);
|
||||
// Properties invalidate the composite as far as their undo would (the masked layer is
|
||||
// empty here; the adjustment reaches everything).
|
||||
// empty here, and the adjustment reaches only what lies beneath it: nothing, #9329).
|
||||
let damage = s.active().unwrap().last_damage;
|
||||
assert_eq!(damage, crate::layer_multi_cmds::step_damage(&before, &s.active().unwrap().doc));
|
||||
assert_eq!(damage.is_none(), adjustment);
|
||||
assert_eq!(damage, Some(Rect::EMPTY), "adjustment: {adjustment}");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
|
||||
@@ -20,9 +20,9 @@ mod selection;
|
||||
mod structure;
|
||||
|
||||
use align::{align, distribute};
|
||||
pub(crate) use damage::grow_hint;
|
||||
#[cfg(any(test, debug_assertions))]
|
||||
pub(crate) use damage::hint_misses;
|
||||
pub(crate) use damage::note_insert;
|
||||
pub(crate) use damage::{hint_misses, small_change_pct};
|
||||
pub use damage::{layer_bounds, same_pixels, selection_only_change, step_damage};
|
||||
use moves::link_groups;
|
||||
pub(crate) use moves::shift_surface;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use photocraft_color::{PixelFormat, SampleType};
|
||||
use photocraft_compose::Ancestors;
|
||||
|
||||
use super::{Document, Layer, LayerContent, Rect, Session, VideoData};
|
||||
use super::{Document, Layer, LayerContent, LayerId, Rect, VideoData};
|
||||
|
||||
/// Calls `f` with the rect of every tile that differs between two surfaces of the same format and
|
||||
/// default pixel: a tile only one side has, or a different copy-on-write tile pointer at the same
|
||||
@@ -237,7 +238,8 @@ fn doc_pixels_equal(a: &Document, b: &Document) -> bool {
|
||||
clipping_path: _,
|
||||
quick_mask,
|
||||
quick_mask_unselected: _,
|
||||
patterns,
|
||||
// Compared by `patterns_pixels_equal`.
|
||||
patterns: _,
|
||||
color_table,
|
||||
duotone,
|
||||
layer_comps: _,
|
||||
@@ -264,11 +266,57 @@ fn doc_pixels_equal(a: &Document, b: &Document) -> bool {
|
||||
(Some(x), Some(y)) => alpha_channels_equal(x, y),
|
||||
_ => false,
|
||||
}
|
||||
&& *patterns == b.patterns
|
||||
&& patterns_pixels_equal(a, b)
|
||||
&& *color_table == b.color_table
|
||||
&& *duotone == b.duotone
|
||||
}
|
||||
|
||||
/// Whether `a`'s and `b`'s pattern libraries composite the same. Layers draw a pattern only
|
||||
/// through a reference that `photocraft_doc::pattern::find` resolves (fill and shape layers,
|
||||
/// Pattern Overlay, pattern strokes and glows, Bevel textures), so patterns appended after an
|
||||
/// unchanged prefix change nothing unless some reference now resolves differently: to an
|
||||
/// appended pattern where it resolved to an earlier one or to none. A same-named addition that
|
||||
/// loses to an existing id match changes nothing. Pattern Stamp copies its pattern into the
|
||||
/// document this way on first use; the pixels it paints are a raster change, diffed by tile like
|
||||
/// any other.
|
||||
fn patterns_pixels_equal(a: &Document, b: &Document) -> bool {
|
||||
use photocraft_doc::effects::{Effect, FxPaint};
|
||||
use photocraft_doc::{Fill, Pattern, pattern::find};
|
||||
if a.patterns == b.patterns {
|
||||
return true;
|
||||
}
|
||||
if a.patterns.len() >= b.patterns.len() || !b.patterns.starts_with(a.patterns.as_slice()) {
|
||||
return false;
|
||||
}
|
||||
// The index a reference resolves to; the prefix is equal, so equal indices mean equal patterns.
|
||||
let at = |ps: &[Pattern], id: &str, name: &str| find(ps, id, name).and_then(|p| ps.iter().position(|q| std::ptr::eq(q, p)));
|
||||
let hits = |id: &str, name: &str| at(&a.patterns, id, name) != at(&b.patterns, id, name);
|
||||
let fill = |f: &Fill| matches!(f, Fill::Pattern { id, name, .. } if hits(id, name));
|
||||
let paint = |p: &FxPaint| matches!(p, FxPaint::Pattern { id, name, .. } if hits(id, name));
|
||||
// Past a nesting depth no real document reaches, assume a reference (unequal), as
|
||||
// `pixels_equal_with` does.
|
||||
fn any_layer(layers: &[Layer], depth: usize, refers: &dyn Fn(&Layer) -> bool) -> bool {
|
||||
depth >= 256 || layers.iter().any(|l| refers(l) || matches!(&l.content, LayerContent::Group(g) if any_layer(&g.children, depth + 1, refers)))
|
||||
}
|
||||
let refers = |l: &Layer| {
|
||||
let effect = l.effects.items.iter().any(|e| match e {
|
||||
Effect::OuterGlow(g) | Effect::InnerGlow(g) => paint(&g.paint),
|
||||
Effect::Stroke(s) => paint(&s.paint),
|
||||
Effect::PatternOverlay { id, name, .. } => hits(id, name),
|
||||
Effect::BevelEmboss(b) => b.texture.as_ref().is_some_and(|t| hits(&t.id, &t.name)),
|
||||
Effect::DropShadow(_) | Effect::InnerShadow(_) | Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } | Effect::Satin(_) => false,
|
||||
});
|
||||
effect
|
||||
|| match &l.content {
|
||||
LayerContent::Fill(f) => fill(f),
|
||||
LayerContent::Shape(s) => s.fill.as_ref().is_some_and(fill) || s.stroke.as_ref().is_some_and(|st| fill(&st.paint)),
|
||||
// A smart object draws its cache; its own document holds its own patterns.
|
||||
LayerContent::Raster(_) | LayerContent::Group(_) | LayerContent::Adjustment(_) | LayerContent::Text(_) | LayerContent::Smart(_) => false,
|
||||
}
|
||||
};
|
||||
!any_layer(&b.layers, 0, &refers)
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` composite to the same pixels: they differ at most in fields the
|
||||
/// compositor never reads (selection, guides, paths, names, …), by the same classification as
|
||||
/// [`step_damage`] but without computing any bounds. Cheap: pixels compare by tile pointer.
|
||||
@@ -384,9 +432,9 @@ pub fn selection_only_change(a: &Document, b: &Document) -> bool {
|
||||
/// [`one_sided_bounds`]); one that draws nothing ([`inert_at`]) changes nothing. `None`
|
||||
/// (composite everything) when the step touched anything the layer walk cannot bound:
|
||||
/// document-level fields the compositor reads (canvas size, mode, depth, profile, global light,
|
||||
/// patterns, channels, palettes), layer order and kind changes, layers added or removed that
|
||||
/// reach outside their own bounds, layer properties that do (clipping, excluded channels —
|
||||
/// what `layer.setProps` already reports as unbounded), and video layers. Inserting a copy of a
|
||||
/// patterns, channels, palettes), kind changes, reorders of clipped layers, layers added or
|
||||
/// removed that reach outside their own bounds, clipping or channel exclusion on a group, and
|
||||
/// video layers. A reorder damages the moved layers at both ends ([`moved_ids`]). Inserting a copy of a
|
||||
/// 12 MP layer used to recomposite every layer of the document (#2883, P8/P9 in
|
||||
/// `perf/budgets.toml`).
|
||||
///
|
||||
@@ -397,8 +445,6 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
|
||||
if !doc_pixels_equal(a, b) {
|
||||
return None;
|
||||
}
|
||||
/// The list holding a sibling list's parent group, and the group's index there.
|
||||
type Outer<'d> = Option<(&'d [Layer], usize)>;
|
||||
/// What the groups around a sibling list add to a change inside it: the summed reach of
|
||||
/// their effects, and whether any lays effects out over its frame.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -406,21 +452,67 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
|
||||
reach: i32,
|
||||
spans_frame: bool,
|
||||
}
|
||||
fn walk(xs: &[Layer], ys: &[Layer], (ox, oy): (Outer, Outer), around: Around, a: &Document, b: &Document, out: &mut Rect) -> bool {
|
||||
fn add(out: &mut Rect, r: Rect) {
|
||||
if !r.is_empty() {
|
||||
*out = if out.is_empty() { r } else { out.union(&r) };
|
||||
}
|
||||
}
|
||||
fn walk<'d>(
|
||||
xs: &'d [Layer],
|
||||
ys: &'d [Layer],
|
||||
(px, py): (&Ancestors<'d>, &Ancestors<'d>),
|
||||
around: Around,
|
||||
a: &Document,
|
||||
b: &Document,
|
||||
out: &mut Rect,
|
||||
) -> bool {
|
||||
let depth = b.depth;
|
||||
// The effects of the groups around reach past a change inside them (a parent's drop shadow).
|
||||
let grow = |r: Rect, canvas: Rect| if r.is_empty() { r } else { r.inflate(around.reach).intersect(&canvas) };
|
||||
// So bound a change 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 near = |canvas: Rect| canvas.inflate(around.reach);
|
||||
// Pair the layers by id, stepping over layers only one side has: one that draws nothing
|
||||
// changes no pixels (a new empty layer or group, #1771), any other only where it draws.
|
||||
let one_sided = |layers: &[Layer], k: usize, outer: Outer, canvas: Rect, out: &mut Rect| {
|
||||
let Some(r) = one_sided_bounds(layers, k, outer, canvas) else { return false };
|
||||
if !r.is_empty() {
|
||||
*out = if out.is_empty() { r } else { out.union(&r) };
|
||||
}
|
||||
let one_sided = |layers: &[Layer], k: usize, path: &Ancestors, canvas: Rect, out: &mut Rect| {
|
||||
let Some(r) = one_sided_bounds(layers, k, path, depth, near(canvas)) else { return false };
|
||||
add(out, grow(r, canvas));
|
||||
true
|
||||
};
|
||||
// A reorder: the layers that moved change pixels only where they draw (or, for an
|
||||
// adjustment, reach) at each end, as hiding them there and showing them here would.
|
||||
let Some(moved) = moved_ids(xs, ys) else { return false };
|
||||
for &id in &moved {
|
||||
let (Some(xk), Some(yk)) = (xs.iter().position(|l| l.id == id), ys.iter().position(|l| l.id == id)) else { return false };
|
||||
let (x, y) = (&xs[xk], &ys[yk]);
|
||||
// A clipped layer changes base when it moves, and a layer moving to or from below
|
||||
// clipped layers changes theirs.
|
||||
let clips = |ls: &[Layer], k: usize| ls[k].clipped || ls.get(k + 1).is_some_and(|above| above.clipped);
|
||||
if clips(xs, xk) || clips(ys, yk) || !contained(x, 0) || !contained(y, 0) {
|
||||
return false;
|
||||
}
|
||||
let (Some(bx), Some(by)) = (
|
||||
photocraft_compose::change_bounds_in(xs, xk, px, depth, near(a.bounds())),
|
||||
photocraft_compose::change_bounds_in(ys, yk, py, depth, near(b.bounds())),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
add(out, grow(bx, a.bounds()));
|
||||
add(out, grow(by, b.bounds()));
|
||||
}
|
||||
let (mut i, mut j) = (0, 0);
|
||||
loop {
|
||||
let (x, y) = match (xs.get(i), ys.get(j)) {
|
||||
(None, None) => return true,
|
||||
(Some(x), Some(y)) if x.id == y.id => (x, y),
|
||||
(Some(x), _) if moved.contains(&x.id) => {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
(_, Some(y)) if moved.contains(&y.id) => {
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
_ if inert_at(ys, j) => {
|
||||
j += 1;
|
||||
continue;
|
||||
@@ -430,20 +522,20 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
|
||||
continue;
|
||||
}
|
||||
(_, Some(y)) if xs.iter().all(|x| x.id != y.id) => {
|
||||
if !one_sided(ys, j, oy, b.bounds(), out) {
|
||||
if !one_sided(ys, j, py, b.bounds(), out) {
|
||||
return false;
|
||||
}
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
(Some(x), _) if ys.iter().all(|y| y.id != x.id) => {
|
||||
if !one_sided(xs, i, ox, a.bounds(), out) {
|
||||
if !one_sided(xs, i, px, a.bounds(), out) {
|
||||
return false;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// Both sides have the layer, in another order.
|
||||
// Both sides have the layer, in another order (`moved_ids` pairs the rest).
|
||||
_ => return false,
|
||||
};
|
||||
let (xk, yk) = (i, j);
|
||||
@@ -452,21 +544,39 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
|
||||
if x.video.is_some() || y.video.is_some() {
|
||||
return false;
|
||||
}
|
||||
// Clipping and channel exclusion change how *other* layers render, outside this
|
||||
// layer's own bounds; they have no bounded damage.
|
||||
if x.clipped != y.clipped || x.excluded_channels != y.excluded_channels {
|
||||
// Clipping and channel exclusion on a group change how it composites its children;
|
||||
// they have no bounded damage. Channel exclusion on any other layer is per pixel where
|
||||
// it draws, which its change bounds below cover.
|
||||
if (x.clipped != y.clipped || x.excluded_channels != y.excluded_channels) && (x.children().is_some() || y.children().is_some()) {
|
||||
return false;
|
||||
}
|
||||
if x.clipped != y.clipped {
|
||||
// The clipped layers directly above change base too (from this layer to the one
|
||||
// beneath it, or back). A group base composites differently with clipped layers
|
||||
// (a pass-through one holding an adjustment then renders isolated), so not that.
|
||||
let base_is_group = |ls: &[Layer], k: usize| ls[..k].iter().rev().find(|l| !l.clipped).is_some_and(|l| l.children().is_some());
|
||||
if base_is_group(xs, xk) || base_is_group(ys, yk) {
|
||||
return false;
|
||||
}
|
||||
for (ls, k, path, d) in [(xs, xk, px, a), (ys, yk, py, b)] {
|
||||
for c in (k + 1..ls.len()).take_while(|&c| ls[c].clipped) {
|
||||
let Some(r) = photocraft_compose::change_bounds_in(ls, c, path, depth, near(d.bounds())) else { return false };
|
||||
add(out, grow(r, d.bounds()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let tiles = tile_damage(x, y);
|
||||
if tiles != Some(Rect::EMPTY) {
|
||||
// Both sides' extents: a move changes pixels where it left and where it landed.
|
||||
// A clipped adjustment reaches as far as its base (#6535).
|
||||
let (Some(bx), Some(by)) =
|
||||
(photocraft_compose::change_bounds_in(xs, xk, ox, a.bounds()), photocraft_compose::change_bounds_in(ys, yk, oy, b.bounds()))
|
||||
else {
|
||||
// A clipped adjustment reaches as far as its base (#6535). Grown by what the
|
||||
// groups around reach, as any change inside them (a parent's drop shadow).
|
||||
let (Some(bx), Some(by)) = (
|
||||
photocraft_compose::change_bounds_in(xs, xk, px, depth, near(a.bounds())),
|
||||
photocraft_compose::change_bounds_in(ys, yk, py, depth, near(b.bounds())),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
let whole = bx.union(&by);
|
||||
let whole = grow(bx, a.bounds()).union(&grow(by, b.bounds()));
|
||||
// Only pixels changed: the changed tiles, grown by what the groups around reach,
|
||||
// never more than the whole extents. Effects laid out over a frame repaint it
|
||||
// everywhere when it moves (#4053), so then the whole extents.
|
||||
@@ -474,19 +584,33 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
|
||||
|| (photocraft_compose::effects::spans_frame(y)
|
||||
&& photocraft_compose::effects_frame(x, a.bounds()) != photocraft_compose::effects_frame(y, b.bounds()));
|
||||
let d = match tiles {
|
||||
Some(t) if !frame_moved => t.inflate(around.reach).intersect(&whole.inflate(around.reach)).intersect(&b.bounds()),
|
||||
Some(t) if !frame_moved => t.inflate(around.reach).intersect(&whole).intersect(&b.bounds()),
|
||||
_ => whole,
|
||||
};
|
||||
*out = out.union(&d);
|
||||
}
|
||||
match (x.children(), y.children()) {
|
||||
(Some(xc), Some(yc)) => {
|
||||
let reach = |l: &Layer| if photocraft_compose::effects::has_effects(l) { photocraft_compose::effects::margin(l) } else { 0 };
|
||||
// A change inside that moves the group's frame (a layer added, removed or
|
||||
// hidden at its edge) lays effects spanning that frame out again over the
|
||||
// whole group, beyond the change (#4053).
|
||||
let spans = photocraft_compose::effects::spans_frame;
|
||||
if (spans(x) || spans(y)) && photocraft_compose::effects_frame(x, a.bounds()) != photocraft_compose::effects_frame(y, b.bounds()) {
|
||||
let (Some(bx), Some(by)) = (
|
||||
photocraft_compose::change_bounds_in(xs, xk, px, depth, near(a.bounds())),
|
||||
photocraft_compose::change_bounds_in(ys, yk, py, depth, near(b.bounds())),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
add(out, grow(bx, a.bounds()));
|
||||
add(out, grow(by, b.bounds()));
|
||||
}
|
||||
let inner = Around {
|
||||
reach: around.reach.saturating_add(reach(x).max(reach(y))),
|
||||
reach: around.reach.saturating_add(effects_reach(x).max(effects_reach(y))),
|
||||
spans_frame: around.spans_frame || photocraft_compose::effects::spans_frame(x) || photocraft_compose::effects::spans_frame(y),
|
||||
};
|
||||
if !walk(xc, yc, (Some((xs, xk)), Some((ys, yk))), inner, a, b, out) {
|
||||
let (qx, qy): (Vec<_>, Vec<_>) = (px.iter().copied().chain([(xs, xk)]).collect(), py.iter().copied().chain([(ys, yk)]).collect());
|
||||
if !walk(xc, yc, (&qx, &qy), inner, a, b, out) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -496,7 +620,49 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
|
||||
}
|
||||
}
|
||||
let mut out = Rect::EMPTY;
|
||||
if walk(&a.layers, &b.layers, (None, None), Around { reach: 0, spans_frame: false }, a, b, &mut out) { Some(out) } else { None }
|
||||
if walk(&a.layers, &b.layers, (&[], &[]), Around { reach: 0, spans_frame: false }, a, b, &mut out) { Some(out) } else { None }
|
||||
}
|
||||
|
||||
/// The layers both sibling lists hold that changed places (`None` when the lists are too long to
|
||||
/// compare): those outside a longest common subsequence of the ids both sides have, so a bring
|
||||
/// forward moves one layer, not every layer it passes.
|
||||
fn moved_ids(xs: &[Layer], ys: &[Layer]) -> Option<Vec<LayerId>> {
|
||||
use std::collections::HashSet;
|
||||
if xs.len() == ys.len() && xs.iter().zip(ys).all(|(x, y)| x.id == y.id) {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let in_y: HashSet<LayerId> = ys.iter().map(|l| l.id).collect();
|
||||
let cx: Vec<LayerId> = xs.iter().map(|l| l.id).filter(|id| in_y.contains(id)).collect();
|
||||
let in_x: HashSet<LayerId> = cx.iter().copied().collect();
|
||||
let cy: Vec<LayerId> = ys.iter().map(|l| l.id).filter(|id| in_x.contains(id)).collect();
|
||||
if cx == cy {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let (n, m) = (cx.len(), cy.len());
|
||||
// An O(n·m) table: past a few million cells, call it unbounded instead.
|
||||
if n.saturating_mul(m) > 4_000_000 {
|
||||
return None;
|
||||
}
|
||||
let w = m + 1;
|
||||
let mut t = vec![0u32; (n + 1) * w];
|
||||
for i in (0..n).rev() {
|
||||
for j in (0..m).rev() {
|
||||
t[i * w + j] = if cx[i] == cy[j] { t[(i + 1) * w + j + 1] + 1 } else { t[(i + 1) * w + j].max(t[i * w + j + 1]) };
|
||||
}
|
||||
}
|
||||
let (mut i, mut j, mut kept) = (0, 0, HashSet::new());
|
||||
while i < n && j < m {
|
||||
if cx[i] == cy[j] {
|
||||
kept.insert(cx[i]);
|
||||
i += 1;
|
||||
j += 1;
|
||||
} else if t[(i + 1) * w + j] >= t[i * w + j + 1] {
|
||||
i += 1;
|
||||
} else {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
Some(cx.into_iter().filter(|id| !kept.contains(id)).collect())
|
||||
}
|
||||
|
||||
/// How many tiles that differ between `before` and `after` (in the surfaces of layers both have)
|
||||
@@ -514,9 +680,54 @@ pub(crate) fn hint_misses(before: &Document, after: &Document, hint: Rect) -> us
|
||||
misses
|
||||
}
|
||||
|
||||
/// `hint`, a command's own rect for pixels it changed in one of `doc`'s layers, grown as far as
|
||||
/// [`step_damage`] grows a change there ([`grow_in_layer`], then by the effects of the groups
|
||||
/// around the layer), for whichever layer that was: the hint doesn't say. A brush dab on a
|
||||
/// feathered mask changes a soft ring around the dab; cut to the bare dab, the ring stayed stale.
|
||||
/// Layers the compositor doesn't draw are skipped as it skips them (a hidden layer, a clipped
|
||||
/// layer over a hidden base, and everything inside a hidden group): a change there shows nowhere,
|
||||
/// and growing by a hidden layer's effects widened every dab elsewhere.
|
||||
pub(crate) fn grow_hint(doc: &Document, hint: Rect) -> Rect {
|
||||
fn walk(layers: &[Layer], reach: i32, hint: Rect, out: &mut Rect) {
|
||||
let mut base_visible = true;
|
||||
for l in layers {
|
||||
if !l.clipped {
|
||||
base_visible = l.visible;
|
||||
}
|
||||
if !l.visible || !base_visible {
|
||||
continue;
|
||||
}
|
||||
let feather = l.mask.as_ref().map_or(0.0, |m| m.feather);
|
||||
*out = out.union(&grow_in_layer(l, hint, feather).inflate(reach));
|
||||
if let Some(children) = l.children() {
|
||||
walk(children, reach.saturating_add(effects_reach(l)), hint, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = hint;
|
||||
if !hint.is_empty() {
|
||||
walk(&doc.layers, 0, hint, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How far layer `l`'s own effects carry a change to its pixels: 0 without effects.
|
||||
fn effects_reach(l: &Layer) -> i32 {
|
||||
if photocraft_compose::effects::has_effects(l) { photocraft_compose::effects::margin(l) } else { 0 }
|
||||
}
|
||||
|
||||
/// `r`, changed pixels of a surface layer `l` draws from, grown as far as the change can show in
|
||||
/// `l`'s own render: by the `feather` (in pixels) the compositor blurs the surface by, then by
|
||||
/// `l`'s effects.
|
||||
fn grow_in_layer(l: &Layer, r: Rect, feather: f32) -> Rect {
|
||||
let r = if feather > 0.0 { photocraft_vector::feather::grow(r, photocraft_vector::feather::feather_sigma(feather)) } else { r };
|
||||
let margin = effects_reach(l);
|
||||
if r.is_empty() || margin == 0 { r } else { r.inflate(margin) }
|
||||
}
|
||||
|
||||
/// The pixels a change from layer `a` to layer `b` (the same layer on either side of a step) can
|
||||
/// have changed when only the pixels of its surfaces changed: the tiles that differ
|
||||
/// ([`surface_damage`]), a mask's grown by its feather, all grown by the layer's own effects.
|
||||
/// ([`surface_damage`]), grown as far as each shows in the layer's render ([`grow_in_layer`]).
|
||||
/// Empty when the layers render identically. `None` when anything else changed (a property, the
|
||||
/// content kind, a surface's format or default pixel): the caller then takes the layer's whole
|
||||
/// extents. Children of groups are not compared (the caller walks them).
|
||||
@@ -524,34 +735,33 @@ fn tile_damage(a: &Layer, b: &Layer) -> Option<Rect> {
|
||||
let mut tiles = Rect::EMPTY;
|
||||
let only_pixels = layer_pixels_cmp(a, b, &mut |x, y, feather| {
|
||||
let Some(r) = surface_damage(x, y) else { return false };
|
||||
let r = if feather > 0.0 { photocraft_vector::feather::grow(r, photocraft_vector::feather::feather_sigma(feather)) } else { r };
|
||||
tiles = tiles.union(&r);
|
||||
// Effects are equal on both sides here (they are compared before any surface).
|
||||
tiles = tiles.union(&grow_in_layer(b, r, feather));
|
||||
true
|
||||
});
|
||||
if !only_pixels {
|
||||
return None;
|
||||
}
|
||||
// Effects are equal on both sides here (they are compared before any surface).
|
||||
let margin = if photocraft_compose::effects::has_effects(b) { photocraft_compose::effects::margin(b) } else { 0 };
|
||||
Some(if tiles.is_empty() || margin == 0 { tiles } else { tiles.inflate(margin) })
|
||||
only_pixels.then_some(tiles)
|
||||
}
|
||||
|
||||
/// Neither `l` nor anything inside it is a video layer or excludes channels.
|
||||
fn contained(l: &Layer, depth: usize) -> bool {
|
||||
depth < 256 && l.video.is_none() && l.excluded_channels == 0 && l.children().is_none_or(|c| c.iter().all(|c| contained(c, depth + 1)))
|
||||
}
|
||||
|
||||
/// The pixels adding or removing `layers[k]` can change, when that is bounded: its change bounds
|
||||
/// (`photocraft_compose::change_bounds_in`: not for an unclipped adjustment, or a pass-through
|
||||
/// group holding one; a clipped adjustment's are its base's), provided it isn't the clipping base
|
||||
/// (`photocraft_compose::change_bounds_in`: an unclipped adjustment's cover the layers beneath it
|
||||
/// in its isolation scope; a clipped adjustment's are its base's), provided it isn't the clipping base
|
||||
/// of clipped layers above it (they would change base), and neither it nor anything inside it is
|
||||
/// a video layer or excludes channels (both reach outside the layer's bounds, see
|
||||
/// [`step_damage`]).
|
||||
fn one_sided_bounds(layers: &[Layer], k: usize, outer: Option<(&[Layer], usize)>, canvas: Rect) -> Option<Rect> {
|
||||
fn contained(l: &Layer, depth: usize) -> bool {
|
||||
depth < 256 && l.video.is_none() && l.excluded_channels == 0 && l.children().is_none_or(|c| c.iter().all(|c| contained(c, depth + 1)))
|
||||
}
|
||||
/// a video layer (it reaches outside the layer's bounds, see [`step_damage`]) or excludes
|
||||
/// channels. Channel exclusion is per pixel where the layer draws, so it doesn't actually reach
|
||||
/// further (`step_damage` bounds a property change of it that way); here it stays unbounded only
|
||||
/// to be conservative.
|
||||
fn one_sided_bounds(layers: &[Layer], k: usize, ancestors: &Ancestors, depth: photocraft_color::SampleType, canvas: Rect) -> Option<Rect> {
|
||||
let l = layers.get(k)?;
|
||||
let new_base = !l.clipped && layers.get(k + 1).is_some_and(|above| above.clipped);
|
||||
if new_base || !contained(l, 0) {
|
||||
return None;
|
||||
}
|
||||
photocraft_compose::change_bounds_in(layers, k, outer, canvas)
|
||||
photocraft_compose::change_bounds_in(layers, k, ancestors, depth, canvas)
|
||||
}
|
||||
|
||||
/// Whether `layers[k]` draws nothing wherever it sits, so adding or removing it leaves the
|
||||
@@ -576,12 +786,18 @@ fn inert_at(layers: &[Layer], k: usize) -> bool {
|
||||
&& (l.clipped || layers.get(k + 1).is_none_or(|above| !above.clipped))
|
||||
}
|
||||
|
||||
/// Report the pixels a command made of more than one edit changed since `before` ([`step_damage`]),
|
||||
/// so the canvas recomposites only where its new layers draw instead of the whole document.
|
||||
/// A single [`Session::edit`] already reports its own damage: don't call this after one (#5695).
|
||||
pub(crate) fn note_insert(s: &mut Session, before: &Document) {
|
||||
let Some(st) = s.active_mut() else { return };
|
||||
st.last_damage = step_damage(before, &st.doc);
|
||||
/// How much of the document (percent, rounded down) changed between `a` and `b`, when that is
|
||||
/// some but under 25 %: what [`step_damage`] finds, which a command that reported "redraw
|
||||
/// everything" (`None`) should have reported instead. `None` when nothing changed (a view-only
|
||||
/// change), when it's 25 % or more, or when `step_damage` can't bound it (a canvas-size change).
|
||||
#[cfg(any(test, debug_assertions))]
|
||||
pub(crate) fn small_change_pct(a: &Document, b: &Document) -> Option<u64> {
|
||||
let d = step_damage(a, b).filter(|d| !d.is_empty())?;
|
||||
let doc = b.bounds();
|
||||
let whole = u64::from(doc.width()) * u64::from(doc.height());
|
||||
let changed = d.intersect(&doc);
|
||||
let pct = u64::from(changed.width()) * u64::from(changed.height()) * 100 / whole.max(1);
|
||||
(pct < 25).then_some(pct)
|
||||
}
|
||||
|
||||
/// Content bounds of a layer's pixels as stored (type and shape layers: their cached render), or
|
||||
|
||||
@@ -152,6 +152,7 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let mask_target = p.get("target").and_then(Value::as_str) == Some("mask");
|
||||
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
|
||||
let mut shift = (0, 0);
|
||||
let nested = s.edit("Move", |doc, _| {
|
||||
let (alone, rest): (Vec<LayerId>, Vec<LayerId>) = roots.iter().partition(|id| mask_target && doc.layer(**id).is_some_and(moves_mask_alone));
|
||||
let mut ids = move_targets(doc, &rest);
|
||||
@@ -175,7 +176,7 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A board moved past any canvas edge grows the canvas, as a new one does (#1531, #3070).
|
||||
if ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) {
|
||||
crate::artboard_cmds::fit_canvas(doc);
|
||||
shift = crate::artboard_cmds::fit_canvas(doc);
|
||||
}
|
||||
// The Move tool carries the selection along when it moves several layers whole, as
|
||||
// Photoshop does (#7538): one step, so Undo takes both back.
|
||||
@@ -184,6 +185,7 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(nested)
|
||||
})?;
|
||||
crate::artboard_cmds::follow_shift(s, shift);
|
||||
if nested.is_empty() {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
|
||||
@@ -272,6 +272,7 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul
|
||||
let sel = selected(s);
|
||||
let old_active = s.active().and_then(|d| d.active_layer);
|
||||
let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true);
|
||||
let mut shift = (0i32, 0i32);
|
||||
let (copies, active) = s.edit(label, |doc, active| {
|
||||
let mut copies = Vec::new();
|
||||
let mut new_active = None;
|
||||
@@ -281,7 +282,9 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul
|
||||
let dup = crate::commands::layer_copy(doc, id, add_copy)?;
|
||||
let nid = doc.insert_above(Some(id), dup);
|
||||
if !in_place {
|
||||
crate::artboard_cmds::place_copy(doc, nid)?;
|
||||
// Each copy's shift moved the whole document, so they add up.
|
||||
let (dx, dy) = crate::artboard_cmds::place_copy(doc, nid)?;
|
||||
shift = (shift.0.saturating_add(dx), shift.1.saturating_add(dy));
|
||||
}
|
||||
if Some(id) == old_active {
|
||||
new_active = Some(nid);
|
||||
@@ -293,6 +296,7 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul
|
||||
*active = a;
|
||||
Ok((copies, a))
|
||||
})?;
|
||||
crate::artboard_cmds::follow_shift(s, shift);
|
||||
let out = copies.iter().map(|l| l.0).collect::<Vec<_>>();
|
||||
reselect(s, copies, active);
|
||||
Ok(json!({"layers": out, "layer": active.map(|l| l.0)}))
|
||||
|
||||
@@ -176,13 +176,13 @@ fn moves_and_layer_props_report_only_their_area() {
|
||||
assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17)));
|
||||
s.execute("layer.setProps", json!({"layer": a.0, "opacity": 0.5, "blend": "Multiply"})).unwrap();
|
||||
assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17)));
|
||||
// Clipping changes reach the layers around: everything.
|
||||
// Clipping a pixel layer with nothing clipped to it changes only where it draws (#9329).
|
||||
s.execute("layer.setProps", json!({"layer": a.0, "clipped": true})).unwrap();
|
||||
assert_eq!(damage(&s), None);
|
||||
// An adjustment layer changes everything beneath it.
|
||||
assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17)));
|
||||
// An adjustment layer changes everything beneath it: here the Background, the canvas.
|
||||
let adj = s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.setProps", json!({"layer": adj, "visible": false})).unwrap();
|
||||
assert_eq!(damage(&s), None);
|
||||
assert_eq!(damage(&s), Some(doc(&s).bounds()));
|
||||
// The Background (opaque everywhere): everything.
|
||||
let bg = doc(&s).layers[0].id;
|
||||
s.execute("layer.setProps", json!({"layer": bg.0, "opacity": 0.5})).unwrap();
|
||||
@@ -269,11 +269,11 @@ fn new_layers_that_change_clipping_recomposite_everything() {
|
||||
based.layers.insert(under, l);
|
||||
assert_eq!(step_damage(&before, &based), None);
|
||||
assert_eq!(step_damage(&based, &before), None);
|
||||
// An adjustment reaches every pixel below it.
|
||||
// An adjustment reaches every pixel below it: here the Background, the canvas.
|
||||
let mut adjusted = before.clone();
|
||||
adjusted.insert_above(None, Layer::new("inv", LayerContent::Adjustment(photocraft_doc::Adjustment::Invert)));
|
||||
assert_eq!(step_damage(&before, &adjusted), None);
|
||||
assert_eq!(step_damage(&adjusted, &before), None);
|
||||
assert_eq!(step_damage(&before, &adjusted), Some(before.bounds()));
|
||||
assert_eq!(step_damage(&adjusted, &before), Some(before.bounds()));
|
||||
// Empty layers draw nothing, in any blend mode.
|
||||
let mut styled = before.clone();
|
||||
let mut l = Layer::raster("styled", styled.pixel_format());
|
||||
@@ -343,11 +343,11 @@ fn toggling_a_clipped_adjustment_damages_only_its_base() {
|
||||
s.execute("layer.setProps", json!({"layer": adj.0, "visible": false})).unwrap();
|
||||
assert_eq!(damage(&s), Some(base_rect));
|
||||
assert_eq!(patched(&s, &shown), hidden);
|
||||
// Unclipped, the adjustment still reaches the whole canvas.
|
||||
// Unclipped over the Background, the adjustment still reaches the whole canvas.
|
||||
s.execute("layer.setProps", json!({"layer": adj.0, "visible": true})).unwrap();
|
||||
s.execute("layer.releaseClippingMask", json!({"layer": adj.0})).unwrap();
|
||||
s.execute("layer.hideLayers", json!({"layer": adj.0})).unwrap();
|
||||
assert_eq!(damage(&s), None);
|
||||
assert_eq!(damage(&s), Some(doc(&s).bounds()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -395,6 +395,49 @@ fn clipped_adjustment_in_pass_through_clip_base_damages_its_group() {
|
||||
assert_eq!(step_damage(&before, &after), Some(Rect::new(2, 1, 4, 3)));
|
||||
}
|
||||
|
||||
/// #9329: hiding the last visible unclipped adjustment in a pass-through group that is a clip
|
||||
/// base switches the group from isolated to pass-through rendering, which agrees with the old
|
||||
/// pixels outside the layers beneath only up to float rounding, so it damages the group too.
|
||||
#[test]
|
||||
fn unclipped_adjustment_in_pass_through_clip_base_damages_its_group() {
|
||||
use photocraft_doc::{Adjustment, BlendMode};
|
||||
let solid = |name: &str, r: Rect, blend: BlendMode| {
|
||||
let mut l = Layer::raster(name, PixelFormat::RGBA8);
|
||||
l.surface_mut().unwrap().fill_rect(r, &[0.5, 0.3, 0.7, 0.6]);
|
||||
l.blend = blend;
|
||||
l
|
||||
};
|
||||
let mut before = Document::with_background(
|
||||
"t",
|
||||
photocraft_geom::Size::new(10, 8),
|
||||
photocraft_doc::ColorMode::Rgb,
|
||||
photocraft_doc::SampleType::U8,
|
||||
photocraft_color::Color::WHITE,
|
||||
);
|
||||
before.layers.clear();
|
||||
before.layers.push(solid("bg", Rect::new(0, 0, 2, 2), BlendMode::Normal));
|
||||
let a = Layer::new("A", LayerContent::Adjustment(Adjustment::Invert));
|
||||
let mut g = Layer::group("G", vec![solid("P", Rect::new(2, 1, 4, 3), BlendMode::Normal), a, solid("Q", Rect::new(6, 4, 8, 6), BlendMode::Multiply)]);
|
||||
g.blend = BlendMode::PassThrough;
|
||||
before.layers.push(g);
|
||||
let mut x = solid("X", Rect::new(2, 1, 7, 5), BlendMode::Normal);
|
||||
x.clipped = true;
|
||||
before.layers.push(x);
|
||||
let mut after = before.clone();
|
||||
let LayerContent::Group(g) = &mut after.layers[1].content else { panic!("group") };
|
||||
g.children[1].visible = false;
|
||||
// The layers beneath A (0..4 × 0..3) and the group (2..8 × 1..6).
|
||||
let r = Rect::new(0, 0, 8, 6);
|
||||
assert_eq!(step_damage(&before, &after), Some(r));
|
||||
assert_eq!(step_damage(&after, &before), Some(r));
|
||||
assert!(unchanged_outside(&before, &after, r));
|
||||
// Without the layer clipped to the group it stays pass-through: just the layers beneath.
|
||||
before.layers.truncate(2);
|
||||
after.layers.truncate(2);
|
||||
assert_eq!(step_damage(&before, &after), Some(Rect::new(0, 0, 4, 3)));
|
||||
assert!(unchanged_outside(&before, &after, Rect::new(0, 0, 4, 3)));
|
||||
}
|
||||
|
||||
/// #2883 (P8/P9): a duplicate shares the source's tiles (no pixel copy) and recomposites only
|
||||
/// where it draws; undo brings back exactly the old pixels. A copy that becomes the clipping
|
||||
/// base of the layers above still recomposites everything.
|
||||
@@ -1224,13 +1267,314 @@ fn undo_of_clipping_or_channel_exclusion_composites_everything() {
|
||||
let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20));
|
||||
let b = rect_layer(&mut s, Rect::new(12, 12, 30, 30));
|
||||
select_all(&mut s, &[b]);
|
||||
// Clipping reaches the layers clipped above, outside this layer's bounds.
|
||||
s.execute("layer.setProps", json!({"clipped": true})).unwrap();
|
||||
// #9329: on a pixel layer both are bounded: clipping by the layer (and the clipped layers
|
||||
// above it), channel exclusion by the layer (per pixel where it draws).
|
||||
for p in [json!({"clipped": true}), json!({"channels": [true, false, true]})] {
|
||||
let before = doc(&s).clone();
|
||||
s.execute("layer.setProps", p.clone()).unwrap();
|
||||
let after = doc(&s).clone();
|
||||
s.undo();
|
||||
let r = damage(&s).unwrap_or_else(|| panic!("{p} is bounded"));
|
||||
assert!(r.width() < 100 && unchanged_outside(&after, &before, r), "{p}: {r:?}");
|
||||
}
|
||||
// On a group they change how it composites its children: everything.
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
let g = s.active().unwrap().active_layer.unwrap();
|
||||
assert!(doc(&s).layer(g).unwrap().children().is_some());
|
||||
s.execute("layer.setProps", json!({"layer": g.0, "clipped": true})).unwrap();
|
||||
s.undo();
|
||||
assert_eq!(damage(&s), None, "a clipping change recomposites everything");
|
||||
s.execute("layer.setProps", json!({"channels": [true, false, true]})).unwrap();
|
||||
assert_eq!(damage(&s), None, "a group's clipping change recomposites everything");
|
||||
s.execute("layer.setProps", json!({"layer": g.0, "channels": [true, false, true]})).unwrap();
|
||||
s.undo();
|
||||
assert_eq!(damage(&s), None, "an excluded-channel change recomposites everything");
|
||||
assert_eq!(damage(&s), None, "a group's excluded-channel change recomposites everything");
|
||||
}
|
||||
|
||||
/// A new adjustment layer of `kind` (made while `s`'s selection is active, so it masks it).
|
||||
fn adjustment(s: &mut Session, kind: &str) -> LayerId {
|
||||
LayerId(s.execute(&format!("layer.newAdjustmentLayer.{kind}"), json!({})).unwrap()["layer"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Run `id` with `p`, then undo and redo it: each step's damage is bounded, smaller than the
|
||||
/// canvas, and covers every pixel it changed (`unchanged_outside`). Returns the step's damage.
|
||||
fn bounded_step(s: &mut Session, id: &str, p: serde_json::Value) -> Rect {
|
||||
let before = doc(s).clone();
|
||||
s.execute(id, p).unwrap();
|
||||
let after = doc(s).clone();
|
||||
let canvas = after.bounds();
|
||||
let check = |s: &Session, from: &Document, to: &Document, what: &str| {
|
||||
let r = damage(s).unwrap_or_else(|| panic!("{id} {what}: bounded"));
|
||||
assert!(r.width() * r.height() < canvas.width() * canvas.height(), "{id} {what}: {r:?}");
|
||||
assert!(unchanged_outside(from, to, r), "{id} {what}: {r:?} misses changed pixels");
|
||||
r
|
||||
};
|
||||
let r = check(s, &before, &after, "");
|
||||
s.undo();
|
||||
check(s, &after, &before, "undo");
|
||||
s.redo();
|
||||
check(s, &before, &after, "redo");
|
||||
r
|
||||
}
|
||||
|
||||
/// #9329, #6533: in a 32-bit document hiding a masked adjustment damages only its mask, over
|
||||
/// an opaque Background too. An integer document rounds the whole backdrop after every
|
||||
/// visible adjustment layer (#9033), so there it still damages the canvas.
|
||||
#[test]
|
||||
fn hiding_a_masked_adjustment_damages_only_its_mask() {
|
||||
for depth in [32, 8] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 800, "height": 600, "depth": depth})).unwrap();
|
||||
let c = rect_layer(&mut s, Rect::new(50, 50, 700, 500));
|
||||
s.execute("layer.setProps", json!({"layer": c.0, "opacity": 0.37})).unwrap();
|
||||
let reveal = Rect::new(520, 330, 560, 370);
|
||||
s.execute("select.rect", json!({"x": reveal.x0, "y": reveal.y0, "width": 40, "height": 40})).unwrap();
|
||||
let adj = adjustment(&mut s, "invert");
|
||||
assert!(doc(&s).layer(adj).unwrap().mask.is_some());
|
||||
if depth == 32 {
|
||||
let r = bounded_step(&mut s, "layer.setProps", json!({"layer": adj.0, "visible": false}));
|
||||
assert!(r.contains_rect(&reveal), "{r:?}");
|
||||
} else {
|
||||
s.execute("layer.setProps", json!({"layer": adj.0, "visible": false})).unwrap();
|
||||
assert_eq!(damage(&s), Some(doc(&s).bounds()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #9329, #6528: Show Only This Layer, in a document whose only layer that could reach
|
||||
/// everywhere was an adjustment, is bounded by where the layers draw.
|
||||
#[test]
|
||||
fn show_only_with_an_adjustment_is_bounded() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8, "background": "transparent"})).unwrap();
|
||||
let a = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
|
||||
let b = rect_layer(&mut s, Rect::new(40, 20, 60, 50));
|
||||
s.execute("layer.setProps", json!({"layer": b.0, "opacity": 0.37})).unwrap();
|
||||
let _ = adjustment(&mut s, "invert");
|
||||
let r = bounded_step(&mut s, "layer.showOnly", json!({"layer": a.0}));
|
||||
assert_eq!(r, Rect::new(10, 10, 60, 50));
|
||||
}
|
||||
|
||||
/// #9329: Bring Forward damages only where the moved layer draws, not the whole canvas.
|
||||
#[test]
|
||||
fn bring_forward_damages_only_the_moved_layer() {
|
||||
let mut s = session(8);
|
||||
let a = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
|
||||
let _b = rect_layer(&mut s, Rect::new(20, 20, 50, 50));
|
||||
let _c = rect_layer(&mut s, Rect::new(60, 60, 70, 70));
|
||||
select_all(&mut s, &[a]);
|
||||
let r = bounded_step(&mut s, "layer.arrange.bringForward", json!({}));
|
||||
assert_eq!(r, Rect::new(10, 10, 30, 30));
|
||||
}
|
||||
|
||||
/// #9329: Send Backward, its undo and its redo each damage only the moved layer; an
|
||||
/// adjustment moving past a layer reaches as far as the layers beneath it at either end.
|
||||
#[test]
|
||||
fn send_backward_undo_and_redo_are_bounded() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8, "background": "transparent"})).unwrap();
|
||||
let _a = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
|
||||
let b = rect_layer(&mut s, Rect::new(20, 20, 50, 50));
|
||||
select_all(&mut s, &[b]);
|
||||
// Either layer of the swapped pair is the one that moved.
|
||||
let r = bounded_step(&mut s, "layer.arrange.sendBackward", json!({}));
|
||||
assert!(r == Rect::new(20, 20, 50, 50) || r == Rect::new(10, 10, 30, 30), "{r:?}");
|
||||
let _c = rect_layer(&mut s, Rect::new(60, 60, 70, 70));
|
||||
let adj = adjustment(&mut s, "invert");
|
||||
select_all(&mut s, &[adj]);
|
||||
bounded_step(&mut s, "layer.arrange.sendBackward", json!({}));
|
||||
}
|
||||
|
||||
/// #9329: a moved group holding a video layer has no bounded damage, as the video layer itself
|
||||
/// has none.
|
||||
#[test]
|
||||
fn bring_forward_on_a_group_holding_a_video_layer_is_unbounded() {
|
||||
let mut s = session(8);
|
||||
let v = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
|
||||
s.edit("video", |doc, _| {
|
||||
let l = doc.layer_mut(v).unwrap();
|
||||
let frame = l.surface().unwrap().clone();
|
||||
l.video = Some(photocraft_doc::VideoData::new(vec![frame.clone(), frame], 24.0));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("layer.select", json!({"layer": v.0})).unwrap();
|
||||
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
let b = rect_layer(&mut s, Rect::new(20, 20, 50, 50));
|
||||
assert_eq!(doc(&s).layers.iter().map(|l| l.id).skip(1).collect::<Vec<_>>(), vec![g, b]);
|
||||
select_all(&mut s, &[g]);
|
||||
s.execute("layer.arrange.bringForward", json!({})).unwrap();
|
||||
assert_eq!(doc(&s).layers.iter().map(|l| l.id).skip(1).collect::<Vec<_>>(), vec![b, g]);
|
||||
assert_eq!(damage(&s), None);
|
||||
}
|
||||
|
||||
/// #9329: reordering inside a group with a drop shadow damages the shadow too. The moved layer
|
||||
/// knocks out the one beneath it, so the group's shape, and with it the shadow, changes.
|
||||
#[test]
|
||||
fn a_reorder_inside_a_group_with_a_drop_shadow_damages_the_shadow() {
|
||||
let mut s = session(8);
|
||||
let k = rect_layer(&mut s, Rect::new(30, 30, 50, 50));
|
||||
let b = rect_layer(&mut s, Rect::new(20, 20, 50, 50));
|
||||
s.edit("knockout", |doc, _| {
|
||||
let l = doc.layer_mut(k).unwrap();
|
||||
l.advanced.knockout = photocraft_doc::Knockout::Shallow;
|
||||
l.fill_opacity = 0.0;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select_all(&mut s, &[k, b]);
|
||||
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.edit("fx", |doc, _| {
|
||||
doc.layer_mut(g).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(doc(&s).layer(g).unwrap().children().unwrap().iter().map(|l| l.id).collect::<Vec<_>>(), vec![k, b]);
|
||||
select_all(&mut s, &[k]);
|
||||
let r = bounded_step(&mut s, "layer.arrange.bringForward", json!({}));
|
||||
assert!(r.contains_rect(&Rect::new(30, 30, 50, 50)), "{r:?}");
|
||||
}
|
||||
|
||||
/// #9329: deleting a layer inside a group with a drop shadow, and adding it back on undo,
|
||||
/// damages the shadow too, which reaches past the layer.
|
||||
#[test]
|
||||
fn adding_or_deleting_a_layer_inside_a_group_with_a_drop_shadow_damages_the_shadow() {
|
||||
let mut s = session(8);
|
||||
let k = rect_layer(&mut s, Rect::new(20, 20, 30, 30));
|
||||
let b = rect_layer(&mut s, Rect::new(50, 40, 60, 50));
|
||||
select_all(&mut s, &[k, b]);
|
||||
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.edit("fx", |doc, _| {
|
||||
doc.layer_mut(g).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = bounded_step(&mut s, "layer.delete", json!({"layer": k.0}));
|
||||
assert!(r.contains_rect(&Rect::new(20, 20, 30, 30)), "{r:?}");
|
||||
}
|
||||
|
||||
/// A group holding `layers`, with a drop shadow that reaches about 8 px down and right of them.
|
||||
fn shadowed_group(s: &mut Session, layers: &[LayerId]) -> LayerId {
|
||||
select_all(s, layers);
|
||||
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.edit("fx", |doc, _| {
|
||||
doc.layer_mut(g).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
g
|
||||
}
|
||||
|
||||
/// [`bounded_step`] for a step that must change canvas pixels, so it can't pass vacuously.
|
||||
fn bounded_visible_step(s: &mut Session, id: &str, p: serde_json::Value) -> Rect {
|
||||
let before = photocraft_compose::render(doc(s), doc(s).bounds());
|
||||
let r = bounded_step(s, id, p);
|
||||
assert_ne!(photocraft_compose::render(doc(s), doc(s).bounds()).px, before.px, "{id}: no canvas pixel changed");
|
||||
r
|
||||
}
|
||||
|
||||
/// #9329: deleting a layer just off the canvas inside a group whose drop shadow reaches onto
|
||||
/// it, and adding it back on undo, damages the shadow on the canvas.
|
||||
#[test]
|
||||
fn deleting_an_off_canvas_layer_damages_its_group_shadow_on_the_canvas() {
|
||||
let mut s = session(8);
|
||||
let k = rect_layer(&mut s, Rect::new(-10, 20, -1, 30));
|
||||
let b = rect_layer(&mut s, Rect::new(50, 40, 60, 50));
|
||||
shadowed_group(&mut s, &[k, b]);
|
||||
bounded_visible_step(&mut s, "layer.delete", json!({"layer": k.0}));
|
||||
}
|
||||
|
||||
/// #9329: reordering a layer just off the canvas inside a group whose drop shadow reaches onto
|
||||
/// it damages the shadow on the canvas. The moved layer knocks out the one beneath it, so the
|
||||
/// group's shape, and with it the shadow, changes.
|
||||
#[test]
|
||||
fn reordering_an_off_canvas_layer_damages_its_group_shadow_on_the_canvas() {
|
||||
let mut s = session(8);
|
||||
let k = rect_layer(&mut s, Rect::new(-9, 25, -1, 35));
|
||||
let b = rect_layer(&mut s, Rect::new(-14, 20, -1, 40));
|
||||
s.edit("knockout", |doc, _| {
|
||||
let l = doc.layer_mut(k).unwrap();
|
||||
l.advanced.knockout = photocraft_doc::Knockout::Shallow;
|
||||
l.fill_opacity = 0.0;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
shadowed_group(&mut s, &[k, b]);
|
||||
select_all(&mut s, &[k]);
|
||||
bounded_visible_step(&mut s, "layer.arrange.bringForward", json!({}));
|
||||
}
|
||||
|
||||
/// #9329: unclipping a layer inside a group with a drop shadow exposes its pixels outside its
|
||||
/// old base, which moves the group's shadow past the layer; clipping it back, on undo and redo,
|
||||
/// too.
|
||||
#[test]
|
||||
fn clipping_and_unclipping_inside_a_shadowed_group_damages_the_shadow() {
|
||||
let mut s = session(8);
|
||||
let a = rect_layer(&mut s, Rect::new(20, 20, 30, 30));
|
||||
let b = rect_layer(&mut s, Rect::new(25, 25, 45, 45));
|
||||
s.execute("layer.setProps", json!({"layer": b.0, "clipped": true})).unwrap();
|
||||
shadowed_group(&mut s, &[a, b]);
|
||||
bounded_visible_step(&mut s, "layer.setProps", json!({"layer": b.0, "clipped": false}));
|
||||
bounded_visible_step(&mut s, "layer.setProps", json!({"layer": b.0, "clipped": true}));
|
||||
}
|
||||
|
||||
/// #9329: a property change on a layer inside a group with a drop shadow changes the shadow,
|
||||
/// which reaches past the layer.
|
||||
#[test]
|
||||
fn a_property_change_inside_a_shadowed_group_damages_the_shadow() {
|
||||
let mut s = session(8);
|
||||
let a = rect_layer(&mut s, Rect::new(20, 20, 30, 30));
|
||||
let b = rect_layer(&mut s, Rect::new(50, 40, 60, 50));
|
||||
shadowed_group(&mut s, &[a, b]);
|
||||
bounded_visible_step(&mut s, "layer.setProps", json!({"layer": a.0, "opacity": 0.3}));
|
||||
}
|
||||
|
||||
/// #9329: hiding or deleting a layer at the edge of a group with a Gradient Overlay shrinks the
|
||||
/// group's frame, which lays the gradient out again over the rest of the group (#4053).
|
||||
#[test]
|
||||
fn hiding_or_deleting_a_layer_in_a_group_with_a_gradient_overlay_damages_the_group() {
|
||||
use photocraft_doc::{Effect, FxCommon, Gradient};
|
||||
let mut s = session(8);
|
||||
let a = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
|
||||
let b = rect_layer(&mut s, Rect::new(60, 40, 80, 60));
|
||||
select_all(&mut s, &[a, b]);
|
||||
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.edit("fx", |doc, _| {
|
||||
doc.layer_mut(g).unwrap().effects.items.push(Effect::GradientOverlay {
|
||||
common: FxCommon::new(photocraft_doc::BlendMode::Normal, 1.0),
|
||||
gradient: Gradient::default(),
|
||||
dither: false,
|
||||
interpolation: None,
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = bounded_visible_step(&mut s, "layer.setProps", json!({"layer": b.0, "visible": false}));
|
||||
assert!(r.contains_rect(&Rect::new(10, 10, 30, 30)), "{r:?}");
|
||||
s.undo();
|
||||
let r = bounded_visible_step(&mut s, "layer.delete", json!({"layer": b.0}));
|
||||
assert!(r.contains_rect(&Rect::new(10, 10, 30, 30)), "{r:?}");
|
||||
}
|
||||
|
||||
/// #9329: clipping a layer to the one beneath damages it and the layers clipped to it
|
||||
/// (they change base), on undo and redo too.
|
||||
#[test]
|
||||
fn clipping_a_layer_damages_it_and_the_clipped_run_above() {
|
||||
let mut s = session(8);
|
||||
let _a = rect_layer(&mut s, Rect::new(10, 10, 40, 40));
|
||||
let b = rect_layer(&mut s, Rect::new(20, 20, 60, 50));
|
||||
let c = rect_layer(&mut s, Rect::new(30, 15, 70, 45));
|
||||
s.execute("layer.setProps", json!({"layer": c.0, "clipped": true})).unwrap();
|
||||
let r = bounded_step(&mut s, "layer.setProps", json!({"layer": b.0, "clipped": true}));
|
||||
assert_eq!(r, Rect::new(20, 15, 70, 50));
|
||||
}
|
||||
|
||||
/// #9329: excluding a channel from a pixel layer's blend damages only where it draws.
|
||||
#[test]
|
||||
fn excluding_a_channel_damages_only_the_layer() {
|
||||
let mut s = session(8);
|
||||
let _a = rect_layer(&mut s, Rect::new(10, 10, 40, 40));
|
||||
let b = rect_layer(&mut s, Rect::new(20, 20, 60, 50));
|
||||
let r = bounded_step(&mut s, "layer.setProps", json!({"layer": b.0, "channels": [true, false, true]}));
|
||||
assert_eq!(r, Rect::new(20, 20, 60, 50));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -173,23 +173,71 @@ fn tile_damage_grows_by_the_layer_effect_margin() {
|
||||
assert!(unchanged_outside(&before, &after, d));
|
||||
}
|
||||
|
||||
/// The default drop shadow, `distance` px away and `size` px soft.
|
||||
fn drop_shadow(distance: f32, size: f32) -> photocraft_doc::Effect {
|
||||
match photocraft_doc::Effect::default_drop_shadow() {
|
||||
photocraft_doc::Effect::DropShadow(sh) => photocraft_doc::Effect::DropShadow(photocraft_doc::Shadow { distance, size, ..sh }),
|
||||
e => e,
|
||||
}
|
||||
}
|
||||
|
||||
/// A styled layer inside a styled group: the group's shadow is cast by the child's shadow too, so
|
||||
/// a dab's change reaches as far as both shadows together, not just the farther one.
|
||||
#[test]
|
||||
fn a_dab_inside_a_group_with_a_drop_shadow_damages_the_shadow() {
|
||||
let mut s = session(1024, 768);
|
||||
let child = layer_with(&mut s, &[(Rect::new(600, 400, 700, 500), [1.0, 0.0, 0.0, 1.0])]);
|
||||
let child = layer_with(&mut s, &[(Rect::new(200, 400, 300, 500), [1.0, 0.0, 0.0, 1.0])]);
|
||||
s.execute("layer.select", json!({"layer": child.0})).unwrap();
|
||||
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.edit("fx", |doc, _| {
|
||||
doc.layer_mut(g).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
|
||||
for id in [child, g] {
|
||||
doc.layer_mut(id).unwrap().effects.items.push(drop_shadow(40.0, 2.0));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(photocraft_compose::effects::margin(doc(&s).layer(g).unwrap()) > 0);
|
||||
let dab = Rect::new(640, 440, 660, 460);
|
||||
let (before, after) = paint(&mut s, child, dab, [0.0, 0.0, 1.0, 1.0]);
|
||||
assert!(photocraft_compose::effects::margin(doc(&s).layer(g).unwrap()) > 40);
|
||||
// A brush dab (a hinted edit) in empty space left of a tile's right edge. Each shadow falls
|
||||
// about 20 px right and 35 px down, so the group's shadow of the child's shadow lands about
|
||||
// 40 px right and 70 px down, in the next tile and past either shadow's reach alone.
|
||||
s.execute("layer.select", json!({"layer": child.0})).unwrap();
|
||||
let before = doc(&s);
|
||||
s.execute("paint.stroke", json!({"points": [[TILE_SIZE - 30, 300]], "size": 10, "hardness": 1.0, "color": "#0000ff", "layer": child.0})).unwrap();
|
||||
assert_eq!(s.damage_misses, 0);
|
||||
let d = damage(&s).expect("a bounded dab");
|
||||
assert!(d.contains_rect(&dab), "{d:?}");
|
||||
assert!(unchanged_outside(&before, &after, d), "the group's shadow changed outside {d:?}");
|
||||
assert!(d.x0 < TILE_SIZE && d.x1 > TILE_SIZE, "{d:?}");
|
||||
assert!(unchanged_outside(&before, &doc(&s), d), "the group's shadow changed outside {d:?}");
|
||||
}
|
||||
|
||||
/// A layer the compositor doesn't draw adds nothing to a dab elsewhere: neither a hidden layer's
|
||||
/// effects nor those of layers inside a hidden group grow the hint.
|
||||
#[test]
|
||||
fn a_brush_hint_ignores_the_effects_of_hidden_layers() {
|
||||
let mut s = session(1024, 768);
|
||||
let plain = full_layer(&mut s);
|
||||
let hidden = layer_with(&mut s, &[(Rect::new(800, 600, 900, 700), [1.0, 0.0, 0.0, 1.0])]);
|
||||
let child = layer_with(&mut s, &[(Rect::new(50, 600, 150, 700), [0.0, 1.0, 0.0, 1.0])]);
|
||||
s.execute("layer.select", json!({"layer": child.0})).unwrap();
|
||||
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.edit("fx", |doc, _| {
|
||||
for id in [hidden, child] {
|
||||
let l = doc.layer_mut(id).unwrap();
|
||||
l.effects.items.push(drop_shadow(40.0, 40.0));
|
||||
}
|
||||
doc.layer_mut(hidden).unwrap().visible = false;
|
||||
doc.layer_mut(g).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(photocraft_compose::effects::margin(doc(&s).layer(hidden).unwrap()) > 40);
|
||||
// A dab in the middle of a tile, far from every tile edge.
|
||||
s.execute("layer.select", json!({"layer": plain.0})).unwrap();
|
||||
let before = doc(&s);
|
||||
s.execute("paint.stroke", json!({"points": [[384, 384]], "size": 10, "hardness": 1.0, "color": "#0000ff", "layer": plain.0})).unwrap();
|
||||
assert_eq!(s.damage_misses, 0);
|
||||
let d = damage(&s).expect("a bounded dab");
|
||||
assert!(d.contains(384, 384) && d.width() <= 20 && d.height() <= 20, "grown by a hidden layer: {d:?}");
|
||||
assert!(unchanged_outside(&before, &doc(&s), d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -210,6 +258,12 @@ fn painting_a_clip_base_under_a_styled_clipped_layer_is_covered() {
|
||||
let (before, after) = paint(&mut s, base, Rect::new(640, 440, 660, 460), [0.0, 0.0, 0.0, 0.0]);
|
||||
let d = damage(&s).expect("a bounded base edit");
|
||||
assert!(unchanged_outside(&before, &after, d), "the clipped layer changed outside {d:?}");
|
||||
// At a tile's edge too: the clipped layer's shadow is built from its own shape, and the base
|
||||
// only masks it pixel by pixel, so a base edit changes nothing past its own tiles.
|
||||
let (before, after) = paint(&mut s, base, Rect::new(3 * TILE_SIZE - 6, 440, 3 * TILE_SIZE, 460), [0.0, 0.0, 0.0, 0.0]);
|
||||
let d = damage(&s).expect("a bounded base edit");
|
||||
assert!(d.x1 <= 3 * TILE_SIZE, "{d:?}");
|
||||
assert!(unchanged_outside(&before, &after, d), "the clipped layer changed outside {d:?}");
|
||||
}
|
||||
|
||||
/// #4053: effects laid out over the layer's frame repaint it everywhere when it grows.
|
||||
@@ -269,6 +323,41 @@ fn a_hint_that_misses_a_changed_tile_is_counted() {
|
||||
assert_eq!(damage(&s), Some(Rect::new(600, 400, 620, 420)));
|
||||
}
|
||||
|
||||
/// A brush hint is the bare dab; on a feathered mask the dab changes a soft ring around it, and
|
||||
/// the hint must not cut that off.
|
||||
#[test]
|
||||
fn a_brush_hint_on_a_feathered_mask_keeps_the_ring() {
|
||||
let mut s = session(1024, 768);
|
||||
let id = full_layer(&mut s);
|
||||
s.edit("mask", |doc, _| {
|
||||
doc.layer_mut(id).unwrap().mask = Some(photocraft_doc::LayerMask { feather: 10.0, ..photocraft_doc::LayerMask::reveal_all() });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = doc(&s);
|
||||
s.execute("paint.stroke", json!({"points": [[500, 400]], "size": 10, "hardness": 1.0, "color": "#000000", "target": "mask", "layer": id.0})).unwrap();
|
||||
assert_eq!(s.damage_misses, 0);
|
||||
let d = damage(&s).expect("a bounded dab");
|
||||
assert!(unchanged_outside(&before, &doc(&s), d), "the feathered mask changed outside {d:?}");
|
||||
}
|
||||
|
||||
/// The same for a layer's effects: the dab's drop shadow lands outside the dab.
|
||||
#[test]
|
||||
fn a_brush_hint_on_a_layer_with_a_drop_shadow_keeps_the_shadow() {
|
||||
let mut s = session(1024, 768);
|
||||
let id = layer_with(&mut s, &[(Rect::new(600, 400, 700, 500), [1.0, 0.0, 0.0, 1.0])]);
|
||||
s.edit("fx", |doc, _| {
|
||||
doc.layer_mut(id).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = doc(&s);
|
||||
s.execute("paint.stroke", json!({"points": [[300, 300]], "size": 10, "hardness": 1.0, "color": "#0000ff", "layer": id.0})).unwrap();
|
||||
assert_eq!(s.damage_misses, 0);
|
||||
let d = damage(&s).expect("a bounded dab");
|
||||
assert!(unchanged_outside(&before, &doc(&s), d), "the shadow changed outside {d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painting_command_hints_cover_their_changed_tiles() {
|
||||
let mut s = session(600, 400);
|
||||
@@ -319,3 +408,195 @@ fn painting_command_hints_cover_their_changed_tiles() {
|
||||
assert!(unchanged_outside(&before, &doc(&s), d), "{cmd}: pixels changed outside {d:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// PR C (#9329): damage spans a command, not a revision.
|
||||
|
||||
/// The damage since the command began: measured from the revision before it, bounded, and
|
||||
/// covering every pixel the command changed.
|
||||
fn command_damage(s: &mut Session, cmd: &str, p: serde_json::Value) -> (std::sync::Arc<Document>, Rect) {
|
||||
let (before, rev) = (doc(s), s.active().unwrap().revision);
|
||||
s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.revision - rev >= 2, "{cmd}: several revisions ({} → {})", rev, st.revision);
|
||||
assert_eq!(st.damage_from(), rev, "{cmd}: measured from before the command");
|
||||
let d = st.last_damage.unwrap_or_else(|| panic!("{cmd}: bounded damage"));
|
||||
assert!(unchanged_outside(&before, &st.doc, d), "{cmd}: pixels changed outside {d:?}");
|
||||
(before, d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_into_reports_damage_since_the_command_began() {
|
||||
let mut s = session(1024, 768);
|
||||
layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.2, 0.4, 0.6, 1.0]), (Rect::new(40, 40, 120, 120), [0.9, 0.1, 0.1, 1.0])]);
|
||||
s.execute("select.rect", json!({"x": 40, "y": 40, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("edit.copy", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 700, "y": 500, "width": 120, "height": 90})).unwrap();
|
||||
let (_, d) = command_damage(&mut s, "edit.pasteSpecial.pasteInto", json!({}));
|
||||
assert!(!d.intersect(&Rect::new(700, 500, 820, 590)).is_empty(), "the pasted area: {d:?}");
|
||||
assert!(u64::from(d.width()) * u64::from(d.height()) * 4 < 1024 * 768, "the pasted area, not the canvas: {d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_path_damage_spans_every_subpath() {
|
||||
let mut s = session(1024, 768);
|
||||
layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.5, 0.5, 0.5, 1.0])]);
|
||||
let path = json!({"subpaths": [{"knots": [[20, 20], [80, 20], [80, 80]]}, {"knots": [[800, 600], [900, 600], [900, 700]]}]});
|
||||
s.execute("path.set", json!({ "path": path })).unwrap();
|
||||
// A tool with its own `paint.*` command runs once per subpath, one revision each.
|
||||
let (_, d) = command_damage(&mut s, "path.stroke", json!({"tool": "burn", "size": 16}));
|
||||
assert!(d.contains(50, 20) && d.contains(850, 600), "both subpaths: {d:?}");
|
||||
assert_eq!(s.whole_redraws, 0);
|
||||
}
|
||||
|
||||
/// Pattern Stamp copies its pattern into the document on first use: a pattern no layer
|
||||
/// refers to draws nothing, so a multi-subpath Stroke Path stays bounded.
|
||||
#[test]
|
||||
fn a_new_unreferenced_pattern_keeps_stroke_path_bounded() {
|
||||
let mut s = session(1024, 768);
|
||||
layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.5, 0.5, 0.5, 1.0])]);
|
||||
let path = json!({"subpaths": [{"knots": [[20, 20], [80, 20], [80, 80]]}, {"knots": [[800, 600], [900, 600], [900, 700]]}]});
|
||||
s.execute("path.set", json!({ "path": path })).unwrap();
|
||||
let n = doc(&s).patterns.len();
|
||||
let p = json!({"tool": "patternStamp", "size": 16, "hardness": 100, "pattern": "Checkerboard", "scale": 100, "aligned": true});
|
||||
let (_, d) = command_damage(&mut s, "path.stroke", p);
|
||||
assert!(doc(&s).patterns.len() > n, "the stamp added its pattern");
|
||||
assert!(d.contains(50, 20) && d.contains(850, 600), "both subpaths: {d:?}");
|
||||
assert_eq!(s.whole_redraws, 0);
|
||||
}
|
||||
|
||||
/// A pattern that an existing layer refers to (here a fill layer whose pattern was missing)
|
||||
/// changes that layer's pixels when it is added: not bounded by the tile diff.
|
||||
#[test]
|
||||
fn a_new_pattern_a_layer_refers_to_is_unbounded() {
|
||||
let mut s = session(400, 300);
|
||||
s.execute("layer.newFillLayer.pattern", json!({"pattern": "Checkerboard"})).unwrap();
|
||||
// Without its pixel cache, so both sides render the fill from the library.
|
||||
let mut with = (*doc(&s)).clone();
|
||||
with.layers.iter_mut().for_each(|l| l.fill_cache = None);
|
||||
let mut without = with.clone();
|
||||
without.patterns.clear();
|
||||
assert!(!same_pixels(&without, &with), "the fill layer draws only with its pattern");
|
||||
assert_eq!(step_damage(&without, &with), None);
|
||||
// Unchanged libraries, and an unreferenced addition, stay pixel-equal.
|
||||
assert_eq!(step_damage(&with, &with), Some(Rect::EMPTY));
|
||||
let plain = doc(&session(400, 300));
|
||||
let mut more = (*plain).clone();
|
||||
more.patterns = with.patterns.clone();
|
||||
assert_eq!(step_damage(&plain, &more), Some(Rect::EMPTY));
|
||||
assert!(unchanged_outside(&plain, &more, Rect::EMPTY));
|
||||
}
|
||||
|
||||
/// An appended pattern sharing its name with one a layer already resolves by id loses to that id
|
||||
/// match (`pattern::find` tries ids first), so the layer draws as before: bounded, not a whole
|
||||
/// redraw. A cross-document layer copy can bring such a pattern along.
|
||||
#[test]
|
||||
fn a_same_named_new_pattern_a_reference_still_resolves_past_is_bounded() {
|
||||
let mut s = session(400, 300);
|
||||
s.execute("layer.newFillLayer.pattern", json!({"pattern": "Checkerboard"})).unwrap();
|
||||
let mut with = (*doc(&s)).clone();
|
||||
with.layers.iter_mut().for_each(|l| l.fill_cache = None);
|
||||
let refers_by_id = with.layers.iter().any(|l| matches!(&l.content, LayerContent::Fill(photocraft_doc::Fill::Pattern { id, .. }) if !id.is_empty()));
|
||||
assert!(refers_by_id, "the fill layer refers to its pattern by id");
|
||||
let mut twin = with.patterns[0].clone();
|
||||
twin.id = "another-id".into();
|
||||
twin.surface.fill_rect(Rect::new(0, 0, twin.width as i32, twin.height as i32), &[1.0, 0.0, 1.0, 1.0]);
|
||||
let mut more = with.clone();
|
||||
more.patterns.push(twin);
|
||||
assert_eq!(step_damage(&with, &more), Some(Rect::EMPTY));
|
||||
assert!(unchanged_outside(&with, &more, Rect::EMPTY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_compound_reports_no_change() {
|
||||
let mut s = session(600, 400);
|
||||
let id = layer_with(&mut s, &[(Rect::new(0, 0, 50, 50), [1.0, 0.0, 0.0, 1.0])]);
|
||||
let (before, rev) = (doc(&s), s.active().unwrap().revision);
|
||||
let r: Result<()> = crate::analysis_cmds::compound(&mut s, "Both", |s| {
|
||||
paint(s, id, Rect::new(300, 200, 340, 240), [0.0, 1.0, 0.0, 1.0]);
|
||||
paint(s, id, Rect::new(10, 300, 40, 340), [0.0, 0.0, 1.0, 1.0]);
|
||||
Err(EngineError::Other("the second step failed".into()))
|
||||
});
|
||||
assert!(r.is_err());
|
||||
// What `Session::dispatch` does after any inline command.
|
||||
s.note_command_damage("test.compound", &before, rev);
|
||||
let st = s.active().unwrap();
|
||||
assert!(same_pixels(&before, &st.doc), "rolled back");
|
||||
assert_eq!((st.damage_from(), st.last_damage), (rev, Some(Rect::EMPTY)), "nothing changed since it began");
|
||||
assert_eq!(s.whole_redraws, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_then_edit_in_one_command_is_bounded() {
|
||||
let mut s = session(1024, 768);
|
||||
let id = layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.2, 0.4, 0.6, 1.0])]);
|
||||
let steps = vec![
|
||||
("layer.select".to_string(), json!({"layer": id.0})),
|
||||
("select.rect".to_string(), json!({"x": 300, "y": 300, "width": 50, "height": 40})),
|
||||
("edit.fill".to_string(), json!({"color": "#ff0000"})),
|
||||
("select.deselect".to_string(), json!({})),
|
||||
];
|
||||
s.actions.list.push(crate::actions_cmds::Action::new("A", steps));
|
||||
let (_, d) = command_damage(&mut s, "actions.play", json!({"action": "A"}));
|
||||
assert!(d.contains(300, 300) && d.contains(349, 339), "{d:?}");
|
||||
assert!(u64::from(d.width()) * u64::from(d.height()) * 4 < 1024 * 768, "the filled tiles, not the canvas: {d:?}");
|
||||
assert_eq!(s.whole_redraws, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_document_redraws_of_small_edits_are_counted() {
|
||||
let mut s = session(1000, 1000);
|
||||
let id = layer_with(&mut s, &[(Rect::new(0, 0, 1000, 1000), [0.2, 0.4, 0.6, 1.0])]);
|
||||
// A synthetic command that paints 1 % and reports "everything".
|
||||
let rev = s.active().unwrap().revision;
|
||||
let (before, _) = paint(&mut s, id, Rect::new(10, 10, 110, 110), [1.0, 0.0, 0.0, 1.0]);
|
||||
s.active_mut().unwrap().last_damage = None;
|
||||
s.note_command_damage("test.wholeRedraw", &before, rev);
|
||||
assert_eq!(s.whole_redraws, 1);
|
||||
// A canvas-size change really does redraw everything: not counted.
|
||||
s.execute("image.canvasSize", json!({"width": 1200, "height": 900})).unwrap();
|
||||
assert_eq!(s.active().unwrap().last_damage, None);
|
||||
assert_eq!(s.whole_redraws, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_command_redraws_the_whole_document_for_a_small_edit() {
|
||||
let mut s = session(1024, 768);
|
||||
let base = layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.2, 0.4, 0.6, 1.0])]);
|
||||
let small = layer_with(&mut s, &[(Rect::new(100, 100, 160, 160), [0.9, 0.1, 0.1, 1.0])]);
|
||||
let other = layer_with(&mut s, &[(Rect::new(130, 130, 190, 190), [0.1, 0.9, 0.1, 1.0])]);
|
||||
let path = json!({"subpaths": [{"knots": [[20, 20], [80, 20]]}, {"knots": [[800, 600], [900, 600]]}]});
|
||||
let steps: Vec<(&str, serde_json::Value)> = vec![
|
||||
("layer.select", json!({"layer": base.0})),
|
||||
("select.rect", json!({"x": 300, "y": 300, "width": 50, "height": 40})),
|
||||
("edit.fill", json!({"color": "#ff0000"})),
|
||||
("filter.blur.gaussianBlur", json!({"radius": 2})),
|
||||
("edit.copy", json!({})),
|
||||
("select.rect", json!({"x": 600, "y": 400, "width": 80, "height": 60})),
|
||||
("edit.pasteSpecial.pasteInto", json!({})),
|
||||
("edit.undo", json!({})),
|
||||
("edit.redo", json!({})),
|
||||
("layer.select", json!({"layer": base.0})),
|
||||
("paint.stroke", json!({"points": [[100, 400], [200, 420]], "size": 20, "color": "#2040ff"})),
|
||||
("edit.undo", json!({})),
|
||||
("edit.redo", json!({})),
|
||||
("path.set", json!({ "path": path })),
|
||||
("path.stroke", json!({"tool": "pencil", "size": 4, "color": "#0000ff", "opacity": 100})),
|
||||
("path.stroke", json!({"tool": "burn", "size": 16})),
|
||||
("layer.select", json!({"layer": small.0})),
|
||||
("layer.setProps", json!({"layer": small.0, "opacity": 0.5})),
|
||||
("layer.setProps", json!({"layer": small.0, "visible": false})),
|
||||
("layer.setProps", json!({"layer": small.0, "visible": true})),
|
||||
("layer.translate", json!({"layer": small.0, "dx": 20, "dy": 10})),
|
||||
// Show Only hides the full-canvas base: a large change, so not counted either way.
|
||||
("layer.showOnly", json!({"layer": small.0})),
|
||||
("layer.showOnly", json!({"layer": small.0})),
|
||||
("layer.arrange.bringForward", json!({})),
|
||||
("layer.arrange.sendBackward", json!({})),
|
||||
("layer.setProps", json!({"layer": other.0, "clipped": true})),
|
||||
("layer.new.layer", json!({})),
|
||||
];
|
||||
for (cmd, p) in steps {
|
||||
s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
|
||||
assert_eq!(s.whole_redraws, 0, "{cmd}: redrew the whole document for a small edit");
|
||||
}
|
||||
}
|
||||
@@ -276,7 +276,7 @@ fn raw_enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
let d = s.active().ok_or("no document open")?;
|
||||
match d.doc.mode {
|
||||
ColorMode::Rgb | ColorMode::Grayscale => Ok(()),
|
||||
m => Err(format!("Camera Raw Filter needs an RGB or Grayscale document (this one is {m:?})")),
|
||||
m => Err(format!("RAW Develop Filter needs an RGB or Grayscale document (this one is {m:?})")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,12 +412,13 @@ fn camera_raw_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if raw_pixels(area).is_none() {
|
||||
return Err(bad(
|
||||
RAW,
|
||||
format!("the image is too large for Camera Raw ({}×{} px; max {} megapixels)", area.width(), area.height(), MAX_RAW_PIXELS / 1_000_000),
|
||||
format!("the image is too large for RAW Develop ({}×{} px; max {} megapixels)", area.width(), area.height(), MAX_RAW_PIXELS / 1_000_000),
|
||||
));
|
||||
}
|
||||
}
|
||||
let t0 = Stopwatch::start();
|
||||
let id = run_filter(s, RAW, "Camera Raw Filter", p, p.clone(), false, &|surf, canvas| camera_raw_surface(surf, canvas.union(&surf.content_bounds()), &cr))?;
|
||||
let id =
|
||||
run_filter(s, RAW, "RAW Develop Filter", p, p.clone(), false, &|surf, canvas| camera_raw_surface(surf, canvas.union(&surf.content_bounds()), &cr))?;
|
||||
Ok(json!({"layer": id.0, "identity": cr.is_identity(), "ms": t0.ms()}))
|
||||
}
|
||||
|
||||
@@ -469,7 +470,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
},
|
||||
CommandSpec {
|
||||
id: RAW,
|
||||
label: "Camera Raw Filter…",
|
||||
label: "RAW Develop Filter…",
|
||||
menu: &["Filter"],
|
||||
shortcut: Some("Cmd+Shift+A"),
|
||||
params: r##"{"temperature":-100..100=0,"tint":-100..100=0,"exposure":-5..5=0,"contrast":-100..100=0,"highlights":-100..100=0,"shadows":-100..100=0,"whites":-100..100=0,"blacks":-100..100=0,"texture":-100..100=0,"clarity":-100..100=0,"dehaze":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=0,"curveHighlights":-100..100=0,"curveLights":-100..100=0,"curveDarks":-100..100=0,"curveShadows":-100..100=0,"curveSplits":[25,50,75],"pointCurve":[[in,out]],"pointCurveRed":[[in,out]],"pointCurveGreen":[[in,out]],"pointCurveBlue":[[in,out]],"hslHue":[8],"hslSat":[8],"hslLum":[8],"gradeShadows":{"hue":deg,"sat":0..100,"lum":-100..100},"gradeMidtones":{},"gradeHighlights":{},"gradeGlobal":{},"gradeBlending":0..100=50,"gradeBalance":-100..100=0,"shadowTint":-100..100=0,"calibrationHue":[red,green,blue] -100..100,"calibrationSat":[red,green,blue] -100..100 (the Calibration panel: Shadows tint and the primaries' hue and saturation),"sharpenAmount":0..150=0,"sharpenRadius":0.5..3=1,"sharpenDetail":0..100=25,"sharpenMasking":0..100=0,"noiseLuminance":0..100=0,"noiseLuminanceDetail":0..100=50,"noiseColor":0..100=0,"noiseColorDetail":0..100=50,"grainAmount":0..100=0,"grainSize":0..100=25,"grainRoughness":0..100=50,"vignetteAmount":-100..100=0,"vignetteMidpoint":0..100=50,"vignetteRoundness":-100..100=0,"vignetteFeather":0..100=50,"vignetteHighlights":0..100=0,"vignetteStyle":"highlightPriority|colorPriority|paintOverlay","seed":u32=0}"##,
|
||||
@@ -492,6 +493,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
#[test]
|
||||
fn raw_develop_filter_keeps_its_automation_id() {
|
||||
let command = super::specs().into_iter().find(|command| command.id == "filter.cameraRaw").expect("existing RAW command");
|
||||
assert_eq!(command.label, "RAW Develop Filter…");
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
fn session(depth: u32) -> Session {
|
||||
|
||||
@@ -22,14 +22,33 @@ fn has_notes(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.active().is_some_and(|d| !d.doc.notes.is_empty()) { Ok(()) } else { Err("the document has no notes".into()) }
|
||||
}
|
||||
|
||||
/// PDF-style date (`D:YYYYMMDDhhmmssZ`) as Photoshop stores in notes; empty without a clock.
|
||||
/// Photoshop's default note colour (#11795): RGB 255, 255, 131 (stored as 16-bit 0x8383 blue).
|
||||
pub const DEFAULT_NOTE_COLOR: [f32; 3] = [1.0, 1.0, 131.0 / 255.0];
|
||||
|
||||
/// The PDF date (`D:YYYYMMDDHHMMSS+HH'mm'`) Photoshop stores in a note: local time with its
|
||||
/// offset from UTC (#11795), through chrono. Empty without a clock (the web build).
|
||||
fn pdf_date() -> String {
|
||||
let iso = crate::analysis_cmds::now_iso();
|
||||
if iso.len() < 19 {
|
||||
return String::new();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let now = chrono::Local::now();
|
||||
pdf_date_at(&now.with_timezone(now.offset()))
|
||||
}
|
||||
let digits: String = iso[..19].chars().filter(char::is_ascii_digit).collect();
|
||||
format!("D:{digits}Z")
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`pdf_date`] for the moment `at`: its own wall-clock time and UTC offset.
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
pub(crate) fn pdf_date_at<Tz: chrono::TimeZone>(at: &chrono::DateTime<Tz>) -> String
|
||||
where
|
||||
Tz::Offset: std::fmt::Display,
|
||||
{
|
||||
use chrono::Offset;
|
||||
let off = at.offset().fix().local_minus_utc();
|
||||
let (sign, off) = if off < 0 { ('-', -off) } else { ('+', off) };
|
||||
format!("D:{}{sign}{:02}'{:02}'", at.format("%Y%m%d%H%M%S"), off / 3600, off % 3600 / 60)
|
||||
}
|
||||
|
||||
pub fn note_json(i: usize, n: &Note) -> Value {
|
||||
@@ -44,7 +63,8 @@ fn color_of(cmd: &str, p: &Value) -> Result<Option<Color>> {
|
||||
if p.get("color").is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let c = crate::commands::color_param(cmd, p, "color", [1.0, 1.0, 0.51, 1.0])?;
|
||||
let [r, g, b] = DEFAULT_NOTE_COLOR;
|
||||
let c = crate::commands::color_param(cmd, p, "color", [r, g, b, 1.0])?;
|
||||
Ok(Some(Color::rgb(c[0], c[1], c[2])))
|
||||
}
|
||||
|
||||
@@ -65,10 +85,11 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
author: p.get("author").and_then(Value::as_str).unwrap_or("").to_string(),
|
||||
text: p.get("text").and_then(Value::as_str).unwrap_or("").to_string(),
|
||||
position: [x, y],
|
||||
popup: [x + 20.0, y + 20.0, x + 260.0, y + 160.0],
|
||||
// Photoshop's popup: 240 × 140, at the icon's top-left + (8, 10) (#11795).
|
||||
popup: [x + 8.0, y + 10.0, x + 248.0, y + 150.0],
|
||||
color: Color::rgb(DEFAULT_NOTE_COLOR[0], DEFAULT_NOTE_COLOR[1], DEFAULT_NOTE_COLOR[2]),
|
||||
open: p.get("open").and_then(Value::as_bool).unwrap_or(true),
|
||||
modified: pdf_date(),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(c) = color_of(CMD, p)? {
|
||||
n.color = c;
|
||||
@@ -131,7 +152,8 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("all").and_then(Value::as_bool) == Some(true) {
|
||||
let n = s.active().map_or(0, |d| d.doc.notes.len());
|
||||
s.edit("Delete All Notes", |d, _| {
|
||||
// Photoshop's name for the step, with a lower-case "all" (#11791).
|
||||
s.edit("Delete all Notes", |d, _| {
|
||||
d.notes.clear();
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -270,7 +292,8 @@ mod tests {
|
||||
let d = s.active().unwrap().doc.clone();
|
||||
assert_eq!(d.notes[0].text, "fixed");
|
||||
assert_eq!(d.notes[0].position, [20.0, 12.0]);
|
||||
assert_eq!(d.notes[0].popup[0], 40.0);
|
||||
// The popup travels with its icon: 20 + 8 (#11795).
|
||||
assert_eq!(d.notes[0].popup[0], 28.0);
|
||||
// Unchanged edits don't add history.
|
||||
let before = s.active().unwrap().history.past_len();
|
||||
assert_eq!(s.execute("notes.set", json!({"index": 0, "text": "fixed"})).unwrap()["changed"], false);
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! #11795: what a new note stores, as in Photoshop: colour 255, 255, 131, a 240 × 140 popup at the
|
||||
//! icon's top-left + (8, 10), and a local-time PDF date with its offset. Document operations move
|
||||
//! the popup with its icon and keep its size.
|
||||
|
||||
use chrono::{FixedOffset, TimeZone};
|
||||
use serde_json::json;
|
||||
|
||||
use super::notes_cmds::{DEFAULT_NOTE_COLOR, pdf_date_at};
|
||||
use crate::Session;
|
||||
|
||||
fn session(w: u32, h: u32) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn note(s: &Session, i: usize) -> photocraft_doc::Note {
|
||||
s.active().unwrap().doc.notes[i].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_note_has_the_default_colour_and_popup() {
|
||||
let mut s = session(600, 400);
|
||||
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
|
||||
let n = note(&s, 0);
|
||||
let rgb = n.color.to_rgb();
|
||||
assert_eq!(rgb.map(|v| (v * 255.0).round() as i32), [255, 255, 131], "{rgb:?}");
|
||||
assert_eq!(DEFAULT_NOTE_COLOR.map(|v| (v * 65535.0).round() as u32), [0xffff, 0xffff, 0x8383], "the 16-bit components Photoshop saves");
|
||||
assert_eq!(n.popup, [108.0, 110.0, 348.0, 250.0], "icon + (8, 10), 240 × 140");
|
||||
// A note on the pasteboard keeps its popup there too.
|
||||
s.execute("notes.add", json!({"x": -178, "y": 300})).unwrap();
|
||||
assert_eq!(note(&s, 1).popup, [-170.0, 310.0, 70.0, 450.0]);
|
||||
// An explicit colour still wins.
|
||||
s.execute("notes.add", json!({"x": 10, "y": 10, "color": [0.25, 0.5, 1.0]})).unwrap();
|
||||
assert_eq!(note(&s, 2).color.to_rgb(), [0.25, 0.5, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_date_is_local_time_with_its_offset() {
|
||||
let at = |offset: i32| FixedOffset::east_opt(offset).unwrap().with_ymd_and_hms(2026, 11, 6, 20, 14, 55).unwrap();
|
||||
assert_eq!(pdf_date_at(&at(3600)), "D:20261106201455+01'00'");
|
||||
assert_eq!(pdf_date_at(&at(0)), "D:20261106201455+00'00'");
|
||||
assert_eq!(pdf_date_at(&at(-(5 * 3600 + 30 * 60))), "D:20261106201455-05'30'");
|
||||
// A new note's own date has that shape.
|
||||
let mut s = session(100, 100);
|
||||
s.execute("notes.add", json!({"x": 10, "y": 10})).unwrap();
|
||||
let d = note(&s, 0).modified;
|
||||
let b = d.as_bytes();
|
||||
assert!(d.len() == 23 && d.starts_with("D:") && matches!(b[16], b'+' | b'-') && b[19] == b'\'' && b[22] == b'\'', "{d}");
|
||||
assert!(d[2..16].chars().all(|c| c.is_ascii_digit()), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_size_moves_the_icon_and_keeps_the_popup_size() {
|
||||
let mut s = session(600, 400);
|
||||
s.execute("notes.add", json!({"x": 100, "y": 99})).unwrap();
|
||||
let before = note(&s, 0);
|
||||
s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap();
|
||||
let n = note(&s, 0);
|
||||
assert_eq!(n.position, [50.0, 49.5], "the icon point scales as today");
|
||||
let size = |p: [f64; 4]| [p[2] - p[0], p[3] - p[1]];
|
||||
assert_eq!(size(n.popup), size(before.popup), "240 × 140 still");
|
||||
assert_eq!([n.popup[0] - n.position[0], n.popup[1] - n.position[1]], [8.0, 10.0], "still at icon + (8, 10)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_size_and_a_quarter_turn_keep_the_popup_size() {
|
||||
let mut s = session(600, 400);
|
||||
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
|
||||
s.execute("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})).unwrap();
|
||||
let n = note(&s, 0);
|
||||
assert_eq!(n.position, [0.0, 50.0], "moved by the canvas offset");
|
||||
assert_eq!(n.popup, [8.0, 60.0, 248.0, 200.0]);
|
||||
s.execute("image.imageRotation.90cw", json!({})).unwrap();
|
||||
let r = note(&s, 0);
|
||||
assert_eq!([r.popup[2] - r.popup[0], r.popup[3] - r.popup[1]], [240.0, 140.0], "a turn doesn't swap the popup's sides");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mode_change_leaves_notes_alone() {
|
||||
let mut s = session(100, 100);
|
||||
s.execute("notes.add", json!({"x": 10, "y": 20})).unwrap();
|
||||
let before = note(&s, 0);
|
||||
s.execute("image.mode.cmyk", json!({})).unwrap();
|
||||
assert_eq!(note(&s, 0), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turn_keeps_todays_popup_origin_and_the_popup_size() {
|
||||
// Where the popup sits after a turn wasn't measured (#11795), so it keeps today's origin (the
|
||||
// top-left of the turned rectangle) and only the size rule applies.
|
||||
let mut s = session(600, 400);
|
||||
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
|
||||
// The popup [108, 110, 348, 250] turned 90° clockwise on a 400 px tall canvas spans x 150..290,
|
||||
// y 108..348; it starts there and stays 240 × 140.
|
||||
s.execute("image.imageRotation.90cw", json!({})).unwrap();
|
||||
assert_eq!(note(&s, 0).popup, [150.0, 108.0, 390.0, 248.0]);
|
||||
// A flip keeps today's mirrored popup, which already has its size.
|
||||
let mut s = session(600, 400);
|
||||
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
|
||||
s.execute("image.imageRotation.flipCanvasHorizontal", json!({})).unwrap();
|
||||
assert_eq!(note(&s, 0).popup, [252.0, 110.0, 492.0, 250.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unset_popup_stays_unset_under_image_size() {
|
||||
// An all-zero popup means "none stored": PSD export writes its default popup for it, so Image
|
||||
// Size must not turn it into a 0 × 0 rectangle somewhere else.
|
||||
let mut s = session(600, 400);
|
||||
let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
|
||||
doc.notes.push(photocraft_doc::Note { position: [100.0, 100.0], ..Default::default() });
|
||||
s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap();
|
||||
let n = note(&s, 0);
|
||||
assert_eq!(n.position, [50.0, 50.0]);
|
||||
assert_eq!(n.popup, [0.0; 4]);
|
||||
}
|
||||
Loaded 100 of 535 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user