diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000000..2408084cf9 --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,6 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json +reviews: + auto_review: + # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them. + ignore_usernames: + - "dependabot[bot]" diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..2c4b8cb1a4 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,30 @@ +version: 2 +updates: + # Maintain Rust / Cargo dependencies + - package-ecosystem: "cargo" + directory: "/" + schedule: + interval: "daily" + time: "06:00" + timezone: "America/New_York" + # Consolidate updates into a single PR rather than one PR per crate + groups: + cargo-dependencies: + patterns: + - "*" + commit-message: + prefix: "chore(deps)" + + # Maintain GitHub Actions workflows + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + time: "06:00" + timezone: "America/New_York" + groups: + actions: + patterns: + - "*" + commit-message: + prefix: "ci(deps)" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4303f0aac4..ba8243353d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -193,6 +193,16 @@ jobs: cargo nextest run --profile ci --workspace --locked --features heif "${targets[@]}" shell: bash + # Every command against adversarial params must return Err, never panic or hang (AGENTS.md + # Rule 9). It is `#[ignore]`d (slow), so Test skips it. Same packages, features and targets as + # Test, so nothing rebuilds: `--test panic_hunt` would drop the other crates' dev-dependency + # features and recompile the whole graph. The `ci` profile terminates it if it hangs. + - name: Panic hunt + if: runner.os == 'Linux' + run: >- + cargo nextest run --profile ci --workspace --locked --features heif --lib --bins --tests + --run-ignored only -E 'binary_id(photocraft-engine::panic_hunt)' + - name: Doctests if: matrix.part == 'all' || matrix.part == 'unit' run: cargo test --workspace --locked --features heif --doc diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 26eca62464..cbbbe069a5 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -27,7 +27,7 @@ next to them. | `crates/ui-egui/src/i18n/sr.tsv` | Serbian (Latin, Ekavian) UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) | | `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) | | `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) | -| `assets/icons/*.svg` except `slice-knife.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.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` and `marquee-{row,column}.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/*.svg` except `slice-knife.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.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` and `marquee-{row,column}.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/sampler.svg` | Color Sampler tool glyph: a target reticle marking a sampled pixel | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | @@ -38,11 +38,12 @@ 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/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 | | `assets/icons/gradient.svg` | Gradient tool glyph: a rounded rectangle filled with a left-to-right linear ramp, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/eraser-background.svg`, `assets/icons/eraser-magic.svg` | Background Eraser and Magic Eraser tool glyphs: Lucide `eraser` plus added marks | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from `icons/eraser.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/brush-replace.svg` | Color Replacement tool glyph: Lucide `brush` plus two swap arrows | Lucide Icons and Contributors; arrows by PhotoCraft contributors | Derived from `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | -| `assets/icons/quick-selection.svg` | Quick Selection tool glyph: Lucide `brush` plus a dashed selection arc around the bristles | Lucide Icons and Contributors; arc by PhotoCraft contributors | Derived from `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/quick-selection.svg` | Quick Selection tool glyph: Lucide `brush`, scaled to 70%, inside a dashed upright rounded "C" selection | Lucide Icons and Contributors; selection by PhotoCraft contributors | Derived from `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/bandage-sparkle.svg` | Remove tool glyph: Lucide `bandage` moved down, plus a sparkle mark | Lucide Icons and Contributors; mark by PhotoCraft contributors | Derived from `icons/bandage.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/direct-select.svg` | Direct Selection tool glyph: Lucide `mouse-pointer-2` plus an anchor square | Lucide Icons and Contributors; square by PhotoCraft contributors | Derived from `icons/mouse-pointer-2.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/pen-freeform.svg`, `assets/icons/pen-curvature.svg` | Freeform Pen and Curvature Pen tool glyphs: Lucide `pen-tool` scaled down, plus a freehand squiggle or a curve through two points | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from `icons/pen-tool.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | @@ -57,6 +58,7 @@ next to them. | `crates/ui-egui/src/theme.rs` (Solarized Dark palette) | Solarized colour scheme used by the Solarized Dark theme | Ethan Schoonover | | MIT, [`LICENSE-solarized.txt`](crates/ui-egui/src/LICENSE-solarized.txt) | | `crates/ui-egui/src/theme.rs` (Breeze Light and Breeze Dark themes) | The Breeze Light and Breeze Dark themes are original colour values on PhotoCraft's Studio layout, chosen to look close to KDE Plasma's Breeze (cool blue-greys, blue accent, 5 px frame radius) so the app blends into a Plasma desktop. None of Breeze's colour values, files or code are copied; the values are a few levels away from its schemes and tuned for text contrast | PhotoCraft contributors | Inspired by the look of KDE Breeze, (its colour schemes are LGPL-2.0-or-later) | Original work | | `crates/ui-egui/src/theme.rs` (Soft Dark and Soft Light themes) | Original colour values and radii for two low-contrast themes on PhotoCraft's Studio layout; no third-party palette, file or code is used | PhotoCraft contributors | Original | Original work | +| `crates/algo/data/libfacedetection.bin` (face detection weights, read by `crates/algo/src/faces.rs`, whose network code is a port of the library's) | libfacedetection CNN (YuNet design) weights and inference code, weights converted to half precision | Shiqi Yu | [ShiqiYu/libfacedetection](https://github.com/ShiqiYu/libfacedetection) (`src/facedetectcnn-data.cpp`, `facedetectcnn.cpp`, `facedetectcnn-model.cpp`) | BSD-3-Clause, [`LICENSE-libfacedetection.txt`](crates/algo/data/LICENSE-libfacedetection.txt) | ### Optional build input: craft-fonts (not files in this repo) diff --git a/Cargo.lock b/Cargo.lock index 138ca3d814..6b5a7bbf9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -849,7 +849,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.5", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -1222,6 +1222,11 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-docpath" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63" + [[package]] name = "craft-print" version = "0.1.0" @@ -1891,7 +1896,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1929,6 +1934,18 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exacl" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de9e551ced9d700a31dacb8b168129640240fcd7a279a3fa4d59608b84ebcae" +dependencies = [ + "bitflags 2.13.2", + "log", + "scopeguard", + "uuid", +] + [[package]] name = "exr" version = "1.74.2" @@ -3028,7 +3045,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -3690,7 +3707,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png 0.18.1", "thiserror 2.0.21", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4436,7 +4453,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4613,7 +4630,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.9.0" +version = "0.11.1" dependencies = [ "arboard", "async-io", @@ -4646,6 +4663,7 @@ dependencies = [ "rfd", "ron", "serde_json", + "tempfile", "winit", "winresource", "winsafe", @@ -4657,7 +4675,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.9.0" +version = "0.11.1" dependencies = [ "crc32fast", "flate2", @@ -4667,7 +4685,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.9.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4680,7 +4698,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.9.0" +version = "0.11.1" dependencies = [ "base64 0.22.1", "cap-std", @@ -4693,6 +4711,7 @@ dependencies = [ "photocraft-geom", "photocraft-io", "rmcp", + "rustix 1.1.5", "schemars", "serde", "serde_json", @@ -4702,7 +4721,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.9.0" +version = "0.11.1" dependencies = [ "photocraft-automation", "photocraft-codecs", @@ -4716,7 +4735,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.9.0" +version = "0.11.1" dependencies = [ "moxcms", "rayon", @@ -4724,7 +4743,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.9.0" +version = "0.11.1" dependencies = [ "exr", "flate2", @@ -4745,7 +4764,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.9.0" +version = "0.11.1" dependencies = [ "photocraft-cms", "serde", @@ -4753,7 +4772,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.9.0" +version = "0.11.1" dependencies = [ "criterion", "photocraft-color", @@ -4768,7 +4787,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.9.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4779,7 +4798,7 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.9.0" +version = "0.11.1" dependencies = [ "blake3", "craft-print", @@ -4795,6 +4814,7 @@ dependencies = [ "photocraft-format", "photocraft-geom", "photocraft-io", + "photocraft-ipp", "photocraft-ops", "photocraft-paint", "photocraft-plugins", @@ -4805,6 +4825,7 @@ dependencies = [ "photocraft-vector", "rayon", "roxmltree", + "same-file", "serde", "serde_json", "tempfile", @@ -4814,10 +4835,11 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.9.0" +version = "0.11.1" dependencies = [ "blake3", "crc32fast", + "exacl", "flate2", "libc", "photocraft-codecs", @@ -4831,18 +4853,19 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "winsafe", ] [[package]] name = "photocraft-geom" -version = "0.9.0" +version = "0.11.1" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.9.0" +version = "0.11.1" dependencies = [ "half", "log", @@ -4859,16 +4882,17 @@ dependencies = [ [[package]] name = "photocraft-heif" -version = "0.9.0" +version = "0.11.1" dependencies = [ "heic-rs", ] [[package]] name = "photocraft-io" -version = "0.9.0" +version = "0.11.1" dependencies = [ "blake3", + "craft-docpath", "crc32fast", "flate2", "photocraft-affinity", @@ -4893,16 +4917,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "photocraft-ipp" +version = "0.11.1" + [[package]] name = "photocraft-ops" -version = "0.9.0" +version = "0.11.1" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.9.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4913,7 +4941,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.9.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4928,7 +4956,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.9.0" +version = "0.11.1" dependencies = [ "flate2", "photocraft-psd", @@ -4939,17 +4967,18 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.9.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", "proptest", + "rayon", "serde", ] [[package]] name = "photocraft-raw" -version = "0.9.0" +version = "0.11.1" dependencies = [ "flate2", "image", @@ -4964,7 +4993,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.9.0" +version = "0.11.1" dependencies = [ "block2 0.6.2", "objc2 0.6.4", @@ -4976,7 +5005,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.9.0" +version = "0.11.1" dependencies = [ "memory-stats", "photocraft-color", @@ -4987,7 +5016,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.9.0" +version = "0.11.1" dependencies = [ "flate2", "parley", @@ -4996,12 +5025,13 @@ dependencies = [ "photocraft-geom", "photocraft-psd", "photocraft-raster", + "rayon", "skrifa", ] [[package]] name = "photocraft-ui-egui" -version = "0.9.0" +version = "0.11.1" dependencies = [ "base64 0.22.1", "craft-print", @@ -5037,12 +5067,13 @@ dependencies = [ "serde_json", "sys-locale", "toml", + "unicode-bidi", "winsafe", ] [[package]] name = "photocraft-vector" -version = "0.9.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5053,7 +5084,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.9.0" +version = "0.11.1" dependencies = [ "eframe", "egui", @@ -5075,7 +5106,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.9.0" +version = "0.11.1" dependencies = [ "flate2", "js-sys", @@ -5468,7 +5499,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5987,7 +6018,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -6054,7 +6085,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -6692,7 +6723,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -6919,10 +6950,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -7322,7 +7353,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -8082,7 +8113,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -8662,7 +8693,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.9.0" +version = "0.11.1" dependencies = [ "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 0d0f93ae7c..b3f49802e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.9.0" +version = "0.11.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -36,9 +36,11 @@ photocraft-engine = { path = "crates/engine" } photocraft-ui-egui = { path = "crates/ui-egui" } photocraft-testkit = { path = "crates/testkit" } photocraft-tablet = { path = "crates/tablet" } +photocraft-ipp = { path = "crates/ipp" } # external craft-print = { git = "https://github.com/storytold/craft-libs", rev = "3d37da389a3618ab9b76109da11416e9ca4ea719" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -136,6 +138,14 @@ opt-level = "z" [profile.wasm-release.package.naga] opt-level = "z" +# The browser UI toolkit favors size to stay within the WebAssembly upload budget. +[profile.wasm-release.package.egui] +opt-level = "z" +[profile.wasm-release.package.epaint] +opt-level = "z" +[profile.wasm-release.package.eframe] +opt-level = "z" + # Pixel processing keeps its speed-oriented optimization level, with two exceptions. # Colour-management transforms are built once and cached (`transform::cached`), so "z" costs # little runtime. The browser app composites per frame on the GPU (`crates/gpu`, WebGPU/WebGL2), diff --git a/NOTICE b/NOTICE index 887010d4a6..a7302a940c 100644 --- a/NOTICE +++ b/NOTICE @@ -16,6 +16,7 @@ Inter font (assets/fonts/Inter-*.ttf) — SIL Open Font License 1.1. See assets/ JetBrains Mono font (assets/fonts/JetBrainsMono-Regular.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-JetBrainsMono.txt. Lucide icons (assets/icons/*.svg, except slice-knife.svg) — ISC; icons derived from Feather also MIT. See assets/icons/LICENSE-lucide.txt. SCOWL English word list (assets/dict/en_US-scowl-50.txt.gz) — SCOWL license. See assets/dict/LICENSE-SCOWL.txt. +libfacedetection face detection weights and network (crates/algo/data/libfacedetection.bin, crates/algo/src/faces/cnn.rs) — BSD-3-Clause, Copyright (c) 2015-2019, Shiqi Yu, all rights reserved. See crates/algo/data/LICENSE-libfacedetection.txt. Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) also embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (today BIZ UDPGothic, Shippori Mincho and diff --git a/README.md b/README.md index d1e839323c..7554fcd8f2 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,9 @@ macOS · Windows · Linux · FreeBSD · Web License: MIT OR Apache-2.0 Status: early alpha +
+ Scanned by SonarCloud + Reviewed by CodeRabbit

@@ -275,6 +278,8 @@ flatpak install --user photocraft--linux-x86_64.flatpak # or -linux-a flatpak run ai.storyteller.photocraft ``` +The Flatpak prints through the host's CUPS socket (File › Print talks IPP to it directly, no `lp` needed); without CUPS, or without a printer, File › Print opens the system print dialog through the print portal. See [printing](docs/printing.md). + The AppImage needs no install: the first run registers its launcher icon and menu entry in `~/.local/share` so the dock shows PhotoCraft's icon on Wayland. Set `PHOTOCRAFT_NO_DESKTOP_INTEGRATION=1` to skip that, and see [`docs/releasing.md`](docs/releasing.md) › Linux to undo it. On a Wayland session, files dropped on the window don't open yet: winit 0.30, the windowing library under egui, has no Wayland drag and drop (#386). Use File › Open, or copy the image in your file manager and paste it with Ctrl+V. To drag and drop, start PhotoCraft under XWayland: `WAYLAND_DISPLAY= photocraft`, `WAYLAND_DISPLAY= ./photocraft--linux-x86_64.AppImage`, or `flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft`. On Wayland, PhotoCraft shows the command for your install in a notice until you dismiss it. Preferences › Performance › Linux display server = X11 does the same on every launch. With a fractional display scale (125%, 150%, 175%) an XWayland window is drawn at a lower resolution and enlarged by the compositor, so the interface is blurred there; native Wayland stays sharp (#1072). @@ -300,6 +305,19 @@ Maintainers: [`docs/releasing.md`](docs/releasing.md) explains how releases are > [!IMPORTANT] > **Status:** PhotoCraft is in early alpha, and we want to be straight about where it stands: much of Photoshop's feature surface exists in some form, but **it is not yet a Photoshop replacement for daily professional work**. The biggest gaps are AI/generative features, 15 missing tools, depth in typography and pro workflows, and plug-in compatibility. Every Photoshop menu item is wired to a command ([`docs/parity-checklist.md`](docs/parity-checklist.md)), but that measures wiring, not behaviour. The honest, dimension-by-dimension picture and where we're going next are in the [roadmap](ROADMAP.md) and [parity assessment](docs/target-app-parity.md). Expect rough edges, and please file issues (include your OS, document size, layer count and a screenshot). You can also tell us what broke on [Discord](https://discord.gg/artcraft). +## Community packages + +These installers are maintained by community members, not by the PhotoCraft team. + +On Gentoo, the [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages the Linux release as `media-gfx/photocraft-bin`: + +```sh +eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git +emaint sync -r snakebyte +echo 'media-gfx/photocraft-bin ~amd64' >> /etc/portage/package.accept_keywords/photocraft +emerge --ask media-gfx/photocraft-bin +``` + ## Documentation Developer, architecture, automation, format, and security documentation is maintained in the [PhotoCraft documentation book](book/). diff --git a/apps/photocraft-cli/Cargo.toml b/apps/photocraft-cli/Cargo.toml index a6d3b49389..f4848f379a 100644 --- a/apps/photocraft-cli/Cargo.toml +++ b/apps/photocraft-cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "photocraft-cli" -description = "Headless Photocraft: convert, inspect, run commands, batch, MCP server" +description = "Headless PhotoCraft: convert, inspect, run commands, batch, MCP server" version.workspace = true edition.workspace = true license.workspace = true diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index b93d4ccc8f..0e3429d074 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -1,4 +1,4 @@ -//! Headless Photocraft command line. `run` is the whole program, so it can be +//! Headless PhotoCraft command line. `run` is the whole program, so it can be //! tested in-process as well as through the binary. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -12,22 +12,24 @@ use photocraft_io::ExportOptions; use serde_json::{Value, json}; pub const USAGE: &str = "\ -photocraft-cli: headless Photocraft +photocraft-cli: headless PhotoCraft USAGE: - photocraft-cli convert [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] + photocraft-cli convert [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression ] [--dds-mipmaps] Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …). TIFF output is flat unless --tiff-layers keeps the layers (Photoshop layer data). --quality sets the JPEG or WebP quality; a WebP written with a quality is lossy, without one lossless. --tga-bits sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none. Without it: 32 with an alpha channel or transparency, else 24. --dpx-bits sets a DPX's bits per sample. Without it: 8 for an 8-bit document, else 16. + --dds-compression sets a DDS texture's compression: none (uncompressed, the default), bc1 + (DXT1: alpha on or off), bc2 (DXT3) or bc3 (DXT5). --dds-mipmaps also writes the full mip chain. photocraft-cli info [--compact] Print the document as JSON (size, mode, depth, layer tree). - photocraft-cli run ( | --new ) --cmd [--params ] [--cmd …] [--out ] [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] + photocraft-cli run ( | --new ) --cmd [--params ] [--cmd …] [--out ] [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression ] [--dds-mipmaps] Open a file, run engine commands in order, save the result. Each --params applies to the preceding --cmd. Prints each command's JSON result. - photocraft-cli batch --actions [--action ] --in

--out [--format ] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] + photocraft-cli batch --actions [--action ] --in --out [--format ] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression ] [--dds-mipmaps] Apply an action list to every image in a directory. A Photoshop Actions file (.atn) is a set: its action --action names plays, as below. JSON steps are [id, params] pairs, {\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them @@ -69,18 +71,23 @@ struct Subcommand { } const SUBCOMMANDS: &[Subcommand] = &[ - Subcommand { name: "convert", values: &["--format", "--quality", "--tga-bits", "--dpx-bits"], bare: &["--tiff-layers"], run: convert }, + Subcommand { + name: "convert", + values: &["--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"], + bare: &["--tiff-layers", "--dds-mipmaps"], + run: convert, + }, Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) }, Subcommand { name: "run", - values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits"], - bare: &["--tiff-layers"], + values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"], + bare: &["--tiff-layers", "--dds-mipmaps"], run: run_cmds, }, Subcommand { name: "batch", - values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits"], - bare: &["--in-place", "--tiff-layers"], + values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"], + bare: &["--in-place", "--tiff-layers", "--dds-mipmaps"], run: batch, }, Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet }, @@ -219,6 +226,11 @@ fn export_opts(a: &Args) -> Result { o.encode.dpx_bits = Some(b.parse().ok().and_then(photocraft_io::DpxBits::from_bits).ok_or_else(|| format!("bad --dpx-bits `{b}`: expected 8, 10, 12 or 16"))?); } + if let Some(c) = a.get("--dds-compression") { + o.encode.dds.compression = + photocraft_io::DdsCompression::from_name(c).ok_or_else(|| format!("bad --dds-compression `{c}`: expected none, bc1, bc2 or bc3"))?; + } + o.encode.dds.mipmaps = a.has("--dds-mipmaps"); Ok(o) } diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rs index 3c28a8196e..6c62e40804 100644 --- a/apps/photocraft-cli/tests/cli.rs +++ b/apps/photocraft-cli/tests/cli.rs @@ -494,6 +494,39 @@ fn dpx_converts_both_ways_with_the_bits_asked_for() { } } +/// DDS converts both ways; `--dds-compression` picks the FourCC (bytes 84–87; none writes +/// uncompressed pixels) and `--dds-mipmaps` the mip count (bytes 28–31). A compression that +/// isn't none, bc1, bc2 or bc3 is refused and nothing is written (#1327). +#[test] +fn dds_converts_both_ways_with_the_compression_asked_for() { + let d = tmp("dds"); + let a = d.join("a.png"); + write_png(&a, 8, 4, 3); + for (args, fourcc, mips) in [ + (&[][..], [0; 4], 1), + (&["--dds-compression", "bc1"][..], *b"DXT1", 1), + (&["--dds-compression", "DXT3", "--dds-mipmaps"][..], *b"DXT3", 4), + (&["--dds-compression", "bc3"][..], *b"DXT5", 1), + (&["--dds-mipmaps"][..], [0; 4], 4), + ] { + let out = d.join("a.dds"); + ok(bin().arg("convert").arg(&a).arg(&out).args(args)); + let bytes = std::fs::read(&out).unwrap(); + let mip_count = u32::from_le_bytes(bytes[28..32].try_into().unwrap()); + assert_eq!((&bytes[..4], &bytes[84..88], mip_count), (&b"DDS "[..], &fourcc[..], mips), "{args:?}"); + let back = d.join("back.png"); + ok(bin().arg("convert").arg(&out).arg(&back)); + assert!(back.exists(), "{args:?}"); + } + for bad in ["bc7", "dxt2", ""] { + let out = d.join("bad.dds"); + let o = bin().arg("convert").arg(&a).arg(&out).args(["--dds-compression", bad]).output().unwrap(); + assert_eq!(o.status.code(), Some(1), "--dds-compression {bad}"); + assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("bad --dds-compression `{bad}`")), "--dds-compression {bad}"); + assert!(!out.exists(), "--dds-compression {bad} wrote a file"); + } +} + /// `--tga-bits` picks a TGA's bits per pixel (byte 16 of its header); anything but 24 or 32 is /// refused and nothing is written. #[test] diff --git a/apps/photocraft-web/Cargo.toml b/apps/photocraft-web/Cargo.toml index a4ded64181..4ecad80ae4 100644 --- a/apps/photocraft-web/Cargo.toml +++ b/apps/photocraft-web/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "photocraft-web" -description = "Photocraft in the browser (eframe web runner, WebGPU with WebGL2 fallback)" +description = "PhotoCraft in the browser (eframe web runner, WebGPU with WebGL2 fallback)" version.workspace = true edition.workspace = true license.workspace = true @@ -34,7 +34,7 @@ rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "Navigator"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "DomRect", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "Navigator"] } [dev-dependencies] serde_json = { workspace = true } diff --git a/apps/photocraft-web/src/main.rs b/apps/photocraft-web/src/main.rs index 5ba75f5254..0802a02ebf 100644 --- a/apps/photocraft-web/src/main.rs +++ b/apps/photocraft-web/src/main.rs @@ -1,4 +1,4 @@ -//! Photocraft in the browser. +//! PhotoCraft in the browser. //! //! Runs the same [`photocraft_ui_egui::PhotocraftApp`] as the desktop app through eframe's web //! runner (wgpu: WebGPU where available, WebGL2 otherwise). Build with `trunk build --release` @@ -6,10 +6,10 @@ //! //! Differences from the desktop app: //! - no TCP control server (browsers can't listen on sockets); -//! - File → Open uses the browser file picker; bytes arrive asynchronously through -//! `Services::inbox`; +//! - file pickers return browser file contents asynchronously through `Services::file_dialog`; +//! this includes File → Open and commands such as Place Embedded; //! - saving/exporting triggers a browser download; -//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox. +//! - dropped files are read asynchronously by `web::WebShell` and delivered through `Services::inbox`. //! //! URL query flags: `?cpu` forces the CPU canvas path (same as `PHOTOCRAFT_CPU_CANVAS=1`); //! `?webgl` forces the WebGL2 backend instead of WebGPU. diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs index eb350d17eb..a248ecbb13 100644 --- a/apps/photocraft-web/src/web.rs +++ b/apps/photocraft-web/src/web.rs @@ -1,6 +1,8 @@ //! The browser shell: web `Services`, drag-and-drop, and the eframe web runner. +use std::cell::Cell; use std::collections::{HashMap, HashSet}; +use std::rc::Rc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; @@ -79,11 +81,13 @@ pub fn start() { Box::new(move |cc| { PhotocraftApp::setup_context(&cc.egui_ctx, ThemeKind::Pro); let inbox: Inbox = Arc::default(); + let place_inbox: Inbox = Arc::default(); let served: Served = Arc::default(); load_font_manifest(served.clone(), cc.egui_ctx.clone()); let (session, warnings) = crate::preset_bridge::session(presets.clone()); preset_warnings.extend(warnings); - let mut app = PhotocraftApp::new(session, services(inbox.clone())); + let drag = listen_drag(&pen_target); + let mut app = PhotocraftApp::new(session, services(inbox.clone(), place_inbox.clone(), drag_pos_service(pen_target.clone(), drag))); if !preset_warnings.is_empty() { photocraft_ui_egui::notices::post(&mut app, i18n::t("Some brush presets could not be loaded"), preset_warnings, true, None); } @@ -97,7 +101,7 @@ pub fn start() { } let unsaved = Arc::new(AtomicBool::new(false)); guard_unload(unsaved.clone()); - Ok(Box::new(WebShell { app, inbox, unsaved, served, database, presets })) + Ok(Box::new(WebShell { app, inbox, place_inbox, unsaved, served, database, presets })) }), ) .await; @@ -140,6 +144,38 @@ fn listen_pen(target: &web_sys::HtmlCanvasElement, feed: photocraft_ui_egui::sty } } +/// The pointer in a drag over the page, in CSS pixels relative to the viewport (`clientX`, +/// `clientY`): the last `dragover` or `drop` event's. +type DragPos = Rc>>; + +/// Follows files dragged over the canvas. eframe's drop events carry no pointer position and the +/// page gets no pointer events during a drag, so this is where a drop lands: on the document's +/// canvas it places the files, elsewhere it opens them (#5749). +fn listen_drag(target: &web_sys::HtmlCanvasElement) -> DragPos { + use wasm_bindgen::closure::Closure; + let pos = DragPos::default(); + for kind in ["dragover", "drop"] { + let pos = pos.clone(); + // A DragEvent is a MouseEvent: only its client position is read. + let cb = Closure::::new(move |e: web_sys::MouseEvent| pos.set(Some((e.client_x() as f32, e.client_y() as f32)))); + if target.add_event_listener_with_callback(kind, cb.as_ref().unchecked_ref()).is_ok() { + cb.forget(); + } + } + pos +} + +/// `Services::cursor_pos` for the web: the last drag position in egui points, mapped as eframe +/// maps pointer events (relative to the canvas, divided by the zoom factor). +fn drag_pos_service(canvas: web_sys::HtmlCanvasElement, pos: DragPos) -> photocraft_ui_egui::CursorPosFn { + Box::new(move |ctx: &egui::Context| { + let (x, y) = pos.get()?; + let rect = canvas.get_bounding_client_rect(); + let zoom = ctx.zoom_factor(); + (zoom.is_finite() && zoom > 0.0).then(|| egui::pos2((x - rect.left() as f32) / zoom, (y - rect.top() as f32) / zoom)) + }) +} + /// Closing or reloading the tab while a document has unsaved changes asks first, as closing the /// desktop window does: the browser shows its own "Leave site?" prompt (#1380). `unsaved` is /// refreshed every frame by [`WebShell`]. @@ -219,10 +255,13 @@ async fn fetch_bytes(url: &str, integrity: Option<&str>) -> Result, Stri } /// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously, -/// so the app's own drop path can't handle them) and feed them through the inbox. +/// so the app's own drop path can't handle them) and feed them through the inboxes. struct WebShell { app: PhotocraftApp, + /// Dropped files to open as documents. inbox: Inbox, + /// Dropped files to place on the active document's canvas. + place_inbox: Inbox, /// Read by the `beforeunload` listener ([`guard_unload`]). unsaved: Arc, served: Served, @@ -285,17 +324,26 @@ impl WebShell { impl eframe::App for WebShell { fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)); - for f in dropped { - let inbox = self.inbox.clone(); + if !dropped.is_empty() { + let names: Vec = + dropped.iter().map(|f| f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into())).collect(); + // Decided now, where the drop landed: on the document's canvas the files are placed + // as layers (as on the desktop), elsewhere opened. + let places = self.app.dropped_on_canvas(ctx, &names); + let files: Vec<_> = dropped.into_iter().zip(names).zip(places).collect(); + let (inbox, place_inbox) = (self.inbox.clone(), self.place_inbox.clone()); let ctx = ctx.clone(); + // One after another, so they open or place in the order they were dropped. wasm_bindgen_futures::spawn_local(async move { - let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); - match f.bytes_async().await { - Ok(bytes) => { - inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)); - ctx.request_repaint(); + for ((f, name), place) in files { + match f.bytes_async().await { + Ok(bytes) => { + let queue = if place { &place_inbox } else { &inbox }; + queue.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)); + ctx.request_repaint(); + } + Err(e) => log::error!("couldn't read dropped file {name}: {e}"), } - Err(e) => log::error!("couldn't read dropped file {name}: {e}"), } }); } @@ -333,7 +381,7 @@ impl eframe::App for WebShell { } } -fn services(inbox: Inbox) -> Services { +fn services(inbox: Inbox, place_inbox: Inbox, cursor_pos: photocraft_ui_egui::CursorPosFn) -> Services { Services { screen_pick: screen_color_service(), import: Some(Box::new(|name: &str, bytes: &[u8], max_svg_group_depth: usize| { @@ -379,11 +427,15 @@ fn services(inbox: Inbox) -> Services { } })), write: Some(Box::new(|path: &str, bytes: &[u8]| download(path, bytes))), + // A download may be cancelled and never reports back: it doesn't save the document. + write_unconfirmed: true, encode_png: Some(Box::new(|w, h, rgba| { let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?; photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string()) })), inbox: Some(inbox), + place_inbox: Some(place_inbox), + cursor_pos: Some(cursor_pos), // Preferences live in the browser's localStorage. load_prefs: Some(Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten())), save_prefs: Some(Box::new(|text: &str| local_storage().ok_or("no localStorage")?.set_item(PREFS_KEY, text).map_err(|e| format!("{e:?}")))), diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml index e5af663471..505947e222 100644 --- a/apps/photocraft/Cargo.toml +++ b/apps/photocraft/Cargo.toml @@ -4,7 +4,7 @@ version.workspace = true edition.workspace = true license.workspace = true default-run = "photocraft" -description = "Photocraft: an open-source, native image editor" +description = "PhotoCraft: an open-source, native image editor" build = "build.rs" [features] @@ -65,6 +65,8 @@ dispatch2 = { version = "=0.3.1", default-features = false, features = ["std"] } # Drop position on X11 (`cursor.rs`): pure-Rust X client, already in Cargo.lock; pinned exactly. [target.'cfg(target_os = "linux")'.dependencies] photocraft-cms = { workspace = true } +# The print portal's PDF: a private (0600) temporary file, removed when the dialog is done. +tempfile = "3" x11rb = { version = "=0.13.2", default-features = false, features = ["image", "randr", "xkb"] } # Clipboard images in types other than PNG on Wayland (`services.rs`, #2546): arboard asks for # image/png only. Already in Cargo.lock (arboard's wayland-data-control); pinned exactly. diff --git a/apps/photocraft/src/app_dirs.rs b/apps/photocraft/src/app_dirs.rs index 2897bebdb0..a75520f3c4 100644 --- a/apps/photocraft/src/app_dirs.rs +++ b/apps/photocraft/src/app_dirs.rs @@ -9,6 +9,9 @@ //! folder can't be written (read-only medium, Program Files), the app warns and falls back. //! 3. The platform convention: macOS `~/Library/Application Support/Photocraft`, Windows //! `%APPDATA%\Photocraft`, Linux `$XDG_CONFIG_HOME/photocraft` or `~/.config/photocraft`. +//! +//! One exception: the platform convention keeps crash-recovery autosaves out of what is synced +//! with the settings: the Windows roaming profile and the Linux config folder ([`recovery_dir`]). use std::ffi::OsString; use std::path::{Path, PathBuf}; @@ -60,6 +63,396 @@ pub fn config_dir() -> Option { current().dir.clone() } +/// The crash-recovery folder's name. +const RECOVERY: &str = "Recovery"; + +/// Where crash-recovery autosaves live, with any left in the settings directory by an earlier +/// version moved there first ([`adopt_legacy_recovery`]). Call it once, at startup. +pub fn recovery_dir() -> Option { + let data = current(); + let dir = resolve_recovery(data, |k| std::env::var_os(k))?; + Some(match data.dir.as_ref().map(|d| d.join(RECOVERY)) { + Some(legacy) => adopt_legacy_recovery(&legacy, &dir), + None => dir, + }) +} + +/// The recovery folder for `data`. Autosaves hold whole documents and are rewritten every few +/// minutes, so with the platform convention they stay out of what is synced with the settings: +/// - Windows (#5648): the machine-local `%LOCALAPPDATA%\Photocraft\Recovery`; the roaming +/// `%APPDATA%` may be synced at sign-in and sign-out or capped by policy. +/// - Linux and other XDG systems (#6612): `$XDG_STATE_HOME/photocraft/Recovery`, by default +/// `~/.local/state/photocraft/Recovery`, where the XDG Base Directory spec puts state that +/// should outlive a restart but isn't configuration; dotfile managers and config sync often copy +/// `~/.config` whole. As the spec asks, a relative `XDG_STATE_HOME` is ignored. +/// - macOS: `~/Library/Application Support/Photocraft/Recovery` as before. Apple's guidelines put +/// app-created data that can't be regenerated there; `~/Library/Caches` may be purged by the +/// system. +/// +/// They are never in a temp or cache folder, which cleanup tools may empty before a crashed +/// document is recovered. The override and portable folders keep everything in one place. +pub fn resolve_recovery(data: &DataDir, env: impl Fn(&str) -> Option) -> Option { + if data.mode == Mode::Platform { + if cfg!(windows) { + if let Some(local) = env("LOCALAPPDATA").filter(|l| !l.is_empty()) { + return Some(PathBuf::from(local).join("Photocraft").join(RECOVERY)); + } + } else if !cfg!(target_os = "macos") { + let state = env("XDG_STATE_HOME") + .map(PathBuf::from) + .filter(|s| s.is_absolute()) + .or_else(|| env("HOME").filter(|h| !h.is_empty()).map(|h| PathBuf::from(h).join(".local").join("state"))); + if let Some(state) = state { + return Some(state.join("photocraft").join(RECOVERY)); + } + } + } + data.dir.as_ref().map(|d| d.join(RECOVERY)) +} + +/// The lock file, beside the recovery folder, that keeps two PhotoCraft processes starting at +/// once (`--new-instance`, control launches) from moving the same autosaves. +const MIGRATION_LOCK: &str = "recovery-migration.lock"; + +/// How long a launch waits for another one's move before going ahead without moving anything. +const MIGRATION_WAIT: std::time::Duration = std::time::Duration::from_secs(5); + +/// Suffix of a copy staged for publishing ([`stage_copy`]): disposable, the original still exists. +const STAGED: &str = ".moving"; + +/// Suffix of an original set aside while it is copied to another volume ([`move_across`]): it +/// may be the only copy, so it is put back, never thrown away, if the move doesn't finish. +const HELD: &str = ".held"; + +/// Move autosaves from `legacy` (the recovery folder of versions before #5648) into `dir`, so a +/// crash just before an update is still offered for recovery. Returns the folder this process +/// uses for its recovery store. That is `legacy` only when `dir` doesn't exist and no process can +/// be moving autosaves (the move failed, or its lock can't be made), so nothing deletes what is +/// written there. A launch that finds another one moving uses `dir`, which the move never +/// replaces or removes. See [`adopt_locked`] for how they move. +pub fn adopt_legacy_recovery(legacy: &Path, dir: &Path) -> PathBuf { + adopt_legacy_recovery_waiting(legacy, dir, MIGRATION_WAIT) +} + +/// [`adopt_legacy_recovery`], waiting up to `wait` for another process's move. +fn adopt_legacy_recovery_waiting(legacy: &Path, dir: &Path, wait: std::time::Duration) -> PathBuf { + let held_aside = || legacy.parent().is_some_and(|p| !side_entries(p, legacy, HELD).is_empty()); + if legacy == dir || (!legacy.is_dir() && !held_aside()) { + return dir.to_path_buf(); + } + // An empty old folder has nothing to move (`remove_dir` only removes an empty one). + if !held_aside() && std::fs::remove_dir(legacy).is_ok() { + return dir.to_path_buf(); + } + let unmoved = || if dir.exists() || !legacy.is_dir() { dir.to_path_buf() } else { legacy.to_path_buf() }; + let Some(parent) = dir.parent() else { return unmoved() }; + let lock = + std::fs::create_dir_all(parent).and_then(|()| std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(parent.join(MIGRATION_LOCK))); + let Ok(lock) = lock else { + // No lock file means no other process can be moving: the old folder is safe to use. + log::warn!("couldn't open the recovery move lock in {}; autosaves stay where they are", parent.display()); + return unmoved(); + }; + let deadline = std::time::Instant::now() + wait; + loop { + match lock.try_lock() { + Ok(()) => break, + Err(std::fs::TryLockError::WouldBlock) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(50)), + Err(std::fs::TryLockError::WouldBlock) => { + // Another process is moving and may yet remove the old folder: never write there. + log::info!("another PhotoCraft is moving crash-recovery autosaves; using {}", dir.display()); + return dir.to_path_buf(); + } + Err(std::fs::TryLockError::Error(e)) => { + // Locking fails for every process here alike, so none can be moving. + log::warn!("couldn't lock {}: {e}; autosaves stay where they are", parent.join(MIGRATION_LOCK).display()); + return unmoved(); + } + } + } + // The lock file stays (removing it would race a process about to lock it); the OS releases + // the lock when `lock` is dropped or the process ends. + let used = adopt_locked(legacy, dir); + if used == legacy { + // This process writes its autosaves to the old folder: it keeps the lock for as long as it + // runs, so no other launch moves (and removes) the folder under it. + KEPT_LOCKS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(lock); + } + used +} + +/// Migration locks of the old folders this process uses (see [`adopt_legacy_recovery`]), kept +/// until it ends. +static KEPT_LOCKS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// The move itself, under the migration lock. First, what a process that ended mid-move left is +/// tidied: originals it set aside are put back, copies it staged are removed. An empty `legacy` +/// is then just removed. Otherwise the whole folder moves if `dir` doesn't exist yet; when both +/// exist, each autosave (`.pcraft` bundle and `.json` sidecar, see +/// `photocraft_format::autosave`) moves as a whole, bundle first, unless `dir` already has either +/// part, and one that stays is left in `legacy` untouched. Every move is a [`move_path`]. +fn adopt_locked(legacy: &Path, dir: &Path) -> PathBuf { + if let Some(parent) = legacy.parent() { + for held in side_entries(parent, legacy, HELD) { + put_back(&held, legacy); + } + } + // Autosave parts held aside inside the old folder by a per-autosave move. + let held_parts: Vec<(PathBuf, String)> = std::fs::read_dir(legacy) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| e.file_name().to_str().and_then(|n| side_of(n, HELD)).map(|orig| (e.path(), orig.to_owned()))) + .collect(); + for (held, original) in held_parts { + put_back(&held, &legacy.join(original)); + } + for folder in [dir.parent(), Some(dir)].into_iter().flatten() { + remove_stale_staging(folder); + } + // Another process may have finished the move while this one waited. + if !legacy.is_dir() { + return dir.to_path_buf(); + } + if std::fs::remove_dir(legacy).is_ok() { + return dir.to_path_buf(); + } + if !dir.exists() { + // The common case: the whole folder moves at once. + return match move_path(legacy, dir) { + Ok(()) => { + log::info!("moved crash-recovery autosaves from {} to {}", legacy.display(), dir.display()); + dir.to_path_buf() + } + Err(e) => { + log::warn!("couldn't move crash-recovery autosaves from {} to {} ({e}); using the old folder", legacy.display(), dir.display()); + if legacy.is_dir() { legacy.to_path_buf() } else { dir.to_path_buf() } + } + }; + } + move_entries(legacy, dir); + // Only an emptied folder goes; anything that couldn't move stays for a later launch. + let _ = std::fs::remove_dir(legacy); + dir.to_path_buf() +} + +/// Move each autosave of `from` into `to` (both folders): bundle first, then sidecar, skipped if +/// `to` has either part. Temp files of an interrupted write (`photocraft_format::atomic`) go +/// along too, for the recovery store's startup sweep there. +fn move_entries(from: &Path, to: &Path) { + let Ok(entries) = std::fs::read_dir(from) else { return }; + let names: Vec = entries.flatten().filter_map(|e| e.file_name().to_str().map(str::to_owned)).collect(); + let keys: std::collections::BTreeSet<&str> = names.iter().filter_map(|n| n.strip_suffix(".pcraft").or_else(|| n.strip_suffix(".json"))).collect(); + for key in keys { + let parts = [format!("{key}.pcraft"), format!("{key}.json")]; + if parts.iter().any(|p| std::fs::symlink_metadata(to.join(p)).is_ok()) { + continue; + } + // A bundle that moves without its sidecar is still listed (`list_recovery` reads a + // committed bundle's manifest); a sidecar must never move without its bundle. + for part in &parts { + let src = from.join(part); + if std::fs::symlink_metadata(&src).is_ok() + && let Err(e) = move_path(&src, &to.join(part)) + { + log::warn!("couldn't move {} to {}: {e}", src.display(), to.display()); + break; + } + } + } + for name in names.iter().filter(|n| n.ends_with(".pcsave.tmp")) { + let _ = move_path(&from.join(name), &to.join(name)); + } +} + +/// How deep [`copy_tree`] follows folders: an autosave bundle is a few levels deep. +const MAX_COPY_DEPTH: u32 = 16; + +fn already_exists(path: &Path) -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::AlreadyExists, format!("{} already exists", path.display())) +} + +/// A path beside `of`, named `..-`, that no other call uses. +fn side_path(of: &Path, suffix: &str) -> std::io::Result { + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let parent = of.parent().ok_or_else(|| std::io::Error::other(format!("{} has no parent folder", of.display())))?; + let name = of.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + Ok(parent.join(format!(".{name}.{}-{}{suffix}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)))) +} + +/// The name `side` was made from, if it is a [`side_path`] name with `suffix`. +fn side_of<'a>(side: &'a str, suffix: &str) -> Option<&'a str> { + let rest = side.strip_prefix('.')?.strip_suffix(suffix)?; + let (name, ids) = rest.rsplit_once('.')?; + let (pid, n) = ids.split_once('-')?; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + (!name.is_empty() && digits(pid) && digits(n)).then_some(name) +} + +/// The side paths with `suffix` in `folder` made from `of`. +fn side_entries(folder: &Path, of: &Path, suffix: &str) -> Vec { + let Some(name) = of.file_name().and_then(|n| n.to_str()) else { return Vec::new() }; + std::fs::read_dir(folder) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.file_name().to_str().and_then(|n| side_of(n, suffix)) == Some(name)) + .map(|e| e.path()) + .collect() +} + +/// Move the file or folder `from` to `to` without ever replacing anything at `to`. On one volume +/// a folder is renamed (Windows refuses an existing target; elsewhere only an empty folder could +/// be replaced) and a file is hard-linked, which fails on an existing target, and then unlinked +/// at `from`. Otherwise (another volume, e.g. a roaming profile redirected to a network share +/// while `%LOCALAPPDATA%` stays local) it is copied ([`move_across`]). +fn move_path(from: &Path, to: &Path) -> std::io::Result<()> { + if std::fs::symlink_metadata(to).is_ok() { + return Err(already_exists(to)); + } + let meta = std::fs::symlink_metadata(from)?; + let moved = if meta.is_dir() { std::fs::rename(from, to) } else { std::fs::hard_link(from, to).and_then(|()| std::fs::remove_file(from)) }; + match moved { + Ok(()) => Ok(()), + Err(e) if matches!(e.kind(), std::io::ErrorKind::AlreadyExists | std::io::ErrorKind::DirectoryNotEmpty) => Err(e), + Err(_) => move_across(from, to), + } +} + +/// Move `from` to `to` by copying. `from` is first renamed aside on its own volume +/// (`..-.held`, [`hold`]), so a process still writing to the old path (another +/// launch that couldn't take the lock, an older PhotoCraft) starts a new `from` there instead of +/// adding to what is copied, and nothing it writes is removed. The held original is copied to a +/// staged path ([`stage_copy`]), published without replacing anything ([`publish`]), and only +/// then removed. If the copy or publish fails, the held original is put back ([`put_back`]). +fn move_across(from: &Path, to: &Path) -> std::io::Result<()> { + let held = hold(from)?; + match stage_copy(&held, to).and_then(|staged| publish(&staged, to)) { + Ok(()) => { + let removed = if std::fs::symlink_metadata(&held)?.is_dir() { std::fs::remove_dir_all(&held) } else { std::fs::remove_file(&held) }; + if let Err(e) = removed { + log::warn!("copied {} to {} but couldn't remove {}: {e}", from.display(), to.display(), held.display()); + } + Ok(()) + } + Err(e) => { + put_back(&held, from); + Err(e) + } + } +} + +/// Rename `from` aside on its own volume (see [`move_across`]); returns where it is now. +fn hold(from: &Path) -> std::io::Result { + let held = side_path(from, HELD)?; + std::fs::rename(from, &held)?; + Ok(held) +} + +/// Return the held original `held` to `original`. If `original` has been made again meanwhile (a +/// writer that kept using the old path), the held folder's entries move into it without replacing +/// anything ([`move_entries`]); whatever can't move stays held, logged, and is tried again under +/// the next move's lock ([`adopt_locked`] puts back what a process that ended mid-move held). +/// Nothing held is ever removed with data in it. +fn put_back(held: &Path, original: &Path) { + if std::fs::symlink_metadata(original).is_err() && std::fs::rename(held, original).is_ok() { + return; + } + if held.is_dir() && original.is_dir() { + move_entries(held, original); + if std::fs::remove_dir(held).is_ok() { + return; + } + } + log::warn!("{} is kept aside: {} exists", held.display(), original.display()); +} + +/// Copy `from` to a staging path beside `to` that this call creates exclusively, so nothing +/// another process made is ever written to or cleaned up. On failure the staged copy is removed. +fn stage_copy(from: &Path, to: &Path) -> std::io::Result { + let staged = side_path(to, STAGED)?; + let is_dir = std::fs::symlink_metadata(from)?.is_dir(); + let copied = if is_dir { copy_tree(from, &staged, 0) } else { copy_file(from, &staged) }; + if let Err(e) = copied { + // `copy_tree` and `copy_file` create `staged` exclusively, and everything under a + // fresh folder is new: `AlreadyExists` means `staged` was someone else's to keep. + if e.kind() != std::io::ErrorKind::AlreadyExists { + let _ = if is_dir { std::fs::remove_dir_all(&staged) } else { std::fs::remove_file(&staged) }; + } + return Err(e); + } + Ok(staged) +} + +/// Remove copies a process left staged in `folder` when it ended mid-move: disposable, since the +/// original is still in place or held aside. Called only under the migration lock, which every +/// staging happens under. Links are never followed. +fn remove_stale_staging(folder: &Path) { + let Ok(entries) = std::fs::read_dir(folder) else { return }; + for entry in entries.flatten() { + if !entry.file_name().to_str().is_some_and(|n| side_of(n, STAGED).is_some()) { + continue; + } + let removed = match entry.file_type() { + Ok(t) if t.is_dir() => std::fs::remove_dir_all(entry.path()), + Ok(t) if t.is_file() => std::fs::remove_file(entry.path()), + _ => continue, + }; + if let Err(e) = removed { + log::warn!("couldn't remove the stale staged copy {}: {e}", entry.path().display()); + } + } +} + +/// Give the staged copy its final name `to` without replacing anything there (see [`move_path`] +/// for the folder and file cases). On failure the staged copy is removed and `to` is untouched. +fn publish(staged: &Path, to: &Path) -> std::io::Result<()> { + let is_dir = std::fs::symlink_metadata(staged)?.is_dir(); + let published = if std::fs::symlink_metadata(to).is_ok() { + Err(already_exists(to)) + } else if is_dir { + std::fs::rename(staged, to) + } else { + std::fs::hard_link(staged, to).and_then(|()| std::fs::remove_file(staged)) + }; + if published.is_err() { + let _ = if is_dir { std::fs::remove_dir_all(staged) } else { std::fs::remove_file(staged) }; + } + published +} + +/// Copy the folder `from` to the new folder `to` (created here; an existing `to` is an error): +/// plain files and folders only (a link or other special file is refused), at most +/// [`MAX_COPY_DEPTH`] levels. +fn copy_tree(from: &Path, to: &Path, depth: u32) -> std::io::Result<()> { + if depth > MAX_COPY_DEPTH { + return Err(std::io::Error::other(format!("{} is nested too deep", from.display()))); + } + std::fs::create_dir(to)?; + for entry in std::fs::read_dir(from)? { + let entry = entry?; + let target = to.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_tree(&entry.path(), &target, depth.saturating_add(1))?; + } else { + copy_file(&entry.path(), &target)?; + } + } + Ok(()) +} + +/// Copy one plain file (a link or other special file is refused) to the new file `to` (an +/// existing `to` is an error), flushed to disk. +fn copy_file(from: &Path, to: &Path) -> std::io::Result<()> { + if !std::fs::symlink_metadata(from)?.file_type().is_file() { + return Err(std::io::Error::other(format!("{} is not a plain file", from.display()))); + } + let mut src = std::fs::File::open(from)?; + let mut dst = std::fs::OpenOptions::new().write(true).create_new(true).open(to)?; + std::io::copy(&mut src, &mut dst)?; + dst.sync_all() +} + /// Resolve the data directory from the environment (`env`) and the executable's folder. pub fn resolve(env: impl Fn(&str) -> Option, exe_dir: Option<&Path>) -> DataDir { if let Some(d) = env("PHOTOCRAFT_CONFIG_DIR").filter(|d| !d.is_empty()) { @@ -223,6 +616,330 @@ mod tests { let _ = std::fs::remove_dir_all(&root); } + /// #5648: on Windows, autosaves go to the machine-local `%LOCALAPPDATA%`, not the roaming + /// profile; an override or portable folder keeps them inside itself. + #[test] + fn autosaves_stay_out_of_the_roaming_profile() { + let root = temp("recovery-local"); + let settings = root.join("appdata").join("Photocraft"); + let local = root.join("local"); + let env = env_of(&[("LOCALAPPDATA", &local)]); + let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; + let expected = if cfg!(windows) { local.join("Photocraft").join("Recovery") } else { settings.join("Recovery") }; + assert_eq!(resolve_recovery(&platform, &env), Some(expected)); + for mode in [Mode::Override, Mode::Portable] { + let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; + assert_eq!(resolve_recovery(&d, &env), Some(settings.join("Recovery")), "{mode:?}"); + } + // No (or an empty) LOCALAPPDATA: beside the settings, as before. + let empty = PathBuf::new(); + assert_eq!(resolve_recovery(&platform, env_of(&[("LOCALAPPDATA", &empty)])), Some(settings.join("Recovery"))); + assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); + let nowhere = DataDir { dir: None, mode: Mode::Platform, warning: None }; + assert_eq!(resolve_recovery(&nowhere, |_| None), None); + let _ = std::fs::remove_dir_all(&root); + } + + /// #6612: on Linux (and other XDG systems) autosaves go to `$XDG_STATE_HOME`, by default + /// `~/.local/state`, not the config folder; a relative `XDG_STATE_HOME` is ignored. Windows + /// and macOS don't read it, and an override or portable folder keeps them inside itself. + #[test] + fn autosaves_go_to_the_xdg_state_folder() { + let root = temp("recovery-xdg"); + let settings = root.join("home").join(".config").join("photocraft"); + let home = root.join("home"); + let state = root.join("state"); + let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; + let xdg = !cfg!(windows) && !cfg!(target_os = "macos"); + let expect = |xdg_path: PathBuf| Some(if xdg { xdg_path } else { settings.join("Recovery") }); + assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), expect(state.join("photocraft").join("Recovery"))); + let default = home.join(".local").join("state").join("photocraft").join("Recovery"); + assert_eq!(resolve_recovery(&platform, env_of(&[("HOME", &home)])), expect(default.clone())); + let relative = PathBuf::from("relative/state"); + assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &relative), ("HOME", &home)])), expect(default.clone())); + let empty = PathBuf::new(); + assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &empty), ("HOME", &home)])), expect(default)); + // No home at all: beside the settings, as before. + assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); + for mode in [Mode::Override, Mode::Portable] { + let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; + assert_eq!(resolve_recovery(&d, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), Some(settings.join("Recovery")), "{mode:?}"); + } + let _ = std::fs::remove_dir_all(&root); + } + + /// An autosave bundle and its sidecar, as `format::Autosaver` writes them. + fn autosave(dir: &Path, key: &str) { + std::fs::create_dir_all(dir.join(format!("{key}.pcraft"))).unwrap(); + std::fs::write(dir.join(format!("{key}.pcraft")).join("manifest.json"), key).unwrap(); + std::fs::write(dir.join(format!("{key}.json")), key).unwrap(); + } + + #[test] + fn autosaves_from_the_old_folder_move_to_the_new_one() { + let root = temp("recovery-move"); + let legacy = root.join("roaming").join("Recovery"); + let dir = root.join("local").join("Photocraft").join("Recovery"); + autosave(&legacy, "a"); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); + assert!(!legacy.exists(), "the old folder is gone"); + assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); + assert!(dir.join("a.json").is_file()); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn autosaves_merge_into_an_existing_folder_without_overwriting() { + let root = temp("recovery-merge"); + let legacy = root.join("roaming").join("Recovery"); + let dir = root.join("local").join("Recovery"); + autosave(&legacy, "old"); + autosave(&legacy, "both"); + // A temp file of an interrupted write moves along, for the recovery store's sweep. + let temp_file = ".old.json.4294967294-0.pcsave.tmp"; + std::fs::write(legacy.join(temp_file), b"partial").unwrap(); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("both.json"), "newer").unwrap(); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); + assert!(dir.join(temp_file).is_file() && !legacy.join(temp_file).exists()); + assert!(dir.join("old.pcraft").is_dir() && dir.join("old.json").is_file(), "a whole autosave moves"); + assert_eq!(std::fs::read_to_string(dir.join("both.json")).unwrap(), "newer", "never overwritten"); + assert!(!dir.join("both.pcraft").exists(), "a clashing autosave isn't split"); + assert!(legacy.join("both.pcraft").is_dir() && legacy.join("both.json").is_file(), "it stays behind whole"); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn autosaves_that_cannot_move_keep_being_used_where_they_are() { + let root = temp("recovery-stuck"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + // A file where the new folder's parent should be: nothing can be created there. + std::fs::write(root.join("blocked"), b"in the way").unwrap(); + let dir = root.join("blocked").join("Recovery"); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), legacy); + assert!(legacy.join("a.json").is_file(), "nothing lost"); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn an_empty_old_folder_is_removed_even_where_it_cannot_move() { + let root = temp("recovery-empty"); + let legacy = root.join("roaming").join("Recovery"); + std::fs::create_dir_all(&legacy).unwrap(); + std::fs::write(root.join("blocked"), b"in the way").unwrap(); + let dir = root.join("blocked").join("Recovery"); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir, "nothing to keep listed"); + assert!(!legacy.exists(), "the empty old folder is gone"); + let _ = std::fs::remove_dir_all(&root); + } + + /// Where a rename can't cross volumes (a roaming profile on a network share), an autosave + /// is copied whole, nested folders included, and only then removed. + #[test] + fn a_move_across_volumes_copies_then_removes() { + let root = temp("recovery-copy"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + std::fs::create_dir_all(legacy.join("a.pcraft").join("tiles")).unwrap(); + std::fs::write(legacy.join("a.pcraft").join("tiles").join("t0.zst"), b"tile").unwrap(); + let dir = root.join("local").join("Recovery"); + std::fs::create_dir_all(root.join("local")).unwrap(); + move_across(&legacy, &dir).unwrap(); + assert!(!legacy.exists(), "the original is removed after the copy"); + assert_eq!(side_leftovers(&root.join("roaming")), 0, "nothing is left held aside"); + assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); + assert_eq!(std::fs::read(dir.join("a.pcraft").join("tiles").join("t0.zst")).unwrap(), b"tile"); + assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a"); + // One file on its own, as the per-autosave moves do. + move_across(&dir.join("a.json"), &root.join("a.json")).unwrap(); + assert!(!dir.join("a.json").exists() && root.join("a.json").is_file()); + assert_eq!(side_leftovers(&dir) + side_leftovers(&root), 0); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn a_failed_copy_puts_the_original_back_and_leaves_no_partial_copy() { + let root = temp("recovery-copy-fail"); + let legacy = root.join("Recovery"); + autosave(&legacy, "a"); + // Deeper than any bundle: the copy gives up part way. + let mut deep = legacy.join("a.pcraft"); + for _ in 0..=MAX_COPY_DEPTH { + deep = deep.join("d"); + } + std::fs::create_dir_all(&deep).unwrap(); + let dir = root.join("Local"); + assert!(move_across(&legacy, &dir).is_err()); + assert!(!dir.exists(), "nothing is published"); + assert_eq!(side_leftovers(&root), 0, "no staged copy, nothing left held aside"); + assert!(legacy.join("a.json").is_file() && deep.is_dir(), "the original is back in place"); + // A target that already exists is never copied into or removed. + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("keep"), b"mine").unwrap(); + assert!(move_across(&legacy.join("a.json"), &dir).is_err()); + assert_eq!(std::fs::read(dir.join("keep")).unwrap(), b"mine"); + assert!(legacy.join("a.json").is_file()); + assert_eq!(side_leftovers(&root) + side_leftovers(&legacy), 0); + let _ = std::fs::remove_dir_all(&root); + } + + /// Staged (`.moving`) and held (`.held`) side paths left in `dir`. + fn side_leftovers(dir: &Path) -> usize { + std::fs::read_dir(dir) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_str().is_some_and(|n| side_of(n, STAGED).is_some() || side_of(n, HELD).is_some())) + .count() + } + + /// The target appears after the copy is staged (another process got there first): publishing + /// fails, that process's target keeps its contents, the staged copy is removed and the + /// original is left as it was. Folder and file alike. + #[test] + fn a_target_that_appears_while_copying_is_never_replaced_or_removed() { + let root = temp("recovery-race"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + let local = root.join("local"); + std::fs::create_dir_all(&local).unwrap(); + // A whole folder. + let dir = local.join("Recovery"); + let staged = stage_copy(&legacy, &dir).unwrap(); + autosave(&dir, "theirs"); + let e = publish(&staged, &dir).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read_to_string(dir.join("theirs.json")).unwrap(), "theirs", "their folder is intact"); + assert!(!dir.join("a.json").exists(), "nothing was copied into it"); + assert!(!staged.exists() && side_leftovers(&local) == 0, "only the staged copy is removed"); + assert!(legacy.join("a.json").is_file(), "the original is untouched"); + // One file. + let to = dir.join("a.json"); + let staged = stage_copy(&legacy.join("a.json"), &to).unwrap(); + std::fs::write(&to, "theirs").unwrap(); + assert_eq!(publish(&staged, &to).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read_to_string(&to).unwrap(), "theirs"); + assert!(!staged.exists() && legacy.join("a.json").is_file()); + let _ = std::fs::remove_dir_all(&root); + } + + /// A process holds the lock and is copying the old folder (held aside, copy staged) when a + /// second launch gives up waiting. The second launch must get the new folder, never the old + /// one, and what it writes there survives the first one finishing: the publish refuses the + /// now-existing folder and the original is put back, so both autosaves stay (#6412 review). + #[test] + fn a_launch_that_times_out_never_writes_where_a_move_removes() { + let _spawns = crate::no_child_spawns(); + let root = temp("recovery-timeout"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "old"); + let local = root.join("local"); + std::fs::create_dir_all(&local).unwrap(); + let dir = local.join("Recovery"); + // First process: takes the lock, sets the original aside and stages its copy, then pauses. + let first = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(local.join(MIGRATION_LOCK)).unwrap(); + first.lock().unwrap(); + let held = hold(&legacy).unwrap(); + let staged = stage_copy(&held, &dir).unwrap(); + // Second launch: times out and writes a newer autosave where it was told to. + let chosen = adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO); + assert_eq!(chosen, dir, "a launch that couldn't get the lock never uses the old folder"); + autosave(&chosen, "new"); + // First process resumes: publish, and on failure put the original back (as `move_across`). + assert_eq!(publish(&staged, &dir).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + put_back(&held, &legacy); + drop(first); + assert_eq!(std::fs::read_to_string(dir.join("new.json")).unwrap(), "new", "the newer autosave survives"); + assert_eq!(std::fs::read_to_string(legacy.join("old.json")).unwrap(), "old", "the old one is back in place"); + assert_eq!(side_leftovers(&local) + side_leftovers(&root.join("roaming")), 0); + // The next launch merges them. + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert!(dir.join("old.json").is_file() && dir.join("new.json").is_file() && !legacy.exists()); + let _ = std::fs::remove_dir_all(&root); + } + + /// A writer that still uses the old path while it is being copied (an older PhotoCraft) + /// starts a new folder there; the move removes only the original it held aside. + #[test] + fn a_write_to_the_old_path_during_a_copy_is_not_removed() { + let root = temp("recovery-old-writer"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "old"); + let local = root.join("local"); + std::fs::create_dir_all(&local).unwrap(); + let dir = local.join("Recovery"); + let held = hold(&legacy).unwrap(); + let staged = stage_copy(&held, &dir).unwrap(); + autosave(&legacy, "new"); + publish(&staged, &dir).unwrap(); + std::fs::remove_dir_all(&held).unwrap(); + assert_eq!(std::fs::read_to_string(dir.join("old.json")).unwrap(), "old"); + assert_eq!(std::fs::read_to_string(legacy.join("new.json")).unwrap(), "new", "the new write is untouched"); + let _ = std::fs::remove_dir_all(&root); + } + + /// What a process killed mid-move left is tidied at the next move: a held original is put + /// back (it may be the only copy) and moved, a staged copy is removed; other dot-files and + /// look-alike names are not touched. + #[test] + fn a_killed_move_is_tidied_next_time() { + let root = temp("recovery-stale"); + let roaming = root.join("roaming"); + let legacy = roaming.join("Recovery"); + autosave(&legacy, "a"); + let held = hold(&legacy).unwrap(); + assert!(!legacy.exists() && held.is_dir()); + let local = root.join("local"); + let dir = local.join("Recovery"); + let stale = local.join(".Recovery.4294967294-3.moving"); + autosave(&stale, "half"); + let kept = [local.join(".Recovery.moving"), local.join(".keep.1-x.moving"), local.join("notes.txt")]; + for k in &kept { + std::fs::write(k, b"x").unwrap(); + } + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a", "the held original was put back and moved"); + assert!(!stale.exists(), "the stale staged copy is gone"); + assert_eq!(side_leftovers(&roaming), 0); + assert!(kept.iter().all(|k| k.is_file()), "only side names are touched"); + assert_eq!(side_of(".a.json.12-0.moving", STAGED), Some("a.json")); + assert!(side_of("a.json.12-0.moving", STAGED).is_none() && side_of(".a.json.-0.moving", STAGED).is_none()); + assert!(side_of(".a.json.12-0.held", STAGED).is_none() && side_of(".a.json.12-0.held", HELD) == Some("a.json")); + let _ = std::fs::remove_dir_all(&root); + } + + /// While another process holds the move lock, a launch moves nothing and uses the new folder; + /// once the lock is released, the move happens. + #[test] + fn a_move_waits_for_another_process_holding_the_lock() { + let _spawns = crate::no_child_spawns(); + let root = temp("recovery-lock"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + let dir = root.join("local").join("Recovery"); + std::fs::create_dir_all(root.join("local")).unwrap(); + let held = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(root.join("local").join(MIGRATION_LOCK)).unwrap(); + held.lock().unwrap(); + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert!(legacy.join("a.json").is_file() && !dir.exists(), "nothing moved under another's lock"); + drop(held); + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert!(dir.join("a.json").is_file() && !legacy.exists()); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn no_old_folder_or_the_same_folder_changes_nothing() { + let root = temp("recovery-noop"); + let dir = root.join("Recovery"); + assert_eq!(adopt_legacy_recovery(&root.join("missing"), &dir), dir); + assert!(!dir.exists(), "nothing is created up front"); + autosave(&dir, "a"); + assert_eq!(adopt_legacy_recovery(&dir, &dir), dir); + assert!(dir.join("a.json").is_file()); + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn missing_exe_dir_or_env_never_panics() { let d = resolve(|_| None, None); diff --git a/apps/photocraft/src/file_dialog_probe.rs b/apps/photocraft/src/file_dialog_probe.rs index 9ee14c0afb..eed74a58f2 100644 --- a/apps/photocraft/src/file_dialog_probe.rs +++ b/apps/photocraft/src/file_dialog_probe.rs @@ -70,25 +70,61 @@ pub fn start() { /// Whether the portal's `FileChooser` interface is on the session bus: `Some(false)` only when the /// bus or the interface is definitely absent, `None` for anything inconclusive (a slow reply). +/// +/// Asks the portal object to introspect itself rather than reading the interface's `version` +/// property: xdg-desktop-portal exports `FileChooser` only when a backend offers it, and without +/// one a property read fails with `InvalidArgs` ("No such interface"), an error the old check +/// didn't count as absent (#5739). The interface list answers the question directly. #[cfg(target_os = "linux")] fn file_chooser_portal() -> Option { let Ok(conn) = zbus::blocking::connection::Builder::session().and_then(|b| b.method_timeout(std::time::Duration::from_secs(5)).build()) else { return Some(false); }; - let proxy = zbus::blocking::proxy::Builder::>::new(&conn) - .destination("org.freedesktop.portal.Desktop") - .and_then(|b| b.path("/org/freedesktop/portal/desktop")) - .and_then(|b| b.interface("org.freedesktop.portal.FileChooser")) - .and_then(|b| b.cache_properties(zbus::proxy::CacheProperties::No).build()) - .ok()?; - match proxy.get_property::("version") { - Ok(_) => Some(true), - Err(zbus::Error::MethodError(name, _, _)) => { - let name = name.as_str(); - let absent = ["ServiceUnknown", "UnknownObject", "UnknownInterface", "UnknownProperty"].iter().any(|n| name.ends_with(n)); - absent.then_some(false) - } - Err(_) => None, + let reply = conn.call_method( + Some("org.freedesktop.portal.Desktop"), + "/org/freedesktop/portal/desktop", + Some("org.freedesktop.DBus.Introspectable"), + "Introspect", + &(), + ); + match reply { + Ok(message) => match message.body().deserialize::() { + Ok(xml) => Some(interface_listed(&xml)), + Err(_) => None, + }, + Err(e) => classify_error(&e), + } +} + +/// Whether introspection XML lists the portal's `FileChooser` interface (not a longer name such as +/// `FileChooser2`). +#[cfg(target_os = "linux")] +fn interface_listed(xml: &str) -> bool { + ["\"", "'"].iter().any(|quote| xml.contains(&format!(" Option { + use zbus::fdo::Error as Fdo; + // Names a bus daemon or portal answers with when the thing asked about is absent. + const ABSENT: [&str; 7] = ["ServiceUnknown", "NameHasNoOwner", "UnknownObject", "UnknownInterface", "UnknownMethod", "UnknownProperty", "InvalidArgs"]; + match e { + zbus::Error::FDO(fdo) => matches!( + **fdo, + Fdo::ServiceUnknown(_) + | Fdo::NameHasNoOwner(_) + | Fdo::UnknownObject(_) + | Fdo::UnknownInterface(_) + | Fdo::UnknownMethod(_) + | Fdo::UnknownProperty(_) + | Fdo::InvalidArgs(_) + ) + .then_some(false), + zbus::Error::MethodError(name, _, _) => ABSENT.iter().any(|n| name.as_str().ends_with(n)).then_some(false), + _ => None, } } @@ -126,4 +162,69 @@ mod tests { assert!(!on_path("kdialog", &path)); std::fs::remove_dir_all(&dir).unwrap(); } + + #[cfg(target_os = "linux")] + mod portal { + use super::super::*; + + const WITH_FILE_CHOOSER: &str = r#" + + + + + + +"#; + const WITHOUT_FILE_CHOOSER: &str = r#" + + +"#; + + fn method_error(name: &'static str) -> zbus::Error { + let call = zbus::message::Message::method_call("/a", "M").unwrap().build(&()).unwrap(); + let reply = zbus::message::Message::error(&call.header(), name).unwrap().build(&"detail").unwrap(); + zbus::Error::MethodError(name.try_into().unwrap(), Some("detail".into()), reply) + } + + #[test] + fn the_interface_list_says_whether_a_file_chooser_is_offered() { + assert!(interface_listed(WITH_FILE_CHOOSER)); + assert!(interface_listed(""), "single quotes"); + assert!(!interface_listed(WITHOUT_FILE_CHOOSER), "portal without a backend"); + assert!(!interface_listed(r#""#), "longer name"); + assert!(!interface_listed("")); + } + + #[test] + fn dbus_errors_for_a_missing_interface_mean_absent() { + // zbus's fdo proxies hand D-Bus errors back as `Error::FDO`, a plain method call as + // `MethodError`; both forms count. The portal answers `InvalidArgs` ("No such interface") + // when no backend offers the interface (#5739). + for e in [ + zbus::fdo::Error::InvalidArgs("No such interface".into()), + zbus::fdo::Error::UnknownInterface("x".into()), + zbus::fdo::Error::ServiceUnknown("x".into()), + zbus::fdo::Error::NameHasNoOwner("x".into()), + zbus::fdo::Error::UnknownObject("x".into()), + ] { + let desc = format!("{e:?}"); + assert_eq!(classify_error(&zbus::Error::FDO(Box::new(e))), Some(false), "{desc}"); + } + } + + #[test] + fn method_error_names_still_count_as_absent() { + for name in ["org.freedesktop.DBus.Error.ServiceUnknown", "org.freedesktop.DBus.Error.InvalidArgs", "org.freedesktop.DBus.Error.UnknownMethod"] { + assert_eq!(classify_error(&method_error(name)), Some(false), "{name}"); + } + assert_eq!(classify_error(&method_error("org.freedesktop.DBus.Error.AccessDenied")), None); + } + + #[test] + fn inconclusive_errors_are_not_absent() { + assert_eq!(classify_error(&zbus::Error::FDO(Box::new(zbus::fdo::Error::NoReply("slow".into())))), None); + assert_eq!(classify_error(&zbus::Error::FDO(Box::new(zbus::fdo::Error::Failed("x".into())))), None); + assert_eq!(classify_error(&zbus::Error::InputOutput(std::sync::Arc::new(std::io::Error::other("gone")))), None); + } + } } diff --git a/apps/photocraft/src/logging.rs b/apps/photocraft/src/logging.rs index 292428b8ce..5c8f0697dd 100644 --- a/apps/photocraft/src/logging.rs +++ b/apps/photocraft/src/logging.rs @@ -4,7 +4,9 @@ //! lost device, the crash guard's panic report) vanished. A launch from a desktop menu has no //! terminal, so the file is what a bug report can attach: `/logs/photocraft.log` //! (see `app_dirs`). Each start moves the previous log to `photocraft.1.log` (and that one to -//! `.2`), so the log of a run that crashed survives the next launch. +//! `.2`), so the log of a run that crashed survives the next launch. A start while another +//! instance is still running leaves that instance's log alone and writes `photocraft-.log` +//! (see [`rotate`]). //! //! Levels: `info` for PhotoCraft's own crates, `warn` for everything else (wgpu and naga are //! chatty). `RUST_LOG` replaces that with env_logger-style directives: `debug`, @@ -15,7 +17,7 @@ //! written once the file is attached. Writing never panics: a file that can't be created or //! written leaves standard error as the only sink. -use std::fs::File; +use std::fs::{File, OpenOptions, TryLockError}; use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::{Mutex, OnceLock, PoisonError}; @@ -116,10 +118,76 @@ fn numbered(dir: &Path, n: usize) -> PathBuf { if n == 0 { dir.join(LOG_FILE) } else { dir.join(format!("photocraft.{n}.log")) } } -/// Shift the previous logs up one (`.log` → `.1.log` → … → `..log`, the oldest dropped) -/// and create a fresh, empty log file in `dir` (created if missing). -pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> { +/// Held by the instance that writes [`LOG_FILE`], from its start until it exits. A separate lock +/// file rather than a lock on the log itself: Windows locks are mandatory, and a locked log could +/// not be opened for a bug report while the app runs. +pub const OWNER_LOCK: &str = "photocraft.lock"; +/// Held while one start rotates and prunes the logs, so two starts at once can't interleave. +pub const ROTATE_LOCK: &str = "rotate.lock"; + +/// The log of an instance started while another one was writing [`LOG_FILE`]. +fn instance_log(dir: &Path, pid: u32) -> PathBuf { + dir.join(format!("photocraft-{pid}.log")) +} + +/// The lock file that marks [`instance_log`] as in use. +fn instance_lock(dir: &Path, pid: u32) -> PathBuf { + dir.join(format!("photocraft-{pid}.lock")) +} + +/// The process id in an [`instance_log`] file name. +fn instance_pid(name: &str) -> Option { + let digits = name.strip_prefix("photocraft-")?.strip_suffix(".log")?; + if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + digits.parse().ok() +} + +fn open_lock(path: &Path) -> std::io::Result { + OpenOptions::new().read(true).write(true).create(true).truncate(false).open(path) +} + +/// Take `file`'s lock without waiting: `Ok(true)` holds it, `Ok(false)` when another process holds it. +fn try_hold(file: &File) -> std::io::Result { + match file.try_lock() { + Ok(()) => Ok(true), + Err(TryLockError::WouldBlock) => Ok(false), + Err(TryLockError::Error(e)) => Err(e), + } +} + +/// Open a fresh, empty log file in `dir` (created if missing). +/// +/// Normally the previous logs shift up one (`.log` → `.1.log` → … → `..log`, the oldest +/// dropped). While another instance is still writing [`LOG_FILE`] (it holds [`OWNER_LOCK`]), the +/// chain is left alone and this start writes `photocraft-.log` instead: rotating would move +/// that instance's live log away and, a few launches later, delete it (#6432). Such side-by-side +/// logs are pruned to the newest [`KEEP`] once their instances have exited. On a file system +/// without locks every start rotates, as before. +pub fn rotate(dir: &Path) -> std::io::Result { std::fs::create_dir_all(dir)?; + // Waits only for another start's few file operations; without locking support, go on. + let guard = open_lock(&dir.join(ROTATE_LOCK)).ok().filter(|g| g.lock().is_ok()); + let log = rotate_locked(dir); + drop(guard); + log +} + +fn rotate_locked(dir: &Path) -> std::io::Result { + prune_instance_logs(dir); + let owner = open_lock(&dir.join(OWNER_LOCK))?; + let state = try_hold(&owner); + if let Ok(false) = state { + let pid = std::process::id(); + let lock = open_lock(&instance_lock(dir, pid))?; + let held = try_hold(&lock).unwrap_or(false); + let path = instance_log(dir, pid); + let file = File::create(&path)?; + return Ok(LogFile { path, file, owner: held.then_some(lock) }); + } + // This start holds the owner lock (or the file system has no locks). + let held = state.unwrap_or(false); for n in (1..=KEEP).rev() { match std::fs::rename(numbered(dir, n - 1), numbered(dir, n)) { Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e), @@ -128,7 +196,40 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> { } let path = numbered(dir, 0); let file = File::create(&path)?; - Ok((path, file)) + Ok(LogFile { path, file, owner: held.then_some(owner) }) +} + +/// Remove the side-by-side logs of instances that have exited, all but the newest [`KEEP`]. +/// A log whose lock file is held belongs to a running instance and is never touched. Failures +/// are ignored: pruning only saves disk space. +fn prune_instance_logs(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + let mut finished: Vec<(SystemTime, u32)> = Vec::new(); + for entry in entries.flatten() { + let Some(pid) = entry.file_name().to_str().and_then(instance_pid) else { continue }; + // A missing lock file means nobody holds it; an unknown lock state counts as running. + let running = match OpenOptions::new().read(true).write(true).open(instance_lock(dir, pid)) { + Ok(lock) => !try_hold(&lock).unwrap_or(false), + Err(_) => false, + }; + if !running { + let modified = entry.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH); + finished.push((modified, pid)); + } + } + finished.sort_unstable_by(|a, b| b.cmp(a)); + for &(_, pid) in finished.iter().skip(KEEP) { + let _ = std::fs::remove_file(instance_log(dir, pid)); + let _ = std::fs::remove_file(instance_lock(dir, pid)); + } +} + +/// A log file opened by [`rotate`]. +pub struct LogFile { + pub path: PathBuf, + pub file: File, + /// The held lock that marks `path` as in use; `None` where locking isn't supported. + owner: Option, } /// One formatted log line: ` [] : \n`. @@ -205,17 +306,20 @@ pub struct AppLogger { filter: Filter, stderr: bool, sink: Mutex, + /// The lock that marks the attached log file as in use (see [`rotate`]); held until exit. + owner: Mutex>, } impl AppLogger { pub fn new(filter: Filter, stderr: bool) -> AppLogger { - AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)) } + AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)), owner: Mutex::new(None) } } /// Rotate the logs in `dir` and send records to the fresh file; returns its path. pub fn attach_dir(&self, dir: &Path) -> Result { - let (path, file) = rotate(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let LogFile { path, file, owner } = rotate(dir).map_err(|e| format!("{}: {e}", dir.display()))?; self.sink.lock().unwrap_or_else(PoisonError::into_inner).attach(file); + *self.owner.lock().unwrap_or_else(PoisonError::into_inner) = owner; Ok(path) } } @@ -316,9 +420,10 @@ mod tests { #[test] fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() { + let _spawns = crate::no_child_spawns(); let dir = temp_dir("rotate"); for run in 1..=4 { - let (path, _file) = rotate(&dir).expect("rotate"); + let LogFile { path, file: _file, owner: _owner } = rotate(&dir).expect("rotate"); assert_eq!(path, dir.join(LOG_FILE)); assert_eq!(std::fs::read_to_string(&path).expect("read"), ""); std::fs::write(&path, format!("run {run}")).expect("write"); @@ -330,6 +435,66 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// #6432: a second launch moved the running instance's live log to `.1.log`, a third to + /// `.2.log`, and a fourth deleted it. + #[test] + fn a_second_start_leaves_the_running_instance_log_alone() { + let _spawns = crate::no_child_spawns(); + let dir = temp_dir("second"); + let mut first = rotate(&dir).expect("first start"); + assert_eq!(first.path, dir.join(LOG_FILE)); + first.file.write_all(b"first, before\n").expect("write"); + for _ in 0..KEEP + 1 { + let second = rotate(&dir).expect("second start"); + assert_eq!(second.path, instance_log(&dir, std::process::id())); + assert_eq!(read(&second.path), ""); + } + first.file.write_all(b"first, after\n").expect("write"); + assert_eq!(read(&dir.join(LOG_FILE)), "first, before\nfirst, after\n"); + assert!(!dir.join("photocraft.1.log").exists(), "the running instance's log was rotated"); + // Once the first instance is gone, the next start rotates as before. + drop(first); + let third = rotate(&dir).expect("third start"); + assert_eq!(third.path, dir.join(LOG_FILE)); + assert_eq!(read(&dir.join("photocraft.1.log")), "first, before\nfirst, after\n"); + drop(third); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn instance_logs_are_pruned_only_when_no_one_holds_them() { + let _spawns = crate::no_child_spawns(); + let dir = temp_dir("prune"); + let first = rotate(&dir).expect("first start"); + // Earlier side-by-side runs that have exited, oldest first; the oldest has no lock file + // (as if its lock file had been removed), the others an unlocked one. + let now = SystemTime::now(); + for (age, pid) in [(400u64, 1u32), (300, 2), (200, 3), (100, 4)] { + let path = instance_log(&dir, pid); + std::fs::write(&path, format!("run {pid}")).expect("write"); + File::options().write(true).open(&path).expect("open").set_modified(now - Duration::from_secs(age)).expect("mtime"); + if pid != 1 { + std::fs::write(instance_lock(&dir, pid), "").expect("lock file"); + } + } + // One older still running: its log is never removed, however old. + let live = instance_log(&dir, 5); + std::fs::write(&live, "live").expect("write"); + File::options().write(true).open(&live).expect("open").set_modified(now - Duration::from_secs(900)).expect("mtime"); + let held = File::create(instance_lock(&dir, 5)).expect("lock file"); + held.try_lock().expect("hold"); + + let second = rotate(&dir).expect("second start"); + assert_eq!(second.path, instance_log(&dir, std::process::id())); + // The newest KEEP finished ones stay, the rest go with their lock files. + assert!(instance_log(&dir, 4).exists() && instance_log(&dir, 3).exists()); + assert!(!instance_log(&dir, 2).exists() && !instance_log(&dir, 1).exists()); + assert!(!instance_lock(&dir, 2).exists()); + assert_eq!(read(&live), "live"); + drop((first, second, held)); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() { let dir = temp_dir("blocked"); @@ -355,7 +520,7 @@ mod tests { #[test] fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() { let dir = temp_dir("pending"); - let (path, file) = rotate(&dir).expect("rotate"); + let LogFile { path, file, .. } = rotate(&dir).expect("rotate"); let mut sink = Sink::new(MAX_FILE_BYTES); sink.write("early 1\n"); sink.write("early 2\n"); @@ -368,7 +533,7 @@ mod tests { #[test] fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() { let dir = temp_dir("bounded"); - let (path, file) = rotate(&dir).expect("rotate"); + let LogFile { path, file, .. } = rotate(&dir).expect("rotate"); let mut sink = Sink::new(MAX_FILE_BYTES); for i in 0..MAX_PENDING + 5 { sink.write(&format!("line {i}\n")); @@ -384,7 +549,7 @@ mod tests { #[test] fn the_file_stops_at_its_size_cap_with_one_note() { let dir = temp_dir("cap"); - let (path, file) = rotate(&dir).expect("rotate"); + let LogFile { path, file, .. } = rotate(&dir).expect("rotate"); let mut sink = Sink::new(100); sink.attach(file); for i in 0..50 { diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index c0f93bd319..b0b00a865c 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -1,9 +1,14 @@ -//! Photocraft desktop app. +//! PhotoCraft desktop app. //! //! Usage: `photocraft [--control ] [--control-token <64-hex> | //! --control-token-file ] [--automation-read-root ] //! [--automation-write-root ] [--safe-gpu] [--in-window-menus] [--present-mode ] -//! [--frame-latency ] [--stroke-trace ] [--new-instance] [files…]` +//! [--frame-latency ] [--stroke-trace ] [--new-instance] [--] [files…]` +//! (`photocraft --help` prints [`USAGE`]; `--version` prints the version). +//! +//! Any other argument starting with `-` is a usage error (exit status 2, issue #6431), so a typo +//! such as `--safegpu` doesn't open the window and then fail to open the flag as a file. A file +//! whose name starts with `-` goes after `--`. //! //! On Windows and Linux a launch hands its files to the PhotoCraft that is already running (new //! tabs in its window) and exits; `--new-instance` starts a separate copy instead, as does any @@ -58,6 +63,9 @@ mod photoshop_settings; #[cfg(target_os = "linux")] mod portal_save; mod presentation; +// The print portal needs the session bus (zbus, Linux only); its pure helpers are tested everywhere. +#[cfg(any(target_os = "linux", test))] +mod print_portal; mod screen_color; mod services; // macOS gets one instance from LaunchServices (open-documents Apple events). @@ -149,21 +157,188 @@ fn parse_control_port(value: &str, source: &str) -> Result { value.trim().parse().map_err(|_| format!("{source}: `{value}` is not a valid port (expected a number from 0 to 65535)")) } -/// Process exit status for the collected `--control` / `PHOTOCRAFT_CONTROL_PORT` errors: `None` -/// when there are none, else 2 (a command-line usage error), never 0. -fn control_args_exit_code(errors: &[String]) -> Option { +/// Process exit status for the collected usage errors (a bad `--control` / +/// `PHOTOCRAFT_CONTROL_PORT`, an unknown option): `None` when there are none, else 2 (a +/// command-line usage error), never 0. +fn usage_exit_code(errors: &[String]) -> Option { if errors.is_empty() { None } else { Some(2) } } +/// `photocraft --help`. Keep in step with the options `main` accepts and the module docs. +const USAGE: &str = "\ +Usage: photocraft [options] [--] [files…] + +Opens PhotoCraft with the given files. + +Options: + -h, --help Print this help and exit + --version Print the version, commit and build date and exit + --safe-gpu Start with the CPU renderer for this launch (after a graphics driver crash) + --in-window-menus macOS: keep the menus inside the window instead of the menu bar + --new-instance Windows and Linux: start a separate PhotoCraft instead of opening + the files in the one already running + --present-mode How frames reach the display: fifo, autovsync or novsync + --frame-latency Frames queued for the display: 1 to 3 + --stroke-trace + Time each brush stroke's frames + --control Start the localhost JSON-lines control server on this port + --control-token <64-hex> Control server token (default: a new random one, printed) + --control-token-file Read the control server token from this file, or create it + with a new one + --automation-read-root Directory the control server may read files from + --automation-write-root + Directory the control server may write files to + -- Treat every later argument as a file, even one starting with `-` + +A bad --present-mode, --frame-latency or --stroke-trace value is reported and ignored. +Environment: PHOTOCRAFT_CONTROL_PORT, PHOTOCRAFT_CONTROL_TOKEN, PHOTOCRAFT_CONTROL_TOKEN_FILE, +PHOTOCRAFT_AUTOMATION_READ_ROOT, PHOTOCRAFT_AUTOMATION_WRITE_ROOT, PHOTOCRAFT_PRESENT_MODE, +PHOTOCRAFT_FRAME_LATENCY, PHOTOCRAFT_STROKE_TRACE, PHOTOCRAFT_IN_WINDOW_MENUS, PHOTOCRAFT_NEW_INSTANCE, +PHOTOCRAFT_CONFIG_DIR. +"; + +/// Print to standard output for `--help` / `--version`. Unlike `println!`, never panics when +/// stdout is closed or a pipe (`photocraft --help | head -1`). +fn print_stdout(text: &str) { + use std::io::Write as _; + let mut out = std::io::stdout().lock(); + let _ = out.write_all(text.as_bytes()).and_then(|()| out.flush()); +} + +/// Everything the desktop launcher takes from the command line, on top of the environment +/// defaults handed in to `parse_launch_args`. +#[derive(Debug, Default, PartialEq, Eq)] +struct LaunchArgs { + control_port: Option, + control_token: Option, + control_token_file: Option, + automation_read_root: Option, + automation_write_root: Option, + files: Vec, + /// Arguments that are not valid Unicode (issue #1108): a file manager can hand over a Latin-1 + /// file name on Linux, and `std::env::args()` would panic before any window opened. Paths are + /// reported in a notice once the app is up; a control token is a usage error like a bad port. + unreadable_paths: Vec, + safe_gpu: bool, + new_instance: bool, + /// Options that apply only to the process they're given to; a launch with any keeps its own. + launch_options: Vec<&'static str>, + present_mode_arg: Option, + frame_latency_arg: Option, + stroke_trace_arg: Option, + in_window_menus: bool, + /// `--help` / `-h`: print [`USAGE`] and exit 0; parsing stops there. + help: bool, + /// `--version`: print the version and exit 0; parsing stops there. + version: bool, + /// Usage errors (a bad or missing control/automation value, an unknown option); a non-empty + /// list fails the launch with exit status 2 (issues #701, #6429, #6431). + errors: Vec, +} + +/// Parse the desktop launch arguments over the environment defaults in `out`. A control or +/// automation flag with no value is a usage error naming the flag (issue #6429), never a silent +/// fall back to a generated token or to no root: like `--control` with a bad port, it exits 2. +/// So is an unknown option (#6431); a file whose name starts with `-` goes after `--`. +fn parse_launch_args(args: impl Iterator, mut out: LaunchArgs) -> LaunchArgs { + let mut args = args; + // After `--`, every argument is a file, even one that starts with `-`. + let mut only_files = false; + while let Some(a) = args.next() { + if only_files { + match a.into_string() { + Ok(s) => out.files.push(s), + Err(raw) => out.unreadable_paths.push(raw.to_string_lossy().into_owned()), + } + continue; + } + match a.to_str() { + Some("--") => only_files = true, + Some("--help" | "-h") => { + out.help = true; + break; + } + Some("--control") => match args.next() { + Some(value) => match parse_control_port(&value.to_string_lossy(), "--control") { + Ok(port) => out.control_port = Some(port), + Err(error) => out.errors.push(error), + }, + None => out.errors.push("--control: missing port value (expected `--control `)".to_string()), + }, + Some("--control-token") => match args.next().map(std::ffi::OsString::into_string) { + Some(Ok(token)) => out.control_token = Some(token), + Some(Err(raw)) => out.errors.push(format!("--control-token: value is not valid Unicode (`{}`)", raw.to_string_lossy())), + None => out.errors.push("--control-token: missing token value (expected `--control-token `)".to_string()), + }, + Some("--control-token-file") => match args.next() { + Some(value) => out.control_token_file = Some(std::path::PathBuf::from(value)), + None => out.errors.push("--control-token-file: missing file path value (expected `--control-token-file `)".to_string()), + }, + Some("--automation-read-root") => { + out.launch_options.push("--automation-read-root"); + match args.next() { + Some(value) => out.automation_read_root = Some(std::path::PathBuf::from(value)), + None => out.errors.push("--automation-read-root: missing directory value (expected `--automation-read-root `)".to_string()), + } + } + Some("--automation-write-root") => { + out.launch_options.push("--automation-write-root"); + match args.next() { + Some(value) => out.automation_write_root = Some(std::path::PathBuf::from(value)), + None => out.errors.push("--automation-write-root: missing directory value (expected `--automation-write-root `)".to_string()), + } + } + Some("--safe-gpu") => { + out.launch_options.push("--safe-gpu"); + out.safe_gpu = true; + } + Some(flag @ ("--present-mode" | "--frame-latency" | "--stroke-trace")) => { + out.launch_options.push(match flag { + "--present-mode" => "--present-mode", + "--frame-latency" => "--frame-latency", + _ => "--stroke-trace", + }); + let flag = flag.to_string(); + match args.next().map(std::ffi::OsString::into_string) { + Some(Ok(v)) => match flag.as_str() { + "--present-mode" => out.present_mode_arg = Some(v), + "--frame-latency" => out.frame_latency_arg = Some(v), + _ => out.stroke_trace_arg = Some(v), + }, + // A bad value is reported and ignored; it never fails the launch. + _ => eprintln!("photocraft: {flag}: missing or unreadable value; ignored"), + } + } + Some("--in-window-menus") => { + out.launch_options.push("--in-window-menus"); + out.in_window_menus = true; + } + Some("--new-instance") => out.new_instance = true, + Some("--version") => { + out.version = true; + break; + } + // Old macOS passes a process serial number when launched from Finder. + Some(s) if s.starts_with("-psn_") => {} + // A typo such as `--safegpu`, or `--help` spelt another way, must not open the window + // and then fail to open the flag as a file (#6431). + Some(s) if s.starts_with('-') => out.errors.push(format!("unknown option `{s}` (put `--` before a file name that starts with `-`)")), + Some(s) => out.files.push(s.to_owned()), + None => out.unreadable_paths.push(a.to_string_lossy().into_owned()), + } + } + out +} + #[cfg(test)] mod control_port_tests { - use super::{control_args_exit_code, parse_control_port}; + use super::{parse_control_port, usage_exit_code}; #[test] fn control_port_errors_exit_non_zero() { - assert_eq!(control_args_exit_code(&[]), None); + assert_eq!(usage_exit_code(&[]), None); let errors = vec![parse_control_port("nope", "--control").unwrap_err()]; - assert_eq!(control_args_exit_code(&errors), Some(2)); + assert_eq!(usage_exit_code(&errors), Some(2)); } #[test] @@ -184,105 +359,152 @@ mod control_port_tests { } } +#[cfg(test)] +mod launch_args_tests { + use super::{LaunchArgs, parse_launch_args, usage_exit_code}; + use std::ffi::OsString; + + fn parse(values: &[&str]) -> LaunchArgs { + parse_launch_args(values.iter().map(OsString::from), LaunchArgs::default()) + } + + #[test] + fn flags_without_a_value_are_usage_errors() { + // Issue #6429: a missing value must fail the launch, not silently fall back to a + // generated token or to no root. + for flag in ["--control", "--control-token", "--control-token-file", "--automation-read-root", "--automation-write-root"] { + let parsed = parse(&[flag]); + assert_eq!(parsed.errors.len(), 1, "{flag}: {:?}", parsed.errors); + assert!(parsed.errors[0].starts_with(flag), "{}", parsed.errors[0]); + assert!(parsed.errors[0].contains("missing"), "{}", parsed.errors[0]); + assert_eq!(usage_exit_code(&parsed.errors), Some(2)); + } + } + + #[test] + fn missing_value_does_not_clear_an_environment_default() { + // `--automation-read-root` with no value must not drop a root set through the env var. + let defaults = LaunchArgs { automation_read_root: Some("/env/read".into()), automation_write_root: Some("/env/write".into()), ..Default::default() }; + let parsed = parse_launch_args(["--automation-read-root"].iter().map(OsString::from), defaults); + assert_eq!(parsed.automation_read_root.as_deref(), Some(std::path::Path::new("/env/read"))); + assert_eq!(parsed.automation_write_root.as_deref(), Some(std::path::Path::new("/env/write"))); + assert_eq!(parsed.errors.len(), 1, "{:?}", parsed.errors); + } + + #[test] + fn values_are_parsed_and_no_errors_remain() { + let parsed = parse(&[ + "--control", + "50494", + "--control-token", + "abcd", + "--control-token-file", + "/tmp/token", + "--automation-read-root", + "/r", + "--automation-write-root", + "/w", + "--safe-gpu", + "--in-window-menus", + "--new-instance", + "--present-mode", + "mailbox", + "photo.psd", + ]); + assert!(parsed.errors.is_empty(), "{:?}", parsed.errors); + assert_eq!(parsed.control_port, Some(50494)); + assert_eq!(parsed.control_token.as_deref(), Some("abcd")); + assert_eq!(parsed.control_token_file.as_deref(), Some(std::path::Path::new("/tmp/token"))); + assert_eq!(parsed.automation_read_root.as_deref(), Some(std::path::Path::new("/r"))); + assert_eq!(parsed.automation_write_root.as_deref(), Some(std::path::Path::new("/w"))); + assert!(parsed.safe_gpu); + assert!(parsed.in_window_menus); + assert!(parsed.new_instance); + assert_eq!(parsed.present_mode_arg.as_deref(), Some("mailbox")); + assert_eq!(parsed.launch_options, vec!["--automation-read-root", "--automation-write-root", "--safe-gpu", "--in-window-menus", "--present-mode"]); + assert_eq!(parsed.files, vec!["photo.psd".to_string()]); + } + + #[test] + fn version_stops_parsing() { + let parsed = parse(&["--version", "--control"]); + assert!(parsed.version); + assert!(parsed.errors.is_empty(), "{:?}", parsed.errors); + } + + #[test] + fn help_stops_parsing_and_double_dash_ends_options() { + let parsed = parse(&["-h", "--safegpu", "--control"]); + assert!(parsed.help); + assert!(parsed.errors.is_empty(), "{:?}", parsed.errors); + + let parsed = parse(&["--safegpu", "--", "--help", "-x"]); + assert!(!parsed.help); + assert_eq!(parsed.errors.len(), 1, "{:?}", parsed.errors); + assert!(parsed.errors[0].contains("unknown option `--safegpu`"), "{}", parsed.errors[0]); + assert_eq!(parsed.files, vec!["--help".to_string(), "-x".to_string()]); + } +} + fn main() -> eframe::Result { // First, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); crash_guard::install_hook(); // The system font scan can take seconds (minutes on some Macs): run it off the UI thread. photocraft_ui_egui::type_tool::warm_fonts(); - let mut control_port: Option = None; - let mut control_arg_errors: Vec = Vec::new(); + let mut launch = LaunchArgs { + automation_read_root: std::env::var_os("PHOTOCRAFT_AUTOMATION_READ_ROOT").map(std::path::PathBuf::from), + automation_write_root: std::env::var_os("PHOTOCRAFT_AUTOMATION_WRITE_ROOT").map(std::path::PathBuf::from), + in_window_menus: std::env::var_os("PHOTOCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0"), + ..Default::default() + }; if let Some(value) = std::env::var("PHOTOCRAFT_CONTROL_PORT").ok().filter(|v| !v.trim().is_empty()) { match parse_control_port(&value, "PHOTOCRAFT_CONTROL_PORT") { - Ok(port) => control_port = Some(port), - Err(error) => control_arg_errors.push(error), + Ok(port) => launch.control_port = Some(port), + Err(error) => launch.errors.push(error), } } - let mut control_token = None; - let mut control_token_file = None; - let mut automation_read_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_READ_ROOT").map(std::path::PathBuf::from); - let mut automation_write_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_WRITE_ROOT").map(std::path::PathBuf::from); - let mut files = Vec::new(); - // Arguments that are not valid Unicode (issue #1108): a file manager can hand over a Latin-1 - // file name on Linux, and `std::env::args()` would panic before any window opened. Paths are - // reported in a notice once the app is up; a control token is a usage error like a bad port. - let mut unreadable_paths: Vec = Vec::new(); - let mut safe_gpu = false; - let mut new_instance = false; - // Options that apply only to the process they're given to; a launch with any keeps its own. - let mut launch_options: Vec<&'static str> = Vec::new(); - let (mut present_mode_arg, mut frame_latency_arg, mut stroke_trace_arg): (Option, Option, Option) = (None, None, None); - let mut in_window_menus = std::env::var_os("PHOTOCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0"); - let mut args = std::env::args_os().skip(1); - while let Some(a) = args.next() { - match a.to_str() { - Some("--control") => match args.next() { - Some(value) => match parse_control_port(&value.to_string_lossy(), "--control") { - Ok(port) => control_port = Some(port), - Err(error) => control_arg_errors.push(error), - }, - None => control_arg_errors.push("--control: missing port value (expected `--control `)".to_string()), - }, - Some("--control-token") => match args.next().map(std::ffi::OsString::into_string) { - Some(Ok(token)) => control_token = Some(token), - Some(Err(raw)) => control_arg_errors.push(format!("--control-token: value is not valid Unicode (`{}`)", raw.to_string_lossy())), - None => control_token = None, - }, - Some("--control-token-file") => control_token_file = args.next().map(std::path::PathBuf::from), - Some("--automation-read-root") => { - launch_options.push("--automation-read-root"); - automation_read_root = args.next().map(std::path::PathBuf::from); - } - Some("--automation-write-root") => { - launch_options.push("--automation-write-root"); - automation_write_root = args.next().map(std::path::PathBuf::from); - } - Some("--safe-gpu") => { - launch_options.push("--safe-gpu"); - safe_gpu = true; - } - Some(flag @ ("--present-mode" | "--frame-latency" | "--stroke-trace")) => { - launch_options.push(match flag { - "--present-mode" => "--present-mode", - "--frame-latency" => "--frame-latency", - _ => "--stroke-trace", - }); - let flag = flag.to_string(); - match args.next().map(std::ffi::OsString::into_string) { - Some(Ok(v)) => match flag.as_str() { - "--present-mode" => present_mode_arg = Some(v), - "--frame-latency" => frame_latency_arg = Some(v), - _ => stroke_trace_arg = Some(v), - }, - // A bad value is reported and ignored; it never fails the launch. - _ => eprintln!("photocraft: {flag}: missing or unreadable value; ignored"), - } - } - Some("--in-window-menus") => { - launch_options.push("--in-window-menus"); - in_window_menus = true; - } - Some("--new-instance") => new_instance = true, - Some("--version") => { - println!("photocraft {}", photocraft_engine::build_info::long_version()); - return Ok(()); - } - // Old macOS passes a process serial number when launched from Finder. - Some(s) if s.starts_with("-psn_") => {} - Some(s) => files.push(s.to_owned()), - None => unreadable_paths.push(a.to_string_lossy().into_owned()), - } + launch = parse_launch_args(std::env::args_os().skip(1), launch); + if launch.help { + print_stdout(USAGE); + return Ok(()); + } + if launch.version { + print_stdout(&format!("photocraft {}\n", photocraft_engine::build_info::long_version())); + return Ok(()); } - // A malformed control port must not silently drop the control server (issue #701): name the - // bad value and fail the launch, like `photocraft-cli serve --port` does for the same typo. - // Exit status 2 is the usual command-line usage error, so a launcher sees the failure. - if let Some(code) = control_args_exit_code(&control_arg_errors) { - for error in &control_arg_errors { + // A malformed control port must not silently drop the control server (issue #701), a control + // or automation flag without its value must not silently fall back to a generated token or + // to no root (issue #6429), and an unknown option must not open the window (#6431): name the + // bad argument and fail the launch, like `photocraft-cli` does for the same typos. Exit + // status 2 is the usual command-line usage error, so a launcher sees the failure. + if let Some(code) = usage_exit_code(&launch.errors) { + for error in &launch.errors { eprintln!("photocraft: {error}"); } + eprintln!("Run `photocraft --help` for usage."); std::process::exit(code); } + let LaunchArgs { + control_port, + control_token, + control_token_file, + automation_read_root, + automation_write_root, + files, + unreadable_paths, + safe_gpu, + new_instance, + launch_options, + present_mode_arg, + frame_latency_arg, + stroke_trace_arg, + in_window_menus, + help: _, + version: _, + errors: _, + } = launch; // The log file lives under the settings directory; opened after the arguments, so `--version` // and usage errors leave no file behind. Records logged until now are written to it first. @@ -499,7 +721,15 @@ fn main() -> eframe::Result { services::xwayland_command(var("FLATPAK_ID").as_deref(), var("APPIMAGE").as_deref(), std::env::var_os("DISPLAY").is_some()); } } - let mut app = PhotocraftApp::new(Session::new(), services); + #[cfg(target_os = "linux")] + let session = { + let mut session = Session::new(); + session.print_spooler = print_portal::spooler(); + session + }; + #[cfg(not(target_os = "linux"))] + let session = Session::new(); + let mut app = PhotocraftApp::new(session, services); app.min_frame_ms = uncapped.then_some(1000.0 / 240.0); app.integrated_titlebar = cfg!(target_os = "macos"); app.custom_titlebar = custom_titlebar; @@ -690,6 +920,19 @@ fn main() -> eframe::Result { result } +/// Tests that spawn child processes hold this for reading, tests that check who holds a file lock +/// for writing ([`no_child_spawns`]): until its `exec`, a child holds a copy of every open file, +/// `flock`s included, so a spawn in another test could keep a lock this process just dropped held +/// for a moment. +#[cfg(test)] +pub(crate) static CHILD_SPAWNS: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +/// Held by a test that checks who holds a file lock: no other test spawns a child meanwhile. +#[cfg(test)] +pub(crate) fn no_child_spawns() -> std::sync::RwLockWriteGuard<'static, ()> { + CHILD_SPAWNS.write().unwrap_or_else(std::sync::PoisonError::into_inner) +} + #[cfg(test)] mod tests { #[test] diff --git a/apps/photocraft/src/monitor_profile.rs b/apps/photocraft/src/monitor_profile.rs index 8e33869696..c210e096ec 100644 --- a/apps/photocraft/src/monitor_profile.rs +++ b/apps/photocraft/src/monitor_profile.rs @@ -495,6 +495,7 @@ mod tests { #[cfg(unix)] #[test] fn a_hung_helper_is_stopped_and_big_replies_dont_block() { + let _spawns = crate::CHILD_SPAWNS.read().unwrap_or_else(std::sync::PoisonError::into_inner); let t0 = std::time::Instant::now(); let e = run_helper(std::process::Command::new("sleep").arg("30"), std::time::Duration::from_millis(300)).unwrap_err(); assert!(e.contains("took longer than"), "{e}"); diff --git a/apps/photocraft/src/portal_save/tests.rs b/apps/photocraft/src/portal_save/tests.rs index ed44a10d9c..5a839b6025 100644 --- a/apps/photocraft/src/portal_save/tests.rs +++ b/apps/photocraft/src/portal_save/tests.rs @@ -36,17 +36,22 @@ fn mock_portal(script: Script) -> Option<(zbus::blocking::Connection, Seen, std: /// once the user is done with it (here after 300 ms). fn mock_portal_with(script: Script, own_paths: bool) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> { use std::io::BufRead; + let spawns = crate::CHILD_SPAWNS.read().unwrap_or_else(std::sync::PoisonError::into_inner); let mut daemon = std::process::Command::new("dbus-daemon").args(["--session", "--nofork", "--print-address=1"]).stdout(std::process::Stdio::piped()).spawn().ok()?; + drop(spawns); let mut address = String::new(); std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?; let address = address.trim().to_string(); let server = zbus::blocking::connection::Builder::address(address.as_str()).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap(); let seen: Seen = Arc::default(); let log = seen.clone(); + // A stream only gets the messages that arrive after it exists: made in the thread, it could + // miss a `SaveFile` sent before the thread got going, and the call would wait forever. + let messages = zbus::blocking::MessageIterator::from(&server); std::thread::spawn(move || { let mut script = script.into_iter(); - for msg in zbus::blocking::MessageIterator::from(&server) { + for msg in messages { let Ok(msg) = msg else { break }; let header = msg.header(); if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("SaveFile") { diff --git a/apps/photocraft/src/print_portal.rs b/apps/photocraft/src/print_portal.rs new file mode 100644 index 0000000000..0eef02a01c --- /dev/null +++ b/apps/photocraft/src/print_portal.rs @@ -0,0 +1,239 @@ +//! Printing through the XDG Print portal (`org.freedesktop.portal.Print`): the system print +//! dialog, which a sandboxed app can reach without a CUPS socket. The engine prints over IPP +//! when it can reach a print server (`photocraft-ipp`); this is its fallback when it cannot, and +//! the only route with `PHOTOCRAFT_PRINT_PORTAL=1` (`0` disables it). `PreparePrint` shows the +//! dialog seeded with the job's copies and paper; `Print` hands it the PDF. Both answer through a +//! `Request` object's `Response` signal, which this module waits for on its own thread so the +//! window keeps painting while the dialog is open; the outcome goes to the log. +//! https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Print.html + +#[cfg(target_os = "linux")] +use photocraft_engine::print_cmds::{PrintJob, Spooler}; + +/// The spooler to install on the session, unless `PHOTOCRAFT_PRINT_PORTAL=0`. The portal itself +/// is looked up per job, so a missing one costs nothing at start-up. +#[cfg(target_os = "linux")] +pub fn spooler() -> Option { + let setting = std::env::var("PHOTOCRAFT_PRINT_PORTAL").ok(); + if setting.as_deref() == Some("0") { + return None; + } + Some(Spooler { name: "portal", preferred: setting.as_deref() == Some("1"), run: std::sync::Arc::new(print) }) +} + +/// Opens the system print dialog for the job and returns as soon as it is up. +#[cfg(target_os = "linux")] +fn print(job: &PrintJob) -> Result { + let conn = zbus::blocking::connection::Builder::session() + .and_then(|b| b.method_timeout(std::time::Duration::from_secs(5)).build()) + .map_err(|e| format!("no session bus for the print portal ({e}); print to PDF instead"))?; + let proxy = portal(&conn)?; + let version: u32 = proxy.get_property("version").map_err(|e| format!("no print portal on this desktop ({e}); print to PDF instead"))?; + // The document goes to a private temporary file (0600, created atomically by `tempfile`), + // not a guessable name in a shared /tmp. The guard owns the file: it lives on the portal + // thread until the dialog is done, and a failure to start that thread drops it here. + let mut file = tempfile::Builder::new().prefix("photocraft-print-").suffix(".pdf").tempfile().map_err(|e| format!("cannot create the print file: {e}"))?; + std::io::Write::write_all(&mut file, &job.pdf).map_err(|e| format!("cannot write the print file: {e}"))?; + let (title, settings, page_setup) = (job.title.clone(), settings(job), page_setup(job)); + std::thread::Builder::new() + .name("print-portal".into()) + .spawn(move || { + let outcome = dialog(&conn, &title, &settings, &page_setup, file.path()); + drop(file); + match outcome { + Ok(what) => log::info!("print portal (v{version}): {what}"), + Err(e) => log::warn!("print portal (v{version}): {e}"), + } + }) + .map_err(|e| format!("cannot start the print thread: {e}"))?; + Ok("the system print dialog".into()) +} + +#[cfg(target_os = "linux")] +fn portal(conn: &zbus::blocking::Connection) -> Result, String> { + zbus::blocking::Proxy::new(conn, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Print") + .map_err(|e| e.to_string()) +} + +/// `PreparePrint` then `Print`, each waited for on its request's `Response` signal. +#[cfg(target_os = "linux")] +fn dialog( + conn: &zbus::blocking::Connection, + title: &str, + settings: &[(&'static str, Seed)], + page_setup: &[(&'static str, Seed)], + pdf: &std::path::Path, +) -> Result { + use std::collections::HashMap; + use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value}; + type Dict<'a> = HashMap<&'a str, Value<'a>>; + fn as_dict(pairs: &[(&'static str, Seed)]) -> Dict<'static> { + pairs + .iter() + .map(|(k, v)| { + let value = match v { + Seed::Text(t) => Value::from(t.clone()), + Seed::Mm(mm) => Value::from(*mm), + }; + (*k, value) + }) + .collect() + } + let proxy = portal(conn)?; + let sender = conn.unique_name().map(|n| n.as_str().to_string()).ok_or("the bus connection has no name")?; + let wait = |token: &str| -> Result, String> { + let path = request_path(&sender, token); + let request = zbus::blocking::Proxy::new(conn, "org.freedesktop.portal.Desktop", path, "org.freedesktop.portal.Request").map_err(|e| e.to_string())?; + request.receive_signal("Response").map_err(|e| e.to_string()) + }; + let response = |mut signals: zbus::blocking::proxy::SignalIterator<'static>| -> Result, String> { + let message = signals.next().ok_or("the print portal went away")?; + let (code, results): (u32, HashMap) = message.body().deserialize().map_err(|e| format!("odd portal reply: {e}"))?; + match code { + 0 => Ok(results), + 1 => Err("cancelled in the print dialog".into()), + _ => Err("the print dialog failed".into()), + } + }; + + let token = format!("photocraft_prepare_{}", nonce()); + let signals = wait(&token)?; + let mut options: Dict<'_> = HashMap::new(); + options.insert("handle_token", Value::from(token.as_str())); + let _: OwnedObjectPath = + proxy.call("PreparePrint", &("", title, as_dict(settings), as_dict(page_setup), options)).map_err(|e| format!("PreparePrint failed: {e}"))?; + let results = response(signals)?; + let prepared = results.get("token").and_then(|v| u32::try_from(v.clone()).ok()).ok_or("the print dialog gave no token")?; + + let file = std::fs::File::open(pdf).map_err(|e| format!("cannot reopen the print file: {e}"))?; + let token = format!("photocraft_print_{}", nonce()); + let signals = wait(&token)?; + let mut options: Dict<'_> = HashMap::new(); + options.insert("handle_token", Value::from(token.as_str())); + options.insert("token", Value::from(prepared)); + let fd = zbus::zvariant::Fd::from(std::os::fd::AsFd::as_fd(&file)); + let _: OwnedObjectPath = proxy.call("Print", &("", title, fd, options)).map_err(|e| format!("Print failed: {e}"))?; + response(signals)?; + Ok("printed through the system print dialog".into()) +} + +#[cfg(target_os = "linux")] +fn nonce() -> u64 { + use std::sync::atomic::{AtomicU64, Ordering}; + static N: AtomicU64 = AtomicU64::new(0); + let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0); + t ^ N.fetch_add(1, Ordering::Relaxed) +} + +/// The request object the portal answers on: the sender's unique name without its colon and +/// with dots as underscores, then the handle token. +fn request_path(unique_name: &str, token: &str) -> String { + format!("/org/freedesktop/portal/desktop/request/{}/{token}", unique_name.trim_start_matches(':').replace('.', "_")) +} + +/// A value seeded into the dialog: GtkPrintSettings are strings; a GtkPageSetup's sizes are +/// doubles in millimetres (`gtk_paper_size_new_from_gvariant` ignores anything else). +#[derive(Debug, Clone, PartialEq)] +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +enum Seed { + Text(String), + Mm(f64), +} + +fn text(s: &str) -> Seed { + Seed::Text(s.to_string()) +} + +/// The standard paper sizes, as (PWG name, PPD name, width mm, height mm), portrait. GTK's +/// print settings take the PWG name; its page setup finds the size by the PPD name. +const PAPERS: [(&str, &str, f64, f64); 8] = [ + ("na_letter", "Letter", 215.9, 279.4), + ("na_legal", "Legal", 215.9, 355.6), + ("na_ledger", "Ledger", 279.4, 431.8), + ("iso_a3", "A3", 297.0, 420.0), + ("iso_a4", "A4", 210.0, 297.0), + ("iso_a5", "A5", 148.0, 210.0), + ("na_index-4x6", "4x6", 101.6, 152.4), + ("na_5x7", "5x7", 127.0, 177.8), +]; + +const MM_PER_PT: f64 = 25.4 / 72.0; + +type Paper = (&'static str, &'static str, f64, f64); + +/// The job's paper: its row in `PAPERS` when it is a standard size, and the portrait size in +/// millimetres. +fn paper(paper_pt: (f64, f64)) -> (Option<&'static Paper>, f64, f64) { + let (w, h) = (paper_pt.0.min(paper_pt.1) * MM_PER_PT, paper_pt.0.max(paper_pt.1) * MM_PER_PT); + let row = PAPERS.iter().find(|(_, _, pw, ph)| (pw - w).abs() < 1.0 && (ph - h).abs() < 1.0); + (row, w, h) +} + +fn orientation(landscape: bool) -> Seed { + text(if landscape { "landscape" } else { "portrait" }) +} + +/// `PreparePrint`'s settings (GtkPrintSettings keys, string values). +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn settings_for(copies: u32, paper_pt: (f64, f64), landscape: bool) -> Vec<(&'static str, Seed)> { + let (row, w, h) = paper(paper_pt); + let mut v = vec![("n-copies", text(&copies.to_string())), ("orientation", orientation(landscape))]; + match row { + Some((pwg, _, _, _)) => v.push(("paper-format", text(pwg))), + None => v.extend([("paper-width", text(&format!("{w:.2}"))), ("paper-height", text(&format!("{h:.2}")))]), + } + v +} + +/// `PreparePrint`'s page setup (GtkPageSetup keys): the size in millimetres, found by its PPD +/// name when it has one, else a custom size named by its dimensions. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn page_setup_for(paper_pt: (f64, f64), landscape: bool) -> Vec<(&'static str, Seed)> { + let (row, w, h) = paper(paper_pt); + let mut v = vec![("Orientation", orientation(landscape)), ("Width", Seed::Mm(w)), ("Height", Seed::Mm(h))]; + match row { + Some((_, ppd, _, _)) => v.push(("PPDName", text(ppd))), + None => v.push(("Name", text(&format!("custom_{w:.0}x{h:.0}mm")))), + } + v +} + +#[cfg(target_os = "linux")] +fn settings(job: &PrintJob) -> Vec<(&'static str, Seed)> { + settings_for(job.copies, job.paper, job.landscape) +} + +#[cfg(target_os = "linux")] +fn page_setup(job: &PrintJob) -> Vec<(&'static str, Seed)> { + page_setup_for(job.paper, job.landscape) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn request_path_follows_the_portal_rule() { + assert_eq!(request_path(":1.42", "photocraft_prepare_7"), "/org/freedesktop/portal/desktop/request/1_42/photocraft_prepare_7"); + } + + #[test] + fn standard_papers_get_their_pwg_and_ppd_names_and_custom_ones_their_size() { + // A4 landscape as the engine lays it out: width > height, still A4. + let s = settings_for(2, (841.89, 595.28), true); + assert_eq!(s, vec![("n-copies", text("2")), ("orientation", text("landscape")), ("paper-format", text("iso_a4"))]); + let p = page_setup_for((841.89, 595.28), true); + assert_eq!(p[0], ("Orientation", text("landscape"))); + let Seed::Mm(w) = p[1].1 else { panic!("width is millimetres") }; + let Seed::Mm(h) = p[2].1 else { panic!("height is millimetres") }; + assert!((w - 210.0).abs() < 0.01 && (h - 297.0).abs() < 0.01, "{w} x {h}"); + assert_eq!(p[3], ("PPDName", text("A4"))); + assert_eq!(settings_for(1, (612.0, 792.0), false)[2], ("paper-format", text("na_letter"))); + assert_eq!(page_setup_for((612.0, 792.0), false)[3], ("PPDName", text("Letter"))); + assert_eq!(settings_for(1, (288.0, 432.0), false)[2], ("paper-format", text("na_index-4x6"))); + // 100 x 200 mm is nobody's standard. + let custom = settings_for(1, (283.46, 566.93), false); + assert_eq!(&custom[2..], &[("paper-width", text("100.00")), ("paper-height", text("200.00"))]); + assert_eq!(page_setup_for((283.46, 566.93), false)[3], ("Name", text("custom_100x200mm"))); + } +} diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 6c34fda33a..437f5cee12 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -6,7 +6,7 @@ use photocraft_doc::{Document, Layer, Size}; use photocraft_format::RecoveryStore; use photocraft_geom::Rect; use photocraft_ui_egui::{FileDialogAnswer, FileDialogReply, FileDialogRequest, Recoverable, Services}; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::future::Future; use std::path::{Path, PathBuf}; use std::pin::Pin; @@ -36,16 +36,47 @@ fn open_filter_extensions(extensions: &[&str]) -> Vec { extensions.iter().map(|ext| if case_sensitive_globs { ext.chars().map(class).collect() } else { ext.to_string() }).collect() } -/// An explicit SVG filter keeps vector artwork discoverable even when a native picker defaults to -/// the PhotoCraft-only filter. SVG is also included in All Formats for normal multi-format opens. +/// File › Open's file types after All Formats, as Photoshop lists them: one per format, so a folder +/// of mixed files can be narrowed to one kind (#6337). Together they cover every extension of +/// [`OPEN_EXTS`]. An explicit SVG filter also keeps vector artwork discoverable when a native +/// picker defaults to another filter. +const OPEN_FILTERS: &[(&str, &[&str])] = &[ + ("PhotoCraft", &["pcraft"]), + ("Photoshop", &["psd", "psb", "psdt"]), + ("Affinity", &["af", "afdesign", "afphoto", "afpub"]), + ("Krita", &["kra", "krz"]), + ("OpenRaster", &["ora"]), + ("Paint.NET", &["pdn"]), + ("SVG", SVG_EXTS), + ("PNG", &["png"]), + ("JPEG", &["jpg", "jpeg"]), + ("HEIF", &["heic", "heif", "hif"]), + ("TIFF", &["tif", "tiff"]), + ("WebP", &["webp"]), + ("GIF", &["gif"]), + ("BMP", &["bmp"]), + ("Targa", &["tga"]), + ("ICO", &["ico"]), + ("QOI", &["qoi"]), + ("PCX", &["pcx"]), + ("DDS", &["dds"]), + ("XPM", &["xpm"]), + ("Portable Bitmap", &["pbm", "pgm", "ppm", "pam", "pfm"]), + ("OpenEXR", &["exr"]), + ("Radiance HDR", &["hdr"]), + ("FITS", &["fits", "fit", "fts"]), + ("DPX and Cineon", &["dpx", "cin"]), + ("Camera Raw", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]), + ("Brushes", &["abr"]), + ("Gradients", &["grd"]), + ("Swatches", &["aco", "ase"]), + ("Keyboard Shortcuts", &["kys"]), +]; + fn open_filters() -> Vec<(&'static str, Vec)> { - vec![ - ("All Formats", open_filter_extensions(OPEN_EXTS)), - ("PhotoCraft", open_filter_extensions(&["pcraft"])), - ("OpenRaster", open_filter_extensions(&["ora"])), - ("Krita", open_filter_extensions(&["kra", "krz"])), - ("SVG", open_filter_extensions(SVG_EXTS)), - ] + std::iter::once(("All Formats", open_filter_extensions(OPEN_EXTS))) + .chain(OPEN_FILTERS.iter().map(|(name, exts)| (*name, open_filter_extensions(exts)))) + .collect() } /// File › Save As formats: (filter name, extensions). The filter matching the suggested name's @@ -68,6 +99,8 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ ("OpenEXR", &["exr"]), ("FITS", &["fits", "fit"]), ("DPX", &["dpx"]), + // Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327). + ("DDS", &["dds"]), ]; /// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog @@ -160,10 +193,7 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>, let dialog = if let Some(exts) = extensions { dialog.add_filter("Supported Files", &open_filter_extensions(&exts.iter().map(String::as_str).collect::>())) } else { - open_filters() - .into_iter() - .fold(dialog, |dialog, (name, extensions)| dialog.add_filter(name, &extensions)) - .add_filter("Paint.NET", &open_filter_extensions(&["pdn"])) + open_filters().into_iter().fold(dialog, |dialog, (name, extensions)| dialog.add_filter(name, &extensions)) }; if multiple { let picked = dialog.pick_files(); @@ -264,8 +294,8 @@ fn block_on(future: impl Future) -> T { } /// Per-user settings directory: `PHOTOCRAFT_CONFIG_DIR`, else `/PhotoCraftData` in -/// portable mode, else the platform convention. Everything the app persists lives under it; see -/// [`crate::app_dirs`]. +/// portable mode, else the platform convention. Everything the app persists lives under it +/// except, on Windows and Linux, crash-recovery autosaves; see [`crate::app_dirs`]. pub fn config_dir() -> Option { crate::app_dirs::config_dir() } @@ -280,8 +310,11 @@ pub fn presets_dir() -> Option { config_dir().map(|d| d.join("Presets")) } +/// Crash-recovery autosaves: under the settings directory, except where that is synced with the +/// settings: the Windows roaming profile and the Linux config folder (see +/// [`crate::app_dirs::resolve_recovery`]). fn recovery_dir() -> Option { - config_dir().map(|d| d.join("Recovery")) + crate::app_dirs::recovery_dir() } /// Write `bytes` crash-safely (temp file beside the target, fsync, rename, directory fsync; see @@ -462,6 +495,7 @@ fn shell_word(s: &str) -> String { pub fn native(automation: Option) -> Services { let clip: Rc>> = Rc::default(); + let clip_unreadable: Rc> = Rc::default(); let automation_read = automation.clone().map(|workspace| { Box::new(move |path: &str| { let bytes = workspace.read(path).map_err(|error| error.to_string())?; @@ -504,6 +538,11 @@ pub fn native(automation: Option) -> save_file: Some(Arc::new(save_file)), file_dialog: Some(Box::new(show_file_dialog)), write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))), + file_stamp: Some(Box::new(|path: &str| { + // Follows a symlink, as Save writes through it to the file it points at. + let meta = std::fs::metadata(path).ok()?; + Some(photocraft_ui_egui::FileStamp { len: meta.len(), modified: meta.modified().ok() }) + })), automation_read, automation_write, automation_open_pcraft, @@ -530,11 +569,19 @@ pub fn native(automation: Option) -> }), clipboard_get_image: Some({ let clip = clip.clone(); + let unreadable = clip_unreadable.clone(); Box::new(move || { let mut slot = clip.try_borrow_mut().ok()?; let cb = match slot.as_mut() { Some(c) => c, - None => slot.insert(arboard::Clipboard::new().ok()?), + None => { + // arboard opens only when some backend works. In a Flatpak on Wayland none + // does (#5031): the sandbox hides the data-control protocol from it, and + // `--socket=fallback-x11` gives no X server while a compositor runs. + let opened = arboard::Clipboard::new(); + unreadable.set(opened.is_err()); + slot.insert(opened.ok()?) + } }; // Copied files first: Finder also puts the file's icon on the clipboard as an // image, which would otherwise paste instead of the file. @@ -550,6 +597,7 @@ pub fn native(automation: Option) -> None }) }), + clipboard_unreadable: Some(Box::new(move || clip_unreadable.get())), load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())), photoshop_shortcuts: Some(Box::new(|| crate::photoshop_settings::live_keyboard_shortcuts(&|k| std::env::var_os(k)))), save_prefs: Some(Box::new(|text: &str| write_atomic(&prefs_file().ok_or("no config directory")?, text.as_bytes()))), @@ -722,6 +770,26 @@ mod tests { assert!(svg_filter.iter().any(|glob| matches(glob, "svg")) && svg_filter.iter().any(|glob| matches(glob, "svgz"))); } + /// #6337: after All Formats, every format File › Open reads has its own filter, and no filter + /// offers an extension All Formats doesn't. + #[test] + fn every_open_format_has_its_own_filter() { + let filters = open_filters(); + assert_eq!(filters[0], ("All Formats", open_filter_extensions(OPEN_EXTS)), "All Formats comes first"); + let mut named: Vec<&str> = OPEN_FILTERS.iter().flat_map(|(_, exts)| exts.iter().copied()).collect(); + let total = named.len(); + named.sort_unstable(); + named.dedup(); + assert_eq!(named.len(), total, "an extension is listed under two filters"); + let mut all = OPEN_EXTS.to_vec(); + all.sort_unstable(); + assert_eq!(named, all, "the named filters cover All Formats exactly"); + let names: Vec<&str> = filters.iter().map(|(name, _)| *name).collect(); + for name in ["Photoshop", "Affinity", "HEIF", "PNG", "JPEG", "TIFF", "Portable Bitmap", "OpenEXR", "Radiance HDR", "Paint.NET"] { + assert!(names.contains(&name), "{name}"); + } + } + #[cfg(not(all(unix, not(target_os = "macos"))))] #[test] fn open_filters_keep_literal_extensions_on_windows_and_macos() { @@ -837,7 +905,7 @@ mod tests { assert!(format.caps().write, "{name}: .{ext} can't be written"); } } - for ext in ["ico", "gif", "bmp"] { + for ext in ["ico", "gif", "bmp", "dds"] { assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered"); } assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type"); diff --git a/apps/photocraft/tests/command_line_usage.rs b/apps/photocraft/tests/command_line_usage.rs new file mode 100644 index 0000000000..c4c745ea9a --- /dev/null +++ b/apps/photocraft/tests/command_line_usage.rs @@ -0,0 +1,95 @@ +//! `photocraft --help` and unknown options must not open the window (#6431): before the fix, +//! any argument the loop didn't know was taken as a file, so `--help` or a typo such as +//! `--safegpu` launched the GUI and logged "Couldn't open --help". +//! +//! These run the real binary, and every case must exit before the window opens: Windows and +//! macOS runners have a desktop, so a launch that gets that far hangs until the test times out. +//! Cases whose arguments are valid add a bad `--control` value, which fails the launch with the +//! other usage errors, so stderr shows whether those arguments were taken as unknown options. + +/// Run `photocraft` with `args` in an isolated config dir; return the exit +/// status, stdout and stderr. +fn run_photocraft(args: &[&str]) -> (std::process::ExitStatus, String, String) { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("photocraft-usage-{}-{n}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let output = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft")) + .args(args) + .env("PHOTOCRAFT_CONFIG_DIR", &dir) + .env_remove("PHOTOCRAFT_CONTROL_PORT") + .env_remove("DISPLAY") + .env_remove("WAYLAND_DISPLAY") + .env_remove("WAYLAND_SOCKET") + .output() + .expect("failed to run photocraft binary"); + std::fs::remove_dir_all(&dir).ok(); + (output.status, String::from_utf8_lossy(&output.stdout).into_owned(), String::from_utf8_lossy(&output.stderr).into_owned()) +} + +#[test] +fn help_prints_usage_and_exits_0() { + for flag in ["--help", "-h"] { + let (status, stdout, stderr) = run_photocraft(&[flag]); + assert_eq!(status.code(), Some(0), "{flag} must exit 0, stderr: {stderr}"); + assert!(stdout.starts_with("Usage: photocraft"), "{flag} stdout: {stdout}"); + for option in ["--safe-gpu", "--new-instance", "--control ", "--version", "--"] { + assert!(stdout.contains(option), "{flag} usage must list {option}: {stdout}"); + } + assert!(!stderr.contains("Couldn't open"), "{flag} was taken as a file: {stderr}"); + } +} + +#[test] +fn help_wins_over_later_arguments() { + let (status, stdout, _) = run_photocraft(&["--help", "picture.psd", "--safegpu"]); + assert_eq!(status.code(), Some(0)); + assert!(stdout.starts_with("Usage: photocraft"), "stdout: {stdout}"); +} + +#[test] +fn unknown_options_exit_2_naming_them() { + for flag in ["--safegpu", "-x", "--help=yes"] { + let (status, stdout, stderr) = run_photocraft(&[flag]); + assert_eq!(status.code(), Some(2), "{flag} must be a usage error, stderr: {stderr}"); + assert!(stderr.contains(&format!("unknown option `{flag}`")), "stderr: {stderr}"); + assert!(stderr.contains("photocraft --help"), "stderr should point at --help: {stderr}"); + assert!(stdout.is_empty(), "stdout: {stdout}"); + } +} + +#[test] +fn unknown_option_errors_are_reported_with_control_port_errors() { + let (status, _, stderr) = run_photocraft(&["--control", "nope", "--safegpu"]); + assert_eq!(status.code(), Some(2), "stderr: {stderr}"); + assert!(stderr.contains("`nope` is not a valid port"), "stderr: {stderr}"); + assert!(stderr.contains("unknown option `--safegpu`"), "stderr: {stderr}"); +} + +#[test] +fn arguments_after_double_dash_are_files() { + // `--` ends the options: `--help` and `-x` after it are file names, so neither prints usage + // nor is an unknown option; only the bad port is reported. + let (status, stdout, stderr) = run_photocraft(&["--control", "nope", "--", "--help", "-x"]); + assert_eq!(status.code(), Some(2), "stderr: {stderr}"); + assert!(stderr.contains("`nope` is not a valid port"), "stderr: {stderr}"); + assert!(!stdout.contains("Usage:"), "stdout: {stdout}"); + assert!(!stderr.contains("unknown option"), "stderr: {stderr}"); +} + +#[test] +fn macos_process_serial_number_is_still_ignored() { + // Old macOS passes `-psn_` when launching from Finder; it is neither a file nor an error. + let (status, _, stderr) = run_photocraft(&["--control", "nope", "-psn_0_12345"]); + assert_eq!(status.code(), Some(2), "stderr: {stderr}"); + assert!(stderr.contains("`nope` is not a valid port"), "stderr: {stderr}"); + assert!(!stderr.contains("unknown option"), "stderr: {stderr}"); +} + +#[test] +fn new_instance_is_a_known_option() { + let (status, _, stderr) = run_photocraft(&["--control", "nope", "--new-instance"]); + assert_eq!(status.code(), Some(2), "stderr: {stderr}"); + assert!(stderr.contains("`nope` is not a valid port"), "stderr: {stderr}"); + assert!(!stderr.contains("unknown option"), "stderr: {stderr}"); +} diff --git a/assets/icons/ellipse-dashed.svg b/assets/icons/ellipse-dashed.svg new file mode 100644 index 0000000000..f852dcf3a7 --- /dev/null +++ b/assets/icons/ellipse-dashed.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/quick-selection.svg b/assets/icons/quick-selection.svg index 454b38bae6..7e63dc66b9 100644 --- a/assets/icons/quick-selection.svg +++ b/assets/icons/quick-selection.svg @@ -9,8 +9,8 @@ stroke-linecap="round" stroke-linejoin="round" > - - - - + + + + diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 4f3d02496a..2c36b464c2 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -5,6 +5,9 @@ - **Headless:** an in-process `Headless` session owns the engine and performs file I/O. - **Bridge:** `BridgeClient` forwards tools to a desktop application started with `photocraft --control `. +For a source checkout, first [install the CLI on PATH and register the server](../../../docs/mcp.md#install-and-register). +The installed binary survives `cargo clean`; a symlink into `target/release` does not. + Start the headless server with: ```sh diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.md index 2e65d51550..c333cbc737 100644 --- a/book/src/formats/raster-formats.md +++ b/book/src/formats/raster-formats.md @@ -19,6 +19,7 @@ Every route that writes a document to a flat format (Save As, the CLI, MCP `doc_ - Formats without transparency (JPEG, Radiance HDR) get the image composited over white, as Export As and Quick Export do; in CMYK, white is no ink. - Formats that can't embed an ICC profile (GIF, BMP, TGA, QOI, ICO, Netpbm/PFM) get RGB documents in another profile (linear light, Display P3, …) converted to sRGB through the colour engine (perceptual intent), since an untagged file is read as sRGB. OpenEXR and Radiance HDR get linear sRGB instead (linear gray for a grayscale OpenEXR), which is how they are tagged when opened. - TGA, as Photoshop's Targa: an RGB Targa is 24 or 32 bits per pixel. Save As and Save a Copy ask (Targa Options, starting at 32 with an alpha channel, else 24); Export As has a Resolution choice (Auto, 24 or 32 bits/pixel); scripts pass `tgaBits` (`--tga-bits` on the CLI). At 32 bits the document's alpha channel is the file's alpha when it has exactly one (spot channels don't count; with several, none is used), and the colours are written exactly, never premultiplied or cleared where the alpha is 0, so a game texture's mask and its colours both survive. Without a usable alpha channel the layers' transparency is the alpha (opaque without any). 24 bits write no alpha, compositing transparency over white. Without a choice: 32 with an alpha channel or transparency, else 24. A 32-bit Targa opens as an opaque Background with its alpha as "Alpha 1", so it round-trips. Grayscale Targas are 8-bit. +- DDS, for game and 3D textures: Save As and Save a Copy ask (DDS Options) for the compression (None, uncompressed and lossless; BC1/DXT1, whose alpha is on or off; BC2/DXT3; BC3/DXT5) and whether to generate mipmaps (the full chain down to 1×1, each level a box filter of the one above). Scripts pass `ddsCompression` (`none`, `bc1`, `bc2`, `bc3`) and `ddsMipmaps` (`--dds-compression`, `--dds-mipmaps` on the CLI). Opening one reads its top mip level. Flat TIFF and JPEG exports of composited CMYK documents convert the RGB composite back through the document's CMYK ICC profile (relative colorimetric with black point compensation) and embed diff --git a/contributors/people.toml b/contributors/people.toml index 8694c72698..99d81059e9 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -159,6 +159,29 @@ sync_github_name = false real_name = "Ufuk Efe" sync_github_name = true +[people.nicolasfalesy] +sync_github_name = true + [people.sidney] real_name = "Sidney Markowitz" sync_github_name = true + +[people.TaylorBurke] +sync_github_name = true + +[people.1Git2Clone] +sync_github_name = true + +[people.Silvertree2010] +display_name = "Netter" +sync_github_name = false + +[people.Byxis] +sync_github_name = true + +[people.00xJS] +sync_github_name = true + +[people.guillehr2] +real_name = "Guillem Hermida" +sync_github_name = true diff --git a/crates/affinity/README.md b/crates/affinity/README.md index 3e4e066156..535c3736c6 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -139,11 +139,18 @@ zstd window, 4096 saved revisions, array lengths no longer than the bytes left, 16 777 216 decoded values per document stream (fields and array elements together, counted before anything is allocated: a value takes about 40 bytes in memory however few it took in the file; the largest of those 189 public documents uses 3.3 million), 384 levels of object nesting, 128 levels of layers, 500 000 layers, four million curve -nodes per curve, 64 megapixels per pixel layer (cropped to its content first) and 1024 gradient +nodes per curve, 4 levels of spot colours defined through spot colours, 64 megapixels per pixel layer (cropped to its content first) and 1024 gradient stops; `photocraft-io` adds 300 000 pixels a side per document and 64 megapixels per image on the canvas. Every archive entry's CRC-32 and size must match. Malformed input returns an `Error`; the crate has no panics outside tests. +Compound outlines have a separate active-reference cycle check and a depth cap of 64. Across +the document, geometry expansion admits at most 500 000 combined outline calls and operand-slot +visits (including nulls and non-object values), and four million points created or copied into +compounds. Operand slots are charged before filtering, without first collecting an operand list. +A compound that crosses a limit or contains a cycle is omitted +with a warning as a whole; ordinary shared operands remain valid and keep each occurrence's transform. + ## Privacy Affinity documents can hold the folder they were saved in, user names, original image paths and diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs index 08554134db..6c8ea602c9 100644 --- a/crates/affinity/src/geometry.rs +++ b/crates/affinity/src/geometry.rs @@ -6,10 +6,103 @@ use crate::stream::{ObjId, Tag, Value}; /// Nodes per curve object. const MAX_NODES: usize = 4_000_000; +const MAX_COMPOUND_DEPTH: usize = 64; +const MAX_OUTLINE_VISITS: usize = 500_000; +const MAX_OUTLINE_POINTS: usize = 4_000_000; + +/// Geometry is expanded per occurrence, since parametric outlines can depend on their world +/// transform. Bound work across the entire document instead of memoizing by object id alone. +pub(crate) struct Budget { + visits_left: usize, + points_left: usize, +} + +impl Default for Budget { + fn default() -> Self { + Self { visits_left: MAX_OUTLINE_VISITS, points_left: MAX_OUTLINE_POINTS } + } +} + +impl Budget { + /// Charge an outline call or a raw compound operand slot before inspecting it. + fn visit(&mut self) -> Result<(), &'static str> { + self.visits_left = self.visits_left.checked_sub(1).ok_or("compound geometry budget exhausted")?; + Ok(()) + } + + /// Charge both leaf geometry and each copy into a compound before allocating that copy. + fn path(&mut self, path: &Path) -> Result<(), &'static str> { + let points = path.subpaths.iter().fold(0usize, |n, s| n.saturating_add(1).saturating_add(s.segments.len().saturating_mul(3))); + let Some(left) = self.points_left.checked_sub(points) else { + // Do not rebuild an expensive leaf for every subsequent root after exhaustion. + self.visits_left = 0; + return Err("compound geometry budget exhausted"); + }; + self.points_left = left; + Ok(()) + } +} /// The node-space outline of a curve, shape or compound node, and whether it fills even-odd. /// Instances (master-page or symbol copies) take the geometry of their master. pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> { + match outline_inner(r, id, class, world, &mut Vec::new()) { + Ok(path) => path, + Err(reason) => { + r.warn(reason); + None + } + } +} + +fn outline_inner(r: &mut Reader, id: ObjId, class: Tag, world: Affine, active: &mut Vec) -> Result, &'static str> { + r.geometry_budget.visit()?; + if active.contains(&id) { + return Err("cyclic compound shape"); + } + // Independent of the layer-tree limit: Comp operands do not pass through Reader::node. + if active.len() >= MAX_COMPOUND_DEPTH { + return Err("compound depth exceeds 64 levels"); + } + if class != Tag::of(b"Comp") { + let path = leaf_outline(r, id, class, world); + if let Some((path, _)) = &path { + r.geometry_budget.path(path)?; + } + return Ok(path); + } + active.push(id); + let result = compound(r, id, world, active); + active.pop(); + result +} + +fn compound(r: &mut Reader, id: ObjId, world: Affine, active: &mut Vec) -> Result, &'static str> { + let s = r.s; + // One path of all operands' contours, filled even-odd, as before. A safety failure rejects + // the whole outline: a partial add/subtract shape could silently change its meaning. + let mut path = Path::default(); + // Charge every slot before filtering nulls or malformed values. Stream::objs would scan + // and allocate the whole list first, repeating uncharged work for each shared occurrence. + let children = if let Some(Value::Array(children)) = s.field(id, b"Chld") { children.as_slice() } else { &[] }; + for child in children { + r.geometry_budget.visit()?; + let Value::Obj(Some(c)) = child else { continue }; + let c = *c; + let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); + let Some(class) = s.class(c) else { return Ok(None) }; + if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) { + r.warn("compound shapes that intersect or exclude (imported as add)"); + } + if let Some((p, _)) = outline_inner(r, c, class, local.then(world), active)? { + r.geometry_budget.path(&p)?; + path.subpaths.extend(p.transformed(local).subpaths); + } + } + Ok(Some((path, true))) +} + +fn leaf_outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> { let s = r.s; match &class.0.to_be_bytes() { b"PCrv" | b"TxtC" => { @@ -18,23 +111,6 @@ pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> O let multi = path.subpaths.len() > 1; Some((path, multi)) } - b"Comp" => { - // One path of all the operands' contours in the compound's space, filled even-odd: this - // matches add and subtract operands in every public sample; a true union of overlapping - // added operands would differ. - let mut path = Path::default(); - for c in s.objs(id, b"Chld") { - let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - let class = s.class(c)?; - if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) { - r.warn("compound shapes that intersect or exclude (imported as add)"); - } - if let Some((p, _)) = outline(r, c, class, local.then(world)) { - path.subpaths.extend(p.transformed(local).subpaths); - } - } - Some((path, true)) - } _ => { let (shape, box_owner) = match s.obj(id, b"Shpe") { Some(sh) => (sh, id), diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs index 7fba5a4597..7c05072419 100644 --- a/crates/affinity/src/model.rs +++ b/crates/affinity/src/model.rs @@ -298,6 +298,7 @@ pub(crate) struct Reader<'s, 'a, 'b> { warnings: BTreeMap, nodes: usize, active: HashSet, + pub(crate) geometry_budget: crate::geometry::Budget, /// Decoded pixels still available ([`Limits::max_pixel_bytes`] less what the layers read so /// far hold). pixels_left: usize, @@ -305,7 +306,16 @@ pub(crate) struct Reader<'s, 'a, 'b> { impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { fn new(s: &'s Stream, archive: &'b mut Archive<'a>, limits: Limits) -> Self { - Self { s, archive, dpi: 72.0, warnings: BTreeMap::new(), nodes: 0, active: HashSet::new(), pixels_left: limits.max_pixel_bytes } + Self { + s, + archive, + dpi: 72.0, + warnings: BTreeMap::new(), + nodes: 0, + active: HashSet::new(), + geometry_budget: crate::geometry::Budget::default(), + pixels_left: limits.max_pixel_bytes, + } } /// Admit a layer's decoded pixels before they are allocated (#4960). `rgba` is the layer's diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs index c4ebff8446..343c276b60 100644 --- a/crates/affinity/src/paint.rs +++ b/crates/affinity/src/paint.rs @@ -134,8 +134,19 @@ fn floats(v: &Value) -> Option> { } } +/// Spot colours defined through spot colours. A spot colour (`Pant`) is read through its RGB +/// equivalent, else its base colour, which in real files hold plain colours. Colours are shared +/// objects, so one can link to itself, and with both links followed at every level a colour read +/// costs up to 2^(depth+1) lookups. +const MAX_SPOT_DEPTH: usize = 4; + /// A colour object (`RGBA`, `HSLA`, `CMYK`, `GRAY`, `LABA`, `Pant`). pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option { + color_at(r, id, 0) +} + +/// [`color`] of an object `depth` spot colours down. +fn color_at(r: &mut Reader, id: ObjId, depth: usize) -> Option { let s = r.s; let class = s.class(id)?; let col = || -> Option> { @@ -166,8 +177,12 @@ pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option { Color::Lab { l: 100.0 * u(0)?, a: 255.0 * u(1)? - 128.0, b: 255.0 * u(2)? - 128.0, alpha: u(3)? } } b"Pant" => { + if depth >= MAX_SPOT_DEPTH { + r.warn("spot colours nested deeper than 4 levels (left empty)"); + return None; + } r.warn("spot colours (imported as their RGB equivalent)"); - return s.obj(id, b"srgb").and_then(|c| color(r, c)).or_else(|| s.obj(id, b"base").and_then(|c| color(r, c))); + return s.obj(id, b"srgb").and_then(|c| color_at(r, c, depth + 1)).or_else(|| s.obj(id, b"base").and_then(|c| color_at(r, c, depth + 1))); } b"RegC" => Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0, a: 1.0 }, _ => { diff --git a/crates/affinity/src/preview.rs b/crates/affinity/src/preview.rs index f50cb8c3e9..d3341eeb1c 100644 --- a/crates/affinity/src/preview.rs +++ b/crates/affinity/src/preview.rs @@ -94,11 +94,8 @@ pub fn preview(bytes: &[u8]) -> Result, Error> { } image_data = true; } - b"IEND" => { - if !image_data { - return Err(Error::Malformed("PNG has no image data")); - } - } + b"IEND" if !image_data => return Err(Error::Malformed("PNG has no image data")), + b"IEND" => {} _ if kind.first().is_some_and(u8::is_ascii_uppercase) => { return Err(Error::Unsupported("unknown critical PNG chunk")); } diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index 59ae99044a..2c68a064a3 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -538,3 +538,174 @@ mod pixels { ); } } + +/// Spot colours that link to themselves or to each other. Each document is read on a 1 MiB +/// stack, the smallest main-thread stack PhotoCraft runs on (Windows), first in a child process +/// that must finish within 20 s. A stack overflow aborts the process it happens in, so unbounded +/// recursion fails the one test that caused it instead of taking the other tests in the binary +/// down with it. +mod spot_colours { + use std::io::{Read, Write}; + use std::process::{Command, Stdio}; + use std::time::{Duration, Instant}; + + use crate::container::Limits; + use crate::model::{Document, Kind}; + use crate::paint::{Color, Paint}; + use crate::stream::Tag; + use crate::synth::{self, F, Method, tag}; + + /// A one-page document whose page holds `top`, read in a child process first and then here. + fn read(top: Vec) -> Document { + let spread = F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(top))]); + let data = synth::stream(&[(tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]); + let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None); + let test = std::thread::current().name().unwrap_or("reader").to_owned(); + read_in_child(&bytes, &test); + read_on_small_stack(bytes, &test).unwrap() + } + + /// Reads on a 1 MiB thread named after the test, so a stack overflow message names the test. + fn read_on_small_stack(bytes: Vec, test: &str) -> Result { + let reader = std::thread::Builder::new().name(test.to_owned()).stack_size(1 << 20).spawn(move || crate::read(&bytes, Limits::default())).unwrap(); + reader.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic)) + } + + /// Set in the child process to the name of the test it reads for. + const CHILD: &str = "PHOTOCRAFT_AFFINITY_READ_CHILD"; + + /// Runs `read_child` in a new process of this test binary on `bytes` and fails the test if + /// that process crashes, panics or takes over 20 s, or never read the document. + fn read_in_child(bytes: &[u8], test: &str) { + let mut child = Command::new(std::env::current_exe().unwrap()) + .args(["tests::spot_colours::read_child", "--exact", "--ignored", "--nocapture", "--test-threads=1"]) + .env(CHILD, test) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let drain = |mut pipe: Box| { + std::thread::spawn(move || { + let mut text = String::new(); + let _ = pipe.read_to_string(&mut text); + text + }) + }; + let stdout = drain(Box::new(child.stdout.take().unwrap())); + let stderr = drain(Box::new(child.stderr.take().unwrap())); + // Fed from a thread, so a child that never reads cannot block the deadline below; a child + // that dies first breaks the pipe and is reported by its exit status. + let (mut stdin, input) = (child.stdin.take().unwrap(), bytes.to_vec()); + let feed = std::thread::spawn(move || { + let _ = stdin.write_all(&input); + }); + let deadline = Instant::now() + Duration::from_secs(20); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break Some(status); + } + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + break None; + } + std::thread::sleep(Duration::from_millis(10)); + }; + feed.join().unwrap(); + let output = format!("{}{}", stdout.join().unwrap(), stderr.join().unwrap()); + match status { + None => panic!("reading the document did not finish within 20 s:\n{output}"), + Some(status) if !status.success() => panic!("reading the document failed in a child process ({status}):\n{output}"), + // A filter that matched no test would also exit successfully, having read nothing. + Some(_) => assert!(output.contains(&format!("read {} bytes", bytes.len())), "the child process did not read the document:\n{output}"), + } + } + + /// Not a test of its own: `read_in_child` runs it in a child process to read the document on + /// its stdin. Without the variable, as when run with `--ignored`, it does nothing. + #[test] + #[ignore = "run by read_in_child in a child process"] + fn read_child() { + let Some(test) = std::env::var_os(CHILD) else { return }; + let mut bytes = Vec::new(); + std::io::stdin().read_to_end(&mut bytes).unwrap(); + let len = bytes.len(); + let _ = read_on_small_stack(bytes, &test.to_string_lossy()); + println!("read {len} bytes"); + } + + /// An ellipse filled with `colour`. + fn filled(id: u32, colour: F) -> F { + F::Def( + id, + vec![tag(b"ShpN")], + vec![ + (tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 1.0, 1.0])), + (tag(b"Shpe"), F::Def(id + 1_000_000, vec![tag(b"ShpE")], vec![])), + (tag(b"BFFl"), F::Shared(vec![F::Def(id + 2_000_000, vec![tag(b"FilS")], vec![(tag(b"Colr"), colour)])])), + ], + ) + } + + fn spot(id: u32, fields: Vec<(Tag, F)>) -> F { + F::Def(id, vec![tag(b"Pant")], fields) + } + + fn fills(doc: &Document) -> &[Paint] { + match &doc.spreads[0].nodes[0].kind { + Kind::Shape { fills, .. } => fills, + other => panic!("expected a shape, got {other:?}"), + } + } + + fn warned(doc: &Document, what: &str) -> bool { + doc.warnings.iter().any(|w| w.contains(what)) + } + + #[test] + fn a_spot_colour_that_is_its_own_rgb_equivalent_is_refused() { + let doc = read(vec![filled(10, spot(20, vec![(tag(b"srgb"), F::Ref(20))]))]); + assert!(fills(&doc).is_empty(), "{:?}", fills(&doc)); + assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings); + } + + #[test] + fn spot_colours_that_are_each_others_base_and_rgb_equivalent_are_refused() { + let doc = read(vec![filled(10, spot(20, vec![(tag(b"base"), spot(21, vec![(tag(b"srgb"), F::Ref(20))]))]))]); + assert!(fills(&doc).is_empty(), "{:?}", fills(&doc)); + assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings); + } + + #[test] + fn spot_colours_of_spot_colours_do_not_take_exponential_time() { + // Each level's RGB equivalent and base are the next level, and the last is in an unknown + // model, so both are followed everywhere: 2^41 colour reads before the fix. + fn level(id: u32, left: u32) -> F { + if left == 0 { + return F::Def(id, vec![tag(b"XXXX")], vec![]); + } + spot(id, vec![(tag(b"srgb"), level(id + 1, left - 1)), (tag(b"base"), F::Ref(id + 1))]) + } + let doc = read(vec![filled(10, level(100, 40))]); + assert!(fills(&doc).is_empty(), "{:?}", fills(&doc)); + } + + /// `spots` spot colours, each defined through the next, around an opaque RGB colour. + fn spots(id: u32, spots: u32) -> F { + if spots == 0 { + let rgba: Vec = [1.0f32, 0.5, 0.25, 1.0].iter().flat_map(|c| c.to_le_bytes()).collect(); + return F::Def(id, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct(rgba))]); + } + spot(id, vec![(tag(b"srgb"), self::spots(id + 1, spots - 1))]) + } + + #[test] + fn spot_colours_nest_four_levels_and_no_deeper() { + let doc = read(vec![filled(10, spots(100, 4))]); + assert_eq!(fills(&doc), [Paint::Solid(Color::Rgb { r: 1.0, g: 0.5, b: 0.25, a: 1.0 })]); + let doc = read(vec![filled(10, spots(100, 5))]); + assert!(fills(&doc).is_empty(), "{:?}", fills(&doc)); + assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings); + } +} diff --git a/crates/affinity/tests/compound_limits.rs b/crates/affinity/tests/compound_limits.rs new file mode 100644 index 0000000000..76f2e6e4a1 --- /dev/null +++ b/crates/affinity/tests/compound_limits.rs @@ -0,0 +1,212 @@ +//! #6423: compound operands form a graph, not necessarily a tree. +#![cfg(feature = "synth")] +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use photocraft_affinity::model::{Document, Kind}; +use photocraft_affinity::synth::{self, F, Method, tag}; +use photocraft_affinity::{Limits, read}; +use std::time::{Duration, Instant}; + +fn compound(id: u32, children: Vec) -> F { + F::Def(id, vec![tag(b"Comp")], vec![(tag(b"Chld"), F::Shared(children))]) +} + +fn rectangle() -> F { + F::Def(100, vec![tag(b"ShpN")], vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 10.0, 20.0])), (tag(b"Shpe"), F::Def(101, vec![tag(b"ShNR")], vec![]))]) +} + +fn document_bytes(definitions: Vec, roots: Vec) -> Vec { + let data = synth::stream(&[ + (tag(b"Defs"), F::Shared(definitions)), + ( + tag(b"DocR"), + F::Def( + 1, + vec![tag(b"DocN")], + vec![( + tag(b"Chld"), + F::Shared(vec![F::Def( + 2, + vec![tag(b"Sprd")], + vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(roots))], + )]), + )], + ), + ), + ]); + synth::container(&[("doc.dat", &data, Method::Zlib)], None) +} + +fn document(definitions: Vec, roots: Vec) -> Document { + read(&document_bytes(definitions, roots), Limits::default()).unwrap() +} + +// A stack overflow aborts rather than unwinds. Keep that failure (and an exponential hang) +// inside a child process, so the regression fails without killing the entire test runner. +fn isolated(name: &str, check: impl FnOnce()) { + if std::env::var("PHOTOCRAFT_COMPOUND_CASE").as_deref() == Ok(name) { + check(); + return; + } + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", name, "--nocapture"]) + .env("PHOTOCRAFT_COMPOUND_CASE", name) + .spawn() + .unwrap(); + let start = Instant::now(); + loop { + if let Some(status) = child.try_wait().unwrap() { + assert!(status.success(), "compound import failed: {status}"); + break; + } + if start.elapsed() > Duration::from_secs(10) { + child.kill().unwrap(); + child.wait().unwrap(); + panic!("compound import exceeded ten seconds"); + } + std::thread::sleep(Duration::from_millis(20)); + } +} + +fn unsupported(doc: &Document, warning: &str) { + assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Unsupported)); + assert!(doc.warnings.iter().any(|w| w.contains(warning)), "{:?}", doc.warnings); +} + +#[test] +fn self_referencing_compound_is_reported_without_aborting() { + isolated("self_referencing_compound_is_reported_without_aborting", || { + let doc = document(vec![], vec![compound(10, vec![F::Ref(10)]), rectangle()]); + unsupported(&doc, "cyclic compound"); + assert!(matches!(doc.spreads[0].nodes[1].kind, Kind::Shape { .. }), "a cycle must not poison unrelated shapes"); + }); +} + +#[test] +fn indirectly_cyclic_compound_is_not_imported_as_a_partial_shape() { + isolated("indirectly_cyclic_compound_is_not_imported_as_a_partial_shape", || { + let doc = document(vec![rectangle()], vec![compound(10, vec![F::Ref(100), compound(11, vec![F::Ref(10)])])]); + unsupported(&doc, "cyclic compound"); + }); +} + +fn nested(levels: u32, repeated: bool) -> Document { + // Flat definitions bypass the stream parser's nesting cap: only references form the depth. + let mut definitions = vec![rectangle()]; + let mut previous = 100; + for id in 200..200 + levels { + let children = if repeated { vec![F::Ref(previous), F::Ref(previous)] } else { vec![F::Ref(previous)] }; + definitions.push(compound(id, children)); + previous = id; + } + document(definitions, vec![F::Ref(previous)]) +} + +#[test] +fn deep_compound_graph_is_bounded_on_a_small_stack() { + isolated("deep_compound_graph_is_bounded_on_a_small_stack", || { + std::thread::Builder::new().stack_size(512 * 1024).spawn(|| unsupported(&nested(1000, false), "compound depth")).unwrap().join().unwrap(); + }); +} + +#[test] +fn shared_operands_cannot_expand_exponentially() { + isolated("shared_operands_cannot_expand_exponentially", || unsupported(&nested(40, true), "compound geometry budget")); +} + +#[test] +fn shared_empty_operands_also_have_a_work_limit() { + isolated("shared_empty_operands_also_have_a_work_limit", || { + let mut definitions = vec![compound(100, vec![])]; + let mut previous = 100; + for id in 200..240 { + definitions.push(compound(id, vec![F::Ref(previous), F::Ref(previous)])); + previous = id; + } + unsupported(&document(definitions, vec![F::Ref(previous)]), "compound geometry budget"); + }); +} + +#[test] +fn geometry_budget_is_shared_across_layer_roots() { + isolated("geometry_budget_is_shared_across_layer_roots", || { + let mut definitions = vec![rectangle()]; + let mut previous = 100; + for id in 200..214 { + definitions.push(compound(id, vec![F::Ref(previous), F::Ref(previous)])); + previous = id; + } + let mut roots = vec![F::Ref(previous); 12]; + roots.push(F::Ref(100)); + let doc = document(definitions, roots); + let nodes = &doc.spreads[0].nodes; + assert!(matches!(nodes[0].kind, Kind::Shape { .. }), "a modest shared graph still imports"); + assert!(matches!(nodes.last().unwrap().kind, Kind::Unsupported), "later roots cannot reset the exhausted budget"); + assert!(doc.warnings.iter().any(|w| w.contains("compound geometry budget"))); + }); +} + +#[test] +fn ordinary_shared_operands_keep_both_transformed_copies() { + let mut translated = compound(201, vec![F::Ref(100)]); + let F::Def(_, _, fields) = &mut translated else { unreachable!() }; + fields.push((tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 30.0, 0.0, 1.0, 40.0]))); + let doc = document(vec![rectangle(), compound(200, vec![F::Ref(100)]), translated], vec![compound(202, vec![F::Ref(200), F::Ref(201)])]); + assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); + let Kind::Shape { path, .. } = &doc.spreads[0].nodes[0].kind else { panic!("expected compound outline") }; + assert_eq!(path.subpaths.len(), 2); + for (a, b) in path.subpaths[0].segments.iter().flatten().zip(path.subpaths[1].segments.iter().flatten()) { + assert_eq!(b.x, a.x + 30.0); + assert_eq!(b.y, a.y + 40.0); + } +} + +#[test] +fn null_operand_slots_cannot_bypass_geometry_budget() { + isolated("null_operand_slots_cannot_bypass_geometry_budget", || { + let bytes = document_bytes(vec![compound(10, vec![F::Null; 1_000_000])], vec![F::Ref(10); 20_000]); + let start = Instant::now(); + let doc = read(&bytes, Limits::default()).unwrap(); + eprintln!("one million nulls / 20,000 placements: {} bytes, read {:.3}s", bytes.len(), start.elapsed().as_secs_f64()); + unsupported(&doc, "compound geometry budget"); + assert_eq!(doc.spreads[0].nodes.len(), 20_000); + assert!(doc.spreads[0].nodes.iter().all(|n| matches!(n.kind, Kind::Unsupported))); + }); +} + +#[test] +fn null_operand_slots_share_budget_across_layer_roots() { + isolated("null_operand_slots_share_budget_across_layer_roots", || { + let doc = document(vec![compound(10, vec![F::Null; 1_000])], vec![F::Ref(10); 1_000]); + assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Shape { .. }), "a small empty compound remains valid"); + assert!(matches!(doc.spreads[0].nodes.last().unwrap().kind, Kind::Unsupported)); + assert!(doc.warnings.iter().any(|w| w.contains("compound geometry budget"))); + }); +} + +#[test] +fn null_operand_slots_cannot_leave_a_partial_shape() { + isolated("null_operand_slots_cannot_leave_a_partial_shape", || { + let mut slots = vec![F::Ref(100)]; + slots.extend(vec![F::Null; 1_000_000]); + let doc = document(vec![rectangle(), compound(10, slots)], vec![F::Ref(10)]); + unsupported(&doc, "compound geometry budget"); + }); +} + +#[test] +fn non_object_operand_slots_also_consume_budget() { + isolated("non_object_operand_slots_also_consume_budget", || { + let comp = F::Def(10, vec![tag(b"Comp")], vec![(tag(b"Chld"), F::U8s(vec![0; 1_000_000]))]); + unsupported(&document(vec![comp], vec![F::Ref(10)]), "compound geometry budget"); + }); +} + +#[test] +fn ordinary_null_operand_slots_preserve_shared_contours() { + let doc = document(vec![rectangle(), compound(10, vec![F::Null, F::Ref(100), F::Null, F::Ref(100), F::Null])], vec![F::Ref(10)]); + assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); + let Kind::Shape { path, .. } = &doc.spreads[0].nodes[0].kind else { panic!("expected compound outline") }; + assert_eq!(path.subpaths.len(), 2); + assert_eq!(path.subpaths[0], path.subpaths[1]); +} diff --git a/crates/algo/data/LICENSE-libfacedetection.txt b/crates/algo/data/LICENSE-libfacedetection.txt new file mode 100644 index 0000000000..33abd64f06 --- /dev/null +++ b/crates/algo/data/LICENSE-libfacedetection.txt @@ -0,0 +1,35 @@ +By downloading, copying, installing or using the software you agree to this license. +If you do not agree to this license, do not download, install, +copy or use the software. + + + License Agreement For libfacedetection + (3-clause BSD License) + +Copyright (c) 2015-2019, Shiqi Yu, all rights reserved. +shiqi.yu@gmail.com + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the names of the copyright holders nor the names of the contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as is" and +any express or implied warranties, including, but not limited to, the implied +warranties of merchantability and fitness for a particular purpose are disclaimed. +In no event shall copyright holders or contributors be liable for any direct, +indirect, incidental, special, exemplary, or consequential damages +(including, but not limited to, procurement of substitute goods or services; +loss of use, data, or profits; or business interruption) however caused +and on any theory of liability, whether in contract, strict liability, +or tort (including negligence or otherwise) arising in any way out of +the use of this software, even if advised of the possibility of such damage. \ No newline at end of file diff --git a/crates/algo/data/libfacedetection.bin b/crates/algo/data/libfacedetection.bin new file mode 100644 index 0000000000..0941c4f689 Binary files /dev/null and b/crates/algo/data/libfacedetection.bin differ diff --git a/crates/algo/examples/bench_multiband.rs b/crates/algo/examples/bench_multiband.rs new file mode 100644 index 0000000000..9d58b81a54 --- /dev/null +++ b/crates/algo/examples/bench_multiband.rs @@ -0,0 +1,42 @@ +//! Time and peak memory of the Photomerge multi-band blend: `n` RGB sources of `mp` megapixels +//! (3:2), each overlapping the next by half its width. +//! `cargo run --release -p photocraft-algo --example bench_multiband [n] [mp]` (default 4 × 24 MP). +//! Peak memory is the growth of the process's high-water mark during the blend (Linux only). +use std::time::Instant; + +use photocraft_algo::panorama::{self, RoiImage}; + +/// The process's peak resident set in MiB (`VmHWM`), where `/proc` has it. +fn peak_mib() -> Option { + let s = std::fs::read_to_string("/proc/self/status").ok()?; + let kb: f64 = s.lines().find(|l| l.starts_with("VmHWM:"))?.split_whitespace().nth(1)?.parse().ok()?; + Some(kb / 1024.0) +} + +fn main() { + let mut args = std::env::args().skip(1); + let n: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(4).max(1); + let mp: f64 = args.next().and_then(|a| a.parse().ok()).unwrap_or(24.0); + let sh = ((mp * 1e6 / 1.5).sqrt().round() as usize).max(2); + let sw = sh * 3 / 2; + let step = sw / 2; + let (cw, ch) = (step * (n - 1) + sw, sh); + let rois: Vec = (0..n) + .map(|k| { + let px = (0..sw * sh * 3).map(|i| ((i / 3 % sw * 7 + i / 3 / sw * 3 + k * 31 + i % 3 * 50) % 251) as f32 / 251.0).collect(); + RoiImage { x0: (step * k) as i32, y0: 0, w: sw, h: sh, ch: 3, px, alpha: vec![1.0; sw * sh] } + }) + .collect(); + // Each canvas column belongs to the image whose centre is nearest, as a seam would split it. + let wts: Vec> = (0..n) + .map(|k| (0..sw * sh).map(|i| if ((step * k + i % sw + step / 2) / step).saturating_sub(1).min(n - 1) == k { 1.0 } else { 0.0 }).collect()) + .collect(); + let levels = panorama::blend_levels(cw, ch).min(7); + let before = peak_mib(); + let t0 = Instant::now(); + let (px, cov) = panorama::multiband(cw, ch, &rois, &wts, levels); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + let peak = peak_mib().zip(before).map_or("n/a".to_string(), |(a, b)| format!("{:.0} MiB", a - b)); + println!("{n} × {sw}×{sh} ({mp} MP) RGB, canvas {cw}×{ch}, {levels} levels: {ms:.0} ms, peak +{peak} during the blend"); + std::hint::black_box((px, cov)); +} diff --git a/crates/algo/src/blur2.rs b/crates/algo/src/blur2.rs index e917405083..bb6b47656c 100644 --- a/crates/algo/src/blur2.rs +++ b/crates/algo/src/blur2.rs @@ -335,7 +335,7 @@ pub(crate) fn lens_blur(src: &Image, out: Rect, ctx: &Ctx, spec: &LensSpec) -> V } src.get(x, y, n - 1) } - DepthSource::LayerMask => spec.depth_map?.get(x, y, 0), + DepthSource::LayerMask | DepthSource::Channel => spec.depth_map?.get(x, y, 0), }; Some(if spec.invert { 1.0 - d } else { d }) }; diff --git a/crates/algo/src/camera_raw.rs b/crates/algo/src/camera_raw.rs index f855b08bfe..3cadd1d20c 100644 --- a/crates/algo/src/camera_raw.rs +++ b/crates/algo/src/camera_raw.rs @@ -67,22 +67,16 @@ impl Encoding { pub(crate) fn of(gamma: f32) -> Self { Encoding(if gamma.is_finite() && gamma > 0.0 { gamma.clamp(0.5, 4.0) } else { 0.0 }) } + /// A value in this encoding as linear light. pub(crate) fn decode(self, v: f32) -> f32 { if self.0 > 0.0 { v.max(0.0).powf(self.0) } else { srgb_to_linear(v) } } + /// Linear light back into this encoding, the inverse of [`Encoding::decode`]. pub(crate) fn encode(self, v: f32) -> f32 { if self.0 > 0.0 { v.max(0.0).powf(1.0 / self.0) } else { linear_to_srgb(v) } } } -fn srgb_encode(v: f32) -> f32 { - linear_to_srgb(v) -} - -fn srgb_decode(v: f32) -> f32 { - srgb_to_linear(v) -} - fn luma_linear(c: [f32; 3]) -> f32 { luma(c) } diff --git a/crates/algo/src/camera_raw/local_tone.rs b/crates/algo/src/camera_raw/local_tone.rs index 7844f8d74b..1dbf58421f 100644 --- a/crates/algo/src/camera_raw/local_tone.rs +++ b/crates/algo/src/camera_raw/local_tone.rs @@ -79,23 +79,48 @@ fn mirror(i: isize, n: usize) -> usize { const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0]; +/// Planes smaller than this run their rows on one thread: the filter builds a whole pyramid per +/// reference (up to 96), and splitting its small levels into one-row tasks cost more in rayon's +/// scheduling than the rows themselves (a fifth of a Shadows render on 36 MP, measured). +const PAR_MIN: usize = 1 << 15; + +/// [`par_rows`] for a plane, on one thread when it is small (see [`PAR_MIN`]). +fn rows(buf: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync + Send) { + if buf.len() < PAR_MIN { + buf.chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| f(y, row)); + } else { + par_rows(buf, w, 1, f); + } +} + /// The binomial 5-tap blur, sampled every `step` pixels from 0 (1 = full resolution). fn blur_step(p: &Plane, step: usize) -> Plane { let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step)); - // Columns first at the kept rows, then rows at the kept columns. + // Columns first at the kept rows, then rows at the kept columns. Each sum adds the same terms + // in the same order as a `mirror` per tap would, so the result is bit for bit the same; the + // source rows are found once per row and the columns mirrored only near the edges. let mut tmp = vec![0.0f32; p.w * h2]; - par_rows(&mut tmp, p.w, 1, |y2, row| { + rows(&mut tmp, p.w, |y2, row| { let y = (y2 * step) as isize; + let src: [&[f32]; 5] = std::array::from_fn(|k| { + let r = mirror(y + k as isize - 2, p.h); + &p.v[r * p.w..(r + 1) * p.w] + }); for (x, o) in row.iter_mut().enumerate() { - *o = (0..5).map(|k| TAPS[k] * p.v[mirror(y + k as isize - 2, p.h) * p.w + x]).sum(); + *o = (0..5).map(|k| TAPS[k] * src[k][x]).sum(); } }); let mut out = vec![0.0f32; w2 * h2]; - par_rows(&mut out, w2, 1, |y2, row| { + rows(&mut out, w2, |y2, row| { let src = &tmp[y2 * p.w..(y2 + 1) * p.w]; for (x2, o) in row.iter_mut().enumerate() { - let x = (x2 * step) as isize; - *o = (0..5).map(|k| TAPS[k] * src[mirror(x + k as isize - 2, p.w)]).sum(); + let x = x2 * step; + *o = if x >= 2 && x + 2 < p.w { + let s = &src[x - 2..x + 3]; + (0..5).map(|k| TAPS[k] * s[k]).sum() + } else { + (0..5).map(|k| TAPS[k] * src[mirror(x as isize + k as isize - 2, p.w)]).sum() + }; } }); Plane { w: w2, h: h2, v: out } @@ -107,14 +132,78 @@ fn down(p: &Plane) -> Plane { } /// `p` brought up to `w × h`: zeros between samples, then the blur times four. +/// +/// Three samples in four are zero, so their taps are skipped instead of blurring a zero-filled +/// plane: the nonzero terms are added in the same order (skipping `+0.0` terms changes at most the +/// sign of a zero, and the filter only adds and exponentiates these values). fn up(p: &Plane, w: usize, h: usize) -> Plane { - let mut z = Plane { w, h, v: vec![0.0; w * h] }; - for y in 0..p.h.min(h.div_ceil(2)) { - for x in 0..p.w.min(w.div_ceil(2)) { - z.v[2 * y * w + 2 * x] = p.v[y * p.w + x] * 4.0; + let (lh, lw) = (p.h.min(h.div_ceil(2)), p.w.min(w.div_ceil(2))); + // The source sample behind index `i` of a zero-stuffed axis of length `n` holding `lim` samples. + let src = |i: isize, n: usize, lim: usize| { + let m = mirror(i, n); + (m.is_multiple_of(2) && m / 2 < lim).then_some(m / 2) + }; + // Columns first, only at the even columns (the odd ones are all zero). + let mut tmp = vec![0.0f32; lw * h]; + if lw > 0 { + rows(&mut tmp, lw, |y, row| { + let taps: [Option<&[f32]>; 5] = std::array::from_fn(|k| src(y as isize + k as isize - 2, h, lh).map(|r| &p.v[r * p.w..r * p.w + lw])); + for (j, o) in row.iter_mut().enumerate() { + *o = (0..5).filter_map(|k| taps[k].map(|s| TAPS[k] * (s[j] * 4.0))).sum(); + } + }); + } + let mut out = vec![0.0f32; w * h]; + rows(&mut out, w, |y, row| { + let t = &tmp[y * lw..(y + 1) * lw]; + for (x, o) in row.iter_mut().enumerate() { + *o = if x >= 2 && x + 2 < w { + // Away from the edges no tap mirrors. + (0..5) + .filter_map(|k| { + let i = x + k - 2; + (i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * t[i / 2]) + }) + .sum() + } else { + (0..5).filter_map(|k| src(x as isize + k as isize - 2, w, lw).map(|j| TAPS[k] * t[j])).sum() + }; } + }); + Plane { w, h, v: out } +} + +/// The source rows of [`up`]`(p, w, h)` at output row `y`, one per tap (`None` where the +/// zero-stuffed row is all zeros). +fn up_rows(p: &Plane, h: usize, y: usize) -> [Option; 5] { + let lh = p.h.min(h.div_ceil(2)); + std::array::from_fn(|k| { + let m = mirror(y as isize + k as isize - 2, h); + (m.is_multiple_of(2) && m / 2 < lh).then_some(m / 2) + }) +} + +/// One sample of [`up`]`(p, w, h)`: column `x` of the output row whose [`up_rows`] are `rows`. +/// It adds the same terms in the same order as `up`, so it gives the same bits. +fn up_at(p: &Plane, w: usize, rows: &[Option; 5], x: usize) -> f32 { + let lw = p.w.min(w.div_ceil(2)); + let col = |j: usize| -> f32 { (0..5).filter_map(|k| rows[k].map(|r| TAPS[k] * (p.v[r * p.w + j] * 4.0))).sum() }; + if x >= 2 && x + 2 < w { + // Away from the edges no tap mirrors. + (0..5) + .filter_map(|k| { + let i = x + k - 2; + (i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * col(i / 2)) + }) + .sum() + } else { + (0..5) + .filter_map(|k| { + let m = mirror(x as isize + k as isize - 2, w); + (m.is_multiple_of(2) && m / 2 < lw).then(|| TAPS[k] * col(m / 2)) + }) + .sum() } - blur_step(&z, 1) } /// Levels down to about 2 pixels on the short side. @@ -154,21 +243,21 @@ fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane { for k in 0..refs { let r = lo + step * k as f32; let mut m = Plane { w: u.w, h: u.h, v: u.v.clone() }; - par_rows(&mut m.v, u.w, 1, |_, row| { + rows(&mut m.v, u.w, |_, row| { for v in row.iter_mut() { *v = remap(*v, r); } }); let gr = gaussian(m, n); for l in 0..n - 1 { - let coarse = up(&gr[l + 1], gr[l].w, gr[l].h); - let (gl, fine, lw) = (&g[l].v, &gr[l].v, g[l].w); - par_rows(&mut lap[l], lw, 1, |y, row| { + let (gl, fine, lw, lh, coarse) = (&g[l].v, &gr[l].v, g[l].w, g[l].h, &gr[l + 1]); + rows(&mut lap[l], lw, |y, row| { + let taps = up_rows(coarse, lh, y); for (x, o) in row.iter_mut().enumerate() { let i = y * lw + x; let wgt = (1.0 - (gl[i].clamp(lo, hi) - r).abs() / step).max(0.0); if wgt > 0.0 { - *o += wgt * (fine[i] - coarse.v[i]); + *o += wgt * (fine[i] - up_at(coarse, lw, &taps, x)); } } }); @@ -188,8 +277,10 @@ fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane { /// The `q` quantile (0 … 1) of `v`. fn quantile(v: &[f32], q: f32) -> f32 { let mut s = v.to_vec(); - s.sort_by(f32::total_cmp); - s[((s.len() - 1) as f32 * q).round() as usize] + // Selecting the one element is linear, a full sort is not (5 sorts of the work copy were a + // fifteenth of a render). `total_cmp` ties are bit-identical, so it is the sorted element. + let i = ((s.len() - 1) as f32 * q).round() as usize; + *s.select_nth_unstable_by(i, f32::total_cmp).1 } /// 1st and 99th percentiles of the log luminance on a copy at most 256 pixels across. @@ -337,6 +428,84 @@ mod tests { const SRGB: Encoding = Encoding(0.0); + /// The plain blur: a `mirror` per tap over the whole plane, the reference for [`blur_step`]. + fn blur_step_reference(p: &Plane, step: usize) -> Plane { + let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step)); + let mut tmp = vec![0.0f32; p.w * h2]; + for y2 in 0..h2 { + for x in 0..p.w { + tmp[y2 * p.w + x] = (0..5).map(|k| TAPS[k] * p.v[mirror((y2 * step) as isize + k as isize - 2, p.h) * p.w + x]).sum(); + } + } + let mut out = vec![0.0f32; w2 * h2]; + for y2 in 0..h2 { + for x2 in 0..w2 { + out[y2 * w2 + x2] = (0..5).map(|k| TAPS[k] * tmp[y2 * p.w + mirror((x2 * step) as isize + k as isize - 2, p.w)]).sum(); + } + } + Plane { w: w2, h: h2, v: out } + } + + /// The plain upsampling: a zero-stuffed plane blurred whole, the reference for [`up`]. + fn up_reference(p: &Plane, w: usize, h: usize) -> Plane { + let mut z = Plane { w, h, v: vec![0.0; w * h] }; + for y in 0..p.h.min(h.div_ceil(2)) { + for x in 0..p.w.min(w.div_ceil(2)) { + z.v[2 * y * w + 2 * x] = p.v[y * p.w + x] * 4.0; + } + } + blur_step_reference(&z, 1) + } + + fn noise_plane(w: usize, h: usize, seed: u32) -> Plane { + let mut s = seed.wrapping_mul(2_654_435_761).max(1); + let v = (0..w * h) + .map(|_| { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s % 20_000) as f32 / 1000.0 - 16.0 + }) + .collect(); + Plane { w, h, v } + } + + #[test] + fn the_fast_pyramid_matches_the_plain_one_exactly() { + // Odd, even, tiny and large-enough-to-run-in-parallel sizes, as the pyramid's levels are. + for (i, (w, h)) in [(1, 1), (1, 7), (2, 2), (3, 5), (5, 3), (8, 6), (37, 23), (64, 64), (301, 211)].into_iter().enumerate() { + let p = noise_plane(w, h, i as u32 + 1); + for step in [1, 2] { + assert_eq!(blur_step(&p, step).v, blur_step_reference(&p, step).v, "blur {w}×{h} step {step}"); + } + for (uw, uh) in [(w * 2, h * 2), (w * 2 - 1, h * 2 - 1), (w * 2, h * 2 - 1), (w.max(2) * 2 - 3, h * 2)] { + let full = up(&p, uw, uh); + assert_eq!(full.v, up_reference(&p, uw, uh).v, "up {w}×{h} → {uw}×{uh}"); + // The filter samples `up` one pixel at a time; every sample has the same bits. + for y in 0..uh { + let taps = up_rows(&p, uh, y); + for x in 0..uw { + assert_eq!(up_at(&p, uw, &taps, x).to_bits(), full.v[y * uw + x].to_bits(), "up_at {w}×{h} → {uw}×{uh} at {x},{y}"); + } + } + } + } + } + + #[test] + fn quantile_is_the_sorted_element() { + let p = noise_plane(301, 211, 9); + let mut v = p.v.clone(); + // Ties and signed zeros, which `total_cmp` orders by their bits. + v.extend([0.0, -0.0, 0.0, -0.0, 3.5, 3.5, f32::MIN_POSITIVE]); + let mut sorted = v.clone(); + sorted.sort_by(f32::total_cmp); + for q in [0.0, 0.001, 0.01, 0.25, 0.5, 0.99, 1.0] { + let want = sorted[((sorted.len() - 1) as f32 * q).round() as usize]; + assert_eq!(quantile(&v, q).to_bits(), want.to_bits(), "q {q}"); + } + } + fn grey(w: usize, h: usize, f: impl Fn(usize, usize) -> f32) -> Vec<[f32; 4]> { (0..w * h).map(|i| f(i % w, i / w)).map(|v| [v, v, v, 1.0]).collect() } diff --git a/crates/algo/src/camera_raw/whites_blacks.rs b/crates/algo/src/camera_raw/whites_blacks.rs index 382ade50e9..93bb9cff31 100644 --- a/crates/algo/src/camera_raw/whites_blacks.rs +++ b/crates/algo/src/camera_raw/whites_blacks.rs @@ -369,14 +369,14 @@ pub(crate) fn apply(px: &mut [[f32; 4]], width: usize, w: f32, b: f32, enc: Enco if per_channel { for c in 0..3 { let over = (lin[c] - 1.0).max(0.0); - q[c] = enc.encode(super::srgb_decode(grey(super::srgb_encode(lin[c].min(1.0)))) + over); + q[c] = enc.encode(super::srgb_to_linear(grey(super::linear_to_srgb(lin[c].min(1.0)))) + over); } } else { let y = super::luma_linear(lin).max(0.0); if y <= 1e-7 { continue; } - let y2 = super::srgb_decode(grey(super::srgb_encode(y.min(1.0)))) + (y - 1.0).max(0.0); + let y2 = super::srgb_to_linear(grey(super::linear_to_srgb(y.min(1.0)))) + (y - 1.0).max(0.0); let k = y2 / y; for c in 0..3 { q[c] = enc.encode(lin[c] * k); diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs index 76880cd5ad..981e854cc5 100644 --- a/crates/algo/src/content_aware.rs +++ b/crates/algo/src/content_aware.rs @@ -566,6 +566,133 @@ pub fn level_transform(ch: usize, from: &[f32], to: &[f32], a: Adapt) -> Vec<(f3 .collect() } +/// One stroke of the Content-Aware Fill workspace's Sampling Brush: a hard round brush of +/// diameter `size` along `points` (document px), adding to the sampling area or taking from it. +#[derive(Clone, Debug, PartialEq)] +pub struct SamplingStroke { + pub add: bool, + pub size: f64, + pub points: Vec<[f64; 2]>, +} + +impl SamplingStroke { + /// Bounds of the pixels the stroke covers. + pub fn bounds(&self) -> Rect { + let r = (self.size / 2.0).max(0.5); + self.points.iter().fold(Rect::EMPTY, |acc, p| { + let b = Rect::new( + (p[0] - r).floor() as i32, + (p[1] - r).floor() as i32, + ((p[0] + r).ceil() as i32).saturating_add(1), + ((p[1] + r).ceil() as i32).saturating_add(1), + ); + if acc.is_empty() { b } else { acc.union(&b) } + }) + } +} + +/// Squared distance from `p` to the segment `a`–`b`. +fn seg_dist2(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 { + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let l2 = dx * dx + dy * dy; + let t = if l2 > 0.0 { (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let (qx, qy) = (a[0] + t * dx - p[0], a[1] + t * dy - p[1]); + qx * qx + qy * qy +} + +/// Paint `strokes` in order into `mask` (row-major over `area`): a pixel whose centre lies within +/// half the brush size of a stroke's path is set (adding) or cleared (subtracting). A mask that +/// does not cover `area` exactly is left as it is. +pub fn paint_strokes(mask: &mut [bool], area: Rect, strokes: &[SamplingStroke]) { + let w = area.width() as usize; + if mask.len() != w * area.height() as usize { + return; + } + for s in strokes { + let r = (s.size / 2.0).max(0.5); + let r2 = r.powi(2); + let segs: Vec<([f64; 2], [f64; 2])> = match s.points.as_slice() { + [] => continue, + [p] => vec![(*p, *p)], + pts => pts.windows(2).map(|p| (p[0], p[1])).collect(), + }; + // A stroke covers the union of its segments' pixels: each segment only looks at its own + // bounds. + for (a, b) in segs { + let bounds = Rect::new( + (a[0].min(b[0]) - r).floor() as i32, + (a[1].min(b[1]) - r).floor() as i32, + ((a[0].max(b[0]) + r).ceil() as i32).saturating_add(1), + ((a[1].max(b[1]) + r).ceil() as i32).saturating_add(1), + ) + .intersect(&area); + for y in bounds.y0..bounds.y1 { + for x in bounds.x0..bounds.x1 { + let c = [f64::from(x) + 0.5, f64::from(y) + 0.5]; + if seg_dist2(c, a, b) <= r2 + && let Some(m) = mask.get_mut((y - area.y0) as usize * w + (x - area.x0) as usize) + { + *m = s.add; + } + } + } + } + } +} + +/// The pixels of `area` (row-major) whose centres lie inside the polygon `pts` (even-odd rule): +/// what a lasso outlines. +pub fn polygon_mask(area: Rect, pts: &[[f64; 2]]) -> Vec { + let (w, h) = (area.width() as usize, area.height() as usize); + let mut out = vec![false; w * h]; + if pts.len() < 3 { + return out; + } + let mut xs: Vec = Vec::new(); + for row in 0..h { + let cy = f64::from(area.y0) + row as f64 + 0.5; + xs.clear(); + for i in 0..pts.len() { + let (a, b) = (pts[i], pts[(i + 1) % pts.len()]); + if (a[1] <= cy) != (b[1] <= cy) { + xs.push(a[0] + (cy - a[1]) / (b[1] - a[1]) * (b[0] - a[0])); + } + } + xs.sort_by(f64::total_cmp); + for pair in xs.as_chunks::<2>().0 { + // Pixel centres x + 0.5 within [pair0, pair1). + let x0 = ((pair[0] - 0.5).ceil() as i64 - i64::from(area.x0)).clamp(0, w as i64) as usize; + let x1 = ((pair[1] - 0.5).ceil() as i64 - i64::from(area.x0)).clamp(0, w as i64) as usize; + out[row * w + x0..row * w + x1.max(x0)].iter_mut().for_each(|v| *v = true); + } + } + out +} + +/// Grow (`by` > 0) or shrink (`by` < 0) a mask by `|by|` pixels (Euclidean): the lasso's Expand +/// and Contract. +pub fn grow_mask(mask: &[bool], w: usize, h: usize, by: i32) -> Vec { + if by == 0 || w == 0 || h == 0 { + return mask.to_vec(); + } + let r = f32::from(u16::try_from(by.unsigned_abs()).unwrap_or(u16::MAX)); + if by > 0 { + let d = crate::selection::edt(mask, w, h); + d.iter().map(|v| *v <= r).collect() + } else { + let outside: Vec = mask.iter().map(|v| !v).collect(); + let d = crate::selection::edt(&outside, w, h); + d.iter().map(|v| *v > r).collect() + } +} + +/// The Sampling Brush's starting size for a selection with bounds `hole`: a tenth of the sampling +/// window's side, as Photoshop opens the workspace (20 px for a 50 px selection, 40 for 100). +pub fn default_brush_size(hole: Rect) -> f64 { + let (w, h) = (f64::from(hole.width().max(50)), f64::from(hole.height().max(50))); + (0.4 * (w * h).sqrt()).round() +} + #[cfg(test)] mod tests { use super::*; @@ -577,6 +704,43 @@ mod tests { (img, hole) } + #[test] + fn strokes_paint_their_path_and_leave_a_mismatched_mask_alone() { + let area = Rect::new(10, 20, 50, 40); + let (w, h) = (40, 20); + let strokes = [ + SamplingStroke { add: true, size: 6.0, points: vec![[12.0, 25.0], [40.0, 25.0], [45.0, 35.0]] }, + SamplingStroke { add: false, size: 3.0, points: vec![[30.0, 25.0]] }, + SamplingStroke { add: true, size: 2.0, points: Vec::new() }, + ]; + let mut mask = vec![false; w * h]; + paint_strokes(&mut mask, area, &strokes); + // The same pixels as testing every pixel against every segment of each stroke in turn. + let mut want = vec![false; w * h]; + for s in &strokes { + let r2 = (s.size / 2.0).max(0.5).powi(2); + let segs: Vec<_> = if s.points.len() == 1 { vec![(s.points[0], s.points[0])] } else { s.points.windows(2).map(|p| (p[0], p[1])).collect() }; + for (i, m) in want.iter_mut().enumerate() { + let c = [f64::from(area.x0) + (i % w) as f64 + 0.5, f64::from(area.y0) + (i / w) as f64 + 0.5]; + if segs.iter().any(|(a, b)| seg_dist2(c, *a, *b) <= r2) { + *m = s.add; + } + } + } + assert_eq!(mask, want); + assert!(mask[5 * w + 10] && !mask[5 * w + 20], "added along the path, cleared under the subtracting dab"); + // A mask shorter or longer than the area is not touched (and nothing panics). + for len in [0, 7, w * h - 1, w * h + 3] { + let mut short = vec![false; len]; + paint_strokes(&mut short, area, &strokes); + assert!(short.iter().all(|v| !v), "len {len}"); + } + // Hostile coordinates stay inside the area. + let mut m = vec![false; w * h]; + let wild = [SamplingStroke { add: true, size: 5000.0, points: vec![[f64::MAX, -1e300], [f64::NAN, 1e7]] }]; + paint_strokes(&mut m, area, &wild); + } + #[test] fn cancelled_fill_stops_and_progress_reaches_one() { use std::sync::atomic::{AtomicU32, Ordering}; diff --git a/crates/algo/src/distort.rs b/crates/algo/src/distort.rs index 664169afa4..fb6e3e69c3 100644 --- a/crates/algo/src/distort.rs +++ b/crates/algo/src/distort.rs @@ -28,32 +28,47 @@ pub(crate) fn centre(b: Rect) -> (f32, f32, f32) { (b.x0 as f32 + w / 2.0, b.y0 as f32 + h / 2.0, w.min(h) / 2.0) } +/// The bounds' centre and half width and height: Twirl, Pinch and Spherize act inside the ellipse +/// inscribed in the bounds, as Photoshop's do, so on a wide or tall image the effect reaches all +/// four edges instead of stopping at a circle fitted to the shorter side (#5643). A point maps to +/// unit-circle coordinates `(u, v)` and back. +fn ellipse(b: Rect) -> (f32, f32, f32, f32) { + let (w, h) = (b.width() as f32, b.height() as f32); + (b.x0 as f32 + w / 2.0, b.y0 as f32 + h / 2.0, w / 2.0, h / 2.0) +} + pub(crate) fn twirl(src: &Image, out: Rect, ctx: &Ctx, angle: f32) -> Vec { - let (cx, cy, rr) = centre(ctx.bounds); + let (cx, cy, hx, hy) = ellipse(ctx.bounds); let a = angle.to_radians(); remap(src, out, ctx, Edge::Repeat, |x, y| { - let (dx, dy) = (x - cx, y - cy); - let r = (dx * dx + dy * dy).sqrt(); - if r >= rr || rr <= 0.0 { + if hx <= 0.0 || hy <= 0.0 { return (x, y); } - let t = a * (1.0 - r / rr); + let (u, v) = ((x - cx) / hx, (y - cy) / hy); + let r = (u * u + v * v).sqrt(); + if r >= 1.0 { + return (x, y); + } + let t = a * (1.0 - r); let (s, c) = t.sin_cos(); - (cx + dx * c - dy * s, cy + dx * s + dy * c) + (cx + (u * c - v * s) * hx, cy + (u * s + v * c) * hy) }) } pub(crate) fn pinch(src: &Image, out: Rect, ctx: &Ctx, amount: f32) -> Vec { - let (cx, cy, rr) = centre(ctx.bounds); + let (cx, cy, hx, hy) = ellipse(ctx.bounds); let a = (amount / 100.0).clamp(-1.0, 1.0); remap(src, out, ctx, Edge::Repeat, |x, y| { - let (dx, dy) = (x - cx, y - cy); - let r = (dx * dx + dy * dy).sqrt(); - if r >= rr || r <= 0.0 { + if hx <= 0.0 || hy <= 0.0 { return (x, y); } - let rs = rr * (r / rr).powf(1.0 - a * 0.5); - (cx + dx * rs / r, cy + dy * rs / r) + let (u, v) = ((x - cx) / hx, (y - cy) / hy); + let r = (u * u + v * v).sqrt(); + if r >= 1.0 || r <= 0.0 { + return (x, y); + } + let k = r.powf(1.0 - a * 0.5) / r; + (cx + u * k * hx, cy + v * k * hy) }) } @@ -64,20 +79,22 @@ fn sphere_1d(rn: f32, a: f32) -> f32 { } pub(crate) fn spherize(src: &Image, out: Rect, ctx: &Ctx, amount: f32, mode: SpherizeMode) -> Vec { - let b = ctx.bounds; - let (cx, cy, rr) = centre(b); - let (hx, hy) = (b.width() as f32 / 2.0, b.height() as f32 / 2.0); + let (cx, cy, hx, hy) = ellipse(ctx.bounds); let a = (amount / 100.0).clamp(-1.0, 1.0); remap(src, out, ctx, Edge::Repeat, |x, y| { let (dx, dy) = (x - cx, y - cy); match mode { SpherizeMode::Normal => { - let r = (dx * dx + dy * dy).sqrt(); - if r >= rr || r <= 0.0 { + if hx <= 0.0 || hy <= 0.0 { return (x, y); } - let rs = rr * sphere_1d(r / rr, a); - (cx + dx * rs / r, cy + dy * rs / r) + let (u, v) = (dx / hx, dy / hy); + let r = (u * u + v * v).sqrt(); + if r >= 1.0 || r <= 0.0 { + return (x, y); + } + let k = sphere_1d(r, a) / r; + (cx + u * k * hx, cy + v * k * hy) } SpherizeMode::HorizontalOnly => { if dx.abs() >= hx { diff --git a/crates/algo/src/faces.rs b/crates/algo/src/faces.rs new file mode 100644 index 0000000000..aa246fcaf8 --- /dev/null +++ b/crates/algo/src/faces.rs @@ -0,0 +1,90 @@ +//! Face detection: a port of libfacedetection's CNN (Shiqi Yu, BSD-3; `data/LICENSE-libfacedetection.txt`). +//! +//! The network is the YuNet design: a backbone of 1×1 pointwise and 3×3 depthwise convolutions with +//! 2×2 max pooling, a feature pyramid at strides 8, 16 and 32, and per-cell heads for the face score, +//! the box and five landmarks (eyes, nose tip, mouth corners). The weights (`data/libfacedetection.bin`, +//! converted to half precision from the library's `facedetectcnn-data.cpp`) are about 100 KB, and +//! inference is plain Rust: no runtime, so it works offline. +//! +//! [`detect`] takes straight RGBA in `0..=1` and returns faces in pixel coordinates of that image. +//! +//! The browser build (wasm32) leaves the network and its weights out, as `photocraft-raw` does with +//! its JPEG XL decoder: they would push the wasm over the per-file cap of static hosts +//! (packaging/web/package.sh). There [`AVAILABLE`] is false and [`detect`] finds nothing. + +#[cfg(not(target_arch = "wasm32"))] +mod cnn; + +/// Whether this build can detect faces (not the browser build: see the module docs). +pub const AVAILABLE: bool = cfg!(not(target_arch = "wasm32")); + +/// Longest side the network looks at; larger images are scaled down first (faces smaller than +/// about 10 px at this scale are missed). +pub const MAX_SIDE: usize = 1280; + +/// One detected face, in pixels of the image passed to [`detect`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Face { + /// Confidence `0..=1` (the library reports faces above 0.5 as reliable). + pub score: f32, + /// Left, top, width and height. + pub rect: [f32; 4], + /// Right eye, left eye (as seen in the image: the first is on the image's left), nose tip, + /// right mouth corner, left mouth corner. + pub landmarks: [[f32; 2]; 5], +} + +/// Faces in `px` (straight RGBA `0..=1`, `w × h`, row-major) scoring at least `min_score`, best +/// first. Transparent pixels count as white. `None` when `px` doesn't match the size. +#[cfg(not(target_arch = "wasm32"))] +pub fn detect(px: &[[f32; 4]], w: usize, h: usize, min_score: f32) -> Option> { + if w == 0 || h == 0 || px.len() != w.checked_mul(h)? { + return None; + } + // Scale down (box filter) so the longer side is at most MAX_SIDE. + let step = w.max(h).div_ceil(MAX_SIDE).max(1); + let (sw, sh) = (w.div_ceil(step), h.div_ceil(step)); + let mut bgr = vec![[0.0f32; 3]; sw * sh]; + for y in 0..sh { + for x in 0..sw { + let (mut acc, mut n) = ([0.0f32; 3], 0.0f32); + for yy in y * step..((y + 1) * step).min(h) { + for xx in x * step..((x + 1) * step).min(w) { + let [r, g, b, a] = px[yy * w + xx]; + let a = a.clamp(0.0, 1.0); + for (k, v) in [b, g, r].into_iter().enumerate() { + acc[k] += v.clamp(0.0, 1.0) * a + (1.0 - a); + } + n += 1.0; + } + } + bgr[y * sw + x] = acc.map(|v| (v / n.max(1.0) * 255.0).round()); + } + } + let s = step as f32; + let faces = cnn::network(&bgr, sw, sh)? + .into_iter() + .filter(|f| f.score >= min_score) + .map(|f| Face { score: f.score, rect: f.rect.map(|v| v * s), landmarks: f.landmarks.map(|[x, y]| [x * s, y * s]) }) + .collect(); + Some(faces) +} + +/// The browser build has no detector (see the module docs): always `None`. +#[cfg(target_arch = "wasm32")] +pub fn detect(_px: &[[f32; 4]], _w: usize, _h: usize, _min_score: f32) -> Option> { + None +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + #[test] + fn no_faces_in_flat_or_tiny_images_and_bad_sizes_are_refused() { + assert_eq!(detect(&vec![[0.5, 0.5, 0.5, 1.0]; 64 * 48], 64, 48, 0.5), Some(vec![])); + assert_eq!(detect(&[[1.0, 1.0, 1.0, 1.0]], 1, 1, 0.5), Some(vec![])); + assert_eq!(detect(&[[1.0; 4]; 3], 2, 2, 0.5), None); + assert_eq!(detect(&[], 0, 0, 0.5), None); + } +} diff --git a/crates/algo/src/faces/cnn.rs b/crates/algo/src/faces/cnn.rs new file mode 100644 index 0000000000..b86cac7eb2 --- /dev/null +++ b/crates/algo/src/faces/cnn.rs @@ -0,0 +1,323 @@ +//! The network itself (native builds only: see the parent module's docs). + +use super::Face; +use crate::par; + +/// The weights: `PCFACE1\0`, the layer count (u16), then per layer its input channels (u16), filters +/// (u16) and kind (u8: 0 pointwise, 1 depthwise), the weights and the biases, all little-endian f16. +static WEIGHTS: &[u8] = include_bytes!("../../data/libfacedetection.bin"); + +const MAGIC: &[u8] = b"PCFACE1\0"; +const LAYERS: usize = 53; +/// Faces whose boxes overlap more than this (intersection over union) are one face. +const NMS_OVERLAP: f32 = 0.45; +/// Candidates kept before non-maximum suppression, as the library does. +const TOP_K: usize = 1000; + +struct Layer { + channels: usize, + filters: usize, + depthwise: bool, + weights: Vec, + biases: Vec, +} + +/// A feature map: `rows × cols` cells of `channels` values each. +#[derive(Clone)] +struct Blob { + rows: usize, + cols: usize, + channels: usize, + data: Vec, +} + +impl Blob { + fn new(rows: usize, cols: usize, channels: usize) -> Self { + Blob { rows, cols, channels, data: vec![0.0; rows * cols * channels] } + } +} + +fn f16_to_f32(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let exp = i32::from((h >> 10) & 0x1f); + let frac = f32::from(h & 0x3ff); + match exp { + 0 => sign * frac * (2.0f32).powi(-24), + 31 => { + if frac == 0.0 { + sign * f32::INFINITY + } else { + f32::NAN + } + } + _ => sign * (1.0 + frac / 1024.0) * (2.0f32).powi(exp - 15), + } +} + +fn parse(bytes: &[u8]) -> Option> { + let rest = bytes.strip_prefix(MAGIC)?; + let mut at = 0usize; + let u16_at = |n: &mut usize| -> Option { + let b = rest.get(*n..*n + 2)?; + *n += 2; + Some(u16::from_le_bytes([b[0], b[1]])) + }; + let count = usize::from(u16_at(&mut at)?); + if count != LAYERS { + return None; + } + let mut layers = Vec::with_capacity(count); + for _ in 0..count { + let channels = usize::from(u16_at(&mut at)?); + let filters = usize::from(u16_at(&mut at)?); + let depthwise = *rest.get(at)? == 1; + at += 1; + let nw = if depthwise { 9 * channels } else { filters * channels }; + let mut read = |n: usize| -> Option> { (0..n).map(|_| u16_at(&mut at).map(f16_to_f32)).collect() }; + let weights = read(nw)?; + let biases = read(filters)?; + if depthwise && filters != channels { + return None; + } + layers.push(Layer { channels, filters, depthwise, weights, biases }); + } + (at == rest.len()).then_some(layers) +} + +/// A 1×1 or 3×3 depthwise convolution with bias, then ReLU when `relu`. +fn conv(x: &Blob, l: &Layer, relu: bool) -> Option { + if x.channels != l.channels { + return None; + } + let mut out = Blob::new(x.rows, x.cols, l.filters); + let (rows, cols, cin, cout) = (x.rows, x.cols, x.channels, l.filters); + par::chunks_mut(&mut out.data, cols * cout, rows * cols * cout > 1 << 16, |row, line| { + for col in 0..cols { + let o = &mut line[col * cout..(col + 1) * cout]; + if l.depthwise { + o.copy_from_slice(&l.biases); + for r in row.saturating_sub(1)..(row + 2).min(rows) { + for c in col.saturating_sub(1)..(col + 2).min(cols) { + let k = (r + 1 - row) * 3 + (c + 1 - col); + let input = &x.data[(r * cols + c) * cin..(r * cols + c + 1) * cin]; + let w = &l.weights[k * cin..(k + 1) * cin]; + for ((o, i), w) in o.iter_mut().zip(input).zip(w) { + *o += i * w; + } + } + } + } else { + let input = &x.data[(row * cols + col) * cin..(row * cols + col + 1) * cin]; + for (f, o) in o.iter_mut().enumerate() { + let w = &l.weights[f * cin..(f + 1) * cin]; + *o = l.biases[f] + input.iter().zip(w).map(|(i, w)| i * w).sum::(); + } + } + if relu { + for v in o.iter_mut() { + *v = v.max(0.0); + } + } + } + }); + Some(out) +} + +/// Pointwise then depthwise (ReLU after the depthwise one when `relu`). +fn conv_dp(x: &Blob, p: &Layer, d: &Layer, relu: bool) -> Option { + conv(&conv(x, p, false)?, d, relu) +} + +fn unit(x: &Blob, l: &[Layer]) -> Option { + let [p1, d1, p2, d2] = l else { return None }; + conv_dp(&conv_dp(x, p1, d1, true)?, p2, d2, true) +} + +fn max_pool(x: &Blob) -> Blob { + let rows = x.rows.saturating_sub(3).div_ceil(2) + 1; + let cols = x.cols.saturating_sub(3).div_ceil(2) + 1; + let mut out = Blob::new(rows, cols, x.channels); + for r in 0..rows { + for c in 0..cols { + let o = (r * cols + c) * x.channels; + for ch in 0..x.channels { + let mut m = f32::NEG_INFINITY; + for rr in r * 2..(r * 2 + 2).min(x.rows) { + for cc in c * 2..(c * 2 + 2).min(x.cols) { + m = m.max(x.data[(rr * x.cols + cc) * x.channels + ch]); + } + } + out.data[o + ch] = m; + } + } + } + out +} + +/// `small` upsampled ×2 (nearest) plus `big`. +fn up_add(small: &Blob, big: &Blob) -> Option { + if small.rows * 2 != big.rows || small.cols * 2 != big.cols || small.channels != big.channels { + return None; + } + let mut out = big.clone(); + let ch = big.channels; + for r in 0..big.rows { + for c in 0..big.cols { + let s = ((r / 2) * small.cols + c / 2) * ch; + let o = (r * big.cols + c) * ch; + for k in 0..ch { + out.data[o + k] += small.data[s + k]; + } + } + } + Some(out) +} + +/// The network's input: each cell holds the 3×3 neighbourhood (stride 2) of BGR values `0..=255`, +/// so the first, 3×3 stride-2 convolution is a pointwise one. The size is padded to 32. +fn input(bgr: &[[f32; 3]], w: usize, h: usize) -> Blob { + let rows = h.div_ceil(32) * 16; + let cols = w.div_ceil(32) * 16; + let mut b = Blob::new(rows, cols, 32); + for r in 0..rows { + for c in 0..cols { + let cell = (r * cols + c) * 32; + for fy in 0..3 { + let Some(y) = (r * 2 + fy).checked_sub(1).filter(|&y| y < h) else { continue }; + for fx in 0..3 { + let Some(x) = (c * 2 + fx).checked_sub(1).filter(|&x| x < w) else { continue }; + let o = cell + (fy * 3 + fx) * 3; + b.data[o..o + 3].copy_from_slice(&bgr[y * w + x]); + } + } + } + } + b +} + +/// The heads of one pyramid level, decoded to candidate faces (in network pixels). +fn candidates(feat: &Blob, l: &[Layer], heads: [usize; 4], stride: f32, out: &mut Vec) -> Option<()> { + let head = |i: usize| conv_dp(feat, l.get(i)?, l.get(i + 1)?, false); + let (cls, reg, obj, kps) = (head(heads[0])?, head(heads[1])?, head(heads[2])?, head(heads[3])?); + if cls.channels != 1 || obj.channels != 1 || reg.channels != 4 || kps.channels != 10 { + return None; + } + let sigmoid = |v: f32| 1.0 / (1.0 + (-v.clamp(-88.0, 88.0)).exp()); + for r in 0..feat.rows { + for c in 0..feat.cols { + let i = r * feat.cols + c; + let score = (sigmoid(cls.data[i]) * sigmoid(obj.data[i])).sqrt(); + if score < 0.2 { + continue; + } + let (px, py) = (c as f32 * stride, r as f32 * stride); + let b = ®.data[i * 4..i * 4 + 4]; + let (cx, cy) = (b[0] * stride + px, b[1] * stride + py); + let (bw, bh) = (b[2].exp() * stride, b[3].exp() * stride); + let k = &kps.data[i * 10..i * 10 + 10]; + let mut landmarks = [[0.0; 2]; 5]; + for (n, lm) in landmarks.iter_mut().enumerate() { + *lm = [k[2 * n] * stride + px, k[2 * n + 1] * stride + py]; + } + out.push(Face { score, rect: [cx - bw / 2.0, cy - bh / 2.0, bw, bh], landmarks }); + } + } + Some(()) +} + +fn iou(a: &[f32; 4], b: &[f32; 4]) -> f32 { + let w = ((a[0] + a[2]).min(b[0] + b[2]) - a[0].max(b[0])).max(0.0); + let h = ((a[1] + a[3]).min(b[1] + b[3]) - a[1].max(b[1])).max(0.0); + let i = w * h; + if i <= 0.0 { 0.0 } else { i / (a[2] * a[3] + b[2] * b[3] - i) } +} + +/// The heads (cls, reg, obj, kps: their first layer) of the stride 8, 16 and 32 levels. +const HEADS: [[usize; 4]; 3] = [[29, 35, 41, 47], [31, 37, 43, 49], [33, 39, 45, 51]]; + +/// The backbone and feature pyramid: the stride 8, 16 and 32 feature maps the heads read. +fn features(bgr: &[[f32; 3]], w: usize, h: usize, l: &[Layer]) -> Option<[Blob; 3]> { + let x = conv(&input(bgr, w, h), l.first()?, true)?; + let x = max_pool(&conv_dp(&x, l.get(1)?, l.get(2)?, true)?); + let x = unit(&unit(&x, l.get(3..7)?)?, l.get(7..11)?)?; + let f8 = unit(&max_pool(&x), l.get(11..15)?)?; + let f16 = unit(&max_pool(&f8), l.get(15..19)?)?; + let f32_ = unit(&max_pool(&f16), l.get(19..23)?)?; + let f32_ = conv_dp(&f32_, l.get(27)?, l.get(28)?, true)?; + let f16 = conv_dp(&up_add(&f32_, &f16)?, l.get(25)?, l.get(26)?, true)?; + let f8 = conv_dp(&up_add(&f16, &f8)?, l.get(23)?, l.get(24)?, true)?; + Some([f8, f16, f32_]) +} + +pub(super) fn network(bgr: &[[f32; 3]], w: usize, h: usize) -> Option> { + let l = parse(WEIGHTS)?; + let levels = features(bgr, w, h, &l)?; + let mut faces = Vec::new(); + // Heads (cls, reg, obj, kps) per level, as in the library's model. + for ((feat, heads), stride) in levels.iter().zip(HEADS).zip([8.0, 16.0, 32.0]) { + candidates(feat, &l, heads, stride, &mut faces)?; + } + faces.sort_by(|a, b| b.score.total_cmp(&a.score)); + faces.truncate(TOP_K); + let mut kept: Vec = Vec::new(); + for f in faces { + if kept.iter().all(|k| iou(&k.rect, &f.rect) <= NMS_OVERLAP) { + kept.push(f); + } + } + Some(kept) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn weights_parse() { + let l = parse(WEIGHTS).expect("bundled weights"); + assert_eq!(l.len(), LAYERS); + assert_eq!((l[0].channels, l[0].filters, l[0].depthwise), (32, 16, false)); + assert_eq!((l[2].channels, l[2].filters, l[2].depthwise), (16, 16, true)); + assert!(l.iter().all(|l| l.weights.iter().chain(&l.biases).all(|v| v.is_finite()))); + // Damaged weights are refused, not read past their end. + assert!(parse(&WEIGHTS[..WEIGHTS.len() - 1]).is_none()); + assert!(parse(b"nope").is_none()); + } + + /// The sum of every head's raw output on a fixed test image matches libfacedetection's own C++ + /// (computed with its f32 weights; ours are f16, hence the tolerance). + #[test] + fn heads_match_the_reference_implementation() { + let (w, h) = (96usize, 72usize); + let bgr: Vec<[f32; 3]> = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let (r, g, b) = ((x * 7 + y * 3) % 256, (x * x + y * 5) % 256, (x * y * 3 + 11) % 256); + [b as f32, g as f32, r as f32] + }) + .collect(); + let l = parse(WEIGHTS).unwrap(); + let levels = features(&bgr, w, h, &l).unwrap(); + let reference = + [27.647039, 549.579923, -1645.299678, 914.784787, -6.149318, 35.705980, -454.742148, 163.847111, 1.267630, 28.415509, -85.662257, 62.294208]; + let mut got = Vec::new(); + for (feat, heads) in levels.iter().zip(HEADS) { + for first in heads { + let o = conv_dp(feat, &l[first], &l[first + 1], false).unwrap(); + got.push(o.data.iter().map(|&v| f64::from(v)).sum::()); + } + } + for (g, r) in got.iter().zip(reference) { + assert!((g - r).abs() <= 0.01 * r.abs().max(10.0), "{got:?}"); + } + } + + #[test] + fn f16_decoding() { + assert_eq!(f16_to_f32(0x3c00), 1.0); + assert_eq!(f16_to_f32(0xc000), -2.0); + assert_eq!(f16_to_f32(0x0000), 0.0); + assert_eq!(f16_to_f32(0x3555), 0.333_251_95); + assert_eq!(f16_to_f32(0x0001), 2.0f32.powi(-24)); + } +} diff --git a/crates/algo/src/features.rs b/crates/algo/src/features.rs index ab98de757e..80de7b993e 100644 --- a/crates/algo/src/features.rs +++ b/crates/algo/src/features.rs @@ -45,12 +45,9 @@ pub const PATCH_RADIUS: usize = 15; struct Rng(u64); impl Rng { + /// The next value of the SplitMix64 sequence. fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) + crate::photo_util::splitmix64(&mut self.0) } fn unit(&mut self) -> f64 { (self.next() >> 11) as f64 / (1u64 << 53) as f64 @@ -60,25 +57,98 @@ impl Rng { } } +/// Columns per band of the vertical blur pass: 64 f32 = 256 bytes = four cache lines per row, so +/// walking down a band touches whole lines, and the band's working set stays in cache. +const BLUR_BAND: usize = 64; + +/// Box blur of radius `r` (edges clamped): a running f32 sum along rows, then along columns. +/// +/// Both passes are parallel and give bit for bit what the one-line-at-a-time version gave: every +/// output sums its window in the same order. Rows are independent. For the column pass, the +/// image is cut into bands of columns; each column keeps its own f32 running sum, started from +/// its first window summed in order and updated in the same order, so only the loop nest changes +/// (the inner loop runs across a band's columns and vectorises), never any column's arithmetic. fn blur(w: usize, h: usize, v: &[f32], r: usize) -> Vec { - let pass = |src: &[f32], horizontal: bool| -> Vec { - let mut dst = vec![0.0f32; src.len()]; - let (n, m) = if horizontal { (h, w) } else { (w, h) }; - for line in 0..n { - let at = |k: i64| { - let k = k.clamp(0, m as i64 - 1) as usize; - if horizontal { src[line * w + k] } else { src[k * w + line] } - }; - let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum(); - for k in 0..m { - let i = if horizontal { line * w + k } else { k * w + line }; - dst[i] = acc / (2 * r + 1) as f32; - acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64); + if w == 0 || h == 0 { + return Vec::new(); + } + let den = (2 * r + 1) as f32; + let mut tmp = vec![0.0f32; w * h]; + par_rows(&mut tmp, w, |line, dst| { + let src = &v[line * w..(line + 1) * w]; + let at = |k: i64| src[k.clamp(0, w as i64 - 1) as usize]; + let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum(); + for (k, o) in dst.iter_mut().enumerate() { + *o = acc / den; + acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64); + } + }); + let mut dst = vec![0.0f32; w * h]; + // One list of row segments per band, each segment a `&mut` slice of `dst`: no `unsafe`. + let mut bands: Vec> = (0..w.div_ceil(BLUR_BAND)).map(|_| Vec::with_capacity(h)).collect(); + for row in dst.chunks_exact_mut(w) { + for (band, seg) in bands.iter_mut().zip(row.chunks_mut(BLUR_BAND)) { + band.push(seg); + } + } + let src = &tmp; + let run = |bi: usize, segs: &mut [&mut [f32]], acc: &mut Vec| { + let (x0, bw) = (bi * BLUR_BAND, segs.first().map_or(0, |s| s.len())); + let row = |k: i64| { + let o = (k.clamp(0, h as i64 - 1) as usize) * w + x0; + &src[o..o + bw] + }; + // The first window, summed in order from the same start as `Iterator::sum` uses. + acc.clear(); + acc.resize(bw, std::iter::empty::().sum()); + for k in -(r as i64)..=r as i64 { + for (t, &x) in acc.iter_mut().zip(row(k)) { + *t += x; + } + } + for (k, seg) in segs.iter_mut().enumerate() { + let (add, sub) = (row(k as i64 + r as i64 + 1), row(k as i64 - r as i64)); + for (((o, t), &p), &m) in seg.iter_mut().zip(acc.iter_mut()).zip(add).zip(sub) { + *o = *t / den; + *t += p - m; } } - dst }; - pass(&pass(v, true), false) + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + bands.into_par_iter().enumerate().for_each_init(Vec::new, |acc, (bi, mut segs)| run(bi, &mut segs, acc)); + } + #[cfg(target_arch = "wasm32")] + { + let mut acc = Vec::new(); + for (bi, mut segs) in bands.into_iter().enumerate() { + run(bi, &mut segs, &mut acc); + } + } + dst +} + +/// Runs `f(y, row)` over the `w`-wide rows of `buf`, in parallel on native targets. +fn par_rows(buf: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync + Send) { + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + buf.par_chunks_mut(w).enumerate().for_each(|(y, row)| f(y, row)); + } + #[cfg(target_arch = "wasm32")] + buf.chunks_mut(w).enumerate().for_each(|(y, row)| f(y, row)); +} + +/// [`par_rows`] over three row-aligned buffers in lockstep. +fn par_rows3(a: &mut [f32], b: &mut [f32], c: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32], &mut [f32], &mut [f32]) + Sync + Send) { + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + a.par_chunks_mut(w).zip(b.par_chunks_mut(w)).zip(c.par_chunks_mut(w)).enumerate().for_each(|(y, ((a, b), c))| f(y, a, b, c)); + } + #[cfg(target_arch = "wasm32")] + a.chunks_mut(w).zip(b.chunks_mut(w)).zip(c.chunks_mut(w)).enumerate().for_each(|(y, ((a, b), c))| f(y, a, b, c)); } /// Harris corners: at most `max` corners at least `min_dist` pixels apart, strongest first, @@ -88,28 +158,40 @@ pub fn harris(w: usize, h: usize, img: &[f32], max: usize, min_dist: f32, valid: return Vec::new(); } let (mut xx, mut yy, mut xy) = (vec![0.0f32; w * h], vec![0.0f32; w * h], vec![0.0f32; w * h]); - for y in 1..h - 1 { + // Rows are independent (each output pixel reads only `img`), so they run in parallel. + par_rows3(&mut xx, &mut yy, &mut xy, w, |y, xxr, yyr, xyr| { + if y == 0 || y + 1 == h { + return; + } for x in 1..w - 1 { let p = |dx: i64, dy: i64| img[((y as i64 + dy) as usize) * w + (x as i64 + dx) as usize]; // Sobel. let gx = (p(1, -1) + 2.0 * p(1, 0) + p(1, 1)) - (p(-1, -1) + 2.0 * p(-1, 0) + p(-1, 1)); let gy = (p(-1, 1) + 2.0 * p(0, 1) + p(1, 1)) - (p(-1, -1) + 2.0 * p(0, -1) + p(1, -1)); - let i = y * w + x; - xx[i] = gx * gx; - yy[i] = gy * gy; - xy[i] = gx * gy; + xxr[x] = gx * gx; + yyr[x] = gy * gy; + xyr[x] = gx * gy; } - } + }); // Two box passes approximate the Gaussian window. let (xx, yy, xy) = (blur(w, h, &blur(w, h, &xx, 1), 1), blur(w, h, &blur(w, h, &yy, 1), 1), blur(w, h, &blur(w, h, &xy, 1), 1)); - let r: Vec = (0..w * h).map(|i| xx[i] * yy[i] - xy[i] * xy[i] - 0.04 * (xx[i] + yy[i]).powi(2)).collect(); + let mut r = vec![0.0f32; w * h]; + par_rows(&mut r, w, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * w + x; + *o = xx[i] * yy[i] - xy[i] * xy[i] - 0.04 * (xx[i] + yy[i]).powi(2); + } + }); let peak = r.iter().copied().fold(0.0f32, f32::max); if peak <= 0.0 { return Vec::new(); } let m = PATCH_RADIUS + 1; - let mut cand: Vec = Vec::new(); - for y in m..h - m { + // Rows are scanned in parallel and joined in row order; the sort below fully orders the + // candidates anyway (score, then y, then x), so the order they arrive in cannot matter. + let rows = par_map((h - m).saturating_sub(m), |i| { + let y = m + i; + let mut found: Vec = Vec::new(); for x in m..w - m { let v = r[y * w + x]; if v < peak * 0.01 { @@ -125,9 +207,11 @@ pub fn harris(w: usize, h: usize, img: &[f32], max: usize, min_dist: f32, valid: continue; } } - cand.push(Corner { x: x as f32, y: y as f32, score: v }); + found.push(Corner { x: x as f32, y: y as f32, score: v }); } - } + found + }); + let mut cand: Vec = rows.into_iter().flatten().collect(); cand.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.y.total_cmp(&b.y)).then(a.x.total_cmp(&b.x))); // Minimum spacing via a coarse occupancy grid. let cell = min_dist.max(1.0); @@ -176,37 +260,37 @@ pub fn describe(w: usize, h: usize, img: &[f32], corners: &[Corner], upright: bo let (xi, yi) = ((x.round() as i64).clamp(0, w as i64 - 1) as usize, (y.round() as i64).clamp(0, h as i64 - 1) as usize); smooth[yi * w + xi] }; - corners - .iter() - .map(|c| { - let (s, co) = if upright { - (0.0, 1.0) - } else { - let (mut m10, mut m01) = (0.0f32, 0.0f32); - let r = PATCH_RADIUS as i64; - for dy in -r..=r { - for dx in -r..=r { - if dx * dx + dy * dy <= r * r { - let v = at(c.x + dx as f32, c.y + dy as f32); - m10 += dx as f32 * v; - m01 += dy as f32 * v; - } + // Every descriptor depends only on its own corner and the smoothed image: computed in + // parallel, kept in corner order. + par_map(corners.len(), |ci| { + let c = &corners[ci]; + let (s, co) = if upright { + (0.0, 1.0) + } else { + let (mut m10, mut m01) = (0.0f32, 0.0f32); + let r = PATCH_RADIUS as i64; + for dy in -r..=r { + for dx in -r..=r { + if dx * dx + dy * dy <= r * r { + let v = at(c.x + dx as f32, c.y + dy as f32); + m10 += dx as f32 * v; + m01 += dy as f32 * v; } } - m01.atan2(m10).sin_cos() - }; - let mut d = [0u64; 4]; - for (i, p) in pairs().iter().enumerate() { - let rot = |x: f32, y: f32| (c.x + x * co - y * s, c.y + x * s + y * co); - let (ax, ay) = rot(p[0], p[1]); - let (bx, by) = rot(p[2], p[3]); - if at(ax, ay) < at(bx, by) { - d[i / 64] |= 1 << (i % 64); - } } - d - }) - .collect() + m01.atan2(m10).sin_cos() + }; + let mut d = [0u64; 4]; + for (i, p) in pairs().iter().enumerate() { + let rot = |x: f32, y: f32| (c.x + x * co - y * s, c.y + x * s + y * co); + let (ax, ay) = rot(p[0], p[1]); + let (bx, by) = rot(p[2], p[3]); + if at(ax, ay) < at(bx, by) { + d[i / 64] |= 1 << (i % 64); + } + } + d + }) } pub fn hamming(a: &Descriptor, b: &Descriptor) -> u32 { @@ -560,3 +644,124 @@ mod tests { assert_eq!(hamming(&[0, 0, 0, 0], &[1, 3, 0, u64::MAX]), 67); } } + +/// The row / column-band parallel `blur`, `harris` and `describe` against the serial code they +/// replaced. Every output must stay bit for bit the same. +#[cfg(test)] +mod parallel_tests { + use super::*; + + /// The serial blur exactly as it was before the parallelisation. + fn ref_blur(w: usize, h: usize, v: &[f32], r: usize) -> Vec { + let pass = |src: &[f32], horizontal: bool| -> Vec { + let mut dst = vec![0.0f32; src.len()]; + let (n, m) = if horizontal { (h, w) } else { (w, h) }; + for line in 0..n { + let at = |k: i64| { + let k = k.clamp(0, m as i64 - 1) as usize; + if horizontal { src[line * w + k] } else { src[k * w + line] } + }; + let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum(); + for k in 0..m { + let i = if horizontal { line * w + k } else { k * w + line }; + dst[i] = acc / (2 * r + 1) as f32; + acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64); + } + } + dst + }; + pass(&pass(v, true), false) + } + + fn mix(mut z: u64) -> u64 { + z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// Integer-only data with negatives, signed zeros and large values, so a different order of + /// additions cannot hide. + fn noise(len: usize, seed: u64) -> Vec { + (0..len as u64) + .map(|i| { + let z = mix(seed.wrapping_mul(0x1234_5678_9ABC).wrapping_add(i)); + let v = (z >> 40) as f32 / 16_777_216.0; + match z & 31 { + 0 => -v, + 1 => -0.0, + 2 => v * 1000.0, + _ => v, + } + }) + .collect() + } + + /// Blocks of random brightness: lots of strong corners, no libm in the making. Only the + /// recorded-hash test below uses it, and that one is Linux x86_64 only. + #[cfg(all(target_os = "linux", target_arch = "x86_64"))] + fn blocks(w: usize, h: usize, seed: u64) -> Vec { + (0..w * h).map(|i| (mix(seed + ((i % w) / 8) as u64 * 4096 + ((i / w) / 8) as u64) >> 40) as f32 / 16_777_216.0).collect() + } + + #[cfg(all(target_os = "linux", target_arch = "x86_64"))] + fn fnv(parts: &[u64]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + for p in parts { + h ^= p; + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + h + } + + #[test] + fn blur_matches_the_serial_code() { + // Widths around the 64-column band (1 band, band + 1, several bands, a ragged last one), + // 1-wide and 1-high images, and radii 0, 1, 2, larger than the image. + let widths = [1usize, 2, 3, 31, 63, 64, 65, 127, 128, 129, 200]; + let heights = [1usize, 2, 3, 5, 17, 40]; + for (a, &w) in widths.iter().enumerate() { + for (b, &h) in heights.iter().enumerate() { + let v = noise(w * h, (a * 10 + b) as u64); + for r in [0usize, 1, 2, 3, 7, 50] { + let (got, want) = (blur(w, h, &v, r), ref_blur(w, h, &v, r)); + let (g, e): (Vec, Vec) = (got.iter().map(|x| x.to_bits()).collect(), want.iter().map(|x| x.to_bits()).collect()); + assert_eq!(g, e, "blur {w}x{h} r={r}"); + } + } + } + assert!(blur(0, 0, &[], 1).is_empty()); + } + + // `harris` and `describe` go through the platform's hypot / ln / cos / atan2 / sin_cos, so the + // hashes recorded from the old code only hold where those are the same functions. + #[cfg(all(target_os = "linux", target_arch = "x86_64"))] + #[test] + fn harris_and_describe_hashes_recorded_from_the_serial_code() { + // Sizes: a whole number of 64-column bands and a ragged one; with and without a validity mask. + for (w, h, max, md, want_corners, want_desc) in + [(211usize, 157usize, 300usize, 6.0f32, 0xeccc6928d3ae3b8cu64, 0xd1e6caae4d68f253u64), (128, 97, 60, 3.0, 0xe3f6615117fa7da7, 0x818ae7e965ecf88f)] + { + let img = blocks(w, h, 7); + let valid: Vec = (0..w * h).map(|i| !((i % w) > w / 2 && (i / w) < h / 3)).collect(); + let mut parts = Vec::new(); + for v in [None, Some(valid.as_slice())] { + let c = harris(w, h, &img, max, md, v); + for k in &c { + parts.extend([k.x.to_bits() as u64, k.y.to_bits() as u64, k.score.to_bits() as u64]); + } + parts.push(c.len() as u64); + } + assert_eq!(fnv(&parts), want_corners, "harris {w}x{h}"); + let c = harris(w, h, &img, max, md, None); + assert!(c.len() > 10, "{} corners", c.len()); + let mut parts = Vec::new(); + for upright in [false, true] { + for d in describe(w, h, &img, &c, upright) { + parts.extend(d); + } + } + assert_eq!(fnv(&parts), want_desc, "describe {w}x{h}"); + } + } +} diff --git a/crates/algo/src/inpaint.rs b/crates/algo/src/inpaint.rs index ee472b2296..2dd40198d8 100644 --- a/crates/algo/src/inpaint.rs +++ b/crates/algo/src/inpaint.rs @@ -65,15 +65,13 @@ const SOURCE_MOMENTS_MAX: usize = 1 << 20; #[derive(Clone)] pub(crate) struct Rng(u64); impl Rng { + /// A generator whose sequence is fixed by `seed`. pub(crate) fn new(seed: u64) -> Self { Rng(seed ^ 0x9E37_79B9_7F4A_7C15) } + /// The next value of the SplitMix64 sequence. pub(crate) fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) + crate::photo_util::splitmix64(&mut self.0) } /// Skip `n` numbers (the same state as after `n` calls of [`Rng::next`]). pub(crate) fn skip(&mut self, n: u64) { diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index 49ab15871c..6cefbbd4c1 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -32,6 +32,7 @@ mod distort; mod distort2; pub mod erase; pub mod exif; +pub mod faces; pub mod features; mod fxutil; mod gallery; @@ -481,7 +482,8 @@ pub enum FilterParams { distribution: Distribution, monochromatic: bool, seed: u32, - /// Depth for [`DepthSource::LayerMask`] (channel 0, document coordinates), supplied by the caller. + /// Depth for [`DepthSource::LayerMask`] and [`DepthSource::Channel`] (channel 0, document + /// coordinates), supplied by the caller. #[serde(skip)] depth_map: Option>, }, @@ -743,8 +745,8 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec noise::add(src, out, ctx, *amount, *distribution, *monochromatic, *seed), FilterParams::Median { radius } => noise::median(src, out, *radius, None), FilterParams::DustAndScratches { radius, threshold } => noise::median(src, out, *radius, Some(*threshold)), - FilterParams::Minimum { radius, preserve } => other::min_max_preserve(src, out, *radius, false, *preserve), - FilterParams::Maximum { radius, preserve } => other::min_max_preserve(src, out, *radius, true, *preserve), + FilterParams::Minimum { radius, preserve } => min_max_ink(src, out, ctx, *radius, false, *preserve), + FilterParams::Maximum { radius, preserve } => min_max_ink(src, out, ctx, *radius, true, *preserve), FilterParams::Offset { horizontal, vertical, undefined } => other::offset(src, out, ctx, *horizontal, *vertical, *undefined), FilterParams::Mosaic { cell_size } => stylize::mosaic(src, out, ctx, *cell_size), FilterParams::Emboss { angle, height, amount } => stylize::emboss(src, out, ctx, *angle, *height, *amount), @@ -908,6 +910,23 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec Vec { + if !fxutil::subtractive(ctx) { + return other::min_max_preserve(src, out, radius, max, preserve); + } + let n = src.ch.max(1); + let cc = if ctx.alpha { n - 1 } else { n }; + let flip = |data: &mut [f32]| data.chunks_exact_mut(n).for_each(|px| px.iter_mut().take(cc).for_each(|v| *v = 1.0 - *v)); + let mut inv = src.clone(); + flip(&mut inv.data); + let mut res = other::min_max_preserve(&inv, out, radius, max, preserve); + flip(&mut res); + res +} + /// Output tile size used by [`apply`]. pub const TILE: i32 = 256; @@ -971,6 +990,7 @@ fn auto_tile(params: &FilterParams, bounds: Rect) -> i32 { } /// [`apply`] / [`apply_in`] with an explicit tile size (tests use it to check tile independence). +/// Nonpositive tile sizes are treated as one pixel. pub fn apply_tiled( surface: &Surface, params: &FilterParams, @@ -1013,6 +1033,8 @@ fn apply_tiled_with_impl( ctl: &photocraft_raster::Interrupt, prepare_fast_paths: bool, ) -> Option { + // Every dispatch path needs a positive step, including Motion Blur's fallback. + let tile = tile.max(1); if ctl.cancelled() { return None; } diff --git a/crates/algo/src/other2.rs b/crates/algo/src/other2.rs index b5a16f06ea..61ccfc0038 100644 --- a/crates/algo/src/other2.rs +++ b/crates/algo/src/other2.rs @@ -8,7 +8,8 @@ use crate::image::Image; use crate::{Ctx, HsbModel}; /// Custom: `Σ kernel·pixel / scale + offset/255` per colour channel (alpha -/// kept). Kernels shorter than 25 entries are zero-padded. +/// kept). Kernels shorter than 25 entries are zero-padded. CMYK samples are +/// ink, so there it runs on `1 - ink` and a positive offset brightens. pub(crate) fn custom(src: &Image, out: Rect, ctx: &Ctx, kernel: &[f32], scale: f32, offset: f32) -> Vec { let n = src.ch; let cc = ncol(ctx, n); @@ -16,6 +17,7 @@ pub(crate) fn custom(src: &Image, out: Rect, ctx: &Ctx, kernel: &[f32], scale: f (0..25).filter_map(|i| kernel.get(i).copied().filter(|v| *v != 0.0).map(|v| (i as i32 % 5 - 2, i as i32 / 5 - 2, v))).collect(); let s = if scale == 0.0 { 1.0 } else { scale }; let off = offset / 255.0; + let sub = crate::fxutil::subtractive(ctx); let mut res = src.crop(out); if k.is_empty() { return res; @@ -23,8 +25,10 @@ pub(crate) fn custom(src: &Image, out: Rect, ctx: &Ctx, kernel: &[f32], scale: f for (i, px) in res.chunks_exact_mut(n).enumerate() { let (x, y) = xy(out, i); for (c, v) in px.iter_mut().enumerate().take(cc) { - let sum: f32 = k.iter().map(|&(dx, dy, w)| src.get(x + dx, y + dy, c) * w).sum(); - *v = sum / s + off; + // CMYK: convolve brightness (1 - ink), then back to ink. + let lum = |v: f32| if sub { 1.0 - v } else { v }; + let sum: f32 = k.iter().map(|&(dx, dy, w)| lum(src.get(x + dx, y + dy, c)) * w).sum(); + *v = lum(sum / s + off); } } res diff --git a/crates/algo/src/panorama.rs b/crates/algo/src/panorama.rs index fd7ccbc591..75fa9a4bfb 100644 --- a/crates/algo/src/panorama.rs +++ b/crates/algo/src/panorama.rs @@ -35,7 +35,7 @@ #![allow(clippy::needless_range_loop)] // index loops mirror the maths (pixels × channels) use crate::features::{self, Descriptor, Model}; -use crate::photo_util::{Normal, Rng, par_map, solve_dense}; +use crate::photo_util::{Normal, Rng, par_map, par_rows, solve_dense}; use crate::transform::Homography; /// Photomerge layouts. @@ -996,58 +996,99 @@ pub fn blend_levels(w: usize, h: usize) -> usize { n } +/// `a[i] ⊕ b[i]` for every `i` (the shorter length wins, like `zip`), in parallel on native +/// targets. Purely elementwise, so the result is the serial result bit for bit. +fn par_zip(a: &[f32], b: &[f32], f: impl Fn(f32, f32) -> f32 + Sync + Send) -> Vec { + const CHUNK: usize = 1 << 14; + let mut out = vec![0.0f32; a.len().min(b.len())]; + let fill = |o: &mut [f32], a: &[f32], b: &[f32]| { + for ((o, &a), &b) in o.iter_mut().zip(a).zip(b) { + *o = f(a, b); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_mut(CHUNK).zip(a.par_chunks(CHUNK)).zip(b.par_chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); + } + #[cfg(target_arch = "wasm32")] + out.chunks_mut(CHUNK).zip(a.chunks(CHUNK)).zip(b.chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); + out +} + +/// `f(a[i])` for every `i`, in parallel on native targets (elementwise, so bit for bit serial). +fn par_map1(a: &[f32], f: impl Fn(f32) -> f32 + Sync + Send) -> Vec { + par_zip(a, a, |x, _| f(x)) +} + +// `reduce`, `expand` and `push_pull` run one pyramid level for one image at a time, and the +// images themselves only fill part of a many-core machine, so each of them also runs its rows +// in parallel. Every output element is computed by the same expression, in the same order, as +// the one-thread loops they replace (rows never read each other's output), so the result is +// bit for bit unchanged. + fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; // Separable 5-tap binomial, then decimate. let mut tmp = vec![0.0f32; nw * h * ch]; - for y in 0..h { + par_rows(&mut tmp, nw, ch, |y, row| { + let line = &src[y * w * ch..(y + 1) * w * ch]; for x in 0..nw { + // The clamped source column of each tap is the same for every channel. + let xs: [usize; 5] = std::array::from_fn(|t| (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize * ch); for c in 0..ch { let mut s = 0.0; - for (t, kv) in k.iter().enumerate() { - let xx = (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize; - s += kv * src[(y * w + xx) * ch + c]; + for (kv, xx) in k.iter().zip(xs) { + s += kv * line[xx + c]; } - tmp[(y * nw + x) * ch + c] = s / 16.0; + row[x * ch + c] = s / 16.0; } } - } + }); let mut out = vec![0.0f32; nw * nh * ch]; - for y in 0..nh { - for x in 0..nw { - for c in 0..ch { - let mut s = 0.0; - for (t, kv) in k.iter().enumerate() { - let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; - s += kv * tmp[(yy * nw + x) * ch + c]; - } - out[(y * nw + x) * ch + c] = s / 16.0; + par_rows(&mut out, nw, ch, |y, row| { + // Each output row is five source rows added in tap order: the same sum per element as + // before (`0 + k0·a + k1·b + …`), but over whole rows so it vectorises. + for (t, kv) in k.iter().enumerate() { + let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; + for (o, &v) in row.iter_mut().zip(&tmp[yy * nw * ch..(yy + 1) * nw * ch]) { + *o += kv * v; } } - } + for o in row.iter_mut() { + *o /= 16.0; + } + }); (nw, nh, out) } fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { // Bilinear upsampling at half-pixel-aligned positions. let mut out = vec![0.0f32; w * h * ch]; - for y in 0..h { - let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); - let (y0, ty) = (fy.floor() as usize, fy - fy.floor()); - let y1 = (y0 + 1).min(sh - 1); - for x in 0..w { + // Source columns and weights depend on x only: worked out once instead of for every row. + // The clamped position is never negative, so truncating is `floor` (and spares the libm call). + let cols: Vec<(usize, usize, f32)> = (0..w) + .map(|x| { let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); - let (x0, tx) = (fx.floor() as usize, fx - fx.floor()); - let x1 = (x0 + 1).min(sw - 1); - for c in 0..ch { - let p = |xx: usize, yy: usize| src[(yy * sw + xx) * ch + c]; - let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx; - let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx; - out[(y * w + x) * ch + c] = top + (bot - top) * ty; + let x0 = fx as usize; + (x0 * ch, (x0 + 1).min(sw - 1) * ch, fx - x0 as f32) + }) + .collect(); + par_rows(&mut out, w, ch, |y, row| { + let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); + let y0 = fy as usize; + let ty = fy - y0 as f32; + let y1 = (y0 + 1).min(sh - 1); + let (r0, r1) = (&src[y0 * sw * ch..(y0 + 1) * sw * ch], &src[y1 * sw * ch..(y1 + 1) * sw * ch]); + for (px, &(x0, x1, tx)) in row.chunks_exact_mut(ch.max(1)).zip(&cols) { + for (c, o) in px.iter_mut().enumerate() { + let top = r0[x0 + c] + (r0[x1 + c] - r0[x0 + c]) * tx; + let bot = r1[x0 + c] + (r1[x1 + c] - r1[x0 + c]) * tx; + *o = top + (bot - top) * ty; } } - } + }); out } @@ -1058,47 +1099,99 @@ fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { return; } let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + // Coarse sums. A coarse row is fed by two fine rows; walking them in raster order adds each + // coarse cell's (up to) four fine pixels in the order the serial scatter-add did, from zero. let mut cpx = vec![0.0f32; nw * nh * ch]; let mut cw = vec![0.0f32; nw * nh]; - for y in 0..h { - for x in 0..w { - let (i, j) = (y * w + x, (y / 2) * nw + x / 2); - let a = wt[i]; - cw[j] += a; - for c in 0..ch { - cpx[j * ch + c] += a * px[i * ch + c]; + par_rows(&mut cw, nw, 1, |cy, row| { + for y in 2 * cy..(2 * cy + 2).min(h) { + for (x, &a) in wt[y * w..(y + 1) * w].iter().enumerate() { + row[x / 2] += a; } } - } - for j in 0..nw * nh { - if cw[j] > 0.0 { - for c in 0..ch { - cpx[j * ch + c] /= cw[j]; + }); + let px_in: &[f32] = px; + par_rows(&mut cpx, nw, ch, |cy, row| { + for y in 2 * cy..(2 * cy + 2).min(h) { + for x in 0..w { + let (i, j) = (y * w + x, x / 2); + let a = wt[i]; + for c in 0..ch { + row[j * ch + c] += a * px_in[i * ch + c]; + } } - cw[j] = 1.0; + } + }); + // Normalise by the weight (this reads `cw` before it is reset to 0 / 1 below). + par_rows(&mut cpx, nw, ch, |cy, row| { + for cx in 0..nw { + let wj = cw[cy * nw + cx]; + if wj > 0.0 { + for c in 0..ch { + row[cx * ch + c] /= wj; + } + } + } + }); + for v in cw.iter_mut() { + if *v > 0.0 { + *v = 1.0; } } if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { push_pull(nw, nh, ch, &mut cpx, &cw); } - for y in 0..h { + par_rows(px, w, ch, |y, row| { for x in 0..w { let i = y * w + x; if wt[i] < 1.0 { let j = (y / 2) * nw + x / 2; let a = wt[i]; for c in 0..ch { - px[i * ch + c] = a * px[i * ch + c] + (1.0 - a) * cpx[j * ch + c]; + row[x * ch + c] = a * row[x * ch + c] + (1.0 - a) * cpx[j * ch + c]; } } } - } + }); } +/// One image's pyramid in [`multiband`]: the grid origin `(gx0, gy0)` at level 0, the Laplacian +/// levels `(w, h, colours)` and the Gaussian weight levels. +type PyramidBand = (i32, i32, Vec<(usize, usize, Vec)>, Vec>); + +/// The part of `band` on panorama row `py` of level `l`: the panorama column its first pixel +/// lands on, its width, its weight row and its colour row. `None` when it misses the row. +fn band_row(band: &PyramidBand, l: usize, ch: usize, py: usize) -> Option<(usize, usize, &[f32], &[f32])> { + let (ox, oy) = ((band.0 >> l) as usize, (band.1 >> l) as usize); + let (lw, lh, colours) = &band.2[l]; + (py >= oy && py - oy < *lh).then(|| { + let y = py - oy; + (ox, *lw, &band.3[l][y * lw..(y + 1) * lw], &colours[y * lw * ch..(y + 1) * lw * ch]) + }) +} + +/// Estimated bytes of band construction [`multiband`] keeps in flight at once. Images are built +/// and accumulated in batches under it, so its peak memory doesn't grow with the image count +/// (#7758). Four 24 MP RGB sources (~1.2 GB each) fit in one batch: building bands side by side +/// uses a many-core machine better than one band's row-parallel work, and one at a time made the +/// usual 2–4 image Photomerge 12–36% slower on a 32-thread desktop. +#[cfg(not(target_arch = "wasm32"))] +const BAND_BUDGET: usize = 5 << 30; +/// Without threads the bands of a batch are built one after another anyway, so each is added as +/// soon as it is built (the browser's address space is 4 GB). +#[cfg(target_arch = "wasm32")] +const BAND_BUDGET: usize = 0; + /// Multi-band blend of `imgs` into a `w × h` panorama (origin 0,0) with one weight map per image /// over the same grid as its ROI (`weights[i]` has `w_i × h_i` entries). Returns the colour /// channels (`ch` per pixel) and the total coverage. pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { + multiband_batched(w, h, imgs, weights, levels, BAND_BUDGET) +} + +/// [`multiband`], building at most `budget` estimated bytes of bands at a time (at least one +/// image). Each pixel still adds the bands in image order, so the result doesn't depend on it. +fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize, budget: usize) -> (Vec, Vec) { let ch = imgs.first().map_or(1, |i| i.ch); let levels = levels.max(1); let align = 1i32 << (levels - 1); @@ -1112,87 +1205,144 @@ pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], le let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); let margin = align * 4; // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. - let bands = par_map(imgs.len(), |k| { - let im = &imgs[k]; + let grid = |im: &RoiImage| { let gx0 = ((im.x0 - margin).max(0) / align) * align; let gy0 = ((im.y0 - margin).max(0) / align) * align; let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); - let (gw, gh) = ((gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize); + (gx0, gy0, (gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize) + }; + // Building one band holds its grid's colour and weight planes about three times over: the + // pyramids are 4/3 of a plane, and the grid copy, coverage and `expand` scratch come on top. + let cost = |im: &RoiImage| { + let (_, _, gw, gh) = grid(im); + gw.saturating_mul(gh).saturating_mul(ch + 1).saturating_mul(4 * 3) + }; + let band = |k: usize| -> PyramidBand { + let im = &imgs[k]; + let (gx0, gy0, gw, gh) = grid(im); + // Each grid pixel takes the image pixel that lands on it (every image pixel lands on at + // most one), so rows of the grid are independent and fill in parallel. + let src_of = |gx: usize, gy: usize| -> Option { + let (x, y) = (gx as i64 + gx0 as i64 - im.x0 as i64, gy as i64 + gy0 as i64 - im.y0 as i64); + (x >= 0 && y >= 0 && (x as usize) < im.w && (y as usize) < im.h).then(|| y as usize * im.w + x as usize) + }; let mut px = vec![0.0f32; gw * gh * ch]; - let mut cov = vec![0.0f32; gw * gh]; - let mut wt = vec![0.0f32; gw * gh]; - for y in 0..im.h { - for x in 0..im.w { - let (gx, gy) = (im.x0 + x as i32 - gx0, im.y0 + y as i32 - gy0); - if gx < 0 || gy < 0 || gx as usize >= gw || gy as usize >= gh { - continue; + par_rows(&mut px, gw, ch, |gy, row| { + for gx in 0..gw { + if let Some(i) = src_of(gx, gy) { + row[gx * ch..(gx + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); } - let (i, g) = (y * im.w + x, gy as usize * gw + gx as usize); - cov[g] = im.alpha[i]; - wt[g] = weights[k][i] * im.alpha[i].min(1.0); - px[g * ch..(g + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); } - } - let bin: Vec = cov.iter().map(|a| if *a > 0.5 { 1.0 } else { 0.0 }).collect(); + }); + let mut cov = vec![0.0f32; gw * gh]; + par_rows(&mut cov, gw, 1, |gy, row| { + for (gx, o) in row.iter_mut().enumerate() { + if let Some(i) = src_of(gx, gy) { + *o = im.alpha[i]; + } + } + }); + let mut wt = vec![0.0f32; gw * gh]; + par_rows(&mut wt, gw, 1, |gy, row| { + for (gx, o) in row.iter_mut().enumerate() { + if let Some(i) = src_of(gx, gy) { + *o = weights[k][i] * im.alpha[i].min(1.0); + } + } + }); + let bin: Vec = par_map1(&cov, |a| if a > 0.5 { 1.0 } else { 0.0 }); + drop(cov); push_pull(gw, gh, ch, &mut px, &bin); - // Laplacian of the colours, Gaussian of the weights. + drop(bin); + // Laplacian of the colours, Gaussian of the weights. Planes move into the pyramids rather + // than being copied: with one image built at a time, a copy is a serial pass over it. let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); let mut gau: Vec> = Vec::new(); let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); for l in 0..levels { if l + 1 == levels { - lap.push((cw, chh, cur.clone())); - gau.push(cwt.clone()); + lap.push((cw, chh, cur)); + gau.push(cwt); break; } let (nw, nh, down) = reduce(cw, chh, ch, &cur); let up = expand(nw, nh, ch, &down, cw, chh); - lap.push((cw, chh, cur.iter().zip(&up).map(|(a, b)| a - b).collect())); - gau.push(cwt.clone()); + lap.push((cw, chh, par_zip(&cur, &up, |a, b| a - b))); let (_, _, wdown) = reduce(cw, chh, 1, &cwt); + gau.push(cwt); cw = nw; chh = nh; cur = down; cwt = wdown; } (gx0, gy0, lap, gau) - }); - for (gx0, gy0, lap, gau) in &bands { - for (l, ((lw, lh, band), g)) in lap.iter().zip(gau).enumerate() { - let (ox, oy) = ((gx0 >> l) as usize, (gy0 >> l) as usize); - let (pw, ph) = sizes[l]; - for y in 0..*lh { - let py = oy + y; - if py >= ph { - break; - } - for x in 0..*lw { - let px = ox + x; - if px >= pw { - break; - } - let (i, p) = (y * lw + x, py * pw + px); - let k = g[i]; - if k <= 0.0 { - continue; - } - wsum[l][p] += k; - for c in 0..ch { - acc[l][p * ch + c] += k * band[i * ch + c]; - } - } - } + }; + // Build the bands a batch at a time and add each batch before building the next. Each pixel + // adds the bands in the same order as the serial loop (per level, bands one after another; + // batches follow each other in image order), but rows of a level are independent, so they + // run in parallel: every row walks the batch's bands itself. + let mut start = 0; + while start < imgs.len() { + let mut end = start + 1; + let mut bytes = cost(&imgs[start]); + while let Some(im) = imgs.get(end) + && bytes.saturating_add(cost(im)) <= budget + { + bytes = bytes.saturating_add(cost(im)); + end += 1; } + let bands = par_map(end - start, |j| band(start + j)); + for l in 0..levels { + let pw = sizes[l].0; + par_rows(&mut wsum[l], pw, 1, |py, row| { + for b in &bands { + let Some((ox, lw, g, _)) = band_row(b, l, ch, py) else { continue }; + for x in 0..lw { + let px = ox + x; + if px >= pw { + break; + } + let k = g[x]; + if k <= 0.0 { + continue; + } + row[px] += k; + } + } + }); + par_rows(&mut acc[l], pw, ch, |py, row| { + for b in &bands { + let Some((ox, lw, g, band)) = band_row(b, l, ch, py) else { continue }; + for x in 0..lw { + let px = ox + x; + if px >= pw { + break; + } + let k = g[x]; + if k <= 0.0 { + continue; + } + for c in 0..ch { + row[px * ch + c] += k * band[x * ch + c]; + } + } + } + }); + } + start = end; } for l in 0..levels { - let (pw, ph) = sizes[l]; - for p in 0..pw * ph { - let k = wsum[l][p]; - for c in 0..ch { - acc[l][p * ch + c] = if k > 1e-8 { acc[l][p * ch + c] / k } else { 0.0 }; + let pw = sizes[l].0; + let ws = &wsum[l]; + par_rows(&mut acc[l], pw, ch, |py, row| { + for x in 0..pw { + let k = ws[py * pw + x]; + for c in 0..ch { + row[x * ch + c] = if k > 1e-8 { row[x * ch + c] / k } else { 0.0 }; + } } - } + }); } // Collapse. // `levels ≥ 1`, so there is always a coarsest level. @@ -1201,22 +1351,27 @@ pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], le let (pw, ph) = sizes[l]; let (sw, sh) = sizes[l + 1]; let up = expand(sw, sh, ch, &cur, pw, ph); - cur = acc[l].iter().zip(&up).map(|(a, b)| a + b).collect(); + cur = par_zip(&acc[l], &up, |a, b| a + b); } - // Coverage: union of the images. + // Coverage: union of the images. Rows are independent; each walks the images in order, so a + // pixel sees the same sequence of `max` calls as in the serial loop. let mut cov = vec![0.0f32; w * h]; - for im in imgs { - for y in 0..im.h { + par_rows(&mut cov, w, 1, |py, row| { + for im in imgs { + let y = py as i64 - im.y0 as i64; + if y < 0 || y as usize >= im.h { + continue; + } for x in 0..im.w { - let (px, py) = (im.x0 + x as i32, im.y0 + y as i32); - if px < 0 || py < 0 || px as usize >= w || py as usize >= h { + let px = im.x0 + x as i32; + if px < 0 || px as usize >= w { continue; } - let p = py as usize * w + px as usize; - cov[p] = cov[p].max(im.alpha[y * im.w + x]); + let p = px as usize; + row[p] = row[p].max(im.alpha[y as usize * im.w + x]); } } - } + }); (cur, cov) } @@ -1431,3 +1586,411 @@ mod tests { assert!(cov.iter().all(|c| *c == 1.0)); } } + +/// The row-parallel `reduce` / `expand` / `push_pull` / `multiband` against the serial code they +/// replaced, kept below verbatim as the reference. Every output must stay bit for bit the same. +#[cfg(test)] +mod parallel_tests { + use super::*; + + fn mix(mut z: u64) -> u64 { + z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// Deterministic data from integer arithmetic only (no libm): mostly `0..1`, with negatives, + /// signed zeros and large values so a different order of operations cannot hide. + fn noise(len: usize, seed: u64) -> Vec { + (0..len as u64) + .map(|i| { + let z = mix(seed.wrapping_mul(0x1234_5678_9ABC).wrapping_add(i)); + let v = (z >> 40) as f32 / 16_777_216.0; + match z & 31 { + 0 => -v, + 1 => -0.0, + 2 => v * 1000.0, + 3 => 0.0, + _ => v, + } + }) + .collect() + } + + /// Weights with exact zeros, exact ones and partial values, in blobs and noise. + fn weights(w: usize, h: usize, seed: u64) -> Vec { + (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let z = mix(seed + i as u64); + if (x / 5 + y / 3) % 3 == 0 { + 0.0 + } else if z.is_multiple_of(7) { + ((z >> 20) % 100) as f32 / 100.0 + } else { + 1.0 + } + }) + .collect() + } + + fn bits(v: &[f32]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() + } + + fn fnv(parts: &[&[f32]]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + for p in parts { + for x in *p { + h ^= x.to_bits() as u64; + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + } + h + } + + /// Sizes that cross the odd / even and tiny cases (1 wide, 1 high, 1×1, odd, power of two + 1). + const SIZES: [(usize, usize); 12] = [(1, 1), (1, 9), (9, 1), (2, 2), (3, 5), (4, 4), (17, 13), (64, 40), (65, 41), (97, 61), (130, 7), (7, 130)]; + + fn ref_reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; + // Separable 5-tap binomial, then decimate. + let mut tmp = vec![0.0f32; nw * h * ch]; + for y in 0..h { + for x in 0..nw { + for c in 0..ch { + let mut s = 0.0; + for (t, kv) in k.iter().enumerate() { + let xx = (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize; + s += kv * src[(y * w + xx) * ch + c]; + } + tmp[(y * nw + x) * ch + c] = s / 16.0; + } + } + } + let mut out = vec![0.0f32; nw * nh * ch]; + for y in 0..nh { + for x in 0..nw { + for c in 0..ch { + let mut s = 0.0; + for (t, kv) in k.iter().enumerate() { + let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; + s += kv * tmp[(yy * nw + x) * ch + c]; + } + out[(y * nw + x) * ch + c] = s / 16.0; + } + } + } + (nw, nh, out) + } + + fn ref_expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { + // Bilinear upsampling at half-pixel-aligned positions. + let mut out = vec![0.0f32; w * h * ch]; + for y in 0..h { + let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); + let (y0, ty) = (fy.floor() as usize, fy - fy.floor()); + let y1 = (y0 + 1).min(sh - 1); + for x in 0..w { + let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); + let (x0, tx) = (fx.floor() as usize, fx - fx.floor()); + let x1 = (x0 + 1).min(sw - 1); + for c in 0..ch { + let p = |xx: usize, yy: usize| src[(yy * sw + xx) * ch + c]; + let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx; + let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx; + out[(y * w + x) * ch + c] = top + (bot - top) * ty; + } + } + } + out + } + + fn ref_push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { + if w <= 1 && h <= 1 { + return; + } + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + let mut cpx = vec![0.0f32; nw * nh * ch]; + let mut cw = vec![0.0f32; nw * nh]; + for y in 0..h { + for x in 0..w { + let (i, j) = (y * w + x, (y / 2) * nw + x / 2); + let a = wt[i]; + cw[j] += a; + for c in 0..ch { + cpx[j * ch + c] += a * px[i * ch + c]; + } + } + } + for j in 0..nw * nh { + if cw[j] > 0.0 { + for c in 0..ch { + cpx[j * ch + c] /= cw[j]; + } + cw[j] = 1.0; + } + } + if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { + ref_push_pull(nw, nh, ch, &mut cpx, &cw); + } + for y in 0..h { + for x in 0..w { + let i = y * w + x; + if wt[i] < 1.0 { + let j = (y / 2) * nw + x / 2; + let a = wt[i]; + for c in 0..ch { + px[i * ch + c] = a * px[i * ch + c] + (1.0 - a) * cpx[j * ch + c]; + } + } + } + } + } + + fn ref_multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { + let ch = imgs.first().map_or(1, |i| i.ch); + let levels = levels.max(1); + let align = 1i32 << (levels - 1); + // Level sizes of the panorama. + let mut sizes = vec![(w, h)]; + for _ in 1..levels { + let Some(&(pw, ph)) = sizes.last() else { break }; + sizes.push((pw.div_ceil(2), ph.div_ceil(2))); + } + let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); + let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); + let margin = align * 4; + // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. + let bands = par_map(imgs.len(), |k| { + let im = &imgs[k]; + let gx0 = ((im.x0 - margin).max(0) / align) * align; + let gy0 = ((im.y0 - margin).max(0) / align) * align; + let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); + let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); + let (gw, gh) = ((gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize); + let mut px = vec![0.0f32; gw * gh * ch]; + let mut cov = vec![0.0f32; gw * gh]; + let mut wt = vec![0.0f32; gw * gh]; + for y in 0..im.h { + for x in 0..im.w { + let (gx, gy) = (im.x0 + x as i32 - gx0, im.y0 + y as i32 - gy0); + if gx < 0 || gy < 0 || gx as usize >= gw || gy as usize >= gh { + continue; + } + let (i, g) = (y * im.w + x, gy as usize * gw + gx as usize); + cov[g] = im.alpha[i]; + wt[g] = weights[k][i] * im.alpha[i].min(1.0); + px[g * ch..(g + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); + } + } + let bin: Vec = cov.iter().map(|a| if *a > 0.5 { 1.0 } else { 0.0 }).collect(); + ref_push_pull(gw, gh, ch, &mut px, &bin); + // Laplacian of the colours, Gaussian of the weights. + let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); + let mut gau: Vec> = Vec::new(); + let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); + for l in 0..levels { + if l + 1 == levels { + lap.push((cw, chh, cur.clone())); + gau.push(cwt.clone()); + break; + } + let (nw, nh, down) = ref_reduce(cw, chh, ch, &cur); + let up = ref_expand(nw, nh, ch, &down, cw, chh); + lap.push((cw, chh, cur.iter().zip(&up).map(|(a, b)| a - b).collect())); + gau.push(cwt.clone()); + let (_, _, wdown) = ref_reduce(cw, chh, 1, &cwt); + cw = nw; + chh = nh; + cur = down; + cwt = wdown; + } + (gx0, gy0, lap, gau) + }); + for (gx0, gy0, lap, gau) in &bands { + for (l, ((lw, lh, band), g)) in lap.iter().zip(gau).enumerate() { + let (ox, oy) = ((gx0 >> l) as usize, (gy0 >> l) as usize); + let (pw, ph) = sizes[l]; + for y in 0..*lh { + let py = oy + y; + if py >= ph { + break; + } + for x in 0..*lw { + let px = ox + x; + if px >= pw { + break; + } + let (i, p) = (y * lw + x, py * pw + px); + let k = g[i]; + if k <= 0.0 { + continue; + } + wsum[l][p] += k; + for c in 0..ch { + acc[l][p * ch + c] += k * band[i * ch + c]; + } + } + } + } + } + for l in 0..levels { + let (pw, ph) = sizes[l]; + for p in 0..pw * ph { + let k = wsum[l][p]; + for c in 0..ch { + acc[l][p * ch + c] = if k > 1e-8 { acc[l][p * ch + c] / k } else { 0.0 }; + } + } + } + // Collapse. + // `levels ≥ 1`, so there is always a coarsest level. + let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; + for l in (0..levels - 1).rev() { + let (pw, ph) = sizes[l]; + let (sw, sh) = sizes[l + 1]; + let up = ref_expand(sw, sh, ch, &cur, pw, ph); + cur = acc[l].iter().zip(&up).map(|(a, b)| a + b).collect(); + } + // Coverage: union of the images. + let mut cov = vec![0.0f32; w * h]; + for im in imgs { + for y in 0..im.h { + for x in 0..im.w { + let (px, py) = (im.x0 + x as i32, im.y0 + y as i32); + if px < 0 || py < 0 || px as usize >= w || py as usize >= h { + continue; + } + let p = py as usize * w + px as usize; + cov[p] = cov[p].max(im.alpha[y * im.w + x]); + } + } + } + (cur, cov) + } + + #[test] + fn reduce_and_expand_match_the_serial_code() { + for (n, &(w, h)) in SIZES.iter().enumerate() { + for ch in [1usize, 3, 4] { + let src = noise(w * h * ch, n as u64 * 7 + ch as u64); + let (nw, nh, got) = reduce(w, h, ch, &src); + let (rw, rh, want) = ref_reduce(w, h, ch, &src); + assert_eq!((nw, nh), (rw, rh)); + assert_eq!(bits(&got), bits(&want), "reduce {w}x{h}x{ch}"); + // Expand back to the original size and to sizes that are not twice the source's. + for (ew, eh) in [(w, h), (2 * nw, 2 * nh), (2 * nw - 1, 2 * nh + 1), (w + 3, h + 5)] { + let got = expand(nw, nh, ch, &want, ew, eh); + let want_up = ref_expand(nw, nh, ch, &want, ew, eh); + assert_eq!(bits(&got), bits(&want_up), "expand {nw}x{nh}x{ch} to {ew}x{eh}"); + } + } + } + } + + #[test] + fn push_pull_matches_the_serial_code() { + for (n, &(w, h)) in SIZES.iter().enumerate() { + for ch in [1usize, 3] { + for variant in 0..3u64 { + let wt = match variant { + 0 => weights(w, h, n as u64), + 1 => vec![1.0; w * h], + // A single covered pixel: every level of the recursion has to fill from it. + _ => (0..w * h).map(|i| if i == (w * h) / 3 { 1.0 } else { 0.0 }).collect(), + }; + let px = noise(w * h * ch, 100 + n as u64); + let (mut got, mut want) = (px.clone(), px); + push_pull(w, h, ch, &mut got, &wt); + ref_push_pull(w, h, ch, &mut want, &wt); + assert_eq!(bits(&got), bits(&want), "push_pull {w}x{h}x{ch} variant {variant}"); + } + } + } + } + + /// ROIs of assorted sizes and offsets (some sticking out of the canvas), with holes in the alpha. + fn rois(w: usize, h: usize, ch: usize, seed: u64) -> (Vec, Vec>) { + let specs = + [(0i32, 0i32, w * 2 / 3, h), (w as i32 / 3, -(h as i32) / 5, w * 2 / 3 + 1, h * 3 / 4 + 1), (-(w as i32) / 4, h as i32 / 2, w / 2 + 1, h / 2 + 3)]; + let imgs: Vec = specs + .iter() + .enumerate() + .map(|(k, &(x0, y0, iw, ih))| { + let (iw, ih) = (iw.max(1), ih.max(1)); + let mut alpha = vec![1.0f32; iw * ih]; + for (i, a) in alpha.iter_mut().enumerate() { + let z = mix(seed + k as u64 * 1000 + i as u64); + if (i % iw) / 4 % 5 == 2 && (i / iw) % 6 < 3 { + *a = 0.0; + } else if z.is_multiple_of(11) { + *a = 0.3; + } + } + RoiImage { x0, y0, w: iw, h: ih, ch, px: noise(iw * ih * ch, seed + k as u64), alpha } + }) + .collect(); + let wts = imgs.iter().enumerate().map(|(k, r)| weights(r.w, r.h, seed + 50 + k as u64)).collect(); + (imgs, wts) + } + + #[test] + fn multiband_matches_the_serial_code() { + for (n, &(w, h)) in [(1usize, 1usize), (5, 3), (40, 30), (97, 61), (130, 70), (64, 64), (201, 129)].iter().enumerate() { + for ch in [1usize, 3] { + let (imgs, wts) = rois(w, h, ch, n as u64 * 31 + ch as u64); + for levels in [1usize, 2, 3, 5, 7] { + let got = multiband(w, h, &imgs, &wts, levels); + let want = ref_multiband(w, h, &imgs, &wts, levels); + assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels}"); + assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels}"); + } + } + } + // No images at all, and zero levels. + assert_eq!(multiband(9, 7, &[], &[], 3).0.len(), ref_multiband(9, 7, &[], &[], 3).0.len()); + } + + /// Batching the bands (#7758) changes when they are built, not the result. Budgets from none + /// (one image per batch) up to everything in steps of a fifth pass through every split of the + /// three images. + #[test] + fn multiband_batches_match_the_serial_code() { + let budgets: Vec = + std::iter::successors(Some(1024.0f64), |b| Some(b * 1.2)).take_while(|b| *b < 4e6).map(|b| b as usize).chain([0, usize::MAX]).collect(); + for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() { + for ch in [1usize, 3] { + let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64); + for levels in [1usize, 3, 5] { + let want = ref_multiband(w, h, &imgs, &wts, levels); + for &budget in &budgets { + let got = multiband_batched(w, h, &imgs, &wts, levels, budget); + assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels} budget {budget}"); + assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels} budget {budget}"); + } + } + } + } + } + + /// Hashes recorded from the code before it was made parallel (plain f32 arithmetic only, so + /// they hold on every platform). + #[test] + fn multiband_hashes_recorded_from_the_serial_code() { + let (imgs, wts) = rois(97, 61, 3, 5); + let (px, cov) = multiband(97, 61, &imgs, &wts, 5); + assert_eq!(fnv(&[&px, &cov]), 0xf89a5726082ebb6c, "97x61 rgb, 5 levels"); + let (imgs, wts) = rois(130, 70, 1, 9); + let (px, cov) = multiband(130, 70, &imgs, &wts, 7); + assert_eq!(fnv(&[&px, &cov]), 0xb7d7ddc59d201730, "130x70 grey, 7 levels"); + let wt = weights(65, 41, 3); + let mut px = noise(65 * 41 * 3, 4); + push_pull(65, 41, 3, &mut px, &wt); + assert_eq!(fnv(&[&px]), 0x50ea36a84ca9a68f, "push_pull 65x41 rgb"); + let (nw, nh, r) = reduce(65, 41, 3, &px); + assert_eq!(fnv(&[&r, &expand(nw, nh, 3, &r, 65, 41)]), 0x51823acfb4206dd8, "reduce + expand 65x41 rgb"); + } +} diff --git a/crates/algo/src/params_ext.rs b/crates/algo/src/params_ext.rs index 3a9572fb46..2349604196 100644 --- a/crates/algo/src/params_ext.rs +++ b/crates/algo/src/params_ext.rs @@ -182,6 +182,9 @@ pub enum DepthSource { None, Transparency, LayerMask, + /// An alpha channel of the document (Photoshop lists them after Layer Mask), supplied by the + /// caller like the layer mask. + Channel, } /// Built-in Shape Blur kernels. diff --git a/crates/algo/src/photo_util.rs b/crates/algo/src/photo_util.rs index bf65bc4459..7316088079 100644 --- a/crates/algo/src/photo_util.rs +++ b/crates/algo/src/photo_util.rs @@ -159,15 +159,21 @@ pub(crate) fn par_map(n: usize, f: impl Fn(usize) -> T + Sync + Send) - (0..n).map(f).collect() } +/// Advances `state` one SplitMix64 step and returns the mixed output. +pub(crate) fn splitmix64(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = *state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + /// Deterministic 64-bit generator (SplitMix64). pub(crate) struct Rng(pub u64); impl Rng { + /// The next value of the SplitMix64 sequence. pub fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) + splitmix64(&mut self.0) } pub fn below(&mut self, n: usize) -> usize { (self.next() % n.max(1) as u64) as usize @@ -183,15 +189,7 @@ pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 { (z >> 40) as f32 / (1u64 << 24) as f32 } -/// sRGB transfer function, decode (extended linearly below 0 and as a power above 1). -pub(crate) fn srgb_to_linear(v: f32) -> f32 { - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } -} - -/// sRGB transfer function, encode. -pub(crate) fn linear_to_srgb(v: f32) -> f32 { - if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } -} +pub(crate) use photocraft_color::convert::{linear_to_srgb, srgb_to_linear}; /// Bilinear sample of channel `c` of a `w × h × ch` buffer, clamped to the edges. pub(crate) fn bilinear(buf: &[f32], w: usize, h: usize, ch: usize, c: usize, x: f32, y: f32) -> f32 { @@ -217,6 +215,41 @@ pub(crate) fn catmull_rom(t: f32) -> [f32; 4] { mod tests { use super::*; + /// The shared step and [`Rng`] reproduce the inlined copies they replaced, bit for bit. + #[test] + fn splitmix64_output_is_unchanged() { + /// The SplitMix64 step as each generator inlined it before. + fn inlined(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = *state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + let mut zero = 0; + assert_eq!([0; 3].map(|_| splitmix64(&mut zero)), [0xE220_A839_7B1D_CDAF, 0x6E78_9E6A_A1B9_65F4, 0x06C4_5D18_8009_454F]); + for seed in [0, 1, 42, 0x2545_F491_4F6C_DD1D, u64::MAX] { + let (mut shared, mut copy, mut rng) = (seed, seed, Rng(seed)); + for _ in 0..10_000 { + let want = inlined(&mut copy); + assert_eq!(splitmix64(&mut shared), want); + assert_eq!(rng.next(), want); + } + } + } + + /// The shared sRGB functions match the removed copies bit for bit. + #[test] + fn srgb_transfer_output_is_unchanged() { + let decode = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; + let encode = |v: f32| if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + for i in -2000..=6000 { + let v = i as f32 / 4000.0; + assert_eq!(srgb_to_linear(v).to_bits(), decode(v).to_bits(), "decode {v}"); + assert_eq!(linear_to_srgb(v).to_bits(), encode(v).to_bits(), "encode {v}"); + } + } + #[test] fn dense_and_sparse_solvers_agree() { // Overdetermined line fit y = 2x + 1. diff --git a/crates/algo/src/render.rs b/crates/algo/src/render.rs index baba88f93e..d40ff9cda8 100644 --- a/crates/algo/src/render.rs +++ b/crates/algo/src/render.rs @@ -146,8 +146,9 @@ pub(crate) fn lens_flare(src: &Image, out: Rect, ctx: &Ctx, brightness: f32, cen let mut c = rgba(ctx, px); for k in 0..3 { let a = (f[k] * bright).max(0.0); - // Screen keeps highlights below white for display-referred values. - c[k] = 1.0 - (1.0 - c[k]) * (1.0 - a.min(1.0)); + // Screen (c + a·(1 − c)) keeps display-referred values below white; a 32-bit + // value already above white is left as is rather than pulled down towards it. + c[k] += a.min(1.0) * (1.0 - c[k]).max(0.0); } set_rgba(ctx, px, c); } diff --git a/crates/algo/src/render2.rs b/crates/algo/src/render2.rs index ed6567ca5c..19a4b8218d 100644 --- a/crates/algo/src/render2.rs +++ b/crates/algo/src/render2.rs @@ -274,15 +274,13 @@ pub fn composite(surface: &mut Surface, prims: &[Prim], clip: Rect, selection: O pub struct Rng(u64); impl Rng { + /// A generator whose sequence is fixed by `seed` and `salt`. pub fn new(seed: u32, salt: u64) -> Rng { Rng(((seed as u64) << 32) ^ salt.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ 0x2545_F491_4F6C_DD1D) } + /// The next value of the SplitMix64 sequence. pub fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) + crate::photo_util::splitmix64(&mut self.0) } /// Uniform in [0, 1). pub fn f(&mut self) -> f32 { diff --git a/crates/algo/src/segment/grabcut.rs b/crates/algo/src/segment/grabcut.rs index 573c09079e..e1c1d89de0 100644 --- a/crates/algo/src/segment/grabcut.rs +++ b/crates/algo/src/segment/grabcut.rs @@ -126,7 +126,9 @@ pub fn object_select(sampler: &dyn Sampler, canvas: Rect, rect: Rect, work_px: u } let (fg, bg) = grabcut(&img, &mut trimap, 8)?; let low: Vec = trimap.iter().map(|t| is_fg(*t)).collect(); - let low = super::clean_mask(&low, lw, lh, 0.1, 0.002); + let low = super::clean_mask(&low, lw, lh, 0.1, 0.0); + // Every enclosed hole, however small, fills only when it looks like the object, so background seen through it stays open. + let low = super::fill_holes_by_model(&low, &img, &fg, &bg, 0.0, 0.05); super::finish_region(sampler, window, step, &low, lw, lh, Some((&fg, &bg))) } @@ -209,7 +211,9 @@ pub fn object_at(sampler: &dyn Sampler, canvas: Rect, x: f32, y: f32, work_px: u let mut seeds = vec![false; w * h]; seeds[sy * w + sx] = true; let low = super::keep_seeded(&low, &seeds, w, h); - let low = super::clean_mask(&low, w, h, 0.1, 0.01); + let low = super::clean_mask(&low, w, h, 0.1, 0.0); + // As in the rectangle mode: enclosed holes fill only when they look like the object. + let low = super::fill_holes_by_model(&low, &img, &fg, &bg, 0.0, 0.05); if !low.iter().any(|v| *v) { return None; } diff --git a/crates/algo/src/segment/tests.rs b/crates/algo/src/segment/tests.rs index 743c3dc460..e060913c9b 100644 --- a/crates/algo/src/segment/tests.rs +++ b/crates/algo/src/segment/tests.rs @@ -912,3 +912,61 @@ fn select_subject_dump_pictures() { write("ring", &img, None); write("ring-selected", &img, reg.as_ref()); } + +/// A dark square on a light background with a square hole that shows the background colour. +fn square_with_hole(hole: usize) -> RgbImage { + let (w, h) = (400usize, 300usize); + let mut rng = Rng::new(11); + let (x0, y0) = (100usize, 50usize); + RgbImage::from_fn(w, h, |x, y| { + let n = 0.02 * rng.normal(); + let in_square = x >= x0 && x < x0 + 200 && y >= y0 && y < y0 + 200; + let in_hole = x >= x0 + 96 && x < x0 + 96 + hole && y >= y0 + 96 && y < y0 + 96 + hole; + let c = if in_square && !in_hole { [0.1, 0.12, 0.15] } else { [0.9, 0.9, 0.85] }; + c.map(|v: f32| (v + n).clamp(0.0, 1.0)) + }) +} + +#[test] +fn object_select_keeps_small_background_hole_open() { + let img = square_with_hole(8); + let s = ImageSampler { img: &img, origin: (0, 0) }; + let canvas = Rect::new(0, 0, 400, 300); + let reg = grabcut::object_select(&s, canvas, Rect::new(80, 30, 320, 270), 1_000_000).unwrap(); + assert!(reg.at(150, 100) >= 0.5, "the square itself is selected"); + assert!(reg.at(200, 150) < 0.5, "background seen through the object stays unselected"); +} + +#[test] +fn object_at_keeps_small_background_hole_open() { + let img = square_with_hole(16); + let s = ImageSampler { img: &img, origin: (0, 0) }; + let canvas = Rect::new(0, 0, 400, 300); + let reg = grabcut::object_at(&s, canvas, 130.0, 80.0, 1_000_000).unwrap(); + assert!(reg.at(150, 100) >= 0.5, "the square itself is selected"); + assert!(reg.at(203, 153) < 0.5, "background seen through the object stays unselected"); +} + +#[test] +fn hole_fill_without_specks_fills_object_coloured_holes_only() { + // The hole check Object Selection uses: no hole fills just for being small, a speck of the object's colour still does. + let (w, h) = (40usize, 40usize); + let mut rng = Rng::new(5); + let in_square = |x: usize, y: usize| (5..35).contains(&x) && (5..35).contains(&y); + let bg_hole = |x: usize, y: usize| (10..12).contains(&x) && (10..12).contains(&y); + let fg_hole = |x: usize, y: usize| (25..27).contains(&x) && (25..27).contains(&y); + let img = RgbImage::from_fn(w, h, |x, y| { + let n = 0.02 * rng.normal(); + let c = if in_square(x, y) && !bg_hole(x, y) { [0.1, 0.12, 0.15] } else { [0.9, 0.9, 0.85] }; + c.map(|v: f32| (v + n).clamp(0.0, 1.0)) + }); + let mask: Vec = (0..w * h).map(|i| in_square(i % w, i / w) && !bg_hole(i % w, i / w) && !fg_hole(i % w, i / w)).collect(); + // The colour models, as GrabCut would fit them: the object colour vs. the backdrop colour. + let dark: Vec = (0..w * h).map(|i| in_square(i % w, i / w) && !bg_hole(i % w, i / w)).collect(); + let (fs, bs): (Vec<_>, Vec<_>) = img.px.iter().zip(&dark).partition(|(_, m)| **m); + let fit = |v: Vec<(&[f32; 3], &bool)>| Gmm::fit(&v.iter().map(|(p, _)| **p).collect::>(), 3, gmm::DEFAULT_REG).unwrap(); + let (fg, bg) = (fit(fs), fit(bs)); + let out = fill_holes_by_model(&mask, &img, &fg, &bg, 0.0, 0.05); + assert!(out[25 * w + 25], "a speck of the object's colour fills"); + assert!(!out[10 * w + 10], "a speck of the background's colour stays open"); +} diff --git a/crates/algo/src/stack.rs b/crates/algo/src/stack.rs index 2eec57e598..dbb5b22e65 100644 --- a/crates/algo/src/stack.rs +++ b/crates/algo/src/stack.rs @@ -23,85 +23,184 @@ pub enum Stat { Variance, } -fn stat(v: &mut [f32], s: Stat) -> f32 { +/// Reusable per-chunk scratch for [`Stat::Entropy`]: an 8-bit histogram plus the list of bins the +/// current pixel touched. Allocated once per parallel chunk instead of one `HashMap` per channel +/// per pixel (the old cost: ~4.6 s for 3 × 24 MP). +struct EntropyScratch { + counts: [u32; 256], + touched: Vec, +} + +impl EntropyScratch { + fn new() -> Self { + Self { counts: [0; 256], touched: Vec::new() } + } +} + +/// Shannon entropy (bits) of the 8-bit values in `v`, over log2(N). `v.len() >= 2`. +fn entropy(v: &[f32], scratch: &mut EntropyScratch) -> f32 { + let n = v.len() as f32; + for x in v { + let bin = (x.clamp(0.0, 1.0) * 255.0).round() as u8; + let c = &mut scratch.counts[usize::from(bin)]; + if *c == 0 { + scratch.touched.push(bin); + } + *c += 1; + } + // Sum the bins in ascending order. The old HashMap summed in its (randomly seeded) iteration + // order, and float addition is not associative, so the old result could differ in the last + // bit from run to run; a fixed order makes it deterministic. Sorting only the few touched + // bins keeps this O(samples), not O(256), per pixel. + scratch.touched.sort_unstable(); + let h: f32 = scratch + .touched + .iter() + .map(|&bin| { + let p = scratch.counts[usize::from(bin)] as f32 / n; + -p * p.log2() + }) + .sum(); + // Reset only the bins used, so the 256-entry array is never cleared wholesale. + for &bin in &scratch.touched { + scratch.counts[usize::from(bin)] = 0; + } + scratch.touched.clear(); + h / n.log2() +} + +/// `x` to the power `k` by repeated squaring. Every step is one IEEE 754 multiplication, so the +/// result has the same bits on every target. On Windows (MSVC), `f32::powi` with an exponent the +/// compiler cannot see as a constant calls the C runtime's `powf`, which rounds differently. +fn ipow(x: f32, k: u32) -> f32 { + let (mut base, mut k, mut acc) = (x, k, 1.0f32); + loop { + if k & 1 != 0 { + acc *= base; + } + k >>= 1; + if k == 0 { + return acc; + } + base *= base; + } +} + +fn stat(v: &mut [f32], s: Stat, scratch: &mut EntropyScratch) -> f32 { let n = v.len() as f32; if v.is_empty() { return 0.0; } + // Modes that need neither the mean nor the moments return before computing them (the old code + // computed the mean for every mode and threw it away; skipping it changes no result). + match s { + Stat::Summation => return v.iter().sum::(), + Stat::Minimum => return v.iter().copied().fold(f32::MAX, f32::min), + Stat::Maximum => return v.iter().copied().fold(f32::MIN, f32::max), + Stat::Range => return v.iter().copied().fold(f32::MIN, f32::max) - v.iter().copied().fold(f32::MAX, f32::min), + Stat::Median => { + // `total_cmp` is a total order whose ties are bit-identical values, so an unstable + // sort gives exactly the stable sort's result. + v.sort_unstable_by(f32::total_cmp); + let k = v.len(); + return if k % 2 == 1 { v[k / 2] } else { (v[k / 2 - 1] + v[k / 2]) / 2.0 }; + } + Stat::Entropy => { + if v.len() < 2 { + return 0.0; + } + return entropy(v, scratch); + } + _ => {} + } let mean = v.iter().sum::() / n; - let m = |k: i32| v.iter().map(|x| (x - mean).powi(k)).sum::() / n; + let m = |k: u32| v.iter().map(|x| ipow(x - mean, k)).sum::() / n; match s { Stat::Mean => mean, - Stat::Summation => v.iter().sum::(), - Stat::Minimum => v.iter().copied().fold(f32::MAX, f32::min), - Stat::Maximum => v.iter().copied().fold(f32::MIN, f32::max), - Stat::Range => v.iter().copied().fold(f32::MIN, f32::max) - v.iter().copied().fold(f32::MAX, f32::min), - Stat::Median => { - v.sort_by(f32::total_cmp); - let k = v.len(); - if k % 2 == 1 { v[k / 2] } else { (v[k / 2 - 1] + v[k / 2]) / 2.0 } - } Stat::Variance => m(2), Stat::StandardDeviation => m(2).sqrt(), Stat::Skewness => { let sd = m(2).sqrt(); // Map −2..2 to 0..1 (0.5 = symmetric). - if sd < 1e-6 { 0.5 } else { (m(3) / sd.powi(3) / 4.0 + 0.5).clamp(0.0, 1.0) } + if sd < 1e-6 { 0.5 } else { (m(3) / ipow(sd, 3) / 4.0 + 0.5).clamp(0.0, 1.0) } } Stat::Kurtosis => { let var = m(2); // 0..10 → 0..1. if var < 1e-12 { 0.0 } else { (m(4) / (var * var) / 10.0).clamp(0.0, 1.0) } } - Stat::Entropy => { - if v.len() < 2 { - return 0.0; - } - let mut counts: std::collections::HashMap = std::collections::HashMap::new(); - for x in v.iter() { - *counts.entry((x.clamp(0.0, 1.0) * 255.0).round() as u8).or_default() += 1; - } - let h: f32 = counts - .values() - .map(|&c| { - let p = c as f32 / n; - -p * p.log2() - }) - .sum(); - h / n.log2() - } + // Handled above; a no-op keeps the match exhaustive without a panic path. + Stat::Summation | Stat::Minimum | Stat::Maximum | Stat::Range | Stat::Median | Stat::Entropy => 0.0, } } +/// Output pixels per parallel task: big enough to amortise the per-task scratch buffers and +/// rayon's scheduling, small enough (6000 tasks for 24 MP) to balance across many cores. +const CHUNK: usize = 4096; + /// Combines `layers` (each `len` pixels) with statistic `s`. Colour results retain their float /// range; quantisation/clipping belongs to the destination surface, not the statistic. pub fn combine(layers: &[Vec<[f32; 4]>], s: Stat) -> Vec<[f32; 4]> { + // Pick the statistic once, outside the pixel loop: each arm passes `stat` a constant mode, so + // the compiler builds one loop per statistic with the `match` folded away. Matching on `s` + // three times per pixel inside one shared loop made one thread 5–15% slower than the old + // serial loop (Mean, Variance, StdDev, Skewness, Kurtosis); this alone cuts Mean's + // instructions by a fifth. + match s { + Stat::Entropy => combine_with(layers, |v, sc| stat(v, Stat::Entropy, sc)), + Stat::Kurtosis => combine_with(layers, |v, sc| stat(v, Stat::Kurtosis, sc)), + Stat::Maximum => combine_with(layers, |v, sc| stat(v, Stat::Maximum, sc)), + Stat::Mean => combine_with(layers, |v, sc| stat(v, Stat::Mean, sc)), + Stat::Median => combine_with(layers, |v, sc| stat(v, Stat::Median, sc)), + Stat::Minimum => combine_with(layers, |v, sc| stat(v, Stat::Minimum, sc)), + Stat::Range => combine_with(layers, |v, sc| stat(v, Stat::Range, sc)), + Stat::Skewness => combine_with(layers, |v, sc| stat(v, Stat::Skewness, sc)), + Stat::StandardDeviation => combine_with(layers, |v, sc| stat(v, Stat::StandardDeviation, sc)), + Stat::Summation => combine_with(layers, |v, sc| stat(v, Stat::Summation, sc)), + Stat::Variance => combine_with(layers, |v, sc| stat(v, Stat::Variance, sc)), + } +} + +fn combine_with(layers: &[Vec<[f32; 4]>], f: impl Fn(&mut [f32], &mut EntropyScratch) -> f32 + Sync + Send) -> Vec<[f32; 4]> { let len = layers.iter().map(Vec::len).max().unwrap_or(0); let mut out = vec![[0.0f32; 4]; len]; - let mut samples: [Vec; 3] = Default::default(); - for (i, o) in out.iter_mut().enumerate() { - for v in samples.iter_mut() { - v.clear(); - } - let mut alpha = 0.0f32; - for l in layers { - if let Some(p) = l.get(i) - && p[3] > 0.0 - { - for c in 0..3 { - samples[c].push(p[c]); + // Every output pixel depends only on the input pixels at the same index, so chunks of the + // output are independent: `par_rows` over a `CHUNK`-wide "row" with one channel (it runs + // serially on wasm). The per-pixel arithmetic is unchanged, hence the result is bit-identical + // to the serial loop for every mode (Entropy: see [`entropy`]). + crate::photo_util::par_rows(&mut out, CHUNK, 1, |chunk, outs| { + // Scratch is per chunk, not per pixel: the old loop's three `Vec`s were already reused + // across pixels, so keep that, and give each task its own set. + // Sized to the layer count up front and filled by index (`k` samples per pixel): a + // `push` per sample re-checked the capacity and stored the length every time; indexing + // cuts the loop's instructions by another third. + let mut samples: [Vec; 3] = [0, 1, 2].map(|_| vec![0.0; layers.len()]); + let mut scratch = EntropyScratch::new(); + let base = chunk * CHUNK; + for (j, o) in outs.iter_mut().enumerate() { + let i = base + j; + let mut k = 0; + let mut alpha = 0.0f32; + for l in layers { + if let Some(p) = l.get(i) + && p[3] > 0.0 + { + for c in 0..3 { + samples[c][k] = p[c]; + } + k += 1; + alpha = alpha.max(p[3]); } - alpha = alpha.max(p[3]); } + if alpha <= 0.0 { + continue; + } + for c in 0..3 { + o[c] = f(&mut samples[c][..k], &mut scratch); + } + o[3] = alpha; } - if alpha <= 0.0 { - continue; - } - for c in 0..3 { - o[c] = stat(&mut samples[c], s); - } - o[3] = alpha; - } + }); out } @@ -168,4 +267,246 @@ mod tests { let layers = vec![px(0.5), px(0.5), px(1.0)]; assert_eq!(combine(&layers, Stat::Median)[0][0], 0.5); } + + /// Five layers over six pixels (the last layer is short). Covers opaque, partly transparent, + /// fully transparent, HDR / negative, single-sample and tied-value pixels. + fn fixture() -> Vec> { + vec![ + vec![[0.10, 0.20, 0.30, 1.0], [0.5, 0.5, 0.5, 1.0], [0.9, 0.9, 0.9, 0.0], [-2.0, 4.0, 0.0, 1.0], [0.7, 0.2, 0.1, 0.5], [0.25, 0.25, 0.25, 1.0]], + vec![[0.90, 0.60, 0.30, 1.0], [0.0, 0.0, 0.0, 0.0], [0.8, 0.8, 0.8, 0.0], [3.0, -1.0, 0.5, 0.75], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.25, 1.0]], + vec![[0.20, 0.90, 0.30, 0.5], [0.1, 0.2, 0.3, 1.0], [0.7, 0.7, 0.7, 0.0], [0.5, 0.5, 0.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.5, 0.75, 0.25, 0.25]], + vec![[0.30, 0.05, 0.30, 0.25], [0.3, 0.4, 0.5, 0.5], [0.6, 0.6, 0.6, 0.0], [1.5, 1.5, 1.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.5, 1.0]], + vec![[0.10, 0.70, 0.99, 1.0], [0.9, 0.1, 0.2, 1.0], [0.5, 0.5, 0.5, 0.0], [0.0, 0.0, 0.0, 1.0]], + ] + } + + fn bits(px: &[[f32; 4]]) -> Vec<[u32; 4]> { + px.iter().map(|p| p.map(f32::to_bits)).collect() + } + + /// Every mode except Entropy is bit-for-bit what the old serial loop produced. The expected + /// bit patterns were recorded by running the unmodified `combine` on [`fixture`]. + #[test] + fn statistics_are_bit_identical_to_the_serial_implementation() { + let layers = fixture(); + let expected: Vec<(Stat, Vec<[u32; 4]>)> = vec![ + ( + Stat::Kurtosis, + [ + [0x3e96956b, 0x3e182e3f, 0x3ea66664, 0x3f800000], + [0x3e3d004c, 0x3e0b4396, 0x3e030e1f, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3e594eb2, 0x3e6ef420, 0x3e7ffffe, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3e6eeeee, 0x3e6eeeee, 0x3e6eeeee, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Maximum, + [ + [0x3f666666, 0x3f666666, 0x3f7d70a4, 0x3f800000], + [0x3f666666, 0x3f000000, 0x3f000000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x40400000, 0x40800000, 0x3fc00000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3f000000, 0x3f400000, 0x3f000000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Mean, + [ + [0x3ea3d70a, 0x3efae148, 0x3ee0418a, 0x3f800000], + [0x3ee66666, 0x3e99999a, 0x3ec00000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3f19999a, 0x3f800000, 0x3f000000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3ea00000, 0x3f200000, 0x3ea00000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Median, + [ + [0x3e4ccccd, 0x3f19999a, 0x3e99999a, 0x3f800000], + [0x3ecccccd, 0x3e99999a, 0x3ecccccd, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3f000000, 0x3f000000, 0x3f000000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3e800000, 0x3f400000, 0x3e800000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Minimum, + [ + [0x3dcccccd, 0x3d4ccccd, 0x3e99999a, 0x3f800000], + [0x3dcccccd, 0x3dcccccd, 0x3e4ccccd, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0xc0000000, 0xbf800000, 0x00000000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3e800000, 0x3e800000, 0x3e800000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Range, + [ + [0x3f4ccccc, 0x3f599999, 0x3f30a3d7, 0x3f800000], + [0x3f4ccccc, 0x3ecccccd, 0x3e99999a, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x40a00000, 0x40a00000, 0x3fc00000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3e800000, 0x3f000000, 0x3e800000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Skewness, + [ + [0x3f522026, 0x3ee7cf76, 0x3f600000, 0x3f800000], + [0x3f1bd152, 0x3efffffe, 0x3ee4a11b, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3eedb65a, 0x3f2ea754, 0x3f3a6c7a, 0x3f800000], + [0x3f000000, 0x3f000000, 0x3f000000, 0x3f000000], + [0x3f49e69e, 0x3e58658a, 0x3f49e69e, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::StandardDeviation, + [ + [0x3e99421e, 0x3ea23b6b, 0x3e8d4fdf, 0x3f800000], + [0x3e97739e, 0x3e21e89b, 0x3e050581, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3fd3e0b1, 0x3fd9f9e5, 0x3f0c378c, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3dddb3d7, 0x3e5db3d7, 0x3dddb3d7, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Summation, + [ + [0x3fcccccd, 0x401ccccd, 0x400c28f6, 0x3f800000], + [0x3fe66666, 0x3f99999a, 0x3fc00000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x40400000, 0x40a00000, 0x40200000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3fa00000, 0x40200000, 0x3fa00000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Variance, + [ + [0x3db78033, 0x3dcd9e83, 0x3d9c022a, 0x3f800000], + [0x3db33332, 0x3ccccccd, 0x3c8a3d70, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x402f5c29, 0x4039999a, 0x3e99999a, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3c400000, 0x3d400000, 0x3c400000, 0x3f800000], + ] + .to_vec(), + ), + ]; + for (mode, want) in expected { + assert_eq!(bits(&combine(&layers, mode)), want, "{mode:?}"); + } + } + + /// Entropy against values worked out by hand (bits of the 8-bit histogram, over log2(N)). + #[test] + fn entropy_matches_hand_computed_values() { + let out = combine(&fixture(), Stat::Entropy); + let h = |ps: &[f64]| -> f64 { + let n: f64 = ps.iter().sum(); + ps.iter().map(|c| -(c / n) * (c / n).log2()).sum::() / n.log2() + }; + // Pixel 1: four distinct values -> 2 bits / log2(4) = exactly 1. + assert_eq!(out[1][0], 1.0); + // Pixel 2: every sample transparent -> untouched. + assert_eq!(out[2], [0.0; 4]); + // Pixel 3, red: -2 and 0 land in bin 0, 3 and 1.5 clamp into bin 255, 0.5 is alone. + assert!((f64::from(out[3][0]) - h(&[2.0, 2.0, 1.0])).abs() < 1e-6, "{}", out[3][0]); + // Pixel 4: a single contributing sample has no entropy. + assert_eq!(out[4], [0.0, 0.0, 0.0, 0.5]); + // Pixel 5: three samples share a bin, one is alone, in every channel. + for (c, v) in out[5].iter().take(3).enumerate() { + assert!((f64::from(*v) - h(&[3.0, 1.0])).abs() < 1e-6, "channel {c}: {v}"); + } + } + + /// The old HashMap summed in a random order, so Entropy could differ by an ulp between runs. + /// Now the bins are summed in ascending order: repeated runs (and any thread count) agree. + #[test] + fn entropy_is_deterministic() { + let layers: Vec> = (0..7) + .map(|k| { + (0..3 * CHUNK + 17).map(|i| [((i * 7 + k * 13) % 11) as f32 / 10.0, ((i + k) % 5) as f32 / 4.0, ((i * k) % 9) as f32 / 8.0, 1.0]).collect() + }) + .collect(); + let first = bits(&combine(&layers, Stat::Entropy)); + for _ in 0..8 { + assert_eq!(bits(&combine(&layers, Stat::Entropy)), first); + } + } + + /// Chunking is invisible: a multi-chunk image (with a ragged last chunk and layers of unequal + /// length) gives, pixel by pixel, what combining that pixel on its own gives. + #[test] + fn chunked_result_equals_per_pixel_result() { + let len = 2 * CHUNK + 5; + let layer = |k: usize, n: usize| -> Vec<[f32; 4]> { + (0..n) + .map(|i| { + [ + ((i * 31 + k * 7) % 101) as f32 / 100.0, + ((i * 17 + k) % 53) as f32 / 52.0 - 0.2, + ((i + 3 * k) % 29) as f32 / 28.0, + if (i + k).is_multiple_of(4) { 0.0 } else { 0.5 + ((i + k) % 3) as f32 / 4.0 }, + ] + }) + .collect() + }; + let layers = vec![layer(1, len), layer(2, CHUNK + 3), layer(3, len - 1), layer(4, 0), layer(5, len)]; + for mode in [ + Stat::Entropy, + Stat::Kurtosis, + Stat::Maximum, + Stat::Mean, + Stat::Median, + Stat::Minimum, + Stat::Range, + Stat::Skewness, + Stat::StandardDeviation, + Stat::Summation, + Stat::Variance, + ] { + let whole = combine(&layers, mode); + assert_eq!(whole.len(), len); + for i in (0..len).step_by(97).chain([CHUNK - 1, CHUNK, CHUNK + 1, 2 * CHUNK - 1, 2 * CHUNK, len - 1]) { + let one: Vec> = layers.iter().map(|l| l.get(i).map(|p| vec![*p]).unwrap_or_default()).collect(); + assert_eq!(whole[i].map(f32::to_bits), combine(&one, mode)[0].map(f32::to_bits), "{mode:?} pixel {i}"); + } + } + } + + #[test] + fn no_layers_gives_an_empty_result() { + assert!(combine(&[], Stat::Median).is_empty()); + } + + /// [`ipow`] multiplies in the order `x·x²` for the cube and `x²·x²` for the fourth power. + #[test] + fn ipow_squares_and_multiplies() { + for x in [0.58f32, -0.12, -2.6, 2.4, -0.6, 1.0e-3, 0.0] { + assert_eq!(ipow(x, 0).to_bits(), 1.0f32.to_bits()); + assert_eq!(ipow(x, 1).to_bits(), x.to_bits()); + assert_eq!(ipow(x, 2).to_bits(), (x * x).to_bits()); + assert_eq!(ipow(x, 3).to_bits(), (x * (x * x)).to_bits()); + assert_eq!(ipow(x, 4).to_bits(), ((x * x) * (x * x)).to_bits()); + } + } } diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rs index 31def5f99d..b7fc92113c 100644 --- a/crates/algo/src/tests.rs +++ b/crates/algo/src/tests.rs @@ -90,6 +90,27 @@ fn radial_blur_quality_defaults_for_older_serialized_parameters() { assert_eq!(decoded, FilterParams::RadialBlur { amount: 20.0, method: RadialMethod::Spin, quality: RadialQuality::Good, center_x: 0.5, center_y: 0.5 }); } +#[test] +fn nonpositive_tile_sizes_match_one_pixel_tiles() { + let area = Rect::new(0, 0, 4, 3); + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let source = pattern(depth, area); + for params in all_filters().into_iter().chain([FilterParams::ShapeBlur { radius: 3.0, shape: BlurShape::Star }]) { + let expected = apply_tiled(&source, ¶ms, area, area, None, 1, Some(area)); + for tile in [0, -64, i32::MIN] { + let actual = apply_tiled(&source, ¶ms, area, area, None, tile, Some(area)); + assert_eq!(actual.read_region(area), expected.read_region(area), "{}: {depth:?}, tile={tile}", params.label()); + let cancellable = apply_tiled_with(&source, ¶ms, area, area, None, tile, Some(area), &photocraft_raster::Interrupt::NONE) + .expect("a nonpositive tile size is normalized, not rejected"); + assert_eq!(cancellable.read_region(area), expected.read_region(area), "{}: {depth:?}, tile={tile}", params.label()); + let cancelled = photocraft_raster::Interrupt::cancel_only(&|| true); + assert!(apply_tiled_with(&source, ¶ms, area, area, None, tile, Some(area), &cancelled).is_none()); + } + } + assert_eq!(source.read_region(area), pattern(depth, area).read_region(area)); + } +} + #[test] fn every_filter_is_tile_independent() { let s = pattern(SampleType::U8, R); @@ -248,6 +269,32 @@ fn minimum_maximum_spread() { assert!((mn.pixel(10, 10)[0] - 0.5).abs() < 1e-6); } +/// CMYK samples are ink, so Maximum spreads paper white and Minimum spreads ink, as Photoshop +/// does: Maximum r 1 removes a 1-px C 100% line on white, Minimum widens it to 3 px. Alpha keeps +/// the usual polarity (Maximum grows opaque areas, Minimum grows transparent ones). +#[test] +fn minimum_maximum_treat_cmyk_as_ink() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut s = Surface::new(PixelFormat::new(ColorMode::Cmyk, depth, true)); + s.fill_rect(R, &[0.0, 0.0, 0.0, 0.0, 1.0]); + s.fill_rect(Rect::new(20, 0, 21, 30), &[1.0, 0.0, 0.0, 0.0, 1.0]); + s.write_pixel(5, 5, &[0.0, 0.0, 0.0, 0.0, 0.0]); + for preserve in [Preserve::Squareness, Preserve::Roundness] { + let mx = run(&s, &FilterParams::Maximum { radius: 1.0, preserve }); + for x in 17..24 { + assert!(mx.pixel(x, 15)[0].abs() < 1e-6, "{depth:?} {preserve:?} Maximum C at x {x}: {:?}", mx.pixel(x, 15)); + } + assert!((mx.pixel(5, 5)[4] - 1.0).abs() < 1e-6, "{depth:?} {preserve:?} Maximum grows alpha"); + let mn = run(&s, &FilterParams::Minimum { radius: 1.0, preserve }); + for x in 17..24 { + let want = if (19..=21).contains(&x) { 1.0 } else { 0.0 }; + assert!((mn.pixel(x, 15)[0] - want).abs() < 1e-6, "{depth:?} {preserve:?} Minimum C at x {x}: {:?}", mn.pixel(x, 15)); + } + assert!(mn.pixel(6, 5)[4].abs() < 1e-6, "{depth:?} {preserve:?} Minimum shrinks alpha"); + } + } +} + #[test] fn maximum_roundness_grows_a_point_into_a_disc() { // One white pixel on black: Maximum spreads it over the structuring element itself. @@ -414,6 +461,24 @@ fn twirl_keeps_centre_and_outside() { assert_ne!(out.pixel(20, 12), s.pixel(20, 12)); } +/// #5643: on a wide image Twirl, Pinch and Spherize fill the ellipse inscribed in the bounds, as +/// Photoshop's do, not just a circle fitted to the height: a point near the left and right edges +/// on the middle row changes, the corners don't, and a square still uses its inscribed circle. +#[test] +fn round_distortions_fill_the_inscribed_ellipse() { + let b = Rect::new(0, 0, 80, 40); + let s = pattern(SampleType::F32, b); + for p in [FilterParams::Twirl { angle: 180.0 }, FilterParams::Pinch { amount: 80.0 }, FilterParams::Spherize { amount: 80.0, mode: SpherizeMode::Normal }] { + let out = apply(&s, &p, b, b, None); + // 30 px left of centre on the middle row: outside the old 20 px circle, inside the ellipse. + assert_ne!(out.pixel(10, 21), s.pixel(10, 21), "{p:?}"); + assert_ne!(out.pixel(69, 18), s.pixel(69, 18), "{p:?}"); + for (x, y) in [(0, 0), (79, 0), (0, 39), (79, 39)] { + assert_eq!(out.pixel(x, y), s.pixel(x, y), "{p:?}: corner ({x}, {y}) is outside the ellipse"); + } + } +} + #[test] fn motion_blur_spreads_along_angle_only() { let mut s = flat(SampleType::F32, R, [0.0, 0.0, 0.0, 1.0]); diff --git a/crates/algo/src/tests_ext.rs b/crates/algo/src/tests_ext.rs index fd35f2742a..7c28485f1f 100644 --- a/crates/algo/src/tests_ext.rs +++ b/crates/algo/src/tests_ext.rs @@ -435,6 +435,35 @@ fn lens_flare_is_brightest_at_its_centre() { assert!(out.pixel(38, 2)[0] >= 0.2 - 1e-6, "screen never darkens"); } +#[test] +fn lens_flare_never_darkens_32_bit_values_above_one() { + // #5785: the screen formula turned 2.0 into 1.5 (and 1.0 at the core). + let p = FilterParams::LensFlare { brightness: 150.0, center_x: 0.25, center_y: 0.5, lens: LensType::Zoom }; + let out = run(&flat(SampleType::F32, R, [2.0, 2.0, 2.0, 1.0]), &p); + for px in out.read_region(R).as_chunks::<4>().0 { + assert!(px[..3].iter().all(|&v| v >= 2.0), "{px:?}"); + } +} + +#[test] +fn lens_flare_8_bit_result_is_the_screen_blend() { + // The flare amount per pixel, read from a black 32-bit image (screen over 0 is the amount). + let p = FilterParams::LensFlare { brightness: 150.0, center_x: 0.25, center_y: 0.5, lens: LensType::Zoom }; + let amount = run(&flat(SampleType::F32, R, [0.0, 0.0, 0.0, 1.0]), &p).read_region(R); + let src = pattern(SampleType::U8, R); + let base = src.read_region(R); + let expected: Vec = base + .as_chunks::<4>() + .0 + .iter() + .zip(amount.as_chunks::<4>().0) + .flat_map(|(c, a)| [0, 1, 2].map(|k| 1.0 - (1.0 - c[k]) * (1.0 - a[k].min(1.0))).into_iter().chain([c[3]])) + .collect(); + let mut want = Surface::new(fmt(SampleType::U8)); + want.write_region(R, &expected); + assert_eq!(run(&src, &p).read_region(R), want.read_region(R)); +} + #[test] fn lighting_point_light_falls_off() { let s = flat(SampleType::F32, R, [0.8, 0.8, 0.8, 1.0]); @@ -608,6 +637,28 @@ fn custom_kernel_shifts_and_offsets() { assert!((off.pixel(5, 5)[0] - 0.4).abs() < 1e-5); } +/// CMYK samples are ink: Custom's positive offset brightens (removes ink), as in Photoshop +/// (identity, scale 1, offset +50: white stays white, C=100% becomes C≈80%). Alpha is untouched. +/// Photoshop's CMYK depths; float is unclamped on both polarities (RGB white + offset exceeds 1). +#[test] +fn custom_offset_brightens_cmyk() { + let mut id = vec![0.0; 25]; + id[12] = 1.0; + let p = FilterParams::Custom { kernel: id, scale: 1.0, offset: 50.0 }; + for depth in [SampleType::U8, SampleType::U16] { + let f = PixelFormat::new(ColorMode::Cmyk, depth, true); + let mut s = Surface::new(f); + s.fill_rect(R, &[0.0, 0.0, 0.0, 0.0, 0.6]); + let w = run(&s, &p).pixel(5, 5); + assert!(w[..4].iter().all(|v| v.abs() < 1e-6) && (w[4] - 0.6).abs() < 0.01, "{depth:?} white: {w:?}"); + let mut s = Surface::new(f); + s.fill_rect(R, &[1.0, 0.5, 0.0, 0.0, 1.0]); + let c = run(&s, &p).pixel(5, 5); + let want = [1.0 - 50.0 / 255.0, 0.5 - 50.0 / 255.0, 0.0, 0.0, 1.0]; + assert!(c.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01), "{depth:?} C100: {c:?}"); + } +} + #[test] fn hsb_filter_encodes_and_decodes() { let s = flat(SampleType::F32, R, [1.0, 0.0, 0.0, 1.0]); diff --git a/crates/algo/src/tone.rs b/crates/algo/src/tone.rs index 2632d4a29a..5a0f752fac 100644 --- a/crates/algo/src/tone.rs +++ b/crates/algo/src/tone.rs @@ -65,6 +65,35 @@ pub fn replace_color(px: &mut [[f32; 4]], color: [f32; 3], fuzziness: f32, hue: mask } +/// Replace Color's Result swatch: `color` after the hue (±180°), saturation and lightness (±100) +/// shift, as a fully matched pixel of that colour becomes. +pub fn replace_color_result(color: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [f32; 3] { + let mut px = [[color[0], color[1], color[2], 1.0]]; + replace_color_masked(&mut px, &[1.0], hue, saturation, lightness); + [px[0][0], px[0][1], px[0][2]] +} + +/// The hue (±180°), saturation and lightness (±100) shift that turns `from` into `to`, as +/// Photoshop's Result Color Picker sets the sliders. A shift the sliders can't reach (a grey has +/// no hue to turn, black or white no saturation to give) goes as far as they do. +pub fn replace_color_shift(from: [f32; 3], to: [f32; 3]) -> (f32, f32, f32) { + let [fh, fs, fl] = rgb_to_hsl(from); + let [th, ts, tl] = rgb_to_hsl(to); + // Hue turns the short way round; a grey target keeps the hue where it is. + let hue = if ts <= 0.0 { 0.0 } else { ((th - fh + 0.5).rem_euclid(1.0) - 0.5) * 360.0 }; + // Inverse of the shift in `replace_color_masked`: up moves toward 1, down toward 0. + let amount = |from: f32, to: f32| { + if to >= from { + if from >= 1.0 { 0.0 } else { (to - from) / (1.0 - from) * 100.0 } + } else if from <= 0.0 { + 0.0 + } else { + (to / from - 1.0) * 100.0 + } + }; + (hue.clamp(-180.0, 180.0), amount(fs, ts).clamp(-100.0, 100.0), amount(fl, tl).clamp(-100.0, 100.0)) +} + /// Replace Color's hue, saturation and lightness shift, applied to each pixel as far as `mask` /// (`0..=1`, one per pixel: the colour match, localized or not) covers it. pub fn replace_color_masked(px: &mut [[f32; 4]], mask: &[f32], hue: f32, saturation: f32, lightness: f32) { @@ -277,6 +306,28 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) { mod tests { use super::*; + /// #6278: the Result swatch is the sampled colour after the shift, and a picked Result sets + /// the sliders that give it. + #[test] + fn replace_color_result_and_shift_round_trip() { + let from = [0.8, 0.2, 0.2]; + let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 2e-3); + assert!(near(replace_color_result(from, 0.0, 0.0, 0.0), from), "no shift, no change"); + for to in [[0.2, 0.3, 0.9], [0.9, 0.85, 0.1], [0.4, 0.1, 0.1], [0.95, 0.6, 0.6], [0.1, 0.6, 0.3]] { + let (h, s, l) = replace_color_shift(from, to); + assert!((-180.0..=180.0).contains(&h) && (-100.0..=100.0).contains(&s) && (-100.0..=100.0).contains(&l)); + assert!(near(replace_color_result(from, h, s, l), to), "{to:?}: ({h}, {s}, {l}) gives {:?}", replace_color_result(from, h, s, l)); + } + // Red to blue turns the short way (−120°, not +240°). + assert!((replace_color_shift([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]).0 + 120.0).abs() < 0.5); + // A grey target: saturation all the way down, the hue left alone. + let (h, s, _) = replace_color_shift(from, [0.5, 0.5, 0.5]); + assert_eq!((h, s), (0.0, -100.0)); + // Black has no saturation to raise: the slider stays put rather than dividing by zero. + let (h, s, l) = replace_color_shift([0.0, 0.0, 0.0], [0.2, 0.6, 0.3]); + assert!(h.is_finite() && s.is_finite() && l > 0.0); + } + fn ramp(w: usize, h: usize) -> Vec<[f32; 4]> { (0..w * h) .map(|i| { diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 050d08c322..91260bd285 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -231,14 +231,37 @@ pub fn quad_to_rect(q: &[[f64; 2]; 4], w: f64, h: f64) -> Option { /// The destination rectangle [`warp_surface`] fills for `src_rect` under `h`: the warped corners /// plus a pixel for filter support, each side clamped to ±2²⁰. `None` when a corner maps to -/// infinity (the result is then empty). Lets a caller price a warp before allocating it. +/// infinity (the result is then empty). Use [`warp_output_size`] to price the full result before +/// admitting a transform: clipping these bounds must not hide an excessive scale. pub fn warp_output_bounds(src_rect: Rect, h: &Homography) -> Option { + corner_bounds(&warp_corners(src_rect, h)?) +} + +/// Unclipped output dimensions, including the same filter support as [`warp_output_bounds`]. +/// Position does not affect the price, so translating a small layer far away stays cheap. +/// Unrepresentable or non-finite dimensions saturate at `u64::MAX`, allowing a caller to refuse +/// the warp with a saturating pixel-budget comparison. Empty and singular inputs have no output. +pub fn warp_output_size(src_rect: Rect, h: &Homography) -> Option<(u64, u64)> { + let corners = warp_corners(src_rect, h)?; + if !corners.iter().all(|(x, y)| x.is_finite() && y.is_finite()) { + return Some((u64::MAX, u64::MAX)); + } + let x0 = corners.iter().map(|c| c.0).fold(f64::MAX, f64::min).floor(); + let y0 = corners.iter().map(|c| c.1).fold(f64::MAX, f64::min).floor(); + let x1 = corners.iter().map(|c| c.0).fold(f64::MIN, f64::max).ceil(); + let y1 = corners.iter().map(|c| c.1).fold(f64::MIN, f64::max).ceil(); + // Float-to-integer casts saturate, including when the finite endpoints' difference overflows. + Some((((x1 - x0) as u64).saturating_add(2), ((y1 - y0) as u64).saturating_add(2))) +} + +fn warp_corners(src_rect: Rect, h: &Homography) -> Option<[(f64, f64); 4]> { if src_rect.is_empty() || h.inverse().is_none() { return None; } - let corners = [(src_rect.x0, src_rect.y0), (src_rect.x1, src_rect.y0), (src_rect.x1, src_rect.y1), (src_rect.x0, src_rect.y1)] - .map(|(x, y)| h.apply(x as f64, y as f64)); - corner_bounds(&corners) + Some( + [(src_rect.x0, src_rect.y0), (src_rect.x1, src_rect.y0), (src_rect.x1, src_rect.y1), (src_rect.x0, src_rect.y1)] + .map(|(x, y)| h.apply(x as f64, y as f64)), + ) } fn corner_bounds(corners: &[(f64, f64); 4]) -> Option { @@ -310,7 +333,12 @@ fn warp( // A source straddling the horizon draws only its front side: the inverse w at a pixel has the // sign of the forward w at the source point it samples, and the other side would show as a // mirrored copy wrapped round infinity (#4863). - let front = side.is_none().then(|| h.front_side([src_rect.x0 as f64, src_rect.y0 as f64, src_rect.x1 as f64, src_rect.y1 as f64])); + // A clip wholly on one side of the inverse horizon only samples that side, so that side is drawn + // (a Perspective Crop low on a converging photo has most of the layer beyond its horizon, #7557). + let clip_w = clip.map(|c| [(c.x0, c.y0), (c.x1, c.y0), (c.x1, c.y1), (c.x0, c.y1)].map(|(x, y)| inv.w(x as f64, y as f64))); + let clip_side = clip_w.and_then(|cw| [1.0, -1.0].into_iter().find(|&s| cw.iter().all(|&w| s * w > 0.0))); + let front = + side.is_none().then(|| clip_side.unwrap_or_else(|| h.front_side([src_rect.x0 as f64, src_rect.y0 as f64, src_rect.x1 as f64, src_rect.y1 as f64]))); let bounds = corner_bounds(&corners); let dst = match (clip, bounds) { // The warped corners only bound the result while the whole source is in front of the horizon. @@ -510,6 +538,31 @@ fn warp( mod tests { use super::*; + #[test] + fn output_size_prices_the_unclipped_extent_independently_of_position() { + let src = Rect::new(0, 0, 24, 16); + for dx in [0.0, 900_000.0, 10_000_000.0] { + let h = Homography([1.0, 0.0, dx, 0.0, 1.0, -dx, 0.0, 0.0, 1.0]); + assert_eq!(warp_output_size(src, &h), Some((26, 18))); + } + for sx in [1e7, -1e7] { + let h = Homography([sx, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + assert_eq!(warp_output_size(src, &h), Some((240_000_002, 18))); + } + } + + #[test] + fn output_size_saturates_overflows_and_preserves_filter_support() { + let src = Rect::new(0, 0, 24, 16); + let fractional = Homography([0.5, 0.0, 0.25, 0.0, 1.0, 0.75, 0.0, 0.0, 1.0]); + let bounds = warp_output_bounds(src, &fractional).unwrap(); + assert_eq!(warp_output_size(src, &fractional), Some((u64::from(bounds.width()), u64::from(bounds.height())))); + let huge = Homography([1e308, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + assert_eq!(warp_output_size(src, &huge), Some((u64::MAX, u64::MAX))); + assert_eq!(warp_output_size(Rect::EMPTY, &Homography::IDENTITY), None); + assert_eq!(warp_output_size(src, &Homography([0.0; 9])), None); + } + #[test] fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { let mut s = Surface::new(PixelFormat::RGBA8); @@ -665,6 +718,22 @@ mod tests { assert_eq!(ok.front_side([0.0, 0.0, 100.0, 100.0]), ok.w(50.0, 50.0).signum()); } + /// #7557: a Perspective Crop quad low on a strongly converging photo puts the horizon across + /// the layer with most of it (and its centre) on the far side. The clip maps wholly into the + /// quad, so its side is the one drawn, not the source's majority. + #[test] + fn a_clip_wholly_on_one_side_draws_that_side() { + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); + let q = [[40.0, 70.0], [60.0, 70.0], [90.0, 95.0], [10.0, 95.0]]; + let h = quad_to_rect(&q, 50.0, 39.0).unwrap(); + assert!(h.front_side([0.0, 0.0, 100.0, 100.0]) * h.w(50.0, 80.0) < 0.0, "the source's majority is behind the quad's side"); + for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { + let w = warp_surface_clipped(&s, s.content_bounds(), &h, interp, Rect::new(0, 0, 50, 39)).unwrap(); + assert_eq!(w.rgba(25, 20), [1.0, 0.0, 0.0, 1.0], "{interp:?}"); + } + } + #[test] fn identity_and_translation_are_exact() { let mut s = rgba(); diff --git a/crates/algo/src/warp.rs b/crates/algo/src/warp.rs index 188de07d47..54a6c7c868 100644 --- a/crates/algo/src/warp.rs +++ b/crates/algo/src/warp.rs @@ -14,8 +14,9 @@ //! later (lower-right) cell wins. Work is split per destination tile (parallel on native). use photocraft_color::PixelFormat; -use photocraft_geom::Rect; -use photocraft_raster::Surface; +use photocraft_geom::{Rect, TileCoord}; +use photocraft_raster::{Surface, Tile}; +use std::sync::Arc; use crate::transform::{Interp, bicubic}; @@ -207,7 +208,7 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2 } let n = fmt.channels(); let a = n - 1; - let work = |(t, tris): (&Rect, &Vec<[usize; 3]>)| -> Option<(Rect, Vec)> { + let work = |(t, tris): (&Rect, &Vec<[usize; 3]>)| -> Option<(TileCoord, Arc)> { if tris.is_empty() { return None; } @@ -296,6 +297,11 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2 f64::from(px[((y - foot.y0) as usize * fw + (x - foot.x0) as usize) * n + c]) } }; + // Offset of pixel (x, y) when the `taps` x `taps` block from it lies inside `foot`, so + // the samplers can index `px` directly instead of bounds-checking every tap. + let base = |x: i32, y: i32, taps: i32| -> Option { + (x >= foot.x0 && y >= foot.y0 && x + taps <= foot.x1 && y + taps <= foot.y1).then(|| ((y - foot.y0) as usize * fw + (x - foot.x0) as usize) * n) + }; let mut outp = vec![0.0f32; w * h * n]; let mut any = false; let mut acc = [0.0f64; 8]; @@ -313,6 +319,17 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2 Interp::Bilinear => { let (ix, iy) = (u.floor() as i32, v.floor() as i32); let (fx, fy) = (u - f64::from(ix), v - f64::from(iy)); + if let Some(o) = base(ix, iy, 2) { + for (dy, wy) in [(0, 1.0 - fy), (1, fy)] { + for (dx, wx) in [(0, 1.0 - fx), (1, fx)] { + let p = &px[o + (dy * fw + dx) * n..][..n]; + for (s, v) in acc.iter_mut().zip(p) { + *s += f64::from(*v) * wx * wy; + } + } + } + return; + } for (dy, wy) in [(0, 1.0 - fy), (1, fy)] { for (dx, wx) in [(0, 1.0 - fx), (1, fx)] { for (c, s) in acc.iter_mut().enumerate().take(n) { @@ -327,6 +344,21 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2 let (u, v) = (snap(u), snap(v)); let (ix, iy) = (u.floor() as i32, v.floor() as i32); let (wx, wy) = (bicubic(u - f64::from(ix)), bicubic(v - f64::from(iy))); + if let Some(o) = base(ix - 1, iy - 1, 4) { + for (j, wyj) in wy.iter().enumerate() { + for (i, wxi) in wx.iter().enumerate() { + let k = wxi * wyj; + if k == 0.0 { + continue; + } + let p = &px[o + (j * fw + i) * n..][..n]; + for (s, v) in acc.iter_mut().zip(p) { + *s += f64::from(*v) * k; + } + } + } + return; + } for (j, wyj) in wy.iter().enumerate() { for (i, wxi) in wx.iter().enumerate() { let k = wxi * wyj; @@ -378,19 +410,27 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2 } outp[b + a] = al as f32; } - any.then_some((*t, outp)) + if !any { + return None; + } + // Encoded (and dropped if fully transparent) here, in parallel, rather than one tile at + // a time once all are done. `t` lies in one tile. + let mut one = Surface::new(fmt); + one.write_region(*t, &outp); + one.prune(); + if one.tile_count() == 0 { + return None; + } + one.take_tiles(*t).pop() }; #[cfg(not(target_arch = "wasm32"))] - let done: Vec<(Rect, Vec)> = { + let done: Vec<(TileCoord, Arc)> = { use rayon::prelude::*; tiles.par_iter().zip(bins.par_iter()).filter_map(work).collect() }; #[cfg(target_arch = "wasm32")] - let done: Vec<(Rect, Vec)> = tiles.iter().zip(bins.iter()).filter_map(work).collect(); - for (r, v) in done { - out.write_region(r, &v); - } - out.prune(); + let done: Vec<(TileCoord, Arc)> = tiles.iter().zip(bins.iter()).filter_map(work).collect(); + out.put_tiles(done); out } diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 0738140a41..f5e88b3591 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "photocraft-automation" -description = "MCP server (rmcp) over the Photocraft engine, plus a bridge to a running GUI" +description = "MCP server (rmcp) over the PhotoCraft engine, plus a bridge to a running GUI" version.workspace = true edition.workspace = true license.workspace = true @@ -30,3 +30,7 @@ cap-std = "4" [dev-dependencies] rmcp = { version = "3.5", default-features = false, features = ["client", "server", "macros", "transport-io"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] } + +# Reading back an extended attribute the write path should have preserved (#7095). +[target.'cfg(unix)'.dev-dependencies] +rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index cd34ab3410..fc4526eedb 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -19,7 +19,8 @@ pub struct Opened { /// Decode a document that was read through a filesystem capability. pub fn open_bytes(name: &str, bytes: &[u8]) -> Result { if Path::new(name).extension().is_some_and(|extension| extension.eq_ignore_ascii_case(photocraft_format::EXTENSION)) { - return Ok(Opened { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new(), source_read_only: false }); + let document = photocraft_format::load_from_bytes(bytes)?; + return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false }); } let r = photocraft_io::import(name, bytes)?; Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only }) @@ -29,7 +30,8 @@ pub fn open_bytes(name: &str, bytes: &[u8]) -> Result { /// natively; everything else goes through `photocraft-io` (PSD, PNG, …). pub fn open(path: &Path) -> Result { if path.is_dir() { - return Ok(Opened { document: photocraft_format::load_path(path)?, warnings: Vec::new(), source_read_only: false }); + let document = photocraft_format::load_path(path)?; + return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false }); } let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 15a0e24e30..3db25c4fdd 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -114,6 +114,7 @@ impl Headless { let mut opts = photocraft_io::ExportOptions { tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits, ..Default::default() }; opts.encode.dpx_bits = photocraft_engine::file_cmds::dpx_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; + opts.encode.dds = photocraft_engine::file_cmds::dds_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?.unwrap_or_default(); if let Some(q) = p.get("quality").and_then(Value::as_u64) { opts.encode.jpeg_quality = q.clamp(1, 100) as u8; opts.encode.webp_quality = q.clamp(1, 100) as u8; diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 7928420b12..0735511f20 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -97,11 +97,15 @@ pub fn validate_token(token: &str) -> Result<(), AutomationError> { } /// Compare fixed-width tokens without an early exit on a mismatching byte. +/// +/// Hex letters match in either case: [`validate_token`] accepts uppercase, and the server keeps +/// the token lowercased, so a client sending the token exactly as it was configured must still +/// authenticate (#6425). Only `A`–`Z` fold, so a non-hex byte never matches a hex digit. pub fn token_matches(expected: &str, supplied: &str) -> bool { if expected.len() != TOKEN_HEX_LEN || supplied.len() != TOKEN_HEX_LEN { return false; } - expected.bytes().zip(supplied.bytes()).fold(0u8, |different, (a, b)| different | (a ^ b)) == 0 + expected.bytes().zip(supplied.bytes()).fold(0u8, |different, (a, b)| different | (a.to_ascii_lowercase() ^ b.to_ascii_lowercase())) == 0 } /// Validate the first TCP frame without exposing any control method before authentication. @@ -135,7 +139,27 @@ pub fn repeat_auth_reply(line: &str) -> Option { } fn read_token_file(path: &Path) -> Result { - let token = std::fs::read_to_string(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; + // Validate what we actually opened, not just the name: an existing control-token file must be + // a regular file that no other local principal can read. A freshly created one is 0600 + // (`create_token_file`); an operator-supplied one is checked here so a group- or world-readable + // token is refused rather than trusted as the control credential (#4966). + let mut file = std::fs::File::open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; + let meta = file.metadata().map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; + if !meta.is_file() { + return Err(AutomationError::Io(format!("{}: control token file is not a regular file", path.display()))); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if meta.mode() & 0o077 != 0 { + return Err(AutomationError::Io(format!( + "{}: control token file is readable by group or others (mode {:o}); restrict it to its owner (e.g. chmod 600)", + path.display(), + meta.mode() & 0o777 + ))); + } + } + let token = std::io::read_to_string(&mut file).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; let token = token.trim().to_owned(); validate_token(&token)?; Ok(token) @@ -348,6 +372,45 @@ mod tests { assert_eq!(reply["result"]["authenticated"], true); } + fn auth_line(token: &str) -> String { + json!({"id": 1, "method": AUTH_METHOD, "params": {"token": token}}).to_string() + } + + /// #6425: `validate_token` accepts uppercase hex and the server keeps the token lowercased, so a + /// client sending the token exactly as it was configured was refused. + #[test] + fn a_token_authenticates_in_any_letter_case() { + let configured = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; + let mixed = "0123456789AbCdEf0123456789aBcDeF0123456789ABCDEF0123456789abcdef"; + let expected = server_token(Some(configured), None).unwrap(); + for supplied in [configured, &configured.to_ascii_lowercase(), mixed] { + let (reply, authenticated) = authentication_reply(&auth_line(supplied), &expected); + assert!(authenticated, "{supplied}: {reply}"); + assert_eq!(reply["result"]["authenticated"], true); + } + // The comparison is case-insensitive in both directions. + assert!(token_matches(configured, &configured.to_ascii_lowercase())); + + // A different token, or a non-hex character that only folds to a hex one, still fails. + let other = "1123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; + let (_, authenticated) = authentication_reply(&auth_line(other), &expected); + assert!(!authenticated); + let not_hex = "0123456789ABCDEG0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; + assert!(!token_matches(&expected, not_hex)); + } + + /// #6425: the same for a token file whose contents are uppercase. + #[test] + fn an_uppercase_token_file_authenticates_its_exact_contents() { + let path = std::env::temp_dir().join(format!("photocraft-control-token-upper-{}-{}.txt", std::process::id(), generate_token().unwrap())); + let contents = generate_token().unwrap().to_ascii_uppercase(); + create_token_file(&path, &contents).unwrap(); + let expected = server_token(None, Some(&path)); + std::fs::remove_file(&path).unwrap(); + let (reply, authenticated) = authentication_reply(&auth_line(&contents), &expected.unwrap()); + assert!(authenticated, "{reply}"); + } + #[test] fn repeat_auth_on_an_authenticated_connection_says_so() { let line = json!({"id": 3, "method": AUTH_METHOD, "params": {"token": "anything"}}).to_string(); @@ -417,22 +480,50 @@ mod tests { #[test] fn an_authenticated_connection_outlives_the_authentication_deadline() { let (server, mut client) = tcp_pair(); + // The test thread writes the first line before the deadline starts. The sender writes the + // second line once the connection has authenticated and the deadline has passed. + client.write_all(b"one\n").unwrap(); + let limit = Duration::from_secs(1); + let mut reader = std::io::BufReader::new(AuthDeadlineStream::new(server, limit)); + let deadline = Instant::now() + limit; + let (tx, rx) = std::sync::mpsc::channel(); let sender = std::thread::spawn(move || { - client.write_all(b"one\n").unwrap(); - std::thread::sleep(Duration::from_millis(500)); + rx.recv().unwrap(); + std::thread::sleep((deadline + Duration::from_millis(300)).saturating_duration_since(Instant::now())); client.write_all(b"two\n").unwrap(); }); - let mut reader = std::io::BufReader::new(AuthDeadlineStream::new(server, Duration::from_millis(200))); let mut line = String::new(); assert_eq!(read_bounded_line(&mut reader, &mut line).unwrap(), LineRead::Line); assert_eq!(line, "one\n"); reader.get_mut().authenticated().unwrap(); + tx.send(()).unwrap(); // Sent 300 ms after the deadline: only the idle timeout applies now. assert_eq!(read_bounded_line(&mut reader, &mut line).unwrap(), LineRead::Line); assert_eq!(line, "two\n"); sender.join().unwrap(); } + #[cfg(unix)] + #[test] + fn an_existing_token_file_must_be_owner_only() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("photocraft-token-perm-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("token.txt"); + let token = "0123456789abcdef".repeat(4); // 64 hex chars, passes validate_token + std::fs::write(&path, &token).unwrap(); + + // A group- or world-readable token is refused: the control credential must not be shared (#4966). + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(read_token_file(&path).is_err(), "a 0644 token file must be refused"); + + // Owner-only is opened, read and validated. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(read_token_file(&path).unwrap(), token, "a 0600 token file must be read"); + + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn connection_limiter_releases_capacity() { let limiter = ConnectionLimiter::new(1); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index f52376a9c5..567d0b4837 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -170,6 +170,13 @@ pub struct SaveParams { /// DPX: 8, 10, 12 or 16 bits per sample. Unset: 8 for an 8-bit document, else 16. #[serde(default, rename = "dpxBits")] pub dpx_bits: Option, + /// DDS: "none" (uncompressed, the default), "bc1" (DXT1: alpha on or off), "bc2" (DXT3) or + /// "bc3" (DXT5). + #[serde(default, rename = "ddsCompression")] + pub dds_compression: Option, + /// DDS: also write the full mip chain, each level a box filter of the one above. + #[serde(default, rename = "ddsMipmaps")] + pub dds_mipmaps: bool, #[serde(default)] pub index: Option, } @@ -1001,10 +1008,15 @@ impl PhotocraftMcp { Some((_, Some(bits))) => Some(bits), Some((b, None)) => return Ok(fail(format!("`dpxBits` must be 8, 10, 12 or 16, got {b}"))), }; + let dds_compression = match p.dds_compression.as_deref().map(|c| (c, photocraft_io::DdsCompression::from_name(c))) { + None => None, + Some((_, Some(c))) => Some(c), + Some((c, None)) => return Ok(fail(format!("`ddsCompression` must be none, bc1, bc2 or bc3, got {c:?}"))), + }; if let Some(b) = self.bridge_client() { // The bridge forwards to the running app's `app.save`, which takes only an optional // path (without one it writes back to the document's own layered file, as headless - // does) and the Targa bits, so the other options are headless-only. Saying so beats + // does), the Targa bits and the DDS options, so the other options are headless-only. Saying so beats // saving with defaults while the caller believes their quality or format was applied. let unsupported: Vec<&str> = [ p.format.is_some().then_some("format"), @@ -1026,12 +1038,19 @@ impl PhotocraftMcp { if let Some(bits) = tga_bits { params["tgaBits"] = json!(bits.bits()); } + if let Some(c) = dds_compression { + params["ddsCompression"] = json!(c.name()); + } + if p.dds_mipmaps { + params["ddsMipmaps"] = json!(true); + } return to_result(b.call("app.save", params).await); } let Some(r) = self .headless_op(move |h| { let mut opts = photocraft_io::ExportOptions { tiff_layers: p.tiff_layers, tga_bits, ..Default::default() }; opts.encode.dpx_bits = dpx_bits; + opts.encode.dds = photocraft_io::DdsOptions { compression: dds_compression.unwrap_or_default(), mipmaps: p.dds_mipmaps }; if let Some(q) = p.quality { opts.encode.jpeg_quality = q.clamp(1, 100); opts.encode.webp_quality = q.clamp(1, 100); diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index f73a702385..99dedac77d 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -74,6 +74,13 @@ impl AuthorizedWorkspace { /// as [`photocraft_format::atomic_write`], through the directory capability). On failure /// the previous file is untouched and the temporary file is removed. /// + /// Replacing a file carries its extended attributes — macOS Finder tags, Linux `user.*` — + /// onto the file that takes its place (#7095), through the two open descriptors rather than + /// their paths, so nothing here reaches outside the write root to finish a write. The rest + /// of what [`photocraft_format::atomic_write`] preserves does not follow: its permission + /// step is tracked in #4963, and the Windows `ReplaceFileW` swap is path-based, which this + /// path may not use. + /// /// The parent directory must already exist. `cap-std` performs path /// resolution and file creation relative to the held directory handle, so /// a non-existent final target is supported without ambient path access. @@ -85,10 +92,20 @@ impl AuthorizedWorkspace { let tmp = parent.join(photocraft_format::atomic::temp_name(&leaf)); let mut options = OpenOptions::new(); options.write(true).create_new(true); - let written = root.dir.open_with(&tmp, &options).and_then(|mut file| { + let written = root.dir.open_with(&tmp, &options).and_then(|file| { + let mut file = file.into_std(); file.write_all(bytes)?; + #[cfg(unix)] + { + use std::os::fd::AsFd; + // Best effort, and only when there is a file being replaced: a save still + // succeeds for a document whose Finder tag could not come along. + if let Ok(old) = root.dir.open(&relative) { + let _ = photocraft_format::atomic::meta::copy_xattrs(old.as_fd(), file.as_fd()); + } + } // Falls back to a plain fsync on shares that refuse a full flush (#1336). - photocraft_format::atomic::sync_file(&file.into_std()) + photocraft_format::atomic::sync_file(&file) }); let renamed = written.and_then(|()| photocraft_format::atomic::retry_rename(RenameRetry::platform(), || root.dir.rename(&tmp, &root.dir, &relative))); if let Err(e) = renamed { @@ -572,6 +589,32 @@ mod tests { assert!(temp_files(&inside).is_empty()); } + /// #7095: replacing a file through the automation path keeps the old file's extended + /// attributes, the same as a save through `atomic_write` does. + #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] + #[test] + fn write_keeps_the_replaced_files_extended_attributes() { + #[cfg(target_os = "macos")] + const TAG: &str = "com.apple.metadata:_kMDItemUserTags"; + #[cfg(not(target_os = "macos"))] + const TAG: &str = "user.photocraft.test"; + + let (inside, _, workspace) = roots("xattr"); + let path = inside.join("doc.psd"); + workspace.write("doc.psd", b"original").unwrap(); + if rustix::fs::setxattr(&path, TAG, b"tagged", rustix::fs::XattrFlags::empty()).is_err() { + return; // a file system without extended attributes: nothing to assert + } + + workspace.write("doc.psd", b"replacement, longer").unwrap(); + + assert_eq!(std::fs::read(&path).unwrap(), b"replacement, longer"); + let mut buf = [0u8; 64]; + let len = rustix::fs::getxattr(&path, TAG, buf.as_mut_slice()).expect("the attribute was dropped"); + assert_eq!(&buf[..len], b"tagged"); + assert!(temp_files(&inside).is_empty()); + } + #[cfg(unix)] #[test] fn write_into_read_only_folder_keeps_the_original() { diff --git a/crates/automation/tests/krita.rs b/crates/automation/tests/krita.rs index 85bde4f5fc..44de53ff2a 100644 --- a/crates/automation/tests/krita.rs +++ b/crates/automation/tests/krita.rs @@ -4,14 +4,15 @@ use photocraft_automation::Headless; use serde_json::json; -/// A tiled pixel file with one raw 64x64 tile of `bgra` at (0, 0). +/// A tiled pixel file with one raw 64x64 tile of `bgra` at (0, 0). Krita writes a raw tile +/// (flag 0) as plain interleaved pixels; only LZF tiles are split into byte planes. fn tiles(bgra: [u8; 4]) -> Vec { let n = 64 * 64; let mut out = b"VERSION 2\nTILEWIDTH 64\nTILEHEIGHT 64\nPIXELSIZE 4\nDATA 1\n".to_vec(); out.extend(format!("0,0,LZF,{}\n", 1 + n * 4).into_bytes()); out.push(0); - for b in bgra { - out.extend(std::iter::repeat_n(b, n)); + for _ in 0..n { + out.extend(bgra); } out } diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs index 7386f3d58c..5a9fa7c56e 100644 --- a/crates/automation/tests/mcp.rs +++ b/crates/automation/tests/mcp.rs @@ -415,6 +415,45 @@ async fn headless_doc_save_writes_targa_bits() { cleanup(&dir); } +/// `ddsCompression` and `ddsMipmaps` reach the app's `app.save` through the bridge; an unknown +/// compression is refused before anything is sent. +#[tokio::test(flavor = "multi_thread")] +async fn bridge_doc_save_forwards_dds_options() { + let (addr, app) = fake_app().await; + let client = connect(PhotocraftMcp::bridge(&addr, CONTROL_TOKEN).unwrap()).await; + let saved = json_of(&call(&client, "doc_save", json!({"path": "out.dds", "ddsCompression": "DXT5", "ddsMipmaps": true})).await); + assert_eq!(saved, json!({"saved": {"path": "out.dds", "ddsCompression": "bc3", "ddsMipmaps": true}})); + let r = call(&client, "doc_save", json!({"path": "out.dds", "ddsCompression": "bc7"})).await; + assert_eq!(r.is_error, Some(true), "{}", text(&r)); + assert!(text(&r).contains("ddsCompression"), "{}", text(&r)); + client.cancel().await.unwrap(); + app.abort(); +} + +/// Headless `doc_save`/`doc_export` write the DDS compression (the FourCC, bytes 84–87) and mip +/// count (bytes 28–31) asked for; unset, an uncompressed texture without mipmaps. +#[tokio::test(flavor = "multi_thread")] +async fn headless_doc_save_writes_dds_options() { + let dir = tmp("dds-options"); + let client = connect(headless_in(&dir)).await; + call(&client, "doc_new", json!({"width": 16, "height": 8, "background": "white"})).await; + for (tool, params, fourcc, mips) in [ + ("doc_export", json!({"path": "plain.dds"}), [0; 4], 1), + ("doc_export", json!({"path": "bc1.dds", "ddsCompression": "bc1"}), *b"DXT1", 1), + ("doc_save", json!({"path": "bc3.dds", "ddsCompression": "bc3", "ddsMipmaps": true}), *b"DXT5", 5), + ] { + let r = call(&client, tool, params.clone()).await; + assert_ne!(r.is_error, Some(true), "{params}: {}", text(&r)); + let bytes = std::fs::read(dir.join(params["path"].as_str().unwrap())).unwrap(); + assert_eq!((&bytes[84..88], u32::from_le_bytes(bytes[28..32].try_into().unwrap())), (&fourcc[..], mips), "{params}"); + } + let r = call(&client, "doc_export", json!({"path": "bad.dds", "ddsCompression": "bc7"})).await; + assert_eq!(r.is_error, Some(true), "{}", text(&r)); + assert!(!dir.join("bad.dds").exists()); + client.cancel().await.unwrap(); + cleanup(&dir); +} + #[tokio::test(flavor = "multi_thread")] async fn bridge_response_budget_drops_connection_without_retrying_the_operation() { use photocraft_automation::{BridgeClient, budgets::MAX_RESPONSE_BYTES}; diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs index d6911ccd24..f93b00372b 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -1,4 +1,4 @@ -//! Photocraft colour management: a pure-Rust ICC v2/v4 colour management module. +//! PhotoCraft colour management: a pure-Rust ICC v2/v4 colour management module. //! //! * [`Profile`] parses ICC profiles (matrix/TRC RGB, gray TRC, `mft1`/`mft2`/`mAB `/`mBA ` //! LUT profiles incl. CMYK↔Lab, `curv`/`para` curves) and writes ICC v4 profiles. diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index 0a68ef8bce..47ff164fda 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -245,7 +245,7 @@ fn smooth(x: f32) -> f32 { x * x * (3.0 - 2.0 * x) } -/// Generated looks shipped with Photocraft (procedural, CC0): `(id, label)`. +/// Generated looks shipped with PhotoCraft (procedural, CC0): `(id, label)`. pub const BUILTIN: [(&str, &str); 8] = [ ("warm", "Warm Filter"), ("cool", "Cool Filter"), diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 96a23dbfce..390e509dce 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -2,7 +2,7 @@ //! //! Adobe's CMYK profiles (U.S. Web Coated SWOP, Coated FOGRA39 …) are proprietary, and the //! freely downloadable characterisation-based profiles come with redistribution conditions, so -//! Photocraft ships a CMYK profile it generates itself from a documented printer model: +//! PhotoCraft ships a CMYK profile it generates itself from a documented printer model: //! //! * **Forward model** (CMYK → XYZ): Yule–Nielsen modified Neugebauer (n = 2) over the 16 //! ink overprints, with Demichel coverage weights and a parabolic tone value increase (dot diff --git a/crates/codecs/README.md b/crates/codecs/README.md index d4f7094894..539365c95b 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -38,9 +38,9 @@ let out = encode(&img, Format::Tiff, &EncodeOptions::default())?; | WebP | yes | yes | U8 | RGB, RGBA | yes | yes | yes | yes | no | no | yes (VP8, when `webp_lossless` is off) | `image-webp` / built-in VP8 | | GIF | yes | yes | U8 | RGBA | 1-bit | no | no | no | no | no | yes (256-colour palette) | `image` | | BMP | yes | yes | U8 | RGB, RGBA | yes | no | no | no | no | no | no | `image` | -| TGA | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | no | `image` | +| TGA | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | no | `image` (read) / built in (RLE write, one scanline per packet) | | ICO | yes | yes | U8 | RGBA (at most 256×256) | yes | no | no | no | no | no | no | `image` | -| DDS | yes | **no** | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | n/a | built in | +| DDS | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | yes (BC1–BC3, when `EncodeOptions::dds` asks for one) | built in | | Netpbm (PBM/PGM/PPM/PAM/PFM) | yes | yes | U8, U16, F32 (float: PFM gray/RGB only) | all six (PAM `CMYK`/`CMYK_ALPHA`) | yes (PAM) | no | no | no | no | no | no | built in | | QOI | yes | yes | U8 | RGB, RGBA | yes | no | no | no | no | no | no | `image` | | OpenEXR | yes | yes | F16, F32 | Y, YA, RGB, RGBA | yes | no | no | no | no | no | no | `exr` | @@ -73,7 +73,15 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them (8, 16, 24 or 32 bits, RGB or luminance, with or without alpha) or BC1/BC2/BC3 (DXT1/DXT3/DXT5), with the legacy header or the DX10 one. Everything opens as U8; the other mip levels are ignored. Cubemaps, texture arrays, volume textures, premultiplied DXT2/DXT4 and other formats - (BC4–BC7, float) are refused with `CodecError::Unsupported`. Writing is not provided. + (BC4–BC7, float) are refused with `CodecError::Unsupported`. Writing (`EncodeOptions::dds`) makes + a 2D texture with the legacy header: uncompressed by default (BGRA, BGRX, or luminance with or + without alpha, so it reads back exactly), or BC1/BC2/BC3. The block encoder is our own, from + Microsoft's public block-compression documentation: RGB565 endpoints fitted along each block's + principal axis and refined by least squares, indices picked against the palette the reader + decodes; BC1 turns texels under half opacity into its transparent black, and BC3 picks + whichever alpha mode fits. `mipmaps` adds the full chain down to 1×1, each level a box filter + of the one above (the last column and row of an odd-sized level average three pixels, so none + is dropped). Cubemaps, arrays, BC4–BC7 and sRGB (DX10-only) formats aren't written. * **FITS.** The image in the primary HDU, or the first `IMAGE` extension, is read; `NAXIS3 = 3` opens as RGB and any other plane count opens the first plane with `DecodeWarning::MorePages`. diff --git a/crates/codecs/src/codecs/dds.rs b/crates/codecs/src/codecs/dds.rs index efe93c7f2e..d35c7d1092 100644 --- a/crates/codecs/src/codecs/dds.rs +++ b/crates/codecs/src/codecs/dds.rs @@ -1,13 +1,24 @@ -//! DirectDraw Surface (DDS) reader: the top mip level of a 2D texture, either uncompressed -//! (8 to 32 bits per pixel described by channel masks, RGB or luminance) or block-compressed -//! BC1/BC2/BC3 (DXT1/DXT3/DXT5), with or without the DX10 header. Read-only. Cubemaps, -//! texture arrays and volume textures are refused rather than flattened to one face or slice. +//! DirectDraw Surface (DDS) textures, after Microsoft's public DDS documentation ("DDS", +//! "DDS_HEADER", "DDS_PIXELFORMAT", "DDS_HEADER_DXT10"). +//! +//! Reading: the top mip level of a 2D texture, either uncompressed (8 to 32 bits per pixel +//! described by channel masks, RGB or luminance) or block-compressed BC1/BC2/BC3 +//! (DXT1/DXT3/DXT5), with or without the DX10 header. Cubemaps, texture arrays and volume +//! textures are refused rather than flattened to one face or slice. +//! +//! Writing: a 2D texture, uncompressed (BGRA or BGRX, luminance with or without alpha) or +//! BC1/BC2/BC3, optionally with its full mip chain. The legacy header describes all of these, +//! so no DX10 header is written; formats only DXGI can name (BC4–BC7, sRGB) aren't written. +use std::borrow::Cow; + +use super::dds_bc::{self, Block, Mask}; use crate::SampleType; use crate::error::CodecError; +use crate::fidelity::Plan; use crate::format::Format; use crate::image::{ChannelLayout, Image}; -use crate::options::Limits; +use crate::options::{DdsCompression, EncodeOptions, Limits}; /// `DDS ` plus the 124-byte DDS_HEADER. const HEADER: usize = 128; @@ -224,27 +235,12 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { Image::from_u8(width, height, layout, pixels) } -fn rgb565(c: u16) -> [u8; 3] { - let scale = |v: u16, max: u16| ((u32::from(v) * 255 + u32::from(max) / 2) / u32::from(max)) as u8; - [scale(c >> 11, 31), scale((c >> 5) & 63, 63), scale(c & 31, 31)] -} - /// A BC1 colour block. BC2 and BC3 colour blocks always have four colours; only BC1's /// `c0 <= c1` order selects three colours and transparent black. fn bc1(block: &[u8], one_bit_alpha: bool) -> [[u8; 4]; 16] { let byte = |i: usize| block.get(i).copied().unwrap_or(0); let (c0, c1) = (u16::from_le_bytes([byte(0), byte(1)]), u16::from_le_bytes([byte(2), byte(3)])); - let (a, b) = (rgb565(c0), rgb565(c1)); - let mix = |wa: u32, wb: u32| { - let d = wa + wb; - let at = |i: usize| ((wa * u32::from(a[i]) + wb * u32::from(b[i]) + d / 2) / d) as u8; - [at(0), at(1), at(2), 255] - }; - let palette = if c0 > c1 || !one_bit_alpha { - [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(2, 1), mix(1, 2)] - } else { - [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(1, 1), [0; 4]] - }; + let palette = dds_bc::colour_palette(c0, c1, c0 > c1 || !one_bit_alpha); let indices = u32::from_le_bytes([byte(4), byte(5), byte(6), byte(7)]); std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) } @@ -259,21 +255,9 @@ fn bc2_alpha(block: &[u8]) -> [u8; 16] { /// 0 and 255 when `a0 <= a1`. fn bc3_alpha(block: &[u8]) -> [u8; 16] { let byte = |i: usize| block.get(i).copied().unwrap_or(0); - let (a0, a1) = (u32::from(byte(0)), u32::from(byte(1))); - let mut palette = [a0, a1, 0, 0, 0, 0, 0, 255]; - if a0 > a1 { - for (k, v) in palette.iter_mut().enumerate().skip(2) { - let k = k as u32; - *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7; - } - } else { - for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) { - let k = k as u32; - *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5; - } - } + let palette = dds_bc::alpha_palette(byte(0), byte(1)); let bits = u64::from_le_bytes([byte(2), byte(3), byte(4), byte(5), byte(6), byte(7), 0, 0]); - std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize] as u8) + std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize]) } fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] { @@ -282,3 +266,260 @@ fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] { } texels } + +const DDSD_CAPS: u32 = 0x1; +const DDSD_HEIGHT: u32 = 0x2; +const DDSD_WIDTH: u32 = 0x4; +const DDSD_PITCH: u32 = 0x8; +const DDSD_PIXELFORMAT: u32 = 0x1000; +const DDSD_MIPMAPCOUNT: u32 = 0x2_0000; +const DDSD_LINEARSIZE: u32 = 0x8_0000; +const DDSCAPS_COMPLEX: u32 = 0x8; +const DDSCAPS_TEXTURE: u32 = 0x1000; +const DDSCAPS_MIPMAP: u32 = 0x40_0000; + +fn encode_err(reason: impl std::fmt::Display) -> CodecError { + CodecError::encode(Format::Dds, reason) +} + +/// How a written texture stores its pixels. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Store { + /// 8-bit luminance. + Luminance, + /// 8-bit luminance, then 8-bit alpha. + LuminanceAlpha, + /// Blue, green, red and an unused byte (written as 255, so a reader that takes it for + /// alpha still sees an opaque texture). + Bgrx, + Bgra, + Bc1, + Bc2, + Bc3, +} + +impl Store { + /// The storage for an image of `layout`, as [`crate::fidelity::plan`] chose it. + fn new(compression: DdsCompression, layout: ChannelLayout) -> Result { + Ok(match (compression, layout) { + (DdsCompression::None, ChannelLayout::Gray) => Store::Luminance, + (DdsCompression::None, ChannelLayout::GrayA) => Store::LuminanceAlpha, + (DdsCompression::None, ChannelLayout::Rgb) => Store::Bgrx, + (DdsCompression::None, ChannelLayout::Rgba) => Store::Bgra, + (DdsCompression::Bc1, ChannelLayout::Rgba) => Store::Bc1, + (DdsCompression::Bc2, ChannelLayout::Rgba) => Store::Bc2, + (DdsCompression::Bc3, ChannelLayout::Rgba) => Store::Bc3, + (_, layout) => return Err(encode_err(format!("{layout:?} pixels can't be written as `{}`", compression.name()))), + }) + } + + /// Bytes per pixel, or per 4×4 block for a block compression. + fn unit(self) -> usize { + match self { + Store::Luminance => 1, + Store::LuminanceAlpha => 2, + Store::Bgrx | Store::Bgra => 4, + Store::Bc1 => 8, + Store::Bc2 | Store::Bc3 => 16, + } + } + + fn is_block(self) -> bool { + matches!(self, Store::Bc1 | Store::Bc2 | Store::Bc3) + } + + /// Bytes of one row of pixels (or of 4×4 blocks) of a level `width` wide. + fn row_bytes(self, width: usize) -> Option { + if self.is_block() { width.div_ceil(4).checked_mul(self.unit()) } else { width.checked_mul(self.unit()) } + } + + fn level_bytes(self, width: usize, height: usize) -> Option { + let rows = if self.is_block() { height.div_ceil(4) } else { height }; + self.row_bytes(width)?.checked_mul(rows) + } + + /// DDS_PIXELFORMAT: flags, FourCC, bits per pixel and the red, green, blue and alpha masks. + fn pixel_format(self) -> (u32, [u8; 4], u32, [u32; 4]) { + match self { + Store::Luminance => (DDPF_LUMINANCE, [0; 4], 8, [0xff, 0, 0, 0]), + Store::LuminanceAlpha => (DDPF_LUMINANCE | DDPF_ALPHAPIXELS, [0; 4], 16, [0xff, 0, 0, 0xff00]), + Store::Bgrx => (DDPF_RGB, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0]), + Store::Bgra => (DDPF_RGB | DDPF_ALPHAPIXELS, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]), + Store::Bc1 => (DDPF_FOURCC, *b"DXT1", 0, [0; 4]), + Store::Bc2 => (DDPF_FOURCC, *b"DXT3", 0, [0; 4]), + Store::Bc3 => (DDPF_FOURCC, *b"DXT5", 0, [0; 4]), + } + } +} + +/// Levels in a full mip chain: the larger side halves down to 1. +fn mip_levels(width: u32, height: u32) -> u32 { + 32 - width.max(height).max(1).leading_zeros() +} + +fn half((w, h): (usize, usize)) -> (usize, usize) { + ((w / 2).max(1), (h / 2).max(1)) +} + +pub(crate) fn encode(image: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { + let img = image.converted(plan.layout, SampleType::U8); + let pixels = img.as_u8().ok_or_else(|| encode_err("the image was not converted to 8 bits per channel"))?; + let store = Store::new(opts.dds.compression, img.layout())?; + let (width, height) = img.dimensions(); + let levels = if opts.dds.mipmaps { mip_levels(width, height) } else { 1 }; + let top = (width as usize, height as usize); + // Every level's size, checked before anything is allocated. + let mut sizes = Vec::new(); + let mut size = top; + for _ in 0..levels { + sizes.push(store.level_bytes(size.0, size.1).ok_or_else(|| encode_err("texture size overflow"))?); + size = half(size); + } + let total = sizes.iter().try_fold(HEADER, |total, &s| total.checked_add(s)).ok_or_else(|| encode_err("texture size overflow"))?; + let header = header(width, height, store, levels, sizes.first().copied().unwrap_or(0))?; + let mut out = crate::options::alloc_zeroed::(total)?; + out.get_mut(..HEADER).ok_or_else(|| encode_err("output buffer too small"))?.copy_from_slice(&header); + + let channels = img.layout().channels(); + let mut level = Cow::Borrowed(pixels); + let (mut size, mut at) = (top, HEADER); + for (i, &bytes) in sizes.iter().enumerate() { + let dst = out.get_mut(at..at + bytes).ok_or_else(|| encode_err("output buffer too small"))?; + write_level(store, &level, size, dst)?; + at += bytes; + if i + 1 < sizes.len() { + let next = half(size); + level = Cow::Owned(downsample(&level, size, next, channels)?); + size = next; + } + } + Ok(out) +} + +/// The `DDS ` signature and DDS_HEADER. `top` is the top level's size in bytes. +fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Result<[u8; HEADER], CodecError> { + let mut b = [0u8; HEADER]; + let mut put = |at: usize, v: u32| { + if let Some(d) = b.get_mut(at..at + 4) { + d.copy_from_slice(&v.to_le_bytes()); + } + }; + // Uncompressed: the pitch of one row. Compressed: the whole top level (its "linear size"). + let (size_flag, pitch_or_size) = if store.is_block() { (DDSD_LINEARSIZE, Some(top)) } else { (DDSD_PITCH, store.row_bytes(width as usize)) }; + let pitch_or_size = + pitch_or_size.and_then(|v| u32::try_from(v).ok()).ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?; + let mipmapped = levels > 1; + put(4, 124); + put(8, DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | size_flag | if mipmapped { DDSD_MIPMAPCOUNT } else { 0 }); + put(12, height); + put(16, width); + put(20, pitch_or_size); + put(28, levels); + let (flags, fourcc, bits, masks) = store.pixel_format(); + put(76, 32); + put(80, flags); + put(84, u32::from_le_bytes(fourcc)); + put(88, bits); + for (i, mask) in masks.into_iter().enumerate() { + put(92 + 4 * i, mask); + } + put(108, DDSCAPS_TEXTURE | if mipmapped { DDSCAPS_COMPLEX | DDSCAPS_MIPMAP } else { 0 }); + b[..4].copy_from_slice(b"DDS "); + Ok(b) +} + +/// Runs `f` on each `len`-byte row of `out` with its index, in parallel on native targets. +fn rows(out: &mut [u8], len: usize, f: impl Fn(usize, &mut [u8]) + Send + Sync) { + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_mut(len.max(1)).enumerate().for_each(|(i, row)| f(i, row)); + } + #[cfg(target_arch = "wasm32")] + for (i, row) in out.chunks_mut(len.max(1)).enumerate() { + f(i, row); + } +} + +/// Writes one level of `width` × `height` pixels (in the image's layout) into `dst`. +fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst: &mut [u8]) -> Result<(), CodecError> { + let row_bytes = store.row_bytes(width).ok_or_else(|| encode_err("texture size overflow"))?; + match store { + Store::Luminance | Store::LuminanceAlpha => { + // The image's gray (and alpha) samples, in the same order. + let src = pixels.get(..dst.len()).ok_or_else(|| encode_err("the level is smaller than its size"))?; + dst.copy_from_slice(src); + } + Store::Bgrx | Store::Bgra => { + let channels = if store == Store::Bgra { 4 } else { 3 }; + rows(dst, row_bytes, |y, row| { + let src = pixels.get(y * width * channels..).unwrap_or_default(); + for (d, s) in row.as_chunks_mut::<4>().0.iter_mut().zip(src.chunks_exact(channels)) { + let byte = |i: usize| s.get(i).copied().unwrap_or(255); + *d = [byte(2), byte(1), byte(0), byte(3)]; + } + }); + } + Store::Bc1 | Store::Bc2 | Store::Bc3 => { + let (texels, _) = pixels.as_chunks::<4>(); + rows(dst, row_bytes, |by, row| { + for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { + let (block, inside) = gather(texels, (width, height), bx, by); + let encoded: &[u8] = match store { + Store::Bc1 => &dds_bc::encode_bc1(&block, inside), + Store::Bc2 => &dds_bc::encode_bc2(&block, inside), + _ => &dds_bc::encode_bc3(&block, inside), + }; + for (d, s) in d.iter_mut().zip(encoded) { + *d = *s; + } + } + }); + } + } + Ok(()) +} + +/// Block (`bx`, `by`)'s texels, and which of them lie inside the image. +fn gather(texels: &[[u8; 4]], (width, height): (usize, usize), bx: usize, by: usize) -> (Block, Mask) { + let mut block = [[0u8; 4]; 16]; + let mut inside: Mask = 0; + for (t, texel) in block.iter_mut().enumerate() { + let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4); + if x < width + && y < height + && let Some(p) = texels.get(y * width + x) + { + *texel = *p; + inside |= 1 << t; + } + } + (block, inside) +} + +/// The next mip level: each pixel the average of the 2×2 pixels it covers, or of 2×3, 3×2 or +/// 3×3 along the last column and row of an odd-sized level, so no pixel is dropped. +fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), channels: usize) -> Result, CodecError> { + let len = nw.checked_mul(nh).and_then(|n| n.checked_mul(channels)).ok_or_else(|| encode_err("mip level size overflow"))?; + let mut dst = crate::options::alloc_zeroed::(len)?; + let span = |i: usize, n: usize, size: usize| 2 * i..=if i + 1 == n { size.saturating_sub(1) } else { 2 * i + 1 }; + rows(&mut dst, nw * channels, |y, row| { + let ys = span(y, nh, h); + for (x, px) in row.chunks_exact_mut(channels.max(1)).enumerate() { + let xs = span(x, nw, w); + for (c, v) in px.iter_mut().enumerate() { + let (mut sum, mut n) = (0u32, 0u32); + for sy in ys.clone() { + for sx in xs.clone() { + if let Some(&s) = src.get((sy * w + sx) * channels + c) { + sum += u32::from(s); + n += 1; + } + } + } + *v = ((sum + n / 2) / n.max(1)) as u8; + } + } + }); + Ok(dst) +} diff --git a/crates/codecs/src/codecs/dds_bc.rs b/crates/codecs/src/codecs/dds_bc.rs new file mode 100644 index 0000000000..bbd55b4bf3 --- /dev/null +++ b/crates/codecs/src/codecs/dds_bc.rs @@ -0,0 +1,368 @@ +//! BC1, BC2 and BC3 (DXT1, DXT3, DXT5) blocks, after Microsoft's public block compression +//! documentation ("Block Compression (Direct3D 10)" and "Texture Block Compression in Direct3D +//! 11"): the palettes the DDS reader decodes with, and the block encoder the DDS writer uses. +//! +//! The encoder fits a block's colours with two RGB565 endpoints along their principal axis, +//! refines them by least squares, and scores every candidate against the exact palette the +//! reader rebuilds, so the indices it picks are the best ones for what a decoder shows. + +/// The 16 texels of a 4×4 block, row by row, as RGBA. +pub(crate) type Block = [[u8; 4]; 16]; + +/// Bit `t` set for each texel `t` of a block that counts: edge blocks of a texture whose size is +/// not a multiple of four have texels outside the image. +pub(crate) type Mask = u16; + +pub(crate) fn rgb565(c: u16) -> [u8; 3] { + let scale = |v: u16, max: u16| ((u32::from(v) * 255 + u32::from(max) / 2) / u32::from(max)) as u8; + [scale(c >> 11, 31), scale((c >> 5) & 63, 63), scale(c & 31, 31)] +} + +/// The colours a colour block's indices select. Four-colour mode (BC1 with `c0 > c1`, and every +/// BC2 and BC3 block) adds two colours at thirds; three-colour mode adds the midpoint and +/// transparent black. +pub(crate) fn colour_palette(c0: u16, c1: u16, four: bool) -> [[u8; 4]; 4] { + let (a, b) = (rgb565(c0), rgb565(c1)); + let mix = |wa: u32, wb: u32| { + let d = wa + wb; + let at = |i: usize| ((wa * u32::from(a[i]) + wb * u32::from(b[i]) + d / 2) / d) as u8; + [at(0), at(1), at(2), 255] + }; + if four { + [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(2, 1), mix(1, 2)] + } else { + [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(1, 1), [0; 4]] + } +} + +/// A BC3 alpha block's eight values: six interpolated at sevenths when `a0 > a1`, else four +/// interpolated at fifths followed by 0 and 255. +pub(crate) fn alpha_palette(a0: u8, a1: u8) -> [u8; 8] { + let (a0, a1) = (u32::from(a0), u32::from(a1)); + let mut palette = [a0, a1, 0, 0, 0, 0, 0, 255]; + if a0 > a1 { + for (k, v) in palette.iter_mut().enumerate().skip(2) { + let k = k as u32; + *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7; + } + } else { + for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) { + let k = k as u32; + *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5; + } + } + palette.map(|v| v as u8) +} + +/// A BC1 block. Texels under half opacity become BC1's transparent black, which needs the +/// three-colour mode; an opaque block takes whichever mode fits its colours better. +pub(crate) fn encode_bc1(block: &Block, inside: Mask) -> [u8; 8] { + let transparent = select(block, inside, |t| t[3] < 128); + colour_block(block, inside & !transparent, transparent, true) +} + +/// A BC2 block: four bits of alpha per texel, then a four-colour block. +pub(crate) fn encode_bc2(block: &Block, inside: Mask) -> [u8; 16] { + let bits = block.iter().enumerate().fold(0u64, |bits, (t, texel)| bits | ((u64::from(texel[3]) * 15 + 127) / 255) << (4 * t)); + join(bits.to_le_bytes(), colour_block(block, inside, 0, false)) +} + +/// A BC3 block: an interpolated alpha block, then a four-colour block. +pub(crate) fn encode_bc3(block: &Block, inside: Mask) -> [u8; 16] { + join(alpha_block(block, inside), colour_block(block, inside, 0, false)) +} + +fn join(a: [u8; 8], b: [u8; 8]) -> [u8; 16] { + std::array::from_fn(|i| if i < 8 { a.get(i) } else { b.get(i - 8) }.copied().unwrap_or(0)) +} + +/// The texels of `inside` for which `f` holds. +fn select(block: &Block, inside: Mask, f: impl Fn(&[u8; 4]) -> bool) -> Mask { + block.iter().enumerate().filter(|(t, texel)| inside >> t & 1 != 0 && f(texel)).fold(0, |m, (t, _)| m | 1 << t) +} + +fn rgb_of(texel: &[u8; 4]) -> [f32; 3] { + [f32::from(texel[0]), f32::from(texel[1]), f32::from(texel[2])] +} + +/// RGB565 of a colour, rounding each channel to the nearest level. +fn to565(c: [f32; 3]) -> u16 { + let q = |v: f32, max: f32| (v.clamp(0.0, 255.0) * max / 255.0).round() as u16; + q(c[0], 31.0) << 11 | q(c[1], 63.0) << 5 | q(c[2], 31.0) +} + +fn distance(a: &[u8; 4], b: &[u8; 4]) -> u32 { + (0..3).map(|i| u32::from(a[i].abs_diff(b[i])).pow(2)).sum() +} + +/// A colour block (endpoints, then 2-bit indices) for the `opaque` texels' colours, with the +/// `transparent` ones on BC1's transparent index. `bc1` allows the three-colour mode; BC2 and +/// BC3 always decode four colours. +fn colour_block(block: &Block, opaque: Mask, transparent: Mask, bc1: bool) -> [u8; 8] { + let colours: Vec<[f32; 3]> = block.iter().enumerate().filter(|(t, _)| opaque >> t & 1 != 0).map(|(_, texel)| rgb_of(texel)).collect(); + if colours.is_empty() { + // Nothing visible: every texel on the transparent index (or index 0 of black). + let indices = if transparent != 0 { u32::MAX } else { 0 }; + return pack(0, 0, indices); + } + let (lo, hi) = principal_endpoints(&colours); + let mut candidates = vec![(to565(lo), to565(hi))]; + let modes: &[bool] = if transparent != 0 { + &[false] + } else if bc1 { + &[true, false] + } else { + &[true] + }; + let mut best: Option<(u32, [u8; 8])> = None; + // Each refinement starts from the best block so far: its indices give the least-squares + // endpoints, which become one more candidate. + for round in 0..3 { + for &(e0, e1) in &candidates { + for &four in modes { + let (bytes, error) = fit(block, opaque, transparent, e0, e1, four); + if best.is_none_or(|(e, _)| error < e) { + best = Some((error, bytes)); + } + } + } + let Some((error, bytes)) = best else { break }; + if error == 0 || round == 2 { + break; + } + candidates = least_squares(block, opaque, &bytes).into_iter().collect(); + if candidates.is_empty() { + break; + } + } + best.map_or([0; 8], |(_, bytes)| bytes) +} + +/// Orders endpoints `e0`, `e1` for the mode (`c0 > c1` for four colours, `c0 <= c1` for three) +/// and picks each texel's nearest palette colour. Returns the block and its squared error. +fn fit(block: &Block, opaque: Mask, transparent: Mask, e0: u16, e1: u16, four: bool) -> ([u8; 8], u32) { + let (c0, c1) = if four == (e0 >= e1) { (e0, e1) } else { (e1, e0) }; + // Equal endpoints can't be in four-colour order; the palette is then one colour either way. + let palette = colour_palette(c0, c1, four && c0 > c1); + let choices = if four && c0 > c1 { 4 } else { 3 }; + let mut indices = 0u32; + let mut error = 0u32; + for (t, texel) in block.iter().enumerate() { + let index = if transparent >> t & 1 != 0 { + 3 + } else if opaque >> t & 1 != 0 { + let (i, d) = palette.iter().take(choices).enumerate().map(|(i, p)| (i, distance(texel, p))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); + error += d; + i as u32 + } else { + 0 + }; + indices |= index << (2 * t); + } + (pack(c0, c1, indices), error) +} + +fn pack(c0: u16, c1: u16, indices: u32) -> [u8; 8] { + let (c0, c1, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes()); + [c0[0], c0[1], c1[0], c1[1], i[0], i[1], i[2], i[3]] +} + +/// The ends of the colours' spread along their principal axis (the covariance's dominant +/// eigenvector, by power iteration), clamped to the RGB cube. +fn principal_endpoints(colours: &[[f32; 3]]) -> ([f32; 3], [f32; 3]) { + let n = colours.len().max(1) as f32; + let mean = [0, 1, 2].map(|i| colours.iter().map(|c| c[i]).sum::() / n); + let mut cov = [[0f32; 3]; 3]; + for c in colours { + let d = [c[0] - mean[0], c[1] - mean[1], c[2] - mean[2]]; + for (i, row) in cov.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v += d[i] * d[j]; + } + } + } + let times = |a: [f32; 3]| [0, 1, 2].map(|i| cov[i][0] * a[0] + cov[i][1] * a[1] + cov[i][2] * a[2]); + let iterate = |start: usize| { + let mut axis = [0f32; 3]; + axis[start] = 1.0; + for _ in 0..8 { + let next = times(axis); + let len = next.iter().map(|v| v * v).sum::().sqrt(); + if !len.is_normal() { + break; + } + axis = next.map(|v| v / len); + } + axis + }; + // From each channel's axis, keeping the one the colours spread along most: a channel that + // varies on its own is already an eigenvector, so a single start there would never leave it + // even when the others vary more together. + let spread = |a: [f32; 3]| times(a).iter().zip(a).map(|(x, y)| x * y).sum::(); + let axis = [0, 1, 2].map(iterate).into_iter().max_by(|&a, &b| spread(a).total_cmp(&spread(b))).unwrap_or([1.0, 0.0, 0.0]); + let along = |c: &[f32; 3]| (c[0] - mean[0]) * axis[0] + (c[1] - mean[1]) * axis[1] + (c[2] - mean[2]) * axis[2]; + let (lo, hi) = colours.iter().map(along).fold((f32::MAX, f32::MIN), |(lo, hi), t| (lo.min(t), hi.max(t))); + let at = |t: f32| [0, 1, 2].map(|i| (mean[i] + t * axis[i]).clamp(0.0, 255.0)); + if lo > hi { (mean, mean) } else { (at(lo), at(hi)) } +} + +/// The endpoints that minimise the squared error for the indices `bytes` already chose: each +/// texel's index fixes its weights between the endpoints, giving 2×2 normal equations per +/// channel. `None` when the indices don't constrain both endpoints. +fn least_squares(block: &Block, opaque: Mask, bytes: &[u8; 8]) -> Option<(u16, u16)> { + let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); + let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); + let four = c0 > c1; + // How much of c0 each index holds. + let weight = |i: u32| match (four, i) { + (_, 0) => Some(1.0f32), + (_, 1) => Some(0.0), + (true, 2) => Some(2.0 / 3.0), + (true, _) => Some(1.0 / 3.0), + (false, 2) => Some(0.5), + (false, _) => None, + }; + let (mut aa, mut ab, mut bb) = (0f32, 0f32, 0f32); + let (mut ax, mut bx) = ([0f32; 3], [0f32; 3]); + for (t, texel) in block.iter().enumerate() { + if opaque >> t & 1 == 0 { + continue; + } + let Some(a) = weight(indices >> (2 * t) & 3) else { continue }; + let b = 1.0 - a; + let c = rgb_of(texel); + aa += a * a; + ab += a * b; + bb += b * b; + for ((x0, x1), v) in ax.iter_mut().zip(bx.iter_mut()).zip(c) { + *x0 += a * v; + *x1 += b * v; + } + } + let det = aa * bb - ab * ab; + if det.abs() < 1e-3 { + return None; + } + let e0 = [0, 1, 2].map(|i| (ax[i] * bb - bx[i] * ab) / det); + let e1 = [0, 1, 2].map(|i| (bx[i] * aa - ax[i] * ab) / det); + Some((to565(e0), to565(e1))) +} + +/// A BC3 alpha block: whichever of the two modes (eight values between the extremes, or six +/// between the extremes other than 0 and 255, plus exact 0 and 255) fits better. +fn alpha_block(block: &Block, inside: Mask) -> [u8; 8] { + let alphas = || block.iter().enumerate().filter(move |(t, _)| inside >> t & 1 != 0).map(|(_, texel)| texel[3]); + let range = |values: &mut dyn Iterator| values.fold(None, |r: Option<(u8, u8)>, a| Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a))))); + let (lo, hi) = range(&mut alphas()).unwrap_or((0, 0)); + // Eight values need a0 > a1; equal ends fall to the six-value mode, which starts with a0 too. + let eight = alpha_fit(block, inside, hi, lo); + let (mid_lo, mid_hi) = range(&mut alphas().filter(|a| !matches!(a, 0 | 255))).unwrap_or((0, 0)); + let six = alpha_fit(block, inside, mid_lo, mid_hi); + if six.1 < eight.1 { six.0 } else { eight.0 } +} + +fn alpha_fit(block: &Block, inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) { + let palette = alpha_palette(a0, a1); + let mut bits = 0u64; + let mut error = 0u32; + for (t, texel) in block.iter().enumerate() { + if inside >> t & 1 == 0 { + continue; + } + let (i, d) = palette.iter().enumerate().map(|(i, &p)| (i, u32::from(p.abs_diff(texel[3])).pow(2))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); + error += d; + bits |= (i as u64) << (3 * t); + } + let b = bits.to_le_bytes(); + ([a0, a1, b[0], b[1], b[2], b[3], b[4], b[5]], error) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn decode_colour(bytes: &[u8; 8], bc1: bool) -> Block { + let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); + let palette = colour_palette(c0, c1, c0 > c1 || !bc1); + let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); + std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) + } + + #[test] + fn solid_blocks_land_on_the_nearest_565_colour() { + for colour in [[0, 0, 0, 255], [255, 255, 255, 255], [12, 200, 77, 255]] { + let block = [colour; 16]; + let out = decode_colour(&encode_bc1(&block, u16::MAX), true); + for texel in out { + assert!(texel.iter().zip(colour).all(|(a, b)| a.abs_diff(b) <= 4), "{texel:?} for {colour:?}"); + } + } + } + + #[test] + fn two_colour_blocks_are_exact_when_the_colours_are_565() { + let (a, b) = ([255, 0, 0, 255], [0, 0, 255, 255]); + let block: Block = std::array::from_fn(|t| if t % 3 == 0 { a } else { b }); + for bc1 in [true, false] { + let bytes = if bc1 { encode_bc1(&block, u16::MAX) } else { colour_block(&block, u16::MAX, 0, false) }; + assert_eq!(decode_colour(&bytes, bc1), block); + } + } + + #[test] + fn bc1_punches_through_texels_under_half_alpha() { + let block: Block = std::array::from_fn(|t| if t < 8 { [200, 100, 50, 255] } else { [9, 9, 9, 127] }); + let bytes = encode_bc1(&block, u16::MAX); + let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); + assert!(c0 <= c1, "three-colour mode"); + let out = decode_colour(&bytes, true); + assert!(out[..8].iter().all(|t| t[3] == 255) && out[8..].iter().all(|t| *t == [0; 4]), "{out:?}"); + } + + #[test] + fn four_colour_blocks_keep_c0_above_c1() { + // A ramp needs all four colours; BC2 and BC3 blocks must not rely on the order, but + // older decoders read c0 <= c1 as three colours, so the encoder never writes that. + let block: Block = std::array::from_fn(|t| [(t * 16) as u8, 0, 0, 255]); + let bytes = colour_block(&block, u16::MAX, 0, false); + assert!(u16::from_le_bytes([bytes[0], bytes[1]]) > u16::from_le_bytes([bytes[2], bytes[3]])); + } + + #[test] + fn alpha_blocks_pick_the_mode_that_keeps_0_and_255() { + // 0, 255 and a cluster in between: the six-value mode stores 0 and 255 exactly. + let block: Block = std::array::from_fn(|t| [0, 0, 0, [0, 255, 100, 110][t % 4]]); + let bytes = alpha_block(&block, u16::MAX); + assert!(bytes[0] <= bytes[1], "six-value mode"); + let palette = alpha_palette(bytes[0], bytes[1]); + let bits = u64::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], 0, 0]); + for (t, texel) in block.iter().enumerate() { + let got = palette[(bits >> (3 * t)) as usize & 7]; + assert!(got.abs_diff(texel[3]) <= 2, "texel {t}: {got} for {}", texel[3]); + } + } + + #[test] + fn the_principal_axis_is_found_when_one_channel_varies_on_its_own() { + // Red alternates on its own (variance 64); green and blue alternate together (variance 49 + // each, 98 along their shared axis), uncorrelated with red. Starting on red alone would + // keep red's axis and flatten green and blue; the block must do better than its bounding box. + let block: Block = std::array::from_fn(|t| { + let gb = if (t / 2) % 2 == 0 { 121 } else { 135 }; + [if t % 2 == 0 { 120 } else { 136 }, gb, gb, 255] + }); + let error = |bytes: &[u8; 8]| decode_colour(bytes, false).iter().zip(&block).map(|(a, b)| distance(a, b)).sum::(); + let (_, bounding_box) = fit(&block, u16::MAX, 0, to565([120.0, 121.0, 121.0]), to565([136.0, 135.0, 135.0]), true); + let ours = error(&colour_block(&block, u16::MAX, 0, false)); + assert!(ours < bounding_box, "{ours} vs the bounding box's {bounding_box}"); + } + + #[test] + fn texels_outside_the_image_are_ignored() { + // Only the top-left texel is inside: its colour alone decides the endpoints. + let mut block: Block = [[0, 255, 0, 255]; 16]; + block[0] = [255, 0, 255, 255]; + let out = decode_colour(&encode_bc1(&block, 1), true); + assert_eq!(out[0], [255, 0, 255, 255]); + } +} diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs index a55810b4b8..1b268ac559 100644 --- a/crates/codecs/src/codecs/exr.rs +++ b/crates/codecs/src/codecs/exr.rs @@ -15,7 +15,7 @@ use half::f16; use crate::Format; use crate::error::CodecError; use crate::fidelity::Plan; -use crate::image::{ChannelLayout, DecodeWarning, ExrChannelInfo, ExrPartInfo, Image, SampleType, base_channel_name}; +use crate::image::{ChannelLayout, DecodeWarning, ExrChannelInfo, ExrPartInfo, Image, SampleType, base_channel_name, exr_color_channels}; use crate::options::{EncodeOptions, ExrCompression, Limits}; const F: Format = Format::OpenExr; @@ -123,20 +123,9 @@ pub(super) fn read_layer(bytes: &[u8], index: usize) -> Result>) -> Result { let (w, h) = (layer.size.0, layer.size.1); let channels = &layer.channel_data.list; - let find = |n: &str| channels.iter().find(|c| base_channel_name(&c.name.to_string()) == n); - let (color, layout): (Vec<_>, ChannelLayout) = if let (Some(r), Some(g), Some(b)) = (find("R"), find("G"), find("B")) { - match find("A") { - Some(a) => (vec![r, g, b, a], ChannelLayout::Rgba), - None => (vec![r, g, b], ChannelLayout::Rgb), - } - } else if let Some(y) = find("Y").or_else(|| (channels.len() == 1).then(|| &channels[0])) { - match find("A") { - Some(a) => (vec![y, a], ChannelLayout::GrayA), - None => (vec![y], ChannelLayout::Gray), - } - } else { - return Err(CodecError::unsupported(F, "no R/G/B or Y channels")); - }; + let names: Vec<_> = channels.iter().map(|c| c.name.to_string()).collect(); + let (layout, selected) = exr_color_channels(names.iter().map(String::as_str)).ok_or_else(|| CodecError::unsupported(F, "no R/G/B or Y channels"))?; + let color: Vec<_> = selected.iter().map(|i| channels.get(*i).ok_or_else(|| err("selected channel is missing"))).collect::>()?; let all_f16 = color.iter().all(|c| matches!(c.sample_data, FlatSamples::F16(_))); let sample = if all_f16 { SampleType::F16 } else { SampleType::F32 }; let npx = w * h; diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs index 9c37628872..a300de4bd1 100644 --- a/crates/codecs/src/codecs/jpeg.rs +++ b/crates/codecs/src/codecs/jpeg.rs @@ -33,6 +33,8 @@ pub(crate) struct JpegMeta { pub exif: Option>, pub xmp: Option, pub dpi: Option<(f32, f32)>, + /// The APP13 Photoshop image resource blocks (`8BIM` ...), segments joined, without the header. + pub photoshop: Option>, pub adobe_transform: Option, /// (width, height, components) from the first SOFn. pub frame: Option<(u32, u32, u8)>, @@ -108,6 +110,7 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { .or_else(|| m.xmp.as_deref().and_then(xmp_resolution)) .or_else(|| m.exif.as_deref().and_then(exif_resolution)) .or(jfif_dpi); + m.photoshop = Some(photoshop).filter(|p| !p.is_empty()); if !icc_parts.is_empty() { icc_parts.sort_by_key(|p| p.0); let total = icc_parts[0].1 as usize; @@ -226,7 +229,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result } let mut img = Image::from_raw(w, h, layout, SampleType::U8, px)?; img.icc = meta.icc; - img.meta = Metadata { exif: meta.exif, xmp: meta.xmp, dpi: meta.dpi, ..Default::default() }; + img.meta = Metadata { exif: meta.exif, xmp: meta.xmp, dpi: meta.dpi, photoshop_resources: meta.photoshop, ..Default::default() }; if end == DataEnd::Truncated { img.warnings.push(DecodeWarning::Truncated { format: F }); } diff --git a/crates/codecs/src/codecs/mod.rs b/crates/codecs/src/codecs/mod.rs index afb7f96791..d9905ab978 100644 --- a/crates/codecs/src/codecs/mod.rs +++ b/crates/codecs/src/codecs/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod dds; +pub(crate) mod dds_bc; pub(crate) mod deep_exr; pub(crate) mod dpx; pub(crate) mod exr; @@ -10,6 +11,7 @@ pub(crate) mod jpeg; pub(crate) mod pcx; pub(crate) mod png; pub(crate) mod pnm; +pub(crate) mod tga; pub(crate) mod tiff; pub(crate) mod tiff_exif; pub(crate) mod tiff_ifd; diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index 7c1a633d17..f894b3a30d 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -7,7 +7,7 @@ use crate::Format; use crate::error::CodecError; use crate::fidelity::Plan; use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType}; -use crate::options::{EncodeOptions, Limits, PngCompression, alloc_zeroed}; +use crate::options::{EncodeOptions, Limits, PngCompression, PngStereo, alloc_zeroed}; const F: Format = Format::Png; pub(crate) const XMP_KEYWORD: &str = "XML:com.adobe.xmp"; @@ -127,6 +127,38 @@ pub fn palette(bytes: &[u8]) -> Result, CodecError> { Ok(Some(PngPalette { colors, transparent })) } +/// The stereo pairing a PNG declares in its `sTER` chunk (PNG Extensions 1.4.0, §3.6), read +/// from the headers without decoding pixels. `None` when the file has no CRC-valid `sTER` with a +/// defined mode byte. The first valid chunk wins, as a later one would contradict it. +pub fn stereo(bytes: &[u8]) -> Option { + let mut rest = bytes.get(8..)?; + while let Some((length, tail)) = rest.split_first_chunk::<4>() { + let Some((kind, tail)) = tail.split_first_chunk::<4>() else { break }; + let length = u32::from_be_bytes(*length); + if length > i32::MAX as u32 { + break; + } + let Ok(length) = usize::try_from(length) else { break }; + let Some(data) = tail.get(..length) else { break }; + let Some((checksum, next)) = tail.get(length..).and_then(|t| t.split_first_chunk::<4>()) else { break }; + rest = next; + if kind == b"IEND" { + break; + } + if kind != b"sTER" || data.len() != 1 { + continue; + } + let mut crc = flate2::Crc::new(); + crc.update(kind); + crc.update(data); + if crc.sum() != u32::from_be_bytes(*checksum) { + continue; + } + return PngStereo::from_mode(data[0]); + } + None +} + fn map_png_err(e: png::DecodingError) -> CodecError { match e { png::DecodingError::LimitsExceeded => CodecError::LimitExceeded("PNG decoder memory limit".into()), @@ -346,6 +378,10 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, bpp: usize, scratch: &mut [u8], o } }; let cost = |v: &[u8]| v.iter().map(|&b| u64::from((b as i8).unsigned_abs())).sum::(); - let mut best = (cost(row), 0u8); + let mut best = cost(row); + let start = out.len(); + out.push(0); + out.extend_from_slice(row); for kind in 1u8..=4 { + if best == 0 { + break; + } + let mut c = 0u64; for i in 0..n { let x = row[i]; scratch[i] = match kind { @@ -515,27 +558,17 @@ fn filter_row(row: &[u8], prev: Option<&[u8]>, bpp: usize, scratch: &mut [u8], o 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8), _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))), }; + c += u64::from((scratch[i] as i8).unsigned_abs()); + if c >= best { + break; + } } - let c = cost(&scratch[..n]); - if c < best.0 { - best = (c, kind); + if c < best { + best = c; + out[start] = kind; + out[start + 1..].copy_from_slice(&scratch[..n]); } } - out.push(best.1); - if best.1 == 0 { - out.extend_from_slice(row); - return; - } - for i in 0..n { - let x = row[i]; - scratch[i] = match best.1 { - 1 => x.wrapping_sub(left(i)), - 2 => x.wrapping_sub(up(i)), - 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8), - _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))), - }; - } - out.extend_from_slice(&scratch[..n]); } const ADLER_MOD: u32 = 65_521; @@ -574,6 +607,7 @@ pub fn encode_indexed( palette: &[[u8; 3]], transparent: Option, dpi: Option<(f32, f32)>, + stereo: Option, ) -> Result, CodecError> { if width == 0 || height == 0 || indices.len() != width as usize * height as usize { return Err(CodecError::InvalidImage("index data does not match the size".into())); @@ -603,12 +637,95 @@ pub fn encode_indexed( { let encoder = png::Encoder::with_info(&mut out, info).map_err(|e| CodecError::encode(F, e))?; let mut writer = encoder.write_header().map_err(|e| CodecError::encode(F, e))?; + if let Some(stereo) = stereo { + writer.write_chunk(png::chunk::ChunkType(*b"sTER"), &[stereo.mode()]).map_err(|e| CodecError::encode(F, e))?; + } writer.write_image_data(indices).map_err(|e| CodecError::encode(F, e))?; writer.finish().map_err(|e| CodecError::encode(F, e))?; } Ok(out) } +#[cfg(test)] +mod stereo_tests { + use super::*; + + /// One CRC-valid chunk as it appears in a file. + fn chunk(kind: &[u8; 4], data: &[u8]) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + out.extend_from_slice(kind); + out.extend_from_slice(data); + let mut crc = flate2::Crc::new(); + crc.update(kind); + crc.update(data); + out.extend_from_slice(&crc.sum().to_be_bytes()); + out + } + + fn png_with(stereo: &[u8]) -> Vec { + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + out.extend_from_slice(&chunk(b"IHDR", &[0, 0, 0, 2, 0, 0, 0, 1, 8, 2, 0, 0, 0])); + if !stereo.is_empty() { + out.extend_from_slice(&chunk(b"sTER", stereo)); + } + out.extend_from_slice(&chunk(b"IDAT", &[0x78, 0x01, 0x01, 0x00, 0xff, 0xff, 0, 3, 1, 0, 0])); + out.extend_from_slice(&chunk(b"IEND", &[])); + out + } + + #[test] + fn reads_both_defined_views() { + assert_eq!(stereo(&png_with(&[0])), Some(PngStereo::Horizontal)); + assert_eq!(stereo(&png_with(&[1])), Some(PngStereo::Vertical)); + assert_eq!(stereo(&png_with(&[])), None); + // Reserved and unknown mode bytes are not a pairing we can keep. + assert_eq!(stereo(&png_with(&[2])), None); + assert_eq!(stereo(&png_with(&[255])), None); + // A two-byte payload is not sTER data. + assert_eq!(stereo(&png_with(&[0, 0])), None); + assert_eq!(stereo(b"not a png"), None); + } + + #[test] + fn a_broken_crc_is_not_a_stereo_mark() { + let mut bytes = png_with(&[0]); + let kind = bytes.windows(4).position(|w| w == b"sTER").unwrap(); + // The CRC trails the type and the one-byte payload of the chunk. + bytes[kind + 8] ^= 0xff; + assert_eq!(stereo(&bytes), None); + } + + #[test] + fn encode_writes_the_chunk_before_idat_and_it_reads_back() { + let img = Image::from_raw(2, 1, ChannelLayout::Rgb, SampleType::U8, vec![9; 6]).unwrap(); + for view in [PngStereo::Horizontal, PngStereo::Vertical] { + let opts = EncodeOptions { png_stereo: Some(view), ..Default::default() }; + let bytes = crate::encode(&img, Format::Png, &opts).unwrap(); + assert_eq!(stereo(&bytes), Some(view)); + let back = decode(&bytes, &Limits::default()).unwrap(); + assert_eq!(back.data(), img.data()); + let ter = bytes.windows(4).position(|w| w == b"sTER").unwrap(); + let idat = bytes.windows(4).position(|w| w == b"IDAT").unwrap(); + assert!(ter < idat, "sTER before IDAT"); + } + let plain = crate::encode(&img, Format::Png, &EncodeOptions::default()).unwrap(); + assert_eq!(stereo(&plain), None); + } + + #[test] + fn interlaced_and_indexed_encoders_keep_the_mark() { + let img = Image::from_raw(2, 2, ChannelLayout::Rgb, SampleType::U8, vec![9; 12]).unwrap(); + let opts = EncodeOptions { png_stereo: Some(PngStereo::Vertical), png_interlaced: true, ..Default::default() }; + let bytes = crate::encode(&img, Format::Png, &opts).unwrap(); + assert_eq!(stereo(&bytes), Some(PngStereo::Vertical)); + let pal = [[255, 0, 0], [0, 0, 255]]; + let bytes = encode_indexed(2, 1, &[0, 1], &pal, None, None, Some(PngStereo::Horizontal)).unwrap(); + assert_eq!(stereo(&bytes), Some(PngStereo::Horizontal)); + assert_eq!(palette(&bytes).unwrap().map(|p| p.colors), Some(pal.to_vec())); + } +} + #[cfg(test)] mod indexed_tests { use super::*; @@ -617,14 +734,14 @@ mod indexed_tests { fn png8_roundtrips_through_the_decoder() { let pal = [[255, 0, 0], [0, 0, 255], [0, 0, 0]]; let idx = [0u8, 1, 2, 1, 0, 2]; - let bytes = encode_indexed(3, 2, &idx, &pal, Some(2), None).unwrap(); + let bytes = encode_indexed(3, 2, &idx, &pal, Some(2), None, None).unwrap(); let img = decode(&bytes, &Limits::default()).unwrap(); assert_eq!(img.dimensions(), (3, 2)); let px = img.convert(ChannelLayout::Rgba, SampleType::U8); assert_eq!(&px.data()[..8], &[255, 0, 0, 255, 0, 0, 255, 255]); assert_eq!(px.data()[11], 0, "transparent entry"); - assert!(encode_indexed(3, 2, &[9; 6], &pal, None, None).is_err()); - assert!(encode_indexed(3, 3, &idx, &pal, None, None).is_err()); + assert!(encode_indexed(3, 2, &[9; 6], &pal, None, None, None).is_err()); + assert!(encode_indexed(3, 3, &idx, &pal, None, None, None).is_err()); } fn png(color: png::ColorType, trns: Option<&[u8]>) -> Vec { @@ -643,7 +760,7 @@ mod indexed_tests { #[test] fn palette_reads_the_table_and_its_one_transparent_entry() { - let bytes = encode_indexed(2, 1, &[0, 1], &[[1, 2, 3], [4, 5, 6]], Some(1), None).unwrap(); + let bytes = encode_indexed(2, 1, &[0, 1], &[[1, 2, 3], [4, 5, 6]], Some(1), None, None).unwrap(); let colors = vec![[1, 2, 3], [4, 5, 6]]; assert_eq!(palette(&bytes).unwrap(), Some(PngPalette { colors: colors.clone(), transparent: Some(1) })); assert_eq!(palette(&png(png::ColorType::Indexed, None)).unwrap(), Some(PngPalette { colors, transparent: None })); @@ -659,6 +776,109 @@ mod indexed_tests { mod parallel_tests { use super::*; + #[test] + #[ignore = "manual 24 MP release benchmark"] + fn benchmark_filter_selection() { + use std::{hint::black_box, time::Instant}; + for pattern in ["zero", "identical", "varied"] { + let row: Vec = (0..6000 * 4).map(|i| if pattern == "zero" { 0 } else { (i * 17 + i / 13) as u8 }).collect(); + let prev: Vec<_> = row.iter().map(|v| if pattern == "identical" { *v } else { v.wrapping_add(3) }).collect(); + let mut scratch = vec![0; row.len()]; + let mut out = Vec::with_capacity(row.len() + 1); + for trial in 0..6 { + type Filter = fn(&[u8], Option<&[u8]>, usize, &mut [u8], &mut Vec); + let mut paths: [(&str, Filter); 2] = [("main", previous_filter_row), ("split", filter_row)]; + if trial % 2 == 1 { + paths.reverse(); + } + for (name, path) in paths { + let t = Instant::now(); + for _ in 0..4000 { + out.clear(); + black_box(path)(black_box(&row), Some(black_box(&prev)), 4, &mut scratch, &mut out); + black_box(&out); + } + println!("filter,{pattern},{trial},{name},{:.6}", t.elapsed().as_secs_f64() * 1000.0); + } + } + } + } + + // The main-branch implementation before this refactor. + fn previous_filter_row(row: &[u8], prev: Option<&[u8]>, bpp: usize, scratch: &mut [u8], out: &mut Vec) { + let n = row.len(); + let up = |i: usize| prev.map_or(0, |p| p[i]); + let left = |i: usize| if i >= bpp { row[i - bpp] } else { 0 }; + let ul = |i: usize| if i >= bpp { prev.map_or(0, |p| p[i - bpp]) } else { 0 }; + let paeth = |a: u8, b: u8, c: u8| { + let p = i16::from(a) + i16::from(b) - i16::from(c); + let (pa, pb, pc) = ((p - i16::from(a)).abs(), (p - i16::from(b)).abs(), (p - i16::from(c)).abs()); + if pa <= pb && pa <= pc { + a + } else if pb <= pc { + b + } else { + c + } + }; + let cost = |v: &[u8]| v.iter().map(|&b| u64::from((b as i8).unsigned_abs())).sum::(); + let mut best = (cost(row), 0u8); + for kind in 1u8..=4 { + for i in 0..n { + let x = row[i]; + scratch[i] = match kind { + 1 => x.wrapping_sub(left(i)), + 2 => x.wrapping_sub(up(i)), + 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8), + _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))), + }; + } + let c = cost(&scratch[..n]); + if c < best.0 { + best = (c, kind); + } + } + out.push(best.1); + if best.1 == 0 { + out.extend_from_slice(row); + return; + } + for i in 0..n { + let x = row[i]; + scratch[i] = match best.1 { + 1 => x.wrapping_sub(left(i)), + 2 => x.wrapping_sub(up(i)), + 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8), + _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))), + }; + } + out.extend_from_slice(&scratch[..n]); + } + + #[test] + fn adaptive_filter_preserves_minimum_cost_and_ties() { + for bpp in [1, 2, 3, 4, 6, 8] { + for seed in 0..32usize { + let row: Vec = (0..137).map(|i| (i * seed + i / 5) as u8).collect(); + let shifted: Vec<_> = row.iter().map(|v| v.wrapping_add(seed as u8)).collect(); + for prev in [None, Some(row.as_slice()), Some(shifted.as_slice())] { + let mut expected = vec![99]; + let mut actual = expected.clone(); + let mut scratch = vec![0; row.len()]; + previous_filter_row(&row, prev, bpp, &mut scratch, &mut expected); + filter_row(&row, prev, bpp, &mut scratch, &mut actual); + assert_eq!(actual, expected, "bpp={bpp}, seed={seed}"); + } + } + } + let mut out = Vec::new(); + filter_row(&[0; 16], None, 4, &mut [0; 16], &mut out); + assert_eq!(out, vec![0; 17]); + out.clear(); + filter_row(&[1; 16], Some(&[0; 16]), 1, &mut [0; 16], &mut out); + assert_eq!(out, [vec![1, 1], vec![0; 15]].concat()); + } + #[test] fn adler_combine_matches_one_pass() { let a: Vec = (0..100_000u32).map(|i| (i * 7 + i / 13) as u8).collect(); diff --git a/crates/codecs/src/codecs/pnm.rs b/crates/codecs/src/codecs/pnm.rs index ca36db8109..c16cccfd02 100644 --- a/crates/codecs/src/codecs/pnm.rs +++ b/crates/codecs/src/codecs/pnm.rs @@ -66,6 +66,21 @@ impl<'a> Reader<'a> { } } + /// PAM ends its header with an LF-terminated line, unlike P4–P6's single separator. + fn pam_endhdr(&mut self) -> Result<(), CodecError> { + while let Some(&c) = self.b.get(self.pos) { + self.pos += 1; + if c == b'\n' { + // Stop at the first LF: whitespace and '#' after it are raster bytes. + return Ok(()); + } + if !c.is_ascii_whitespace() { + return Err(err("unexpected data after PAM ENDHDR")); + } + } + Err(err("unterminated PAM ENDHDR line")) + } + fn rest(&self) -> &'a [u8] { &self.b[self.pos.min(self.b.len())..] } @@ -269,7 +284,7 @@ fn decode_pam(r: &mut Reader<'_>, limits: &Limits) -> Result _ => return Err(err("unknown PAM header field")), } } - r.single_ws()?; + r.pam_endhdr()?; let (w, h, depth, maxval) = match (w, h, depth, maxval) { (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d), _ => return Err(err("incomplete PAM header")), diff --git a/crates/codecs/src/codecs/tga.rs b/crates/codecs/src/codecs/tga.rs new file mode 100644 index 0000000000..7b52533d7b --- /dev/null +++ b/crates/codecs/src/codecs/tga.rs @@ -0,0 +1,90 @@ +//! Targa writer. The `image` crate still reads Targa ([`super::via_image`]); writing is ours +//! because its run-length packets ran on from the end of one row into the next. TGA 2.0 says a +//! packet must not cross a scanline, and readers that decode a row at a time (Pillow, texture +//! converters, game engines) misread such files (#6382). +//! +//! Like Photoshop's Targa: RLE (types 10 and 11), rows stored bottom-up (the bottom-left origin +//! every reader assumes, also those that ignore the origin bits), alpha bits in the descriptor, +//! and the TGA 2.0 footer. + +use crate::Format; +use crate::error::CodecError; +use crate::image::{ChannelLayout, Image, SampleType}; + +/// Most pixels one packet holds (a 7-bit count, plus one). +const MAX_PACKET: usize = 128; + +/// The TGA 2.0 footer: no extension or developer area, then the signature. +const FOOTER: &[u8; 26] = b"\0\0\0\0\0\0\0\0TRUEVISION-XFILE.\0"; + +/// Encodes an 8-bit Gray, Gray+alpha, RGB or RGBA image as a run-length encoded Targa. +pub(crate) fn encode(img: &Image) -> Result, CodecError> { + let (w, h) = img.dimensions(); + if img.sample_type() != SampleType::U8 { + return Err(CodecError::encode(Format::Tga, format!("{:?} samples (Targa stores 8 bits)", img.sample_type()))); + } + let (bpp, image_type, alpha_bits) = match img.layout() { + ChannelLayout::Gray => (1, 11, 0), + ChannelLayout::GrayA => (2, 11, 8), + ChannelLayout::Rgb => (3, 10, 0), + ChannelLayout::Rgba => (4, 10, 8), + l => return Err(CodecError::encode(Format::Tga, format!("no Targa layout for {l:?}"))), + }; + let (Ok(w16), Ok(h16)) = (u16::try_from(w), u16::try_from(h)) else { + return Err(CodecError::encode(Format::Tga, format!("dimensions exceed 65535x65535: {w}x{h}"))); + }; + let row = w as usize * bpp; + let data = img.data(); + if data.len() != row * h as usize { + return Err(CodecError::InvalidImage("buffer size mismatch".into())); + } + let mut out = Vec::with_capacity(18 + data.len() + data.len() / MAX_PACKET + FOOTER.len()); + out.extend_from_slice(&[0, 0, image_type, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + out.extend_from_slice(&w16.to_le_bytes()); + out.extend_from_slice(&h16.to_le_bytes()); + // Bits per pixel; the descriptor holds the alpha bits, origin bits 0 (bottom-left). + out.extend_from_slice(&[(bpp * 8) as u8, alpha_bits]); + let mut px = vec![0u8; row]; + for y in (0..h as usize).rev() { + px.copy_from_slice(&data[y * row..(y + 1) * row]); + // Targa stores colour as BGR. + if bpp >= 3 { + for p in px.chunks_exact_mut(bpp) { + p.swap(0, 2); + } + } + rle_row(&px, bpp, &mut out); + } + out.extend_from_slice(FOOTER); + Ok(out) +} + +/// One scanline as run-length packets that end with it: a run of two or more equal pixels is a +/// run packet, anything else goes out in raw packets. +fn rle_row(row: &[u8], bpp: usize, out: &mut Vec) { + let px: Vec<&[u8]> = row.chunks_exact(bpp).collect(); + let n = px.len(); + let mut i = 0; + while i < n { + let mut run = 1; + while i + run < n && run < MAX_PACKET && px[i + run] == px[i] { + run += 1; + } + if run >= 2 { + out.push(0x80 | (run - 1) as u8); + out.extend_from_slice(px[i]); + i += run; + continue; + } + // Raw until two equal pixels start a run, the packet is full or the row ends. The first + // pixel always goes in: it differs from the one after it, or it is the row's last. + let start = i; + while i < n && i - start < MAX_PACKET && !(i > start && i + 1 < n && px[i] == px[i + 1]) { + i += 1; + } + out.push((i - start - 1) as u8); + for p in &px[start..i] { + out.extend_from_slice(p); + } + } +} diff --git a/crates/codecs/src/codecs/tiff_exif.rs b/crates/codecs/src/codecs/tiff_exif.rs index d07f555f30..00d47d0702 100644 --- a/crates/codecs/src/codecs/tiff_exif.rs +++ b/crates/codecs/src/codecs/tiff_exif.rs @@ -6,7 +6,9 @@ //! the same reader ([`super::tiff_ifd::File`]): reading a TIFF builds a block from the file's own //! directories, writing one copies the block's directories into the file. Values are copied as //! bytes (re-ordered when the byte orders differ), so tags PhotoCraft doesn't know survive. -//! Classic TIFF only on the reading side: an EXIF block has 4-byte offsets. +//! Classic TIFF only on the reading side: an EXIF block has 4-byte offsets. What is copied is +//! bounded by the stream's own size and a fixed cap, because entries of a hostile file can +//! overlap (see [`read`]). use tiff::encoder::{DirectoryEncoder, TiffEncoder, TiffKind}; use tiff::tags::{Tag, Type}; @@ -27,6 +29,11 @@ const TAG_INTEROP_IFD: u16 = 40965; const IFD0_TAGS: [u16; 7] = [270, 271, 272, 305, 306, 315, 33432]; /// At most this many entries are copied from one directory. const MAX_FIELDS: usize = 1024; +/// At most this many value bytes are copied from one stream, over all its directories. Real EXIF +/// is far smaller (the largest Nikon maker note seen is under 1 MB); the cap leaves room for +/// that and for a few such notes. A stream never yields more than its own length either (see +/// [`read`]). +const MAX_COPIED_BYTES: usize = 4 * 1024 * 1024; /// One entry with its value bytes in the byte order of the stream it came from. #[derive(Clone, Debug, PartialEq)] @@ -53,13 +60,22 @@ impl ExifDirs { } } -fn fields(f: &File<'_>, ifd: &Ifd, keep: impl Fn(u16) -> bool) -> Vec { - ifd.entries - .iter() - .filter(|e| keep(e.tag) && !matches!(e.tag, TAG_EXIF_IFD | TAG_GPS_IFD | TAG_INTEROP_IFD)) - .filter_map(|e| Some(Field { tag: e.tag, ty: e.ty, count: u32::try_from(e.count).ok()?, value: f.data(e)?.to_vec() })) - .take(MAX_FIELDS) - .collect() +/// The entries of `ifd` that `keep` accepts, with their values copied. An entry's value only has +/// to lie inside the file, so entries may overlap: `budget` is the number of value bytes that may +/// still be copied (shared by all the directories of one stream), and an entry whose value does +/// not fit in what is left is skipped, so later, smaller entries can still be kept. +fn fields(f: &File<'_>, ifd: &Ifd, budget: &mut usize, keep: impl Fn(u16) -> bool) -> Vec { + let mut out = Vec::new(); + for e in ifd.entries.iter().filter(|e| keep(e.tag) && !matches!(e.tag, TAG_EXIF_IFD | TAG_GPS_IFD | TAG_INTEROP_IFD)) { + if out.len() >= MAX_FIELDS { + break; + } + let (Ok(count), Some(value)) = (u32::try_from(e.count), f.data(e)) else { continue }; + let Some(left) = budget.checked_sub(value.len()) else { continue }; + *budget = left; + out.push(Field { tag: e.tag, ty: e.ty, count, value: value.to_vec() }); + } + out } fn sub(f: &File<'_>, ifd: &Ifd, tag: u16) -> Option { @@ -69,14 +85,24 @@ fn sub(f: &File<'_>, ifd: &Ifd, tag: u16) -> Option { /// The EXIF parts of the classic TIFF stream `b` (a TIFF file, or an EXIF block without its /// `Exif\0\0` prefix): IFD0's descriptive tags and the Exif and GPS directories. +/// +/// The values copied add up to at most [`MAX_COPIED_BYTES`] and to at most `b.len()`: the values +/// of a well-formed stream are distinct bytes of it, while a hostile one can have many entries +/// point at the same bytes and so ask for far more than its size. Entries that do not fit in what +/// is left are left out (the small descriptive directories come first, so a huge maker note +/// cannot crowd out the GPS position). pub(crate) fn read(b: &[u8]) -> Option { let f = File::parse(b)?; if f.big { return None; } let ifd0 = f.ifd(f.first_ifd)?; - let dir = |tag: u16| sub(&f, &ifd0, tag).map(|d| fields(&f, &d, |_| true)).unwrap_or_default(); - Some(ExifDirs { le: f.le, ifd0: fields(&f, &ifd0, |t| IFD0_TAGS.contains(&t)), exif: dir(TAG_EXIF_IFD), gps: dir(TAG_GPS_IFD) }) + let mut budget = MAX_COPIED_BYTES.min(b.len()); + let ifd0_fields = fields(&f, &ifd0, &mut budget, |t| IFD0_TAGS.contains(&t)); + let mut dir = |tag: u16| sub(&f, &ifd0, tag).map(|d| fields(&f, &d, &mut budget, |_| true)).unwrap_or_default(); + let gps = dir(TAG_GPS_IFD); + let exif = dir(TAG_EXIF_IFD); + Some(ExifDirs { le: f.le, ifd0: ifd0_fields, exif, gps }) } /// Bytes per element whose order a byte-order change reverses: a RATIONAL is two LONGs. diff --git a/crates/codecs/src/codecs/via_image.rs b/crates/codecs/src/codecs/via_image.rs index 7e7eb76b2f..fd45f6a173 100644 --- a/crates/codecs/src/codecs/via_image.rs +++ b/crates/codecs/src/codecs/via_image.rs @@ -1,5 +1,6 @@ //! Formats delegated to the `image` crate (pure-Rust features only): -//! GIF, BMP, TGA, ICO, QOI, Radiance HDR, and AVIF encode (feature `avif`). +//! GIF, BMP, TGA, ICO, QOI, Radiance HDR, and AVIF encode (feature `avif`). Targa is written by +//! [`super::tga`] and only read here. use std::io::Cursor; @@ -163,6 +164,10 @@ pub(crate) fn encode(f: Format, src: &Image, plan: Plan, opts: &EncodeOptions) - return Err(CodecError::encode(f, format!("dimensions exceed {mw}x{mh}"))); } let img = src.converted(plan.layout, plan.sample); + // Targa is written by our encoder: the image crate's RLE packets cross scanlines (#6382). + if f == Format::Tga { + return super::tga::encode(&img); + } let dynimg = to_dynamic(&img)?; let mut cursor = Cursor::new(Vec::new()); match f { diff --git a/crates/codecs/src/fidelity.rs b/crates/codecs/src/fidelity.rs index 594735edb4..a6937b571c 100644 --- a/crates/codecs/src/fidelity.rs +++ b/crates/codecs/src/fidelity.rs @@ -6,7 +6,7 @@ use std::fmt; use crate::format::{Format, caps}; use crate::image::{ChannelLayout, Image, SampleType}; -use crate::options::EncodeOptions; +use crate::options::{DdsCompression, EncodeOptions}; /// Something that will be lost or altered when writing an image to a format. #[derive(Debug, Clone, PartialEq)] @@ -165,6 +165,8 @@ pub(crate) fn plan(image: &Image, format: Format, opts: &EncodeOptions) -> Plan }, // CIELab has no float form: float Lab is written with 16 bits. Format::Tiff if layout.is_lab() && sample.is_float() => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: SampleType::U16 }, + // A block-compressed DDS stores RGBA whatever the source; uncompressed keeps gray and RGB. + Format::Dds if opts.dds.compression.is_block() => Plan { layout: ChannelLayout::Rgba, sample: SampleType::U8 }, _ => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: pick_sample(sample, c.depths) }, } } @@ -211,7 +213,8 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOption if sl.has_alpha() && !p.layout.has_alpha() && image.has_translucency() { w.push(W::AlphaDiscarded); } - if format == Format::Gif && p.layout.has_alpha() && image.has_translucency() { + let binary_alpha = format == Format::Gif || (format == Format::Dds && opts.dds.compression == DdsCompression::Bc1); + if binary_alpha && p.layout.has_alpha() && image.has_translucency() { w.push(W::AlphaBinarized); } if sl.is_cmyk() && !p.layout.is_cmyk() { @@ -227,7 +230,7 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOption // Compression if format == Format::Gif { w.push(W::PaletteQuantized); - } else if c.lossy || (format == Format::WebP && !opts.webp_lossless) { + } else if c.lossy || (format == Format::WebP && !opts.webp_lossless) || (format == Format::Dds && opts.dds.compression.is_block()) { w.push(W::LossyCompression); } diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rs index fa2e1e6cb3..24611bd90d 100644 --- a/crates/codecs/src/format.rs +++ b/crates/codecs/src/format.rs @@ -19,7 +19,8 @@ pub enum Format { Pcx, /// X PixMap icons (XPM2 plain text and XPM3 C-string arrays). Xpm, - /// DirectDraw Surface: the top mip level of a 2D texture, uncompressed or BC1–BC3. + /// DirectDraw Surface: a 2D texture, uncompressed or BC1–BC3. Reading takes the top mip + /// level; writing can add the full mip chain ([`crate::DdsOptions`]). Dds, Qoi, OpenExr, @@ -71,10 +72,6 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[ Format::Pcx, "PCX is supported for opening legacy paint and clipart assets. New files should use PNG; writing obsolete indexed and planar variants is intentionally not provided.", ), - ( - Format::Dds, - "DDS is supported for opening game and 3D textures. Writing one well means choosing a block compression and generating mip levels, which belongs in a texture export, not Save As.", - ), ( Format::Avif, "AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \ @@ -255,7 +252,8 @@ pub fn caps(format: Format) -> FormatCaps { Format::Pnm => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, ..base }, Format::Pcx => FormatCaps { read: true, write: false, layouts: &[L::Rgb], alpha: false, ..base }, Format::Xpm => FormatCaps { read: true, write: false, layouts: &[L::Rgba], ..base }, - Format::Dds => FormatCaps { read: true, write: false, layouts: RGB_GRAY, ..base }, + // Uncompressed by default; a block compression is lossy (see `fidelity_warnings_with`). + Format::Dds => FormatCaps { layouts: RGB_GRAY, ..base }, Format::Qoi => base, Format::OpenExr => FormatCaps { depths: &[S::F16, S::F32], layouts: RGB_GRAY, ..base }, Format::Hdr => FormatCaps { depths: &[S::F32], layouts: &[L::Rgb], alpha: false, lossy: true, ..base }, diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rs index 98168d59d3..5a03e7d283 100644 --- a/crates/codecs/src/image.rs +++ b/crates/codecs/src/image.rs @@ -321,20 +321,75 @@ pub struct ExrPartInfo { impl ExrPartInfo { /// How much this part looks like a colour image the plain [`Image`] decode can show: - /// 4 RGBA, 3 RGB, 2 YA, 1 any-single-channel, 0 anything else (e.g. `Z` beside `A`). + /// 4 RGBA, 3 RGB, 2 YA, 1 Y or any-single-channel, 0 anything else (e.g. `Z` beside `A`). + /// The colour and alpha channels must share a complete layer prefix. The highest-ranked + /// group wins; equal groups prefer unprefixed channels, then the first prefix alphabetically. /// The auto-pick takes the highest rank; ties go to the earlier part. pub fn color_rank(&self) -> u8 { - let has = |n: &str| self.channels.iter().any(|c| base_channel_name(&c.name) == n); - if has("R") && has("G") && has("B") { - return if has("A") { 4 } else { 3 }; - } - if has("Y") { - return if has("A") { 2 } else { 1 }; - } - u8::from(self.channels.len() == 1) + exr_color_channels(self.channels.iter().map(|c| c.name.as_str())).map_or(0, |(layout, _)| layout.channels() as u8) } } +/// One selection policy for header ranking/probing and flat decoding: never synthesize +/// RGB(A) or YA from separate layers. OpenEXR layers use the full prefix before the last +/// dot, including nested layers; a leading or trailing dot alone does not name a layer. +pub(crate) fn exr_color_channels<'a>(names: impl IntoIterator) -> Option<(ChannelLayout, Vec)> { + #[derive(Default)] + struct Group { + r: Option, + g: Option, + b: Option, + a: Option, + y: Option, + } + + // Sorted prefixes make rank ties deterministic independently of channel order, with + // the empty (unprefixed) group first. Unsupported channels cannot complete a group. + let mut groups = std::collections::BTreeMap::<&str, Group>::new(); + let mut count = 0usize; + for (index, name) in names.into_iter().enumerate() { + count = count.saturating_add(1); + let (prefix, base) = name.rsplit_once('.').filter(|(prefix, base)| !prefix.is_empty() && !base.is_empty()).unwrap_or(("", name)); + if !matches!(base, "R" | "G" | "B" | "A" | "Y") { + continue; + } + let group = groups.entry(prefix).or_default(); + let component = match base { + "R" => &mut group.r, + "G" => &mut group.g, + "B" => &mut group.b, + "A" => &mut group.a, + "Y" => &mut group.y, + _ => continue, + }; + component.get_or_insert(index); + } + + let mut best = None; + let mut best_rank = 0; + for group in groups.values() { + let candidate = if let (Some(r), Some(g), Some(b)) = (group.r, group.g, group.b) { + match group.a { + Some(a) => (ChannelLayout::Rgba, vec![r, g, b, a]), + None => (ChannelLayout::Rgb, vec![r, g, b]), + } + } else if let Some(y) = group.y { + match group.a { + Some(a) => (ChannelLayout::GrayA, vec![y, a]), + None => (ChannelLayout::Gray, vec![y]), + } + } else { + continue; + }; + let rank = candidate.0.channels(); + if rank > best_rank { + best = Some(candidate); + best_rank = rank; + } + } + best.or_else(|| (count == 1).then(|| (ChannelLayout::Gray, vec![0]))) +} + /// Strip an optional `layer.` prefix from a channel name (`diffuse.R` → `R`). pub(crate) fn base_channel_name(name: &str) -> &str { name.rsplit('.').next().unwrap_or(name) diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 86611599d5..a5675c9823 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -28,7 +28,7 @@ pub mod web; pub use crate::codecs::exr_cryptomatte::{cryptomatte_id, cryptomatte_key, cryptomatte_preview_color}; pub use crate::codecs::gif_frames::{AnimationFrame, MAX_GIF_FRAMES}; -pub use crate::codecs::png::{PngPalette, encode_indexed as encode_png_indexed, palette as png_palette}; +pub use crate::codecs::png::{PngPalette, encode_indexed as encode_png_indexed, palette as png_palette, stereo as png_stereo}; pub use crate::codecs::tiff::{PhotoshopTags as TiffPhotoshopTags, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian}; pub use crate::codecs::tiff_ifd::{TiffInfo, TiffPage, TiffPageKind}; pub use crate::error::CodecError; @@ -38,7 +38,9 @@ pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect, pub use crate::image::{ ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, Image, Metadata, SampleType, }; -pub use crate::options::{DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, TiffCompression}; +pub use crate::options::{ + DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, PngStereo, TiffCompression, +}; pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp}; pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution}; pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding}; @@ -252,7 +254,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result pnm::encode(image, plan, opts), Format::Pcx => Err(CodecError::unsupported(format, "PCX is import-only; save as PNG instead")), Format::Xpm => Err(CodecError::unsupported(format, "XPM is import-only; save as PNG instead")), - Format::Dds => Err(CodecError::unsupported(format, "DDS is import-only; save as PNG instead")), + Format::Dds => dds::encode(image, plan, opts), Format::Fits => fits::encode(image, plan, opts), Format::Dpx => dpx::encode(image, plan, opts), Format::Cineon => Err(CodecError::unsupported(format, "Cineon is import-only; save as DPX, TIFF or EXR instead")), diff --git a/crates/codecs/src/options.rs b/crates/codecs/src/options.rs index eee5b38c0a..08de328574 100644 --- a/crates/codecs/src/options.rs +++ b/crates/codecs/src/options.rs @@ -100,6 +100,34 @@ pub enum PngCompression { Best, } +/// How a PNG's `sTER` chunk pairs its two views (PNG Extensions 1.4.0, §3.6). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PngStereo { + /// Left and right views side by side, left first. + Horizontal, + /// Left and right views stacked, left on top. + Vertical, +} + +impl PngStereo { + /// The view for an `sTER` mode byte; reserved and unknown values are `None`. + pub fn from_mode(mode: u8) -> Option { + match mode { + 0 => Some(Self::Horizontal), + 1 => Some(Self::Vertical), + _ => None, + } + } + + /// The `sTER` mode byte. + pub fn mode(self) -> u8 { + match self { + Self::Horizontal => 0, + Self::Vertical => 1, + } + } +} + /// TIFF strip compression. The default is none, as in Photoshop: uncompressed strips are the /// only kind every TIFF reader opens (Deflate and the predictor are not baseline TIFF, #4484). #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] @@ -154,6 +182,61 @@ impl DpxBits { } } +/// How a DDS texture stores its pixels. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum DdsCompression { + /// Uncompressed, 8 bits per channel: BGRA (BGRX without alpha), or luminance with or + /// without alpha for grayscale. Lossless. + #[default] + None, + /// BC1 (DXT1): 4 bits per pixel. Alpha is on or off: texels under half opacity become + /// transparent black. + Bc1, + /// BC2 (DXT3): 8 bits per pixel, with 4 bits of explicit alpha per texel. + Bc2, + /// BC3 (DXT5): 8 bits per pixel, with smooth interpolated alpha. + Bc3, +} + +impl DdsCompression { + pub const ALL: [DdsCompression; 4] = [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; + + /// The name scripts and the CLI use: `none`, `bc1`, `bc2` or `bc3`. + pub fn name(self) -> &'static str { + match self { + DdsCompression::None => "none", + DdsCompression::Bc1 => "bc1", + DdsCompression::Bc2 => "bc2", + DdsCompression::Bc3 => "bc3", + } + } + + /// [`Self::name`] back to a compression, also taking the DXT names (`dxt1`, `dxt3`, + /// `dxt5`), in any case. Anything else is `None`. + pub fn from_name(name: &str) -> Option { + match name.to_ascii_lowercase().as_str() { + "none" => Some(DdsCompression::None), + "bc1" | "dxt1" => Some(DdsCompression::Bc1), + "bc2" | "dxt3" => Some(DdsCompression::Bc2), + "bc3" | "dxt5" => Some(DdsCompression::Bc3), + _ => None, + } + } + + /// A block compression (lossy), not uncompressed pixels. + pub fn is_block(self) -> bool { + self != DdsCompression::None + } +} + +/// What a DDS file is written with. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DdsOptions { + pub compression: DdsCompression, + /// Write the full mip chain down to 1×1, each level a box filter of the one above. + pub mipmaps: bool, +} + /// Options for [`crate::encode`]. #[derive(Debug, Clone)] pub struct EncodeOptions { @@ -164,6 +247,9 @@ pub struct EncodeOptions { pub png_compression: PngCompression, /// Write Adam7-interlaced PNG. pub png_interlaced: bool, + /// Write an `sTER` chunk marking the image as a stereo pair (PNG Extensions 1.4.0, §3.6), + /// so a stereo PNG keeps its mark when saved again (#6063). + pub png_stereo: Option, /// WebP: lossless (VP8L, via `image-webp`) or lossy (our VP8 encoder, see /// `codecs::vp8`) with [`Self::webp_quality`]. pub webp_lossless: bool, @@ -176,6 +262,8 @@ pub struct EncodeOptions { pub exr_compression: ExrCompression, /// DPX bits per sample. `None` follows the image: 8 for 8-bit, 16 otherwise. pub dpx_bits: Option, + /// DDS compression and mip chain. + pub dds: DdsOptions, /// Embed the ICC profile when the format supports it. pub embed_icc: bool, /// Embed EXIF/XMP/DPI/text when the format supports it. @@ -189,12 +277,14 @@ impl Default for EncodeOptions { jpeg_chroma_subsampling: true, png_compression: PngCompression::Default, png_interlaced: false, + png_stereo: None, webp_lossless: true, webp_quality: 80, tiff_compression: TiffCompression::None, tiff_bigtiff: false, exr_compression: ExrCompression::Zip16, dpx_bits: None, + dds: DdsOptions::default(), embed_icc: true, embed_metadata: true, } diff --git a/crates/codecs/src/web.rs b/crates/codecs/src/web.rs index 584ceb9d6e..dfd0cd9b90 100644 --- a/crates/codecs/src/web.rs +++ b/crates/codecs/src/web.rs @@ -285,7 +285,8 @@ pub fn decode_wbmp(bytes: &[u8]) -> Result<(u32, u32, Vec), CodecError> { } /// JPEG from 8-bit RGB (`rgb.len() == 3·w·h`): quality 1..=100, optional progressive scans and -/// optimised Huffman tables (Save for Web's "Optimized"), optional ICC profile, density and XMP. +/// optimised Huffman tables (Save for Web's "Optimized"), optional ICC profile, density, EXIF and +/// XMP. EXIF that doesn't fit in one segment is left out (see [`jpeg_exif_fits`]). #[allow(clippy::too_many_arguments)] pub fn encode_jpeg_rgb8( width: u32, @@ -296,6 +297,7 @@ pub fn encode_jpeg_rgb8( optimized: bool, icc: Option<&[u8]>, dpi: Option, + exif: Option<&[u8]>, xmp: Option<&str>, ) -> Result, CodecError> { let e = |e: jpeg_encoder::EncodingError| CodecError::encode(Format::Jpeg, e); @@ -319,9 +321,14 @@ pub fn encode_jpeg_rgb8( let v = d.round().min(65535.0) as u16; enc.set_density(jpeg_encoder::Density::Inch { x: v, y: v }); } + let ppi = dpi.filter(|d| *d >= 1.0).map(|d| (d, d)); + // Upright, without the source's thumbnail, at the JFIF resolution, as Save As writes it. + if let Some(seg) = exif.and_then(|x| crate::codecs::jpeg::exif_segment(x, ppi)) { + enc.add_app_segment(1, &seg).map_err(e)?; + } if let Some(x) = xmp { // Its `tiff:` resolution, if any, says what the JFIF density says (#1691). - let x = crate::resolution::export_xmp(x, dpi.filter(|d| *d >= 1.0).map(|d| (d, d))); + let x = crate::resolution::export_xmp(x, ppi); let mut seg = b"http://ns.adobe.com/xap/1.0/\0".to_vec(); seg.extend_from_slice(x.as_bytes()); enc.add_app_segment(1, &seg).map_err(e)?; @@ -333,6 +340,11 @@ pub fn encode_jpeg_rgb8( Ok(out) } +/// Whether [`encode_jpeg_rgb8`] can write `exif` at `dpi` (it must fit in one APP1 segment). +pub fn jpeg_exif_fits(exif: &[u8], dpi: Option) -> bool { + crate::codecs::jpeg::exif_segment(exif, dpi.filter(|d| *d >= 1.0).map(|d| (d, d))).is_some() +} + #[cfg(test)] mod tests { use super::*; @@ -359,7 +371,7 @@ mod tests { let rgb: Vec = (0..16 * 16 * 3).map(|i| (i * 37 % 256) as u8).collect(); for (q, want) in [(1, (2, 2)), (50, (2, 2)), (51, (1, 1)), (60, (1, 1)), (89, (1, 1)), (100, (1, 1))] { for progressive in [false, true] { - let bytes = encode_jpeg_rgb8(16, 16, &rgb, q, progressive, false, None, None, None).unwrap(); + let bytes = encode_jpeg_rgb8(16, 16, &rgb, q, progressive, false, None, None, None, None).unwrap(); assert_eq!(luma_sampling(&bytes), Some(want), "quality {q} progressive {progressive}"); } } @@ -428,8 +440,8 @@ mod tests { #[test] fn progressive_jpeg_decodes() { let rgb: Vec = (0..64 * 48 * 3).map(|i| (i % 251) as u8).collect(); - let base = encode_jpeg_rgb8(64, 48, &rgb, 80, false, false, None, Some(72.0), Some("")).unwrap(); - let prog = encode_jpeg_rgb8(64, 48, &rgb, 80, true, true, None, None, None).unwrap(); + let base = encode_jpeg_rgb8(64, 48, &rgb, 80, false, false, None, Some(72.0), None, Some("")).unwrap(); + let prog = encode_jpeg_rgb8(64, 48, &rgb, 80, true, true, None, None, None, None).unwrap(); assert_ne!(base, prog); assert_eq!(crate::decode(&base).unwrap().meta.xmp.as_deref(), Some("")); // SOF2 marks a progressive frame. @@ -442,7 +454,7 @@ mod tests { fn web_jpeg_xmp_resolution_follows_the_density() { let rgb = vec![100u8; 8 * 8 * 3]; let xmp = r#""#; - let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), Some(xmp)).unwrap(); + let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), None, Some(xmp)).unwrap(); let img = crate::decode(&out).unwrap(); assert_eq!(img.meta.dpi, Some((72.0, 72.0))); assert_eq!(img.meta.xmp.as_deref().and_then(crate::xmp_resolution), Some((72.0, 72.0))); @@ -461,7 +473,7 @@ mod subsampling_tests { let rgb: Vec = (0..w * h).flat_map(|i| [((i % w) * 4) as u8, 76, ((i / w) * 5) as u8]).collect(); for q in [30, 60, 95] { for (prog, opt) in [(false, false), (false, true), (true, false), (true, true)] { - let bytes = encode_jpeg_rgb8(w, h, &rgb, q, prog, opt, None, None, None).unwrap(); + let bytes = encode_jpeg_rgb8(w, h, &rgb, q, prog, opt, None, None, None, None).unwrap(); let ours = crate::decode(&bytes).unwrap().convert(crate::ChannelLayout::Rgb, crate::SampleType::U8); let err = ours.data().iter().zip(&rgb).map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b))).max().unwrap(); assert!(err < 24, "q{q} progressive={prog} optimized={opt}: max error {err}"); diff --git a/crates/codecs/tests/dds.rs b/crates/codecs/tests/dds.rs index 766555f6e5..ebf4042f48 100644 --- a/crates/codecs/tests/dds.rs +++ b/crates/codecs/tests/dds.rs @@ -59,11 +59,12 @@ const WHITE: u16 = 0xffff; const INDICES_0123: [u8; 4] = [0x04, 0x0e, 0, 0]; #[test] -fn dds_is_readable_but_not_writable() { +fn dds_is_readable_and_writable() { assert_eq!(from_extension("texture.DDS"), Some(Format::Dds)); - assert!(caps(Format::Dds).read && !caps(Format::Dds).write); - let img = photocraft_codecs::Image::from_u8(1, 1, ChannelLayout::Rgba, vec![0, 0, 0, 0]).unwrap(); - assert!(matches!(encode(&img, Format::Dds, &Default::default()), Err(CodecError::Unsupported { .. }))); + assert!(caps(Format::Dds).read && caps(Format::Dds).write); + let img = photocraft_codecs::Image::from_u8(1, 1, ChannelLayout::Rgba, vec![1, 2, 3, 0]).unwrap(); + let b = encode(&img, Format::Dds, &Default::default()).unwrap(); + assert_eq!(decode(&b).unwrap().data(), &[1, 2, 3, 0]); } #[test] diff --git a/crates/codecs/tests/dds_write.rs b/crates/codecs/tests/dds_write.rs new file mode 100644 index 0000000000..3225dd14d6 --- /dev/null +++ b/crates/codecs/tests/dds_write.rs @@ -0,0 +1,372 @@ +//! Writing DDS textures: every storage read back through the reader, the header fields, sizes +//! that aren't a multiple of four, the mip chain, and the block-compression error on ramps. + +use photocraft_codecs::{ChannelLayout, DdsCompression, DdsOptions, EncodeOptions, FidelityWarning, Format, Image, decode, encode, fidelity_warnings_with}; + +const DDSD_PITCH: u32 = 0x8; +const DDSD_MIPMAPCOUNT: u32 = 0x2_0000; +const DDSD_LINEARSIZE: u32 = 0x8_0000; +const REQUIRED: u32 = 0x1007; // CAPS | HEIGHT | WIDTH | PIXELFORMAT +const DDSCAPS_COMPLEX: u32 = 0x8; +const DDSCAPS_TEXTURE: u32 = 0x1000; +const DDSCAPS_MIPMAP: u32 = 0x40_0000; +const DDPF_ALPHAPIXELS: u32 = 0x1; +const DDPF_FOURCC: u32 = 0x4; +const DDPF_RGB: u32 = 0x40; +const DDPF_LUMINANCE: u32 = 0x2_0000; + +const BLOCKS: [DdsCompression; 3] = [DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; + +fn opts(compression: DdsCompression, mipmaps: bool) -> EncodeOptions { + EncodeOptions { dds: DdsOptions { compression, mipmaps }, ..Default::default() } +} + +fn le32(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) +} + +/// A ramp along one line through RGB (red up, green up half as fast, blue down) across the +/// texture, and alpha falling from opaque down it: every block's colours lie on a line, which +/// is what a colour block stores. +fn ramp(w: u32, h: u32, layout: ChannelLayout) -> Image { + let ch = layout.channels(); + let at = |v: u32, n: u32| (v * 255 / (n - 1).max(1)) as u8; + let mut data = Vec::new(); + for y in 0..h { + for x in 0..w { + let r = at(x, w); + let rgba = [r, 64 + r / 2, 255 - r, 255 - at(y, h)]; + match ch { + 1 => data.push(rgba[0]), + 2 => data.extend([rgba[0], rgba[3]]), + _ => data.extend(&rgba[..ch]), + } + } + } + Image::from_u8(w, h, layout, data).unwrap() +} + +/// The same RGBA image, fully opaque. +fn opaque(img: &Image) -> Image { + let data = img.data().chunks(4).flat_map(|p| [p[0], p[1], p[2], 255]).collect(); + Image::from_u8(img.width(), img.height(), ChannelLayout::Rgba, data).unwrap() +} + +/// Largest difference in channel `c` (of four) between RGBA images. +fn max_diff_channel(a: &Image, b: &Image, c: usize) -> u8 { + a.data().chunks(4).zip(b.data().chunks(4)).map(|(x, y)| x[c].abs_diff(y[c])).max().unwrap_or(0) +} + +/// Largest colour difference between RGBA images where `b` is visible (BC1 turns texels under +/// half opacity into transparent black). +fn max_colour_diff(a: &Image, b: &Image) -> u8 { + a.data().chunks(4).zip(b.data().chunks(4)).filter(|(_, y)| y[3] != 0).flat_map(|(x, y)| (0..3).map(|c| x[c].abs_diff(y[c]))).max().unwrap_or(0) +} + +/// A 2D gradient: red across, green down and blue along the diagonal, opaque. +fn gradient(w: u32, h: u32) -> Image { + let data = (0..h).flat_map(|y| (0..w).flat_map(move |x| [(x * 4).min(255) as u8, (y * 4).min(255) as u8, ((x + y) * 2).min(255) as u8, 255])).collect(); + Image::from_u8(w, h, ChannelLayout::Rgba, data).unwrap() +} + +/// PSNR of the colour (not the alpha) of two RGBA images. +fn psnr(a: &Image, b: &Image) -> f64 { + let rgb = |i: &Image| i.data().chunks(4).flat_map(|p| [p[0], p[1], p[2]]).map(f64::from).collect::>(); + let (a, b) = (rgb(a), rgb(b)); + let mse = a.iter().zip(&b).map(|(x, y)| (x - y).powi(2)).sum::() / a.len() as f64; + if mse == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64.powi(2) / mse).log10() } +} + +/// Bytes of one level as a reader computes them from the header's pixel format. +fn level_bytes(file: &[u8], w: usize, h: usize) -> usize { + if le32(file, 80) & DDPF_FOURCC != 0 { + let block = if &file[84..88] == b"DXT1" { 8 } else { 16 }; + w.div_ceil(4) * h.div_ceil(4) * block + } else { + w * h * le32(file, 88) as usize / 8 + } +} + +/// Mip level `i` of a written texture, cut out as a single-level texture and decoded. +fn level(file: &[u8], i: u32) -> Image { + let (w, h) = (le32(file, 16) as usize, le32(file, 12) as usize); + let size = |i: u32| ((w >> i).max(1), (h >> i).max(1)); + let start = 128 + (0..i).map(|j| level_bytes(file, size(j).0, size(j).1)).sum::(); + let (lw, lh) = size(i); + let mut b = file[..128].to_vec(); + b[12..16].copy_from_slice(&(lh as u32).to_le_bytes()); + b[16..20].copy_from_slice(&(lw as u32).to_le_bytes()); + b[28..32].copy_from_slice(&1u32.to_le_bytes()); + b.extend(&file[start..start + level_bytes(file, lw, lh)]); + decode(&b).unwrap() +} + +#[test] +fn uncompressed_textures_round_trip_every_layout_exactly() { + for (layout, pf_flags, bits, masks) in [ + (ChannelLayout::Gray, DDPF_LUMINANCE, 8, [0xff, 0, 0, 0]), + (ChannelLayout::GrayA, DDPF_LUMINANCE | DDPF_ALPHAPIXELS, 16, [0xff, 0, 0, 0xff00]), + (ChannelLayout::Rgb, DDPF_RGB, 32, [0xff_0000, 0xff00, 0xff, 0]), + (ChannelLayout::Rgba, DDPF_RGB | DDPF_ALPHAPIXELS, 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]), + ] { + for (w, h) in [(1, 1), (5, 3), (17, 9)] { + let img = ramp(w, h, layout); + let b = encode(&img, Format::Dds, &EncodeOptions::default()).unwrap(); + let back = decode(&b).unwrap(); + assert_eq!(back.layout(), layout, "{layout:?} {w}x{h}"); + assert_eq!(back.data(), img.data(), "{layout:?} {w}x{h}"); + + assert_eq!((&b[..4], le32(&b, 4), le32(&b, 76)), (&b"DDS "[..], 124, 32)); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_PITCH, "pitch, not linear size, and no mip count"); + assert_eq!((le32(&b, 12), le32(&b, 16)), (h, w)); + assert_eq!(le32(&b, 20), w * bits / 8, "pitch of {layout:?} {w}x{h}"); + assert_eq!((le32(&b, 28), le32(&b, 108)), (1, DDSCAPS_TEXTURE)); + assert_eq!((le32(&b, 80), le32(&b, 88)), (pf_flags, bits)); + assert_eq!([le32(&b, 92), le32(&b, 96), le32(&b, 100), le32(&b, 104)], masks); + assert_eq!(b.len(), 128 + (w * h * bits / 8) as usize); + } + } +} + +#[test] +fn block_compressed_textures_round_trip_through_the_reader() { + for (compression, fourcc, block) in [(DdsCompression::Bc1, b"DXT1", 8), (DdsCompression::Bc2, b"DXT3", 16), (DdsCompression::Bc3, b"DXT5", 16)] { + // Not multiples of four, and the 1×1 and 2×2 textures smaller than one block. + for (w, h) in [(1, 1), (2, 2), (4, 4), (5, 3), (7, 13), (33, 17)] { + let img = ramp(w, h, ChannelLayout::Rgba); + let b = encode(&img, Format::Dds, &opts(compression, false)).unwrap(); + let linear = w.div_ceil(4) * h.div_ceil(4) * block; + assert_eq!(&b[84..88], fourcc); + assert_eq!((le32(&b, 80), le32(&b, 88)), (DDPF_FOURCC, 0)); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_LINEARSIZE, "linear size, not pitch"); + assert_eq!(le32(&b, 20), linear, "{compression:?} {w}x{h}: the top level's size"); + assert_eq!(b.len(), 128 + linear as usize); + + let back = decode(&b).unwrap(); + assert_eq!((back.dimensions(), back.layout()), ((w, h), ChannelLayout::Rgba)); + // Steep ramps across tiny textures put three colours where a block interpolates at + // thirds, so this bound is loose; it still catches swapped channels or misplaced + // blocks. `block_compression_error_on_gradients_is_bounded` is the tight one. A BC1 + // block with transparent texels has only three colours, so BC1's colours are + // checked on the opaque ramp. + let (src, back_colour) = if compression == DdsCompression::Bc1 { + let o = opaque(&img); + let back = decode(&encode(&o, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + (o, back) + } else { + (img.clone(), back.clone()) + }; + let colour = max_colour_diff(&src, &back_colour); + assert!(colour <= 24, "{compression:?} {w}x{h}: colour off by {colour}"); + let alpha = max_diff_channel(&img, &back, 3); + match compression { + DdsCompression::Bc1 => assert!(back.data().chunks(4).zip(img.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 })), + _ => assert!(alpha <= 8, "{compression:?} {w}x{h}: alpha off by {alpha}"), + } + } + } +} + +#[test] +fn gray_and_rgb_sources_are_written_as_rgba_blocks() { + for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb] { + for compression in BLOCKS { + let img = ramp(8, 8, layout); + let back = decode(&encode(&img, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + let want = img.convert(ChannelLayout::Rgba, img.sample_type()); + assert_eq!(back.layout(), ChannelLayout::Rgba); + let colour = max_colour_diff(&want, &back); + assert!(colour <= 8, "{layout:?} {compression:?}: colour off by {colour}"); + } + } +} + +#[test] +fn block_compression_error_on_gradients_is_bounded() { + let (line, plane) = (ramp(64, 64, ChannelLayout::Rgba), gradient(64, 64)); + for compression in BLOCKS { + let roundtrip = |img: &Image| decode(&encode(img, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + let (line_back, plane_back) = (roundtrip(&line), roundtrip(&plane)); + let (line_err, plane_err) = (max_colour_diff(&line, &line_back), max_colour_diff(&plane, &plane_back)); + let p = psnr(&plane, &plane_back); + let alpha = max_diff_channel(&line, &line_back, 3); + // Colours on a line only lose the RGB565 rounding of the endpoints (up to 4 levels in + // red and blue). A gradient in two directions is not on a line: the spread off a + // block's best line alone limits this one to about 40 dB, and RGB565 costs a little + // more (the encoder measures 38.6 dB and 9 levels at most). + assert!(line_err <= 5, "{compression:?}: colour ramp off by {line_err}"); + assert!(plane_err <= 10, "{compression:?}: 2D gradient off by {plane_err}"); + assert!(p >= 38.0, "{compression:?}: 2D gradient PSNR {p:.1} dB"); + match compression { + DdsCompression::Bc1 => assert!(line_back.data().chunks(4).zip(line.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 })), + // Four bits: within half a step of 17. + DdsCompression::Bc2 => assert!(alpha <= 8, "BC2 alpha off by {alpha}"), + // Eight values across a block's few levels of alpha. + _ => assert!(alpha <= 2, "BC3 alpha off by {alpha}"), + } + } +} + +#[test] +fn solid_and_cutout_textures_keep_their_values() { + // RGB565-exact colours and BC2's 4-bit alpha steps come back exactly. + let solid = Image::from_u8(6, 5, ChannelLayout::Rgba, [255, 0, 255, 170].repeat(30)).unwrap(); + for compression in BLOCKS { + let back = decode(&encode(&solid, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + let want = if compression == DdsCompression::Bc1 { [255, 0, 255, 255] } else { [255, 0, 255, 170] }; + assert!(back.data().chunks(4).all(|p| p == want), "{compression:?}: {:?}", &back.data()[..4]); + } + // A cutout: BC1's transparent texels decode as transparent black, the rest stay opaque. + let cutout: Vec = (0..36).flat_map(|i| if (i / 6 + i % 6) % 2 == 0 { [200, 40, 40, 255] } else { [10, 10, 10, 0] }).collect(); + let cutout = Image::from_u8(6, 6, ChannelLayout::Rgba, cutout).unwrap(); + for compression in BLOCKS { + let back = decode(&encode(&cutout, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + assert_eq!(max_diff_channel(&cutout, &back, 3), 0, "{compression:?}"); + if compression == DdsCompression::Bc1 { + assert!(back.data().chunks(4).filter(|p| p[3] == 0).all(|p| p == [0, 0, 0, 0])); + } + } +} + +#[test] +fn mipmaps_write_the_full_chain_box_filtered() { + // 16×8 halves to 8×4, 4×2, 2×1 and 1×1: five levels. + let img = ramp(16, 8, ChannelLayout::Rgba); + let b = encode(&img, Format::Dds, &opts(DdsCompression::None, true)).unwrap(); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_PITCH | DDSD_MIPMAPCOUNT); + assert_eq!(le32(&b, 28), 5); + assert_eq!(le32(&b, 108), DDSCAPS_TEXTURE | DDSCAPS_COMPLEX | DDSCAPS_MIPMAP); + assert_eq!(b.len(), 128 + 4 * (16 * 8 + 8 * 4 + 4 * 2 + 2 + 1)); + assert_eq!(decode(&b).unwrap().data(), img.data(), "the reader still reads the top level"); + let mut above = img.clone(); + for i in 1..5 { + let got = level(&b, i); + assert_eq!(got.dimensions(), ((16 >> i).max(1), (8 >> i).max(1))); + let want = box_filter(&above); + assert_eq!(got.data(), want.data(), "level {i}"); + above = got; + } + // 1×1 has a single level. + let one = encode(&ramp(1, 1, ChannelLayout::Rgba), Format::Dds, &opts(DdsCompression::None, true)).unwrap(); + assert_eq!((le32(&one, 28), le32(&one, 8) & DDSD_MIPMAPCOUNT), (1, 0)); +} + +/// The documented filter, written independently: each pixel averages the 2×2 pixels it covers, +/// and the last column and row of an odd-sized level take in the leftover pixel too. +fn box_filter(src: &Image) -> Image { + let (w, h) = (src.width() as usize, src.height() as usize); + let (nw, nh) = ((w / 2).max(1), (h / 2).max(1)); + let ch = src.layout().channels(); + let span = |i: usize, n: usize, size: usize| (2 * i, if i + 1 == n { size } else { 2 * i + 2 }); + let mut out = Vec::new(); + for y in 0..nh { + for x in 0..nw { + let ((x0, x1), (y0, y1)) = (span(x, nw, w), span(y, nh, h)); + for c in 0..ch { + let values: Vec = + (y0..y1).flat_map(|sy| (x0..x1).map(move |sx| (sy, sx))).map(|(sy, sx)| u32::from(src.data()[(sy * w + sx) * ch + c])).collect(); + let n = values.len() as u32; + out.push(((values.iter().sum::() + n / 2) / n) as u8); + } + } + } + Image::from_u8(nw as u32, nh as u32, src.layout(), out).unwrap() +} + +#[test] +fn odd_sized_mip_chains_keep_every_pixel() { + // 5×3 → 2×1 → 1×1. The 2×1 level's right pixel averages columns 2–4 of all three rows. + let img = ramp(5, 3, ChannelLayout::Gray); + let b = encode(&img, Format::Dds, &opts(DdsCompression::None, true)).unwrap(); + assert_eq!(le32(&b, 28), 3); + assert_eq!(b.len(), 128 + 5 * 3 + 2 + 1); + let second = level(&b, 1); + assert_eq!(second.data(), box_filter(&img).data()); + let px = |x: usize, y: usize| u32::from(img.data()[y * 5 + x]); + let right: u32 = (0..3).flat_map(|y| (2..5).map(move |x| (x, y))).map(|(x, y)| px(x, y)).sum(); + assert_eq!(u32::from(second.data()[1]), (right + 4) / 9); +} + +#[test] +fn block_compressed_mip_chains_have_a_block_per_small_level() { + for compression in BLOCKS { + let block = if compression == DdsCompression::Bc1 { 8 } else { 16 }; + let img = ramp(12, 6, ChannelLayout::Rgba); + let b = encode(&img, Format::Dds, &opts(compression, true)).unwrap(); + // 12×6, 6×3, 3×1, 1×1: 3×2, 2×1, 1 and 1 blocks. + assert_eq!(le32(&b, 28), 4); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_LINEARSIZE | DDSD_MIPMAPCOUNT); + assert_eq!(le32(&b, 20), 6 * block); + assert_eq!(b.len(), 128 + (6 + 2 + 1 + 1) * block as usize); + for i in 0..4 { + let got = level(&b, i); + assert_eq!(got.dimensions(), ((12 >> i).max(1), (6 >> i).max(1)), "{compression:?} level {i}"); + } + } +} + +#[test] +fn strips_and_tiny_textures_encode_with_every_option() { + for (w, h) in [(1, 1), (1, 9), (9, 1), (2, 3), (3, 2)] { + for compression in DdsCompression::ALL { + for mipmaps in [false, true] { + let img = ramp(w, h, ChannelLayout::Rgba); + let b = encode(&img, Format::Dds, &opts(compression, mipmaps)).unwrap_or_else(|e| panic!("{w}x{h} {compression:?} {mipmaps}: {e}")); + assert_eq!(decode(&b).unwrap().dimensions(), (w, h)); + } + } + } +} + +#[test] +fn fidelity_warnings_follow_the_compression() { + let translucent = ramp(8, 8, ChannelLayout::Rgba); + let warns = |c| fidelity_warnings_with(&translucent, Format::Dds, &opts(c, false)); + assert!(warns(DdsCompression::None).is_empty(), "uncompressed RGBA loses nothing"); + for c in BLOCKS { + assert!(warns(c).contains(&FidelityWarning::LossyCompression), "{c:?}"); + } + assert!(warns(DdsCompression::Bc1).contains(&FidelityWarning::AlphaBinarized)); + assert!(!warns(DdsCompression::Bc3).contains(&FidelityWarning::AlphaBinarized)); +} + +#[test] +fn compression_names_round_trip() { + for c in DdsCompression::ALL { + assert_eq!(DdsCompression::from_name(c.name()), Some(c)); + } + assert_eq!(DdsCompression::from_name("DXT5"), Some(DdsCompression::Bc3)); + assert_eq!(DdsCompression::from_name("dxt1"), Some(DdsCompression::Bc1)); + for bad in ["", "bc7", "dxt2", "uncompressed "] { + assert_eq!(DdsCompression::from_name(bad), None, "{bad:?}"); + } +} + +/// Encode timings on a synthetic ~30 MP texture (6336×4752). Ignored by default; run in release: +/// +/// ```sh +/// cargo test --release -p photocraft-codecs --test dds_write -- --ignored --nocapture +/// ``` +#[test] +#[ignore] +fn dds_encode_timings_on_30_mp() { + let (w, h) = (6336u32, 4752u32); + let mut s = 0x1234_5678u32; + let mut data = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..h { + for x in 0..w { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + data.extend([(x / 25 + y / 19) as u8, (x / 31) as u8 ^ (s as u8 & 3), (y / 23) as u8, (255 - x / 25) as u8]); + } + } + let img = Image::from_u8(w, h, ChannelLayout::Rgba, data).unwrap(); + for compression in DdsCompression::ALL { + for mipmaps in [false, true] { + let t = std::time::Instant::now(); + let b = encode(&img, Format::Dds, &opts(compression, mipmaps)).unwrap(); + eprintln!("{compression:?} mipmaps={mipmaps}: {:.0} ms, {} MB", t.elapsed().as_secs_f64() * 1e3, b.len() >> 20); + } + } +} diff --git a/crates/codecs/tests/exr_multipart.rs b/crates/codecs/tests/exr_multipart.rs index f106d37791..421d494710 100644 --- a/crates/codecs/tests/exr_multipart.rs +++ b/crates/codecs/tests/exr_multipart.rs @@ -8,7 +8,9 @@ use exr::prelude::{ WritableImage, }; use photocraft_codecs::f16; -use photocraft_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType, decode, decode_as_with, decode_exr_part, exr_info}; +use photocraft_codecs::{ + ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType, decode, decode_as_with, decode_exr_part, exr_info, probe_size, +}; fn layer_f32(name: &str, comp: Compression, chans: &[(&str, Vec)]) -> Layer> { let n = chans.iter().find(|(_, v)| !v.is_empty()).map_or(0, |(_, v)| v.len()); @@ -226,3 +228,107 @@ fn decoding_one_part_does_not_decode_the_others() { assert_eq!((img.width(), img.height()), (4, 4)); assert!(img.to_normalized().iter().all(|v| near(*v, 0.75)), "wrong pixels"); } + +fn channel_group_file(channels: &[(&str, f32)]) -> Vec { + let channels: Vec<_> = channels.iter().map(|(name, value)| (*name, vec![*value; 4])).collect(); + write_image(vec![layer_f32("groups", Compression::ZIP1, &channels)]) +} + +fn assert_channel_group(bytes: &[u8], layout: ChannelLayout, expected: &[f32]) { + assert_eq!(exr_info(bytes, &Limits::default()).unwrap()[0].color_rank(), expected.len() as u8); + assert_eq!(probe_size(bytes).unwrap(), (2, 2)); + for img in [decode(bytes).unwrap(), decode_exr_part(bytes, 0, &DecodeOptions::default()).unwrap()] { + assert_eq!(img.layout(), layout); + assert_eq!(img.to_normalized(), expected.repeat(4)); + } +} + +#[test] +fn flat_decode_keeps_rgb_channels_in_one_group() { + // A partial group sorts before the nested beauty layer, but cannot donate its R. + let bytes = channel_group_file(&[("aaa.R", 9.0), ("beauty.diffuse.R", 0.25), ("beauty.diffuse.G", 0.5), ("beauty.diffuse.B", 2.0)]); + assert_channel_group(&bytes, ChannelLayout::Rgb, &[0.25, 0.5, 2.0]); +} + +#[test] +fn flat_decode_does_not_borrow_another_groups_alpha() { + for alpha in ["A", "aaa.A", "beauty.other.A"] { + let bytes = channel_group_file(&[(alpha, 0.125), ("beauty.R", 0.25), ("beauty.G", 0.5), ("beauty.B", 2.0)]); + assert_channel_group(&bytes, ChannelLayout::Rgb, &[0.25, 0.5, 2.0]); + let bytes = channel_group_file(&[(alpha, 0.125), ("beauty.Y", 0.5)]); + assert_channel_group(&bytes, ChannelLayout::Gray, &[0.5]); + } +} + +#[test] +fn flat_decode_rejects_rgb_split_between_groups() { + for channels in [ + [("aaa.R", 0.25), ("bbb.G", 0.5), ("ccc.B", 2.0)], + [("beauty.R", 0.25), ("beauty.diffuse.G", 0.5), ("beauty.diffuse.B", 2.0)], + [(".R", 0.25), ("G", 0.5), ("B", 2.0)], + ] { + let bytes = channel_group_file(&channels); + assert_eq!(exr_info(&bytes, &Limits::default()).unwrap()[0].color_rank(), 0); + assert!(probe_size(&bytes).is_err()); + assert!(decode(&bytes).is_err()); + assert!(decode_exr_part(&bytes, 0, &DecodeOptions::default()).is_err()); + } +} + +#[test] +fn auto_pick_and_probe_skip_incoherent_rgb_parts() { + let bytes = write_image(vec![ + layer_f32("split", Compression::ZIP1, &[("aaa.R", vec![9.0; 4]), ("bbb.G", vec![8.0; 4]), ("ccc.B", vec![7.0; 4])]), + layer_f32("luminance", Compression::ZIP1, &[("Y", vec![0.5; 16]), ("A", vec![0.75; 16])]), + ]); + let parts = exr_info(&bytes, &Limits::default()).unwrap(); + assert_eq!(parts.iter().map(|part| part.color_rank()).collect::>(), [0, 2]); + assert_eq!(probe_size(&bytes).unwrap(), (4, 4)); + let img = decode(&bytes).unwrap(); + assert_eq!((img.width(), img.height(), img.layout()), (4, 4, ChannelLayout::GrayA)); + assert_eq!(img.to_f32_samples().unwrap(), [0.5, 0.75].repeat(16)); +} + +#[test] +fn flat_decode_prefers_the_highest_ranked_complete_group() { + let bytes = + channel_group_file(&[("aaa.R", 9.0), ("aaa.G", 8.0), ("aaa.B", 7.0), ("beauty.R", 0.25), ("beauty.G", 0.5), ("beauty.B", 2.0), ("beauty.A", 0.75)]); + assert_channel_group(&bytes, ChannelLayout::Rgba, &[0.25, 0.5, 2.0, 0.75]); + let bytes = channel_group_file(&[("aaa.Y", 9.0), ("beauty.Y", 0.5), ("beauty.A", 0.75)]); + assert_channel_group(&bytes, ChannelLayout::GrayA, &[0.5, 0.75]); +} + +#[test] +fn flat_decode_breaks_group_ties_by_prefix() { + let bytes = channel_group_file(&[("z.R", 9.0), ("z.G", 8.0), ("z.B", 7.0), ("beauty.R", 0.25), ("beauty.G", 0.5), ("beauty.B", 2.0)]); + assert_channel_group(&bytes, ChannelLayout::Rgb, &[0.25, 0.5, 2.0]); + // Even a prefix that sorts before the unprefixed channel names loses a rank tie. + let bytes = channel_group_file(&[("0.R", 9.0), ("0.G", 8.0), ("0.B", 7.0), ("R", 0.25), ("G", 0.5), ("B", 2.0)]); + assert_channel_group(&bytes, ChannelLayout::Rgb, &[0.25, 0.5, 2.0]); +} + +#[test] +fn flat_decode_preserves_luminance_and_lone_channel_fallbacks() { + for prefix in ["", "beauty."] { + let y = format!("{prefix}Y"); + let a = format!("{prefix}A"); + assert_channel_group(&channel_group_file(&[(&y, 2.0), (&a, 0.75)]), ChannelLayout::GrayA, &[2.0, 0.75]); + assert_channel_group(&channel_group_file(&[(&y, 2.0)]), ChannelLayout::Gray, &[2.0]); + } + for name in ["depth.Z", "A", "beauty.A"] { + // A lone alpha is one grayscale channel, not the same samples duplicated as YA. + assert_channel_group(&channel_group_file(&[(name, 9.0)]), ChannelLayout::Gray, &[9.0]); + } +} + +#[test] +fn half_float_group_does_not_use_unrelated_float_channels() { + let mut layer = layer_f32("mixed", Compression::ZIP1, &[("aaa.R", vec![9.0; 4]), ("aaa.A", vec![0.125; 4])]); + for (name, value) in [("beauty.R", 0.25), ("beauty.G", 0.5), ("beauty.B", 2.0), ("beauty.A", 0.75)] { + layer.channel_data.list.push(AnyChannel::new(name, FlatSamples::F16(vec![f16::from_f32(value); 4]))); + } + layer.channel_data = AnyChannels::sort(layer.channel_data.list); + let bytes = write_image(vec![layer]); + assert_channel_group(&bytes, ChannelLayout::Rgba, &[0.25, 0.5, 2.0, 0.75]); + assert_eq!(decode(&bytes).unwrap().sample_type(), SampleType::F16); +} diff --git a/crates/codecs/tests/pnm_headers.rs b/crates/codecs/tests/pnm_headers.rs new file mode 100644 index 0000000000..b6d9c076f5 --- /dev/null +++ b/crates/codecs/tests/pnm_headers.rs @@ -0,0 +1,82 @@ +use photocraft_codecs::{ChannelLayout, CodecError, Format, SampleType, decode, decode_as}; + +const PAM_GRAY: &[u8] = b"P7\nWIDTH 1\nHEIGHT 1\nDEPTH 1\nMAXVAL 255\nENDHDR"; +const ENDINGS: &[&[u8]] = &[b"\n", b" \n", b"\t \n", b"\r\n", b" \t\r\n"]; + +#[test] +fn pam_consumes_the_complete_endhdr_line() { + for ending in ENDINGS { + let mut bytes = PAM_GRAY.to_vec(); + bytes.extend_from_slice(ending); + bytes.push(0x80); + let img = decode(&bytes).unwrap(); + assert_eq!(img.dimensions(), (1, 1)); + assert_eq!(img.layout(), ChannelLayout::Gray); + assert_eq!(img.data(), &[0x80], "ENDHDR ending {ending:?}"); + } +} + +#[test] +fn pam_preserves_every_possible_first_raster_byte() { + // In particular, LF, CR, space, tab and '#' must not be skipped as header syntax. + for ending in ENDINGS { + for first in 0..=255u8 { + let mut bytes = PAM_GRAY.to_vec(); + bytes.extend_from_slice(ending); + bytes.push(first); + assert_eq!(decode(&bytes).unwrap().data(), &[first], "ENDHDR ending {ending:?}, raster byte {first}"); + } + } +} + +#[test] +fn pam_crlf_header_preserves_u16_samples_and_alpha() { + for ending in ENDINGS { + let mut bytes = b"P7\r\nWIDTH 1\r\nHEIGHT 1\r\nDEPTH 2\r\nMAXVAL 65535\r\nTUPLTYPE GRAYSCALE_ALPHA\r\nENDHDR".to_vec(); + bytes.extend_from_slice(ending); + bytes.extend_from_slice(b" \n#\r"); + let img = decode(&bytes).unwrap(); + assert_eq!(img.layout(), ChannelLayout::GrayA); + assert_eq!(img.sample_type(), SampleType::U16); + assert_eq!(img.to_u16_samples().unwrap(), vec![0x200a, 0x230d], "ENDHDR ending {ending:?}"); + } +} + +#[test] +fn pam_rejects_unterminated_or_invalid_endhdr_lines() { + for suffix in [b"".as_slice(), b" ", b"\r", b" \t\r", b" \x80", b" \x80\n\x7f", b"#comment\n\x7f"] { + let mut bytes = PAM_GRAY.to_vec(); + bytes.extend_from_slice(suffix); + assert!(matches!(decode_as(Format::Pnm, &bytes), Err(CodecError::Malformed { .. })), "ENDHDR suffix {suffix:?}"); + } +} + +#[test] +fn pam_truncation_never_uses_header_whitespace_as_pixels() { + for ending in ENDINGS { + let mut bytes = PAM_GRAY.to_vec(); + bytes.extend_from_slice(ending); + bytes.push(0x80); + for cut in 0..bytes.len() { + assert!(decode_as(Format::Pnm, &bytes[..cut]).is_err(), "ENDHDR ending {ending:?}, truncated at {cut}"); + } + } +} + +#[test] +fn binary_pnm_keeps_its_single_whitespace_separator() { + for separator in *b" \t\r\n" { + for first in *b" \t\r\n#" { + for (header, channels) in [(b"P5\n1 1\n255".as_slice(), 1), (b"P6\n1 1\n255", 3)] { + let mut bytes = header.to_vec(); + bytes.push(separator); + bytes.extend(std::iter::repeat_n(first, channels)); + assert_eq!(decode(&bytes).unwrap().data(), vec![first; channels]); + } + let mut bytes = b"P4\n8 1".to_vec(); + bytes.extend_from_slice(&[separator, first]); + let expected: Vec = (0..8).map(|bit| if first & (0x80 >> bit) == 0 { 255 } else { 0 }).collect(); + assert_eq!(decode(&bytes).unwrap().data(), expected); + } + } +} diff --git a/crates/codecs/tests/roundtrip.rs b/crates/codecs/tests/roundtrip.rs index 7918d313b6..9c6cb8cb6f 100644 --- a/crates/codecs/tests/roundtrip.rs +++ b/crates/codecs/tests/roundtrip.rs @@ -137,6 +137,9 @@ mod fits { mod dpx { cases!(Format::Dpx); } +mod dds { + cases!(Format::Dds); +} mod qoi { cases!(Format::Qoi); } diff --git a/crates/codecs/tests/tga.rs b/crates/codecs/tests/tga.rs new file mode 100644 index 0000000000..279aa47f8b --- /dev/null +++ b/crates/codecs/tests/tga.rs @@ -0,0 +1,91 @@ +//! Targa writing (#6382): run-length packets end with their scanline, rows are stored bottom-up, +//! and the file reads back exactly. + +use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, decode_as, encode}; + +/// The packets of a run-length encoded Targa body, as (pixels, is a run), from just after the +/// 18-byte header (no image ID or colour map) up to `pixels` pixels. +fn packets(file: &[u8], bpp: usize, pixels: usize) -> Vec<(usize, bool)> { + let mut at = 18; + let mut seen = 0; + let mut out = Vec::new(); + while seen < pixels { + let head = file[at]; + let count = usize::from(head & 0x7f) + 1; + let run = head & 0x80 != 0; + at += 1 + if run { bpp } else { count * bpp }; + seen += count; + out.push((count, run)); + } + out +} + +/// A `w`×`h` image whose rows mix long runs (wider than a packet), short ones and noise, and +/// whose last pixel equals the next row's first, so a packet would run on if it could. +fn sample(w: u32, h: u32, layout: ChannelLayout) -> Image { + let n = layout.channels(); + let mut data = Vec::new(); + for y in 0..h { + for x in 0..w { + let v = match x { + _ if x < 150 => 40, + _ if x % 3 == 0 => (x * 7 + y * 13) as u8, + _ => 200, + }; + let px = [v, v.wrapping_add(y as u8), v ^ 0x5a, 255 - v]; + data.extend_from_slice(&px[..n]); + } + } + Image::from_u8(w, h, layout, data).unwrap() +} + +#[test] +fn rle_packets_end_with_their_scanline() { + for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] { + let (w, h) = (300u32, 4u32); + let file = encode(&sample(w, h, layout), Format::Tga, &EncodeOptions::default()).unwrap(); + let bpp = layout.channels(); + let mut col = 0; + for (count, _) in packets(&file, bpp, (w * h) as usize) { + assert!(count <= 128, "{layout:?}: a packet holds at most 128 pixels"); + assert!(col + count <= w as usize, "{layout:?}: a packet runs from column {col} past the row's end"); + col = (col + count) % w as usize; + } + // A solid image is one run per row (three packets of 128, 128 and 44), not one long run. + let solid = Image::from_u8(w, h, layout, vec![90; (w * h) as usize * bpp]).unwrap(); + let file = encode(&solid, Format::Tga, &EncodeOptions::default()).unwrap(); + let p = packets(&file, bpp, (w * h) as usize); + assert_eq!(p.len(), 3 * h as usize, "{layout:?}"); + assert!(p.iter().all(|&(_, run)| run)); + } +} + +#[test] +fn the_file_is_bottom_up_rle_with_its_alpha_bits_and_the_tga2_footer() { + let mut data = vec![0u8; 2 * 2 * 4]; + // Top row red, bottom row blue, opaque. + for (i, px) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() { + *px = if i < 2 { [255, 0, 0, 255] } else { [0, 0, 255, 255] }; + } + let file = encode(&Image::from_u8(2, 2, ChannelLayout::Rgba, data).unwrap(), Format::Tga, &EncodeOptions::default()).unwrap(); + assert_eq!(file[2], 10, "run-length true colour"); + assert_eq!((file[16], file[17]), (32, 8), "32 bits per pixel, 8 alpha bits, bottom-left origin"); + // The first stored row is the bottom one: a run of two blue pixels, in BGRA. + assert_eq!(&file[18..23], &[0x81, 255, 0, 0, 255]); + assert!(file.ends_with(b"TRUEVISION-XFILE.\0")); + let gray = encode(&Image::from_u8(2, 1, ChannelLayout::Gray, vec![1, 2]).unwrap(), Format::Tga, &EncodeOptions::default()).unwrap(); + assert_eq!((gray[2], gray[16], gray[17]), (11, 8, 0), "run-length grayscale, no alpha bits"); +} + +#[test] +fn every_layout_reads_back_exactly() { + for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] { + for (w, h) in [(1, 1), (300, 4), (129, 3), (5, 130)] { + let img = sample(w, h, layout); + let file = encode(&img, Format::Tga, &EncodeOptions::default()).unwrap(); + let back = decode_as(Format::Tga, &file).unwrap(); + assert_eq!((back.dimensions(), back.layout()), ((w, h), layout), "{layout:?} {w}x{h}"); + assert_eq!(back.data(), img.data(), "{layout:?} {w}x{h}"); + } + } +} diff --git a/crates/codecs/tests/tiff_exif.rs b/crates/codecs/tests/tiff_exif.rs index 92e8c91df0..7e06a0e5b8 100644 --- a/crates/codecs/tests/tiff_exif.rs +++ b/crates/codecs/tests/tiff_exif.rs @@ -166,3 +166,97 @@ fn no_exif_is_written_without_embed_metadata() { let tiff = encode(&img, Format::Tiff, &EncodeOptions { embed_metadata: false, ..Default::default() }).unwrap(); assert_eq!(decode(&tiff).unwrap().meta.exif, None); } + +// --------------------------------------------------------------------------- +// Bounded copying: an entry's value only has to lie inside the file, so a hostile file can have +// many entries point at the same bytes. +// --------------------------------------------------------------------------- + +/// A valid 1x1 gray TIFF whose Exif directory has `entries` UNDEFINED entries of `count` bytes +/// that all point at the same `count` bytes: the file is about `count` bytes long and asks to +/// copy `entries * count`. +fn overlapping_tiff(entries: usize, count: u32) -> Vec { + let entry = |tag: u16, ty: u16, count: u32, value: u32| { + [tag.to_le_bytes().to_vec(), ty.to_le_bytes().to_vec(), count.to_le_bytes().to_vec(), value.to_le_bytes().to_vec()].concat() + }; + let at_exif = 8 + 2 + 12 * 10 + 4; + let data_at = at_exif + 2 + 12 * entries + 4; + let mut out = b"II".to_vec(); + out.extend(42u16.to_le_bytes()); + out.extend(8u32.to_le_bytes()); + out.extend(10u16.to_le_bytes()); + for (tag, ty, value) in + [(256, 3, 1), (257, 3, 1), (258, 3, 8), (259, 3, 1), (262, 3, 1), (273, 4, 0), (277, 3, 1), (278, 3, 1), (279, 4, 1), (34665, 4, at_exif as u32)] + { + out.extend(entry(tag, ty, 1, value)); + } + out.extend(0u32.to_le_bytes()); + out.extend((entries as u16).to_le_bytes()); + for i in 0..entries { + out.extend(entry(i as u16 + 1, 7, count, data_at as u32)); + } + out.extend(0u32.to_le_bytes()); + out.extend(vec![0x5A; count as usize]); + out +} + +#[test] +fn overlapping_field_values_are_bounded() { + // About 62 KB on disk; copied entry by entry it would be 1,000 x 50,000 bytes. + let tiff = overlapping_tiff(1000, 50_000); + assert!(tiff.len() < 64 * 1024); + let img = decode(&tiff).expect("the image itself is fine"); + assert_eq!(img.dimensions(), (1, 1)); + let exif = img.meta.exif.expect("the first entries are kept"); + assert!(exif.len() <= 2 * tiff.len(), "{} bytes of EXIF from a {} byte file", exif.len(), tiff.len()); +} + +#[test] +fn overlapping_field_values_in_an_exif_block_are_bounded_on_export() { + // The same block as an image's EXIF: the writer reads it with the same code. + let block = overlapping_tiff(1000, 50_000); + let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap(); + img.meta.exif = Some(block.clone()); + let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap(); + assert!(tiff.len() <= 2 * block.len(), "a {} byte block wrote a {} byte file", block.len(), tiff.len()); +} + +/// An EXIF block with a maker note of `len` bytes, an exposure time and a GPS latitude reference. +fn block_with_maker_note(le: bool, len: usize) -> Vec { + let b = Block { le }; + b.build( + vec![(271, 2, 4, b"Cam\0".to_vec())], + vec![(33434, 5, 1, b.rational(1, 125)), (37500, 7, len as u32, (0..len).map(|i| (i * 7) as u8).collect())], + vec![(1, 2, 2, b"N\0".to_vec())], + ) +} + +#[test] +fn large_maker_notes_still_survive() { + // Nikon maker notes run from 100 KB to nearly 1 MB. + for len in [200 * 1024, 1000 * 1024] { + let block = block_with_maker_note(true, len); + let mut img = Image::from_raw(4, 3, ChannelLayout::Rgb, SampleType::U8, vec![90; 36]).unwrap(); + img.meta.exif = Some(block.clone()); + let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap(); + let back = decode(&tiff).unwrap().meta.exif.expect("EXIF read back"); + let (ble, _, bexif, bgps) = dirs(&back); + let (ole, _, oexif, ogps) = dirs(&block); + assert_eq!(normalized(&bexif, ble), normalized(&oexif, ole), "{len} byte maker note"); + assert_eq!(normalized(&bgps, ble), normalized(&ogps, ole)); + } +} + +#[test] +fn a_field_beyond_the_cap_is_dropped_and_the_rest_kept() { + let block = block_with_maker_note(false, 6 * 1024 * 1024); + let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap(); + img.meta.exif = Some(block); + let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap(); + assert!(tiff.len() < 1024 * 1024, "{} bytes", tiff.len()); + let back = decode(&tiff).unwrap().meta.exif.expect("EXIF read back"); + let (_, ifd0, exif, gps) = dirs(&back); + assert_eq!(exif.iter().map(|e| e.0).collect::>(), [33434], "the exposure time stays, the 6 MiB maker note goes"); + assert_eq!(gps.iter().map(|e| e.0).collect::>(), [1]); + assert_eq!(ifd0.iter().map(|e| e.0).collect::>(), [271]); +} diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 5acdd79314..cbdf7f35a2 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -37,6 +37,25 @@ pub fn has_effects(layer: &Layer) -> bool { layer.effects.enabled && layer.effects.items.iter().any(Effect::enabled) } +/// Whether an enabled effect is laid out over the layer's frame ([`crate::effects_frame`]), so +/// growing or shrinking the layer repaints it everywhere, not only where its pixels changed: a +/// Gradient Overlay, a gradient stroke (its frame is the shape's extent), and patterns linked with +/// the layer without an effects reference point (overlays, pattern strokes and glows, and bevel +/// textures tile from the frame's top-left). +pub fn spans_frame(layer: &Layer) -> bool { + let unanchored = layer.effects.reference.is_none(); + let pattern = |p: &FxPaint| unanchored && matches!(p, FxPaint::Pattern { .. }); + has_effects(layer) + && layer.effects.items.iter().filter(|e| e.enabled()).any(|e| match e { + Effect::GradientOverlay { .. } => true, + Effect::PatternOverlay { link, .. } => *link && unanchored, + Effect::Stroke(s) => matches!(s.paint, FxPaint::Gradient(_)) || pattern(&s.paint), + Effect::OuterGlow(g) | Effect::InnerGlow(g) => pattern(&g.paint), + Effect::BevelEmboss(b) => unanchored && b.texture.as_ref().is_some_and(|t| t.link), + _ => false, + }) +} + /// Pixels an effect stack can reach beyond the layer's shape. pub fn margin(layer: &Layer) -> i32 { let mut m = 0.0f32; @@ -1509,13 +1528,16 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern tent(&mut h, g.width); h } else { - let sharp = sharp_edges(shape); - let (din, dout) = (bevel_dist_inside(shape, &sharp, size), bevel_dist_outside(shape, &sharp, size)); - let mut h = Map::new(shape.w, shape.h, 0.0); + let [din, dout] = bevel_dists(shape, size); let soft = g.chisel_soft > 0.0; - for i in 0..h.v.len() { - h.v[i] = bevel_chisel_h(g.paint, size, din[i], dout[i], soft); - } + let w = shape.w; + let v = par_fill(w, shape.h, 0.0, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * w + x; + *o = bevel_chisel_h(g.paint, size, din[i], dout[i], soft); + } + }); + let mut h = Map { w, h: shape.h, v }; // Inner and outer Chisel Soft are not blurred in Photoshop (their facets equal Chisel // Hard's across a straight edge); emboss styles keep the blur until measured. if soft && g.paint == BevelPaint::Both { @@ -1536,14 +1558,23 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern let place = Placement::anchored(tex.anchor, t.link, t.phase, t.scale, 0.0); let k = t.depth / unit; let (x0, y0) = (tex.rect.x0, tex.rect.y0); - for y in 0..h.h { - for x in 0..h.w { - let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5); - let p = tile.sample(u, v); - let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3]; - h.v[y * h.w + x] += k * if t.invert { 1.0 - l } else { l }; - } - } + let w = h.w; + par_units( + h.v.len(), + &mut h.v, + w, + &mut [] as &mut [()], + 0, + || (), + |_, y, row, _| { + for (x, o) in row.iter_mut().enumerate() { + let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5); + let p = tile.sample(u, v); + let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3]; + *o += k * if t.invert { 1.0 - l } else { l }; + } + }, + ); } if b.soften >= 1.0 { tent(&mut h, b.soften); @@ -1625,23 +1656,33 @@ fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, pat }; let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) { let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0)); - for y in 0..shape.h as i64 { - for x in 0..shape.w as i64 { - let i = y as usize * shape.w + x as usize; - let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth; - let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth; - let n = [-gx, -gy, 1.0]; - let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); - let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; - let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; - let k = shade - se; - if k > 0.0 { - hi.v[i] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; - } else { - sh.v[i] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region; + // Rows on threads: every pixel reads only `hmap` and `shape`. + par_units( + hi.v.len(), + &mut hi.v, + shape.w, + &mut sh.v, + shape.w, + || (), + |_, y, hi_row, sh_row| { + let y = y as i64; + for x in 0..shape.w as i64 { + let i = y as usize * shape.w + x as usize; + let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth; + let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth; + let n = [-gx, -gy, 1.0]; + let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); + let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; + let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; + let k = shade - se; + if k > 0.0 { + hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; + } else { + sh_row[x as usize] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region; + } } - } - } + }, + ); (apply_contour(hi, &b.gloss_contour), apply_contour(sh, &b.gloss_contour)) }; let maps = match g.paint { @@ -1657,7 +1698,13 @@ fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, pat let (hi, sh) = shade_into(g.depth, 0); let (ho, so) = shade_into(if g.pillow { -g.depth } else { g.depth }, 1); let mix = |a: Map, b: Map| -> Map { - let v = a.v.iter().zip(&b.v).zip(&shape.v).map(|((x, y), s)| if *s > INSIDE_EPS { *x } else { 0.0 } + y * (1.0 - s.min(1.0))).collect(); + let v = par_fill(a.w, a.h, 0.0, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * a.w + x; + let (x, y, s) = (a.v[i], b.v[i], shape.v[i]); + *o = if s > INSIDE_EPS { x } else { 0.0 } + y * (1.0 - s.min(1.0)); + } + }); Map { w: a.w, h: a.h, v } }; vec![mix(hi, ho), mix(sh, so)] @@ -2290,6 +2337,18 @@ pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reac } } +/// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its +/// [`distance_field`], with the sharp edges they both start from found once. +pub fn bevel_distance_fields(alpha: Vec, w: usize, h: usize, reach: f32) -> [Vec; 2] { + bevel_dists(&Map { w, h, v: alpha }, reach) +} + +/// The inside and outside bevel distances of `s`, from one set of sharp edges. +fn bevel_dists(s: &Map, reach: f32) -> [Vec; 2] { + let sharp = sharp_edges(s); + [bevel_dist_inside(s, &sharp, reach), bevel_dist_outside(s, &sharp, reach)] +} + #[cfg(test)] mod tests { use super::*; @@ -2932,6 +2991,55 @@ mod tests { } } + #[test] + fn bevel_maps_do_not_depend_on_the_threads() { + // Every style and technique, softened or not, and a texture; one thread (in order) is the reference. + let mut patchy = aa_disc(101, 101, 40.0); + for (i, v) in patchy.v.iter_mut().enumerate() { + if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { + *v *= 0.6; + } + } + let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy]; + let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); + sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); + sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); + let pats = [Pattern::new("stripes", sf, 4, 4)]; + let light = GlobalLight::default(); + let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss]; + for (k, shape) in shapes.iter().enumerate() { + let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) }; + for style in styles { + for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] { + for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] { + let mut b = bevel_of(style, technique); + (b.size, b.soften) = (size, soften); + if textured { + b.texture = Some(photocraft_doc::BevelTexture { + name: "stripes".into(), + id: String::new(), + scale: 1.0, + depth: 1.0, + invert: false, + link: true, + phase: (0.0, 0.0), + }); + } + let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0; + let one = with_threads(1, run); + for threads in [2, 5, 16] { + let many = with_threads(threads, run); + assert_eq!(one.len(), many.len()); + for (j, (a, m)) in one.iter().zip(&many).enumerate() { + assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads"); + } + } + } + } + } + } + } + /// The four fields that use the distance transform, of `m`. fn distance_field_of(m: &Map, reach: f32) -> Vec> { [FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside] diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 3cf2f1dc19..7c0ce9098e 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -349,6 +349,31 @@ pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer { buf } +/// [`render_layer`] in `doc`'s context: the layer alone over `rect`, with the document's patterns, +/// Global Light, colour mode, depth and canvas (fill layers and gradients are laid out on it), as +/// the canvas composites it. Bakes (Scripts › Flatten All Layer Effects) render through this so +/// the pixels match what was on screen (#5719). Rects past [`MAX_RENDER_PIXELS`] give an empty +/// buffer. +pub fn render_layer_in(doc: &Document, layer: &Layer, rect: Rect) -> Buffer { + if rect.is_empty() { + return Buffer::transparent(rect); + } + if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { + return Buffer::transparent(Rect::EMPTY); + } + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + // A lone layer: a deep knockout reveals transparency, not the document's Background. + let cx = Ctx { doc: None, ..Ctx::for_doc(doc, &patterns) }; + let lab = doc.mode == photocraft_color::ColorMode::Lab; + let hdr = doc.depth == photocraft_color::SampleType::F32; + let cmyk = cmyk_space(doc); + photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { + let mut buf = Buffer::transparent(rect); + in_blend_space(lab, hdr, || composite_stack_at(std::slice::from_ref(layer), &mut buf, &cx, advanced::Scope::ROOT)); + buf + }) +} + /// Documents above this many pixels get thumbnails from a proxy (see [`proxy`]) when that is /// faithful; smaller ones are reduced from the exact composite. pub const PROXY_THUMBNAIL_PIXELS: u64 = 16 << 20; @@ -865,6 +890,38 @@ pub fn paint_bounds(layer: &Layer) -> Option { (!r.is_empty()).then_some(r) } +/// The frame a layer's effects are laid out in: [`paint_bounds`] for a shape, else the layer's +/// bounds ([`layer_bounds`]). A Gradient Overlay spans it, linked patterns tile from its corner. +pub fn effects_frame(layer: &Layer, canvas: Rect) -> Rect { + paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, canvas)) +} + +/// The pixels a change from `a` to `b` repaints beyond those it changed: where a layer whose +/// effects span its frame ([`effects::spans_frame`]) moved that frame, the layer's whole composite +/// before and after. Painting on a layer with a Gradient Overlay lays the one gradient out again +/// over the grown layer, as Photoshop does after each stroke; damage that covers only the stroke +/// leaves the old gradient around earlier strokes (#4053). Empty when no such frame moved. +pub fn relayout_damage(a: &Document, b: &Document) -> Rect { + let mut out = Rect::EMPTY; + let mut add = |r: Rect| { + if !r.is_empty() { + out = if out.is_empty() { r } else { out.union(&r) }; + } + }; + for (_, _, y) in b.walk() { + if !y.visible || !effects::spans_frame(y) { + continue; + } + let Some(x) = a.layer(y.id) else { continue }; + if effects_frame(x, a.bounds()) == effects_frame(y, b.bounds()) { + continue; + } + add(change_bounds(x, a.bounds()).unwrap_or_else(|| a.bounds())); + add(change_bounds(y, b.bounds()).unwrap_or_else(|| b.bounds())); + } + out +} + /// The bounding box of a shape layer's vector content: its path control bounds plus stroke width. pub fn shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option { if sh.fill.is_none() && sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.opacity <= 0.0) { @@ -1489,15 +1546,7 @@ fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buff advanced::composite_clipped(clipped, &mut content, cx); let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); let maps = effect_maps(layer, rect, cx); - effects::composite_with_effects_prepared( - layer, - &content, - backdrop, - &maps, - paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, cx.canvas)), - cx.patterns, - vstroke, - ); + effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); } /// The coverage-mixing gamma of a layer: the text blending gamma @@ -1755,7 +1804,7 @@ fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::s } fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effects::TextureCtx<'a> { - let sb = paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, cx.canvas)); + let sb = effects_frame(layer, cx.canvas); effects::TextureCtx { rect: region, patterns: cx.patterns.source(), anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))) } } @@ -1810,15 +1859,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; let maps = effect_maps(layer, rect, cx); - effects::composite_with_effects_prepared( - layer, - &content, - &mut opaque, - &maps, - paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, cx.canvas)), - cx.patterns, - vstroke, - ); + effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); if let Some(m) = &hide { let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; advanced::apply_hiding_mask(&mut opaque, &plain, m); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index ddd4871548..bd7d3ceba7 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1082,6 +1082,34 @@ fn glow_gradient_follows_the_shape() { assert!(edge[0] > 0.8 && edge[2] < 0.2, "{edge:?}"); } +// A Gradient Overlay spans the layer's frame: growing the layer repaints all of it, not just the +// new pixels (#4053). Effects that don't depend on the frame repaint only what changed. +#[test] +fn relayout_damage_covers_a_layer_whose_gradient_frame_moved() { + let overlay = Effect::GradientOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false }; + let grown = |a: &Document, rect: Rect, rgba: [f32; 4]| { + let mut b = a.clone(); + let old = b.layers.last().unwrap().clone(); + let mut l = solid_layer("sq", rect, rgba); + (l.id, l.effects) = (old.id, old.effects); + *b.layers.last_mut().unwrap() = l; + b + }; + let a = fx_doc(vec![overlay.clone()]); + let b = grown(&a, Rect::new(10, 10, 36, 34), [1.0, 0.0, 0.0, 1.0]); + let d = crate::relayout_damage(&a, &b); + assert!(d.contains_rect(&Rect::new(10, 10, 36, 34)), "{d:?}"); + // Same bounds, other pixels: the frame stays, the pixels' own damage is enough. + assert_eq!(crate::relayout_damage(&a, &grown(&a, Rect::new(10, 10, 30, 30), [0.0, 1.0, 0.0, 1.0])), Rect::EMPTY); + // A Color Overlay doesn't depend on the frame. + let c = fx_doc(vec![Effect::ColorOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), color: Color::BLACK }]); + assert_eq!(crate::relayout_damage(&c, &grown(&c, Rect::new(10, 10, 36, 34), [1.0, 0.0, 0.0, 1.0])), Rect::EMPTY); + // Nor does a disabled overlay. + let mut off = a.clone(); + off.layers.last_mut().unwrap().effects.enabled = false; + assert_eq!(crate::relayout_damage(&off, &grown(&off, Rect::new(10, 10, 36, 34), [1.0, 0.0, 0.0, 1.0])), Rect::EMPTY); +} + #[test] fn gradient_overlay_follows_angle_and_reverse() { let g = Gradient { stops: vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], angle: 0.0, ..Gradient::default() }; diff --git a/crates/doc/src/analysis.rs b/crates/doc/src/analysis.rs index 840bf54990..9b1d8efdb0 100644 --- a/crates/doc/src/analysis.rs +++ b/crates/doc/src/analysis.rs @@ -30,14 +30,12 @@ impl MeasurementScale { } /// Photoshop's "Scale" column text, e.g. `1 pixels = 1.0000 pixels`. pub fn describe(&self) -> String { - format!("{} pixels = {:.4} {}", trim(self.pixel_length), self.logical_length, self.units) + // f64 Display already drops a whole number's `.0` (`5`, `0.5`) and, unlike an i64 cast, + // prints lengths past i64::MAX in full. + format!("{} pixels = {:.4} {}", self.pixel_length, self.logical_length, self.units) } } -fn trim(v: f64) -> String { - if v.fract() == 0.0 { format!("{}", v as i64) } else { format!("{v}") } -} - /// One Count tool group: its numbered markers (document pixel coordinates, in click order). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -133,6 +131,17 @@ mod tests { assert_eq!(MeasurementScale { pixel_length: 0.0, ..Default::default() }.factor(), 1.0); } + #[test] + fn scale_text_prints_large_and_fractional_pixel_lengths() { + let big = MeasurementScale { pixel_length: 1e20, logical_length: 1.0, units: "mm".into() }; + assert_eq!(big.describe(), "100000000000000000000 pixels = 1.0000 mm"); + assert_eq!(MeasurementScale::default().describe(), "1 pixels = 1.0000 pixels"); + let s = |p: f64| MeasurementScale { pixel_length: p, ..Default::default() }.describe(); + assert_eq!(s(5.0), "5 pixels = 1.0000 pixels"); + assert_eq!(s(0.5), "0.5 pixels = 1.0000 pixels"); + assert_eq!(s(12.25), "12.25 pixels = 1.0000 pixels"); + } + #[test] fn serde_defaults_fill_missing_fields() { let m: Measurement = serde_json::from_str("{}").unwrap(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c4f7f523d1..268b0b6b43 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1,4 +1,4 @@ -//! The Photocraft document model: pure data, no rendering, no UI. +//! The PhotoCraft document model: pure data, no rendering, no UI. //! //! Layer order: inside every group (and the root), `children[0]` is the **bottom** layer, matching //! compositing order and the PSD file order. UIs display the list reversed. @@ -912,8 +912,8 @@ pub struct Document { pub variables: Variables, /// Window › Timeline (None until a video timeline is created). pub timeline: Option, - /// How the document's lossy file was encoded (its JPEG quality, WebP lossy or lossless), so - /// a save writes it back the same way rather than at fixed defaults. + /// How the document's lossy file was encoded (its JPEG quality, WebP lossy or lossless, + /// PNG stereo pairing), so a save writes it back the same way rather than at fixed defaults. pub file_encoding: FileEncoding, } @@ -932,6 +932,10 @@ pub struct FileEncoding { /// Lossy WebP quality. #[serde(skip_serializing_if = "Option::is_none")] pub webp_quality: Option, + /// PNG stereo pairing (the `sTER` chunk's mode byte, PNG Extensions 1.4.0 §3.6): `Some(0)` + /// side by side, `Some(1)` stacked, so saving a stereo PNG keeps the mark (#6063). + #[serde(skip_serializing_if = "Option::is_none")] + pub png_stereo: Option, } impl FileEncoding { diff --git a/crates/doc/src/mode.rs b/crates/doc/src/mode.rs index 96e129cbee..9722ce5b15 100644 --- a/crates/doc/src/mode.rs +++ b/crates/doc/src/mode.rs @@ -74,7 +74,7 @@ impl Duotone { let density = 1.0 - gray.clamp(0.0, 1.0); let mut out = [1.0f32; 3]; for ink in &self.inks { - let d = curve_eval(&ink.curve, density); + let d = ink.density(density); for (o, c) in out.iter_mut().zip(ink.color) { // Each ink filters light: full density transmits the ink colour. *o *= 1.0 - d * (1.0 - c); @@ -209,6 +209,22 @@ mod tests { assert!(c[0] > c[2], "{c:?}"); } + #[test] + fn duotone_render_clamps_ink_density_like_multichannel() { + // Curves above 100 % (accepted by `image.mode.duotone`) must not push the print out of + // gamut: red + blue at full density is black, not green. + let over = |name: &str, color| { + let mut ink = DuotoneInk::new(name, color); + ink.curve = vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 2.0 }]; + ink + }; + let d = Duotone { inks: vec![over("Red", [1.0, 0.0, 0.0]), over("Blue", [0.0, 0.0, 1.0])], psd_raw: None }; + assert_eq!(d.render(0.0), [0.0, 0.0, 0.0]); + for g in [0.0, 0.25, 0.5, 1.0] { + assert!(d.render(g).iter().all(|c| (0.0..=1.0).contains(c)), "{g}: {:?}", d.render(g)); + } + } + #[test] fn stack_mode_ids_roundtrip() { for m in StackMode::ALL { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 741d927a3f..fb3bc3fbec 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -43,6 +43,15 @@ roxmltree = "0.20" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tempfile = "3" +# `file_cmds::same_file` on Windows: the volume serial number and file index, so a hard link to a +# file is that file (std's `MetadataExt::file_index` is unstable). +[target.'cfg(windows)'.dependencies] +same-file = "1" + +# Printing on Unix: an IPP client for CUPS (pure Rust); the web build cannot print. +[target.'cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies] +photocraft-ipp = { workspace = true } + [dev-dependencies] photocraft-affinity = { workspace = true, features = ["synth"] } # Synthetic camera raw files for the open tests. diff --git a/crates/engine/examples/bench_crop.rs b/crates/engine/examples/bench_crop.rs new file mode 100644 index 0000000000..1d301ff19c --- /dev/null +++ b/crates/engine/examples/bench_crop.rs @@ -0,0 +1,40 @@ +//! End-to-end timing of `image.crop`, upright and turned, on a two-layer document. +//! `cargo run --release -p photocraft-engine --example bench_crop -- [image] [reps]` +//! Without an image a 3859×2594 noise photo stands in (the size of the Great Wave scan). +use std::time::{Duration, Instant}; + +use photocraft_engine::Session; +use serde_json::{Value, json}; + +fn main() { + let args: Vec = std::env::args().collect(); + let reps: usize = args.get(2).and_then(|v| v.parse().ok()).unwrap_or(3); + let mut s = Session::new(); + match args.get(1) { + Some(path) => { + let bytes = std::fs::read(path).expect("read the image"); + let doc = photocraft_io::import(path, &bytes).expect("decode the image").document; + s.add_document(doc, None); + } + None => { + s.execute("file.new", json!({"width": 3859, "height": 2594, "background": "white"})).expect("new"); + s.execute("filter.noise.addNoise", json!({"amount": 50})).expect("noise"); + } + } + s.execute("layer.duplicate", json!({})).expect("a second layer"); + let cases: [(&str, Value); 3] = [ + ("upright 512x442", json!({"x": 40, "y": 40, "width": 512, "height": 442})), + ("turned 3° 512x442", json!({"x": 40, "y": 40, "width": 512, "height": 442, "angle": 3})), + ("turned 3° 3000x2000", json!({"x": 400, "y": 300, "width": 3000, "height": 2000, "angle": 3})), + ]; + for (label, p) in cases { + let mut best = Duration::MAX; + for _ in 0..reps { + let t = Instant::now(); + s.execute("image.crop", p.clone()).expect("crop"); + best = best.min(t.elapsed()); + s.execute("edit.undo", json!({})).expect("undo"); + } + println!("{label:24} best of {reps}: {best:.2?}"); + } +} diff --git a/crates/engine/examples/bench_web_palette.rs b/crates/engine/examples/bench_web_palette.rs index 5ed1c3a3b0..4b8b87616f 100644 --- a/crates/engine/examples/bench_web_palette.rs +++ b/crates/engine/examples/bench_web_palette.rs @@ -18,13 +18,13 @@ fn main() -> Result<(), Box> { let settings = WebSettings::from_params(&json!({"format": "gif", "colors": 128, "dither": "diffusion"}), "bench")?; let rect = Rect::new(0, 0, w as i32, h as i32); let started = Instant::now(); - let original = optimize(&pixels, w, rect, &settings, None, None, 72.0, false)?; + let original = optimize(&pixels, w, rect, &settings, None, None, None, 72.0, false)?; println!("24 MP generated palette: {:.1} ms", started.elapsed().as_secs_f64() * 1000.0); let mut edited = settings; edited.color_table = Some(original.color_table); edited.color_table_edits.insert(0, [0, 255, 0]); let started = Instant::now(); - let result = optimize(&pixels, w, rect, &edited, None, None, 72.0, false)?; + let result = optimize(&pixels, w, rect, &edited, None, None, None, 72.0, false)?; println!("24 MP edited fixed palette: {:.1} ms ({} bytes)", started.elapsed().as_secs_f64() * 1000.0, result.bytes.len()); Ok(()) } diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs index c1393bb94c..7e3b05b44c 100644 --- a/crates/engine/src/adjust_cmds.rs +++ b/crates/engine/src/adjust_cmds.rs @@ -270,6 +270,8 @@ pub(crate) fn adjust_as_smart_filter(s: &mut Session, kind: &str, label: &str, p if !smart { return Ok(false); } + // A pixel or full lock refuses the smart filter, as for `filter.*` on a smart object. + crate::commands::check_pixels_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?; // The recorded params are the command's own, minus the engine's private `__kind` key. let mut params = p.clone(); if let Value::Object(m) = &mut params { @@ -296,6 +298,18 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { /// Image › Adjustments run as a smart filter (`image.adjustments.` recorded on a smart /// object): the adjustment applied to a copy of `surf`. `None` for kinds or params it can't run. pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Option { + // A Color Lookup filter re-reads its LUT `file`, a path stored in the document: followed only + // as `doc_path` allows, else the filter can't run (like a missing file). + let resolved; + let p = match p.get("file").and_then(Value::as_str).filter(|f| kind == "colorLookup" && !f.is_empty()) { + Some(file) => { + let mut q = p.clone(); + q["file"] = json!(crate::doc_path::resolve(file).ok()?.to_str()?); + resolved = q; + &resolved + } + None => p, + }; let mut out = surf.clone(); if kind == "shadowsHighlights" { let sh = shadows_highlights_params(p); @@ -335,7 +349,7 @@ fn shadows_highlights_params(p: &Value) -> ShadowsHighlights { fn replace_color(s: &mut Session, p: &Value) -> Result { const CMD: &str = "image.adjustments.replaceColor"; - let c = crate::commands::color_param(p, "color", s.tools.foreground); + let c = crate::commands::color_param(CMD, p, "color", s.tools.foreground)?; let fuzz = num(p, "fuzziness", 40.0).clamp(0.0, 200.0); let (h, sat, l) = (num(p, "hue", 0.0).clamp(-180.0, 180.0), num(p, "saturation", 0.0).clamp(-100.0, 100.0), num(p, "lightness", 0.0).clamp(-100.0, 100.0)); // Localized Color Clusters, as in Select › Color Range: the colour only matches within Range diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs index d831fbf448..1dc0c88656 100644 --- a/crates/engine/src/adjust_cmds/tests.rs +++ b/crates/engine/src/adjust_cmds/tests.rs @@ -479,6 +479,26 @@ fn adjustment_smart_filters_take_a_selection_as_their_mask() { assert_eq!(at(&now, 40, 16), at(&original, 40, 16), "outside the mask the composite is unchanged"); } +/// #5655: as for `filter.*` smart filters, a pixel or full lock refuses an adjustment smart +/// filter, leaving the layer and the history as they were. +#[test] +fn locked_smart_objects_refuse_adjustment_smart_filters() { + let adjustments = + [("image.adjustments.invert", json!({})), ("image.adjustments.shadowsHighlights", json!({"shadowAmount": 100, "blackClip": 0, "whiteClip": 0}))]; + for lock in [json!({"all": true}), json!({"pixels": true})] { + for (cmd, p) in &adjustments { + let mut s = smart_session(); + s.execute("layer.lockLayers", lock.clone()).unwrap(); + let (steps, flat) = (s.active().unwrap().history.past_len(), flatten(&s)); + let r = s.execute(cmd, p.clone()); + assert!(r.is_err(), "{cmd} added a smart filter to a smart object locked with {lock}: {r:?}"); + assert!(smart_filters_of(&s).is_empty(), "{cmd} {lock}: nothing recorded"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{cmd} {lock}: no history step"); + assert_eq!(flatten(&s), flat, "{cmd} {lock}: pixels untouched"); + } + } +} + /// A wrong-typed value errors before anything is recorded (never a panic), and the adjustments /// that can't re-render from a source (Replace Color, Match Color) stay off a smart object. #[test] diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rs index 85a6be4513..92b630aa44 100644 --- a/crates/engine/src/analysis_cmds.rs +++ b/crates/engine/src/analysis_cmds.rs @@ -722,10 +722,12 @@ fn group_index(d: &Document, p: &Value) -> Option { (i < d.measurement.count_groups.len()).then_some(i) } -fn color_of(p: &Value, key: &str) -> Option { - p.get(key)?; - let c = crate::commands::color_param(p, key, [1.0, 0.0, 0.0, 1.0]); - Some(Color::rgb(c[0], c[1], c[2])) +fn color_of(cmd: &str, p: &Value, key: &str) -> Result> { + if p.get(key).is_none() { + return Ok(None); + } + let c = crate::commands::color_param(cmd, p, key, [1.0, 0.0, 0.0, 1.0])?; + Ok(Some(Color::rgb(c[0], c[1], c[2]))) } /// Photoshop's colours for new count groups, in order. @@ -755,7 +757,12 @@ fn count_add(s: &mut Session, p: &Value) -> Result { if !at[0].is_finite() || !at[1].is_finite() { return Err(bad("count.add", "coordinates must be finite")); } - let gi = p.get("group").and_then(Value::as_u64).map(|v| v as usize); + let gi = p.get("group").and_then(Value::as_u64).map(|v| usize::try_from(v).map_err(|_| bad("count.add", "no such group"))).transpose()?; + // The first marker creates group zero, but an explicit target must never be redirected. + let group_count = doc(s)?.measurement.count_groups.len().max(1); + if gi.is_some_and(|i| i >= group_count) { + return Err(bad("count.add", "no such group")); + } let n = s.edit("Count", |d, _| { if d.measurement.count_groups.is_empty() { let g = new_group(d, None, None); @@ -840,7 +847,7 @@ fn count_clear(s: &mut Session, p: &Value) -> Result { fn count_new_group(s: &mut Session, p: &Value) -> Result { let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let color = color_of(p, "color"); + let color = color_of("count.newGroup", p, "color")?; s.edit("New Count Group", |d, _| { let g = new_group(d, name, color); d.measurement.count_groups.push(g); @@ -856,7 +863,9 @@ fn count_delete_group(s: &mut Session, p: &Value) -> Result { s.edit("Delete Count Group", |d, _| { d.measurement.count_groups.remove(g); let n = d.measurement.count_groups.len(); - d.measurement.active_count_group = d.measurement.active_count_group.min(n.saturating_sub(1)); + // Removing a group before the active one shifts it down a slot. + let a = d.measurement.active_count_group; + d.measurement.active_count_group = (if g < a { a - 1 } else { a }).min(n.saturating_sub(1)); Ok(()) })?; Ok(count_json(doc(s)?.as_ref())) @@ -887,7 +896,7 @@ fn count_set_group(s: &mut Session, p: &Value) -> Result { if let Some(n) = p.get("name").and_then(Value::as_str) { grp.name = n.to_string(); } - if let Some(c) = color_of(p, "color") { + if let Some(c) = color_of(CMD, p, "color")? { grp.color = c; } if let Some(v) = whole_size(CMD, p, "markerSize", 1, 10)? { @@ -1121,8 +1130,12 @@ fn place_scale_marker(s: &mut Session, p: &Value) -> Result { }; // Bottom-left with a margin; the text sits under (or over) the bar. let margin = (w.min(h) * 0.03).round().max(2.0); - let bar_h = (font_size / 4.0).round().clamp(2.0, h / 4.0); - let text_h = if show_text { font_size * 1.25 } else { 0.0 }; + // `fontSize` is in points; `type.create` renders it at resolution/72 px per point, so lay out + // the bar and label in those pixels (at 300 ppi, 12 pt is 50 px) (#5754). + let dpi = f64::from(d.resolution_dpi); + let font_px = font_size * if dpi.is_finite() && dpi > 0.0 { dpi / 72.0 } else { 1.0 }; + let bar_h = (font_px / 4.0).round().clamp(2.0, h / 4.0); + let text_h = if show_text { font_px * 1.25 } else { 0.0 }; // Keep the bar on the canvas when the text under it doesn't fit; the label is clipped instead (#932). let bar_y = if text_top { h - margin - bar_h } else { h - margin - bar_h - text_h }.max(0.0); // Likewise pull a bar nearly as wide as the image in from the right edge (#932). @@ -1143,7 +1156,7 @@ fn place_scale_marker(s: &mut Session, p: &Value) -> Result { })?; let mut text_layer = Value::Null; if show_text { - let baseline = if text_top { f64::from(bar.y0) - font_size * 0.3 } else { f64::from(bar.y1) + font_size }; + let baseline = if text_top { f64::from(bar.y0) - font_px * 0.3 } else { f64::from(bar.y1) + font_px }; let mut tp = json!({"x": bar.x0, "y": baseline, "text": label, "size": font_size, "color": [rgb[0], rgb[1], rgb[2], 1.0], "name": label}); if let Some(f) = &font { tp["font"] = json!(f); diff --git a/crates/engine/src/analysis_cmds/tests.rs b/crates/engine/src/analysis_cmds/tests.rs index 124f9abf1e..f9138e8b65 100644 --- a/crates/engine/src/analysis_cmds/tests.rs +++ b/crates/engine/src/analysis_cmds/tests.rs @@ -1,5 +1,5 @@ use super::*; -use photocraft_doc::ColorMode; +use photocraft_doc::{ColorMode, LayerContent, LayerId}; fn session(w: u32, h: u32, depth: u32) -> Session { let mut s = Session::new(); @@ -291,6 +291,27 @@ fn count_groups_markers_and_undo() { assert!(s.execute("count.add", json!({"x": 1})).is_err()); } +#[test] +fn deleting_an_earlier_count_group_keeps_the_active_group() { + let mut s = session(100, 100, 8); + s.execute("count.add", json!({"x": 10, "y": 10})).unwrap(); + for _ in 0..3 { + s.execute("count.newGroup", json!({})).unwrap(); + } + s.execute("count.setGroup", json!({"group": 2})).unwrap(); + let r = s.execute("count.deleteGroup", json!({"group": 0})).unwrap(); + assert_eq!(r["activeGroup"], 1); + assert_eq!(r["groups"][1]["name"], "Count Group 3"); + // A later group leaves the active index alone. + let r = s.execute("count.deleteGroup", json!({"group": 2})).unwrap(); + assert_eq!(r["activeGroup"], 1); + assert_eq!(r["groups"][1]["name"], "Count Group 3"); + // Deleting the active last group selects the new last group. + let r = s.execute("count.deleteGroup", json!({})).unwrap(); + assert_eq!(r["activeGroup"], 0); + assert_eq!(r["groups"][0]["name"], "Count Group 2"); +} + #[test] fn log_delete_and_csv_export() { let mut s = session(10, 10, 8); @@ -355,6 +376,27 @@ fn place_scale_marker_builds_one_group_in_one_step() { assert!(d(&s).layers.iter().all(|l| l.name != "Measurement Scale Marker")); } +#[test] +fn place_scale_marker_lays_out_its_label_in_points_at_high_resolution() { + // `fontSize` is in points and `type.create` renders it at resolution/72 px per point, but the + // layout treated it as pixels: at 300 ppi a 12 pt label (50 px) overlapped the bar. + for res in [72.0, 300.0] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1200, "height": 900, "resolution": res, "background": "white"})).unwrap(); + let r = s.execute("image.analysis.placeScaleMarker", json!({"fontSize": 12, "textPosition": "bottom"})).unwrap(); + let bar_bottom = r["barRect"][3].as_f64().unwrap(); + let doc = d(&s); + let Some(LayerContent::Text(t)) = doc.layer(LayerId(r["text"].as_u64().unwrap())).map(|l| &l.content) else { panic!("a type layer: {r}") }; + assert_eq!(t.size_pt, 12.0, "{res} ppi: type.create still gets points"); + let layout = photocraft_text::shared().lock().unwrap().layout(t, doc.resolution_dpi); + let b = layout.bounds().expect("the label has a line"); + let ty = t.transform.m[5]; + let (top, bottom) = (f64::from(b[1]) + ty, f64::from(b[3]) + ty); + assert!(top >= bar_bottom - 0.5, "{res} ppi: label top {top} overlaps the bar ending at {bar_bottom}: {r}"); + assert!(bottom <= 900.5, "{res} ppi: label bottom {bottom} stays on the canvas: {r}"); + } +} + #[test] fn place_scale_marker_on_a_short_document_errors_without_panicking() { // A document under 8 px tall inverted the bar-height clamp and panicked (#932). Call `run` @@ -449,3 +491,47 @@ fn count_set_group_rejects_sizes_that_are_not_whole_numbers() { assert_eq!((g.marker_size, g.label_size), (3, 12), "a rejected call changes nothing"); assert_eq!(s.active().unwrap().history.past_len(), past); } + +#[test] +fn count_add_rejects_unknown_groups_without_changing_the_document() { + for groups in [0, 1, 3] { + for group in [(groups as u64).max(1), u64::MAX] { + let mut s = session(10, 10, 8); + for _ in 0..groups { + s.execute("count.newGroup", json!({})).unwrap(); + } + let before = d(&s); + let history = s.active().unwrap().history.past_len(); + let journal = s.journal.len(); + let error = s.execute("count.add", json!({"x": 2, "y": 3, "group": group})).unwrap_err(); + assert!(error.to_string().contains("no such group"), "{error}"); + assert!(Arc::ptr_eq(&before, &d(&s)), "an invalid target must not create a group or add a marker"); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.journal.len(), journal); + } + } +} + +#[test] +fn count_add_keeps_first_group_creation_and_targets_the_requested_group() { + let mut s = session(10, 10, 8); + // Group zero can be requested before the first marker creates it. + let r = s.execute("count.add", json!({"x": 2, "y": 3, "group": 0})).unwrap(); + assert_eq!(r["groups"][0]["points"], json!([[2.0, 3.0]])); + s.execute("count.newGroup", json!({})).unwrap(); + let before = d(&s).measurement.clone(); + let history = s.active().unwrap().history.past_len(); + let r = s.execute("count.add", json!({"x": 4, "y": 5, "group": 0})).unwrap(); + assert_eq!(r["activeGroup"], 1); + assert_eq!(r["groups"][0]["points"], json!([[2.0, 3.0], [4.0, 5.0]])); + assert_eq!(r["groups"][1]["count"], 0); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + let after = d(&s).measurement.clone(); + assert!(s.undo()); + assert_eq!(d(&s).measurement, before); + assert!(s.redo()); + assert_eq!(d(&s).measurement, after); + // Omitting the group still uses the active group. + let r = s.execute("count.add", json!({"x": 6, "y": 7})).unwrap(); + assert_eq!(r["groups"][1]["points"], json!([[6.0, 7.0]])); +} diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/artboard_cmds.rs index 5cebe86aa9..4bc4a829b2 100644 --- a/crates/engine/src/artboard_cmds.rs +++ b/crates/engine/src/artboard_cmds.rs @@ -9,7 +9,7 @@ use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Artboard, ArtboardBackground, Document, Layer, LayerContent, LayerId, Size}; -use photocraft_geom::Rect; +use photocraft_geom::{Affine, Rect}; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -92,10 +92,12 @@ fn preset_size(name: &str) -> Option<(u32, u32)> { } fn background_param(p: &Value, cmd: &str) -> Result> { - let custom = p.get("color").map(|_| { - let c = color_param(p, "color", [1.0; 4]); - ArtboardBackground::Custom(Color::rgba(c[0], c[1], c[2], c[3])) - }); + let custom = if p.get("color").is_some() { + let c = color_param(cmd, p, "color", [1.0; 4])?; + Some(ArtboardBackground::Custom(Color::rgba(c[0], c[1], c[2], c[3]))) + } else { + None + }; Ok(match p.get("background").and_then(Value::as_str) { None => custom, Some("white") => Some(ArtboardBackground::White), @@ -504,6 +506,9 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result one.layer_comps.clear(); one.last_applied_comp = None; one.last_document_state = None; + // Paths, notes, slices and Count/Ruler marks move with the board. This also shifts + // `one.guides`, but they are rebuilt below from the source's, so nothing moves twice. + crate::canvas_geom::transform_doc_marks(&mut one, &Affine::translate(f64::from(dx), f64::from(dy))); let shift = |v: &[f64], o: i32, len: u32| v.iter().map(|g| g - f64::from(o)).filter(|g| *g > 0.0 && *g < f64::from(len)).collect::>(); one.guides.vertical = shift(&doc.guides.vertical, r.x0, r.width()); one.guides.horizontal = shift(&doc.guides.horizontal, r.y0, r.height()); @@ -528,7 +533,7 @@ fn chosen_artboards(doc: &Document, p: &Value) -> Vec { } } -/// File › Export › Artboards to Files: `_.` per board. +/// File › Export › Artboards to Files: `__.` per board. fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let cmd = "file.export.artboardsToFiles"; let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string(); @@ -538,8 +543,9 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); let mut files = Vec::new(); - for one in chosen_documents(&doc, p)? { - let name = if prefix.is_empty() { sanitize(&one.name) } else { format!("{}_{}", sanitize(&prefix), sanitize(&one.name)) }; + for (i, one) in chosen_documents(&doc, p)?.into_iter().enumerate() { + // Names may be identical, or collide after sanitizing or filesystem case folding. + let name = if prefix.is_empty() { format!("{i:04}_{}", sanitize(&one.name)) } else { format!("{}_{i:04}_{}", sanitize(&prefix), sanitize(&one.name)) }; let path = join(&dir, &format!("{name}.{format}")); save_doc(&one, &path, save)?; files.push(path); diff --git a/crates/engine/src/artboard_cmds/tests.rs b/crates/engine/src/artboard_cmds/tests.rs index 1faf4cb75d..f3053e21fd 100644 --- a/crates/engine/src/artboard_cmds/tests.rs +++ b/crates/engine/src/artboard_cmds/tests.rs @@ -146,8 +146,8 @@ fn export_to_files_and_pdf() { let r = s.execute("file.export.artboardsToFiles", json!({"dir": d, "prefix": "site"})).unwrap(); let files: Vec = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); assert_eq!(files.len(), 2); - assert!(files[0].ends_with("site_Empty_One.png"), "{files:?}"); - assert!(files[1].ends_with("site_Red Board.png"), "{files:?}"); + assert!(files[0].ends_with("site_0000_Empty_One.png"), "{files:?}"); + assert!(files[1].ends_with("site_0001_Red Board.png"), "{files:?}"); let img = photocraft_io::import("x.png", &std::fs::read(&files[1]).unwrap()).unwrap().document; assert_eq!((img.size.width, img.size.height), (10, 10)); let img2 = photocraft_io::import("x.png", &std::fs::read(&files[0]).unwrap()).unwrap().document; @@ -331,6 +331,33 @@ fn export_rejects_a_board_too_far_from_the_origin() { assert_eq!(one.artboards()[0].2.rect, Rect::new(0, 0, 50, 50)); } +/// Artboards to Files moves paths, notes, slices and Count/Ruler marks with the board, like its +/// layers and guides, so they land on the same pixels in the exported file. +#[test] +fn artboard_export_moves_paths_notes_slices_and_marks_with_the_board() { + use photocraft_doc::{CountGroup, NamedPath, Note, Path, Slice, Subpath}; + let mut s = session(8); + s.execute("layer.new.artboard", json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap(); + s.edit("marks", |d, _| { + d.paths.push(NamedPath { name: "P".into(), path: Path::new(vec![Subpath::polygon(&[(210.0, 110.0), (240.0, 110.0), (240.0, 140.0)])]), psd_raw: None }); + d.work_path = Some(Path::new(vec![Subpath::polygon(&[(205.0, 105.0), (215.0, 105.0), (215.0, 115.0)])])); + d.notes.push(Note { position: [220.0, 120.0], popup: [220.0, 120.0, 260.0, 160.0], ..Default::default() }); + d.slices.list.push(Slice { id: 1, rect: Rect::new(210, 110, 230, 130), ..Default::default() }); + d.measurement.count_groups.push(CountGroup { points: vec![[225.0, 125.0]], ..Default::default() }); + Ok(()) + }) + .unwrap(); + let one = artboard_document(doc(&s), doc(&s).artboards()[0].0).unwrap().unwrap(); + let k = &one.paths[0].path.subpaths[0].knots[0].anchor; + assert_eq!((k.x, k.y), (10.0, 10.0)); + let w = &one.work_path.as_ref().unwrap().subpaths[0].knots[0].anchor; + assert_eq!((w.x, w.y), (5.0, 5.0)); + assert_eq!(one.notes[0].position, [20.0, 20.0]); + assert_eq!(one.notes[0].popup, [20.0, 20.0, 60.0, 60.0]); + assert_eq!(one.slices.list[0].rect, Rect::new(10, 10, 30, 30)); + assert_eq!(one.measurement.count_groups[0].points, vec![[25.0, 25.0]]); +} + /// #1531: a board 40×40 at (10, 10) holding a red square at (10..30)², the artboard active. fn board_with_square(s: &mut Session) -> LayerId { add_square(s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]); diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index ebeda48687..9e8eb6cb7c 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -881,11 +881,18 @@ macro_rules! ev { Some(m) => step($id, Value::Object(m)), None => Mapped::Unsupported { harmless: false }, }, - to: |_, p| fields_to(p, $fields, desc("null")), + to: |_, p| if pixel_target(p) { fields_to(p, $fields, desc("null")) } else { None }, } }; } +/// Whether `p` edits the layer's pixels: no `"target"` or `"target":"pixels"`. Photoshop's +/// descriptor for a plain event has no field for a mask, Quick Mask or channel target, so such +/// a step can't be exported faithfully. +fn pixel_target(p: &Value) -> bool { + p.get("target").is_none_or(|t| t.as_str() == Some("pixels")) +} + const INTERPOLATION: &[(&str, &str)] = &[ ("Bcbc", "bicubic"), ("Blnr", "bilinear"), @@ -915,7 +922,10 @@ const STROKE_LOCATION: &[(&str, &str)] = &[("Insd", "inside"), ("Cntr", "center" const INTENT: &[(&str, &str)] = &[("Img ", "perceptual"), ("Clrm", "relative"), ("Grp ", "saturation"), ("AbsC", "absolute")]; const PROFILES: &[(&str, &str)] = &[("sRGB IEC61966-2.1", "srgb"), ("Display P3", "display-p3"), ("Adobe RGB (1998)", "adobe-rgb-compat"), ("ProPhoto RGB", "prophoto-compat")]; -const SMART_BLUR_QUALITY: &[(&str, &str)] = &[("Hgh ", "high"), ("Mdm ", "medium"), ("Low ", "low")]; +/// Smart Blur quality. Photoshop's codes come first, so they are what an export writes (measured in +/// Photoshop: `Hgh `/`Mdm `/`Low ` play back as its fallback, low quality). The old codes after +/// them still read, for actions PhotoCraft wrote before. +const SMART_BLUR_QUALITY: &[(&str, &str)] = &[("SBQL", "low"), ("SBQM", "medium"), ("SBQH", "high"), ("Hgh ", "high"), ("Mdm ", "medium"), ("Low ", "low")]; const SMART_BLUR_MODE: &[(&str, &str)] = &[("SBMN", "normal"), ("SBME", "edgeOnly"), ("SBMO", "overlayEdge")]; const RADIAL_METHOD: &[(&str, &str)] = &[("Spn ", "spin"), ("Zm ", "zoom")]; const RADIAL_QUALITY: &[(&str, &str)] = &[("Drft", "draft"), ("Gd ", "good"), ("Bst ", "best")]; @@ -1577,7 +1587,12 @@ fn close_from(d: &Descriptor) -> Mapped { if get_enum(d, "Svng").as_deref() == Some("Ys") { steps(vec![("file.save", json!({})), ("file.close", json!({}))]) } else { none("file.close") } } -fn close_to(_: &str, _: &Value) -> Option { +/// A Close of an explicit document has no mapping here: written as a plain Close it would +/// close the active document on playback, so it is left to `skipUnsupported`. +fn close_to(_: &str, p: &Value) -> Option { + if p.get("document").is_some_and(|d| !d.is_null()) { + return None; + } Some(desc("null").with("Svng", enm("YsN ", "N "))) } @@ -1608,14 +1623,17 @@ fn transform_from(d: &Descriptor) -> Mapped { if d.get("Skew").is_some() || d.get("Usng").is_some() { return unsupported; } - let geometry_only = p.keys().all(|k| k == "dx" || k == "dy"); + // A whole-pixel move is a plain `layer.translate`; a fractional one needs `edit.transform` + // to keep its sub-pixel placement and interpolation. + let whole_pixels = ["dx", "dy"].iter().all(|k| p.get(*k).and_then(Value::as_f64).is_none_or(|v| v.fract() == 0.0)); + let geometry_only = p.keys().all(|k| k == "dx" || k == "dy") && whole_pixels; match (ref_class(r).as_deref(), target(r)) { (Some("Chnl"), Target::Property(prop)) if prop == "fsel" => step("select.transformSelection", Value::Object(p)), (Some("Lyr"), _) => { let Some(mut lp) = layer_target(r) else { return unsupported }; if geometry_only { - lp.insert("dx".into(), p.get("dx").and_then(Value::as_f64).unwrap_or(0.0).round().into()); - lp.insert("dy".into(), p.get("dy").and_then(Value::as_f64).unwrap_or(0.0).round().into()); + lp.insert("dx".into(), p.get("dx").and_then(Value::as_f64).unwrap_or(0.0).into()); + lp.insert("dy".into(), p.get("dy").and_then(Value::as_f64).unwrap_or(0.0).into()); return step("layer.translate", Value::Object(lp)); } lp.extend(p); @@ -1966,6 +1984,10 @@ fn play_from(d: &Descriptor) -> Mapped { fn play_to(_: &str, p: &Value) -> Option { let name = jstr(p, "action")?; + // The Play Action descriptor written here carries no starting step, so a call from a later step is not a whole call. + if p.get("from").is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0)) { + return None; + } let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(name) }]; if let Some(set) = jstr(p, "set") { items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); @@ -1986,6 +2008,10 @@ fn fill_from(d: &Descriptor) -> Mapped { match get_enum(d, "Usng").as_deref() { Some("FrgC") | None => {} Some("Pttn") => p["contents"] = json!("pattern"), + Some("Clr") => match get_obj(d, "Clr ").and_then(color_hex) { + Some(c) => p["color"] = json!(c), + None => return Mapped::Unsupported { harmless: false }, + }, Some(_) => return Mapped::Unsupported { harmless: false }, } if let Some(t) = get_num(d, "Tlrn") { @@ -2032,7 +2058,16 @@ fn fill_to(id: &str, p: &Value) -> Option { if id == "paint.bucket" { let mut d = desc("null").with("From", D::Descriptor(desc("Pnt ").with("Hrzn", px(jnum(p, "x")?)).with("Vrtc", px(jnum(p, "y")?)))); d = d.with("Tlrn", long(jnum(p, "tolerance").unwrap_or(32.0))).with("AntA", D::Boolean(jbool(p, "antiAlias").unwrap_or(true))); - d = d.with("Usng", enm("FlCn", if jstr(p, "contents") == Some("pattern") { "Pttn" } else { "FrgC" })); + // `source` is the command's older name for `contents`. + d = if p.get("contents").or_else(|| p.get("source")).and_then(Value::as_str) == Some("pattern") { + d.with("Usng", enm("FlCn", "Pttn")) + } else { + // An explicit colour overrides the foreground (#7199): it travels as Fill's `Clr `. + match bucket_color(p.get("color"))? { + Some(c) => d.with("Usng", enm("FlCn", "Clr ")).with("Clr ", D::Descriptor(c)), + None => d.with("Usng", enm("FlCn", "FrgC")), + } + }; if let Some(o) = jnum(p, "opacity") { d = d.with("Opct", pct(o)); } @@ -2054,6 +2089,29 @@ fn fill_to(id: &str, p: &Value) -> Option { Some(d) } +/// The Paint Bucket's `color` as `paint.bucket` reads it (`[r, g, b(, a)]` in 0..=1 or +/// `#rrggbb(aa)`): `Some(None)` when it fills with the foreground (no colour, or a string the +/// command doesn't read), `None` when the colour can't be written (not opaque, or outside 0..=1). +fn bucket_color(v: Option<&Value>) -> Option> { + let rgba = match v { + Some(Value::Array(a)) if a.len() >= 3 => { + let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); + [*c.first()?, *c.get(1)?, *c.get(2)?, c.get(3).copied().unwrap_or(1.0)] + } + Some(Value::String(h)) => { + let h = h.trim_start_matches('#'); + let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f64::from(v) / 255.0); + let (Some(r), Some(g), Some(b)) = (c(0), c(2), c(4)) else { return Some(None) }; + [r, g, b, c(6).unwrap_or(1.0)] + } + _ => return Some(None), + }; + if rgba[3] != 1.0 || !rgba.iter().all(|v| (0.0..=1.0).contains(v)) { + return None; + } + Some(Some(desc("RGBC").with("Rd ", D::Double(rgba[0] * 255.0)).with("Grn ", D::Double(rgba[1] * 255.0)).with("Bl ", D::Double(rgba[2] * 255.0)))) +} + const STROKE: &[F] = &[ F("Wdth", "width", Kind::Long), F("Lctn", "location", Kind::Enum("StrL", STROKE_LOCATION)), @@ -2081,7 +2139,11 @@ fn rotate_from(d: &Descriptor) -> Mapped { } else if targets_layer(d) { return Mapped::Unsupported { harmless: false }; } else { - return step("image.rotation.arbitrary", json!({"angle": angle.abs(), "direction": if angle < 0.0 { "ccw" } else { "cw" }})); + let mut p = json!({"angle": angle.abs(), "direction": if angle < 0.0 { "ccw" } else { "cw" }}); + if let Some(i) = get_enum(d, "Intr").and_then(|i| lookup(INTERPOLATION, &i)).filter(|i| matches!(*i, "bicubic" | "bilinear" | "nearest")) { + p["interpolation"] = i.into(); + } + return step("image.rotation.arbitrary", p); }; none(if targets_layer(d) { layer } else { doc }) } @@ -2101,7 +2163,20 @@ fn rotate_to(id: &str, p: &Value) -> Option { if layer { d = d.with("null", target_ref("Lyr ")); } - Some(d.with("Angl", ang(angle))) + d = d.with("Angl", ang(angle)); + if id == "image.rotation.arbitrary" + && let Some(i) = p.get("interpolation") + { + // The command resamples with nearest, bilinear or bicubic; any other value can't be + // carried faithfully, so refuse rather than replay with a different interpolation. + let i = match i.as_str()? { + "nearestNeighbor" => "nearest", + i @ ("bicubic" | "bilinear" | "nearest") => i, + _ => return None, + }; + d = d.with("Intr", enm("Intp", lookup_back(INTERPOLATION, i)?)); + } + Some(d) } fn flip_from(d: &Descriptor) -> Mapped { @@ -2321,6 +2396,52 @@ fn image_size_from(d: &Descriptor) -> Mapped { step("image.imageSize", Value::Object(p)) } +/// Shadows/Highlights (`adaptCorrect`, #5830): the shadow and highlight tones are `shadowMode` +/// and `highlightMode` objects (amount and width in %, radius in px), then the black and white +/// clips (%), midtone contrast (`center`) and colour correction. Each key is read as its char ID +/// or its string ID, whichever the file used; absent keys keep the command's defaults. +const SHADOWS_HIGHLIGHTS_TONES: [(&str, &str, &str); 2] = [("sdwM", "shadowMode", "shadow"), ("hglM", "highlightMode", "highlight")]; +const SHADOWS_HIGHLIGHTS_TONE: [(&str, &str, &str); 3] = [("Amnt", "amount", "Amount"), ("Wdth", "width", "Tone"), ("Rds ", "radius", "Radius")]; +const SHADOWS_HIGHLIGHTS: [(&str, &str, &str); 4] = + [("BlcC", "blackClip", "blackClip"), ("WhtC", "whiteClip", "whiteClip"), ("Cntr", "center", "midtone"), ("ClrC", "colorCorrection", "color")]; + +fn shadows_highlights_from(d: &Descriptor) -> Mapped { + let mut m = Map::new(); + for (code, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { + let Some(t) = get_obj(d, code).or_else(|| get_obj(d, name)) else { continue }; + for (code, name, suffix) in SHADOWS_HIGHLIGHTS_TONE { + if let Some(v) = get_num(t, code).or_else(|| get_num(t, name)) { + m.insert(format!("{prefix}{suffix}"), Value::from(v)); + } + } + } + for (code, name, param) in SHADOWS_HIGHLIGHTS { + if let Some(v) = get_num(d, code).or_else(|| get_num(d, name)) { + m.insert(param.into(), Value::from(v)); + } + } + step("image.adjustments.shadowsHighlights", Value::Object(m)) +} + +fn shadows_highlights_to(_: &str, p: &Value) -> Option { + let mut d = desc("null"); + for (_, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { + let mut t = desc("adaptCorrectTones"); + for (_, key, suffix) in SHADOWS_HIGHLIGHTS_TONE { + if let Some(v) = jnum(p, &format!("{prefix}{suffix}")) { + t = t.with(key, if suffix == "Radius" { long(v) } else { pct(v) }); + } + } + d = d.with(name, D::Descriptor(t)); + } + for (_, key, param) in SHADOWS_HIGHLIGHTS { + if let Some(v) = jnum(p, param) { + d = d.with(key, if matches!(param, "midtone" | "color") { long(v) } else { D::Double(v) }); + } + } + Some(d) +} + fn image_size_to(_: &str, p: &Value) -> Option { let mut d = desc("null"); if let Some(pc) = jnum(p, "percent") { @@ -2570,8 +2691,8 @@ const EVENTS: &[Event] = &[ ev!("DstS", "dustAndScratches", "Dust & Scratches", "filter.noise.dustAndScratches", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), ev!("Dspc", "despeckle", "Despeckle", "filter.noise.despeckle", &[]), ev!("MtnB", "motionBlur", "Motion Blur", "filter.blur.motionBlur", &[F("Angl", "angle", Kind::Ang), F("Dstn", "distance", Kind::Px)]), - ev!("BoxB", "boxblur", "Box Blur", "filter.blur.boxBlur", &[F("Rds ", "radius", Kind::Px)]), - ev!("SrfB", "surfaceBlur", "Surface Blur", "filter.blur.surfaceBlur", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), + ev!("", "boxblur", "Box Blur", "filter.blur.boxBlur", &[F("Rds ", "radius", Kind::Px)]), + ev!("", "surfaceBlur", "Surface Blur", "filter.blur.surfaceBlur", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), ev!( "SmrB", "smartBlur", @@ -2610,6 +2731,14 @@ const EVENTS: &[Event] = &[ ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::Long)]), Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to }, // Adjustments (Image › Adjustments). + Event { + code: "", + name: "adaptCorrect", + label: "Shadows/Highlights", + ids: &["image.adjustments.shadowsHighlights"], + from: shadows_highlights_from, + to: shadows_highlights_to, + }, Event { code: "Lvls", name: "levels", @@ -2639,7 +2768,7 @@ const EVENTS: &[Event] = &[ adjustment_event!("Exps", "Exps", "exposure", "Exposure"), adjustment_event!("PhtF", "PhtF", "photoFilter", "Photo Filter"), Event { - code: "BlnW", + code: "", name: "blackAndWhite", label: "Black & White", ids: &["image.adjustments.blackWhite"], @@ -2831,7 +2960,7 @@ const EVENTS: &[Event] = &[ from: move_from, to: move_to, }, - ev!("Fltn", "flattenImage", "Flatten Image", "layer.flattenImage", &[]), + ev!("FltI", "flattenImage", "Flatten Image", "layer.flattenImage", &[]), Event { code: "MrgV", name: "mergeVisible", @@ -2917,9 +3046,20 @@ const EVENTS: &[Event] = &[ Event { code: "Stop", name: "stop", label: "Stop", ids: &[STOP_MESSAGE], from: stop_from, to: stop_to }, ]; +/// Four-char codes PhotoCraft once exported for events Photoshop only runs by name (or by +/// another code), with the name they stand for. Measured in Photoshop: `executeAction` with +/// these codes fails ("the command is not currently available"), and `Fltn` is the +/// `flatness` property, not the flatten event. Import keeps accepting them so actions saved +/// before still load; export never writes them. +const LEGACY_CODES: &[(&str, &str)] = &[("BoxB", "boxblur"), ("SrfB", "surfaceBlur"), ("Fltn", "flattenImage"), ("BlnW", "blackAndWhite")]; + fn event_for(item: &AtnEvent) -> Option<&'static Event> { let id = item.id(); - EVENTS.iter().find(|e| (!e.code.is_empty() && e.code.trim_end() == id.trim_end()) || e.name == id) + let find = |id: &str| EVENTS.iter().find(|e| (!e.code.is_empty() && e.code.trim_end() == id.trim_end()) || e.name == id); + find(&id).or_else(|| match item { + AtnEvent::Code(_) => LEGACY_CODES.iter().find(|(code, _)| *code == id).and_then(|(_, name)| find(name)), + AtnEvent::Name(_) => None, + }) } /// The event `id` exports as: the first event listing it whose converter accepts the params @@ -3015,8 +3155,8 @@ pub fn import(bytes: &[u8]) -> std::result::Result { let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), ..Default::default() }; for a in &file.actions { let action = convert_action(a, &set, &mut out.unsupported); - if a.function_key > 0 && !a.shift && !a.command { - out.function_keys.push((action.name.clone(), format!("F{}", a.function_key))); + if a.function_key > 0 { + out.function_keys.push((action.name.clone(), function_key_name(a.function_key, a.shift, a.command))); } out.actions.push(action); } @@ -3055,8 +3195,32 @@ fn export_item(id: &str, params: &Value, set: &str) -> Option { Some(AtnItem { event, dictionary: e.label.to_string(), descriptor: Some(descriptor), ..Default::default() }) } +/// An action's key as a shortcut string: `F5`, with Photoshop's Shift and Command options +/// `Shift+F5`, `Cmd+F5` or `Cmd+Shift+F5` (#7646). +pub fn function_key_name(key: u16, shift: bool, command: bool) -> String { + format!("{}{}F{key}", if command { "Cmd+" } else { "" }, if shift { "Shift+" } else { "" }) +} + +/// The `.atn` function key (1…15), Shift and Command of a shortcut string, or `None` for +/// anything else. +pub fn parse_function_key(key: &str) -> Option<(u16, bool, bool)> { + let (mut shift, mut command) = (false, false); + let mut rest = key; + loop { + if let Some(r) = rest.strip_prefix("Cmd+").filter(|_| !command) { + (command, rest) = (true, r); + } else if let Some(r) = rest.strip_prefix("Shift+").filter(|_| !shift) { + (shift, rest) = (true, r); + } else { + break; + } + } + let n = rest.strip_prefix('F')?.parse::().ok().filter(|n| (1..=15).contains(n))?; + Some((n, shift, command)) +} + /// The `.atn` bytes of `actions` as the set `set`. `function_keys` gives each action's key -/// (`F1`…`F15`). Steps with no Photoshop equivalent are an error unless `skip_unsupported`. +/// (`F1`…`F15`, with `Shift+` and `Cmd+` as [`function_key_name`] writes them). Steps with no Photoshop equivalent are an error unless `skip_unsupported`. pub fn export( set: &str, actions: &[&Action], @@ -3067,11 +3231,8 @@ pub fn export( let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new() }; for a in actions { let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() }; - if let Some((_, key)) = function_keys.iter().find(|(n, _)| n == &a.name) - && let Some(n) = key.strip_prefix('F').and_then(|n| n.parse::().ok()) - && (1..=15).contains(&n) - { - out.function_key = n; + if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) { + (out.function_key, out.shift, out.command) = (n, shift, command); } for (i, (id, params)) in a.steps.iter().enumerate() { let Some(mut item) = export_item(id, params, set) else { @@ -3129,31 +3290,39 @@ fn load(s: &mut Session, p: &Value) -> Result { } let mut taken: Vec = s.actions.list.iter().map(|a| a.name.clone()).collect(); let mut names = Vec::with_capacity(imp.actions.len()); - let mut renamed = Vec::new(); + // The file's name of each action that had to be renamed, and its new name. + let mut renamed: std::collections::HashMap = std::collections::HashMap::new(); let mut steps = 0usize; + let mut added = Vec::with_capacity(imp.actions.len()); for mut a in imp.actions { let name = unique(&a.name, &taken); if name != a.name { - renamed.push((a.name.clone(), name.clone())); + renamed.entry(a.name.clone()).or_insert_with(|| name.clone()); } a.name = name.clone(); taken.push(name.clone()); steps = steps.saturating_add(a.steps.len()); names.push(name); - s.actions.list.push(a); + added.push(a); } - // A Play step calls its action by name: follow renames within the set. - for (from, to) in &renamed { - for a in s.actions.list.iter_mut().filter(|a| a.set.as_deref() == Some(imp.set.as_str())) { - for (id, params) in &mut a.steps { - if id == "actions.play" && params.get("action").and_then(Value::as_str) == Some(from) { - params["action"] = json!(to); + // Play and Conditional steps call actions by name: follow the renames in the actions just + // loaded, each target looked up once by the name the file gave it. + for a in &mut added { + for (id, params) in &mut a.steps { + let keys: &[&str] = match id.as_str() { + "actions.play" => &["action"], + "actions.conditional" => &["then", "else"], + _ => &[], + }; + for key in keys { + if let Some(to) = params.get(*key).and_then(Value::as_str).and_then(|n| renamed.get(n)) { + params[*key] = json!(to); } } } } - let keys: Vec<(String, String)> = - imp.function_keys.into_iter().map(|(n, k)| (renamed.iter().find(|(f, _)| f == &n).map_or(n, |(_, t)| t.clone()), k)).collect(); + s.actions.list.extend(added); + let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect(); if !keys.is_empty() { s.edit_prefs(|prefs| { for (name, key) in &keys { @@ -3176,6 +3345,7 @@ fn load(s: &mut Session, p: &Value) -> Result { fn save(s: &mut Session, p: &Value) -> Result { let cmd = "actions.save"; + crate::actions_cmds::flush_recording(s)?; let skip = match p.get("skipUnsupported") { None | Some(Value::Null) => false, Some(Value::Bool(b)) => *b, @@ -3223,7 +3393,8 @@ fn save(s: &mut Session, p: &Value) -> Result { #[cfg(not(target_arch = "wasm32"))] fn write_file(path: &str, bytes: &[u8]) -> std::io::Result<()> { - std::fs::write(path, bytes) + // Atomic replacement (temporary file + rename): a failed write keeps the previous ATN (#7290). + photocraft_format::atomic_write(std::path::Path::new(path), bytes) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index 871300372c..26865d4060 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -130,6 +130,39 @@ fn load_maps_events_keeps_flags_and_plays() { assert_eq!(s.actions.list[2].set.as_deref(), Some("Other")); } +/// Renames that chain ("A" becomes "A 2" while the file's own "A 2" becomes "A 2 2") rewrite +/// each Play and Conditional target once, to the renamed copy of the action it named. +#[test] +fn load_renames_each_play_target_once() { + let mut s = Session::new(); + let mut mine = Action::new("A", vec![]); + mine.set = Some("Mine".into()); + s.actions.list.push(mine); + let a = Action::new("A", vec![("actions.conditional".into(), json!({"if": "always", "then": "A", "else": "A 2"}))]); + let a2 = Action::new("A 2", vec![("actions.play".into(), json!({"action": "A"}))]); + let keys = [("A".to_string(), "F4".to_string())]; + let (bytes, _) = export("File", &[&a, &a2], &keys, false).unwrap(); + let r = s.execute("actions.load", json!({"data": b64(&bytes)})).unwrap(); + assert_eq!(r["actions"], json!(["A 2", "A 2 2"])); + let get = |n: &str| s.actions.list.iter().find(|a| a.name == n && a.set.as_deref() == Some("File")).unwrap(); + assert_eq!(get("A 2 2").steps[0].1["action"], "A 2", "plays the file's A, not its A 2"); + let cond = &get("A 2").steps[0].1; + assert_eq!((&cond["then"], &cond["else"]), (&json!("A 2"), &json!("A 2 2")), "{cond}"); + assert_eq!(r["functionKeys"], json!([{"action": "A 2", "key": "F4"}])); + + // Adding to a set of the same name leaves the Play steps already in it alone. + let mut s = Session::new(); + for (name, steps) in [("A", vec![]), ("B", vec![("actions.play".to_string(), json!({"action": "A"}))])] { + let mut a = Action::new(name, steps); + a.set = Some("File".into()); + s.actions.list.push(a); + } + let (bytes, _) = export("File", &[&Action::new("A", vec![])], &[], false).unwrap(); + let r = s.execute("actions.load", json!({"data": b64(&bytes), "replace": false})).unwrap(); + assert_eq!(r["actions"], json!(["A 2"])); + assert_eq!(s.actions.list[1].steps[0].1, json!({"action": "A"}), "B still plays the A it had"); +} + #[test] fn save_round_trips_through_photoshop_events() { let mut s = Session::new(); @@ -144,7 +177,7 @@ fn save_round_trips_through_photoshop_events() { assert_eq!(file.name.to_string_lossy(), "Test Set"); assert_eq!(file.actions[0].function_key, 3); let events: Vec = file.actions[0].items.iter().map(|i| i.event.id()).collect(); - assert_eq!(events, ["GsnB", "Mk ", "setd", "slct", "slct", "Stop", "syntheticFill", "Ply ", "Fltn"]); + assert_eq!(events, ["GsnB", "Mk ", "setd", "slct", "slct", "Stop", "syntheticFill", "Ply ", "FltI"]); assert!(file.actions[0].items[0].with_dialog); assert!(!file.actions[0].items[8].enabled); // The kept Photoshop step is written back byte for byte. @@ -174,6 +207,7 @@ fn every_mapped_command_exports_and_imports_back() { ("filter.noise.addNoise", json!({"amount": 12.5, "distribution": "gaussian", "monochromatic": true, "seed": 7})), ("filter.noise.median", json!({"radius": 2})), ("filter.blur.motionBlur", json!({"angle": 45, "distance": 20})), + ("filter.blur.smartBlur", json!({"radius": 2.5, "threshold": 40, "quality": "medium", "mode": "overlayEdge"})), ("filter.other.offset", json!({"horizontal": 10, "vertical": -5, "undefinedAreas": "wrap"})), ("filter.blur.blur", json!({})), ( @@ -186,6 +220,10 @@ fn every_mapped_command_exports_and_imports_back() { json!({"colorize": false, "hue": 10, "saturation": -20, "lightness": 0, "reds": {"hue": 5, "saturation": 0, "lightness": 0, "range": [315, 345, 15, 45]}}), ), ("image.adjustments.brightnessContrast", json!({"brightness": 10, "contrast": -5, "legacy": false})), + ( + "image.adjustments.shadowsHighlights", + json!({"shadowAmount": 60, "shadowTone": 40, "shadowRadius": 25, "highlightAmount": 10, "highlightTone": 50, "highlightRadius": 30, "blackClip": 0.02, "whiteClip": 0.05, "midtone": 15, "color": 20}), + ), ("image.adjustments.threshold", json!({"level": 100})), ("image.adjustments.posterize", json!({"levels": 4})), ("image.adjustments.invert", json!({})), @@ -412,7 +450,6 @@ fn every_mapped_command_exports_and_imports_back() { "filter.blur.blurMore", "filter.blur.boxBlur", "filter.blur.radialBlur", - "filter.blur.smartBlur", "filter.blur.surfaceBlur", "filter.noise.despeckle", "filter.noise.dustAndScratches", @@ -432,6 +469,55 @@ fn every_mapped_command_exports_and_imports_back() { } } +/// `paint.bucket` exported to .atn and imported back → its params, or None when it doesn't export. +fn bucket_round_trip(params: Value) -> Option { + let item = export_item("paint.bucket", ¶ms, "S")?; + let e = event_for(&item.event)?; + match (e.from)(item.descriptor.as_ref()?) { + Mapped::Steps(steps) => steps.first().map(|(id, p)| { + assert_eq!(id, "paint.bucket"); + p.clone() + }), + _ => None, + } +} + +/// A Paint Bucket step with an explicit colour keeps it through .atn (#7199): replayed on a fresh +/// document, whose foreground is black, it still fills red. A colour .atn can't hold makes the +/// step not export rather than fill with the foreground. +#[test] +fn bucket_keeps_an_explicit_color_through_atn() { + let fill = |params: &Value| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "#ffffff"})).unwrap(); + s.execute("paint.bucket", params.clone()).unwrap(); + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(2, 2) + }; + let red = json!({"x": 2, "y": 2, "antiAlias": false, "color": "#ff0000"}); + let back = bucket_round_trip(red.clone()).unwrap(); + assert_eq!(back["color"], "#ff0000", "{back}"); + assert_eq!(fill(&back), fill(&red)); + assert_eq!(fill(&back), vec![1.0, 0.0, 0.0, 1.0]); + // The colour as an array of channels. + assert_eq!(bucket_round_trip(json!({"x": 1, "y": 1, "color": [0.0, 0.5, 1.0]})).unwrap()["color"], "#0080ff"); + // No colour, or one the command can't read: the foreground, as before. + for p in [json!({"x": 1, "y": 1}), json!({"x": 1, "y": 1, "color": "red"})] { + let back = bucket_round_trip(p.clone()).unwrap(); + assert!(back.get("color").is_none() && back.get("contents").is_none(), "{p} → {back}"); + } + // A pattern fill ignores the colour, also when named with the older `source`. + for key in ["contents", "source"] { + let back = bucket_round_trip(json!({"x": 1, "y": 1, key: "pattern", "color": "#ff0000"})).unwrap(); + assert_eq!(back["contents"], "pattern", "{key}: {back}"); + assert!(back.get("color").is_none(), "{key}: {back}"); + } + // Translucent or out-of-range colours have no .atn form. + for c in [json!("#ff000080"), json!([1.0, 0.0, 0.0, 0.5]), json!([2.0, 0.0, 0.0])] { + assert!(bucket_round_trip(json!({"x": 1, "y": 1, "color": c})).is_none(), "{c}"); + } +} + #[test] fn unsupported_shapes_become_photoshop_steps_not_errors() { // Image size in two different percentages, a Paint Bucket click in percent of the canvas, a @@ -536,6 +622,33 @@ fn save_writes_the_file_and_the_set_of_the_selected_action() { std::fs::remove_dir_all(&dir).ok(); } +/// #7290: saving over an existing ATN must replace it atomically (a temporary file renamed over +/// it), never truncate and rewrite it in place, so a write that fails partway (a full disk) +/// leaves the previously valid file readable. A handle opened on the old file still sees the old +/// bytes after an atomic replacement; an in-place rewrite changes them under it. +#[cfg(unix)] +#[test] +fn save_over_an_existing_file_never_rewrites_it_in_place() { + use std::io::Read; + let mut s = Session::new(); + s.actions.list.push(Action::new("Owned", vec![("select.all".into(), json!({}))])); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("Owned.atn"); + let p = path.to_string_lossy().to_string(); + s.execute("actions.save", json!({"path": p})).unwrap(); + let before = std::fs::read(&path).unwrap(); + let mut old = std::fs::File::open(&path).unwrap(); + s.actions.list.push(Action::new("Second", vec![("select.all".into(), json!({}))])); + s.execute("actions.save", json!({"path": p})).unwrap(); + let mut seen = Vec::new(); + old.read_to_end(&mut seen).unwrap(); + assert_eq!(seen, before, "the existing ATN was rewritten in place"); + let after = atn::parse(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(after.actions.len(), 2); + let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(names, vec![std::ffi::OsString::from("Owned.atn")], "no temporary file is left behind"); +} + #[test] fn layer_param_accepts_a_name() { let mut s = Session::new(); @@ -573,7 +686,7 @@ fn remaining_events_import_in_their_photoshop_shapes() { let moved = desc("null") .with("null", target_ref("Lyr ")) .with("FTcs", enm("QCSt", "Qcsa")) - .with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(-57.4)).with("Vrtc", px(12.0)))) + .with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(-57.0)).with("Vrtc", px(12.0)))) .with("Intr", enm("Intp", "Bcbc")); let scaled = desc("null") .with("null", target_ref("Lyr ")) @@ -956,3 +1069,321 @@ fn remove_white_clears_the_targeted_layer_not_the_converted_background() { assert!(!st.doc.is_background(bottom.id), "the Background became a normal layer"); assert!(bottom.surface().unwrap().sample_channel(2, 2, 1) > 0.99, "and kept its pixels"); } + +/// Measured in Photoshop: `executeAction` fails for the codes `BoxB`, `SrfB`, `Fltn` and +/// `BlnW` ("the command is not currently available"), while the names `boxblur`, +/// `surfaceBlur`, `flattenImage`, `blackAndWhite` and the code `FltI` run. +#[test] +fn events_photoshop_only_runs_by_name_export_by_name_and_old_codes_still_import() { + let bw = json!({"reds": 40, "yellows": 60, "greens": 40, "cyans": 60, "blues": 20, "magentas": 80, "tint": false, "tintColor": "#e4d5b0"}); + let cases = [ + ("filter.blur.boxBlur", json!({"radius": 3}), "boxblur", "BoxB"), + ("filter.blur.surfaceBlur", json!({"radius": 5, "threshold": 15}), "surfaceBlur", "SrfB"), + ("layer.flattenImage", json!({}), "FltI", "Fltn"), + ("image.adjustments.blackWhite", bw, "blackAndWhite", "BlnW"), + ]; + for (id, params, written, legacy) in &cases { + let exported = export_item(id, params, "S").unwrap_or_else(|| panic!("{id} does not export")); + assert_eq!(exported.event.id(), *written, "{id} exports under an id Photoshop runs"); + assert_eq!(matches!(exported.event, AtnEvent::Name(_)), written.len() != 4, "{id}: a name is written as a name"); + let d = exported.descriptor.clone(); + // The written id, the name for Flatten Image, and the old code all import to the command. + let name = if *id == "layer.flattenImage" { "flattenImage" } else { written }; + for event in [*written, name, *legacy] { + let e = event_for(&item(event, "", None).event).unwrap_or_else(|| panic!("{event} does not import")); + assert!(e.ids.contains(id), "{event} imports as {:?}, not {id}", e.ids); + match (e.from)(d.as_ref().unwrap()) { + Mapped::Steps(steps) => { + assert_eq!(steps.len(), 1, "{event}: {steps:?}"); + assert_eq!(steps[0].0, *id, "{event}"); + let mut back = steps[0].1.clone(); + normalise(&mut back); + assert_eq!(back, *params, "{event}"); + } + Mapped::Unsupported { .. } => panic!("{event} does not import back"), + } + } + } + + // A whole set of Photoshop-shaped steps (names, FltI) and old PhotoCraft-shaped ones + // (legacy codes) loads to the same commands. + let blur = |event: &str| item(event, "Box Blur", Some(desc("null").with("Rds ", px(3.0)))); + let surface = |event: &str| item(event, "Surface Blur", Some(desc("null").with("Rds ", px(5.0)).with("Thsh", long(15.0)))); + let photoshop = vec![blur("boxblur"), surface("surfaceBlur"), item("FltI", "Flatten Image", None), item("flattenImage", "Flatten Image", None)]; + let legacy = vec![blur("BoxB"), surface("SrfB"), item("Fltn", "Flatten Image", None)]; + let data = set_of("S", vec![("Photoshop", photoshop), ("Legacy", legacy)]); + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(r["unsupported"], json!([]), "{r}"); + let ids = |i: usize| s.actions.list[i].steps.iter().map(|(id, _)| id.clone()).collect::>(); + assert_eq!(ids(0), ["filter.blur.boxBlur", "filter.blur.surfaceBlur", "layer.flattenImage", "layer.flattenImage"]); + assert_eq!(ids(1), ["filter.blur.boxBlur", "filter.blur.surfaceBlur", "layer.flattenImage"]); + assert_eq!(s.actions.list[1].steps[1].1, json!({"radius": 5, "threshold": 15})); + // Saving them writes the ids Photoshop runs, never the old codes. + let saved = s.execute("actions.save", json!({"set": "S"})).unwrap(); + let file = atn::parse(&photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap()).unwrap(); + let events: Vec = file.actions.iter().flat_map(|a| a.items.iter().map(|i| i.event.id())).collect(); + assert_eq!(events, ["boxblur", "surfaceBlur", "FltI", "FltI", "boxblur", "surfaceBlur", "FltI"]); + + // Unknown ids, near misses and the legacy codes written as names stay Photoshop steps, + // never a panic or a wrong command. + for event in ["BoxBlur", "boxBlur", "BOXB", "Fltn ", "FLTI", "", "\u{0}\u{0}\u{0}\u{0}", "BlnWx"] { + let e = event_for(&item(event, "", None).event); + assert!(e.is_none(), "{event:?} maps to {:?}", e.map(|e| e.ids)); + } + // A legacy code with a broken descriptor is unsupported, not a crash. + let e = event_for(&item("SrfB", "", None).event).unwrap(); + assert!(matches!((e.from)(&desc("null").with("Rds ", D::Double(f64::NAN))), Mapped::Unsupported { .. } | Mapped::Steps(_))); + // A wrong-typed key is skipped like any other unreadable field: the step keeps the defaults. + match (e.from)(&desc("null").with("Rds ", text("x"))) { + Mapped::Steps(steps) => assert!(steps.iter().all(|(_, p)| p.get("radius").is_none()), "{steps:?}"), + Mapped::Unsupported { .. } => {} + } +} + +/// Smart Blur's quality uses Photoshop's `SmBQ` codes (`SBQL`/`SBQM`/`SBQH`): measured in +/// Photoshop, the old `Hgh `/`Mdm `/`Low ` play back as its fallback quality. Old codes still read. +#[test] +fn smart_blur_quality_uses_photoshop_codes() { + let smart_blur = + |quality: D, mode: &str| desc("null").with("Rds ", D::Double(6.0)).with("Thsh", D::Double(60.0)).with("SmBQ", quality).with("SmBM", enm("SmBM", mode)); + // Every quality writes Photoshop's code, as a double radius/threshold and both enums, + // and reads back as the same step. + for (quality, code) in [("low", "SBQL"), ("medium", "SBQM"), ("high", "SBQH")] { + let params = json!({"radius": 6, "threshold": 60, "quality": quality, "mode": "edgeOnly"}); + let a = Action::new("Q", vec![("filter.blur.smartBlur".into(), params.clone())]); + let (bytes, skipped) = export("S", &[&a], &[], false).unwrap(); + assert!(skipped.is_empty()); + let file = atn::parse(&bytes).unwrap(); + let it = &file.actions[0].items[0]; + assert_eq!(it.event.id(), "SmrB"); + assert_eq!(it.descriptor.as_ref(), Some(&smart_blur(enm("SmBQ", code), "SBME")), "{quality}"); + let back = import(&bytes).unwrap(); + assert!(back.unsupported.is_empty(), "{quality}"); + assert_eq!(back.actions[0].steps, vec![("filter.blur.smartBlur".to_string(), params)]); + } + + // Photoshop-shaped steps (each quality and mode, as Photoshop stores them) and the codes + // PhotoCraft wrote before this fix read as the right quality. + let cases = [ + ("SBQH", "SBMN", "high", "normal"), + ("SBQM", "SBMO", "medium", "overlayEdge"), + ("SBQL", "SBME", "low", "edgeOnly"), + ("Hgh ", "SBMN", "high", "normal"), + ("Mdm ", "SBMN", "medium", "normal"), + ("Low ", "SBMN", "low", "normal"), + ]; + let items = cases.iter().map(|(q, m, _, _)| item("SmrB", "Smart Blur", Some(smart_blur(enm("SmBQ", q), m)))).collect(); + let data = set_of("Blurs", vec![("Smart", items)]); + let mut s = Session::new(); + s.execute("actions.load", json!({"data": data})).unwrap(); + let steps = &s.actions.list[0].steps; + for ((q, _, quality, mode), (id, p)) in cases.iter().zip(steps) { + assert_eq!(id, "filter.blur.smartBlur", "{q}"); + assert_eq!(p, &json!({"radius": 6, "threshold": 60, "quality": quality, "mode": mode}), "{q}"); + } + + // An unknown code, a quality of the wrong type, NaN and a missing quality never panic: the + // unknown ones stay Photoshop steps, kept verbatim. + let odd = [ + smart_blur(enm("SmBQ", "Xxxx"), "SBMN"), + smart_blur(D::Integer(2), "SBMN"), + smart_blur(enm("SmBQ", "SBQH"), "Xxxx"), + desc("null").with("Rds ", D::Double(f64::NAN)).with("SmBQ", enm("SmBQ", "SBQM")), + desc("null"), + ]; + let items: Vec = odd.iter().map(|d| item("SmrB", "Smart Blur", Some(d.clone()))).collect(); + let imported = import(&photocraft_paint::tile::b64_decode(&set_of("Odd", vec![("Odd", items)])).unwrap()).unwrap(); + let steps = &imported.actions[0].steps; + assert_eq!(steps.len(), odd.len()); + assert_eq!(steps[0].0, PHOTOSHOP_STEP, "an unknown quality is kept verbatim"); + assert_eq!(steps[2].0, PHOTOSHOP_STEP, "an unknown mode is kept verbatim"); + assert_eq!(imported.unsupported.iter().map(|u| u.step).collect::>(), [0, 2]); + // A wrong-type quality is left out (the filter's default applies), as for every enum field. + assert_eq!(steps[1], ("filter.blur.smartBlur".to_string(), json!({"radius": 6, "threshold": 60, "mode": "normal"}))); + // An unknown quality or a non-string one is not exported. + for bad in [json!({"quality": "best"}), json!({"quality": 3}), json!({"radius": "x"})] { + let a = Action::new("Bad", vec![("filter.blur.smartBlur".into(), bad.clone())]); + assert!(export("S", &[&a], &[], false).is_err(), "{bad}"); + } +} + +/// #5830: Shadows/Highlights (`adaptCorrect`) recorded by Photoshop, with string IDs, plays as +/// Image › Adjustments › Shadows/Highlights instead of stopping as a step with no equivalent. +#[test] +fn photoshop_shadows_highlights_steps_play() { + let tones = |amount: f64, width: f64, radius: i32| { + D::Descriptor(desc("adaptCorrectTones").with("amount", pct(amount)).with("width", pct(width)).with("radius", D::Integer(radius))) + }; + let d = desc("null") + .with("shadowMode", tones(35.0, 50.0, 30)) + .with("highlightMode", tones(20.0, 40.0, 24)) + .with("blackClip", D::Double(0.01)) + .with("whiteClip", D::Double(0.02)) + .with("center", D::Integer(5)) + .with("colorCorrection", D::Integer(20)); + let e = event_for(&item("adaptCorrect", "Sombra/Realce", None).event).expect("adaptCorrect is mapped"); + let Mapped::Steps(steps) = (e.from)(&d) else { panic!("Shadows/Highlights maps to a step") }; + assert_eq!(steps.len(), 1); + let (id, p) = &steps[0]; + assert_eq!(id, "image.adjustments.shadowsHighlights"); + let mut p = p.clone(); + normalise(&mut p); + assert_eq!( + p, + json!({"shadowAmount": 35, "shadowTone": 50, "shadowRadius": 30, "highlightAmount": 20, "highlightTone": 40, "highlightRadius": 24, "blackClip": 0.01, "whiteClip": 0.02, "midtone": 5, "color": 20}) + ); + // The same settings as char IDs read the same; absent keys are left to the defaults. + let codes = desc("null") + .with("sdwM", D::Descriptor(desc("adaptCorrectTones").with("Amnt", pct(35.0)).with("Wdth", pct(50.0)).with("Rds ", D::Integer(30)))) + .with("BlcC", D::Double(0.01)); + let Mapped::Steps(steps) = (e.from)(&codes) else { panic!("char IDs map too") }; + let mut q = steps[0].1.clone(); + normalise(&mut q); + assert_eq!(q, json!({"shadowAmount": 35, "shadowTone": 50, "shadowRadius": 30, "blackClip": 0.01})); + // And it runs on a document. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#404040"})).unwrap(); + s.execute(id, p).unwrap(); +} + +#[test] +fn save_while_recording_includes_pending_steps() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("actions.record", json!({"name": "Pending"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Recorded"})).unwrap(); + + // While still recording (without calling actions.stop), save the action. + let saved = s.execute("actions.save", json!({"action": "Pending"})).unwrap(); + assert_eq!(saved["steps"], 1, "pending steps must be flushed and included in save"); + assert_eq!(saved["skipped"], json!([])); + + // After save, recording continues and additional steps are flushed on stop without duplication. + s.execute("layer.new.layer", json!({"name": "Second"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + + let action = s.execute("actions.get", json!({"action": "Pending"})).unwrap(); + assert_eq!(action["steps"].as_array().unwrap().len(), 2, "both steps must be present without duplication"); +} + +/// Photoshop's Close has no document target: a Close of a specific document must not be +/// exported as a plain Close, which would close the active document on playback. +#[test] +fn close_with_document_target_is_not_exported_as_plain_close() { + let targeted = Action { name: "Probe".into(), steps: vec![("file.close".into(), json!({"document": 0}))], ..Default::default() }; + assert!(export("Audit4", &[&targeted], &[], false).is_err()); + let (_, skipped) = export("Audit4", &[&targeted], &[], true).unwrap(); + assert_eq!(skipped, vec![Skipped { action: "Probe".into(), step: 0, id: "file.close".into() }]); + let plain = Action { name: "Plain".into(), steps: vec![("file.close".into(), json!({}))], ..Default::default() }; + let (bytes, skipped) = export("Audit4", &[&plain], &[], false).unwrap(); + assert!(skipped.is_empty()); + let imported = import(&bytes).unwrap(); + assert_eq!(imported.actions[0].steps, vec![("file.close".to_string(), json!({}))]); +} + +/// A translation-only Free Transform with a fractional offset must not collapse into an +/// integer `layer.translate`: the sub-pixel placement and interpolation have to survive. +#[test] +fn fractional_translation_only_transform_keeps_offset_and_interpolation() { + let params = json!({"dx": 0.5, "dy": 0, "interpolation": "bilinear"}); + let d = transform_to("edit.transform", ¶ms).unwrap(); + let file = AtnFile { + name: UnicodeString::new_nul("Frac"), + expanded: false, + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item("transform", "Transform", Some(d))], ..Default::default() }], + warnings: vec![], + }; + let imp = import(&atn::write(&file).unwrap()).unwrap(); + assert!(imp.unsupported.is_empty()); + let steps = &imp.actions[0].steps; + assert_eq!(steps.len(), 1); + assert_eq!(steps[0].0, "edit.transform"); + assert_eq!(steps[0].1.get("dx").and_then(Value::as_f64), Some(0.5)); + assert_eq!(steps[0].1.get("interpolation"), Some(&json!("bilinear"))); +} + +/// Arbitrary canvas rotation must keep its interpolation through a strict export: dropping it +/// silently replays the rotation with the default bicubic resampling. +#[test] +fn arbitrary_rotation_keeps_interpolation_through_atn() { + for params in [ + json!({"angle": 17, "direction": "ccw", "interpolation": "nearest"}), + json!({"angle": 17, "direction": "ccw", "interpolation": "bilinear"}), + json!({"angle": 17, "direction": "ccw", "interpolation": "bicubic"}), + json!({"angle": 17, "direction": "ccw"}), + ] { + let a = Action { name: "Rot".into(), steps: vec![("image.rotation.arbitrary".into(), params.clone())], ..Default::default() }; + let (bytes, skipped) = export("Rot", &[&a], &[], false).unwrap(); + assert!(skipped.is_empty()); + let imported = import(&bytes).unwrap(); + assert!(imported.unsupported.is_empty()); + assert_eq!(imported.actions[0].steps, vec![("image.rotation.arbitrary".to_string(), params)]); + } +} + +/// A filter recorded against a layer mask must not export as a plain filter that edits the +/// layer's pixels on replay: Photoshop's descriptor has no field for PhotoCraft's `target`. +#[test] +fn add_noise_with_mask_target_is_not_exported_as_pixel_filter() { + let masked = Action { + name: "Probe".into(), + steps: vec![("filter.noise.addNoise".into(), json!({"amount": 75, "seed": 123, "target": "mask"}))], + ..Default::default() + }; + assert!(export("Audit", &[&masked], &[], false).is_err()); + let (_, skipped) = export("Audit", &[&masked], &[], true).unwrap(); + assert_eq!(skipped, vec![Skipped { action: "Probe".into(), step: 0, id: "filter.noise.addNoise".into() }]); + for params in [json!({"amount": 75, "seed": 123}), json!({"amount": 75, "seed": 123, "target": "pixels"})] { + let plain = Action { name: "Plain".into(), steps: vec![("filter.noise.addNoise".into(), params)], ..Default::default() }; + let (bytes, skipped) = export("Audit", &[&plain], &[], false).unwrap(); + assert!(skipped.is_empty()); + let imported = import(&bytes).unwrap(); + assert_eq!(imported.actions[0].steps, vec![("filter.noise.addNoise".to_string(), json!({"amount": 75, "seed": 123}))]); + } +} + +/// A Play Action that starts the called action at a later step must not export as a call of the +/// whole action: that would replay the steps the recording deliberately skipped. +#[test] +fn partial_play_action_is_not_exported_as_whole_action_call() { + let partial = Action { name: "Parent".into(), steps: vec![("actions.play".into(), json!({"action": "Child", "from": 1}))], ..Default::default() }; + assert!(export("Set", &[&partial], &[], false).is_err()); + let (_, skipped) = export("Set", &[&partial], &[], true).unwrap(); + assert_eq!(skipped, vec![Skipped { action: "Parent".into(), step: 0, id: "actions.play".into() }]); + for params in [json!({"action": "Child"}), json!({"action": "Child", "from": 0})] { + let whole = Action { name: "Parent".into(), steps: vec![("actions.play".into(), params)], ..Default::default() }; + let (bytes, skipped) = export("Set", &[&whole], &[], false).unwrap(); + assert!(skipped.is_empty()); + let imported = import(&bytes).unwrap(); + assert_eq!(imported.actions[0].steps, vec![("actions.play".to_string(), json!({"action": "Child"}))]); + } +} + +/// #7646: an action's function key keeps Photoshop's Shift and Command options through +/// `.atn` load and save, as `Shift+F5`, `Cmd+F5` and `Cmd+Shift+F5` shortcuts. +#[test] +fn function_keys_keep_shift_and_command() { + let mut file = sample(); + file.actions[1].function_key = 5; + file.actions[1].shift = true; + file.actions[1].command = true; + file.actions[0].shift = true; + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); + assert_eq!(r["functionKeys"], json!([{"action": "Soften", "key": "Shift+F3"}, {"action": "Finish", "key": "Cmd+Shift+F5"}])); + let shortcuts = &s.prefs().shortcuts; + assert_eq!(shortcuts.get("actions.play:Soften").map(String::as_str), Some("Shift+F3")); + assert_eq!(shortcuts.get("actions.play:Finish").map(String::as_str), Some("Cmd+Shift+F5")); + let r = s.execute("actions.save", json!({"set": "Test Set"})).unwrap(); + let saved = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap(); + let keys: Vec<_> = saved.actions.iter().map(|a| (a.function_key, a.shift, a.command)).collect(); + assert_eq!(keys, [(3, true, false), (5, true, true)]); + + assert_eq!(super::parse_function_key("Cmd+F12"), Some((12, false, true))); + assert_eq!(super::parse_function_key("Shift+Cmd+F2"), Some((2, true, true))); + for bad in ["F16", "F0", "Alt+F2", "Cmd+Cmd+F2", "Shift+", "Cmd+K", ""] { + assert_eq!(super::parse_function_key(bad), None, "{bad}"); + } + assert_eq!(super::function_key_name(7, false, false), "F7"); +} diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs index b76f8c836d..3de6bc84a1 100644 --- a/crates/engine/src/brush_cmds.rs +++ b/crates/engine/src/brush_cmds.rs @@ -793,13 +793,19 @@ fn presets_delete(s: &mut Session, p: &Value) -> Result { if s.tools.presets.len() == before { return Err(bad(cmd, format!("no brush preset named `{name}`"))); } - if s.tools.current_preset.as_ref().is_some_and(|c| c.eq_ignore_ascii_case(&name)) { + forget_deleted_preset(s, &name); + Ok(json!({ "count": s.tools.presets.len() })) +} + +/// After preset `name` was deleted (here or in Edit › Presets › Preset Manager): the current +/// brush no longer comes from a preset, and the library is saved. +pub(crate) fn forget_deleted_preset(s: &mut Session, name: &str) { + if s.tools.current_preset.as_ref().is_some_and(|c| c.eq_ignore_ascii_case(name)) { s.tools.current_preset = None; // The remembered brush names the preset it was picked from: the name went away. s.tools.brush_changed(); } s.brush_presets_changed(); - Ok(json!({ "count": s.tools.presets.len() })) } /// Overwrite an existing preset with the current brush (or the current brush plus a `brush` @@ -863,9 +869,16 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { } // Paint amount = darkness × alpha × selection (black = full paint, like Photoshop). let (w, h) = (area.width() as usize, area.height() as usize); - let mut v = vec![0.0f32; w * h]; + // The sampled tip is one f32 buffer over the whole selection; a large selection must fail + // gracefully instead of aborting the process on allocation, so reserve it fallibly. The + // multiply is checked too: on a 32-bit target (wasm32) it can overflow where the rest of + // this command is already fallible. + let len = w.checked_mul(h).ok_or_else(|| crate::allocation::error("defining a brush from the selection", "requested size overflowed"))?; + let mut v = crate::allocation::filled(len, 0.0, "defining a brush from the selection")?; let sc = sel.channels(); - let sv = sel.read_region(area); + // The selection mask is a second buffer of the same size; it must fail gracefully too + // (review of #5469), so read it through the fallible allocator. + let sv = crate::allocation::read_region(sel, area, "defining a brush from the selection")?; for y in 0..h { for x in 0..w { let c = surf.rgba(area.x0 + x as i32, area.y0 + y as i32); diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rs index eaf69281bc..cf9c761ce6 100644 --- a/crates/engine/src/brush_cmds/tests.rs +++ b/crates/engine/src/brush_cmds/tests.rs @@ -371,6 +371,57 @@ fn resizing_a_brush_resizes_its_enabled_secondary_tip() { assert_eq!((s.tools.brush.size, s.tools.brush.dual_brush.size), (40.0, 9.0)); } +/// Every way of changing the main size scales the Dual Brush tip as Photoshop does (#4809): `[` / +/// `]`, the options bar / Brushes panel / Alt+right-drag (`tools.setBrush` with only a size), down +/// to 1 px and back without losing the proportion to a floor. +#[test] +fn every_size_change_scales_the_dual_tip_and_keeps_its_proportion() { + let mut s = session(32, 32); + s.execute("tools.setBrush", json!({"brush": {"size": 100, "dualBrush": {"enabled": true, "size": 20}}})).unwrap(); + let sizes = |s: &Session| (s.tools.brush.size, s.tools.brush.dual_brush.size); + s.execute("tools.decreaseBrushSize", json!({})).unwrap(); + assert_eq!(sizes(&s), (80.0, 16.0)); + s.execute("tools.increaseBrushSize", json!({})).unwrap(); + assert_eq!(sizes(&s), (100.0, 20.0)); + // A coalesced drag (options bar slider, Alt+right-drag) is a run of size-only patches. + for size in [60, 10, 1] { + s.execute("tools.setBrush", json!({"brush": {"size": size}, "coalesce": "drag"})).unwrap(); + } + assert_eq!(s.tools.brush.size, 1.0); + assert!((s.tools.brush.dual_brush.size - 0.2).abs() < 1e-5, "no 0.5 px floor: {}", s.tools.brush.dual_brush.size); + s.execute("tools.setBrush", json!({"brush": {"size": 100}})).unwrap(); + assert_eq!(s.tools.brush.size, 100.0); + assert!((s.tools.brush.dual_brush.size - 20.0).abs() < 1e-3, "back to 20 px: {}", s.tools.brush.dual_brush.size); + // Painting with the sub-pixel dual tip works (the renderer bounds it). + s.execute("tools.setBrush", json!({"brush": {"size": 1}})).unwrap(); + s.execute("paint.stroke", json!({"points": [[4, 16], [28, 16]]})).unwrap(); +} + +/// Picking a preset that captured its size sets both diameters from the preset: the dual tip is +/// not scaled on top of that. +#[test] +fn a_captured_preset_size_is_not_scaled_twice() { + let mut s = session(32, 32); + s.execute("tools.setBrush", json!({"size": 40, "dualBrush": {"enabled": true, "size": 10}})).unwrap(); + s.execute("brush.presets.save", json!({"name": "Dual40"})).unwrap(); + s.execute("tools.setBrush", json!({"size": 200})).unwrap(); + assert_eq!(s.tools.brush.dual_brush.size, 50.0); + s.execute("tools.setBrush", json!({"preset": "Dual40"})).unwrap(); + assert_eq!((s.tools.brush.size, s.tools.brush.dual_brush.size), (40.0, 10.0)); +} + +#[test] +fn bad_sizes_fail_and_leave_the_dual_tip_alone() { + let mut s = session(32, 32); + s.execute("tools.setBrush", json!({"brush": {"size": 100, "dualBrush": {"enabled": true, "size": 20}}})).unwrap(); + for bad in [json!(1e30), json!("big"), json!([1]), json!({"x": 1}), json!(null)] { + let _ = s.execute("tools.setBrush", json!({"brush": {"size": bad}})); + assert_eq!(s.tools.brush.dual_brush.size, 20.0, "{bad}"); + assert_eq!(s.tools.brush.size, 100.0, "{bad}"); + } + assert!(s.execute("tools.setBrush", json!({"brush": {"size": 1e30}})).is_err()); +} + #[test] fn an_uncaptured_preset_size_keeps_dual_brush_proportions() { let mut s = session(32, 32); @@ -442,6 +493,26 @@ fn define_brush_from_selection() { assert!(rgba(&s, 30, 32)[3] > 0.9); } +#[test] +fn define_brush_from_selection_survives_allocation_failure() { + // The sampled tip is one f32 buffer over the whole selection, and the selection mask is a + // second of the same size. Both are reserved through the fallible allocator, so an allocation + // failure must be a graceful error (brush, presets, history and document untouched), never a + // panic or an OOM abort. + let mut s = session(40, 40); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap(); + let brush_before = s.tools.brush.clone(); + let presets_before = s.tools.presets.clone(); + let history_before = s.active().unwrap().history.past_len(); + crate::allocation::fail_next_for_test(); + let result = s.execute("brush.defineFromSelection", json!({"name": "Blob"})); + let _ = crate::allocation::capacity::(0, "reset failpoint"); + assert!(result.is_err(), "an allocation failure must be reported, not panic"); + assert_eq!(s.tools.brush, brush_before, "the current brush is unchanged"); + assert_eq!(s.tools.presets, presets_before, "the preset list is unchanged"); + assert_eq!(s.active().unwrap().history.past_len(), history_before, "no history step was recorded"); +} + #[test] fn works_on_cmyk_and_16_bit() { for (mode, depth) in [("cmyk", 8), ("rgb", 16), ("grayscale", 32)] { diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 46331126ac..1c126ec477 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -109,21 +109,29 @@ fn rename(s: &mut Session, p: &Value) -> Result { let cmd = "brush.presets.rename"; let i = find(s, p, "name", cmd)?; let new = text(p, "newName", cmd)?; - if index_of(&s.tools.presets, &new).is_some_and(|j| j != i) { + rename_at(s, i, &new, cmd)?; + Ok(json!({ "name": new })) +} + +/// Rename preset `i` (shared by Brush Settings and Edit › Presets › Preset Manager): refuses a +/// name another preset has (case-insensitively), makes the preset the user's and keeps the +/// current preset pointing at it. +pub(crate) fn rename_at(s: &mut Session, i: usize, new: &str, cmd: &str) -> Result<()> { + if index_of(&s.tools.presets, new).is_some_and(|j| j != i) { return Err(bad(cmd, format!("a brush preset named `{new}` already exists"))); } let pr = s.tools.presets.get_mut(i).ok_or_else(|| bad(cmd, "no such preset"))?; if pr.name != new { let was_current = s.tools.current_preset.as_ref().is_some_and(|c| c.eq_ignore_ascii_case(&pr.name)); - pr.name = new.clone(); + pr.name = new.to_string(); pr.builtin = false; if was_current { - s.tools.current_preset = Some(new.clone()); + s.tools.current_preset = Some(new.to_string()); s.tools.brush_changed(); } s.brush_presets_changed(); } - Ok(json!({ "name": new })) + Ok(()) } fn move_preset(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/canvas_geom.rs b/crates/engine/src/canvas_geom.rs index 0722c6bd10..8de32f4327 100644 --- a/crates/engine/src/canvas_geom.rs +++ b/crates/engine/src/canvas_geom.rs @@ -55,9 +55,15 @@ fn map_fill(a: &Affine, f: &mut Fill) { if let Fill::Gradient { angle, offset, .. } = f { *angle = map_angle(a, *angle); // The centre offset (a fraction of the frame) turns with the canvas: exact for 90° turns - // and flips, where the frame's sides swap with the axes. + // and flips, where the frame's sides swap with the axes. Scale (Image Size) resizes the + // frame too, so only each axis's direction applies. + let unit = |x: f64, y: f64| { + let n = x.hypot(y); + if n < EPS { (x, y) } else { (x / n, y / n) } + }; + let ((m0, m1), (m2, m3)) = (unit(a.m[0], a.m[1]), unit(a.m[2], a.m[3])); let (ox, oy) = (f64::from(offset.0), f64::from(offset.1)); - *offset = ((a.m[0] * ox + a.m[2] * oy) as f32, (a.m[1] * ox + a.m[3] * oy) as f32); + *offset = ((m0 * ox + m2 * oy) as f32, (m1 * ox + m3 * oy) as f32); } } @@ -150,15 +156,24 @@ pub(crate) fn transform_doc_marks(doc: &mut Document, a: &Affine) { if m1.abs() < EPS && m2.abs() < EPS { g.horizontal.iter_mut().for_each(|y| *y = m3 * *y + ty); g.vertical.iter_mut().for_each(|x| *x = m0 * *x + tx); + // Colours are keyed by exact position, so they move by the same expressions. + for c in &mut g.colors { + c.position = if c.vertical { m0 * c.position + tx } else { m3 * c.position + ty }; + } } else if m0.abs() < EPS && m3.abs() < EPS { // A horizontal guide at y becomes a vertical one at x' = m2·y + tx, and vice versa. let v: Vec = g.horizontal.iter().map(|y| m2 * y + tx).collect(); let h: Vec = g.vertical.iter().map(|x| m1 * x + ty).collect(); g.horizontal = h; g.vertical = v; + for c in &mut g.colors { + c.position = if c.vertical { m1 * c.position + ty } else { m2 * c.position + tx }; + c.vertical = !c.vertical; + } } else { g.horizontal.clear(); g.vertical.clear(); + g.colors.clear(); } } @@ -238,7 +253,8 @@ impl Turn { } /// Every pixel surface a canvas turn moves: content, rendered caches (type, shape, smart object, -/// fill), masks (layer, smart filter), alpha channels, Quick Mask and the selection. +/// fill), stored video frames (current and original), masks (layer, smart filter), alpha +/// channels, Quick Mask and the selection. fn remap_pixels(doc: &mut Document, map: &dyn Fn(i32, i32) -> (i32, i32)) { fn rec(layers: &mut [Layer], map: &dyn Fn(i32, i32) -> (i32, i32)) { let re = |s: &mut Surface| *s = remap_surface(s, map); @@ -249,6 +265,10 @@ fn remap_pixels(doc: &mut Document, map: &dyn Fn(i32, i32) -> (i32, i32)) { if let Some(fc) = &mut l.fill_cache { re(&mut fc.surface); } + // Frames away from the playhead come back on scrubbing; they turn with the canvas (#4956). + if let Some(v) = &mut l.video { + v.frames.iter_mut().chain(v.original_frames.iter_mut().flatten()).for_each(re); + } match &mut l.content { LayerContent::Raster(s) => re(s), LayerContent::Text(t) => t.cache.iter_mut().for_each(re), diff --git a/crates/engine/src/canvas_geom/tests.rs b/crates/engine/src/canvas_geom/tests.rs index 804a18b665..2ba0dfbd66 100644 --- a/crates/engine/src/canvas_geom/tests.rs +++ b/crates/engine/src/canvas_geom/tests.rs @@ -188,6 +188,39 @@ fn gradient_fill_angle_follows_the_canvas() { assert_eq!(map_angle(&Turn::Ccw90.affine(10.0, 20.0), 0.0), 90.0); } +/// The gradient fill's centre offset after `cmd`, as `gradient.fill.get` reports it (% of the frame). +fn fill_offset_after(cmd: &str, p: serde_json::Value) -> (f64, f64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("gradient.fill.create", json!({"from": [10, 50], "to": [90, 50], "style": "radial"})).unwrap(); + s.execute("gradient.fill.set", json!({"angle": 0, "offset": [25, 0]})).unwrap(); + s.execute(cmd, p).unwrap(); + let g = s.execute("gradient.fill.get", json!({})).unwrap(); + (g["offset"][0].as_f64().unwrap(), g["offset"][1].as_f64().unwrap()) +} + +#[test] +fn gradient_fill_offset_stays_a_fraction_of_the_frame() { + let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-3 && (a.1 - b.1).abs() < 1e-3; + // Image Size scales the frame, so the offset (a fraction of it) stays put. + for (w, h) in [(200, 200), (50, 50), (200, 50)] { + let o = fill_offset_after("image.imageSize", json!({"width": w, "height": h})); + assert!(near(o, (25.0, 0.0)), "{w}x{h}: {o:?}"); + } + // Flips and 90° turns still mirror and turn it. + assert!(near(fill_offset_after("image.imageRotation.flipCanvasHorizontal", json!({})), (-25.0, 0.0))); + assert!(near(fill_offset_after("image.imageRotation.90cw", json!({})), (0.0, 25.0))); + assert!(near(fill_offset_after("image.imageRotation.180", json!({})), (-25.0, 0.0))); + // Non-uniform scale with a turn: only the axis swap applies. + let mut f = Fill::gradient(Vec::new(), 0.0, 1.0, photocraft_doc::GradientStyle::Linear, false); + if let Fill::Gradient { offset, .. } = &mut f { + *offset = (0.25, -0.1); + } + map_fill(&Affine { m: [0.0, 3.0, -0.5, 0.0, 7.0, 1.0] }, &mut f); + let Fill::Gradient { offset, .. } = f else { panic!("not a gradient") }; + assert!((offset.0 - 0.1).abs() < 1e-6 && (offset.1 - 0.25).abs() < 1e-6, "{offset:?}"); +} + fn type_and_shape_origin(d: &Document) -> ([f64; 6], [f64; 2]) { let mut t = None; let mut k = None; @@ -230,6 +263,28 @@ fn canvas_size_and_crop_move_vector_geometry() { assert!(mean < 1.0 / 255.0, "{mean}"); } +#[test] +fn guide_colours_follow_their_guides() { + const MAGENTA: [u8; 3] = [255, 0, 255]; + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "#ff00ff"})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30})).unwrap(); + // Crop shifts both guides by 10: the colour goes with the guide at 20, not to the one now there. + s.execute("image.crop", json!({"x": 10, "y": 0, "width": W - 10, "height": H})).unwrap(); + let g = &doc(&s).guides; + assert_eq!(g.vertical, vec![10.0, 20.0]); + assert_eq!((g.color(true, 10.0), g.color(true, 20.0)), (Some(MAGENTA), None)); + // A quarter turn makes it a horizontal guide at y = 10, still magenta. + s.execute("image.imageRotation.90cw", json!({})).unwrap(); + let g = &doc(&s).guides; + assert_eq!(g.horizontal, vec![10.0, 20.0]); + assert_eq!((g.color(false, 10.0), g.color(true, 10.0)), (Some(MAGENTA), None)); + // An arbitrary angle drops the guides, so their colours go too. + s.execute("image.rotation.arbitrary", json!({"angle": 33})).unwrap(); + assert!(doc(&s).guides.colors.is_empty()); +} + #[test] fn image_size_scales_vector_geometry() { let mut s = mixed(8, "rgb"); @@ -270,6 +325,30 @@ fn arbitrary_rotation_moves_marks_and_unlinked_vector_masks() { assert!(mean < 3.0 / 255.0 && big < 0.02, "mean {mean} big {big}"); } +/// A canvas turn moves every stored video frame, not just the displayed one (#4956). +#[test] +fn turns_move_stored_video_frames() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + paint(&mut s, |x, y| if (x, y) == (1, 2) { [1.0, 0.0, 0.0, 1.0] } else { [0.0; 4] }); + s.edit("video", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let frame = l.surface().unwrap().clone(); + let mut v = photocraft_doc::VideoData::new(vec![frame.clone(), frame.clone()], 24.0); + v.original_frames = Some(vec![frame.clone(), frame]); + l.video = Some(v); + Ok(()) + }) + .unwrap(); + s.execute(command(Turn::FlipHorizontal), json!({})).unwrap(); + let v = doc(&s).layers[1].video.as_ref().unwrap(); + for frame in v.frames.iter().chain(v.original_frames.iter().flatten()) { + assert_eq!(frame.pixel(W as i32 - 2, 2), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(frame.pixel(1, 2)[3], 0.0); + } +} + #[test] fn turns_on_empty_and_tiny_documents_never_panic() { for (w, h) in [(1, 1), (1, 7), (5, 1)] { diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index 468db2698b..991f40dc0b 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -1086,17 +1086,19 @@ fn indicates_param(v: Option<&Value>) -> Option { } } -fn color_value(p: &Value, key: &str) -> Option { - p.get(key)?; - let c = crate::commands::color_param(p, key, [1.0, 0.0, 0.0, 1.0]); - Some(Color::rgb(c[0], c[1], c[2])) +fn color_value(cmd: &str, p: &Value, key: &str) -> Result> { + if p.get(key).is_none() { + return Ok(None); + } + let c = crate::commands::color_param(cmd, p, key, [1.0, 0.0, 0.0, 1.0])?; + Ok(Some(Color::rgb(c[0], c[1], c[2]))) } fn new_channel(s: &mut Session, p: &Value) -> Result { let fill = p.get("fill").and_then(Value::as_str).unwrap_or("black").to_string(); let name = p.get("name").and_then(Value::as_str).map(str::to_string); let indicates = indicates_param(p.get("indicates")); - let color = color_value(p, "color"); + let color = color_value("channel.new", p, "color")?; let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); let i = s.edit("New Channel", |doc, _| { let area = doc.bounds(); @@ -1125,7 +1127,7 @@ fn new_channel(s: &mut Session, p: &Value) -> Result { } fn new_spot(s: &mut Session, p: &Value) -> Result { - let color = color_value(p, "color").unwrap_or(Color::rgb(1.0, 0.0, 0.0)); + let color = color_value("channel.newSpot", p, "color")?.unwrap_or(Color::rgb(1.0, 0.0, 0.0)); let solidity = p.get("solidity").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 100.0) as f32 / 100.0; let name = p.get("name").and_then(Value::as_str).map(str::to_string); let from_sel = p.get("fromSelection").and_then(Value::as_bool).unwrap_or(true); @@ -1421,7 +1423,7 @@ fn options(s: &mut Session, p: &Value) -> Result { let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; let r = p.get("channel").and_then(|v| parse_ref(v, doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?; let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); - let color = color_value(p, "color"); + let color = color_value(cmd, p, "color")?; let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); let solidity = p.get("solidity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); let kind = p.get("indicates").and_then(Value::as_str).map(str::to_string); diff --git a/crates/engine/src/color_to_alpha_cmds.rs b/crates/engine/src/color_to_alpha_cmds.rs index a6208e8246..ba8b1aebcc 100644 --- a/crates/engine/src/color_to_alpha_cmds.rs +++ b/crates/engine/src/color_to_alpha_cmds.rs @@ -34,7 +34,7 @@ fn unit(v: f32, default: f32) -> f32 { /// Algorithm parameters (lenient: out-of-range values are clamped, unreadable ones fall back to /// the defaults). [`run`] validates strictly before it gets here. pub(crate) fn params(p: &Value) -> FilterParams { - let c = crate::commands::color_param(p, "color", WHITE); + let c = crate::commands::color_param(ID, p, "color", WHITE).unwrap_or(WHITE); let num = |k: &str, d: f32| p.get(k).and_then(Value::as_f64).map_or(d, |v| unit(v as f32, d)); FilterParams::ColorToAlpha { color: [unit(c[0], 1.0), unit(c[1], 1.0), unit(c[2], 1.0), 1.0], @@ -64,10 +64,9 @@ fn validate(p: &Value) -> Result<()> { Some(Value::String(s)) => { crate::commands::parse_hex(s).ok_or_else(|| bad(format!("`color` must be \"#rrggbb\", not {s:?}")))?; } + Some(Value::Array(a)) if (3..=4).contains(&a.len()) && a.iter().all(|v| v.as_f64().is_some_and(|x| x.is_finite() && (0.0..=1.0).contains(&x))) => {} Some(Value::Array(a)) if (3..=4).contains(&a.len()) => { - if !a.iter().all(|v| v.as_f64().is_some_and(|x| x.is_finite() && (0.0..=1.0).contains(&x))) { - return Err(bad("`color` as an array must hold 3 or 4 numbers in 0..1")); - } + return Err(bad("`color` as an array must hold 3 or 4 numbers in 0..1")); } Some(_) => return Err(bad("`color` must be \"#rrggbb\" or [r, g, b] in 0..1")), } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 2f04187128..9b4d4a7472 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -117,7 +117,10 @@ fn has_selection(s: &Session) -> std::result::Result<(), String> { fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result { if let Some(d) = s.active() { let a = t.affine(f64::from(d.doc.size.width), f64::from(d.doc.size.height)); - s.set_sampler_map(a); + // Sampler points are pixel indices, not pixel edges: map the pixel's centre, so the point + // lands on the same pixel `Turn::pixel_map` moves the pixels to (`w - 1 - x`). + let half = photocraft_geom::Affine::translate(0.5, 0.5); + s.set_sampler_map(half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5))); } s.edit(label, |doc, _| { crate::canvas_geom::turn_canvas(doc, t); @@ -232,15 +235,53 @@ pub(crate) fn u32_id_param(cmd: &str, p: &Value, key: &str) -> Result f32 { p.get(key).and_then(Value::as_f64).map(|v| v as f32).unwrap_or(default) } -pub(crate) fn color_param(p: &Value, key: &str, default: [f32; 4]) -> [f32; 4] { - match p.get(key) { +/// JSON numbers may be finite f64 values but overflow when stored in a document's f32 field. +pub(crate) fn finite_f32(cmd: &str, key: &str, value: f64) -> Result { + let narrowed = value as f32; + if narrowed.is_finite() { Ok(narrowed) } else { Err(bad(cmd, format!("`{key}` must fit a finite 32-bit number"))) } +} + +/// Effect/type parameters contain nested colour arrays and snapshots as well as scalars. +/// Validate before parsing or editing, including numbers hidden in an effect snapshot. +pub(crate) fn check_f32_values(cmd: &str, value: &Value) -> Result<()> { + // Bound the call stack, without allocating a work list proportional to an input array. + fn check(cmd: &str, value: &Value, depth: usize) -> Result<()> { + if depth > 64 { + return Err(bad(cmd, "parameters nested deeper than 64 levels")); + } + match value { + Value::Number(n) => { + finite_f32(cmd, "number", n.as_f64().ok_or_else(|| bad(cmd, "invalid number"))?)?; + } + Value::Array(a) => { + for v in a { + check(cmd, v, depth + 1)?; + } + } + Value::Object(o) => { + for v in o.values() { + check(cmd, v, depth + 1)?; + } + } + _ => {} + } + Ok(()) + } + check(cmd, value, 0) +} + +pub(crate) fn color_param(cmd: &str, p: &Value, key: &str, default: [f32; 4]) -> Result<[f32; 4]> { + Ok(match p.get(key) { Some(Value::Array(a)) if a.len() >= 3 => { - let v: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); - [v[0], v[1], v[2], v.get(3).copied().unwrap_or(1.0)] + let mut out = [0.0, 0.0, 0.0, 1.0]; + for (slot, value) in out.iter_mut().zip(a) { + *slot = finite_f32(cmd, key, value.as_f64().unwrap_or(0.0))?; + } + out } Some(Value::String(s)) => parse_hex(s).unwrap_or(default), _ => default, - } + }) } pub(crate) fn parse_hex(s: &str) -> Option<[f32; 4]> { let s = s.trim_start_matches('#'); @@ -295,7 +336,8 @@ fn set_clipped(s: &mut Session, p: &Value, clip: bool) -> Result { /// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that /// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays -/// in another document). `None` when the param is absent. +/// in another document; a name that matches no layer exactly matches regardless of case, so +/// `"background"` finds the Background). `None` when the param is absent. pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result> { match p.get("layer") { Some(Value::Number(n)) => { @@ -303,19 +345,41 @@ pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result> } Some(Value::String(name)) => { let d = s.active().ok_or(EngineError::NoDocument)?; - d.doc - .walk() - .into_iter() - .rev() + let layers = d.doc.walk(); + let mut top_down = layers.iter().rev(); + top_down + .clone() .find(|(_, _, l)| l.name == *name) + .or_else(|| top_down.find(|(_, _, l)| l.name.to_lowercase() == name.to_lowercase())) .map(|(_, _, l)| Some(l.id)) - .ok_or_else(|| EngineError::Other(format!("no layer named \"{name}\""))) + .ok_or_else(|| EngineError::Other(format!("no layer named \"{name}\"; {}", layer_listing(&d.doc)))) } Some(Value::Null) | None => Ok(None), Some(other) => Err(EngineError::Other(format!("`layer` must be an id or a name, not {other}"))), } } +/// The layers of `doc` as a caller can name them, for an error about a layer that isn't there: +/// `the document's layers are 2 "Background", 3 "Layer 1"` (top-down, at most 20). +pub(crate) fn layer_listing(doc: &Document) -> String { + const MAX: usize = 20; + let layers = doc.walk(); + if layers.is_empty() { + return "the document has no layers".into(); + } + // Names are unbounded input: each one is cut at NAME characters so the error stays short. + const NAME: usize = 64; + let name = |n: &str| match n.char_indices().nth(NAME) { + Some((cut, _)) => format!("{}…", &n[..cut]), + None => n.to_string(), + }; + let mut list: Vec = layers.iter().rev().take(MAX).map(|(_, _, l)| format!("{} {:?}", l.id.0, name(&l.name))).collect(); + if layers.len() > MAX { + list.push(format!("… {} more (see `document.inspect`)", layers.len() - MAX)); + } + format!("the document's layers are {} (a `layer` param takes an id or a name)", list.join(", ")) +} + /// The layer a command targets: [`explicit_layer`], else the active layer. pub(crate) fn layer_param(s: &Session, p: &Value) -> Result { match explicit_layer(s, p)? { @@ -690,7 +754,6 @@ fn build() -> Vec { return crate::layer_multi_cmds::duplicate_selected(s, in_place, "Duplicate Layers"); } let id = layer_param(s, p)?; - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); let nid = s.edit("Duplicate Layer", |doc, active| { let mut dup = layer_copy(doc, id)?; if let Some(name) = &name { @@ -703,7 +766,6 @@ fn build() -> Vec { *active = Some(nid); Ok(nid) })?; - crate::layer_multi_cmds::note_insert(s, &before); Ok(json!({ "layer": nid.0 })) } ), @@ -968,7 +1030,7 @@ fn build() -> Vec { r##"{"color":"#rrggbb"=foreground,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##, has_doc, |s, p| { - let c = color_param(p, "color", s.tools.foreground); + let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?; let id = s.edit("New Color Fill Layer", |doc, active| { let fill = Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode); let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill)); @@ -988,8 +1050,8 @@ fn build() -> Vec { r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)}"##, has_doc, |s, p| { - let a = color_param(p, "from", s.tools.foreground); - let b = color_param(p, "to", s.tools.background); + let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?; + let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?; let angle = f32_or(p, "angle", 90.0); let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")); let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); @@ -1120,8 +1182,10 @@ fn build() -> Vec { } }; let (fg_cmyk, bg_cmyk) = (cmyk("foregroundCmyk")?, cmyk("backgroundCmyk")?); - s.tools.foreground = color_param(p, "foreground", s.tools.foreground); - s.tools.background = color_param(p, "background", s.tools.background); + let foreground = color_param("tools.setColors", p, "foreground", s.tools.foreground)?; + let background = color_param("tools.setColors", p, "background", s.tools.background)?; + s.tools.foreground = foreground; + s.tools.background = background; if let Some(k) = fg_cmyk { let [r, g, b, _] = s.tools.foreground; s.tools.remember_cmyk([r, g, b], k); @@ -1422,6 +1486,7 @@ fn build() -> Vec { v.extend(crate::edit_menu_cmds::specs()); v.extend(crate::fill_key_cmds::specs()); v.extend(crate::sample_cmds::specs()); + v.extend(crate::face_cmds::specs()); v.extend(crate::sampler_cmds::specs()); v.extend(crate::brush_key_cmds::specs()); v.extend(crate::stamp_cmds::specs()); diff --git a/crates/engine/src/comps_cmds.rs b/crates/engine/src/comps_cmds.rs index fe5708387c..43a8ec12f0 100644 --- a/crates/engine/src/comps_cmds.rs +++ b/crates/engine/src/comps_cmds.rs @@ -208,6 +208,23 @@ fn apply_cmd(s: &mut Session, p: &Value) -> Result { apply(s, id, "Apply Layer Comp") } +/// How an action records Apply Layer Comp: by the comp's name, as Photoshop does. Comp ids are +/// local to a document, so a recorded id would apply whichever comp of another document has it +/// (#7181); by name the step finds that document's comp of the name, or stops with an error. +/// The comp is the one just applied, so `{}` and `null` (the last applied) record its name too. +pub(crate) fn recorded_apply(s: &Session, mut p: Value) -> Value { + let Some(d) = s.active() else { return p }; + let Some(comp) = d.doc.last_applied_comp.and_then(|id| d.doc.comp(id)) else { return p }; + // `null` params run as `{}` (the last applied comp), so they are recorded by name too. + if p.is_null() { + p = json!({}); + } + if let Value::Object(m) = &mut p { + m.insert("comp".into(), json!(comp.name)); + } + p +} + fn step(s: &mut Session, delta: i64) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let n = d.doc.layer_comps.len() as i64; diff --git a/crates/engine/src/comps_cmds/tests.rs b/crates/engine/src/comps_cmds/tests.rs index 5458523bcf..d4857ad025 100644 --- a/crates/engine/src/comps_cmds/tests.rs +++ b/crates/engine/src/comps_cmds/tests.rs @@ -347,3 +347,56 @@ fn clearing_warnings_of_an_unknown_comp_is_an_error() { assert_eq!(doc(&s).layer_comps, before); assert_eq!(s.execute("layerComp.updateWarnings", json!({})).unwrap()["count"], 1); } + +/// Apply Layer Comp is recorded by the comp's name, not its document-local id: played in another +/// document it applies that document's comp of the name, or stops when there is none (#7181). +#[test] +fn a_recorded_apply_layer_comp_finds_the_comp_by_name() { + let (mut s, _, _) = session(8); + s.execute("layerComp.new", json!({"name": "Wanted"})).unwrap(); + let wanted = doc(&s).layer_comps[0].id; + s.execute("actions.record", json!({"name": "ApplyWanted"})).unwrap(); + s.execute("layerComp.apply", json!({"comp": wanted})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + // `{}` and `null` apply the last applied comp; they are recorded by name too. + s.execute("actions.record", json!({"name": "ApplyLast"})).unwrap(); + s.execute("layerComp.apply", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + s.execute("actions.record", json!({"name": "ApplyNull"})).unwrap(); + s.execute("layerComp.apply", Value::Null).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + for action in ["ApplyWanted", "ApplyLast", "ApplyNull"] { + let steps = s.execute("actions.get", json!({"action": action})).unwrap()["steps"].clone(); + assert_eq!(steps, json!([["layerComp.apply", {"comp": "Wanted"}]]), "{action}"); + } + + // A second document whose comp with the recorded id is another one. + let (mut other, _, ob) = session(8); + other.actions = s.actions.clone(); + let show = |s: &mut Session, visible: bool| { + s.edit("t", |d, _| { + d.layer_mut(ob).unwrap().visible = visible; + Ok(()) + }) + .unwrap(); + }; + show(&mut other, false); + other.execute("layerComp.new", json!({"name": "Different"})).unwrap(); + show(&mut other, true); + other.execute("layerComp.new", json!({"name": "Wanted"})).unwrap(); + assert_eq!(doc(&other).layer_comps[0].id, wanted, "the recorded id names `Different` here"); + show(&mut other, false); + other.execute("actions.play", json!({"action": "ApplyWanted"})).unwrap(); + let applied = doc(&other).last_applied_comp.and_then(|id| doc(&other).comp(id)).map(|c| c.name.clone()); + assert_eq!(applied.as_deref(), Some("Wanted")); + assert!(doc(&other).layer(ob).unwrap().visible, "Wanted shows the layer"); + + // A document without a comp of that name stops the action instead of applying another one. + other.execute("layerComp.delete", json!({"comp": "Wanted"})).unwrap(); + show(&mut other, false); + let before = (doc(&other).last_applied_comp, doc(&other).layer(ob).unwrap().visible); + let played = other.execute("actions.play", json!({"action": "ApplyWanted"})).unwrap(); + assert_eq!(played["ran"], 0, "{played}"); + assert!(played["failed"]["error"].as_str().unwrap().contains("no layer comp named \"Wanted\""), "{played}"); + assert_eq!((doc(&other).last_applied_comp, doc(&other).layer(ob).unwrap().visible), before, "the document is unchanged"); +} diff --git a/crates/engine/src/doc_path.rs b/crates/engine/src/doc_path.rs new file mode 100644 index 0000000000..b51d164e74 --- /dev/null +++ b/crates/engine/src/doc_path.rs @@ -0,0 +1,58 @@ +//! Paths stored in a document reach the file system only through [`resolve`] (built on +//! [`photocraft_io::doc_path::resolve`]): linked smart objects, the Displace map and Color Lookup +//! file a smart filter re-reads, data-set images and video footage. A refused path is handled like +//! a missing file: the layer keeps its last rendering, and commands that need the file say why. +//! +//! Smart-object rendering has no `Session` argument, so the path of the document being worked on +//! travels in a thread-local scope, entered where commands run ([`crate::Session::edit`], command +//! dispatch, background jobs). Outside a scope there is no document: relative paths are refused +//! and only local absolute paths are followed. + +use std::cell::RefCell; +use std::path::{Path, PathBuf}; + +pub use photocraft_io::doc_path::NotFollowed; + +thread_local! { + static DOCUMENT: RefCell> = const { RefCell::new(None) }; +} + +/// Restores the previous document path when dropped. +pub(crate) struct DocumentScope(Option); + +impl Drop for DocumentScope { + fn drop(&mut self) { + let previous = self.0.take(); + DOCUMENT.with(|d| *d.borrow_mut() = previous); + } +} + +/// Resolve stored paths against `document` (the path of the document being worked on, `None` +/// for one without a file) until the returned scope is dropped. +pub(crate) fn scope(document: Option<&Path>) -> DocumentScope { + let next = document.filter(|d| !d.as_os_str().is_empty()).map(Path::to_path_buf); + DocumentScope(DOCUMENT.with(|d| d.replace(next))) +} + +/// The document path of the current scope (to carry it to another thread). +pub(crate) fn current() -> Option { + DOCUMENT.with(|d| d.borrow().clone()) +} + +/// The file to open for `stored`, a path stored in the document of the current scope. +pub fn resolve(stored: &str) -> Result { + resolve_in(stored, current().as_deref()) +} + +/// The file to open for `stored`, a path stored in the document saved at `document`. +pub fn resolve_in(stored: &str, document: Option<&Path>) -> Result { + photocraft_io::doc_path::resolve(stored, document) +} + +/// The message for a stored path that is not followed. +pub(crate) fn refusal(what: &str, stored: &str, why: NotFollowed) -> crate::EngineError { + crate::EngineError::Other(format!("{what} {stored} is not opened: {why}")) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/doc_path/tests.rs b/crates/engine/src/doc_path/tests.rs new file mode 100644 index 0000000000..393e85a062 --- /dev/null +++ b/crates/engine/src/doc_path/tests.rs @@ -0,0 +1,227 @@ +//! Each kind of place that follows a path stored in a document goes through [`super::resolve`]: a +//! link to another computer is never followed, and a relative link next to the document is. + +use std::path::{Path, PathBuf}; + +use photocraft_doc::{LayerContent, LayerId, SmartSource}; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +/// A link to a share on a TEST-NET-1 address, which never answers. +const REMOTE: &str = r"\\192.0.2.1\share\x.png"; + +/// An empty folder of its own (tests run in parallel). +fn dir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("photocraft-doc-path-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A 32×32 PNG whose pixel at column `x` is `rgb(x)`. +fn png(path: &Path, rgb: impl Fn(u32) -> [u8; 3]) { + let mut px = Vec::new(); + for _ in 0..32 { + for x in 0..32 { + px.extend(rgb(x)); + } + } + let image = photocraft_codecs::Image::from_u8(32, 32, photocraft_codecs::ChannelLayout::Rgb, px).unwrap(); + std::fs::write(path, photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); +} + +/// On Unix `//` followed by an absolute path names that same local file, while the resolver sees a +/// path on another computer: a place that skipped the resolver would read the file. +#[cfg(unix)] +fn network_alias(p: &Path) -> String { + format!("/{}", p.display()) +} + +/// A 32×32 white document saved (as far as its links know) at `d/doc.pcraft`, with `file` placed +/// linked → (session, layer id). +fn document(d: &Path, file: &Path) -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.active_mut().unwrap().path = Some(d.join("doc.pcraft").to_string_lossy().into_owned()); + s.execute("file.placeLinked", json!({"path": file.to_string_lossy()})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + (s, id) +} + +/// Point smart object `id` at `path` without re-rendering it. +fn relink(s: &mut Session, id: LayerId, path: &str) { + s.edit("Relink", |doc, _| { + if let Some(LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) { + sm.source = SmartSource::Linked { path: path.into() }; + } + Ok(()) + }) + .unwrap(); +} + +fn centre(s: &Session) -> [f32; 3] { + let p = photocraft_compose::render(&s.active().unwrap().doc, Rect::new(16, 16, 17, 17)).px[0]; + [p[0], p[1], p[2]] +} + +const RED: [f32; 3] = [1.0, 0.0, 0.0]; +const BLUE: [f32; 3] = [0.0, 0.0, 1.0]; + +fn update(s: &mut Session) -> Result { + s.execute("layer.smartObjects.updateModifiedContent", json!({})).map_err(|e| e.to_string()) +} + +#[test] +fn linked_smart_objects_follow_only_local_files() { + let d = dir("links"); + png(&d.join("red.png"), |_| [255, 0, 0]); + png(&d.join("blue.png"), |_| [0, 0, 255]); + let (mut s, id) = document(&d, &d.join("red.png")); + assert_eq!(centre(&s), RED); + + relink(&mut s, id, REMOTE); + s.start_link_scan(); + assert!(s.link_scan.is_none(), "no look at a file on another computer"); + assert_eq!(s.execute("layer.smartObjects.updateChanged", json!({})).unwrap(), json!({"updated": []})); + let err = update(&mut s).unwrap_err(); + assert!(err.contains("is not opened: the path is on another computer"), "{err}"); + assert_eq!(centre(&s), RED, "the layer keeps its rendering"); + #[cfg(unix)] + { + relink(&mut s, id, &network_alias(&d.join("blue.png"))); + assert!(update(&mut s).is_err()); + assert_eq!(centre(&s), RED, "the file was not read"); + } + + // A relative link is taken from the document's folder. + relink(&mut s, id, "blue.png"); + update(&mut s).unwrap(); + assert_eq!(centre(&s), BLUE); + s.start_link_scan(); + assert!(s.link_scan.is_some(), "a followed link is looked at"); +} + +#[test] +fn package_copies_only_followed_links() { + let d = dir("package"); + png(&d.join("red.png"), |_| [255, 0, 0]); + let (mut s, id) = document(&d, &d.join("red.png")); + relink(&mut s, id, "red.png"); + #[allow(unused_mut)] + let mut remote = vec![REMOTE.to_string()]; + #[cfg(unix)] + remote.push(network_alias(&d.join("red.png"))); + for path in &remote { + s.execute("file.placeLinked", json!({"path": d.join("red.png").to_string_lossy()})).unwrap(); + let other = s.active().unwrap().active_layer.unwrap(); + relink(&mut s, other, path); + } + let r = s.execute("file.package", json!({"dir": d.join("pkg").to_string_lossy()})).unwrap(); + let mut missing: Vec = serde_json::from_value(r["missing"].clone()).unwrap(); + missing.sort(); + remote.sort(); + assert_eq!(missing, remote); + let links = r["links"].as_array().unwrap(); + assert_eq!(links.len(), 1); + assert!(links[0].as_str().unwrap().ends_with("red.png"), "{links:?}"); +} + +#[test] +fn psd_saves_embed_only_followed_links() { + let d = dir("psd"); + png(&d.join("red.png"), |_| [255, 0, 0]); + let (mut s, id) = document(&d, &d.join("red.png")); + relink(&mut s, id, "red.png"); + s.execute("file.placeLinked", json!({"path": d.join("red.png").to_string_lossy()})).unwrap(); + let other = s.active().unwrap().active_layer.unwrap(); + relink(&mut s, other, REMOTE); + let warnings = |r: serde_json::Value| r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect::>(); + let saved = warnings(s.execute("file.saveACopy", json!({"path": d.join("copy.psd").to_string_lossy()})).unwrap()); + assert!(saved.iter().any(|w| w.contains("red.png was embedded")), "{saved:?}"); + assert!(saved.iter().any(|w| w.contains("is not opened: the path is on another computer")), "{saved:?}"); + // Package as PSD writes the copy of the document, whose remote link stays as it was. + let packaged = warnings(s.execute("file.package", json!({"dir": d.join("pkg").to_string_lossy(), "format": "psd"})).unwrap()); + assert!(packaged.iter().any(|w| w.contains("is not opened: the path is on another computer")), "{packaged:?}"); +} + +/// The pixels of the active document after its smart object `id` re-renders with its first smart +/// filter's params set to `params`. +fn replayed(s: &mut Session, id: LayerId, params: serde_json::Value) -> Vec<[f32; 4]> { + s.edit("Params", |doc, _| { + if let Some(LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) { + sm.smart_filters[0].params = params; + } + crate::smart_cmds::refresh(doc, id).map(|_| ()) + }) + .unwrap(); + let doc = &s.active().unwrap().doc; + photocraft_compose::render(doc, doc.bounds()).px +} + +#[test] +fn smart_filters_reread_only_followed_files() { + let d = dir("filters"); + png(&d.join("ramp.png"), |x| [(x * 8) as u8, 0, 0]); + png(&d.join("map.png"), |_| [255, 255, 255]); + // An inverting look: corner (r, g, b) of the cube maps to (1-r, 1-g, 1-b), red fastest. + let corners = (0..8).map(|i| format!("{} {} {}\n", 1 - (i & 1), 1 - ((i >> 1) & 1), 1 - ((i >> 2) & 1))).collect::(); + std::fs::write(d.join("invert.cube"), format!("LUT_3D_SIZE 2\n{corners}")).unwrap(); + let path = |name: &str| d.join(name).to_string_lossy().into_owned(); + + // Displace re-reads its `mapPath`. + let (mut s, id) = document(&d, &d.join("ramp.png")); + s.execute("filter.distort.displace", json!({"layer": id.0, "mapPath": path("map.png"), "horizontal": 50, "vertical": 0})).unwrap(); + let displaced = replayed(&mut s, id, json!({"mapPath": path("map.png"), "horizontal": 50, "vertical": 0})); + let unfiltered = replayed(&mut s, id, json!({"mapPath": REMOTE, "horizontal": 50, "vertical": 0})); + assert_ne!(displaced, unfiltered, "the map moves the pixels"); + assert_eq!(replayed(&mut s, id, json!({"mapPath": "map.png", "horizontal": 50, "vertical": 0})), displaced, "a relative map next to the document"); + #[cfg(unix)] + assert_eq!(replayed(&mut s, id, json!({"mapPath": network_alias(&d.join("map.png")), "horizontal": 50, "vertical": 0})), unfiltered); + + // Color Lookup re-reads its LUT `file`. + let (mut s, id) = document(&d, &d.join("ramp.png")); + s.execute("image.adjustments.colorLookup", json!({"layer": id.0, "lut": "none"})).unwrap(); + let inverted = replayed(&mut s, id, json!({"file": path("invert.cube")})); + let unfiltered = replayed(&mut s, id, json!({"file": REMOTE})); + assert_ne!(inverted, unfiltered, "the look changes the pixels"); + assert_eq!(replayed(&mut s, id, json!({"file": "invert.cube"})), inverted, "a relative look next to the document"); + #[cfg(unix)] + assert_eq!(replayed(&mut s, id, json!({"file": network_alias(&d.join("invert.cube"))})), unfiltered); +} + +#[test] +fn data_sets_and_footage_read_only_followed_files() { + let d = dir("datasets"); + png(&d.join("blue.png"), |_| [0, 0, 255]); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "#ff0000"})).unwrap(); + s.active_mut().unwrap().path = Some(d.join("doc.pcraft").to_string_lossy().into_owned()); + let layer = s.active().unwrap().active_layer.unwrap(); + s.execute("image.variables.define", json!({"defs": [{"name": "img", "layer": layer.0, "type": "pixelReplacement", "method": "conform"}]})).unwrap(); + let set = |name: &str, path: &str| json!({"name": name, "values": [{"variable": "img", "kind": "pixels", "value": path}]}); + s.execute("image.variables.dataSets", json!({"dataSets": [set("remote", REMOTE), set("relative", "blue.png")]})).unwrap(); + let err = s.execute("image.applyDataSet", json!({"name": "remote"})).unwrap_err().to_string(); + assert!(err.contains("is not opened: the path is on another computer"), "{err}"); + assert_eq!(centre(&s), RED); + s.execute("image.applyDataSet", json!({"name": "relative"})).unwrap(); + assert_eq!(centre(&s), BLUE); + + // Reload Frame re-reads the video layer's footage. + s.execute("layer.videoLayers.newVideoLayerFromFile", json!({"path": d.join("blue.png").to_string_lossy()})).unwrap(); + let footage = |s: &mut Session, path: &str| { + let id = s.active().unwrap().active_layer.unwrap(); + s.edit("Footage", |doc, _| { + if let Some(v) = doc.layer_mut(id).and_then(|l| l.video.as_mut()) { + v.source = photocraft_doc::VideoSource::File { path: path.into() }; + } + Ok(()) + }) + .unwrap(); + s.execute("layer.videoLayers.reloadFrame", json!({})).map_err(|e| e.to_string()) + }; + let err = footage(&mut s, REMOTE).unwrap_err(); + assert!(err.contains("is not opened: the path is on another computer"), "{err}"); + footage(&mut s, "blue.png").unwrap(); +} diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index dcb89aa980..aa2ce627f7 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -35,15 +35,14 @@ pub struct Clip { /// Photoshop's layer-based copy (CC 2018 on): with no selection, Copy takes the active layer /// whole when it is a smart object (#2428), a type or shape layer, or a group (its whole subtree) -/// (#2670), so Paste recreates it instead of its pixels. Pixel layers still copy their pixels; -/// several selected layers are [`multi_copy_ids`]. +/// (#2670), so Paste recreates it instead of its pixels. Fill and adjustment layers have no +/// pixels of their own, so they are taken whole too rather than refused (#2344). Pixel layers +/// still copy their pixels; several selected layers are [`multi_copy_ids`]. fn takes_whole(d: &crate::DocState, id: LayerId) -> bool { d.doc.selection.is_none() && d.selected_layers().len() <= 1 && crate::layer_copy_cmds::layered(d.doc.mode) - && d.doc - .layer(id) - .is_some_and(|l| matches!(l.content, LayerContent::Smart(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Group(_))) + && d.doc.layer(id).is_some_and(|l| !matches!(l.content, LayerContent::Raster(_))) } /// A scratch document in the source's colour, to hold copied layers. @@ -280,13 +279,18 @@ fn copy(s: &mut Session, merged: bool) -> Result { } match (d.doc.layer(id).and_then(Layer::surface).filter(|_| several.is_empty()), &layers) { (Some(surf), _) => Clip { layers, ..lift(surf, d.doc.selection.as_ref(), canvas)? }, - // A group has no pixels of its own: the clipboard pixels are what it shows. + // A group or fill layer has no pixels of its own: the clipboard pixels are what it + // shows. Adjustment layers show nothing by themselves, so their clip spans the canvas + // they apply to: Paste places them as a full-canvas layer, and the UI still mirrors + // the clip to the OS clipboard (an empty clip would let a stale OS image replace it). (None, Some(copies)) => { let mut shown = (**copies).clone(); for l in &mut shown.layers { l.visible = true; } - Clip { layers, ..lift(&merged_surface(&shown), None, canvas)? } + let clip = lift(&merged_surface(&shown), None, canvas)?; + let bounds = if clip.bounds.is_empty() { canvas } else { clip.bounds }; + Clip { layers, bounds, ..clip } } (None, None) => return Err(EngineError::Other("the active layer has no pixels".into())), } @@ -390,7 +394,6 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { let moved = shifted(&clip.surface, dx, dy); let target = PixelFormat::new(fmt.mode, fmt.sample, true); let surf = if moved.format() == target { moved } else { moved.convert(target) }; - let before = d.doc.clone(); let id = s.edit("Paste", |doc, active| { let mut l = Layer::raster(doc.next_layer_name("Layer"), target); *crate::pixels_mut(&mut l)? = surf; @@ -399,8 +402,7 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { doc.selection = None; Ok(id) })?; - // Only where the pasted pixels land needs recompositing, not the whole document (#2901). - crate::layer_multi_cmds::note_insert(s, &before); + // `edit` reports only where the pasted pixels land as damage, not the whole document (#2901). Ok(json!({"layer": id.0, "offset": [dx, dy]})) } @@ -1454,12 +1456,12 @@ mod tests { assert!(s.clipboard.is_none(), "a refused copy leaves the clipboard alone"); s.execute("layer.layerMask.revealAll", json!({})).unwrap(); assert!(s.execute("edit.copy", json!({"target": "mask"})).is_ok()); - // An adjustment layer has no pixels of its own: Copy is only enabled while its mask is - // targeted (#2928). + // An adjustment layer has no pixels of its own: Copy takes the layer whole (#2344), and + // its mask while that is targeted (#2928). s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.select", json!({"layer": a})).unwrap(); - assert!(!s.is_enabled("edit.copy"), "no pixels to copy"); + assert!(s.is_enabled("edit.copy"), "the layer itself can be copied"); s.execute("layer.layerMask.revealAll", json!({})).unwrap(); assert!(s.is_enabled_with("edit.copy", &json!({"target": "mask"})), "the mask can be copied"); } @@ -1916,6 +1918,56 @@ mod tests { assert_eq!(shape.surface().map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits"); } + /// #2344: fill and adjustment layers have no pixels of their own, so with no selection Copy + /// takes them whole and Paste recreates them, in the same or another document, in one step. + #[test] + fn copy_paste_keeps_fill_and_adjustment_layers() { + for (depth, other) in [(8, 16), (16, 32), (32, 8)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 40, "depth": depth})).unwrap(); + s.execute("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#ffffff", "angle": 0})).unwrap(); + let LayerContent::Fill(fill) = active_content(&s) else { panic!("a fill layer") }; + let src = s.active().unwrap().active_layer.unwrap(); + assert!(s.is_enabled("edit.copy"), "{depth}-bit: a fill layer can be copied"); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: what it shows"); + let clip = s.clipboard.clone().unwrap(); + assert!(clip.surface.rgba(59, 20)[0] > clip.surface.rgba(0, 20)[0], "{depth}-bit: the clip holds the gradient's pixels"); + let steps = s.active().unwrap().history.past_len(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{depth}-bit: one history step"); + assert_eq!(active_content(&s), LayerContent::Fill(fill.clone()), "{depth}-bit: the paste is the same fill layer"); + assert_ne!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: a new layer"); + s.undo(); + assert_eq!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: undo removes the paste"); + s.redo(); + assert!(matches!(active_content(&s), LayerContent::Fill(_)), "{depth}-bit: redo brings it back"); + + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let LayerContent::Adjustment(levels) = active_content(&s) else { panic!("an adjustment layer") }; + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: it applies to the canvas"); + s.execute("file.new", json!({"width": 30, "height": 30, "depth": other})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(active_content(&s), LayerContent::Adjustment(levels), "{depth}-bit: the same Levels layer in the {other}-bit document"); + assert_eq!(s.active().unwrap().doc.layers.len(), 2, "{depth}-bit: pasted above the Background"); + } + } + + /// #2344: several adjustment layers, which show nothing alone, still copy and paste together. + #[test] + fn several_adjustment_layers_copy_together() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); + let b = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": a})).unwrap(); + s.execute("layer.select", json!({"layer": b, "mode": "toggle"})).unwrap(); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 40, 40])); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 5, "both are pasted"); + assert!(d.layers[3..].iter().all(|l| matches!(l.content, LayerContent::Adjustment(_)))); + } + #[test] fn merge_visible_keeps_hidden_layers() { let mut s = session(); diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs index 11e2273601..b620230a61 100644 --- a/crates/engine/src/edit_menu_cmds.rs +++ b/crates/engine/src/edit_menu_cmds.rs @@ -68,7 +68,7 @@ pub(crate) fn after_command(s: &mut Session, id: &str) { let now = st.doc.layer(layer); let was = prev.layer(layer); let surf_eq = |a: Option<&Surface>, b: Option<&Surface>| match (a, b) { - (Some(a), Some(b)) => crate_fingerprint(a) == crate_fingerprint(b), + (Some(a), Some(b)) => a.format() == b.format() && a.default_pixel() == b.default_pixel() && crate_fingerprint(a) == crate_fingerprint(b), (None, None) => true, _ => false, }; @@ -110,6 +110,12 @@ fn always(_: &Session) -> std::result::Result<(), String> { fn pixel_layer(s: &Session) -> std::result::Result { let d = s.active().ok_or("no document open")?; let id = d.active_layer.ok_or("no active layer")?; + pixel_layer_id(s, id) +} + +/// `id` if it is an unlocked pixel layer of the active document. +fn pixel_layer_id(s: &Session, id: LayerId) -> std::result::Result { + let d = s.active().ok_or("no document open")?; let l = d.doc.layer(id).ok_or("no active layer")?; if !matches!(l.content, LayerContent::Raster(_)) { return Err(format!("active layer is {} {} layer, not a pixel layer", l.content.article(), l.content.kind_name())); @@ -208,7 +214,9 @@ fn fade(s: &mut Session, p: &Value) -> Result { if now.format() != before.format() { return Err(EngineError::Other("can't fade a step that changed the layer's pixel format".into())); } - let area = before.content_bounds().union(&now.content_bounds()); + // A uniform mask can change every pixel without storing a single tile. In that case + // the content bounds are empty, but Fade must still blend across the canvas. + let area = if before.default_pixel() != now.default_pixel() { st.doc.bounds() } else { before.content_bounds().union(&now.content_bounds()) }; let label = format!("Fade {}", src.label); s.edit(&label, |doc, _| { let l = doc.layer_mut(src.layer).ok_or(EngineError::NoLayer(src.layer))?; @@ -323,7 +331,7 @@ fn can_caf(s: &Session) -> std::result::Result<(), String> { } /// Mask surface (gray) of an alpha channel by index or name. -fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> { +pub(crate) fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> { match v { Value::Number(n) => doc.channels.get(n.as_u64()? as usize).map(|c| &c.surface), Value::String(name) => doc.channels.iter().find(|c| c.name == *name).map(|c| &c.surface), @@ -358,38 +366,169 @@ fn delete_and_fill(s: &mut Session, _: &Value) -> Result { content_aware_fill_as(s, &json!({"sampling": "rectangular"}), "edit.deleteAndFillSelection", "Delete and Fill Selection") } -fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &'static str) -> Result { - use photocraft_algo::content_aware::{FillOptions, auto_sampling_with, color_level, fill_owned, rotation_level}; - let id = pixel_layer(s).map_err(EngineError::Other)?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let doc = st.doc.clone(); - let sel = doc.selection.clone().ok_or_else(|| bad(cmd, "no selection"))?; - let hb = sel.content_bounds().intersect(&doc.bounds()); - if hb.is_empty() { +/// Everything one Content-Aware Fill needs, worked out from the document and the command's +/// params. The Content-Aware Fill workspace runs exactly this for its preview, so what it shows +/// is what OK and Apply write. +pub struct CafPlan { + pub layer: LayerId, + /// The rectangle worked on: the sampling window, and any sampling-brush strokes or custom + /// area beyond it. + pub rect: Rect, + /// Photoshop's sampling window around the fill area (`content_aware::sampling_window`). + pub window: Rect, + pub fmt: PixelFormat, + /// What is sampled over `rect`: the target's pixels, or with Sample All Layers the visible + /// composite in the target's encoding. + pub img: Vec, + /// The target's own pixels over `rect` when they differ from `img` (Sample All Layers); see + /// [`CafPlan::layer_pixels`]. + pub layer_px: Option>, + /// The fill area (selection coverage, after the workspace's lasso edits) over `rect`. + pub cover: Vec, + pub hole: Vec, + /// What may be copied from: the sampling option's area before the brush strokes, and after. + pub base: Vec, + pub source: Vec, + pub opts: photocraft_algo::content_aware::FillOptions, + pub output: String, +} + +impl CafPlan { + /// The target layer's pixels over `rect`. + pub fn layer_pixels(&self) -> &[f32] { + self.layer_px.as_deref().unwrap_or(&self.img) + } +} + +/// The workspace's lasso edits of the fill area: `{"op": "new|add|subtract|intersect", "points": +/// [[x, y], ...]}` or `{"op": "expand|contract", "by": px}`, applied in order. +#[derive(Clone, Debug, PartialEq)] +pub enum FillEdit { + Lasso { op: SelOp, points: Vec<[f64; 2]> }, + Grow(i32), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SelOp { + New, + Add, + Subtract, + Intersect, +} + +/// Most `fillEdits` and `samplingStrokes` one fill takes, and most points in all of them +/// together: the strokes and lassos are painted pixel by pixel, segment by segment. +pub const MAX_CAF_EDITS: usize = 1_000; +pub const MAX_CAF_POINTS: usize = 200_000; + +fn points_param(v: &Value, cmd: &str, what: &str, budget: &mut usize) -> Result> { + let a = v.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("{what} needs `points` [[x, y], ...]")))?; + *budget = budget.checked_sub(a.len()).ok_or_else(|| bad(cmd, format!("at most {MAX_CAF_POINTS} points in all fill edits and sampling strokes")))?; + a.iter() + .map(|p| { + let x = p.get(0).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); + let y = p.get(1).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); + match (x, y) { + (Some(x), Some(y)) => Ok([x, y]), + _ => Err(bad(cmd, format!("{what} points must be pairs of finite numbers"))), + } + }) + .collect() +} + +/// `p[key]` as an array of at most [`MAX_CAF_EDITS`] entries (empty when absent). +fn edits_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a [Value]> { + let Some(a) = p.get(key) else { return Ok(&[]) }; + let a = a.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be an array")))?; + if a.len() > MAX_CAF_EDITS { + return Err(bad(cmd, format!("`{key}` takes at most {MAX_CAF_EDITS} entries"))); + } + Ok(a) +} + +fn fill_edits(p: &Value, cmd: &str, budget: &mut usize) -> Result> { + edits_param(p, "fillEdits", cmd)? + .iter() + .map(|e| { + let op = e.get("op").and_then(Value::as_str).unwrap_or(""); + Ok(match op { + "expand" | "contract" => { + let by = e + .get("by") + .and_then(Value::as_f64) + .filter(|v| v.is_finite() && (0.0..=1000.0).contains(v)) + .ok_or_else(|| bad(cmd, "`by` must be 0..1000 px"))?; + FillEdit::Grow(if op == "expand" { by.round() as i32 } else { -(by.round() as i32) }) + } + "new" | "add" | "subtract" | "intersect" => FillEdit::Lasso { + op: match op { + "new" => SelOp::New, + "add" => SelOp::Add, + "subtract" => SelOp::Subtract, + _ => SelOp::Intersect, + }, + points: points_param(e, cmd, "a lasso edit", budget)?, + }, + o => return Err(bad(cmd, format!("unknown fill edit `{o}` (new|add|subtract|intersect|expand|contract)"))), + }) + }) + .collect() +} + +fn sampling_strokes(p: &Value, cmd: &str, budget: &mut usize) -> Result> { + edits_param(p, "samplingStrokes", cmd)? + .iter() + .map(|e| { + let add = match e.get("mode").and_then(Value::as_str).unwrap_or("add") { + "add" => true, + "subtract" => false, + o => return Err(bad(cmd, format!("unknown stroke mode `{o}` (add|subtract)"))), + }; + let size = e + .get("size") + .and_then(Value::as_f64) + .filter(|v| v.is_finite() && (1.0..=5000.0).contains(v)) + .ok_or_else(|| bad(cmd, "a stroke's `size` must be 1..5000 px"))?; + Ok(photocraft_algo::content_aware::SamplingStroke { add, size, points: points_param(e, cmd, "a sampling stroke", budget)? }) + }) + .collect() +} + +/// A Content-Aware Fill's params, checked against the document before any pixel is read. +struct CafParams<'a> { + sel: &'a Surface, + /// The selection's bounds on the canvas. + sb: Rect, + edits: Vec, + strokes: Vec, + sampling: String, + custom_mask: Option<&'a Surface>, + custom_rect: Option, + opts: photocraft_algo::content_aware::FillOptions, + output: String, + surf: &'a Surface, +} + +fn caf_params<'a>(doc: &'a Document, id: LayerId, p: &Value, cmd: &str) -> Result> { + use photocraft_algo::content_aware::{FillOptions, color_level, rotation_level}; + let sel = doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?; + let sb = sel.content_bounds().intersect(&doc.bounds()); + if sb.is_empty() { return Err(bad(cmd, "the selection is outside the canvas")); } + let mut budget = MAX_CAF_POINTS; + let edits = fill_edits(p, cmd, &mut budget)?; + let strokes = sampling_strokes(p, cmd, &mut budget)?; let sampling = str_or(p, "sampling", "auto").to_string(); - let custom_mask: Option = p.get("channel").and_then(|v| channel_mask(&doc, v)).cloned(); + let custom_mask: Option<&Surface> = p.get("channel").and_then(|v| channel_mask(doc, v)); let custom_rect = if p.get("area").is_some() { Some(rect_param(p, "area", cmd)?) } else { None }; - // Photoshop's window (`content_aware::sampling_window`) for Auto and Rectangular; `margin` - // asks for a rectangle that far around the selection instead. - let window = match sampling.as_str() { - "auto" => crate::fill_cmds::sampling_window(hb, doc.bounds()), - "rectangular" => match int(p, "margin") { - Some(m) => hb.inflate(m.clamp(0, 100_000) as i32), - None => crate::fill_cmds::sampling_window(hb, doc.bounds()), - }, - "custom" => { - let r = match (custom_rect, custom_mask.as_ref()) { - (Some(r), _) => r, - (None, Some(m)) => m.content_bounds(), - (None, None) => return Err(bad(cmd, "custom sampling needs `area` [x,y,w,h] or `channel` (alpha channel index or name)")), - }; - r.union(&hb).inflate(4) - } + match sampling.as_str() { + "auto" | "rectangular" => {} + // The workspace's Custom: only what the Sampling Brush adds. + "custom" if custom_rect.is_some() || custom_mask.is_some() || strokes.iter().any(|s| s.add) => {} + "custom" => return Err(bad(cmd, "custom sampling needs `area` [x,y,w,h], `channel` (alpha channel index or name) or `samplingStrokes`")), other => return Err(bad(cmd, format!("unknown sampling `{other}` (auto|rectangular|custom)"))), } - .intersect(&doc.bounds()); let opts = FillOptions { color_adaptation: color_level(str_or(p, "colorAdaptation", "default")), rotations: rotation_level(str_or(p, "rotationAdaptation", "none")), @@ -402,6 +541,77 @@ fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: & return Err(bad(cmd, "`output` must be current|new|duplicate")); } let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; + Ok(CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf }) +} + +/// Work out a Content-Aware Fill (see [`CafPlan`]) on layer `id` of `doc`. +pub fn content_aware_plan(doc: &Document, id: LayerId, p: &Value, cmd: &str) -> Result { + content_aware_plan_with(doc, id, p, cmd, &photocraft_raster::Interrupt::NONE) +} + +/// [`content_aware_plan`], asking `ctl` row by row whether to stop ([`EngineError::Cancelled`]). +pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str, ctl: &photocraft_raster::Interrupt) -> Result { + use photocraft_algo::content_aware::{auto_sampling_with, grow_mask, paint_strokes, polygon_mask}; + use rayon::prelude::*; + + use crate::fill_cmds::{read_window, read_window_mask}; + let CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf } = caf_params(doc, id, p, cmd)?; + let canvas = doc.bounds(); + let cancel = || ctl.cancelled(); + let stop = || if ctl.cancelled() { Err(EngineError::Cancelled) } else { Ok(()) }; + // The fill area: the selection, then the lasso edits, over a rectangle that holds them all. + let grow: i32 = edits.iter().map(|e| if let FillEdit::Grow(b) = e { b.max(&0) } else { &0 }).sum(); + let reach = edits.iter().fold(sb, |r, e| match e { + FillEdit::Lasso { points, .. } => { + points.iter().fold(r, |r, q| r.union(&Rect::new(q[0].floor() as i32, q[1].floor() as i32, q[0].floor() as i32 + 1, q[1].floor() as i32 + 1))) + } + FillEdit::Grow(_) => r, + }); + let er = reach.inflate(grow.saturating_add(1)).intersect(&canvas); + let (ew, eh) = crate::fill_cmds::window_size(er)?; + let ecover = read_window_mask(sel, er, &cancel).ok_or(EngineError::Cancelled)?; + let mut ehole: Vec = ecover.par_iter().map(|c| *c > 0.0).collect(); + for e in &edits { + stop()?; + match e { + FillEdit::Lasso { op, points } => { + let m = polygon_mask(er, points); + for (h, v) in ehole.iter_mut().zip(&m) { + *h = match op { + SelOp::New => *v, + SelOp::Add => *h || *v, + SelOp::Subtract => *h && !*v, + SelOp::Intersect => *h && *v, + }; + } + } + FillEdit::Grow(by) => ehole = grow_mask(&ehole, ew, eh, *by), + } + } + let (bx0, by0, bx1, by1) = mask_bounds(ew, eh, &ehole); + if bx1 <= bx0 { + return Err(bad(cmd, "the fill area is empty")); + } + let hb = Rect::new(er.x0 + bx0 as i32, er.y0 + by0 as i32, er.x0 + bx1 as i32, er.y0 + by1 as i32); + // Photoshop's window (`content_aware::sampling_window`) for Auto and Rectangular; `margin` + // asks for a rectangle that far around the fill area instead. + let window = match sampling.as_str() { + "rectangular" => match int(p, "margin") { + Some(m) => hb.inflate(m.clamp(0, 100_000) as i32), + None => crate::fill_cmds::sampling_window(hb, canvas), + }, + "custom" => match (custom_rect, custom_mask) { + (Some(r), _) => r, + (None, Some(m)) => m.content_bounds(), + (None, None) => hb, + } + .union(&hb) + .inflate(4), + _ => crate::fill_cmds::sampling_window(hb, canvas), + } + .intersect(&canvas); + // Strokes that add to the sampling area may reach past the window. + let rect = strokes.iter().filter(|s| s.add).fold(window, |r, s| r.union(&s.bounds())).intersect(&canvas); let fmt = surf.format(); // Photoshop's Sample All Layers checkbox is off unless the caller asks. When the active // layer has no pixels in the window there is nothing to sample, so that case uses the @@ -412,56 +622,134 @@ fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: & }; let n = fmt.channels(); // Refuse a window too large to read before allocating for it, whatever the sampling (#963). - let (w, h) = crate::fill_cmds::window_size(window)?; - // A background job when started with `Session::start` (#210): reading the window and the - // PatchMatch fill run on a worker against the document snapshot, cancellable per row band. + let (w, h) = crate::fill_cmds::window_size(rect)?; + let pixels = read_window(surf, rect, &cancel).ok_or(EngineError::Cancelled)?; + let (img, layer_px) = if sample_all { + stop()?; + (crate::retouch_cmds::composite_region(doc, Some(id), crate::retouch_cmds::SampleLayers::All, rect, fmt).data, Some(pixels)) + } else { + (pixels, None) + }; + stop()?; + let mut cover = vec![0.0f32; w * h]; + let mut hole = vec![false; w * h]; + cover.par_chunks_mut(w.max(1)).zip(hole.par_chunks_mut(w.max(1))).enumerate().try_for_each(|(y, (crow, hrow))| { + stop()?; + let dy = rect.y0 + y as i32; + if dy < er.y0 || dy >= er.y1 { + return Ok(()); + } + for (x, (c, hl)) in crow.iter_mut().zip(hrow.iter_mut()).enumerate() { + let dx = rect.x0 + x as i32; + if dx >= er.x0 && dx < er.x1 { + let j = (dy - er.y0) as usize * ew + (dx - er.x0) as usize; + let (eh, ec) = (ehole.get(j).copied().unwrap_or(false), ecover.get(j).copied().unwrap_or(0.0)); + *hl = eh; + // Pixels the lasso added are filled outright; selected ones by their coverage. + *c = if eh { if ec > 0.0 { ec } else { 1.0 } } else { 0.0 }; + } + } + Ok::<(), EngineError>(()) + })?; + drop((ecover, ehole)); + // The sampling option's area: Auto keeps what looks like the surroundings within the window, + // Rectangular the whole window, Custom the given area (or nothing, for the brush to add to). + let mut base = vec![false; w * h]; + match sampling.as_str() { + "auto" | "rectangular" => { + let (ww, wh) = (window.width() as usize, window.height() as usize); + let (ox, oy) = ((window.x0 - rect.x0) as usize, (window.y0 - rect.y0) as usize); + let area: Vec = match sampling.as_str() { + "auto" if window == rect => auto_sampling_with(w, h, n, &img, &hole, ctl).map_err(|_| EngineError::Cancelled)?, + "auto" => { + let mut wimg = vec![0.0f32; ww * wh * n]; + let mut whole = vec![false; ww * wh]; + for y in 0..wh { + let s = ((oy + y) * w + ox) * n; + wimg[y * ww * n..(y + 1) * ww * n].copy_from_slice(&img[s..s + ww * n]); + whole[y * ww..(y + 1) * ww].copy_from_slice(&hole[(oy + y) * w + ox..(oy + y) * w + ox + ww]); + } + auto_sampling_with(ww, wh, n, &wimg, &whole, ctl).map_err(|_| EngineError::Cancelled)? + } + _ => vec![true; ww * wh], + }; + for y in 0..wh { + base[(oy + y) * w + ox..(oy + y) * w + ox + ww].copy_from_slice(&area[y * ww..(y + 1) * ww]); + } + } + _ => match (custom_rect, custom_mask) { + (Some(r), _) => base.par_iter_mut().enumerate().for_each(|(i, b)| *b = r.contains(rect.x0 + (i % w) as i32, rect.y0 + (i / w) as i32)), + (None, Some(m)) => { + let v = read_window_mask(m, rect, &cancel).ok_or(EngineError::Cancelled)?; + base.par_iter_mut().zip(&v).for_each(|(b, v)| *b = *v > 0.5); + } + (None, None) => {} + }, + } + stop()?; + base.par_iter_mut().zip(&hole).for_each(|(b, h)| *b &= !*h); + let mut source = base.clone(); + paint_strokes(&mut source, rect, &strokes); + source.par_iter_mut().zip(&hole).for_each(|(s, h)| *s &= !*h); + Ok(CafPlan { layer: id, rect, window, fmt, img, layer_px, cover, hole, base, source, opts, output }) +} + +fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &'static str) -> Result { + use photocraft_algo::content_aware::fill_owned; + // The workspace names the layer it opened on: after an Apply to a new layer that one is + // active, but the fill still samples the original. + let id = match p.get("layer").and_then(Value::as_u64) { + Some(l) => pixel_layer_id(s, LayerId(l)), + None => pixel_layer(s), + } + .map_err(EngineError::Other)?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc = st.doc.clone(); + // Check the params before the job starts. + caf_params(&doc, id, p, cmd)?; + let p = p.clone(); + // A background job when started with `Session::start` (#210): working out the fill area and + // the sampling area, reading the pixels and the PatchMatch fill run on a worker against the + // document snapshot, cancellable per row band. crate::jobs::run( s, label, true, move |ctx| { use rayon::prelude::*; - - use crate::fill_cmds::{read_window, read_window_cover, read_window_mask}; ctx.progress(0.0, label); let cancel = || ctx.cancelled(); - let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; - let img = if sample_all { - if cancel() { - return Err(EngineError::Cancelled); - } - let region = crate::retouch_cmds::composite_region(&doc, None, crate::retouch_cmds::SampleLayers::All, window, fmt); - if cancel() { - return Err(EngineError::Cancelled); - } - region.data - } else { - read_window(surf, window, &cancel).ok_or(EngineError::Cancelled)? - }; - let hole = read_window_cover(&sel, window, &cancel).ok_or(EngineError::Cancelled)?; - let mut source = match (sampling.as_str(), custom_rect, custom_mask.as_ref()) { - ("custom", Some(r), _) => (0..w * h).into_par_iter().map(|i| r.contains(window.x0 + (i % w) as i32, window.y0 + (i / w) as i32)).collect(), - ("custom", None, Some(m)) => read_window_mask(m, window, &cancel).ok_or(EngineError::Cancelled)?.par_iter().map(|v| *v > 0.5).collect(), - _ => vec![true; w * h], - }; - ctx.check()?; - // Auto: only what looks like the selection's surroundings. - if sampling == "auto" { - source = auto_sampling_with(w, h, n, &img, &hole, &photocraft_raster::Interrupt::cancel_only(&cancel)).map_err(|_| EngineError::Cancelled)?; + let plan = content_aware_plan_with(&doc, id, &p, cmd, &photocraft_raster::Interrupt::cancel_only(&cancel))?; + let CafPlan { layer, rect, fmt, img, layer_px, cover, hole, source, opts, output, .. } = plan; + // Patches come only from the sampling area outside the fill area. With none (a + // Rectangular `margin` of 0, a Custom area inside the selection or off the canvas) + // the fill would be black (#6532), so refuse instead. The workspace's preview builds + // the same plan and may show an empty area while the Sampling Brush adds to it. + if !source.iter().any(|s| *s) { + return Err(bad(cmd, "nothing to sample from: the sampling area has no pixels outside the fill area")); } - ctx.check()?; - // The fill changes only the selected pixels: keep the original and the coverage over - // their bounds for the apply step, and fill the window's pixels themselves. + let (w, h) = (rect.width() as usize, rect.height() as usize); + let n = fmt.channels(); + // The fill changes only the fill area: keep the layer's pixels and the coverage over + // its bounds for the apply step, and fill the sampled pixels themselves. let (bx0, by0, bx1, by1) = mask_bounds(w, h, &hole); - let original: Vec = (by0..by1).flat_map(|y| img[(y * w + bx0) * n..(y * w + bx1) * n].iter().copied()).collect(); - let at = |x: usize, y: usize| (window.x0 + x as i32, window.y0 + y as i32); - let ((x0, y0), (x1, y1)) = (at(bx0, by0), at(bx1, by1)); - let cover = read_window_mask(&sel, Rect::new(x0, y0, x1, y1), &cancel).ok_or(EngineError::Cancelled)?; + let own = layer_px.as_deref().unwrap_or(&img); + let original: Vec = (by0..by1).flat_map(|y| own[(y * w + bx0) * n..(y * w + bx1) * n].iter().copied()).collect(); + let cover: Vec = (by0..by1).flat_map(|y| cover[y * w + bx0..y * w + bx1].iter().copied()).collect(); let n_hole = cover.iter().filter(|c| **c > 0.0).count(); - let filled = ctx.stage(0.05, 1.0, label, |ctl| fill_owned(w, h, n, img, &hole, &source, &opts, ctl)).map_err(|_| EngineError::Cancelled)?; - Ok(FilledWindow { filled, bounds: (bx0, by0, bx1, by1), original, cover, n_hole }) + ctx.check()?; + let mut filled = ctx.stage(0.05, 1.0, label, |ctl| fill_owned(w, h, n, img, &hole, &source, &opts, ctl)).map_err(|_| EngineError::Cancelled)?; + // Sampled from all layers: outside the fill area the window keeps the layer's pixels. + if let Some(own) = layer_px { + filled.par_chunks_mut(n.max(1)).zip(own.par_chunks(n.max(1))).zip(hole.par_iter()).for_each(|((f, o), h)| { + if !*h { + f.copy_from_slice(o); + } + }); + } + Ok((layer, rect, fmt, output, FilledWindow { filled, bounds: (bx0, by0, bx1, by1), original, cover, n_hole })) }, - move |s, done| apply_content_aware_fill(s, label, id, &output, fmt, window, done), + move |s, (layer, rect, fmt, output, done)| apply_content_aware_fill(s, label, layer, &output, fmt, rect, done), ) } @@ -1027,18 +1315,18 @@ fn preset_manager(s: &mut Session, p: &Value) -> Result { let new = p.get("newName").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `newName`"))?.to_string(); match kind.as_str() { - "brushes" => { - // A renamed built-in is the user's preset now (and persists as one). - let b = &mut s.tools.presets[i]; - b.name = new; - b.builtin = false; - } + // Same rules as Brush Settings: no duplicate names (case-insensitive), the current + // preset follows, a renamed built-in is the user's preset now (and persists as one). + "brushes" => crate::brush_preset_cmds::rename_at(s, i, &new, cmd)?, "patterns" => s.patterns.items[i].name = new, _ => s.edit_state.custom_shapes[i].name = new, } } "delete" => match kind.as_str() { - "brushes" => drop(s.tools.presets.remove(i)), + "brushes" => { + let gone = s.tools.presets.remove(i); + crate::brush_cmds::forget_deleted_preset(s, &gone.name); + } "patterns" => drop(s.patterns.items.remove(i)), _ => drop(s.edit_state.custom_shapes.remove(i)), }, @@ -1066,6 +1354,7 @@ pub struct PresetFile { pub version: u32, pub brushes: Vec, pub custom_shapes: Vec, + pub tool_presets: Vec, } pub const PRESET_FORMAT: &str = "photocraft-presets"; @@ -1076,7 +1365,7 @@ fn export_import(s: &mut Session, p: &Value) -> Result { .get("kinds") .and_then(Value::as_array) .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) - .unwrap_or_else(|| ["brushes", "customShapes"].iter().map(|k| k.to_string()).collect()); + .unwrap_or_else(|| ["brushes", "customShapes", "tools"].iter().map(|k| k.to_string()).collect()); let want = |k: &str| kinds.iter().any(|x| x == k); match str_or(p, "action", "export") { "export" => { @@ -1095,8 +1384,14 @@ fn export_import(s: &mut Session, p: &Value) -> Result { Vec::new() }, custom_shapes: if want("customShapes") { s.edit_state.custom_shapes.clone() } else { Vec::new() }, + tool_presets: if want("tools") { + let builtins = crate::presets::tools::builtin(); + s.presets.tool_presets.iter().filter(|preset| bool_or(p, "includeBuiltins", false) || !builtins.contains(preset)).cloned().collect() + } else { + Vec::new() + }, }; - Ok(json!({"data": file, "brushes": file.brushes.len(), "customShapes": file.custom_shapes.len()})) + Ok(json!({"data": file, "brushes": file.brushes.len(), "customShapes": file.custom_shapes.len(), "tools": file.tool_presets.len()})) } "import" => { let data = p.get("data").cloned().ok_or_else(|| bad(cmd, "missing `data` (an exported preset file)"))?; @@ -1108,6 +1403,29 @@ fn export_import(s: &mut Session, p: &Value) -> Result { if file.format != PRESET_FORMAT { return Err(bad(cmd, format!("not a preset file (format `{}`)", file.format))); } + // Validate the whole tool import before changing any preset library. + let mut tools = s.presets.tool_presets.clone(); + let nt = if want("tools") { file.tool_presets.len() } else { 0 }; + if nt > crate::presets::tools::MAX_PRESETS { + return Err(bad(cmd, "too many tool presets")); + } + if want("tools") { + for mut preset in file.tool_presets { + preset.name = crate::presets::tools::checked_name(&preset.name, cmd)?; + if preset.tool.trim().is_empty() || !preset.options.is_object() { + return Err(bad(cmd, "tool presets require a non-empty tool and an options object")); + } + if let Some(old) = tools.iter_mut().find(|old| old.name == preset.name && old.tool.eq_ignore_ascii_case(&preset.tool)) { + *old = preset; + } else if tools.iter().any(|old| old.name == preset.name) { + return Err(bad(cmd, "a preset of that name belongs to another tool; rename it before importing")); + } else if tools.len() < crate::presets::tools::MAX_PRESETS { + tools.push(preset); + } else { + return Err(bad(cmd, "too many tool presets")); + } + } + } let (mut nb, mut ns) = (0, 0); if want("brushes") { for mut b in file.brushes { @@ -1132,7 +1450,11 @@ fn export_import(s: &mut Session, p: &Value) -> Result { ns += 1; } } - Ok(json!({"brushes": nb, "customShapes": ns})) + if want("tools") { + s.presets.tool_presets = tools; + s.presets_changed(); + } + Ok(json!({"brushes": nb, "customShapes": ns, "tools": nt})) } other => Err(bad(cmd, format!("unknown action `{other}` (export|import)"))), } @@ -1169,7 +1491,7 @@ pub fn specs() -> Vec { "Content-Aware Fill…", ["Edit"], None, - r##"{"sampling":"auto|rectangular|custom","margin":px?,"area":[x,y,w,h]?,"channel":index|name?,"colorAdaptation":"default|none|high|veryHigh","rotationAdaptation":"none|low|medium|high|full","scale":bool=false,"mirror":bool=false,"sampleAllLayers":bool=false,"output":"current|new|duplicate","seed":u64=1}"##, + r##"{"sampling":"auto|rectangular|custom","margin":px?,"area":[x,y,w,h]?,"channel":index|name?,"samplingStrokes":[{"mode":"add|subtract","size":px,"points":[[x,y],…]}]? (the workspace's Sampling Brush, after the sampling option's area; added strokes may lie outside the window),"fillEdits":[{"op":"new|add|subtract|intersect","points":[[x,y],…]}|{"op":"expand|contract","by":px}]? (the workspace's lasso edits of the fill area, in order),"sampleAllLayers":bool=false,"colorAdaptation":"default|none|high|veryHigh","rotationAdaptation":"none|low|medium|high|full","scale":bool=false,"mirror":bool=false,"output":"current|new|duplicate","layer":id?=active (the layer filled and sampled),"seed":u64=1}"##, can_caf, content_aware_fill ), @@ -1224,7 +1546,7 @@ pub fn specs() -> Vec { "Export/Import Presets…", ["Edit", "Presets"], None, - r##"{"action":"export|import","kinds":["brushes","customShapes"]?,"data":json (import),"includeBuiltins":bool=false}"##, + r##"{"action":"export|import","kinds":["brushes","customShapes","tools"]?,"data":json (import),"includeBuiltins":bool=false}"##, always, export_import ), diff --git a/crates/engine/src/edit_menu_cmds/tests.rs b/crates/engine/src/edit_menu_cmds/tests.rs index f7c2f23e83..16e98b8719 100644 --- a/crates/engine/src/edit_menu_cmds/tests.rs +++ b/crates/engine/src/edit_menu_cmds/tests.rs @@ -57,6 +57,38 @@ fn fade_with_blend_mode_and_invalidation() { assert!(s.execute("edit.fade", json!({"mode": "nonsense"})).is_err()); } +#[test] +fn fade_uniform_layer_mask_invert_at_all_depths() { + for depth in [8, 16, 32] { + for (opacity, expected) in [(0, 1.0), (50, 0.5), (100, 0.0)] { + let mut s = session(depth); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("channel.target", json!({"channel": "mask"})).unwrap(); + let mask_pixel = |s: &Session| { + let layer = active(s); + let mask = &layer.mask.as_ref().unwrap().surface; + mask.pixel(5, 5)[0] + }; + assert!((mask_pixel(&s) - 1.0).abs() < 0.01); + s.execute("image.adjustments.invert", json!({})).unwrap(); + assert!(mask_pixel(&s) < 0.01, "depth {depth}: invert changed the mask"); + assert!(s.edit_state.fade.as_ref().is_some_and(|f| f.mask), "depth {depth}: Fade must target the mask"); + let history_before_fade = s.active().unwrap().history.past_len(); + + s.execute("edit.fade", json!({"opacity": opacity})).unwrap(); + for (x, y) in [(0, 0), (5, 5), (63, 47)] { + let pixel = active(&s).mask.as_ref().unwrap().surface.pixel(x, y)[0]; + assert!((pixel - expected).abs() < 0.02, "depth {depth}, opacity {opacity}, ({x}, {y}): {pixel}"); + } + assert_eq!(s.active().unwrap().history.past_len(), history_before_fade + 1); + assert!(s.undo()); + assert!(mask_pixel(&s) < 0.01, "undo restores inverted mask"); + assert!(s.redo()); + assert!((mask_pixel(&s) - expected).abs() < 0.02, "redo restores faded mask"); + } + } +} + #[test] fn purge_commands() { let mut s = session(8); @@ -105,10 +137,15 @@ fn blob_session(depth: u32) -> Session { fn content_aware_fill_huge_area_neither_panics_nor_wraps() { let mut s = blob_session(8); // `[1e30, 0, 1e30, 10]` overflowed the i32 additions in the area parser (a debug-build - // panic, a garbage sampling window in release); the additions saturate now, so this is - // simply a whole-canvas window. - let r = s.execute("edit.contentAwareFill", json!({"sampling": "custom", "area": [1e30, 0.0, 1e30, 10.0], "colorAdaptation": "none"})).unwrap(); - assert!(r["filled"].as_u64().unwrap() > 100); + // panic, a garbage sampling window in release); the additions saturate now, so the area lies + // wholly right of the canvas: nothing to sample, which is an error, not a black fill (#6532). + let before = s.active().unwrap().doc.clone(); + let past = s.active().unwrap().history.past_len(); + let err = s.execute("edit.contentAwareFill", json!({"sampling": "custom", "area": [1e30, 0.0, 1e30, 10.0], "colorAdaptation": "none"})).unwrap_err(); + assert!(err.to_string().contains("nothing to sample from"), "{err}"); + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &st.doc), "the document changed"); + assert_eq!(st.history.past_len(), past, "a history step was recorded"); // A malformed area names the problem instead of silently falling back. for area in [json!([0.0, 0.0, null, 10.0]), json!([0.0, 0.0, 10.0]), json!("nope")] { let err = s.execute("edit.contentAwareFill", json!({"sampling": "custom", "area": area})).unwrap_err(); @@ -266,6 +303,69 @@ fn content_aware_fill_samples_photoshops_window() { } } +#[test] +fn content_aware_fill_takes_the_workspace_edits() { + // The plan the workspace previews: lasso edits change the fill area (and the window follows), + // sampling-brush strokes change what may be copied, also outside the window. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 275, "y": 175, "width": 50, "height": 50})).unwrap(); + let st = s.active().unwrap(); + let (doc, id) = (st.doc.clone(), st.active_layer.unwrap()); + let plan = |p: Value| content_aware_plan(&doc, id, &p, "edit.contentAwareFill"); + let count = |m: &[bool]| m.iter().filter(|v| **v).count(); + let base = plan(json!({"sampling": "rectangular"})).unwrap(); + assert_eq!((base.window, count(&base.hole)), (Rect::new(200, 100, 400, 300), 2500)); + assert_eq!(count(&base.source), 200 * 200 - 2500); + // A lasso square added beside the selection: a bigger fill area, a window around both. + let p = plan(json!({"sampling": "rectangular", "fillEdits": [{"op": "add", "points": [[340, 175], [390, 175], [390, 225], [340, 225]]}]})).unwrap(); + assert_eq!(count(&p.hole), 5000); + assert!(p.window.width() > 200 && p.window.contains_rect(&Rect::new(275, 175, 390, 225)), "{:?}", p.window); + // Expand by 2 grows the 50 px square to about 54 px (rounded corners). + let p = plan(json!({"sampling": "rectangular", "fillEdits": [{"op": "expand", "by": 2}]})).unwrap(); + assert!((54 * 54 - 20..=54 * 54).contains(&count(&p.hole)), "{}", count(&p.hole)); + // Subtracting it all leaves nothing to fill. + assert!(plan(json!({"fillEdits": [{"op": "subtract", "points": [[0, 0], [600, 0], [600, 400], [0, 400]]}]})).is_err()); + // A subtracting stroke takes a band out of the sampling area; an adding one far away reaches + // past the window, and the plan's rectangle grows to hold it. + let p = plan(json!({"sampling": "rectangular", "samplingStrokes": [{"mode": "subtract", "size": 10, "points": [[210, 110], [390, 110]]}]})).unwrap(); + assert!((count(&base.source) - count(&p.source)).abs_diff(10 * 190) < 60); + let p = plan(json!({"sampling": "rectangular", "samplingStrokes": [{"mode": "add", "size": 20, "points": [[540, 350], [580, 350]]}]})).unwrap(); + assert!(p.rect.contains(560, 350) && !p.window.contains(560, 350)); + assert!(count(&p.source) > count(&base.source) + 600); + // Custom from strokes alone; bad edits are errors. + let p = plan(json!({"sampling": "custom", "samplingStrokes": [{"mode": "add", "size": 20, "points": [[100, 100], [160, 100]]}]})).unwrap(); + assert!((1450..1600).contains(&count(&p.source)), "a 20 px brush along 60 px: {}", count(&p.source)); + for bad in [ + json!({"samplingStrokes": [{"mode": "paint", "size": 10, "points": [[0, 0]]}]}), + json!({"samplingStrokes": [{"size": 0, "points": [[0, 0]]}]}), + json!({"fillEdits": [{"op": "add", "points": [[0, "x"]]}]}), + json!({"fillEdits": [{"op": "expand", "by": -3}]}), + ] { + assert!(plan(bad.clone()).is_err(), "{bad}"); + } + // The command fills with the same plan; `layer` names the layer even when another is active. + let r = s.execute("edit.contentAwareFill", json!({"sampling": "rectangular", "fillEdits": [{"op": "expand", "by": 2}], "layer": id.0})).unwrap(); + assert!(r["filled"].as_u64().unwrap() > 2800); +} + +/// #6532: a sampling area with no pixels outside the fill area is refused instead of filling it +/// black, and leaves the document untouched; any margin past the selection fills. +#[test] +fn content_aware_fill_with_nothing_to_sample_is_refused() { + let mut s = blob_session(8); + let before = px(&s, 30, 22); + let revision = s.active().unwrap().revision; + for p in [json!({"sampling": "rectangular", "margin": 0}), json!({"sampling": "custom", "area": [28, 18, 4, 4]})] { + let e = s.execute("edit.contentAwareFill", p.clone()).unwrap_err().to_string(); + assert!(e.contains("nothing to sample from"), "{p}: {e}"); + assert_eq!(px(&s, 30, 22), before, "{p}: nothing was filled"); + assert_eq!(s.active().unwrap().revision, revision, "{p}: no history step"); + } + s.execute("edit.contentAwareFill", json!({"sampling": "rectangular", "margin": 1})).unwrap(); + assert_ne!(px(&s, 30, 22), before, "the red blob is filled from around the selection"); +} + #[test] fn content_aware_fill_outputs_and_sampling() { let mut s = blob_session(8); @@ -427,6 +527,35 @@ fn define_custom_shape_and_preset_manager() { assert!(t.execute("edit.presets.exportImportPresets", json!({"action": "import", "data": {"format": "other"}})).is_err()); } +#[test] +fn preset_manager_brush_rename_follows_current_preset() { + let mut s = Session::new(); + s.execute("brush.presets.setCurrent", json!({"name": "Chalk"})).unwrap(); + s.execute("edit.presets.presetManager", json!({"action": "rename", "kind": "brushes", "name": "Chalk", "newName": "Chalky"})).unwrap(); + assert_eq!(s.tools.current_preset.as_deref(), Some("Chalky")); + s.execute("brush.presets.update", json!({})).unwrap(); +} + +#[test] +fn preset_manager_brush_rename_refuses_duplicate_name() { + let mut s = Session::new(); + let before: Vec = s.tools.presets.iter().map(|b| b.name.clone()).collect(); + let r = s.execute("edit.presets.presetManager", json!({"action": "rename", "kind": "brushes", "name": "Soft Round", "newName": "hard round"})); + assert!(r.is_err(), "a case-insensitive duplicate name must be refused"); + assert_eq!(s.tools.presets.iter().map(|b| b.name.clone()).collect::>(), before); + // Renaming to a different case of its own name is fine. + s.execute("edit.presets.presetManager", json!({"action": "rename", "kind": "brushes", "name": "Soft Round", "newName": "soft round"})).unwrap(); +} + +#[test] +fn preset_manager_brush_delete_clears_current_preset() { + let mut s = Session::new(); + s.execute("brush.presets.setCurrent", json!({"name": "Chalk"})).unwrap(); + s.execute("edit.presets.presetManager", json!({"action": "delete", "kind": "brushes", "name": "Chalk"})).unwrap(); + assert!(!s.tools.presets.iter().any(|b| b.name == "Chalk")); + assert_eq!(s.tools.current_preset, None); +} + #[test] fn define_brush_preset_wraps_define_from_selection() { let mut s = session(8); @@ -564,3 +693,49 @@ fn fade_allocation_failure_keeps_document_and_history() { assert_eq!(*s.active().unwrap().doc, *before); } } + +#[test] +fn tool_presets_round_trip_through_export_import() { + let mut source = Session::new(); + source.execute("tool.presets.new", json!({"name":"2 : 3", "tool":"crop", "options":{"toolOptions":{"crop_ratio":"2:3"}}})).unwrap(); + let exported = source.execute("edit.presets.exportImportPresets", json!({"action":"export"})).unwrap(); + assert_eq!(exported["tools"], 1); + assert_eq!(exported["data"]["toolPresets"][0]["name"], "2 : 3"); + let mut target = Session::new(); + target.execute("tool.presets.new", json!({"name":"2 : 3", "tool":"crop", "options":{"toolOptions":{"crop_ratio":"1:1"}}})).unwrap(); + for _ in 0..2 { + let result = target.execute("edit.presets.exportImportPresets", json!({"action":"import", "data":exported["data"]})).unwrap(); + assert_eq!(result["tools"], 1); + } + let selected = target.execute("tool.presets.select", json!({"preset":"2 : 3"})).unwrap(); + assert_eq!(selected["options"]["toolOptions"]["crop_ratio"], "2:3"); + assert_eq!(target.presets.tool_presets.iter().filter(|p| p.name == "2 : 3").count(), 1); + let only_brushes = source.execute("edit.presets.exportImportPresets", json!({"kinds":["brushes"]})).unwrap(); + assert_eq!(only_brushes["tools"], 0); + let with_builtins = source.execute("edit.presets.exportImportPresets", json!({"kinds":["tools"], "includeBuiltins":true})).unwrap(); + assert_eq!(with_builtins["tools"].as_u64().unwrap() as usize, source.presets.tool_presets.len()); +} + +#[test] +fn tool_preset_import_is_validated_before_mutation_and_accepts_old_files() { + let mut s = Session::new(); + let before = s.presets.tool_presets.clone(); + for preset in [ + json!({"name":"", "tool":"crop", "options":{}}), + json!({"name":"x".repeat(256), "tool":"crop", "options":{}}), + json!({"name":"Crop", "tool":" ", "options":{}}), + json!({"name":"Crop", "tool":"crop", "options":[]}), + ] { + let result = s.execute( + "edit.presets.exportImportPresets", + json!({"action":"import", "data":{"format":PRESET_FORMAT, "toolPresets":[{"name":"Valid", "tool":"crop", "options":{}}, preset]}}), + ); + assert!(result.is_err()); + assert_eq!(s.presets.tool_presets, before); + } + let too_many: Vec<_> = (0..crate::presets::tools::MAX_PRESETS + 1).map(|i| json!({"name":format!("Crop {i}"), "tool":"crop", "options":{}})).collect(); + assert!(s.execute("edit.presets.exportImportPresets", json!({"action":"import", "data":{"format":PRESET_FORMAT, "toolPresets":too_many}})).is_err()); + assert_eq!(s.presets.tool_presets, before); + let result = s.execute("edit.presets.exportImportPresets", json!({"action":"import", "data":{"format":PRESET_FORMAT, "version":1}})).unwrap(); + assert_eq!(result["tools"], 0); +} diff --git a/crates/engine/src/exr_cmds.rs b/crates/engine/src/exr_cmds.rs index 908942d4fd..5fbc355314 100644 --- a/crates/engine/src/exr_cmds.rs +++ b/crates/engine/src/exr_cmds.rs @@ -52,7 +52,8 @@ fn open_exr_parts(s: &mut Session, p: &Value) -> Result { precomp: p.get("precomp").and_then(Value::as_bool).unwrap_or(false), }; let bytes = read_file(&path)?; - let r = photocraft_io::exr_parts::import(&stem(&path), &bytes, &sel).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let mut r = photocraft_io::exr_parts::import(&stem(&path), &bytes, &sel).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + crate::file_cmds::tag_exr_colorspace(s, &path, &mut r.document); let (i, color) = s.open_document(r.document, Some(path.clone())); Ok(json!({"document": i, "color": color, "warnings": r.warnings})) } @@ -173,6 +174,25 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + /// File Handling › "Open color-less EXR as ACEScg" applies to Open EXR Parts too. + #[test] + fn open_exr_parts_honours_the_aces_cg_preference() { + let dir = std::env::temp_dir().join(format!("pcraft-exr-aces-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("aov.exr"); + write_multipart(&path); + let linear = photocraft_cms::Builtin::LinearSrgb.profile().to_bytes(); + let aces = photocraft_cms::Builtin::AcesCg.profile().to_bytes(); + for (on, want) in [(false, &linear), (true, &aces)] { + let mut s = session(); + s.prefs.edit(|p| p.file_handling.exr_aces_cg = on); + s.execute("file.openExrParts", json!({"path": path.to_str().unwrap(), "part/beauty": true})).unwrap(); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.icc_profile.as_deref().map(|v| v.as_slice()), Some(want.as_slice()), "exr_aces_cg = {on}"); + } + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn open_exr_parts_refuses_an_empty_selection_and_unknown_names() { let dir = std::env::temp_dir().join(format!("pcraft-exr-empty-{}", std::process::id())); diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index c291862167..072a3d4417 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -135,7 +135,7 @@ fn map_pixels(s: &mut Session, label: &str, p: &Value, f: impl FnOnce(Rect, &mut fn stroke(s: &mut Session, p: &Value) -> Result { // Whole pixels, rounded up, as in Photoshop (0.5 px strokes 1 px). let width = p.get("width").and_then(Value::as_f64).filter(|w| w.is_finite()).unwrap_or(1.0).clamp(1.0, 250.0).ceil() as usize; - let color = color_param(p, "color", s.tools.foreground); + let color = color_param("edit.stroke", p, "color", s.tools.foreground)?; // A colour picked as CMYK strokes a CMYK document with the picked inks (#4196). let picked = s.tools.picked_cmyk([color[0], color[1], color[2]]); let mode = match p.get("mode") { @@ -335,15 +335,18 @@ fn clouds(s: &mut Session, p: &Value, difference: bool) -> Result { 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)}"#; +/// 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 { 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)? { - Some(surf) => (crate::transform_cmds::target_bounds(&d.doc, surf), json!({"target": p.get("target")})), + Some(surf) => (crate::transform_cmds::target_frame(&d.doc, surf), json!({"target": p.get("target")})), None => { let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?; let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; - (crate::transform_cmds::transform_bounds(&d.doc, l), json!({"layer": id.0})) + (crate::transform_cmds::transform_frame(&d.doc, l), json!({"layer": id.0})) } }; if b.is_empty() { @@ -869,7 +872,9 @@ pub fn specs() -> Vec { if all == d.doc.bounds() { return Ok(json!({"changed": false})); } - s.execute("image.crop", json!({"x": all.x0, "y": all.y0, "width": all.width(), "height": all.height(), "deleteCroppedPixels": false}))?; + // One History step named as in Photoshop, not the crop's "Crop". + let p = json!({"x": all.x0, "y": all.y0, "width": all.width(), "height": all.height(), "deleteCroppedPixels": false}); + crate::analysis_cmds::compound(s, "Reveal All", |s| s.execute("image.crop", p))?; Ok(json!({"changed": true})) }), spec!( @@ -1469,6 +1474,49 @@ mod tests { assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]); } + /// #6928: with a selection, the presets flip and turn about the selection's own bounds, as + /// in Photoshop: Select All mirrors across the canvas, a marquee across its own centre. + /// Without a selection they keep turning about the content (above). + #[test] + fn transform_presets_turn_about_the_selection() { + let mut s = session(8); + paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]); + paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]); + let green = vec![0.0, 1.0, 0.0, 1.0]; + // Select All on the 40 × 30 canvas: across the canvas's centre lines. + s.execute("select.all", json!({})).unwrap(); + let past = s.active().unwrap().history.past_len(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 14)); + assert_eq!(pixel(&s, 29, 10), green); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step"); + s.execute("edit.transform.flipVertical", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 16, 30, 20)); + assert_eq!(pixel(&s, 29, 19), green); + s.execute("edit.transform.rotate180", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + assert_eq!(pixel(&s, 10, 10), green); + // A marquee (0, 0)–(24, 30) holding the whole square: across x = 12. + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 24, "height": 30})).unwrap(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(4, 10, 14, 14)); + assert_eq!(pixel(&s, 13, 10), green); + // Undo puts it back where it was. + s.undo(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + // A targeted alpha channel turns about the selection's bounds too. + s.execute("channel.new", json!({})).unwrap(); + s.edit("paint channel", |doc, _| { + doc.channels[0].surface.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); + Ok(()) + }) + .unwrap(); + s.execute("channel.target", json!({"channel": 0})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.channels[0].surface.content_bounds(), Rect::new(20, 10, 30, 20)); + } + #[test] fn reselect_restores_the_last_selection() { let mut s = session(8); @@ -1714,8 +1762,12 @@ mod tests { s.execute("layer.translate", json!({"dx": 0, "dy": 0})).ok(); paint_square(&mut s, Rect::new(-5, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]); assert_eq!(reveal_all_bounds(doc(&s)), Rect::new(-5, 0, 40, 30)); + let steps = s.active().unwrap().history.past_len(); s.execute("image.revealAll", json!({})).unwrap(); assert_eq!((doc(&s).size.width, doc(&s).size.height), (45, 30)); + let history = &s.active().unwrap().history; + assert_eq!(history.past_len(), steps + 1, "one step"); + assert_eq!(history.entries().last().map(String::as_str), Some("Reveal All"), "named as in Photoshop, not Crop"); assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false); } diff --git a/crates/engine/src/face_cmds.rs b/crates/engine/src/face_cmds.rs new file mode 100644 index 0000000000..d48df95b84 --- /dev/null +++ b/crates/engine/src/face_cmds.rs @@ -0,0 +1,115 @@ +//! Face detection (#3603): the faces in the document, with their box and five landmarks, from +//! [`photocraft_algo::faces`]. Select › Color Range's Detect Faces and Face-Aware Liquify read +//! faces through [`faces_in`]; `image.detectFaces` reports them to scripts and agents. + +use photocraft_algo::faces::{self, Face}; +use photocraft_doc::{Document, LayerId}; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +/// Faces scoring below this are left out unless asked for (libfacedetection's own threshold for a +/// reliable face). +pub const MIN_SCORE: f32 = 0.5; + +/// Why there are no faces in the browser build (see [`photocraft_algo::faces`]). +const UNAVAILABLE: &str = "face detection isn't available in the browser version of PhotoCraft; use the desktop app"; + +/// The faces in `px` (`w × h` straight RGBA), as [`faces::detect`] finds them. +pub fn detect(px: &[[f32; 4]], w: usize, h: usize, min_score: f32) -> Result> { + if !faces::AVAILABLE { + return Err(EngineError::Other(UNAVAILABLE.into())); + } + faces::detect(px, w, h, min_score).ok_or_else(|| EngineError::Other("face detection failed".into())) +} + +/// The faces in `doc`, best first: in the composite, or in the active layer's pixels when +/// `all_layers` is off. Coordinates are document pixels. +pub fn faces_in(doc: &Document, active: Option, all_layers: bool, min_score: f32) -> Result> { + let area = doc.bounds(); + let (w, h) = (area.width() as usize, area.height() as usize); + let surface = active.and_then(|id| doc.layer(id)).and_then(|l| l.surface()).filter(|_| !all_layers); + let px = match surface { + Some(surf) => { + let mut px = vec![[0.0f32; 4]; w * h]; + surf.read_rgba_into(area, &mut px); + px + } + None => photocraft_compose::render(doc, area).px, + }; + let found = detect(&px, w, h, min_score)?; + let (x0, y0) = (area.x0 as f32, area.y0 as f32); + Ok(found + .into_iter() + .map(|f| Face { rect: [f.rect[0] + x0, f.rect[1] + y0, f.rect[2], f.rect[3]], landmarks: f.landmarks.map(|[x, y]| [x + x0, y + y0]), ..f }) + .collect()) +} + +fn face_json(f: &Face) -> Value { + let pt = |i: usize| json!([f.landmarks[i][0], f.landmarks[i][1]]); + json!({ + "score": f.score, + "rect": f.rect, + "landmarks": {"rightEye": pt(0), "leftEye": pt(1), "nose": pt(2), "mouthRight": pt(3), "mouthLeft": pt(4)}, + }) +} + +fn detect_faces(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "image.detectFaces"; + let bad = |msg: &str| EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }; + let min_score = match p.get("minScore") { + None => MIN_SCORE, + Some(v) => v.as_f64().filter(|v| (0.0..=1.0).contains(v)).ok_or_else(|| bad("minScore must be a number in 0..1"))? as f32, + }; + let all_layers = match p.get("sampleAllLayers") { + None => true, + Some(v) => v.as_bool().ok_or_else(|| bad("sampleAllLayers must be true or false"))?, + }; + let d = s.active().ok_or(EngineError::NoDocument)?; + let found = faces_in(&d.doc, d.active_layer, all_layers, min_score)?; + Ok(json!({ "faces": found.iter().map(face_json).collect::>() })) +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: "image.detectFaces", + label: "Detect Faces", + menu: &[], + shortcut: None, + params: r##"{"minScore":0..1=0.5,"sampleAllLayers":bool=true} → {"faces":[{"score","rect":[x,y,w,h],"landmarks":{"rightEye","leftEye","nose","mouthRight","mouthLeft"}: [x,y] each},…]} (best first; "rightEye" is the one on the image's left)"##, + enabled: |s| { + if !faces::AVAILABLE { + return Err(UNAVAILABLE.into()); + } + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) + }, + run: detect_faces, + journal: false, + }] +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::Session; + + #[test] + fn detect_faces_reports_no_faces_on_a_plain_image_and_validates_params() { + let mut s = Session::new(); + assert!(s.execute("image.detectFaces", json!({})).is_err(), "no document"); + assert!(!s.is_enabled("image.detectFaces")); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + assert!(s.is_enabled("image.detectFaces")); + s.execute("select.all", json!({})).unwrap(); + assert_eq!(s.execute("image.detectFaces", json!({})).unwrap(), json!({"faces": []})); + assert_eq!(s.execute("image.detectFaces", json!({"minScore": 0, "sampleAllLayers": false})).unwrap(), json!({"faces": []})); + // No history step of its own: Undo undoes the Select All before it. + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); + for bad in [json!({"minScore": 2}), json!({"minScore": "high"}), json!({"sampleAllLayers": 1})] { + assert!(s.execute("image.detectFaces", bad.clone()).is_err(), "{bad}"); + } + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 43828b76b1..f9cee9e214 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -219,6 +219,45 @@ pub(crate) fn stem(path: &str) -> String { } } +/// Whether `a` and `b` name the same file: the same text, or, when both exist, the same file on +/// disk (a hard link, a different case on a case-insensitive volume, `./` or `..` in one of them). +pub fn same_file(a: &str, b: &str) -> bool { + if a == b { + return true; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { + return x.dev() == y.dev() && x.ino() == y.ino(); + } + } + #[cfg(windows)] + { + // The volume serial number and file index of each, as unix compares dev and inode, so a + // hard link (another name for the file) is the same file. + if let Ok(same) = same_file::is_same_file(a, b) { + return same; + } + // Should a file not open: NTFS and FAT compare names without case. + if let (Ok(x), Ok(y)) = (std::fs::canonicalize(a), std::fs::canonicalize(b)) { + return x.to_string_lossy().to_lowercase() == y.to_string_lossy().to_lowercase(); + } + } + false +} + +/// A path as command results report it: `/` between components, whatever the platform. +/// +/// `join` already builds with `/`, but a directory from the caller or from `std::path::absolute` +/// carries the native separator, which would leave a reported path mixed. The control channel +/// takes `/` and rejects alternate separators (`AuthorizedWorkspace` in `crates/automation`), so +/// a result spelt this way can be handed straight back to it. Verbatim and UNC prefixes keep +/// theirs: Win32 does not accept `/` after a leading `\\`. +pub(crate) fn forward_slashes(path: String) -> String { + if path.starts_with(r"\\") { path } else { path.replace('\\', "/") } +} + pub(crate) fn join(dir: &str, name: &str) -> String { if dir.is_empty() { name.to_string() @@ -249,8 +288,8 @@ pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { Ok(r.document) } -/// What a headless save writes beyond the format: JPEG quality, TIFF layers, Targa bits, PSD -/// previews and the PSD merged image. +/// What a headless save writes beyond the format: JPEG quality, TIFF layers, Targa bits, DPX +/// bits, DDS compression and mipmaps, PSD previews and the PSD merged image. #[derive(Debug, Clone, Copy)] pub(crate) struct SaveOpts { /// Photoshop's 0–12 JPEG scale. @@ -262,6 +301,9 @@ pub(crate) struct SaveOpts { pub tga_bits: Option, /// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16. pub dpx_bits: Option, + /// DDS: the compression and whether to write the mip chain (`"ddsCompression"`, + /// `"ddsMipmaps"`); unset, uncompressed without mipmaps. + pub dds: photocraft_io::DdsOptions, /// PSD/PSB: embed the thumbnail resource (Preferences › File Handling › Image Previews). pub image_previews: bool, /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB @@ -271,7 +313,15 @@ pub(crate) struct SaveOpts { impl Default for SaveOpts { fn default() -> Self { - SaveOpts { quality: None, tiff_layers: false, tga_bits: None, dpx_bits: None, image_previews: true, psd_maximize_compatibility: true } + SaveOpts { + quality: None, + tiff_layers: false, + tga_bits: None, + dpx_bits: None, + dds: photocraft_io::DdsOptions::default(), + image_previews: true, + psd_maximize_compatibility: true, + } } } @@ -287,6 +337,7 @@ impl SaveOpts { tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits: tga_bits_param(p, cmd)?, dpx_bits: dpx_bits_param(p, cmd)?, + dds: dds_param(p, cmd)?.unwrap_or_default(), image_previews: file_handling.image_previews != crate::prefs::Ask::Never, psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never, }) @@ -331,6 +382,30 @@ pub fn dpx_bits_param(p: &Value, cmd: &str) -> Result Result> { + let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg }; + let compression = match p.get("ddsCompression") { + None | Some(Value::Null) => None, + Some(v) => Some( + v.as_str() + .and_then(photocraft_io::DdsCompression::from_name) + .ok_or_else(|| bad(format!("`ddsCompression` must be \"none\", \"bc1\", \"bc2\" or \"bc3\", got {v}")))?, + ), + }; + let mipmaps = match p.get("ddsMipmaps") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_bool().ok_or_else(|| bad(format!("`ddsMipmaps` must be true or false, got {v}")))?), + }; + if compression.is_none() && mipmaps.is_none() { + return Ok(None); + } + Ok(Some(photocraft_io::DdsOptions { compression: compression.unwrap_or_default(), mipmaps: mipmaps.unwrap_or(false) })) +} + /// Encodes `doc` for `path`'s extension. pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> Result<(Vec, Vec)> { crate::allocation::checkpoint("saving document")?; @@ -340,12 +415,15 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> R tga_bits: save.tga_bits, image_previews: save.image_previews, psd_maximize_compatibility: save.psd_maximize_compatibility, + // Linked files a PSD embeds are resolved against the document being worked on. + document_path: crate::doc_path::current(), ..Default::default() }; // No quality chosen: write the file the way it was opened (a JPEG at its own quality, a WebP // lossy or lossless as it was), as Photoshop's Save does. photocraft_io::apply_file_encoding(doc, &mut opts.encode); opts.encode.dpx_bits = save.dpx_bits; + opts.encode.dds = save.dds; if let Some(q) = save.quality { let q = (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8; opts.encode.jpeg_quality = q; @@ -445,6 +523,15 @@ fn revert(s: &mut Session) -> Result { fn save_a_copy(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path", "file.saveACopy")?.to_string(); let d = s.active().ok_or(EngineError::NoDocument)?; + // A copy over the document's own file replaces it, and a flat or lossy format can't be + // undone, so it takes an explicit `overwrite` (#7437). The desktop dialog writes through the + // shell, after the OS has confirmed the replace. + if d.path.as_deref().is_some_and(|own| same_file(&path, own)) && p.get("overwrite").and_then(Value::as_bool) != Some(true) { + return Err(EngineError::BadParams { + cmd: "file.saveACopy".into(), + msg: "`path` is the document's own file, so the copy would replace it: choose another path, or pass \"overwrite\": true".into(), + }); + } let mut doc = (*d.doc).clone(); if p.get("layers").and_then(Value::as_bool) == Some(false) { // "Layers" unchecked in Save a Copy: write the flattened image. @@ -461,7 +548,7 @@ fn save_a_copy(s: &mut Session, p: &Value) -> Result { /// With File Handling's ACEScg option on, such an EXR opens as ACEScg instead (AP1, /// linear) — the working space ACES render pipelines write. Only the io default is /// replaced; an embedded or EXIF-declared profile is kept untouched. -fn tag_exr_colorspace(s: &Session, name: &str, doc: &mut Document) { +pub(crate) fn tag_exr_colorspace(s: &Session, name: &str, doc: &mut Document) { if !name.to_ascii_lowercase().ends_with(".exr") || !s.prefs.get().file_handling.exr_aces_cg { return; } @@ -578,7 +665,16 @@ fn place(s: &mut Session, p: &Value, linked: bool) -> Result { let cmd = if linked { "file.placeLinked" } else { "file.placeEmbedded" }; let path = str_param(p, "path", cmd)?.to_string(); let bytes = read_file(&path)?; - place_bytes(s, &path, bytes, linked.then(|| path.clone()), p) + // The link is stored absolute: a relative one would later be taken from the document's + // folder (`doc_path`), not the working directory the path was given in. + let link = linked.then(|| { + if std::path::Path::new(&path).is_relative() { + std::path::absolute(&path).map_or_else(|_| path.clone(), |a| a.to_string_lossy().into_owned()) + } else { + path.clone() + } + }); + place_bytes(s, &path, bytes, link, p) } // ---------- File Info (XMP) ---------- @@ -1234,10 +1330,12 @@ fn has_live_effects(l: &Layer) -> bool { l.effects.enabled && l.effects.items.iter().any(|e| e.enabled()) } -/// The layer rendered alone (keeping what `keep` says), as a surface in `fmt`. With `apply_mask` -/// off the layer's pixel and vector masks are left out of the render, so a caller that keeps them -/// live on the baked raster does not mask the pixels twice. -fn bake(l: &Layer, canvas: Rect, fmt: PixelFormat, keep_effects: bool, apply_mask: bool) -> Surface { +/// The layer of `doc` rendered alone (keeping what `keep` says) with the document's Global Light, +/// patterns and canvas, as a surface in the document's format. With `apply_mask` off the layer's +/// pixel and vector masks are left out of the render, so a caller that keeps them live on the +/// baked raster does not mask the pixels twice. +fn bake(doc: &Document, l: &Layer, keep_effects: bool, apply_mask: bool) -> Surface { + let canvas = doc.bounds(); let mut tmp = l.clone(); tmp.opacity = 1.0; tmp.blend = photocraft_color::BlendMode::Normal; @@ -1254,7 +1352,7 @@ fn bake(l: &Layer, canvas: Rect, fmt: PixelFormat, keep_effects: bool, apply_mas // Render over the union of the canvas and the content so off-canvas pixels survive. let area = l.surface().map_or(canvas, |s| s.content_bounds().union(&canvas)); let area = if keep_effects { area.inflate(256) } else { area }; - buffer_surface(&photocraft_compose::render_layer(&tmp, area), fmt) + buffer_surface(&photocraft_compose::render_layer_in(doc, &tmp, area), doc.pixel_format()) } fn walk_ids(doc: &Document) -> Vec { @@ -1264,8 +1362,6 @@ fn walk_ids(doc: &Document) -> Vec { fn flatten_all_effects(s: &mut Session) -> Result { let mut n = 0; s.edit("Flatten All Layer Effects", |doc, _| { - let canvas = doc.bounds(); - let fmt = doc.pixel_format(); for id in walk_ids(doc) { let Some(l) = doc.layer(id) else { continue }; if !has_live_effects(l) || matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) { @@ -1273,7 +1369,7 @@ fn flatten_all_effects(s: &mut Session) -> Result { } // The pixel and vector masks stay on the layer (baking must not destroy them), so the // pixels are baked without them and each mask then applies once to the baked raster. - let px = bake(l, canvas, fmt, true, false); + let px = bake(doc, l, true, false); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; l.content = LayerContent::Raster(px); l.effects = Default::default(); @@ -1290,8 +1386,6 @@ fn flatten_all_effects(s: &mut Session) -> Result { fn flatten_all_masks(s: &mut Session) -> Result { let (mut n, mut skipped) = (0, 0); s.edit("Flatten All Masks", |doc, _| { - let canvas = doc.bounds(); - let fmt = doc.pixel_format(); for id in walk_ids(doc) { let Some(l) = doc.layer(id) else { continue }; let masked = l.mask.as_ref().is_some_and(|m| m.enabled) || l.vector_mask.is_some(); @@ -1304,7 +1398,7 @@ fn flatten_all_masks(s: &mut Session) -> Result { skipped += 1; continue; } - let px = bake(l, canvas, fmt, false, true); + let px = bake(doc, l, false, true); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; l.content = LayerContent::Raster(px); l.mask = None; @@ -1432,7 +1526,7 @@ fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer]) -> String { lattice.layers.push(a); } let out = photocraft_compose::flatten(&lattice); - let mut s = format!("TITLE \"{}\"\n# Created by Photocraft\nLUT_3D_SIZE {n}\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n", title.replace('"', "'")); + let mut s = format!("TITLE \"{}\"\n# Created by PhotoCraft\nLUT_3D_SIZE {n}\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n", title.replace('"', "'")); // .cube order: red changes fastest, then green, then blue. for b in 0..n { for g in 0..n { @@ -1594,7 +1688,7 @@ pub fn specs() -> Vec { "Save a Copy…", &["File"], Some("Cmd+Alt+S"), - r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)}"##, + r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)}"##, native_doc, save_a_copy ), @@ -1657,7 +1751,7 @@ pub fn specs() -> Vec { "Batch…", &["File", "Automate"], None, - r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, batch ), @@ -1666,7 +1760,7 @@ pub fn specs() -> Vec { "Image Processor…", &["File", "Scripts"], None, - r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, image_processor ), @@ -1694,7 +1788,7 @@ pub fn specs() -> Vec { "Layers to Files…", &["File", "Export"], None, - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)} → {files}"##, native_doc, layers_to_files ), @@ -1761,4 +1855,38 @@ mod aces_exr_tests { let d = &s.active().unwrap().doc; assert_eq!(d.icc_profile.as_deref().map(|v| v.as_slice()), Some(aces.as_slice())); } + + /// The desktop app opens files as background jobs (File > Open, drag-drop, Open Recent): + /// the ACEScg preference applies there too, not only to `file.openAs`. + #[test] + fn exr_aces_cg_preference_applies_to_background_opens() { + use crate::jobs::{OpenSource, Started}; + let image = photocraft_codecs::Image::from_f32(4, 4, photocraft_codecs::ChannelLayout::Rgb, &[0.5; 48]).unwrap(); + let bytes = + std::sync::Arc::new(photocraft_codecs::encode(&image, photocraft_codecs::Format::OpenExr, &photocraft_codecs::EncodeOptions::default()).unwrap()); + let linear = photocraft_cms::Builtin::LinearSrgb.profile().to_bytes(); + let aces = photocraft_cms::Builtin::AcesCg.profile().to_bytes(); + for (on, want) in [(false, &linear), (true, &aces)] { + let mut s = Session::new(); + s.prefs.edit(|p| p.file_handling.exr_aces_cg = on); + let v = match s.start_open("shot.exr", OpenSource::Bytes(std::sync::Arc::clone(&bytes))).unwrap() { + Started::Job(id) => s.wait_job(id).unwrap(), + Started::Done(v) => v, + }; + // ACEScg isn't the working space, so Ask When Opening holds it for the prompt, which + // names the ACEScg profile; linear sRGB (io's HDR default) opens without asking. + let profile = match v.get("held").and_then(Value::as_u64) { + Some(held) => { + assert!(on, "{v}"); + assert!(v["color"]["embedded"].as_str().unwrap().starts_with("ACEScg"), "{v}"); + s.take_held_open(held).unwrap().0.icc_profile + } + None => { + assert!(v.get("document").is_some(), "{v}"); + s.active().unwrap().doc.icc_profile.clone() + } + }; + assert_eq!(profile.as_deref().map(|v| v.as_slice()), Some(want.as_slice()), "exr_aces_cg = {on}"); + } + } } diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs index 3cc72c30c4..167ddfb898 100644 --- a/crates/engine/src/file_cmds/tests.rs +++ b/crates/engine/src/file_cmds/tests.rs @@ -135,6 +135,44 @@ fn save_a_copy_keeps_path_and_dirty_state() { assert!(s.execute("file.saveACopy", json!({})).is_err()); } +/// A copy over the document's own file, however the path is spelt, would replace it (a lossy +/// re-encode can't be undone), so it is refused unless `overwrite` is passed (#7437). +#[test] +fn save_a_copy_refuses_the_documents_own_file() { + let dir = tmp("copy-own"); + let path = png(&dir, "own.png", 6, 4, "#ff0000"); + let bytes = std::fs::read(&path).unwrap(); + let mut s = Session::new(); + open_bytes_as(&mut s, &path, &bytes, None, Some(path.clone())).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + let link = join(&dir, "link.png"); + std::fs::hard_link(&path, &link).unwrap(); + let rev = s.active().unwrap().revision; + for p in [path.clone(), format!("{dir}/./own.png"), link] { + let r = s.execute("file.saveACopy", json!({"path": p})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("overwrite")), "{p}: {r:?}"); + assert!(s.execute("file.saveACopy", json!({"path": p, "overwrite": false})).is_err(), "{p}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "{p}"); + let st = s.active().unwrap(); + assert_eq!(st.path.as_deref(), Some(path.as_str()), "{p}"); + assert_eq!(st.revision, rev, "{p}"); + assert!(st.is_dirty(), "{p}"); + } + let other = join(&dir, "other.png"); + s.execute("file.saveACopy", json!({"path": other})).unwrap(); + assert!(std::fs::metadata(&other).unwrap().len() > 0); + s.execute("file.saveACopy", json!({"path": path, "overwrite": true})).unwrap(); + assert_ne!(std::fs::read(&path).unwrap(), bytes); + assert_eq!(s.active().unwrap().path.as_deref(), Some(path.as_str())); + assert!(s.active().unwrap().is_dirty()); + + // A document that was never saved has no file of its own: it copies anywhere, as before. + let mut fresh = session(4, 4, 8); + fresh.execute("file.saveACopy", json!({"path": path})).unwrap(); + assert_eq!(fresh.active().unwrap().path, None); +} + /// `tgaBits` picks the Targa's bits per pixel (byte 16 of the header); unset, a document with an /// alpha channel is written as 32-bit, with the channel as the alpha. #[test] @@ -181,6 +219,53 @@ fn save_a_copy_writes_the_dpx_bits_asked_for() { } } +/// `ddsCompression` picks the DDS FourCC (or none, uncompressed) and `ddsMipmaps` the mip count +/// in the header; unset, an uncompressed texture without mipmaps. Bad values are refused before +/// anything is written. +#[test] +fn save_a_copy_writes_the_dds_options_asked_for() { + let dir = tmp("dds-options"); + let le32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()); + for (params, fourcc, mips) in [ + (json!({}), [0; 4], 1), + (json!({"ddsCompression": "none", "ddsMipmaps": true}), [0; 4], 5), + (json!({"ddsCompression": "bc1"}), *b"DXT1", 1), + (json!({"ddsCompression": "DXT3", "ddsMipmaps": false}), *b"DXT3", 1), + (json!({"ddsCompression": "bc3", "ddsMipmaps": true}), *b"DXT5", 5), + (json!({"ddsCompression": null, "ddsMipmaps": null}), [0; 4], 1), + ] { + let mut s = session(16, 12, 8); + let out = join(&dir, "a.dds"); + let mut p = params.clone(); + p["path"] = json!(out); + s.execute("file.saveACopy", p).unwrap(); + let bytes = std::fs::read(&out).unwrap(); + assert_eq!((&bytes[..4], &bytes[84..88], le32(&bytes, 28)), (&b"DDS "[..], &fourcc[..], mips), "{params}"); + assert_eq!(photocraft_io::import("a.dds", &bytes).unwrap().document.size, photocraft_geom::Size::new(16, 12), "{params}"); + } + let mut s = session(8, 8, 8); + let state = |s: &Session| s.active().map(|st| (st.revision, st.path.clone(), st.is_dirty())); + let before = state(&s); + for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsCompression": 1}), json!({"ddsMipmaps": "yes"}), json!({"ddsMipmaps": 1})] { + let out = join(&dir, "bad.dds"); + let mut p = bad.clone(); + p["path"] = json!(out); + let r = s.execute("file.saveACopy", p); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert!(!std::path::Path::new(&out).exists(), "{bad}: nothing written"); + assert_eq!(state(&s), before, "{bad}: the document is untouched"); + } +} + +#[test] +fn dds_params_are_none_until_one_is_given() { + use photocraft_io::{DdsCompression, DdsOptions}; + assert_eq!(dds_param(&json!({}), "file.saveAs").unwrap(), None); + assert_eq!(dds_param(&json!({"ddsCompression": null}), "file.saveAs").unwrap(), None); + assert_eq!(dds_param(&json!({"ddsMipmaps": true}), "file.saveAs").unwrap(), Some(DdsOptions { compression: DdsCompression::None, mipmaps: true })); + assert_eq!(dds_param(&json!({"ddsCompression": "bc2"}), "file.saveAs").unwrap(), Some(DdsOptions { compression: DdsCompression::Bc2, mipmaps: false })); +} + /// A `tgaBits` other than 24 or 32 is a bad parameter, reported before anything is written. #[test] fn bad_targa_bits_are_refused_before_writing() { @@ -709,6 +794,74 @@ fn flatten_all_layer_effects_keeps_masks() { } } +/// Flattens all layer effects on a red square carrying `fx` (in a document prepared by `setup`) +/// and asserts the composite did not change: the bake uses the document's own context (#5719). +fn assert_flatten_effects_is_a_no_op(depth: u32, setup: impl FnOnce(&mut Document), fx: photocraft_doc::Effect) { + let mut s = session(40, 40, depth); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 14, "y": 14, "width": 12, "height": 12})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + s.edit("fx", |doc, _| { + setup(doc); + let l = doc.layer_mut(id).unwrap(); + l.effects.enabled = true; + l.effects.items.push(fx); + Ok(()) + }) + .unwrap(); + let before = photocraft_compose::flatten(doc(&s)); + assert_eq!(s.execute("file.scripts.flattenAllLayerEffects", json!({})).unwrap()["flattened"], 1); + let after = photocraft_compose::flatten(doc(&s)); + for (i, (a, b)) in after.px.iter().zip(&before.px).enumerate() { + for k in 0..4 { + assert!((a[k] - b[k]).abs() < 0.02, "depth {depth}: pixel ({}, {}) changed: {b:?} -> {a:?}", i % 40, i / 40); + } + } +} + +/// A Drop Shadow that uses Global Light is baked at the document's angle, not the default 120°. +#[test] +fn flatten_all_layer_effects_uses_the_documents_global_light() { + for depth in [8, 16, 32] { + let shadow = photocraft_doc::Effect::DropShadow(photocraft_doc::effects::Shadow { + common: photocraft_doc::effects::FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), + color: photocraft_color::Color::rgb(0.0, 0.0, 1.0), + angle: 120.0, + use_global_light: true, + distance: 10.0, + spread: 0.0, + size: 0.0, + contour: photocraft_doc::effects::Contour::Linear, + anti_alias: false, + noise: 0.0, + knocks_out: true, + }); + assert_flatten_effects_is_a_no_op(depth, |d| d.global_light.angle = 0.0, shadow); + } +} + +/// A Pattern Overlay of a document pattern survives the bake instead of vanishing. +#[test] +fn flatten_all_layer_effects_keeps_a_pattern_overlay() { + for depth in [8, 16, 32] { + let mut tile = photocraft_raster::Surface::new(PixelFormat::new(ColorMode::Rgb, photocraft_color::SampleType::U8, true)); + tile.fill_rect(Rect::new(0, 0, 2, 2), &[0.0, 1.0, 0.0, 1.0]); + let pat = photocraft_doc::Pattern::new("green", tile, 2, 2); + let overlay = photocraft_doc::Effect::PatternOverlay { + common: photocraft_doc::effects::FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), + name: pat.name.clone(), + id: pat.id.clone(), + scale: 1.0, + angle: 0.0, + link: true, + phase: (0.0, 0.0), + }; + assert_flatten_effects_is_a_no_op(depth, |d| d.patterns.push(pat), overlay); + } +} + #[test] fn layers_to_files_writes_each_visible_layer() { let dir = tmp("layers"); @@ -1033,7 +1186,7 @@ fn reveal_in_finder_reveals_the_documents_saved_path() { let path = "/tmp/pics/a.psd"; s.active_mut().unwrap().path = Some(path.into()); let r = s.execute("file.revealInFinder", json!({"dryRun": true})).unwrap(); - let (program, args) = crate::layer_menu_cmds::reveal_command(path); + let (program, args) = crate::layer_menu_cmds::reveal_command(path).unwrap(); assert_eq!(r["program"], json!(program)); assert_eq!(r["args"], json!(args)); // The tab menu names a background tab: the active document is not the one revealed. diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rs index 2aa0a02bdc..c35ed9774b 100644 --- a/crates/engine/src/fill_cmds.rs +++ b/crates/engine/src/fill_cmds.rs @@ -106,7 +106,7 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { let source = match contents { "foreground" => color_source(s, s.tools.foreground), "background" => color_source(s, s.tools.background), - "color" => color_source(s, color_param(p, "color", s.tools.foreground)), + "color" => color_source(s, color_param(CMD, p, "color", s.tools.foreground)?), "black" => Source::Color([0.0, 0.0, 0.0, 1.0]), "gray" => Source::Color([128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]), "white" => Source::Color([1.0; 4]), @@ -334,30 +334,6 @@ pub(crate) fn read_window(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool if cancelled() { None } else { Some(out) } } -/// Which pixels of `r` a selection (or mask) covers at all: channel 0 above zero, read in -/// parallel bands as [`read_window`] does, without holding the coverage itself. -pub(crate) fn read_window_cover(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool + Sync)) -> Option> { - use rayon::prelude::*; - const BAND: usize = 64; - let n = surf.channels().max(1); - let (w, h) = (r.width() as usize, r.height() as usize); - let mut out = vec![false; w * h]; - if out.is_empty() { - return Some(out); - } - out.par_chunks_mut(BAND * w).enumerate().for_each_init(Vec::new, |buf, (i, chunk)| { - if cancelled() { - return; - } - let y0 = r.y0 + (i * BAND) as i32; - surf.read_region_into(Rect::new(r.x0, y0, r.x1, y0 + (chunk.len() / w) as i32), buf); - for (o, px) in chunk.iter_mut().zip(buf.chunks_exact(n)) { - *o = px[0] > 0.0; - } - }); - if cancelled() { None } else { Some(out) } -} - /// Channel 0 of [`read_window`] (a selection's or an alpha channel's coverage). pub(crate) fn read_window_mask(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool + Sync)) -> Option> { use rayon::prelude::*; diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index e40be7b6ac..dd0ff8c803 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -292,6 +292,11 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result let surf = match &mut l.content { LayerContent::Raster(surf) => surf, LayerContent::Smart(_) => { + // A smart filter re-renders from its params alone, without the document's + // channels, so Lens Blur's alpha-channel depth would be lost (#7400). + if matches!(fp, FilterParams::LensBlur { depth: algo::DepthSource::Channel, .. }) { + return Err(EngineError::Other("Lens Blur can't read an alpha channel as depth on a Smart Object: rasterize the layer first".into())); + } // Non-destructive: record the filter and re-render the smart object from its source. let sf = SmartFilter { command: id.clone(), params: params.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true }; @@ -313,7 +318,7 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result } /// Lock transparency: put the layer's alpha back after a filter, in the tiles it changed. -fn keep_alpha(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) { +pub(crate) fn keep_alpha(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) { if old.format() != new.format() || !new.format().alpha { return; } diff --git a/crates/engine/src/filters/validation.rs b/crates/engine/src/filters/validation.rs index 068d37e9da..b2359ffa57 100644 --- a/crates/engine/src/filters/validation.rs +++ b/crates/engine/src/filters/validation.rs @@ -123,9 +123,11 @@ fn choices(id: &str) -> Option<&'static [(&'static str, &'static str)]> { "filter.distort.zigZag" => &[("style", "pondRipples|outFromCenter|aroundCenter")], "filter.render.lensFlare" => &[("lens", "zoom|prime35|prime105|moviePrime")], "filter.render.lightingEffects" => &[("lightType", "spot|point|infinite"), ("texture", "none|red|green|blue|alpha|luminance")], - "filter.blur.lensBlur" => { - &[("shape", "hexagon|triangle|square|pentagon|heptagon|octagon"), ("depthMap", "none|transparency|layerMask"), ("distribution", "uniform|gaussian")] - } + "filter.blur.lensBlur" => &[ + ("shape", "hexagon|triangle|square|pentagon|heptagon|octagon"), + ("depthMap", "none|transparency|layerMask|channel"), + ("distribution", "uniform|gaussian"), + ], "filter.other.hsbHsl" => &[("inputMode", "rgb|hsb|hsl"), ("rowOrder", "hsb|hsl|rgb")], "filter.video.deInterlace" => &[("eliminate", "oddFields|evenFields"), ("createBy", "interpolation|duplication")], _ => return None, diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rs index dae5e9b98b..0425e1932a 100644 --- a/crates/engine/src/filters_ext.rs +++ b/crates/engine/src/filters_ext.rs @@ -277,6 +277,7 @@ pub fn params_for(id: &str, p: &Value) -> Option { depth: match s(p, "depthMap", "none") { "transparency" => DepthSource::Transparency, "layerMask" => DepthSource::LayerMask, + "channel" => DepthSource::Channel, _ => DepthSource::None, }, focal_distance: f(p, "focalDistance", 0.0).clamp(0.0, 255.0), @@ -429,8 +430,19 @@ fn map_from_document(doc: &Document, layer: Option) -> Option } /// Resolves inputs that live outside the target layer: Displace's map (`mapPath`, or -/// `mapDocument` index with optional `mapLayer` id). +/// `mapDocument` index with optional `mapLayer` id), and the alpha channel Lens Blur reads its +/// depth from (`depthChannel`, an index or a name). pub(crate) fn resolve(s: &Session, fp: &mut FilterParams, p: &Value) -> Result<()> { + if let FilterParams::LensBlur { depth: DepthSource::Channel, depth_map, .. } = fp { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let channel = p + .get("depthChannel") + .ok_or_else(|| EngineError::Other("Lens Blur: `depthMap` channel needs `depthChannel` (an alpha channel's index or name)".into()))?; + let surface = crate::edit_menu_cmds::channel_mask(doc, channel) + .ok_or_else(|| EngineError::Other(format!("Lens Blur: the document has no alpha channel {channel}")))?; + *depth_map = Some(Arc::new(algo::Image::read(surface, doc.bounds()))); + return Ok(()); + } let FilterParams::Displace { map, .. } = fp else { return Ok(()) }; if map.is_some() { return Ok(()); @@ -466,13 +478,15 @@ fn map_from_path(path: &str, layer: Option) -> Result> /// The session-free part of [`resolve`]: Displace's `mapPath`. Smart filters record params, not /// the map, so their re-render reads the map again here; without it the filter passed the pixels -/// through. `mapDocument` needs the session and is left unresolved. +/// through. The path is stored in the document, so it is followed only as +/// [`crate::doc_path::resolve`] allows. `mapDocument` needs the session and is left unresolved. pub(crate) fn resolve_map_path(fp: &mut FilterParams, p: &Value) -> Result<()> { if let FilterParams::Displace { map, .. } = fp && map.is_none() && let Some(path) = map_path(p) { - *map = map_from_path(path, p.get("mapLayer").and_then(Value::as_u64))?.map(Arc::new); + let file = crate::doc_path::resolve(path).map_err(|why| crate::doc_path::refusal("the displacement map", path, why))?; + *map = map_from_path(&file.to_string_lossy(), p.get("mapLayer").and_then(Value::as_u64))?.map(Arc::new); } Ok(()) } @@ -660,7 +674,7 @@ pub fn specs() -> Vec { "filter.blur.lensBlur", "Lens Blur…", ["Filter", "Blur"], - r##"{"radius":0..100=15,"shape":"hexagon|triangle|square|pentagon|heptagon|octagon","bladeCurvature":0..100=0,"rotation":0..360=0,"depthMap":"none|transparency|layerMask","focalDistance":0..255=0,"invert":bool,"brightness":0..100=0,"threshold":0..255=255,"noise":0..100=0,"distribution":"uniform|gaussian","monochromatic":bool,"seed":u32=0}"## + r##"{"radius":0..100=15,"shape":"hexagon|triangle|square|pentagon|heptagon|octagon","bladeCurvature":0..100=0,"rotation":0..360=0,"depthMap":"none|transparency|layerMask|channel","depthChannel":index|name?,"focalDistance":0..255=0,"invert":bool,"brightness":0..100=0,"threshold":0..255=255,"noise":0..100=0,"distribution":"uniform|gaussian","monochromatic":bool,"seed":u32=0}"## ), cmd!( "filter.blur.shapeBlur", diff --git a/crates/engine/src/filters_ext/tests.rs b/crates/engine/src/filters_ext/tests.rs index 0f32c5367d..490568e87c 100644 --- a/crates/engine/src/filters_ext/tests.rs +++ b/crates/engine/src/filters_ext/tests.rs @@ -220,6 +220,51 @@ fn lens_blur_uses_the_layer_mask_as_depth() { assert_ne!(pixels(&s), before); } +/// #7400: an alpha channel is a Lens Blur depth source, by name or index, as Photoshop lists +/// the document's channels in Depth Map › Source. A missing channel is an error that changes +/// nothing, and on a Smart Object (whose smart filters re-render without the channels) it is +/// refused instead of silently blurring without depth. +#[test] +fn lens_blur_reads_an_alpha_channel_as_depth() { + let mut s = session(); + // A white channel: depth 1 everywhere. Creating it targets it; the filter is for the layer. + s.execute("channel.new", json!({"name": "Depth Map", "fill": "white"})).unwrap(); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + let before = pixels(&s); + for channel in [json!("Depth Map"), json!(0)] { + let p = |focal: f64| json!({"radius": 6, "depthMap": "channel", "depthChannel": channel, "focalDistance": focal}); + // Focal distance 255 puts depth 1 in focus: nothing blurs. + s.execute("filter.blur.lensBlur", p(255.0)).unwrap(); + assert_eq!(pixels(&s), before, "{channel}: in focus"); + s.execute("filter.blur.lensBlur", p(0.0)).unwrap(); + assert_ne!(pixels(&s), before, "{channel}: out of focus blurs"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixels(&s), before); + } + for bad in [ + json!({"radius": 6, "depthMap": "channel"}), + json!({"radius": 6, "depthMap": "channel", "depthChannel": "Nope"}), + json!({"radius": 6, "depthMap": "channel", "depthChannel": 7}), + ] { + let doc = s.active().unwrap().doc.clone(); + let past = s.active().unwrap().history.past_len(); + let e = s.execute("filter.blur.lensBlur", bad.clone()).unwrap_err().to_string(); + assert!(e.contains("Lens Blur"), "{bad}: {e}"); + assert_eq!(pixels(&s), before, "{bad}: nothing changed"); + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "{bad}: the document was replaced"); + assert_eq!(st.history.past_len(), past, "{bad}: a history step was recorded"); + } + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let past = s.active().unwrap().history.past_len(); + let e = s.execute("filter.blur.lensBlur", json!({"radius": 6, "depthMap": "channel", "depthChannel": "Depth Map"})).unwrap_err().to_string(); + assert!(e.contains("Smart Object"), "{e}"); + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "no smart filter was added"); + assert_eq!(st.history.past_len(), past, "no history step"); +} + #[test] fn params_map_to_algorithm_units() { assert_eq!(params_for("filter.pixelate.crystallize", &json!({"cellSize": 1})), Some(FilterParams::Crystallize { cell_size: 3.0, seed: 0 })); diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/gradient_fill_cmds.rs index 041d311691..356d2252db 100644 --- a/crates/engine/src/gradient_fill_cmds.rs +++ b/crates/engine/src/gradient_fill_cmds.rs @@ -28,9 +28,10 @@ pub const GET: &str = "gradient.fill.get"; /// Largest coordinate accepted for a start/end point (pixels). const MAX_COORD: f32 = 1.0e7; -/// Scale range of a gradient fill (a fraction): Photoshop allows 10–150 % (the PSD stores a -/// percentage). A handle drag past it clamps, so the far handle stops where the scale does. -const SCALE_RANGE: (f32, f32) = (0.1, 1.5); + +/// Scale range of a Gradient Fill layer (a fraction): Photoshop allows 1–1000 %. +/// Gradient Overlay effects have a separate range; the live tool creates fill layers. +pub const SCALE_RANGE: (f32, f32) = (0.01, 10.0); fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } @@ -149,7 +150,7 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } -fn clamp_scale(v: f32) -> f32 { +pub(crate) fn clamp_scale(v: f32) -> f32 { v.clamp(SCALE_RANGE.0, SCALE_RANGE.1) } diff --git a/crates/engine/src/gradient_fill_cmds/tests.rs b/crates/engine/src/gradient_fill_cmds/tests.rs index efcdb494d9..3c0c2f3c6a 100644 --- a/crates/engine/src/gradient_fill_cmds/tests.rs +++ b/crates/engine/src/gradient_fill_cmds/tests.rs @@ -27,7 +27,7 @@ fn create_makes_a_canvas_aligned_fill_layer_with_the_drag_as_handles() { let r = s .execute( CREATE, - json!({"from": [14, 16], "to": [34, 8], "style": "radial", "stops": [[0, "#ff0000"], [1, "#0000ff"]], "opacity": 50, "mode": "multiply"}), + json!({"from": [14, 16], "to": [200, -40], "style": "radial", "stops": [[0, "#ff0000"], [1, "#0000ff"]], "opacity": 50, "mode": "multiply"}), ) .unwrap(); assert_eq!(layer_count(&s), 2); @@ -42,7 +42,7 @@ fn create_makes_a_canvas_aligned_fill_layer_with_the_drag_as_handles() { assert!(!align && dither); let g = s.execute(GET, json!({})).unwrap(); let (from, to) = (g["from"].as_array().unwrap(), g["to"].as_array().unwrap()); - for (v, want) in from.iter().chain(to).zip([14.0, 16.0, 34.0, 8.0]) { + for (v, want) in from.iter().chain(to).zip([14.0, 16.0, 200.0, -40.0]) { assert!((v.as_f64().unwrap() - want).abs() < 1e-3, "{g}"); } // One undo step removes the layer. @@ -225,11 +225,11 @@ fn stops_add_move_recolour_delete_and_midpoints() { #[test] fn preview_equals_the_committed_edit() { let mut s = session(8, "white"); - s.execute(CREATE, json!({"from": [4, 4], "to": [40, 20], "style": "diamond"})).unwrap(); + s.execute(CREATE, json!({"from": [4, 4], "to": [40, 20], "style": "radial"})).unwrap(); let d = s.active().unwrap(); let l = d.doc.layer(d.active_layer.unwrap()).unwrap().clone(); let LayerContent::Fill(f) = &l.content else { panic!() }; - let p = json!({"from": [10, 12], "to": [30, 2]}); + let p = json!({"from": [10, 12], "to": [150, -80]}); let preview = apply_set(&l, f, d.doc.bounds(), &p, [0.0; 4], [1.0; 4]).unwrap(); s.execute(SET, p).unwrap(); assert_eq!(active_fill(&s), preview); @@ -316,12 +316,12 @@ fn commands_fail_gracefully() { s.execute(SET, json!({"scale": 1e30, "angle": 1e9, "offset": [1e4, -1e4]})).unwrap(); let g = s.execute(GET, json!({})).unwrap(); assert!(g["scale"].as_f64().unwrap().is_finite() && g["from"][0].as_f64().unwrap().is_finite()); - // Scale stays within Photoshop's 10–150 %, also for a handle dragged far away. - assert!((g["scale"].as_f64().unwrap() - 150.0).abs() < 1e-3, "{g}"); + // Fill layers use Photoshop's 1–1000 %, also for a handle dragged far away. + assert!((g["scale"].as_f64().unwrap() - 1000.0).abs() < 1e-3, "{g}"); let g = s.execute(SET, json!({"from": [0, 0], "to": [1e6, 0]})).unwrap(); - assert!((g["scale"].as_f64().unwrap() - 150.0).abs() < 1e-3, "{g}"); - let g = s.execute(SET, json!({"scale": 1})).unwrap(); - assert!((g["scale"].as_f64().unwrap() - 10.0).abs() < 1e-3, "{g}"); + assert!((g["scale"].as_f64().unwrap() - 1000.0).abs() < 1e-3, "{g}"); + let g = s.execute(SET, json!({"scale": 0.1})).unwrap(); + assert!((g["scale"].as_f64().unwrap() - 1.0).abs() < 1e-3, "{g}"); } /// Dragging one handle past the scale range stops it; the other handle stays put (#1243). @@ -332,17 +332,19 @@ fn a_clamped_handle_drag_leaves_the_other_handle_alone() { for style in STYLES { for (from, to, short, short_start) in [([14.0, 16.0], [34.0, 16.0], [15.0, 16.0], [33.0, 16.0]), ([24.0, 6.0], [24.0, 26.0], [24.0, 7.0], [24.0, 25.0])] { - let mut s = session(8, "white"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 480, "height": 320})).unwrap(); s.execute(CREATE, json!({"from": from, "to": to, "style": style})).unwrap(); - // End dragged almost onto the start: far below 10 %. + // End dragged almost onto the start: below 1 % on this larger canvas. let g = s.execute(SET, json!({"to": short})).unwrap(); - assert!((g["scale"].as_f64().unwrap() - 10.0).abs() < 1e-3, "{style}: {g}"); + assert!((g["scale"].as_f64().unwrap() - 1.0).abs() < 1e-3, "{style}: {g}"); assert!(close(pt(&g, "from"), from), "{style}: start moved to {:?}", pt(&g, "from")); // The end stops on the line towards the pointer. let e = pt(&g, "to"); assert!((e[0] - from[0]) * (short[0] - from[0]) >= 0.0 && (e[1] - from[1]) * (short[1] - from[1]) >= 0.0, "{style}: {e:?}"); // And the same for the start handle. - let mut s = session(8, "white"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 480, "height": 320})).unwrap(); s.execute(CREATE, json!({"from": from, "to": to, "style": style})).unwrap(); let g = s.execute(SET, json!({"from": short_start})).unwrap(); assert!(close(pt(&g, "to"), to), "{style}: end moved: {g}"); diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 3e870aa686..6d5342b931 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -16,7 +16,8 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { } /// Applies `f` to every pixel surface of a layer tree: content (raster or -/// cached text/shape/smart pixels), fill caches, and (if `masks`) masks. +/// cached text/shape/smart pixels), fill caches, stored video frames (current and original), +/// and (if `masks`) masks. pub(crate) fn for_each_surface(layers: &mut [Layer], masks: bool, f: &mut dyn FnMut(&mut Surface, bool)) { for l in layers { if masks && let Some(m) = &mut l.mask { @@ -25,6 +26,13 @@ pub(crate) fn for_each_surface(layers: &mut [Layer], masks: bool, f: &mut dyn Fn if let Some(fc) = &mut l.fill_cache { f(&mut fc.surface, false); } + // The displayed content is only a copy of the frame at the playhead; the other frames + // would keep the old geometry and depth and come back stale when scrubbing (#4956). + if let Some(v) = &mut l.video { + for frame in v.frames.iter_mut().chain(v.original_frames.iter_mut().flatten()) { + f(frame, false); + } + } match &mut l.content { LayerContent::Raster(s) => f(s, false), LayerContent::Text(t) => { @@ -54,6 +62,18 @@ pub(crate) fn for_each_surface(layers: &mut [Layer], masks: bool, f: &mut dyn Fn } } +/// Drops every fill cache of a layer tree. A fill layer covers the whole canvas, but its cache +/// (the pixels a PSD stored) only the old one: after the canvas grows the fill must re-render +/// from its model, or the added area stays transparent (#7362). +fn drop_fill_caches(layers: &mut [Layer]) { + for l in layers { + l.fill_cache = None; + if let LayerContent::Group(g) = &mut l.content { + drop_fill_caches(&mut g.children); + } + } +} + /// Converts every pixel surface of a layer tree (masks included) to `depth`. pub(crate) fn convert_layers_depth(layers: &mut [Layer], depth: SampleType) { for_each_surface(layers, true, &mut |surf, _| { @@ -103,6 +123,11 @@ pub(crate) fn reidentify_copied_layers(doc: &mut Document) { def.layer = new_id; } } + for slice in &mut doc.slices.list { + if let Some(&new_id) = slice.layer.and_then(|layer| ids.get(&layer)) { + slice.layer = Some(new_id); + } + } } /// Scale every size and distance of a style by `k` (Image Size's Scale Styles, Layer Style › @@ -171,6 +196,12 @@ fn image_size(s: &mut Session, p: &Value) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let (ow, oh) = (d.doc.size.width, d.doc.size.height); let resample = parse_resample(p.get("resample").and_then(Value::as_str).unwrap_or("bicubic")); + // An Indexed Color document holds only its colour table's colours, and a save quantises to + // them: interpolation showed blends that the saved file didn't have (#6019). + let resample = match resample { + Method::Filter(_) | Method::Automatic if d.doc.mode == ColorMode::Indexed => Method::Filter(Resample::Nearest), + m => m, + }; let mut pw = p.get("width").and_then(Value::as_f64); let mut ph = p.get("height").and_then(Value::as_f64); // `percent` scales both sides (what a Photoshop action records as "200%"); an explicit side wins. @@ -337,6 +368,9 @@ fn crop_doc(doc: &mut Document, cmd: &str, r: Rect, delete_pixels: bool, extensi surf.write_interleaved(keep, &saved); } } + if extends { + drop_fill_caches(&mut doc.layers); + } crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes); Ok(()) } @@ -397,6 +431,9 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result { s.edit("Canvas Size", |doc, _| { translate_doc(doc, "image.canvasSize", dx, dy)?; doc.size = Size::new(nw, nh); + if nw > ow as u32 || nh > oh as u32 { + drop_fill_caches(&mut doc.layers); + } crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes); let canvas = doc.bounds(); let old = Rect::from_xywh(dx, dy, ow as u32, oh as u32); @@ -525,8 +562,10 @@ fn crop_target(p: &Value) -> Result { let side = |key: &str| -> Result> { match p.get(key) { None | Some(Value::Null) => Ok(None), + // Whole-number floats (`100.0`) count too, as for the crop rectangle. Some(v) => v .as_u64() + .or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && (0.0..=f64::from(MAX_CROP_SIDE)).contains(f)).map(|f| f as u64)) .and_then(|n| u32::try_from(n).ok()) .filter(|n| (1..=MAX_CROP_SIDE as u32).contains(n)) .map(Some) @@ -629,6 +668,21 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar rotated: true, }; crate::analysis_cmds::compound(s, "Crop", |s| { + // Pixels the crop deletes needn't be turned first: keeping only what lands in the frame + // makes the rotation cost the frame's size, not the canvas's (a small turned crop of a + // 10 MP photo took over half a second). + if delete { + let keep = turned_crop_source(size, new, angle, target); + s.edit("Crop", |doc, _| { + for_each_surface(&mut doc.layers, true, &mut |surf, _| *surf = crop_surface(surf, keep)); + for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { + ch.surface = crop_surface(&ch.surface, keep); + } + // The crop drops the selection anyway. + doc.selection = None; + Ok(()) + })?; + } crate::mode_cmds::rotate_arbitrary(s, &json!({"angle": angle, "direction": "ccw"}))?; // Color Sampler points follow the crop's origin shift too (the rotation moved them above). s.set_sampler_map(photocraft_geom::Affine::translate(-f64::from(target.x0), -f64::from(target.y0))); @@ -646,6 +700,26 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle }))) } +/// The pixels a turned crop reads, in document coordinates before the turn: the source of the +/// `target` frame (on the `new` canvas the rotation by `-angle` makes of `old`), grown by the widest +/// interpolation kernel's reach so every sample the frame's pixels take is kept. +fn turned_crop_source(old: Size, new: Size, angle: f64, target: Rect) -> Rect { + const KERNEL_REACH: f64 = 4.0; + // The inverse of `rotate_arbitrary`'s map: x = c·u + s·v + cx, y = −s·u + c·v + cy, where + // (u, v) is the point relative to the new canvas's centre. + let (sn, cs) = (-angle).to_radians().sin_cos(); + let (cx, cy) = (f64::from(old.width) / 2.0, f64::from(old.height) / 2.0); + let (nx, ny) = (f64::from(new.width) / 2.0, f64::from(new.height) / 2.0); + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for (px, py) in [(target.x0, target.y0), (target.x1, target.y0), (target.x0, target.y1), (target.x1, target.y1)] { + let (u, v) = (f64::from(px) - nx, f64::from(py) - ny); + let (x, y) = (cs * u + sn * v + cx, -sn * u + cs * v + cy); + (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y)); + } + // `as` saturates: a frame near the coordinate limits keeps more, never less. + Rect::new((x0 - KERNEL_REACH).floor() as i32, (y0 - KERNEL_REACH).floor() as i32, (x1 + KERNEL_REACH).ceil() as i32, (y1 + KERNEL_REACH).ceil() as i32) +} + /// Image → Trim. fn trim(s: &mut Session, p: &Value) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; @@ -907,6 +981,28 @@ mod tests { &s.active().unwrap().doc } + /// Document-wide conversions must move every stored video frame, not just the displayed one (#4956). + #[test] + fn crop_moves_stored_video_frames() { + let mut s = session(); + s.edit("video", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let frame = l.surface().unwrap().clone(); + let mut v = photocraft_doc::VideoData::new(vec![frame.clone(), frame.clone()], 24.0); + v.original_frames = Some(vec![frame.clone(), frame]); + l.video = Some(v); + Ok(()) + }) + .unwrap(); + s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap(); + let v = doc(&s).layers[1].video.as_ref().unwrap(); + let red = vec![1.0, 0.0, 0.0, 1.0]; + for frame in v.frames.iter().chain(v.original_frames.iter().flatten()) { + assert_eq!(frame.pixel(20, 10), red); + assert_eq!(frame.pixel(5, 5)[3], 0.0); + } + } + /// Resample on with only a new resolution keeps the print size, as Photoshop's Image Size /// does (an action's `imageSize` with `Rslt` alone); without `keepPrintSize` only the /// resolution changes. @@ -938,6 +1034,28 @@ mod tests { } } + /// #6019: Image Size on an Indexed Color document makes no colours the colour table doesn't have. + #[test] + fn image_size_resamples_indexed_color_with_nearest_neighbor() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + for resample in ["bicubic", "automatic", "bilinear", "lanczos", "preserveDetails"] { + s.execute("image.imageSize", json!({"width": 8, "resample": resample})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layers[0].surface().unwrap(); + for x in 0..8 { + let px = surf.pixel(x, 0); + assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample}: no blended colour at x {x}: {px:?}"); + } + s.execute("history.undo", json!({})).unwrap(); + } + } + /// The canvas border stays opaque after Image Size (it used to fade into transparency, so a /// Background or a 200 % export got a translucent frame), and a full selection stays full. /// #1544: 64 x 48 to 300000 x 300000 (90 billion pixels) started allocating resampled bands @@ -1212,7 +1330,10 @@ mod tests { for y in 0..20 { for x in 0..10 { let (a, b) = (layer_rgba(&s, l, x, y), layer_rgba(&reference, l, x, y)); - assert!(a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-3), "{depth} layer {l} ({x}, {y}): {a:?} vs {b:?}"); + // A fully transparent pixel's colour is invisible, and the turned crop + // doesn't turn the pixels it deletes, which the warp spreads colour from. + let n = if b[3] > 1e-3 { 4 } else { 1 }; + assert!(a.iter().rev().zip(b.iter().rev()).take(n).all(|(p, q)| (p - q).abs() < 1e-3), "{depth} layer {l} ({x}, {y}): {a:?} vs {b:?}"); } } } @@ -1253,6 +1374,61 @@ mod tests { } } + /// A turned crop that deletes the cropped pixels turns only what lands in the frame; inside the + /// new canvas every layer, mask and channel is exactly what turning everything gives (the + /// frame spans several tiles, at several depths and angles). + #[test] + fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() { + use photocraft_color::PixelFormat; + let pixels = || (0..500).flat_map(|y| (0..700).map(move |x| (x, y))); + for depth in [8, 16, 32] { + for angle in [3.0, -7.5, 33.0, 181.0] { + let mut sessions = [true, false].map(|delete| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 700, "height": 500, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let wave = |x: i32, y: i32, k: i32| ((x * 7 + y * 13 + k * 31) % 97) as f32 / 96.0; + let all = Rect::new(0, 0, 700, 500); + let rgba: Vec = pixels().flat_map(|(x, y)| [wave(x, y, 0), wave(x, y, 1), wave(x, y, 2), wave(y, x, 3)]).collect(); + let gray: Vec = pixels().map(|(x, y)| wave(y, x, 4)).collect(); + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().write_region(all, &rgba); + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface.write_region(all, &gray); + l.mask = Some(mask); + let bg = doc.background_mut().unwrap().surface_mut().unwrap(); + bg.write_region(all, &pixels().flat_map(|(x, y)| [wave(x, y, 5), wave(x, y, 6), wave(x, y, 7), 1.0]).collect::>()); + let fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, false); + let mut ch = Surface::new(fmt); + ch.write_region(all, &gray); + doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", ch)); + Ok(()) + }) + .unwrap(); + let p = json!({"x": 150, "y": 120, "width": 330, "height": 290, "angle": angle, "deleteCroppedPixels": delete}); + s.execute("image.crop", p).unwrap(); + s + }); + let [deleted, kept] = &mut sessions; + let (a, b) = (doc(deleted), doc(kept)); + assert_eq!(a.size, b.size, "{depth} {angle}"); + let canvas = a.bounds(); + for (la, lb) in a.layers.iter().zip(&b.layers) { + let (sa, sb) = (la.surface().unwrap(), lb.surface().unwrap()); + assert!(sa.to_interleaved(canvas) == sb.to_interleaved(canvas), "{depth} {angle}: layer {}", la.name); + if let (Some(ma), Some(mb)) = (&la.mask, &lb.mask) { + assert!(ma.surface.to_interleaved(canvas) == mb.surface.to_interleaved(canvas), "{depth} {angle}: mask of {}", la.name); + } + } + assert!(a.channels[0].surface.to_interleaved(canvas) == b.channels[0].surface.to_interleaved(canvas), "{depth} {angle}: alpha channel"); + // Deleting keeps nothing past the canvas. + let layer = a.layers[1].surface().unwrap(); + assert!(canvas.contains_rect(&layer.content_bounds()), "{depth} {angle}: {:?}", layer.content_bounds()); + } + } + } + /// Angle 0 (or a whole turn) is the plain crop: no resampling, the same document. #[test] fn crop_at_angle_zero_is_the_plain_crop() { @@ -1372,6 +1548,14 @@ mod tests { assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(30, 10), 150.0)); } + #[test] + fn crop_target_accepts_whole_number_floats() { + // `json.dumps(100.0)` and many other JSON writers send whole numbers as floats. + let mut s = session(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 20, "height": 10, "targetWidth": 40.0, "targetHeight": 20.0})).unwrap(); + assert_eq!(doc(&s).size, Size::new(40, 20)); + } + #[test] fn crop_target_rejects_bad_params_without_changing_the_document() { let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10}); @@ -1381,6 +1565,10 @@ mod tests { json!({"targetWidth": 0, "targetHeight": 10}), json!({"targetWidth": -5, "targetHeight": 10}), json!({"targetWidth": 10.5, "targetHeight": 10}), + json!({"targetWidth": -1.0, "targetHeight": 10}), + json!({"targetWidth": 0.0, "targetHeight": 10}), + json!({"targetWidth": 1e39, "targetHeight": 10}), + json!({"targetWidth": 300_001.0, "targetHeight": 10}), json!({"targetWidth": "10", "targetHeight": 10}), json!({"targetWidth": 300_001, "targetHeight": 10}), json!({"targetWidth": 4_294_967_306_u64, "targetHeight": 10}), diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index de2afd1556..0ee0573170 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -219,12 +219,36 @@ struct Running { started_ms: f64, coalesce: Option, color_restrict: Option, + /// The document's layer selection when the job started: applying targets it, not whatever + /// got selected meanwhile (a Type click does that without editing the document, #7366). + layers: Option, rx: std::sync::mpsc::Receiver>, apply: Option, #[cfg(not(target_arch = "wasm32"))] handle: Option>, } +/// A document's active layer, selected layers and selection anchor. +#[derive(Clone, PartialEq)] +struct LayerSelection { + active: Option, + selected: Vec, + anchor: Option, +} + +impl LayerSelection { + fn of(st: &crate::DocState) -> Self { + Self { active: st.active_layer, selected: st.selected_layers.clone(), anchor: st.layer_anchor } + } + + fn set(self, st: &mut crate::DocState) { + st.active_layer = self.active; + st.selected_layers = self.selected; + st.layer_anchor = self.anchor; + crate::channel_cmds::fix_view(st); + } +} + impl Running { fn info(&self) -> JobInfo { JobInfo { @@ -323,6 +347,9 @@ pub fn run( ) -> Result { let authorization = s.authorize.or_else(|| RENDER_AUTHORIZATION.with(std::cell::Cell::get)); let _authorization = AuthorizationScope::enter(authorization); + // The job's document: stored paths it follows are resolved against it on any thread. + let document = s.active().and_then(|d| d.path.as_deref()).map(std::path::PathBuf::from); + let _document = crate::doc_path::scope(document.as_deref()); if !s.jobs.spawn || cfg!(target_arch = "wasm32") { let t = work(&s.jobs.inline.clone().unwrap_or_default())?; return apply(s, t); @@ -330,15 +357,17 @@ pub fn run( if s.jobs.pending.is_some() { return Err(EngineError::Other(format!("`{label}` started a second background job in one command"))); } - let (doc, snapshot) = match (lock_document, s.active()) { - (true, Some(st)) => (Some(st.doc.id), Some(Arc::downgrade(&st.doc))), + let (doc, snapshot, layers) = match (lock_document, s.active()) { + (true, Some(st)) => (Some(st.doc.id), Some(Arc::downgrade(&st.doc)), Some(LayerSelection::of(st))), (true, None) => return Err(EngineError::NoDocument), - (false, _) => (None, None), + (false, _) => (None, None, None), }; let ctx = JobCtx::new(); let (tx, rx) = std::sync::mpsc::channel::>(); + let apply_document = document.clone(); let erased: Apply = Box::new(move |s, any| { let _authorization = AuthorizationScope::enter(authorization); + let _document = crate::doc_path::scope(apply_document.as_deref()); let t = any.downcast::().map_err(|_| EngineError::Other("internal error: job result type mismatch".into()))?; apply(s, *t) }); @@ -352,6 +381,7 @@ pub fn run( // no way to get it back, so the error is reported instead. let spawned = std::thread::Builder::new().name(format!("photocraft-job-{}", id.0)).spawn(move || { let _authorization = AuthorizationScope::enter(authorization); + let _document = crate::doc_path::scope(document.as_deref()); let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work(&wctx).map(|t| Box::new(t) as Payload))) .unwrap_or_else(|_| Err(EngineError::Other(format!("`{label_w}` failed with an internal error (logged); the document is unchanged")))); // The receiver is gone when the job was cancelled: nothing to report. @@ -376,6 +406,7 @@ pub fn run( started_ms: now_ms(), coalesce: s.coalesce_request.clone(), color_restrict: s.color_restrict, + layers, rx, apply: Some(erased), #[cfg(not(target_arch = "wasm32"))] @@ -503,7 +534,9 @@ impl Session { warm_layer_bounds(&imported.document, || ctx.check())?; Ok(imported) }, - move |s, r: photocraft_io::ImportResult| { + move |s, mut r: photocraft_io::ImportResult| { + // File Handling's ACEScg option, before the colour prompt looks at the profile. + crate::file_cmds::tag_exr_colorspace(s, &name_a, &mut r.document); // Ask When Opening: held back until the prompt is answered (`take_held_open`). A // developed raw has no embedded profile to ask about. let raw = r.warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); @@ -543,7 +576,7 @@ impl Session { job.ctx.cancel(); Err(e) } - (Err(e), None) => Err(e), + (Err(e), None) => Err(self.explain_missing_layer(e)), (Ok(_), Some(mut job)) => { job.command = command.to_string(); job.params = params; @@ -694,6 +727,7 @@ impl Session { gate(id, ¶ms)?; } let _authorization = AuthorizationScope::enter(self.authorize); + let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); // Last Filter runs as the filter it repeats: journaled, recorded in an action, faded and // run as a job like that filter, so a recorded step replays the same filter anywhere // (#3089), as Transform Again records its transform (#1440). With no filter yet it falls @@ -723,6 +757,7 @@ impl Session { // action it plays (a script step) must not flush the steps it ran so far into the action // being recorded, nor move the recording mark past the entries it is about to replace. let recording = if spec.journal && crate::actions_cmds::replayable(id) { self.actions.recording.take() } else { None }; + let before = self.active().map(|st| st.doc.clone()); // Last-resort guard (AGENTS.md, Never crash): a command that panics anyway fails with an // error instead of taking the app down. `edit` only commits a document after its closure // returns, so the documents are unchanged. @@ -740,7 +775,7 @@ impl Session { job.ctx.cancel(); Err(e) } - (Err(e), None) => Err(e), + (Err(e), None) => Err(self.explain_missing_layer(e)), (Ok(_), Some(mut job)) => { job.command = id.to_string(); job.params = params; @@ -750,12 +785,40 @@ impl Session { Ok(Started::Job(jid)) } (Ok(v), None) => { + if let Some(before) = before { + self.add_relayout_damage(&before); + } self.after_command(id, params, spec.journal, Some(nested_from)); Ok(Started::Done(v)) } } } + /// Grows the damage a command reported for the pixels it changed by what effects laid out + /// over a layer's frame repaint when it moved ([`photocraft_compose::relayout_damage`]): a + /// stroke on a layer with a Gradient Overlay reports the stroke, but the gradient is laid out + /// again over the whole grown layer (#4053). `before` is the active document before. + fn add_relayout_damage(&mut self, before: &Arc) { + let Some(st) = self.active_mut().filter(|st| st.doc.id == before.id && !Arc::ptr_eq(&st.doc, before)) else { return }; + let Some(d) = st.last_damage.filter(|d| !d.is_empty()) else { return }; + let extra = photocraft_compose::relayout_damage(before, &st.doc); + if !extra.is_empty() { + st.last_damage = Some(d.union(&extra)); + } + } + + /// A command that failed on a layer id the document doesn't have says which ids it does have + /// (#5058): ids are not positions (an opened PNG's Background is not layer 1), and an agent + /// should not need `document.inspect` to recover. + fn explain_missing_layer(&self, e: EngineError) -> EngineError { + match (e, self.active()) { + (EngineError::NoLayer(id), Some(st)) if st.doc.layer(id).is_none() => { + EngineError::UnknownLayer { id, known: crate::commands::layer_listing(&st.doc) } + } + (e, _) => e, + } + } + /// Bookkeeping after a command (or a job's apply) succeeded. /// /// `nested_from` is the journal length when the command started. A replayable command stands @@ -778,8 +841,12 @@ impl Session { self.journal.truncate(from); } if !crate::brush_cmds::coalesce_journal(self, id, ¶ms) { - let params = - if id == "layer.select" && self.actions.recording.is_some() { crate::layer_multi_cmds::recorded_selection(self, params) } else { params }; + let params = match id { + _ if self.actions.recording.is_none() => params, + "layer.select" => crate::layer_multi_cmds::recorded_selection(self, params), + "layerComp.apply" => crate::comps_cmds::recorded_apply(self, params), + _ => params, + }; self.journal.push((id.to_string(), params)); } } @@ -801,7 +868,7 @@ impl Session { } fn apply_job(&mut self, job: &Running, apply: Option, payload: Payload) -> Result { - let Running { label, doc, snapshot, coalesce, color_restrict, command, params, journal, .. } = job; + let Running { label, doc, snapshot, coalesce, color_restrict, layers, command, params, journal, .. } = job; let prev_active = self.active; let target = match doc { Some(d) => { @@ -816,6 +883,19 @@ impl Session { } None => None, }; + // Selecting a layer doesn't change the document, so the snapshot check above lets it + // through. Apply against the layers the job started on: the colour restriction and any + // `active`-based edit land on them (#7366). The user's selection is put back below. + let user_layers = match (target, layers) { + (Some(i), Some(started)) => self.docs.get_mut(i).and_then(|st| { + let now = LayerSelection::of(st); + (now != *started).then(|| { + started.clone().set(st); + now + }) + }), + _ => None, + }; self.coalesce_request = coalesce.clone(); self.color_restrict = *color_restrict; // Apply-time hooks can dispatch commands too. Keep the same single-step recording @@ -838,6 +918,15 @@ impl Session { if r.is_ok() { self.after_command(command, params.clone(), *journal, Some(nested_from)); } + // Give the user back the layers they selected while the job ran, unless the job chose a + // selection itself (a new layer, say) or one of their layers is gone. + if let (Some(started), Some(user), Some(st)) = (layers, user_layers, target.and_then(|i| self.docs.get_mut(i))) { + let kept = LayerSelection::of(st) == *started; + let exist = user.active.iter().chain(&user.selected).all(|id| st.doc.layer(*id).is_some()); + if (r.is_err() || kept) && exist { + user.set(st); + } + } // Keep the user's active document unless the job opened a new one. // This also restores the selection when the apply step returned an error. if target.is_some() && self.active == target { diff --git a/crates/engine/src/layer_menu_cmds.rs b/crates/engine/src/layer_menu_cmds.rs index 366f9c8d39..ab25912296 100644 --- a/crates/engine/src/layer_menu_cmds.rs +++ b/crates/engine/src/layer_menu_cmds.rs @@ -373,30 +373,56 @@ fn reveal_in_finder(s: &mut Session, p: &Value) -> Result { let SmartSource::Linked { path } = &sm.source else { return Err(other("embedded smart objects have no file to reveal")); }; - reveal(path, p.get("dryRun").and_then(Value::as_bool).unwrap_or(false)) + // The path is stored in the document: shown only when it would be followed. + let file = + crate::doc_path::resolve_in(path, d.path.as_deref().map(std::path::Path::new)).map_err(|why| crate::doc_path::refusal("the linked file", path, why))?; + reveal(&file.to_string_lossy(), p.get("dryRun").and_then(Value::as_bool).unwrap_or(false)) } /// Show `path` in the platform file manager ([`reveal_command`] + [`spawn`]); `dry_run` answers /// the program and arguments instead (tests). Shared by the smart-object command and the document /// tab's Reveal in Finder (UI-217-6). pub(crate) fn reveal(path: &str, dry_run: bool) -> Result { - let (program, args) = reveal_command(path); + let (program, args) = reveal_command(path)?; if dry_run { return Ok(json!({"program": program, "args": args})); } + ensure_folder(program, &args)?; spawn(program, &args)?; Ok(json!({"path": path})) } +/// `xdg-open` opens whatever it is given in its default application, so it only gets a folder: a +/// linked path such as `tool.jar/a.png` would otherwise launch `tool.jar` instead of showing it. +fn ensure_folder(program: &str, args: &[String]) -> Result<()> { + if program != "xdg-open" { + return Ok(()); + } + match args.first() { + Some(dir) if std::path::Path::new(dir).is_dir() => Ok(()), + Some(dir) => Err(other(format!("{dir} is not a folder, so it can't be shown in the file manager"))), + None => Err(other("no folder to show in the file manager")), + } +} + /// The file-manager invocation that selects `path` on this platform. -pub fn reveal_command(path: &str) -> (&'static str, Vec) { - if cfg!(target_os = "macos") { - ("open", vec!["-R".into(), path.into()]) - } else if cfg!(target_os = "windows") { - ("explorer", vec![format!("/select,{path}")]) - } else { - let parent = std::path::Path::new(path).parent().map_or_else(|| ".".to_string(), |p| p.to_string_lossy().into_owned()); - ("xdg-open", vec![parent]) +pub fn reveal_command(path: &str) -> Result<(&'static str, Vec)> { + reveal_command_on(std::env::consts::OS, path) +} + +/// [`reveal_command`] on the platform `os` (a `std::env::consts::OS` value). +fn reveal_command_on(os: &str, path: &str) -> Result<(&'static str, Vec)> { + match os { + // `--` ends the options: a path starting with `-` is not read as one. + "macos" => Ok(("open", vec!["-R".into(), "--".into(), path.into()])), + // Explorer splits `/select,` arguments at commas and reads quotes itself, so such a path + // would select something else. + "windows" if path.contains([',', '"']) => Err(other(format!("{path} can't be shown in Explorer: its path contains a comma or a quotation mark"))), + "windows" => Ok(("explorer", vec![format!("/select,{path}")])), + _ => { + let parent = std::path::Path::new(path).parent().map_or_else(|| ".".to_string(), |p| p.to_string_lossy().into_owned()); + Ok(("xdg-open", vec![parent])) + } } } diff --git a/crates/engine/src/layer_menu_cmds/tests.rs b/crates/engine/src/layer_menu_cmds/tests.rs index 46688500b1..171034876e 100644 --- a/crates/engine/src/layer_menu_cmds/tests.rs +++ b/crates/engine/src/layer_menu_cmds/tests.rs @@ -465,16 +465,13 @@ fn stack_mode_rejects_sources_without_visible_layers() { #[test] fn reveal_in_finder_dry_run_and_enabled() { + let link = std::env::temp_dir().join("pics").join("a.png").to_string_lossy().into_owned(); let mut s = session(8, "rgb"); assert!(!s.is_enabled("layer.smartObjects.revealInFinder")); s.edit("linked", |doc, active| { let mut l = Layer::new( "linked", - LayerContent::Smart(photocraft_doc::SmartObject::new( - SmartSource::Linked { path: "/tmp/pics/a.png".into() }, - photocraft_geom::Affine::IDENTITY, - None, - )), + LayerContent::Smart(photocraft_doc::SmartObject::new(SmartSource::Linked { path: link.clone() }, photocraft_geom::Affine::IDENTITY, None)), ); l.visible = true; *active = Some(doc.insert_above(*active, l)); @@ -483,11 +480,61 @@ fn reveal_in_finder_dry_run_and_enabled() { .unwrap(); assert!(s.is_enabled("layer.smartObjects.revealInFinder")); let r = s.execute("layer.smartObjects.revealInFinder", json!({"dryRun": true})).unwrap(); - let (prog, args) = reveal_command("/tmp/pics/a.png"); + let (prog, args) = reveal_command(&link).unwrap(); assert_eq!(r["program"], json!(prog)); assert_eq!(r["args"], json!(args)); } +#[test] +fn reveal_follows_linked_paths_like_the_link_and_passes_paths_as_paths() { + let mut s = session(8, "rgb"); + let folder = std::env::temp_dir().join("pics"); + s.active_mut().unwrap().path = Some(folder.join("doc.pcraft").to_string_lossy().into_owned()); + let mut link = |path: &str| { + s.edit("linked", |doc, active| { + let so = photocraft_doc::SmartObject::new(SmartSource::Linked { path: path.into() }, photocraft_geom::Affine::IDENTITY, None); + *active = Some(doc.insert_above(*active, Layer::new("linked", LayerContent::Smart(so)))); + Ok(()) + }) + .unwrap(); + s.execute("layer.smartObjects.revealInFinder", json!({"dryRun": true})).map_err(|e| e.to_string()) + }; + let err = link(r"\\192.0.2.1\share\x.png").unwrap_err(); + assert!(err.contains("is not opened: the path is on another computer"), "{err}"); + // A relative link is shown next to the document. + let r = link("a.png").unwrap(); + assert_eq!(r["args"], json!(reveal_command(&folder.join("a.png").to_string_lossy()).unwrap().1)); + // The document's own file is shown wherever it is, a network share included. + s.active_mut().unwrap().path = Some(r"\\192.0.2.1\share\doc.psd".into()); + s.execute("file.revealInFinder", json!({"dryRun": true})).unwrap(); + + assert_eq!(reveal_command_on("macos", "-a.png").unwrap(), ("open", vec!["-R".to_string(), "--".into(), "-a.png".into()])); + assert_eq!(reveal_command_on("windows", r"C:\pics\a.png").unwrap(), ("explorer", vec![r"/select,C:\pics\a.png".to_string()])); + for path in [r"C:\pics\a,b.png", r#"C:\pics\a".png"#] { + assert!(reveal_command_on("windows", path).is_err(), "{path}"); + } +} + +/// `xdg-open` launches a file it is given, so Reveal hands it the link's folder only when that is a +/// folder: a link stored as `tool.jar/a.png` names a file, not a folder, as its parent. +#[test] +fn reveal_on_linux_never_hands_xdg_open_a_file() { + let dir = std::env::temp_dir().join(format!("photocraft-reveal-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("tool.jar"); + std::fs::write(&file, b"not a folder").unwrap(); + let (program, args) = reveal_command_on("linux", &file.join("a.png").to_string_lossy()).unwrap(); + assert_eq!(args, vec![file.to_string_lossy().into_owned()]); + let err = ensure_folder(program, &args).unwrap_err(); + assert!(err.to_string().contains("is not a folder"), "{err}"); + let (program, args) = reveal_command_on("linux", &dir.join("a.png").to_string_lossy()).unwrap(); + ensure_folder(program, &args).unwrap(); + assert!(ensure_folder("xdg-open", &[]).is_err()); + // Finder and Explorer select the file itself, whatever it is. + ensure_folder("open", &["-R".into(), "--".into(), file.to_string_lossy().into_owned()]).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn mask_all_objects_masks_the_subject() { let mut s = session(8, "rgb"); diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index 1b71e966a4..418b0051d0 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -885,9 +885,9 @@ pub(crate) fn note_inert_insert(s: &mut Session, id: LayerId) { } } -/// Report the pixels an edit from `before` that added layers changed ([`step_damage`]), for -/// commands made of more than one edit, so the canvas recomposites only where the new layers -/// draw instead of the whole document. +/// 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); @@ -1386,7 +1386,6 @@ pub fn delete_selected(s: &mut Session) -> Result { /// this path, #2777). pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Result { let sel = selected(s); - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); let old_active = s.active().and_then(|d| d.active_layer); let (copies, active) = s.edit(label, |doc, active| { let mut copies = Vec::new(); @@ -1408,7 +1407,6 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul *active = a; Ok((copies, a)) })?; - note_insert(s, &before); let out = copies.iter().map(|l| l.0).collect::>(); reselect(s, copies, active); Ok(json!({"layers": out, "layer": active.map(|l| l.0)})) @@ -1823,8 +1821,8 @@ mod tests { x.px.iter().zip(&y.px).enumerate().all(|(i, (p, q))| p == q || damage.contains(i as i32 % w, i as i32 / w)) } - /// Duplicate, paste and delete, and their undo and redo, recomposite only where the layer - /// draws; undoing a duplicate used to recomposite the whole document. + /// Duplicate (one layer or several), paste and delete, and their undo and redo, recomposite + /// only where the layers draw; undoing a duplicate used to recomposite the whole document. #[test] fn duplicate_paste_and_delete_report_where_the_layer_draws() { let mut s = session(8); @@ -1847,6 +1845,12 @@ mod tests { s.execute("edit.copy", json!({})).unwrap(); s.execute("select.deselect", json!({})).unwrap(); step(&mut s, "edit.paste", json!({})); + // Duplicating several selected layers reports where the copies draw, too. + let b = rect_layer(&mut s, Rect::new(30, 30, 40, 40)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + step(&mut s, "layer.duplicate", json!({})); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 40, 40)), "both copies, nothing else"); step(&mut s, "layer.delete", json!({"layer": a.0})); } diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 95b5476850..8933f838b9 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -594,6 +594,9 @@ fn overlay_gradient(g: &mut Gradient, p: &Value) { /// a dialog round trip never touches what it doesn't model: an imported /// gradient stroke keeps its gradient while its opacity is edited. pub fn overlay_effect(fx: &mut Effect, p: &Value) { + if crate::commands::check_f32_values("layer.layerStyle", p).is_err() { + return; + } fn set_color(p: &Value, k: &str, c: &mut Color) { if let Some(x) = color_of(p, k) { *c = x; @@ -821,6 +824,7 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) { /// Builds an effect of `kind` from JSON params (Photoshop units: opacity, /// spread, range in percent; sizes in px; angles in degrees). pub fn effect_from_params(kind: &str, p: &Value) -> Option { + crate::commands::check_f32_values("layer.layerStyle", p).ok()?; let mut fx = fresh_effect(kind)?; overlay_effect(&mut fx, p); Some(fx) @@ -856,6 +860,7 @@ const MAX_EFFECTS: usize = 256; /// mismatches and malformed snapshots are errors, never panics. fn replace_effects(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.layerStyle.replace"; + crate::commands::check_f32_values(CMD, p)?; let id = crate::commands::layer_param(s, p)?; let entries = p.get("effects").and_then(Value::as_array).ok_or_else(|| bad(CMD, "need `effects`: [{kind, params, fx?}]"))?; if entries.len() > MAX_EFFECTS { @@ -905,6 +910,7 @@ fn replace_effects(s: &mut Session, p: &Value) -> Result { } fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result { + crate::commands::check_f32_values(&format!("layer.layerStyle.{kind}"), p)?; let fx = effect_from_params(kind, p).ok_or_else(|| EngineError::Other(format!("unknown effect {kind}")))?; let (fx, pattern) = crate::pattern_cmds::resolve_effect(s, fx)?; let label = format!("Layer Style: {}", fx.label()); @@ -936,6 +942,7 @@ fn make_default(s: &mut Session, p: &Value) -> Result { Some(v) if v.is_object() => v.clone(), _ => return Err(bad(CMD, "`params` must be an object")), }; + crate::commands::check_f32_values(CMD, ¶ms)?; s.presets.layer_defaults.insert(kind.to_string(), params); s.presets_changed(); Ok(json!({"kind": kind})) @@ -1152,17 +1159,25 @@ mod tests { /// blur kernel of 2^62 taps ("capacity overflow"), or ran for minutes at 1e6. The blur width /// is capped at the effect reach, so the document still renders, quickly. #[test] - fn oversized_satin_and_bevel_sizes_render() { - for (cmd, p) in [ - ("satin", json!({"size": 1e308})), - ("satin", json!({"size": 1_000_000})), - ("bevelEmboss", json!({"size": 1e308})), - ("bevelEmboss", json!({"soften": 1e308})), - ("bevelEmboss", json!({"size": 1_000_000, "soften": 1_000_000})), + fn oversized_satin_and_bevel_sizes_stay_saveable_and_render() { + for (cmd, p, accepted) in [ + ("satin", json!({"size": 1e308}), false), + ("satin", json!({"size": 1e30}), true), + ("satin", json!({"size": 1_000_000}), true), + ("bevelEmboss", json!({"size": 1e308}), false), + ("bevelEmboss", json!({"soften": 1e308}), false), + ("bevelEmboss", json!({"size": 1e30, "soften": 1e30}), true), + ("bevelEmboss", json!({"size": 1_000_000, "soften": 1_000_000}), true), ] { let mut s = session(); s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()).unwrap(); + let result = s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()); + if accepted { + result.unwrap(); + } else { + assert!(matches!(result, Err(EngineError::BadParams { .. }))); + } + photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap(); let start = std::time::Instant::now(); s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap_or_else(|e| panic!("{cmd} {p}: {e}")); assert!(start.elapsed().as_secs() < 20, "{cmd} {p}: {:?}", start.elapsed()); diff --git a/crates/engine/src/lens_cmds.rs b/crates/engine/src/lens_cmds.rs index 379ca2402a..ba088c7086 100644 --- a/crates/engine/src/lens_cmds.rs +++ b/crates/engine/src/lens_cmds.rs @@ -62,7 +62,7 @@ pub fn lens_params(cmd: &str, p: &Value, frame: Rect, info: Option<&exif::Camera "edgeExtension" | "extension" => EdgeMode::Extension, "black" => EdgeMode::Color([0.0, 0.0, 0.0, 1.0]), "white" => EdgeMode::Color([1.0, 1.0, 1.0, 1.0]), - "background" | "color" => EdgeMode::Color(crate::commands::color_param(p, "edgeColor", [0.0, 0.0, 0.0, 1.0])), + "background" | "color" => EdgeMode::Color(crate::commands::color_param(cmd, p, "edgeColor", [0.0, 0.0, 0.0, 1.0])?), other => return Err(bad(cmd, format!("unknown edge `{other}` (transparency|edgeExtension|black|white|color)"))), }; let focal = num(p, "focalLength", 0.0); @@ -147,6 +147,9 @@ pub fn raw_params(cmd: &str, p: &Value) -> Result { cr.noise_luminance_detail = cr.noise_luminance_detail.clamp(0.0, 100.0); cr.noise_color = cr.noise_color.clamp(0.0, 100.0); cr.noise_color_detail = cr.noise_color_detail.clamp(0.0, 100.0); + // `exposure` becomes `2^exposure`, which overflows f32 to infinity from 128 up (and then + // writes inf/NaN into 32-bit layers). Clamp to the documented -5..5. + cr.exposure = cr.exposure.clamp(-5.0, 5.0); Ok(cr) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b8d6167c3d..ba7556901b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1,4 +1,4 @@ -//! The Photocraft engine façade: open documents, history, and the command registry. +//! The PhotoCraft engine façade: open documents, history, and the command registry. //! //! Every user-visible action is a command with a stable id (Photoshop-style, such as //! `layer.newAdjustmentLayer.invert`) and JSON parameters. Every frontend goes through the same @@ -34,6 +34,7 @@ mod crop_fill; pub mod cutout_cmds; pub mod display_color; pub mod distort_cmds; +pub mod doc_path; pub mod document_preset_cmds; pub mod edit_cmds; pub mod edit_menu_cmds; @@ -41,6 +42,7 @@ pub mod eraser_cmds; pub mod export_preset_cmds; pub mod exr_cmds; pub mod extra_cmds; +pub mod face_cmds; pub mod file_cmds; pub mod fill_cmds; pub mod fill_key_cmds; @@ -155,6 +157,10 @@ pub enum EngineError { NoDocument, #[error("no such layer {0:?}")] NoLayer(LayerId), + /// [`Self::NoLayer`] as a command reports it: with the layers the document does have, as + /// ids are not positions (#5058). + #[error("no such layer {}; {known}", id.0)] + UnknownLayer { id: LayerId, known: String }, #[error("{0}")] Other(String), /// A background job was cancelled (see [`jobs`]); nothing changed. @@ -480,6 +486,9 @@ pub struct Session { /// the same check a top-level request sees. `None` runs everything, which is what a local /// UI and `photocraft-cli run` do. pub authorize: Option Result<()>>, + /// A further route for File › Print when neither `lp` nor a CUPS server over IPP is + /// reachable (the XDG Print portal in a Flatpak); see `print_cmds::Spooler`. + pub print_spooler: Option, /// Background jobs (see [`jobs`]). jobs: jobs::Jobs, /// Color Sampler points dropped by the last canvas-size change (crop, Canvas Size, Image Size, @@ -782,6 +791,7 @@ impl Session { // Every mutation path (linked-file refresh, transform, place) re-renders smart objects // through this entry; the requesting session's authority must reach those renders. let _authorization = crate::jobs::render_authorization_scope(self.authorize); + let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); let restrict = self.color_restrict; let sampler_map = self.sampler_map.take(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 5c235fb919..453af7806b 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -16,6 +16,9 @@ //! keeps waiting for Update Modified Content, as in Photoshop); one that can't be read (another app //! is still writing it) is tried again once it changes again, not on every look. Only smart objects //! of the document itself follow their files, not ones nested in another smart object's contents. +//! While a background job runs on the document, its files aren't looked at: an update would replace +//! the snapshot the job works on and its result would be thrown away. The first look after the job +//! ends catches up. use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::{Arc, Mutex, PoisonError}; @@ -32,15 +35,17 @@ pub type Stamp = (u64, u128); /// ids, stamp)]). pub type LinkScan = Arc, Option)>)>>>; +/// Stamps `file`, a linked path resolved by [`crate::doc_path`]; `None` (not looked at, like a +/// missing file) when it is not followed. #[cfg(not(target_arch = "wasm32"))] -fn stamp(path: &str) -> Option { - let meta = std::fs::metadata(path).ok()?; +fn stamp(file: Option<&std::path::Path>) -> Option { + let meta = std::fs::metadata(file?).ok()?; let modified = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?; Some((meta.len(), modified.as_nanos())) } #[cfg(target_arch = "wasm32")] -fn stamp(_: &str) -> Option { +fn stamp(_: Option<&std::path::Path>) -> Option { None } @@ -61,11 +66,24 @@ pub fn linked_files(d: &Document) -> Vec<(String, Vec)> { /// the layers of the ones that changed. pub(crate) fn update_changed(s: &mut Session, _: &Value) -> Result { let st = s.active().ok_or(EngineError::NoDocument)?; - let (doc, files) = (st.doc.id.0, linked_files(&st.doc)); - let now = files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p))).collect(); + let (doc, files) = (st.doc.id.0, resolved_files(st)); + let now = files.into_iter().map(|(p, file, ids)| (p, ids, stamp(file.as_deref()))).collect(); s.apply_link_stamps(doc, now) } +/// [`linked_files`] of `st`'s document with the file each path resolves to, or `None` for a path +/// that is not followed ([`crate::doc_path`]). +fn resolved_files(st: &crate::DocState) -> Vec<(String, Option, Vec)> { + let document = st.path.as_deref().map(std::path::Path::new); + linked_files(&st.doc) + .into_iter() + .map(|(p, ids)| { + let file = crate::doc_path::resolve_in(&p, document).ok(); + (p, file, ids) + }) + .collect() +} + impl Session { /// Start stamping the active document's linked files on a worker thread, unless a look is /// still running (or the build has no files to look at: the web app). @@ -74,14 +92,15 @@ impl Session { return; } let Some(st) = self.active() else { return }; - let (doc, files) = (st.doc.id.0, linked_files(&st.doc)); - if files.is_empty() { + let (doc, files) = (st.doc.id.0, resolved_files(st)); + // Nothing to look at: no links, or none that is followed. + if files.iter().all(|(_, file, _)| file.is_none()) { return; } let slot: LinkScan = Arc::default(); let out = slot.clone(); let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || { - let stamps = files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p))).collect(); + let stamps = files.into_iter().map(|(p, file, ids)| (p, ids, stamp(file.as_deref()))).collect(); *out.lock().unwrap_or_else(PoisonError::into_inner) = Some((doc, stamps)); }); if spawned.is_ok() { @@ -103,6 +122,12 @@ impl Session { if self.active().map(|d| d.doc.id.0) != Some(doc) { return Ok(json!({"updated": []})); } + // A background job holds the document: refreshing now would replace the snapshot it works + // on and its result would be discarded. The stamps stay as they were, so the change is + // seen again by the first look after the job ends. + if self.active_job().is_some() { + return Ok(json!({"updated": []})); + } // This document's last stamps; those of closed documents are dropped. let open: HashSet = self.documents().iter().map(|d| d.doc.id.0).collect(); let mut before: HashMap = HashMap::new(); @@ -155,7 +180,7 @@ mod tests { use photocraft_geom::Rect; use serde_json::json; - use crate::Session; + use crate::{EngineError, Session}; fn dir(name: &str) -> std::path::PathBuf { let d = std::env::temp_dir().join(format!("photocraft-link-watch-{name}-{}", std::process::id())); @@ -280,4 +305,53 @@ mod tests { assert!(is(centre(&s), BLUE)); assert!(s.link_scan.is_none()); } + + #[test] + fn a_refresh_waits_for_a_running_job_on_the_document() { + let d = dir("job"); + let path = d.join("art.png"); + std::fs::write(&path, png(10, 10, "#ff0000")).unwrap(); + let (mut s, id) = placed(&path); + s.execute("layer.smartObjects.updateChanged", json!({})).unwrap(); + let (release, job) = gated_job(&mut s); + save(&path, &png(10, 10, "#0000ff")); + let snapshot = s.active().unwrap().doc.clone(); + // The path the desktop app's timer takes: it doesn't go through the command conflict check. + assert_eq!(super::update_changed(&mut s, &json!({})).unwrap(), json!({"updated": []})); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &snapshot), "the job's snapshot must stay in place"); + release.send(()).unwrap(); + s.wait_job(job).unwrap(); + // The job finished; the change that came meanwhile is picked up exactly once. + assert_eq!(s.execute("layer.smartObjects.updateChanged", json!({})).unwrap(), json!({"updated": [id]})); + assert!(is(centre(&s), BLUE)); + assert_eq!(s.execute("layer.smartObjects.updateChanged", json!({})).unwrap(), json!({"updated": []})); + } + + #[test] + fn a_job_on_another_document_does_not_hold_up_a_refresh() { + let d = dir("job-other"); + let path = d.join("art.png"); + std::fs::write(&path, png(10, 10, "#ff0000")).unwrap(); + let (mut s, id) = placed(&path); + s.execute("layer.smartObjects.updateChanged", json!({})).unwrap(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + let (release, job) = gated_job(&mut s); + s.set_active(0); + save(&path, &png(10, 10, "#0000ff")); + assert_eq!(super::update_changed(&mut s, &json!({})).unwrap(), json!({"updated": [id]})); + assert!(is(centre(&s), BLUE)); + release.send(()).unwrap(); + s.wait_job(job).unwrap(); + } + + /// A background job that locks the active document until something is sent on the returned + /// sender. + fn gated_job(s: &mut Session) -> (std::sync::mpsc::Sender<()>, crate::jobs::JobId) { + let (release, gate) = std::sync::mpsc::channel::<()>(); + let r = s.start_job("test.gated", json!({}), "Gated job", true, move |_| gate.recv().map_err(|_| EngineError::Cancelled), |_, ()| Ok(json!(null))); + match r.unwrap() { + crate::jobs::Started::Job(j) => (release, j), + other => panic!("expected a background job, got {other:?}"), + } + } } diff --git a/crates/engine/src/migrate_cmds.rs b/crates/engine/src/migrate_cmds.rs index 18d2be8017..68fbffd25b 100644 --- a/crates/engine/src/migrate_cmds.rs +++ b/crates/engine/src/migrate_cmds.rs @@ -40,12 +40,14 @@ fn migrate(s: &mut Session, p: &Value) -> Result { let st = merge_groups(&mut ps.styles, groups(&v, "styles")); let sh = merge_groups(&mut ps.shapes, groups(&v, "shapes")); let pt = merge_groups(&mut ps.pattern_groups, groups(&v, "pattern_groups")); - // Tool presets are a flat list, matched by name. + // Tool presets are a flat list, matched by name. Read them like the launch loader does (entry by + // entry, checked names), and keep the library within its cap, so what we import survives a restart. let mut tp = 0usize; - if let Some(arr) = v.get("tool_presets").cloned() - && let Ok(incoming) = serde_json::from_value::>(arr) - { - for t in incoming { + if let Some(arr) = v.get("tool_presets").cloned() { + for t in crate::presets::tools::load(arr) { + if ps.tool_presets.len() >= crate::presets::tools::MAX_PRESETS { + break; + } if !ps.tool_presets.iter().any(|e| e.name == t.name) { ps.tool_presets.push(t); tp += 1; @@ -151,6 +153,46 @@ mod tests { let _ = std::fs::remove_file(file); } + #[test] + fn tool_presets_are_read_entry_by_entry_like_the_launch_loader() { + use crate::presets::tools::MAX_PRESETS; + let file = std::env::temp_dir().join(format!("pc-migrate-tools-{}.json", std::process::id())); + let migrate = |s: &mut Session, data: Value| { + std::fs::write(&file, serde_json::to_string(&data).unwrap()).unwrap(); + s.execute("edit.presets.migratePresets", json!({"path": file.to_string_lossy()})).unwrap() + }; + // A damaged entry no longer discards the good ones; blank and overlong names are skipped. + let mut s = Session::new(); + let before = s.presets.tool_presets.len(); + let r = migrate( + &mut s, + json!({"tool_presets": [ + {"name": "4x6 print", "tool": "crop", "options": {}}, + {"name": "old", "tool": null}, + {"name": " ", "tool": "crop"}, + {"name": "x".repeat(300), "tool": "crop"}, + {"name": " Padded ", "tool": "brush", "options": 5}, + ]}), + ); + assert_eq!(r["added"]["toolPresets"], 2); + assert_eq!(s.presets.tool_presets.len(), before + 2); + assert!(s.presets.tool_presets.iter().any(|t| t.name == "4x6 print")); + let padded = s.presets.tool_presets.iter().find(|t| t.name == "Padded").expect("trimmed name"); + assert_eq!(padded.options, json!({})); + // What was imported survives the next launch. + let mut restored = Session::new(); + restored.load_prefs_json(&s.prefs_to_json()).unwrap(); + assert_eq!(restored.presets.tool_presets, s.presets.tool_presets); + // The library stays within MAX_PRESETS. + let mut s = Session::new(); + let many: Vec = (0..MAX_PRESETS + 500).map(|i| json!({"name": format!("p{i}"), "tool": "brush"})).collect(); + let before = s.presets.tool_presets.len(); + let r = migrate(&mut s, json!({"tool_presets": many})); + assert_eq!(s.presets.tool_presets.len(), MAX_PRESETS); + assert_eq!(r["added"]["toolPresets"], MAX_PRESETS - before); + let _ = std::fs::remove_file(file); + } + #[test] fn bad_path_is_an_error() { let mut s = Session::new(); diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/mode_cmds.rs index fe22a192c7..c28b17689a 100644 --- a/crates/engine/src/mode_cmds.rs +++ b/crates/engine/src/mode_cmds.rs @@ -63,7 +63,8 @@ pub fn rotated_size(size: Size, deg: f64) -> Size { pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { const CMD: &str = "image.rotation.arbitrary"; - let angle = f64::from(num(p, "angle", 0.0)); + // At full precision: an f32 angle can grow the canvas 1 px past what `rotated_size` gives callers. + let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(0.0); if !angle.is_finite() || angle.abs() > 3600.0 { return Err(bad(CMD, "angle out of range")); } @@ -75,15 +76,18 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { if deg.rem_euclid(360.0).abs() < 1e-9 { return Ok(json!({"width": s.active().map(|d| d.doc.size.width), "height": s.active().map(|d| d.doc.size.height)})); } - let bg = s.tools.background; + // The Background stays opaque, whatever the background colour's alpha. + let bg = [s.tools.background[0], s.tools.background[1], s.tools.background[2], 1.0]; // Color Sampler points turn with the canvas (the same map the edit applies to the geometry). + // They are pixel indices, so map the pixel's centre, as the warp samples the pixels. { let old = s.active().ok_or(EngineError::NoDocument)?.doc.size; let new = rotated_size(old, deg); let (sn, cs) = deg.to_radians().sin_cos(); let (cx, cy) = (f64::from(old.width) / 2.0, f64::from(old.height) / 2.0); let (nx, ny) = (f64::from(new.width) / 2.0, f64::from(new.height) / 2.0); - s.set_sampler_map(Affine { m: [cs, sn, -sn, cs, nx - (cs * cx - sn * cy), ny - (sn * cx + cs * cy)] }); + let a = Affine { m: [cs, sn, -sn, cs, nx - (cs * cx - sn * cy), ny - (sn * cx + cs * cy)] }; + s.set_sampler_map(Affine::translate(0.5, 0.5).then(&a).then(&Affine::translate(-0.5, -0.5))); } let size = s.edit("Rotate Canvas", |doc, _| { let old = doc.size; @@ -108,7 +112,8 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { let rotated = photocraft_algo::transform::warp_surface(surf, src, &h, interp)?; let mut base = Surface::new(fmt); let fill = photocraft_raster::from_rgba(&fmt, bg); - base.write_region(canvas, &fill.repeat(canvas.width() as usize * canvas.height() as usize)); + // One shared tile per full tile, not a canvas-sized float buffer. + base.fill_rect(canvas, &fill); crate::transform_cmds::composite_over(&mut base, &rotated); base.prune(); *surf = base; @@ -444,6 +449,10 @@ fn parse_inks(cmd: &str, v: &Value, n: usize) -> Result> { if let Some(pts) = ink.get("curve").and_then(Value::as_array) { let mut curve: Vec = pts.iter().filter_map(|p| Some(CurvePoint { input: p.get(0)?.as_f64()? as f32 / 100.0, output: p.get(1)?.as_f64()? as f32 / 100.0 })).collect(); + // 1e39 is a valid JSON number but inf as f32, and a .pcraft with an inf curve can't be saved. + if curve.iter().any(|p| !p.input.is_finite() || !p.output.is_finite()) { + return Err(bad(cmd, "curve points must be finite numbers 0..100")); + } curve.sort_by(|a, b| a.input.total_cmp(&b.input)); if curve.len() >= 2 { d.curve = curve; diff --git a/crates/engine/src/mode_cmds/tests.rs b/crates/engine/src/mode_cmds/tests.rs index d6d020699e..e6892680f7 100644 --- a/crates/engine/src/mode_cmds/tests.rs +++ b/crates/engine/src/mode_cmds/tests.rs @@ -81,6 +81,27 @@ fn rotate_arbitrary_other_modes() { } } +#[test] +fn rotate_arbitrary_keeps_the_background_opaque_with_a_translucent_background_colour() { + let mut s = session(40, 20, 8, "rgb"); + s.execute("tools.setColors", json!({"background": "#00ff0080"})).unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": 30})).unwrap(); + let corner = doc(&s).layers[0].surface().unwrap().rgba(0, 0); + assert_eq!(corner, [0.0, 1.0, 0.0, 1.0], "the uncovered corner is opaque background colour"); +} + +#[test] +fn rotate_arbitrary_keeps_the_full_precision_angle() { + // Rounded to f32 this angle crosses a whole pixel: 1003 px instead of 1002, so a rotated crop + // that sized its canvas with `rotated_size` at f64 would land 1 px off. + let angle = 0.114_706_514_493_370_71; + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1000, "height": 1000})).unwrap(); + let r = s.execute("image.rotation.arbitrary", json!({"angle": angle})).unwrap(); + assert_eq!(rotated_size(Size::new(1000, 1000), angle), Size::new(1002, 1002)); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(1002), Some(1002))); +} + #[test] fn rotate_arbitrary_rotates_grouped_locked_children_and_preserves_lock() { let mut s = Session::new(); @@ -353,6 +374,20 @@ fn duotone_inks_and_display() { assert!(!session(4, 4, 8, "rgb").is_enabled("image.mode.duotone")); } +#[test] +fn duotone_curve_points_must_be_finite() { + let mut s = session(4, 4, 8, "gray"); + // 1e39 overflows f32 to inf, which the .pcraft writer refuses to save. + for curve in [json!([[0, 0], [100, 1e39]]), json!([[0, 0], [1e39, 50]]), json!([[-1e39, 0], [100, 100]])] { + let r = s.execute("image.mode.duotone", json!({"type": "monotone", "inks": [{"curve": curve}]})); + assert!(r.is_err(), "{curve} accepted"); + assert_eq!(doc(&s).mode, ColorMode::Grayscale); + } + s.execute("image.mode.duotone", json!({"type": "monotone", "inks": [{"curve": [[0, 0], [50, 70], [100, 100]]}]})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Duotone); + photocraft_format::save_to_bytes(doc(&s), &Default::default()).unwrap(); +} + #[test] fn modes_round_trip_through_pcraft() { let mut s = session(12, 12, 8, "rgb"); diff --git a/crates/engine/src/notes_cmds.rs b/crates/engine/src/notes_cmds.rs index 54bbd60b7a..2f589f3390 100644 --- a/crates/engine/src/notes_cmds.rs +++ b/crates/engine/src/notes_cmds.rs @@ -40,10 +40,12 @@ fn list_json(d: &Document) -> Value { json!({"notes": d.notes.iter().enumerate().map(|(i, n)| note_json(i, n)).collect::>()}) } -fn color_of(p: &Value) -> Option { - p.get("color")?; - let c = crate::commands::color_param(p, "color", [1.0, 1.0, 0.51, 1.0]); - Some(Color::rgb(c[0], c[1], c[2])) +fn color_of(cmd: &str, p: &Value) -> Result> { + 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])?; + Ok(Some(Color::rgb(c[0], c[1], c[2]))) } fn index_of(s: &Session, p: &Value, cmd: &str) -> Result { @@ -68,7 +70,7 @@ fn add(s: &mut Session, p: &Value) -> Result { modified: pdf_date(), ..Default::default() }; - if let Some(c) = color_of(p) { + if let Some(c) = color_of(CMD, p)? { n.color = c; } let i = s.edit("New Note", |d, _| { @@ -90,7 +92,7 @@ fn set(s: &mut Session, p: &Value) -> Result { if let Some(a) = p.get("author").and_then(Value::as_str) { n.author = a.to_string(); } - if let Some(c) = color_of(p) { + if let Some(c) = color_of(CMD, p)? { n.color = c; } if let Some(o) = p.get("open").and_then(Value::as_bool) { @@ -106,6 +108,9 @@ fn set(s: &mut Session, p: &Value) -> Result { n.position = [nx, ny]; // The popup travels with its icon. n.popup = [n.popup[0] + dx, n.popup[1] + dy, n.popup[2] + dx, n.popup[3] + dy]; + if !n.popup.iter().all(|v| v.is_finite()) { + return Err(bad(CMD, "the move is too far: the note popup would leave the representable range")); + } } if n == d.notes[i] { return Ok(json!({"index": i, "note": note_json(i, &n), "changed": false})); @@ -279,6 +284,19 @@ mod tests { assert!(s.execute("notes.set", json!({"index": 0})).is_err()); } + #[test] + fn huge_move_is_rejected_and_document_stays_saveable() { + let mut s = session(); + s.execute("notes.add", json!({"x": 1.7e308, "y": 0})).unwrap(); + let before = s.active().unwrap().doc.notes[0].clone(); + let past = s.active().unwrap().history.past_len(); + assert!(s.execute("notes.set", json!({"index": 0, "x": -1.7e308})).is_err()); + let a = s.active().unwrap(); + assert_eq!(a.doc.notes[0], before); + assert_eq!(a.history.past_len(), past); + assert!(photocraft_format::save_to_bytes(&a.doc, &Default::default()).is_ok()); + } + #[test] fn bad_params() { let mut s = session(); diff --git a/crates/engine/src/perspective_crop_cmds.rs b/crates/engine/src/perspective_crop_cmds.rs index 8acaf42ce2..0cd1f01604 100644 --- a/crates/engine/src/perspective_crop_cmds.rs +++ b/crates/engine/src/perspective_crop_cmds.rs @@ -188,7 +188,8 @@ fn warp_layers(layers: &mut [Layer], h: &Homography, interp: Interp, clip: Rect, fn apply(doc: &mut Document, q: &[[f64; 2]; 4], h: &Homography, size: (u32, u32), interp: Interp, bg: [f32; 4]) -> Result<()> { let (w, ht) = size; let clip = Rect::from_xywh(0, 0, w, ht); - let bg = photocraft_raster::from_rgba(&doc.pixel_format(), bg); + // The Background stays opaque, whatever the background colour's alpha. + let bg = photocraft_raster::from_rgba(&doc.pixel_format(), [bg[0], bg[1], bg[2], 1.0]); let background_id = doc.background().map(|l| l.id); warp_layers(&mut doc.layers, h, interp, clip, &bg, background_id)?; for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { @@ -298,6 +299,31 @@ mod tests { } } + /// Corners past the canvas: the uncovered Background is the background colour, opaque even + /// when that colour has alpha (the Background stays opaque). + #[test] + fn uncovered_background_is_opaque() { + let q = [[-20.0, -20.0], [180.0, -20.0], [180.0, 140.0], [-20.0, 140.0]]; + let mut s = skewed_ramp(SampleType::U8, &q, 100.0, 80.0); + s.execute("tools.setColors", json!({"background": "#00ff0080"})).unwrap(); + s.execute(CMD, json!({"corners": q, "width": 100, "height": 80})).unwrap(); + let corner = s.active().unwrap().doc.layers[0].surface().unwrap().rgba(0, 0); + assert_eq!(corner, [0.0, 1.0, 0.0, 1.0]); + } + + /// #7557: a quad low on a strongly converging photo (its horizon crosses the canvas, with the + /// canvas centre beyond it) is cropped, not left blank in the background colour. + #[test] + fn a_quad_below_a_horizon_across_the_canvas_keeps_its_content() { + let mut doc = Document::with_background("red", Size::new(100, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE); + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::from_xywh(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); + let mut s = Session::new(); + s.add_document(doc, None); + s.execute(CMD, json!({"corners": [[40, 70], [60, 70], [90, 95], [10, 95]], "width": 50, "height": 39})).unwrap(); + let px = s.active().unwrap().doc.layers[0].surface().unwrap().rgba(25, 20); + assert_eq!(px, [1.0, 0.0, 0.0, 1.0]); + } + /// Bad quads and params are refused with an error, and the document is untouched. #[test] fn perspective_crop_rejects_bad_quads() { diff --git a/crates/engine/src/photo_cmds.rs b/crates/engine/src/photo_cmds.rs index 09fd474aad..c729afd0d5 100644 --- a/crates/engine/src/photo_cmds.rs +++ b/crates/engine/src/photo_cmds.rs @@ -402,10 +402,18 @@ pub(crate) fn seam_blend(warped: &[Surface], canvas: Rect, order: &[usize], seam .collect() }) .collect(); - // Shift ROIs to canvas-relative coordinates for the blend. - let local: Vec = rois.iter().map(|r| RoiImage { x0: r.x0 - canvas.x0, y0: r.y0 - canvas.y0, ..r.clone() }).collect(); + // Shift ROIs to canvas-relative coordinates for the blend, and back after: a shifted copy + // would hold every source's pixels twice (#7758). + for r in &mut rois { + r.x0 -= canvas.x0; + r.y0 -= canvas.y0; + } let levels = if seamless { panorama::blend_levels(cw, chh).min(7) } else { 1 }; - let (blend, cov) = panorama::multiband(cw, chh, &local, &weights, levels); + let (blend, cov) = panorama::multiband(cw, chh, &rois, &weights, levels); + for r in &mut rois { + r.x0 += canvas.x0; + r.y0 += canvas.y0; + } let cc = fmt.mode.color_channels(); let nch = fmt.channels(); let mut composite = Surface::new(fmt); @@ -859,6 +867,7 @@ fn crop_and_straighten(s: &mut Session, _p: &Value) -> Result { let mut nd = Document::new(format!("{} copy {}", doc.name, k + 1), Size::new(pw, ph), doc.mode, doc.depth); nd.icc_profile = doc.icc_profile.clone(); nd.resolution_dpi = doc.resolution_dpi; + nd.duotone = doc.duotone.clone(); let mut bg = Layer::new("Background", LayerContent::Raster(px)); bg.locks.transparency = true; bg.locks.position = true; @@ -871,8 +880,13 @@ fn crop_and_straighten(s: &mut Session, _p: &Value) -> Result { // ---------- specs ---------- -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +/// Photoshop greys Crop and Straighten Photos out for Indexed Color documents. +fn not_indexed(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.doc.mode == ColorMode::Indexed { + return Err("not available for Indexed Color documents".into()); + } + Ok(()) } fn always(_: &Session) -> std::result::Result<(), String> { @@ -907,7 +921,7 @@ pub fn specs() -> Vec { menu: &["File", "Automate"], shortcut: None, params: "{} → one new document per photo found on the scan", - enabled: has_doc, + enabled: not_indexed, run: crop_and_straighten, journal: true, }, @@ -1106,6 +1120,54 @@ mod tests { if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } } + /// A light scan with one dark tilted print on it. + fn scan_with_one_photo() -> Document { + let (w, h) = (300usize, 220usize); + let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; + let (s, co) = 5.0f64.to_radians().sin_cos(); + for y in 0..h { + for x in 0..w { + let (dx, dy) = (x as f64 + 0.5 - 150.0, y as f64 + 0.5 - 110.0); + let (u, v) = (co * dx + s * dy, -s * dx + co * dy); + if u.abs() < 80.0 && v.abs() < 55.0 { + px[y * w + x] = [0.2 + (u / 160.0) as f32 * 0.3, 0.25, 0.3, 1.0]; + } + } + } + doc_from("scan", &px, w, h, SampleType::U8) + } + + #[test] + fn crop_and_straighten_keeps_duotone_inks() { + let mut s = Session::new(); + s.add_document(scan_with_one_photo(), None); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.execute( + "image.mode.duotone", + json!({"type": "duotone", "inks": [{"name": "Black", "color": [0, 0, 0]}, {"name": "Orange", "color": [255, 128, 0]}]}), + ) + .unwrap(); + let src = s.documents()[0].doc.duotone.clone(); + assert!(src.is_some()); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + assert_eq!(r["photos"].as_array().unwrap().len(), 1, "{r}"); + let d = &s.documents()[1].doc; + assert_eq!(d.mode, ColorMode::Duotone); + assert_eq!(d.duotone, src); + } + + #[test] + fn crop_and_straighten_disabled_for_indexed() { + // Photoshop greys the command out for Indexed Color documents. + let mut s = Session::new(); + s.add_document(scan_with_one_photo(), None); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + assert_eq!(s.documents()[0].doc.mode, ColorMode::Indexed); + assert!(!s.is_enabled("file.automate.cropAndStraightenPhotos")); + assert!(s.execute("file.automate.cropAndStraightenPhotos", json!({})).is_err()); + assert_eq!(s.documents().len(), 1); + } + #[test] fn crop_and_straighten_makes_documents() { let (w, h) = (500usize, 360usize); diff --git a/crates/engine/src/plugin_cmds.rs b/crates/engine/src/plugin_cmds.rs index 5c7d2dd71a..a2044f5e8c 100644 --- a/crates/engine/src/plugin_cmds.rs +++ b/crates/engine/src/plugin_cmds.rs @@ -77,10 +77,17 @@ fn run(s: &mut Session, p: &Value) -> Result { *surf = plugin.apply(surf, canvas, selection.as_ref(), &resolved).map_err(err)?; return Ok(()); } + crate::commands::check_pixels_unlocked(doc, layer)?; + let keep_alpha = doc.effective_locks(layer).transparency; let l = doc.layer_mut(layer).ok_or(EngineError::NoLayer(layer))?; match &mut l.content { LayerContent::Raster(surf) => { + // Lock Transparency: the plug-in may change colour but not alpha (as built-in filters). + let before = keep_alpha.then(|| surf.clone()); *surf = plugin.apply(surf, canvas, selection.as_ref(), &resolved).map_err(err)?; + if let Some(before) = &before { + crate::filters::keep_alpha(before, surf); + } Ok(()) } LayerContent::Smart(_) => { diff --git a/crates/engine/src/plugin_cmds/tests.rs b/crates/engine/src/plugin_cmds/tests.rs index 3d178fada9..39bb1acc7d 100644 --- a/crates/engine/src/plugin_cmds/tests.rs +++ b/crates/engine/src/plugin_cmds/tests.rs @@ -155,6 +155,56 @@ fn params_are_validated_and_passed() { Session::new().execute("plugin.remove", json!({"id": "test.cmds.grey"})).unwrap(); } +#[test] +fn locked_layers_refuse_plugin_filters() { + // Like built-in filters: locked pixels (or Lock All) refuse the run with no undo step. + let id = "test.cmds.locks"; + Session::new().execute("plugin.install", json!({"data": b64(&wat_plugin(id, "{}", GREY))})).unwrap(); + for lock_all in [false, true] { + let mut s = doc(16); + let layer = s.active().unwrap().active_layer.unwrap(); + s.edit("lock", |doc, _| { + let l = doc.layer_mut(layer).unwrap(); + if lock_all { + l.locks.all = true; + } else { + l.locks.pixels = true; + } + Ok(()) + }) + .unwrap(); + let before = pixels(&s); + let r = s.execute("plugin.run", json!({"id": id})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("is locked")), "lock_all {lock_all}: {r:?}"); + assert_eq!(pixels(&s), before, "lock_all {lock_all}"); + s.execute("edit.undo", json!({})).unwrap(); + let l = s.active().unwrap().doc.layer(layer).unwrap(); + assert!(!l.locks.pixels && !l.locks.all, "the refused run left no undo step"); + // Unlocked, the plug-in runs. + s.execute("plugin.run", json!({"id": id})).unwrap(); + assert_ne!(pixels(&s), before); + } + // Lock Transparency: the run changes colour but keeps every pixel's alpha (GREY sets alpha too). + let mut s = doc(16); + let layer = s.active().unwrap().active_layer.unwrap(); + s.edit("lock", |doc, _| { + doc.layer_mut(layer).unwrap().locks.transparency = true; + Ok(()) + }) + .unwrap(); + let before = pixels(&s); + s.execute("plugin.run", json!({"id": id})).unwrap(); + let after = pixels(&s); + assert_ne!(after, before); + for (a, b) in after.as_chunks::<4>().0.iter().zip(before.as_chunks::<4>().0) { + assert_eq!(a[3], b[3], "alpha kept"); + if b[3] > 0.0 { + assert!((a[0] - 0.5).abs() < 1e-3, "colour changed: {a:?}"); + } + } + Session::new().execute("plugin.remove", json!({"id": id})).unwrap(); +} + #[test] fn hostile_plugins_fail_without_touching_the_document() { for (id, body) in [ diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 2c2507226d..77acd2e346 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -286,6 +286,10 @@ pub struct Interface { /// own one-row title bar (tiling window managers, desktops that draw their own decorations; /// #1271, #1316). Read when the app starts. macOS always uses the system's. pub system_title_bar: bool, + /// Show the active document's file name in the title bar and the OS window title. The tabs + /// already name the file, so this can be turned off for a plain "PhotoCraft" title (#5037). + /// The unsaved-changes mark stays either way. + pub show_file_name_in_title: bool, /// Notices (the lower-right cards) hide themselves after /// [`Interface::notification_duration_seconds`] unless the pointer rests on them (#2022). pub notification_auto_hide: bool, @@ -317,6 +321,7 @@ impl Default for Interface { enable_animations: true, show_bounding_box_when_dragging_layer: false, system_title_bar: false, + show_file_name_in_title: true, notification_auto_hide: true, notification_duration_seconds: 6, } @@ -1040,7 +1045,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ "type.textEngine", "type.recentFonts", "enhancedControls.scrubbySliderAcceleration", - "enhancedControls.touchGestures", "rawDefaults.colorSpace", "rawDefaults.bitDepth", "rawDefaults.resolution", @@ -1605,6 +1609,100 @@ impl PrefsStore { } } +/// A saved preference [`Session::load_prefs_json`] couldn't read (a wrong type, an unknown +/// choice) and left at its default. +#[derive(Clone, Debug, PartialEq)] +pub struct InvalidPref { + /// JSON keys from the top of the preferences file (`["fileHandling", "recentFileCount"]`), + /// kept apart because keys such as command ids contain dots. + pub keys: Vec, + /// The value the file held there. + pub value: Value, +} + +impl InvalidPref { + /// The dotted path, as `prefs.get` and `prefs.set` take it. + pub fn path(&self) -> String { + self.keys.join(".") + } +} + +/// How deep [`read_lenient`] looks for the readable parts of an unreadable value. +const LENIENT_DEPTH: usize = 32; + +/// Read `v` as a `T`. When that fails, start from `T::default()` and lay the file's values over +/// it one at a time, keeping each one the whole still reads with and descending into objects +/// that don't, so one bad value resets only itself. The values left out are added to +/// `invalid`, their keys after `prefix`. +fn read_lenient(v: Value, prefix: &[&str], invalid: &mut Vec) -> T +where + T: Default + Serialize + for<'de> Deserialize<'de>, +{ + if let Ok(t) = T::deserialize(&v) { + return t; + } + let prefix: Vec = prefix.iter().map(|k| (*k).to_string()).collect(); + let mut acc = serde_json::to_value(T::default()).unwrap_or(Value::Null); + let fits = |root: &Value| T::deserialize(root).is_ok(); + match v { + Value::Object(file) if acc.is_object() && fits(&acc) => { + lay_over(&mut acc, &mut Vec::new(), file, &fits, &prefix, invalid); + T::deserialize(&acc).unwrap_or_default() + } + value => { + invalid.push(InvalidPref { keys: prefix, value }); + T::default() + } + } +} + +/// [`read_lenient`]'s walk: lay `file` over the object at `at` inside `root`, key by key, so that +/// `root` always reads (`fits`). +fn lay_over( + root: &mut Value, + at: &mut Vec, + file: Map, + fits: &dyn Fn(&Value) -> bool, + prefix: &[String], + invalid: &mut Vec, +) { + for (k, fv) in file { + let Some(obj) = object_at(root, at) else { return }; + let old = obj.insert(k.clone(), fv.clone()); + if fits(root) { + continue; + } + // Back to the default. An object keeps its parts that read, and so does a new map entry + // (a shortcut set, a workspace) when it reads from an empty object. + let Some(obj) = object_at(root, at) else { return }; + let mut descend = fv.is_object() && at.len() < LENIENT_DEPTH && matches!(old, None | Some(Value::Object(_))); + match old { + Some(o) => obj.insert(k.clone(), o), + None if descend => obj.insert(k.clone(), Value::Object(Map::new())), + None => obj.remove(&k), + }; + at.push(k); + if descend && !fits(root) { + descend = false; + if let Some((key, parent)) = at.split_last() + && let Some(obj) = object_at(root, parent) + { + obj.remove(key); + } + } + match fv { + Value::Object(m) if descend => lay_over(root, at, m, fits, prefix, invalid), + value => invalid.push(InvalidPref { keys: prefix.iter().chain(at.iter()).cloned().collect(), value }), + } + at.pop(); + } +} + +/// The JSON object at `path` inside `root`. +fn object_at<'a>(root: &'a mut Value, path: &[String]) -> Option<&'a mut Map> { + path.iter().try_fold(root, |cur, k| cur.get_mut(k.as_str()))?.as_object_mut() +} + impl Session { /// The current preferences. pub fn prefs(&self) -> &Preferences { @@ -1653,8 +1751,14 @@ impl Session { /// Restore preferences saved by [`Session::prefs_to_json`]. Missing keys keep their /// defaults and unknown keys are ignored, so files from older and newer versions load. - pub fn load_prefs_json(&mut self, s: &str) -> std::result::Result<(), String> { + /// A value of the wrong type (a hand-edited `"recentFileCount": "ten"`) keeps its default + /// and everything else still loads (#6611); the returned list names those values. Only + /// text that isn't a JSON object fails as a whole. + pub fn load_prefs_json(&mut self, s: &str) -> std::result::Result, String> { let mut v: Value = serde_json::from_str(s).map_err(|e| format!("preferences: {e}"))?; + if !v.is_object() { + return Err("preferences: expected a JSON object".into()); + } // Saved preferences before appearance modes had one concrete theme. Preserve its // appearance instead of silently switching established users to Auto. if let Some(interface) = v.get_mut("interface").and_then(Value::as_object_mut) @@ -1675,9 +1779,10 @@ impl Session { } let color = v.as_object_mut().and_then(|m| m.remove("colorSettings")); let presets = v.as_object_mut().and_then(|m| m.remove("presets")); - let prefs: Preferences = serde_json::from_value(v).map_err(|e| format!("preferences: {e}"))?; + let mut invalid = Vec::new(); + let prefs: Preferences = read_lenient(v, &[], &mut invalid); if let Some(c) = color { - self.color.settings = serde_json::from_value(c).unwrap_or_default(); + self.color.settings = read_lenient(c, &["colorSettings"], &mut invalid); photocraft_compose::psblend::set_text_gamma(self.color.settings.blend_text_gamma); } self.prefs.edit(|p| *p = prefs); @@ -1685,7 +1790,7 @@ impl Session { self.load_presets_json(v); } self.apply_prefs(); - Ok(()) + Ok(invalid) } /// Full JSON view used by `prefs.get`: preferences plus `colorSettings`. diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs index 5314d1f197..55e41949b9 100644 --- a/crates/engine/src/prefs/tests.rs +++ b/crates/engine/src/prefs/tests.rs @@ -915,3 +915,50 @@ fn a_stranded_backup_is_named_in_the_error() { assert_eq!(std::fs::read_to_string(&b).unwrap(), "old B"); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn a_wrongly_typed_value_resets_only_that_field() { + // #6611: one bad value used to reset every preference. + let mut s = Session::new(); + let invalid = s + .load_prefs_json( + r#"{"general": {"beepWhenDone": true}, "fileHandling": {"recentFileCount": "ten", "autosaveMinutes": 5}, + "performance": {"historyStates": 20}, "shortcuts": {"edit.fill": "Cmd+Shift+F", "file.open": 7}}"#, + ) + .unwrap(); + assert!(s.prefs().general.beep_when_done); + assert_eq!(s.prefs().file_handling.autosave_minutes, 5, "a sibling in the same section survives"); + assert_eq!(s.prefs().file_handling.recent_file_count, 20, "the bad value takes the default"); + assert_eq!(s.prefs().performance.history_states, 20); + assert_eq!(s.prefs().shortcuts.get("edit.fill").map(String::as_str), Some("Cmd+Shift+F")); + assert!(!s.prefs().shortcuts.contains_key("file.open")); + let paths: Vec = invalid.iter().map(InvalidPref::path).collect(); + assert_eq!(paths, ["fileHandling.recentFileCount", "shortcuts.file.open"]); + assert_eq!(invalid[0].value, json!("ten")); + assert_eq!(invalid[1].keys, ["shortcuts", "file.open"]); +} + +#[test] +fn a_wrongly_typed_section_or_colour_setting_resets_only_that_part() { + let mut s = Session::new(); + let invalid = s + .load_prefs_json( + r#"{"general": "loud", "performance": {"historyStates": 20}, + "colorSettings": {"workingRgb": "display-p3", "askOnMismatch": "yes"}}"#, + ) + .unwrap(); + assert_eq!(s.prefs().general, General::default()); + assert_eq!(s.prefs().performance.history_states, 20); + assert_eq!(s.color.settings.working_rgb, "display-p3", "the rest of the colour settings load"); + let paths: Vec = invalid.iter().map(InvalidPref::path).collect(); + assert_eq!(paths, ["general", "colorSettings.askOnMismatch"]); + // A valid file reports nothing; one that isn't an object still fails as a whole. + assert!(s.load_prefs_json(&s.prefs_to_json()).unwrap().is_empty()); + for bad in ["[1, 2]", "42", "\"prefs\"", "null", "{", ""] { + assert!(s.load_prefs_json(bad).is_err(), "{bad}"); + } + // Deep nesting and odd values don't panic. + let deep = format!("{{\"general\": {}1{}}}", "{\"a\":".repeat(100), "}".repeat(100)); + assert!(s.load_prefs_json(&deep).is_ok()); + assert!(s.load_prefs_json(r#"{"interface": {"theme": 3, "uiScale": [1]}, "workspaces": {"x": 1}, "menus": 1}"#).is_ok()); +} diff --git a/crates/engine/src/preset_import_cmds.rs b/crates/engine/src/preset_import_cmds.rs index 8da6cee8a0..51ce9bf078 100644 --- a/crates/engine/src/preset_import_cmds.rs +++ b/crates/engine/src/preset_import_cmds.rs @@ -49,13 +49,32 @@ pub(crate) fn file_bytes(p: &Value, cmd: &str, what: &str) -> Result<(Vec, S Ok((bytes, stem)) } -/// A name not used by any preset in `taken` (case-insensitive): `name`, `name 2`, `name 3`… -fn unique(name: &str, taken: &[String]) -> String { - let free = |n: &str| !taken.iter().any(|t| t.eq_ignore_ascii_case(n)); - if free(name) { - return name.to_string(); +/// The preset names in use, for naming new presets. +struct UniqueNames { + /// Every name in use, ASCII-lowercased. + taken: std::collections::HashSet, + /// The next number to try for each repeated name (lowercased). + next: std::collections::HashMap, +} + +impl UniqueNames { + fn new<'a>(names: impl IntoIterator) -> Self { + UniqueNames { taken: names.into_iter().map(str::to_ascii_lowercase).collect(), next: std::collections::HashMap::new() } + } + + /// A name not in use (case-insensitive): `name`, `name 2`, `name 3`… It is in use from then on. + fn unique(&mut self, name: &str) -> String { + let key = name.to_ascii_lowercase(); + if self.taken.insert(key.clone()) { + return name.to_string(); + } + // Resume numbering per name, so a file of identical names stays linear. + let from = self.next.get(&key).copied().unwrap_or(2); + let i = (from..).find(|i| !self.taken.contains(&format!("{key} {i}"))).unwrap_or(from); + self.taken.insert(format!("{key} {i}")); + self.next.insert(key, i + 1); + format!("{name} {i}") } - (2..).map(|i| format!("{name} {i}")).find(|n| free(n)).unwrap_or_else(|| name.to_string()) } fn import_abr(s: &mut Session, p: &Value) -> Result { @@ -93,11 +112,10 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io if p.get("replace").and_then(Value::as_bool).unwrap_or(true) { s.tools.presets.retain(|x| x.builtin || x.group != group); } - let mut taken: Vec = s.tools.presets.iter().map(|x| x.name.clone()).collect(); + let mut taken = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())); let mut names = Vec::with_capacity(imp.presets.len()); for mut preset in imp.presets { - preset.name = unique(&preset.name, &taken); - taken.push(preset.name.clone()); + preset.name = taken.unique(&preset.name); names.push(preset.name.clone()); s.tools.presets.push(preset); } @@ -180,8 +198,7 @@ fn import_image(s: &mut Session, p: &Value) -> Result { let doc = crate::file_cmds::import(decode_name, &bytes)?; let (v, w, h) = image_paint(&doc, cmd)?; let (brush, tw, th) = crate::brush_cmds::sampled_brush(cmd, &v, w, h)?; - let taken: Vec = s.tools.presets.iter().map(|x| x.name.clone()).collect(); - let name = unique(&name, &taken); + let name = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())).unique(&name); s.tools.presets.push(photocraft_paint::BrushPreset { name: name.clone(), brush: brush.clone(), @@ -526,10 +543,55 @@ mod tests { assert_eq!(s.tools.presets.len(), n, "a failed import adds nothing"); } + /// A version 1 brush with a computed tip and no name is named after its tip ("9 px Round"). The + /// import used to number each repeated name by searching the preset names once for every number + /// it tried, so importing 10,000 such brushes took minutes. The test fails when the import takes + /// more than 20 seconds. + #[test] + fn repeated_brush_names_are_numbered_in_linear_time() { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut s = Session::new(); + s.execute("brush.presets.save", json!({"name": "9 PX ROUND 3"})).unwrap(); + let round = LegacyBrush { + name: String::new(), + spacing: 25, + anti_alias: true, + tip: LegacyTip::Computed { diameter: 9, hardness: 100, angle: 0, roundness: 100 }, + }; + let data = photocraft_paint::tile::b64_encode(&write_v12(1, &vec![round; 10_000], false).unwrap()); + let r = s.execute("brush.presets.importAbr", json!({"data": data})).unwrap(); + let names: Vec = r["imported"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); + let _ = tx.send(names); + }); + let names = match rx.recv_timeout(std::time::Duration::from_secs(20)) { + Ok(names) => names, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!("importing the brushes did not finish"), + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => panic!("the import thread panicked"), + }; + // Numbering starts at 2 and skips the number a preset already uses, in any letter case. + assert_eq!(names[..4], ["9 px Round", "9 px Round 2", "9 px Round 4", "9 px Round 5"]); + assert_eq!(names.last(), Some(&format!("9 px Round {}", names.len() + 1))); + assert_eq!(names.iter().collect::>().len(), names.len()); + } + + #[test] + fn repeated_brush_names_take_the_first_free_number() { + let mut s = Session::new(); + s.execute("brush.presets.save", json!({"name": "speckle 3"})).unwrap(); + let tip = AbrSample { id: String::new(), width: 6, height: 4, depth: 8, data: vec![255; 24] }; + let brush = |name: &str| LegacyBrush { name: name.into(), spacing: 25, anti_alias: true, tip: LegacyTip::Sampled(tip.clone()) }; + let file = write_v12(2, &["Speckle", "SPECKLE", "speckle", "Speckle 2", "Speckle", "hard round"].map(brush), true).unwrap(); + let r = s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&file)})).unwrap(); + // Names that differ only in letter case count as the same name. The file's "Speckle 2" comes + // after "SPECKLE" took that name, and "hard round" clashes with the built-in Hard Round. + assert_eq!(r["imported"], json!(["Speckle", "SPECKLE 2", "speckle 4", "Speckle 2 2", "Speckle 5", "hard round 2"])); + } + #[test] fn unique_names() { - let taken = vec!["A".to_string(), "a 2".to_string()]; - assert_eq!(unique("a", &taken), "a 3"); - assert_eq!(unique("B", &taken), "B"); + let mut taken = UniqueNames::new(["A", "a 2"]); + assert_eq!(taken.unique("a"), "a 3"); + assert_eq!(taken.unique("B"), "B"); } } diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rs index 7c92dfba97..2a700aad99 100644 --- a/crates/engine/src/presets/gradients.rs +++ b/crates/engine/src/presets/gradients.rs @@ -604,7 +604,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { let g = preset_param(s, p, CMD)?; let stops = g.doc_stops(s.tools.foreground, s.tools.background); let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(90.0) as f32; - let scale = (p.get("scale").and_then(Value::as_f64).unwrap_or(100.0) as f32 / 100.0).clamp(0.1, 1.5); + let scale = crate::gradient_fill_cmds::clamp_scale(p.get("scale").and_then(Value::as_f64).unwrap_or(100.0) as f32 / 100.0); let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")); let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); let id = s.edit("New Gradient Fill Layer", |doc, active| { @@ -696,7 +696,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: leak(format!( - r##"{{"preset":name?=current|{stops},"angle":deg=90,"style":"linear|radial|angle|reflected|diamond"="linear","scale":10..150=100,"reverse":bool}} → {{layer}}"## + r##"{{"preset":name?=current|{stops},"angle":deg=90,"style":"linear|radial|angle|reflected|diamond"="linear","scale":1..1000=100,"reverse":bool}} → {{layer}}"## )), enabled: super::has_doc, run: apply, diff --git a/crates/engine/src/presets/mod.rs b/crates/engine/src/presets/mod.rs index 6c722c62ef..e5c3415f7d 100644 --- a/crates/engine/src/presets/mod.rs +++ b/crates/engine/src/presets/mod.rs @@ -168,10 +168,29 @@ impl PresetState { } impl Session { - /// Restore presets saved by [`PresetState::to_json`]. Missing sets keep their defaults; a - /// malformed blob is ignored (presets are never worth refusing to start over). + /// Restore presets saved by [`PresetState::to_json`]. Missing or malformed sets keep their + /// defaults (presets are never worth refusing to start over). Each set loads on its own: the + /// shell writes back only the keys that changed, so one damaged set would otherwise discard + /// every other set, saved document presets included, at each launch (#5602). pub fn load_presets_json(&mut self, v: Value) { - let Ok(p) = serde_json::from_value::(v) else { return }; + let Value::Object(mut m) = v else { return }; + fn take(m: &mut serde_json::Map, key: &str) -> Option { + m.remove(key).filter(|v| !v.is_null()).and_then(|v| serde_json::from_value(v).ok()) + } + let p = Persisted { + gradients: take(&mut m, "gradients"), + gradient: take(&mut m, "gradient"), + styles: take(&mut m, "styles"), + shapes: take(&mut m, "shapes"), + pattern_groups: take(&mut m, "pattern_groups"), + tool_presets: take(&mut m, "tool_presets"), + documents: take(&mut m, "documents"), + recent_documents: take(&mut m, "recent_documents"), + export_presets: take(&mut m, "export_presets"), + custom_shapes: take(&mut m, "custom_shapes"), + layer_defaults: take(&mut m, "layer_defaults"), + swatches: take(&mut m, "swatches"), + }; let st = &mut self.presets; if let Some(g) = p.gradients { st.gradients = g; @@ -343,6 +362,9 @@ pub(crate) fn edit_groups(groups: &mut Vec>, action: &str, p: let g = req_str(p, "group", cmd)?; let to = req_str(p, "name", cmd)?.to_string(); let i = groups.iter().position(|x| x.name == g).ok_or_else(|| bad(cmd, format!("no group \"{g}\"")))?; + if g != to && groups.iter().any(|x| x.name == to) { + return Err(bad(cmd, format!("a group named \"{to}\" already exists"))); + } groups[i].name = to.clone(); Ok(json!({"group": to})) } diff --git a/crates/engine/src/presets/tests.rs b/crates/engine/src/presets/tests.rs index dcfc4e94d8..db719afb1d 100644 --- a/crates/engine/src/presets/tests.rs +++ b/crates/engine/src/presets/tests.rs @@ -317,6 +317,23 @@ fn gradient_new_rename_move_delete_groups() { assert!(s.execute("gradient.presets.edit", json!({"action": "explode"})).is_err()); } +#[test] +fn gradient_rename_group_refuses_a_name_another_group_has() { + let mut s = Session::new(); + s.execute("gradient.presets.edit", json!({"action": "newGroup", "name": "Pastels"})).unwrap(); + let names = |s: &mut Session| -> Vec { + s.execute("gradient.presets.list", json!({})).unwrap()["groups"].as_array().unwrap().iter().map(|g| g["name"].clone()).collect() + }; + let before = names(&mut s); + assert!(before.contains(&json!("Blues"))); + let err = s.execute("gradient.presets.edit", json!({"action": "renameGroup", "group": "Pastels", "name": "Blues"})).unwrap_err(); + assert!(err.to_string().contains("already exists"), "{err}"); + assert_eq!(names(&mut s), before, "a refused rename leaves the groups unchanged"); + // Renaming a group to its own name is fine. + s.execute("gradient.presets.edit", json!({"action": "renameGroup", "group": "Pastels", "name": "Pastels"})).unwrap(); + assert_eq!(names(&mut s), before); +} + #[test] fn presets_persist_through_preferences_json() { let mut s = Session::new(); @@ -748,3 +765,47 @@ fn clone_source_errors_and_overlay() { assert_eq!(v["width"], json!(1000.0)); assert_eq!(v["rotation"], json!(-90.0)); } + +// ------------------------------------------------------------------ persistence + +/// #5602: one damaged preset set in the preferences file must not discard the saved New +/// Document presets (or any other set) at the next launch. +#[test] +fn a_damaged_preset_set_keeps_the_other_sets() { + let mut s = Session::new(); + let settings = json!({"width": 1600, "height": 900, "resolution": 144}); + s.execute("document.presets.save", json!({"name": "Banner", "settings": settings})).unwrap(); + let saved = s.presets.to_json(&s); + for key in ["gradients", "gradient", "styles", "shapes", "pattern_groups", "custom_shapes", "layer_defaults", "swatches"] { + let mut blob = saved.clone(); + blob[key] = json!("not a preset set"); + let mut next = Session::new(); + next.load_presets_json(blob); + assert_eq!(next.presets.documents, s.presets.documents, "damaged `{key}`"); + assert_eq!(next.presets.tool_presets.len(), Session::new().presets.tool_presets.len(), "damaged `{key}`"); + } + // Null sets keep their defaults, as before. + let mut next = Session::new(); + next.load_presets_json(json!({"tool_presets": null, "gradients": null, "documents": saved["documents"].clone()})); + assert_eq!(next.presets.tool_presets.len(), Session::new().presets.tool_presets.len()); + assert_eq!(next.presets.gradients.len(), Session::new().presets.gradients.len()); + assert_eq!(next.presets.documents, s.presets.documents); +} + +// ------------------------------------------------------------------ export presets + +#[test] +fn export_presets_survive_a_presets_json_round_trip() { + let mut s = Session::new(); + s.execute("file.export.presets.save", json!({"name": "Web", "settings": {"format": "jpg", "quality": 70}})).unwrap(); + assert_eq!(s.presets.export_presets.len(), 1); + + let saved = s.presets.to_json(&s); + assert_eq!(saved["export_presets"].as_array().map(Vec::len), Some(1)); + + let mut restored = Session::new(); + restored.load_presets_json(saved); + assert_eq!(restored.presets.export_presets.len(), 1); + assert_eq!(restored.presets.export_presets[0].name, "Web"); + assert_eq!(restored.presets.export_presets[0].settings.format, "jpg"); +} diff --git a/crates/engine/src/presets/tools.rs b/crates/engine/src/presets/tools.rs index 796a66623e..2746c1576e 100644 --- a/crates/engine/src/presets/tools.rs +++ b/crates/engine/src/presets/tools.rs @@ -37,7 +37,7 @@ impl Named for ToolPreset { pub const MAX_PRESETS: usize = 1000; /// A preset name: trimmed, 1–[`MAX_NAME`](crate::brush_preset_cmds::MAX_NAME) characters. -fn checked_name(name: &str, cmd: &str) -> Result { +pub(crate) fn checked_name(name: &str, cmd: &str) -> Result { let name = name.trim(); if name.is_empty() { return Err(bad(cmd, "the preset name is empty")); diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 9a0af4a054..0a1701a166 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -8,6 +8,12 @@ //! `"dryRun": true` reports the backend command without spooling; a PDF is kept only at an //! explicit output path. Shared spooler transport files are private and automatically removed. //! +//! Where `lp` is not on the path (a Flatpak has none), the job goes to CUPS over IPP in-process +//! (`photocraft-ipp`, through the sandbox's `--socket=cups`), and when no print server or no +//! printer is reachable, to the app's spooler, the XDG Print portal (`Session::print_spooler`; +//! `PHOTOCRAFT_PRINT_PORTAL=1` prefers it, `=0` removes it). `"printServer"` names a server for +//! one job and always takes the IPP route; `file.printers` lists the queues (#2728). +//! //! Paths to Illustrator writes the document's paths as an Adobe Illustrator 3 compatible //! PostScript file (`m`/`L`/`C` path construction, `n`/`N` unpainted closed/open paths, `*u`/`*U` //! compound paths), following the public PostScript Language Reference and the AI3 format notes. @@ -31,6 +37,191 @@ fn other(e: impl std::fmt::Display) -> EngineError { EngineError::Other(e.to_string()) } +// ---------- Spooling ---------- + +/// A rendered page on its way to the printer: what the IPP route and the app's spooler need. +#[derive(Debug, Clone)] +pub struct PrintJob { + pub pdf: Vec, + /// The printer asked for; `None` means the default. + pub printer: Option, + pub copies: u32, + /// The queue entry's name: the document's. + pub title: String, + /// A print server named in the request (`printServer`), else the system's. + pub server: Option, + /// The page size in points, as laid out (landscape already applied). + pub paper: (f64, f64), + pub landscape: bool, +} + +/// A spooler's work: the job in, where it went out. +pub type SpoolFn = std::sync::Arc std::result::Result + Send + Sync>; + +/// A further route to the printer, installed by the app on `Session::print_spooler`: the XDG +/// Print portal, which shows the system print dialog from inside a sandbox. It takes the jobs +/// no other route can (no print server reachable, no printer set up), or every job when +/// `preferred`. +#[derive(Clone)] +pub struct Spooler { + /// Reported as the job's `backend`. + pub name: &'static str, + pub preferred: bool, + /// Returns where the job went ("the system print dialog"). + pub run: SpoolFn, +} + +/// Why the IPP route could not spool: no route at all (the app's spooler may have one), or a +/// failure on a route that exists (a wrong printer name, a rejected job). +enum SpoolError { + NoRoute(String), + Failed(String), +} + +/// Sends the job and says where it went and through what. A named print server takes the IPP +/// route. Otherwise: the app's spooler when it is preferred; else `craft-print` (`lp`, or the +/// Windows spooler) when it is there; else CUPS over IPP; and the app's spooler when that had +/// no route either. A route that exists but fails (an unknown printer, a refused job) is an +/// error, never a fall-through. +fn spool_job(spooler: Option<&Spooler>, job: &PrintJob, lp: &craft_print::Job) -> Result<(String, String)> { + let app = |sp: &Spooler| (sp.run)(job).map(|m| (m, sp.name.to_string())).map_err(other); + if job.server.is_none() { + if let Some(sp) = spooler.filter(|sp| sp.preferred) { + return app(sp); + } + if let Some(name) = system_spooler() { + return craft_print::submit(&job.pdf, lp).map(|m| (m, name.to_string())).map_err(other); + } + } + match cups_spool(job) { + Ok(m) => Ok((m, "ipp".into())), + Err(SpoolError::NoRoute(why)) => match spooler { + Some(sp) => app(sp), + None => Err(other(why)), + }, + Err(SpoolError::Failed(why)) => Err(other(why)), + } +} + +/// The spooler `craft-print` can talk to, as the job's `backend` name: `lp` when CUPS' command +/// is on the path, the Windows spooler on Windows. `None` in a sandbox without `lp` and in the +/// browser. +fn system_spooler() -> Option<&'static str> { + match craft_print::backend()? { + craft_print::Backend::WindowsPdf => Some("windows"), + craft_print::Backend::Cups => { + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path).any(|dir| dir.join("lp").is_file()).then_some("lp") + } + } +} + +/// The printer a job goes to: the one asked for when the server knows it, else the default, +/// else the only one; otherwise an error that names what there is. +#[cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))] +fn resolve_printer(requested: Option<&str>, default: Option<&str>, printers: &[photocraft_ipp::Printer]) -> std::result::Result { + let names: Vec<&str> = printers.iter().map(|p| p.name.as_str()).collect(); + let known = |n: &str| names.iter().find(|k| k.eq_ignore_ascii_case(n)).map(|k| (*k).to_string()); + if let Some(r) = requested { + let choices = if names.is_empty() { "none".to_string() } else { names.join(", ") }; + return known(r).ok_or_else(|| SpoolError::Failed(format!("no printer called `{r}`; the print server knows: {choices}"))); + } + if printers.is_empty() { + return Err(SpoolError::NoRoute("no printer is set up on this computer; add one in the system settings, or print to PDF".into())); + } + if let Some(d) = default.and_then(known) { + return Ok(d); + } + match names.as_slice() { + [only] => Ok((*only).to_string()), + _ => Err(SpoolError::Failed(format!("no default printer; choose one in the Printer field: {}", names.join(", ")))), + } +} + +#[cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))] +fn cups_server(named: Option<&str>) -> std::result::Result { + match named { + Some(server) => { + let ep = photocraft_ipp::Endpoint::parse(server); + if !ep.reachable() { + return Err(SpoolError::Failed(format!("no print server at {ep}"))); + } + Ok(ep) + } + None => photocraft_ipp::Endpoint::detect() + .ok_or_else(|| SpoolError::NoRoute("no print server: CUPS is not running, or not reachable from this sandbox; print to PDF instead".into())), + } +} + +/// The IPP route: the job to the system's (or the named) CUPS server. +#[cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))] +fn cups_spool(job: &PrintJob) -> std::result::Result { + let failed = |e: photocraft_ipp::Error| SpoolError::Failed(e.to_string()); + let ep = cups_server(job.server.as_deref())?; + let printers = photocraft_ipp::printers(&ep).map_err(failed)?; + let default = printers.iter().find(|p| p.is_default).map(|p| p.name.clone()); + let printer = resolve_printer(job.printer.as_deref(), default.as_deref(), &printers)?; + let is_class = printers.iter().any(|p| p.name == printer && p.is_class); + let user = std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_else(|_| "photocraft".into()); + let id = photocraft_ipp::print_job( + &ep, + &photocraft_ipp::Job { printer: &printer, is_class, title: &job.title, user: &user, copies: job.copies, document: &job.pdf, format: "application/pdf" }, + ) + .map_err(failed)?; + Ok(format!("job {id} on {printer}")) +} + +/// No IPP route here: a named server is a failure, the system's a missing route (the app's +/// spooler may have one). +#[cfg(any(target_arch = "wasm32", target_os = "windows"))] +fn cups_spool(job: &PrintJob) -> std::result::Result { + let why = if cfg!(target_arch = "wasm32") { + "printing needs the desktop app" + } else { + "a print server over IPP is not available on Windows yet; print to PDF instead" + }; + match job.server { + Some(_) => Err(SpoolError::Failed(why.into())), + None => Err(SpoolError::NoRoute(why.into())), + } +} + +/// `file.printers`: the printers the system's (or `printServer`'s) print server knows, with the default. From +/// `craft-print` (`lpstat`, the Windows spooler) where that is the route; over IPP for a named +/// server and where there is no `lp` (a sandbox). +fn system_printers(_s: &mut Session, p: &Value) -> Result { + let named = p.get("printServer").and_then(Value::as_str).filter(|v| !v.is_empty()); + if named.is_none() && system_spooler().is_some() { + let list = craft_print::printers(); + let default = list.iter().find(|p| p.default).map(|p| p.name.clone()); + let printers: Vec = list.into_iter().map(|p| json!({"name": p.name, "default": p.default})).collect(); + return Ok(json!({"server": Value::Null, "default": default, "printers": printers})); + } + #[cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))] + { + let ep = match cups_server(named) { + Ok(ep) => ep, + Err(SpoolError::NoRoute(why) | SpoolError::Failed(why)) => { + return Ok(json!({"server": Value::Null, "default": Value::Null, "printers": [], "note": why})); + } + }; + let list = photocraft_ipp::printers(&ep).map_err(other)?; + let default = list.iter().find(|p| p.is_default).map(|p| p.name.clone()); + let printers: Vec = list + .iter() + .map(|p| { + json!({"name": p.name, "info": p.info, "state": match p.state { 4 => "printing", 5 => "stopped", _ => "idle" }, "acceptingJobs": p.accepting_jobs, "default": p.is_default, "class": p.is_class}) + }) + .collect(); + Ok(json!({"server": ep.to_string(), "default": default, "printers": printers})) + } + #[cfg(not(all(not(target_arch = "wasm32"), not(target_os = "windows"))))] + { + let _ = named; + Ok(json!({"server": Value::Null, "default": Value::Null, "printers": [], "note": "listing printers is not available on this platform yet"})) + } +} + // ---------- PDF ---------- /// Paper sizes in points (portrait). @@ -343,6 +534,7 @@ fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result { let params = p.clone(); let worker_params = params.clone(); let command = cmd.to_string(); + let spooler = s.print_spooler.clone(); if send && !dry { // Session::execute remains synchronous; the desktop's Session::start snapshots here // and runs PDF composition and the potentially slow driver on a worker. @@ -352,7 +544,7 @@ fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result { false, move |ctx| { ctx.progress(0.0, "Print"); - render_and_spool(&doc, &worker_params, &command) + render_and_spool(&doc, &worker_params, &command, spooler.as_ref()) }, move |s, result| { remember_print(s, ¶ms); @@ -370,13 +562,13 @@ fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result { }, ); } - let result = render_and_spool(&doc, p, cmd)?; + let result = render_and_spool(&doc, p, cmd, spooler.as_ref())?; remember_print(s, p); crate::automate_cmds::fire_event(s, "print"); Ok(result) } -fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { +fn render_and_spool(doc: &Document, p: &Value, cmd: &str, spooler: Option<&Spooler>) -> Result { let PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks, emulsion_down } = layout(doc, p, cmd)?; let (img, color) = print_image(doc, p, cmd)?; let description = p @@ -394,7 +586,12 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { // Sending follows the shared command contract; fuzz tests explicitly request dryRun. // The worker returns its result before repeat settings and hooks are applied once. let handling = p.get("colorHandling").and_then(Value::as_str).unwrap_or("printerManages"); - if cfg!(windows) && send && !dry && output.is_none() && native_rgb_compatible(&page, handling) { + // A named print server always takes the IPP route and a preferred app spooler takes every + // job (the route order in `spool_job`), on Windows too: neither may enter the native path + // below, which would print on the local default printer instead. + let named_server = p.get("printServer").and_then(Value::as_str).is_some_and(|v| !v.is_empty()); + let skip_native = named_server || spooler.is_some_and(|sp| sp.preferred); + if cfg!(windows) && !skip_native && send && !dry && output.is_none() && native_rgb_compatible(&page, handling) { require_printing_enabled()?; let printed = print_windows(&page, p, &doc.name, copies)?; return Ok(json!({ @@ -402,10 +599,11 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { "copies": copies, "command": Value::Null, "sent": true, "spooler": printed, "color": color, })); } - if cfg!(windows) && send && !dry && output.is_none() && printer_settings(p)?.is_some() { + if cfg!(windows) && !skip_native && send && !dry && output.is_none() && printer_settings(p)?.is_some() { return Err(other("the selected color profile or page text requires PDF printing. Save as PDF, or clear Print Settings to use PDF printing.")); } let pdf = print_pdf(&page); + let pdf_len = pdf.len(); let job = craft_print::Job { printer: p.get("printer").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string), copies, @@ -425,13 +623,25 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { }; let mut sent = false; let mut spool = Value::Null; + let mut backend = Value::Null; if send && !dry { require_printing_enabled()?; - spool = json!(craft_print::submit(&pdf, &job).map_err(other)?); + let print_job = PrintJob { + printer: job.printer.clone(), + copies, + title: doc.name.clone(), + server: p.get("printServer").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string), + paper: (pw, ph), + landscape: p.get("orientation").and_then(Value::as_str) == Some("landscape"), + pdf, + }; + let (where_, via) = spool_job(spooler, &print_job, &job)?; + spool = json!(where_); + backend = json!(via); sent = true; } Ok( - json!({"pdf": pdf_path, "bytes": pdf.len(), "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, "copies": copies, "command": command, "sent": sent, "spooler": spool, "color": color}), + json!({"pdf": pdf_path, "bytes": pdf_len, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, "copies": copies, "command": command, "sent": sent, "spooler": spool, "backend": backend, "color": color}), ) } @@ -444,7 +654,11 @@ fn native_rgb_compatible(page: &PrintPage, handling: &str) -> bool { && page.label.as_deref().is_none_or(str::is_empty) } -/// Print One Copy repeats these. +/// Where the settings of the last print are kept in Preferences' remembered dialog settings. +pub const REMEMBERED: &str = "file.print"; + +/// Print One Copy repeats these, and Print opens with them. They are kept in the preferences as +/// well, so they survive a relaunch, as Photoshop's do (#7410). fn remember_print(s: &mut Session, p: &Value) { let mut remembered = p.clone(); if let Some(o) = remembered.as_object_mut() { @@ -453,9 +667,31 @@ fn remember_print(s: &mut Session, p: &Value) { // Output and dry-run choices are not remembered, so a send override must not survive them. o.remove("send"); } + let kept = remembered.clone(); + s.prefs.edit(|prefs| { + prefs.dialogs.insert(REMEMBERED.into(), kept); + }); s.file_menu.last_print = Some(remembered); } +/// Drops the `printer` of the settings `q` (and its driver settings) when the print server lists +/// printers but not that one, so the job goes to the default printer. An empty list can't tell. +fn drop_vanished_printer(q: &mut Value, listed: &[&str]) { + let Some(name) = q.get("printer").and_then(Value::as_str).filter(|n| !n.is_empty()) else { return }; + if listed.is_empty() || listed.iter().any(|l| l.eq_ignore_ascii_case(name)) { + return; + } + if let Some(o) = q.as_object_mut() { + o.remove("printer"); + o.remove("printerSettings"); + } +} + +/// The settings of the last print: this session's, else those remembered from an earlier one. +pub fn last_print(s: &Session) -> Option { + s.file_menu.last_print.clone().or_else(|| s.prefs().dialogs.get(REMEMBERED).filter(|v| v.is_object()).cloned()) +} + /// The `printer` parameter, or the system's default printer. fn printer_name(p: &Value) -> Result { if let Some(name) = p.get("printer").and_then(Value::as_str).filter(|v| !v.trim().is_empty()) { @@ -573,21 +809,18 @@ fn require_printing_enabled() -> Result<()> { } } -/// The printers the system spooler knows (Print's Printer menu): CUPS queues and driverless -/// destinations on macOS and Linux, `Win32_Printer` on Windows, none in the browser. -fn system_printers(_: &mut Session, _: &Value) -> Result { - let list = craft_print::printers(); - let default = list.iter().find(|p| p.default).map(|p| p.name.clone()); - let printers: Vec = list.into_iter().map(|p| json!({"name": p.name, "default": p.default})).collect(); - Ok(json!({"printers": printers, "default": default})) -} - fn print(s: &mut Session, p: &Value) -> Result { do_print(s, p, "file.print") } fn print_one_copy(s: &mut Session, p: &Value) -> Result { - let mut q = s.file_menu.last_print.clone().unwrap_or_else(|| json!({})); + let mut q = last_print(s).unwrap_or_else(|| json!({})); + // A printer remembered from an earlier session may be gone: then the default takes the job, + // as the Print dialog falls back (#7410). A list that can't be read decides nothing. + if let Ok(listed) = system_printers(s, &q) { + let names: Vec<&str> = listed["printers"].as_array().into_iter().flatten().filter_map(|p| p["name"].as_str()).collect(); + drop_vanished_printer(&mut q, &names); + } if let (Some(o), Some(extra)) = (q.as_object_mut(), p.as_object()) { for (k, v) in extra { o.insert(k.clone(), v.clone()); @@ -602,8 +835,15 @@ fn print_one_copy(s: &mut Session, p: &Value) -> Result { fn package(s: &mut Session, p: &Value) -> Result { let cmd = "file.package"; let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| bad(cmd, "missing \"dir\" (where to create the package folder)"))?; + // The copies are relinked by absolute path: a relative one would be resolved against the + // package document's folder, not the working directory `dir` is relative to. + // `folder`, `document` and `links` are built on it with `join`, so it is spelt the same way: + // `/` throughout, not a native prefix with `/` after it. + let dir = std::path::absolute(dir).map_or_else(|_| dir.to_string(), |d| d.to_string_lossy().into_owned()); + let dir = crate::file_cmds::forward_slashes(dir); let d = s.active().ok_or(EngineError::NoDocument)?; let doc = (*d.doc).clone(); + let document = d.path.clone(); let name = stem(&d.path.clone().unwrap_or_else(|| doc.name.clone())); // The native format keeps external links; our PSD writer has no `lnkE` (external linked // file) support yet, so a PSD package would embed or flatten them. @@ -612,7 +852,7 @@ fn package(s: &mut Session, p: &Value) -> Result { Some(f) => return Err(bad(cmd, format!("unknown package format `{f}` (pcraft|psd|psb)"))), None => "pcraft".into(), }; - let folder = join(dir, &crate::file_cmds::sanitize(&name)); + let folder = join(&dir, &crate::file_cmds::sanitize(&name)); let links_dir = join(&folder, "Links"); // Copy every linked file once; relink the copy of the document to the copies. let mut copied: Vec<(String, String)> = Vec::new(); @@ -629,7 +869,12 @@ fn package(s: &mut Session, p: &Value) -> Result { fname = format!("{}-{}", copied.len(), fname); } let t = join(&links_dir, &fname); - match read_file(path) { + // A path that is not followed is packaged as missing, like a file that is gone. + let Ok(file) = crate::doc_path::resolve_in(path, document.as_deref().map(std::path::Path::new)) else { + missing.push(path.clone()); + continue; + }; + match read_file(&file.to_string_lossy()) { Ok(bytes) => { write_file(&t, &bytes)?; copied.push((path.clone(), t.clone())); @@ -750,7 +995,7 @@ pub fn specs() -> Vec { CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } }; } - const PRINT_PARAMS: &str = r##"{"printerSettings":hex? (Windows driver settings),"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent}"##; + const PRINT_PARAMS: &str = r##"{"printerSettings":hex? (Windows driver settings),"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"printServer":"host[:port]|socket path"? (default: the system's CUPS; a named server is always printed to over IPP),"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent, spooler:where the job went|null, backend:"lp|windows|ipp|portal"|null}"##; vec![ spec!("file.print", "Print…", &["File"], Some("Cmd+P"), PRINT_PARAMS, native_doc, print), diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index d012f6de41..c54dddf6f8 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -5,7 +5,9 @@ fn tmp(name: &str) -> String { let d = std::env::temp_dir().join(format!("photocraft-print-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); - d.to_string_lossy().into_owned() + // Spelt the way command results spell paths, so an expectation built with `/` matches on + // Windows too. Win32 takes `/` as a separator, so the directory is still usable as one. + d.to_string_lossy().replace('\\', "/") } fn session(mode: &str, depth: u32) -> Session { @@ -224,6 +226,48 @@ fn printer_profile_can_be_an_installed_icc_file() { let _ = std::fs::remove_dir_all(&dir); } +/// #7410: the settings of the last print survive a relaunch, as Photoshop's do. They are kept in +/// the preferences (without the output, dry-run and send choices), and a new session with those +/// preferences, before printing anything, repeats them with Print One Copy. +#[test] +fn the_last_print_settings_survive_a_relaunch() { + let mut s = session("rgb", 8); + assert!(last_print(&s).is_none()); + s.execute("file.print", json!({"dryRun": true, "copies": 3, "paper": "a5", "scale": 50, "intent": "perceptual"})).unwrap(); + let kept = s.prefs().dialogs.get(REMEMBERED).cloned().expect("kept in the preferences"); + assert_eq!((&kept["paper"], &kept["scale"], &kept["intent"]), (&json!("a5"), &json!(50), &json!("perceptual"))); + assert!(kept.get("dryRun").is_none() && kept.get("output").is_none() && kept.get("send").is_none(), "{kept}"); + // A relaunch: a new session with these preferences, nothing printed in it yet. + let mut t = session("rgb", 8); + t.prefs.edit(|p| { + p.dialogs.insert(REMEMBERED.into(), kept.clone()); + }); + assert_eq!(last_print(&t), Some(kept)); + let r = t.execute("file.printOneCopy", json!({"dryRun": true})).unwrap(); + assert_eq!(r["copies"], 1); + assert_eq!(r["paper"], json!([419.53, 595.28])); + assert_eq!(r["scale"], 50.0); +} + +/// #7410: a printer remembered from an earlier session that the print server no longer lists is +/// dropped before Print One Copy repeats the settings (with its driver settings), so the default +/// printer takes the job; a listed one (in any case) stays, and an empty list can't tell. +#[test] +fn a_vanished_remembered_printer_falls_back_to_the_default() { + let settings = || json!({"printer": "Office", "printerSettings": "00ff", "paper": "a5"}); + let mut q = settings(); + drop_vanished_printer(&mut q, &["Studio", "Lab"]); + assert_eq!(q, json!({"paper": "a5"}), "gone: the default printer takes it"); + for listed in [&["Studio", "office"][..], &[][..]] { + let mut q = settings(); + drop_vanished_printer(&mut q, listed); + assert_eq!(q, settings(), "{listed:?}"); + } + let mut q = json!({"printer": "", "paper": "a5"}); + drop_vanished_printer(&mut q, &["Studio"]); + assert_eq!(q, json!({"printer": "", "paper": "a5"}), "the default printer stays the default"); +} + #[test] fn print_one_copy_repeats_the_last_settings() { let mut s = session("rgb", 8); @@ -254,7 +298,12 @@ fn package_copies_links_and_relinks() { let copied = format!("{dir}/pkg/Print Me/Links/art.png"); assert_eq!(r["links"], json!([copied])); assert!(std::path::Path::new(&copied).is_file()); + // Reported paths are `/`-spelt on every platform, not the native separator up to `dir` and + // `/` after it: a client hands them back to the control channel, which takes only `/`. let docp = r["document"].as_str().unwrap(); + for p in [r["folder"].as_str().unwrap(), docp, r["links"][0].as_str().unwrap()] { + assert!(!p.contains('\\'), "{p}"); + } assert!(docp.ends_with("Print Me/Print Me.pcraft")); let back = photocraft_io::import("Print Me.pcraft", &std::fs::read(docp).unwrap()).unwrap().document; let linked: Vec = back @@ -360,7 +409,7 @@ fn spool_transport_streams_pdf_and_propagates_refusal() { let printed = &s.documents().iter().find(|st| st.doc.id == source).unwrap().doc; assert_eq!((printed.size.width, printed.size.height), (150, 300), "print hook ran on the source document"); assert_eq!(out["sent"], true); - assert_eq!(out["spooler"], "request id is Office-42"); + assert_eq!((out["spooler"].as_str(), out["backend"].as_str()), (Some("request id is Office-42"), Some("lp"))); assert!(out["pdf"].is_null(), "spool-only printing leaves no diagnostic PDF"); let pdf = std::fs::read(format!("{dir}/received.pdf")).unwrap(); assert!(pdf.starts_with(b"%PDF-1.4")); @@ -434,3 +483,292 @@ fn printers_lists_the_spooler_destinations_without_a_document() { None => assert!(list.iter().all(|p| p["default"] == false)), } } + +/// Spooling tests run in a child process: `disable_printing` is process-wide and a test above +/// sets it, and CI sets `PHOTOCRAFT_NO_PRINT` for the whole shell. True in the child, which runs +/// the test body; the parent starts the child and checks that it passed. +fn in_child(test: &str, envs: &[(&str, &str)]) -> bool { + const CHILD: &str = "PHOTOCRAFT_TEST_PRINT_CHILD"; + if std::env::var_os(CHILD).is_some() { + return true; + } + let mut cmd = std::process::Command::new(std::env::current_exe().unwrap()); + cmd.args(["--exact", test, "--nocapture"]).env(CHILD, "1").env_remove("PHOTOCRAFT_NO_PRINT"); + for (k, v) in envs { + cmd.env(k, v); + } + // Bounded: a child stuck in a printer dialog or a driver must not hang the suite. + let mut child = cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn().unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break Some(status); + } + if std::time::Instant::now() > deadline { + let _ = child.kill(); + break None; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + }; + let out = child.wait_with_output().unwrap(); + assert!( + status.is_some_and(|s| s.success()), + "{}\nstdout: {}\nstderr: {}", + if status.is_none() { "the child did not finish within 120 s and was killed" } else { "the child failed" }, + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + false +} + +/// A spooler that keeps every job it gets. +fn recording_spooler(preferred: bool, seen: &std::sync::Arc>>) -> Spooler { + let seen = std::sync::Arc::clone(seen); + Spooler { + name: "test", + preferred, + run: std::sync::Arc::new(move |job: &PrintJob| { + seen.lock().unwrap().push(job.clone()); + Ok("queued".into()) + }), + } +} + +#[test] +fn a_preferred_app_spooler_takes_the_job() { + if !in_child("print_cmds::tests::a_preferred_app_spooler_takes_the_job", &[]) { + return; + } + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let mut s = session("rgb", 8); + s.print_spooler = Some(recording_spooler(true, &seen)); + let r = s.execute("file.print", json!({"copies": 2, "paper": "a4", "orientation": "landscape"})).unwrap(); + assert_eq!((r["sent"].as_bool(), r["backend"].as_str(), r["spooler"].as_str()), (Some(true), Some("test"), Some("queued"))); + assert!(r["pdf"].is_null(), "{r}"); + let jobs = seen.lock().unwrap(); + let job = &jobs[0]; + assert!(job.pdf.starts_with(b"%PDF-1.4")); + assert_eq!((job.copies, job.title.as_str(), job.printer.as_deref(), job.landscape), (2, "Print Me.psd", None, true)); + assert!((job.paper.0 - 841.89).abs() < 0.01 && (job.paper.1 - 595.28).abs() < 0.01); + drop(jobs); + // A named print server asks for the IPP route, preferred spooler or not. + let e = s.execute("file.print", json!({"printServer": "127.0.0.1:1"})).unwrap_err().to_string(); + assert!(e.contains("no print server at 127.0.0.1:1") || e.contains("not available on Windows"), "{e}"); + assert_eq!(seen.lock().unwrap().len(), 1); + // "output" keeps the file and does not spool unless asked. + let out = format!("{}/out.pdf", tmp("output")); + let r = s.execute("file.print", json!({"output": out})).unwrap(); + assert_eq!((r["sent"].as_bool(), r["pdf"].as_str()), (Some(false), Some(out.as_str()))); + assert!(std::path::Path::new(&out).exists()); +} + +#[cfg(not(target_os = "windows"))] +mod cups { + use super::*; + use photocraft_ipp::{ + Attribute, OP_CUPS_GET_CLASSES, OP_CUPS_GET_DEFAULT, OP_CUPS_GET_PRINTERS, OP_PRINT_JOB, Printer, Request, TAG_JOB_GROUP, TAG_NAME, TAG_PRINTER_GROUP, + }; + use std::io::{BufRead, BufReader, Read, Write}; + use std::sync::mpsc; + + fn printer(name: &str, is_default: bool) -> Printer { + Printer { name: name.into(), info: String::new(), state: 3, accepting_jobs: true, is_default, is_class: false } + } + + #[test] + fn the_printer_is_the_requested_one_else_the_default_else_the_only_one() { + let two = [printer("Office", false), printer("Lab", true)]; + assert_eq!(resolve_printer(None, Some("Lab"), &two).ok(), Some("Lab".into())); + assert_eq!(resolve_printer(Some("office"), Some("Lab"), &two).ok(), Some("Office".into())); + assert_eq!(resolve_printer(None, None, &two[..1]).ok(), Some("Office".into())); + match resolve_printer(None, None, &two) { + Err(SpoolError::Failed(e)) => assert!(e.contains("no default printer") && e.contains("Office, Lab"), "{e}"), + _ => panic!("several printers and no default must fail"), + } + match resolve_printer(Some("Nope"), Some("Lab"), &two) { + Err(SpoolError::Failed(e)) => assert!(e.contains("`Nope`") && e.contains("Office, Lab"), "{e}"), + _ => panic!("an unknown printer must fail"), + } + match resolve_printer(None, None, &[]) { + Err(SpoolError::NoRoute(e)) => assert!(e.contains("no printer is set up"), "{e}"), + _ => panic!("no printers is no route"), + } + // A printer asked for by name on a server without any is a failure, not a missing route. + match resolve_printer(Some("Office"), None, &[]) { + Err(SpoolError::Failed(e)) => assert!(e.contains("`Office`") && e.contains("none"), "{e}"), + _ => panic!("a named printer never falls through"), + } + // A stale default that the server no longer lists falls through to the only printer. + assert_eq!(resolve_printer(None, Some("Gone"), &two[..1]).ok(), Some("Office".into())); + } + + /// What the fake received per request: op, attributes, document. + type Seen = (u16, Vec, Vec); + + /// A fake CUPS on a TCP port: lists `printers` and `classes`, names `default`, accepts jobs + /// as id 42. Answers for as long as the test process lives. + fn fake_cups(printers: &'static [&'static str], classes: &'static [&'static str], default: Option<&'static str>) -> (String, mpsc::Receiver) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let server = format!("127.0.0.1:{}", listener.local_addr().unwrap().port()); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { break }; + let mut reader = BufReader::new(stream); + let (mut first, mut line, mut len) = (String::new(), String::new(), 0usize); + loop { + line.clear(); + if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + if first.is_empty() { + first = line.clone(); + } + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap(); + } + } + if first.is_empty() { + continue; // a reachability probe + } + let mut body = vec![0u8; len]; + reader.read_exact(&mut body).unwrap(); + let (op, attrs, doc) = photocraft_ipp::parse_request(&body).unwrap(); + let list = |names: &[&str]| { + if names.is_empty() { + return Request::new(0x0406, 1).end(); + } + let mut r = Request::new(0, 1); + for p in names { + r.group(TAG_PRINTER_GROUP); + r.attr(TAG_NAME, "printer-name", p.as_bytes()); + } + r.end() + }; + let reply = match op { + OP_CUPS_GET_PRINTERS => list(printers), + OP_CUPS_GET_CLASSES => list(classes), + OP_CUPS_GET_DEFAULT => match default { + Some(d) => { + let mut r = Request::new(0, 1); + r.group(TAG_PRINTER_GROUP); + r.attr(TAG_NAME, "printer-name", d.as_bytes()); + r.end() + } + None => Request::new(0x0406, 1).end(), + }, + OP_PRINT_JOB => { + let mut r = Request::new(0, 1); + r.group(TAG_JOB_GROUP); + r.integer("job-id", 42); + r.end() + } + _ => Request::new(0x0501, 1).end(), + }; + let _ = tx.send((op, attrs, doc)); + let mut out = reader.into_inner(); + let _ = out.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\n\r\n", reply.len()).as_bytes()); + let _ = out.write_all(&reply); + let _ = out.flush(); + } + }); + (server, rx) + } + + #[test] + fn a_named_server_is_printed_to_over_ipp() { + if !in_child("print_cmds::tests::cups::a_named_server_is_printed_to_over_ipp", &[]) { + return; + } + let (server, rx) = fake_cups(&["Office"], &["Lab"], Some("Lab")); + let mut s = session("rgb", 8); + let r = s.execute("file.print", json!({"printServer": server, "copies": 3})).unwrap(); + assert_eq!((r["sent"].as_bool(), r["backend"].as_str(), r["spooler"].as_str()), (Some(true), Some("ipp"), Some("job 42 on Lab"))); + assert!(r["pdf"].is_null()); + let job = std::iter::from_fn(|| rx.try_recv().ok()).find(|(op, _, _)| *op == OP_PRINT_JOB).expect("a Print-Job request"); + let attr = |name: &str| job.1.iter().find(|a| a.name == name).unwrap_or_else(|| panic!("{name}")); + assert!(attr("printer-uri").text().ends_with("/classes/Lab"), "{}", attr("printer-uri").text()); + assert_eq!( + (attr("copies").int(), attr("job-name").text().as_str(), attr("document-format").text().as_str()), + (Some(3), "Print Me.psd", "application/pdf") + ); + assert!(job.2.starts_with(b"%PDF-1.4")); + // The requested printer, in any case; an unknown one names the choices. + let r = s.execute("file.print", json!({"printServer": server, "printer": "office"})).unwrap(); + assert_eq!(r["spooler"], "job 42 on Office"); + let job = std::iter::from_fn(|| rx.try_recv().ok()).filter(|(op, _, _)| *op == OP_PRINT_JOB).last().expect("the second Print-Job"); + assert!(job.1.iter().any(|a| a.name == "printer-uri" && a.text().ends_with("/printers/Office"))); + let e = s.execute("file.print", json!({"printServer": server, "printer": "Nope"})).unwrap_err().to_string(); + assert!(e.contains("`Nope`") && e.contains("Office, Lab"), "{e}"); + // Printers can be listed. + let r = s.execute("file.printers", json!({"printServer": server})).unwrap(); + let names: Vec<&str> = r["printers"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); + assert_eq!((names, r["default"].as_str()), (vec!["Office", "Lab"], Some("Lab"))); + assert_eq!( + (r["printers"][1]["default"].as_bool(), r["printers"][1]["class"].as_bool(), r["printers"][0]["class"].as_bool()), + (Some(true), Some(true), Some(false)) + ); + } + + #[test] + fn without_a_printer_the_app_spooler_takes_over() { + if !in_child("print_cmds::tests::cups::without_a_printer_the_app_spooler_takes_over", &[]) { + return; + } + let (server, _rx) = fake_cups(&[], &[], None); + let mut s = session("gray", 8); + let e = s.execute("file.print", json!({"printServer": server})).unwrap_err().to_string(); + assert!(e.contains("no printer is set up"), "{e}"); + // Asking for a printer by name never falls through to another route. + let e = s.execute("file.print", json!({"printServer": server, "printer": "Office"})).unwrap_err().to_string(); + assert!(e.contains("`Office`"), "{e}"); + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + s.print_spooler = Some(recording_spooler(false, &seen)); + let r = s.execute("file.print", json!({"printServer": server})).unwrap(); + assert_eq!((r["backend"].as_str(), r["spooler"].as_str()), (Some("test"), Some("queued"))); + assert_eq!(seen.lock().unwrap().len(), 1); + // An unreachable named server is a failure, not a missing route. + let e = s.execute("file.print", json!({"printServer": "127.0.0.1:1"})).unwrap_err().to_string(); + assert!(e.contains("no print server at"), "{e}"); + let r = s.execute("file.printers", json!({"printServer": "127.0.0.1:1"})).unwrap(); + assert!(r["printers"].as_array().unwrap().is_empty() && r["note"].as_str().unwrap().contains("no print server")); + } + + /// The Flatpak case: no `lp` on the path, so the job goes to the system's CUPS over IPP + /// (`CUPS_SERVER` names it here), and with no print server at all to the app's spooler. + /// Runs in a child process, since the path is process-wide. + #[test] + fn without_lp_the_job_goes_over_ipp_then_to_the_app_spooler() { + const CHILD: &str = "PHOTOCRAFT_TEST_PRINT_NO_LP"; + if std::env::var_os(CHILD).is_some() { + let mut s = session("rgb", 8); + let r = s.execute("file.print", json!({"copies": 2})).unwrap(); + assert_eq!((r["sent"].as_bool(), r["backend"].as_str(), r["spooler"].as_str()), (Some(true), Some("ipp"), Some("job 42 on Office"))); + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + s.print_spooler = Some(recording_spooler(false, &seen)); + // The IPP route first, then the app's spooler only when there is no server. + let r = s.execute("file.print", json!({})).unwrap(); + assert_eq!(r["backend"], "ipp"); + assert!(seen.lock().unwrap().is_empty()); + // (CUPS_SERVER is read per job; an unreachable one is no route.) + let r = s.execute("file.print", json!({"printServer": "127.0.0.1:1"})).unwrap_err().to_string(); + assert!(r.contains("no print server at"), "{r}"); + println!("child ok"); + return; + } + let (server, rx) = fake_cups(&["Office"], &[], Some("Office")); + let no_lp = tempfile::tempdir().unwrap(); + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "print_cmds::tests::cups::without_lp_the_job_goes_over_ipp_then_to_the_app_spooler", "--nocapture"]) + .env(CHILD, "1") + .env("PATH", no_lp.path()) + .env("CUPS_SERVER", &server) + .env_remove("PHOTOCRAFT_NO_PRINT") + .output() + .unwrap(); + let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success() && stdout.contains("child ok"), "stdout: {stdout}\nstderr: {stderr}"); + let jobs = std::iter::from_fn(|| rx.try_recv().ok()).filter(|(op, _, _)| *op == OP_PRINT_JOB).count(); + assert_eq!(jobs, 2, "both prints reached the fake CUPS"); + } +} diff --git a/crates/engine/src/proof_sim.rs b/crates/engine/src/proof_sim.rs index f225a5a7a9..6c7afc15d9 100644 --- a/crates/engine/src/proof_sim.rs +++ b/crates/engine/src/proof_sim.rs @@ -18,6 +18,7 @@ use photocraft_cms::{Builtin, Intent, Lut3d, Transform}; use photocraft_color::SampleType; +use photocraft_color::convert::{linear_to_srgb, srgb_to_linear}; use photocraft_doc::Document; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -91,14 +92,16 @@ impl Default for HdrPreview { } impl HdrPreview { + /// Whether the preview passes values through unchanged. pub fn is_identity(&self) -> bool { self.highlight_compression || (self.exposure == 0.0 && self.gamma == 1.0) } + /// One encoded channel value through the 32-bit preview's exposure and gamma. fn apply(&self, v: f32) -> f32 { if self.is_identity() { return v; } - let lin = srgb_decode(v) * 2f32.powf(self.exposure); + let lin = srgb_to_linear(v) * 2f32.powf(self.exposure); srgb_encode(lin.max(0.0).powf(1.0 / self.gamma).min(1.0)) } } @@ -115,13 +118,9 @@ pub fn signature(c: &ColorState, doc: &Document) -> String { format!("{:?} {:?}", pv.setup.kind, h) } -fn srgb_decode(v: f32) -> f32 { - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } -} - +/// sRGB-encodes linear light after clamping it to 0..=1. fn srgb_encode(v: f32) -> f32 { - let v = v.clamp(0.0, 1.0); - if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } + linear_to_srgb(v.clamp(0.0, 1.0)) } /// Viénot et al. (1999): linear RGB → LMS. @@ -201,7 +200,7 @@ pub fn display_lut_with(c: &ColorState, doc: &Document, size: usize, include_hdr let protan = kind == ProofKind::Protanopia; Box::new(move |v| { let s = eval3(&to_srgb, &v); - let sim = dichromat(s.map(srgb_decode), protan).map(srgb_encode); + let sim = dichromat(s.map(srgb_to_linear), protan).map(srgb_encode); eval3(&to_mon, &sim) }) } @@ -262,6 +261,7 @@ fn run_kind(s: &mut Session, id: &str) -> Result { set_kind(s, kind) } +/// View › 32-bit Preview Options for the active document. fn preview_32(s: &mut Session, p: &Value) -> Result { const CMD: &str = "view.thirtyTwoBitPreviewOptions"; let id = s.active().ok_or(EngineError::NoDocument)?.doc.id; @@ -298,6 +298,7 @@ macro_rules! kind_spec { }; } +/// The View › Proof Setup commands. pub fn specs() -> Vec { vec![ kind_spec!("view.proofSetup.workingCyanPlate", "Working Cyan Plate"), @@ -325,6 +326,21 @@ pub fn specs() -> Vec { mod tests { use super::*; + /// The shared sRGB functions match the removed copies bit for bit. + #[test] + fn srgb_transfer_output_is_unchanged() { + let decode = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; + let encode = |v: f32| { + let v = v.clamp(0.0, 1.0); + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } + }; + for i in -2000..=6000 { + let v = i as f32 / 4000.0; + assert_eq!(srgb_to_linear(v).to_bits(), decode(v).to_bits(), "decode {v}"); + assert_eq!(srgb_encode(v).to_bits(), encode(v).to_bits(), "encode {v}"); + } + } + fn session(mode: &str, depth: u32) -> Session { let mut s = Session::new(); s.execute("file.new", json!({"width": 8, "height": 8, "mode": mode, "depth": depth})).unwrap(); diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs index 1d786c61fe..0605b27c91 100644 --- a/crates/engine/src/retouch_cmds.rs +++ b/crates/engine/src/retouch_cmds.rs @@ -15,7 +15,7 @@ use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen, use photocraft_color::{BlendMode, PixelFormat, SampleType}; use photocraft_doc::{Document, LayerContent, LayerId}; use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke, stroke_coverage}; +use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke}; use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde_json::{Value, json}; @@ -36,6 +36,64 @@ fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } } +/// A single stroke's accumulated coverage must stay at or under this many pixels (8192², so a +/// stroke corner to corner across a 24–36 MP canvas fits). Larger footprints return an error +/// instead of allocating. +const MAX_STROKE_PIXELS: u64 = 67_108_864; + +/// Refuse a stroke whose footprint would not fit the coverage budget, from the points and brush +/// size alone, before the renderer allocates anything for it. +fn reject_huge_stroke(cmd: &str, stroke: &Stroke) -> Result<()> { + // Dynamics place dabs beyond the input points, so half the tip is not the whole reach: + // Scattering offsets a centre by up to its amount times the tip size, and a Dual Brush dab + // reaches its own radius further. Pad by what those can add so this estimate does not fall + // short of what the renderer will cover. It is only the cheap early-out; the rendered extent + // is admitted for real in `coverage` below. + let b = &stroke.brush; + let size = f64::from(b.size.max(1.0)); + let scatter = if b.scattering.enabled { size * f64::from(b.scattering.scatter.jitter.max(0.0)) } else { 0.0 }; + let dual = if b.dual_brush.enabled { f64::from(b.dual_brush.size.max(0.0)) * 0.5 } else { 0.0 }; + let pad = size.mul_add(0.5, 4.0) + scatter + dual; + let mut min_x = f64::INFINITY; + let mut min_y = f64::INFINITY; + let mut max_x = f64::NEG_INFINITY; + let mut max_y = f64::NEG_INFINITY; + for q in &stroke.points { + min_x = min_x.min(q.x); + min_y = min_y.min(q.y); + max_x = max_x.max(q.x); + max_y = max_y.max(q.y); + } + if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() { + return Err(bad(cmd, "point coordinates must be finite")); + } + let w = (max_x - min_x + pad * 2.0).ceil().max(1.0); + let h = (max_y - min_y + pad * 2.0).ceil().max(1.0); + if !w.is_finite() || !h.is_finite() || w > 1.0e9 || h > 1.0e9 { + return Err(bad(cmd, format!("stroke too large (at most {MAX_STROKE_PIXELS} px)"))); + } + let area = (w as u64).saturating_mul(h as u64); + if area > MAX_STROKE_PIXELS { + return Err(bad(cmd, format!("stroke too large ({w:.0}×{h:.0} px, at most {MAX_STROKE_PIXELS})"))); + } + Ok(()) +} + +/// The stroke's coverage, with the **rendered** extent admitted before the dense buffer exists. +/// +/// `reject_huge_stroke` estimates from the input points; this is the real bound. Rendering is +/// tiled, so it holds only the tiles the dabs touch; the extent is read from those tiles once +/// every dab is placed (tips, dynamics and scattering included) and checked against `max`, and +/// only a stroke that fits is made dense. `max` is a parameter so tests can inject a small budget. +fn coverage_within(cmd: &str, stroke: &Stroke, max: u64) -> Result<(Rect, Vec)> { + photocraft_paint::retouch::stroke_coverage_within(stroke, max).ok_or_else(|| bad(cmd, format!("stroke too large (at most {max} px)"))) +} + +/// [`coverage_within`] at the shared allowance. +fn coverage(cmd: &str, stroke: &Stroke) -> Result<(Rect, Vec)> { + coverage_within(cmd, stroke, MAX_STROKE_PIXELS) +} + /// A pixel layer, a layer with a mask, or a targeted alpha channel / Quick Mask (as the Brush). fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> { if crate::channel_cmds::edits_channel(s) { @@ -313,6 +371,7 @@ fn clamp_samples(fmt: &PixelFormat, data: &mut [f32]) { fn clone_stamp(s: &mut Session, p: &Value) -> Result { const CMD: &str = "paint.cloneStamp"; let (stroke, id) = parse_brush(s, p, CMD)?; + reject_huge_stroke(CMD, &stroke)?; let which = sample_layers(p, CMD)?; let mode = blend_param(p, CMD)?; let aligned = flag(p, "aligned", true); @@ -337,7 +396,7 @@ fn clone_stamp(s: &mut Session, p: &Value) -> Result { return periodic::Composite { target: surf, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection: sel, lock, mode } .draw(bounds, &stroke.brush, &stroke.points, |r| clone_sample(pre, id, &before, which, r, &map, true, CMD)); } - let (bounds, cov) = stroke_coverage(&stroke); + let (bounds, cov) = coverage(CMD, &stroke)?; // Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned. let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?; Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) @@ -611,13 +670,14 @@ fn heal_region(fmt: &PixelFormat, src: &Region, dst: &Region, mask: &[bool]) -> fn healing_brush(s: &mut Session, p: &Value) -> Result { const CMD: &str = "paint.healingBrush"; let (stroke, id) = parse_brush(s, p, CMD)?; + reject_huge_stroke(CMD, &stroke)?; let which = sample_layers(p, CMD)?; let mode = blend_param(p, CMD)?; let aligned = flag(p, "aligned", true); let map = clone_mapping(s, p, &stroke, CMD)?; let off = map.offset(); let dmg = run_stroke(s, "Healing Brush", id, p, |pre, surf, sel, lock| { - let (bounds, cov) = stroke_coverage(&stroke); + let (bounds, cov) = coverage(CMD, &stroke)?; let (g, cov) = pad_coverage(bounds, &cov, 2); let fmt = surf.format(); let src = clone_sample(pre, id, surf, which, g, &map, false, CMD)?; @@ -650,6 +710,10 @@ fn history_brush(s: &mut Session, p: &Value) -> Result { const CMD: &str = "paint.historyBrush"; let (stroke, id) = parse_brush(s, p, CMD)?; let mode = blend_param(p, CMD)?; + // The coverage and the source region below are both dense over the stroke's bounds, so a + // thin stroke across a large canvas would still ask for the whole box. Refuse it from the + // points and brush size, before the source surface is cloned or anything is rendered (#4961). + reject_huge_stroke(CMD, &stroke)?; let live = s.live_commit.take().filter(|l| l.matches(s, CMD, p, &stroke.points)); let from_live = live.is_some(); let src_surface = history_source(s, id, p, CMD)?; @@ -660,7 +724,7 @@ fn history_brush(s: &mut Session, p: &Value) -> Result { } let fmt = surf.format(); let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; - let (bounds, cov) = stroke_coverage(&stroke); + let (bounds, cov) = coverage(CMD, &stroke)?; let paint = Region::read(&src, bounds); Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) })?; @@ -737,12 +801,12 @@ enum SpotType { /// Photoshop 25.4 (measured): a dab changes exactly the brush's footprint, and Content-Aware takes /// its texture from around it, as Edit › Fill does from its window /// ([`crate::fill_cmds::sampling_window`] of the stroke's bounds), which is what this samples. -fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Rect { - let (bounds, cov) = stroke_coverage(stroke); +fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Result { + let (bounds, cov) = coverage("paint.spotHealing", stroke)?; let size = stroke.brush.size; let region_rect = crate::fill_cmds::sampling_window(bounds, pre.bounds()); if region_rect.is_empty() { - return Rect::EMPTY; + return Ok(Rect::EMPTY); } // Proximity Match looks for its source anywhere in that window. let margin = (region_rect.width().max(region_rect.height()) / 2) as i32; @@ -759,7 +823,7 @@ fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: } let hole: Vec = stroke_cov.iter().map(|c| *c > 0.0).collect(); if !hole.iter().any(|h| *h) { - return Rect::EMPTY; + return Ok(Rect::EMPTY); } // Synthesise over a slightly larger domain than the Poisson region, so the solve's boundary pixels // carry synthesised values that differ from the untouched surroundings: that mismatch is what the @@ -783,12 +847,13 @@ fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: let healed = heal_region(&fmt, &src, &img, &heal_mask); let dmg = bounds.intersect(®ion_rect); let dmg_cov: Vec = (dmg.y0..dmg.y1).flat_map(|y| (dmg.x0..dmg.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x, y)]).collect(); - apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal) + Ok(apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)) } fn spot_healing(s: &mut Session, p: &Value) -> Result { const CMD: &str = "paint.spotHealing"; let (stroke, id) = parse_brush(s, p, CMD)?; + reject_huge_stroke(CMD, &stroke)?; let kind = match string(p, "type", "contentAware") { "contentAware" => SpotType::ContentAware, "createTexture" => SpotType::CreateTexture, @@ -796,7 +861,7 @@ fn spot_healing(s: &mut Session, p: &Value) -> Result { o => return Err(bad(CMD, format!("unknown type `{o}` (contentAware|createTexture|proximityMatch)"))), }; let all = sample_all_layers(p); - let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| Ok(spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock)))?; + let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock))?; Ok(json!({ "damage": damage_json(dmg) })) } diff --git a/crates/engine/src/retouch_cmds/pattern_stamp.rs b/crates/engine/src/retouch_cmds/pattern_stamp.rs index 3908e27b16..6f14ac8eb0 100644 --- a/crates/engine/src/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/retouch_cmds/pattern_stamp.rs @@ -8,19 +8,14 @@ use photocraft_color::{BlendMode, PixelFormat}; use photocraft_compose::pattern::{Placement, Tile, render}; use photocraft_doc::{LayerId, Pattern}; use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke, over_native, stroke_coverage}; +use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke, over_native}; use photocraft_paint::{Stroke, StrokePoint}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde_json::{Value, json}; -use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush}; +use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush, reject_huge_stroke}; use crate::{Result, Session}; -/// A single stroke's accumulated coverage must stay at or under this many pixels (8192², so a -/// stroke corner to corner across a 24–36 MP canvas fits). Larger footprints return an error -/// instead of allocating. -const MAX_STROKE_PIXELS: u64 = 67_108_864; - const STREAM_PHASE_X: u64 = 101; const STREAM_PHASE_Y: u64 = 102; @@ -180,45 +175,6 @@ fn stamp_phase(p: &Value, cmd: &str, aligned: bool, first: &StrokePoint) -> Resu } } -fn reject_huge_stroke(cmd: &str, stroke: &Stroke) -> Result<()> { - let pad = f64::from(stroke.brush.size.max(1.0)).mul_add(0.5, 4.0); - let mut min_x = f64::INFINITY; - let mut min_y = f64::INFINITY; - let mut max_x = f64::NEG_INFINITY; - let mut max_y = f64::NEG_INFINITY; - for q in &stroke.points { - min_x = min_x.min(q.x); - min_y = min_y.min(q.y); - max_x = max_x.max(q.x); - max_y = max_y.max(q.y); - } - if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() { - return Err(bad(cmd, "point coordinates must be finite")); - } - let w = (max_x - min_x + pad * 2.0).ceil().max(1.0); - let h = (max_y - min_y + pad * 2.0).ceil().max(1.0); - if !w.is_finite() || !h.is_finite() || w > 1.0e9 || h > 1.0e9 { - return Err(bad(cmd, format!("stroke too large (at most {MAX_STROKE_PIXELS} px)"))); - } - let area = (w as u64).saturating_mul(h as u64); - if area > MAX_STROKE_PIXELS { - return Err(bad(cmd, format!("stroke too large ({w:.0}×{h:.0} px, at most {MAX_STROKE_PIXELS})"))); - } - Ok(()) -} - -fn reject_bounds(cmd: &str, bounds: Rect) -> Result<()> { - if bounds.is_empty() { - return Ok(()); - } - let (w, h) = (u64::from(bounds.width()), u64::from(bounds.height())); - let area = w.saturating_mul(h); - if area > MAX_STROKE_PIXELS { - return Err(bad(cmd, format!("stroke too large ({w}×{h} px, at most {MAX_STROKE_PIXELS})"))); - } - Ok(()) -} - fn placement(phase: (f32, f32), scale: f32, angle: f32) -> Placement { Placement::new(Rect::EMPTY, false, phase, scale, angle) } @@ -249,8 +205,7 @@ fn paint_aligned( mode: BlendMode, cmd: &str, ) -> Result { - let (bounds, cov) = stroke_coverage(stroke); - reject_bounds(cmd, bounds)?; + let (bounds, cov) = super::coverage(cmd, stroke)?; if bounds.is_empty() { return Ok(Rect::EMPTY); } @@ -333,9 +288,9 @@ mod tests { #[test] fn a_diagonal_across_a_24_mp_canvas_is_not_too_large() { - assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (6015.0, 3999.0)], 100.0)).is_ok()); - assert!(reject_bounds("t", Rect::from_xywh(-60, -60, 6136, 4120)).is_ok()); + let across = stroke(&[(0.0, 0.0), (6015.0, 3999.0)], 100.0); + assert!(reject_huge_stroke("t", &across).is_ok()); + assert!(super::super::coverage("t", &across).is_ok(), "the rendered extent fits too"); assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (9000.0, 9000.0)], 100.0)).is_err()); - assert!(reject_bounds("t", Rect::from_xywh(0, 0, 9000, 9000)).is_err()); } } diff --git a/crates/engine/src/retouch_cmds/remove.rs b/crates/engine/src/retouch_cmds/remove.rs index 4e256fb7fc..d298e8f02c 100644 --- a/crates/engine/src/retouch_cmds/remove.rs +++ b/crates/engine/src/retouch_cmds/remove.rs @@ -71,6 +71,7 @@ fn stroke_bounds(stroke: &Stroke) -> Rect { fn parse_strokes(s: &Session, p: &Value) -> Result<(Vec, Option)> { let Some(list) = p.get("strokes") else { let (stroke, id) = parse_brush(s, p, CMD)?; + reject_huge_stroke(CMD, &stroke)?; return Ok((vec![stroke], id)); }; let list = list.as_array().ok_or_else(|| bad(CMD, "`strokes` is a list of point lists"))?; @@ -86,6 +87,7 @@ fn parse_strokes(s: &Session, p: &Value) -> Result<(Vec, Option o.insert("points".into(), points.clone()); } let (stroke, layer) = parse_brush(s, &one, CMD)?; + reject_huge_stroke(CMD, &stroke)?; strokes.push(stroke); id = layer; } @@ -115,12 +117,12 @@ fn plan(s: &Session, p: &Value) -> Result { /// The hole over the plan's window: the strokes' footprints, their enclosed areas and a margin, /// limited to the selection. Empty when nothing would change. -fn hole(plan: &Plan, sel: Option<&Surface>) -> Vec { +fn hole(plan: &Plan, sel: Option<&Surface>) -> Result> { let win = plan.window; let (w, h) = (win.width() as usize, win.height() as usize); let mut m = vec![false; w * h]; for stroke in &plan.strokes { - let (bounds, cov) = stroke_coverage(stroke); + let (bounds, cov) = super::coverage(CMD, stroke)?; let bw = bounds.width() as usize; for (i, c) in cov.iter().enumerate() { let (x, y) = (bounds.x0 + (i % bw.max(1)) as i32, bounds.y0 + (i / bw.max(1)) as i32); @@ -141,13 +143,13 @@ fn hole(plan: &Plan, sel: Option<&Surface>) -> Vec { *v &= c > 0.0; } } - m + Ok(m) } /// The filled window and the hole it fills, computed on `doc` (a snapshot). `None` when the /// layer's own window is fully transparent: nothing to remove and nothing to fill from. fn run_remove(doc: &mut Document, plan: &Plan, p: &Value, ctx: &crate::jobs::JobCtx, label: &str) -> Result)>> { - let hole = hole(plan, doc.selection.as_ref()); + let hole = hole(plan, doc.selection.as_ref())?; if !hole.iter().any(|m| *m) { return Err(bad(CMD, "the stroke doesn't cover anything that can change (check the selection)")); } diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs index 13df2b26b0..856f819ed9 100644 --- a/crates/engine/src/retouch_cmds/tests.rs +++ b/crates/engine/src/retouch_cmds/tests.rs @@ -544,6 +544,96 @@ fn history_brush_restores_earlier_pixels() { } } +/// #4961 and #6110: every retouch stroke renders its coverage densely over the stroke's bounds +/// and reads a source region over the same box, so a stroke whose box dwarfs the canvas is +/// refused from the points and brush size alone, before anything is cloned or rendered. The +/// document is left as it was, and ordinary strokes still paint at every depth. +#[test] +fn history_brush_refuses_a_stroke_too_large_to_render() { + for depth in DEPTHS { + let mut s = session(40, 20, depth, "rgb"); + s.execute("paint.stroke", json!({"points": [[0, 10], [40, 10]], "size": 12, "hardness": 1.0, "color": "#ff0000"})).unwrap(); + let before = rgba(&s, 20, 10); + + let err = s.execute("paint.historyBrush", json!({"points": [[0, 0], [60000, 60000]], "size": 6, "hardness": 100})).unwrap_err(); + assert!(err.to_string().contains("stroke too large"), "depth {depth}: {err}"); + assert_eq!(rgba(&s, 20, 10), before, "depth {depth}: a refused stroke leaves the pixels alone"); + + // The guard is sized for real work: a stroke corner to corner across the canvas still runs. + s.execute("paint.historyBrush", json!({"points": [[0, 0], [40, 20]], "size": 6, "hardness": 100})).unwrap(); + assert!(rgba(&s, 20, 10).iter().all(|v| *v > 0.99), "depth {depth}: the Open snapshot is white"); + } +} + +/// #6110: Pattern Stamp already refused a stroke it could not render; every other retouch stroke +/// reached the same dense conversion unguarded. Each command refuses the oversized stroke without +/// touching the pixels or the history, and an ordinary stroke still succeeds. +#[test] +fn every_retouch_stroke_refuses_a_box_it_cannot_render() { + let huge = json!([[0, 0], [900_000, 900_000]]); + let ok = json!([[2, 2], [30, 16]]); + // Fixtures that are valid for a plain RGB document with one pixel layer. + let cases: [(&str, Value); 4] = [ + ("paint.cloneStamp", json!({"offset": [4, 0], "size": 8, "hardness": 100})), + ("paint.healingBrush", json!({"offset": [4, 0], "size": 8, "hardness": 100})), + ("paint.spotHealing", json!({"size": 8, "hardness": 100})), + ("paint.historyBrush", json!({"size": 8, "hardness": 100})), + ]; + for (cmd, base) in cases { + let mut s = session(40, 20, 8, "rgb"); + s.execute("paint.stroke", json!({"points": [[0, 10], [40, 10]], "size": 12, "hardness": 1.0, "color": "#ff0000"})).unwrap(); + let before = rgba(&s, 20, 10); + let steps = s.active().unwrap().history.past_len(); + let with = |points: &Value| { + let mut v = base.clone(); + if let Some(o) = v.as_object_mut() { + o.insert("points".into(), points.clone()); + } + v + }; + let err = s.execute(cmd, with(&huge)).unwrap_err().to_string(); + assert!(err.contains("stroke too large"), "{cmd}: {err}"); + assert_eq!(rgba(&s, 20, 10), before, "{cmd}: a refused stroke leaves the pixels alone"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{cmd}: and records no history step"); + + // The allowance still covers ordinary work: this must succeed, not merely avoid the error. + s.execute(cmd, with(&ok)).unwrap_or_else(|e| panic!("{cmd}: an ordinary stroke must work: {e}")); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{cmd}: and records one step"); + } + + // Remove takes a list of strokes; each one is charged as it is parsed. + let mut s = session(40, 20, 8, "rgb"); + let err = s.execute("paint.remove", json!({"strokes": [[[0, 0], [900_000, 900_000]]], "size": 8})).unwrap_err().to_string(); + assert!(err.contains("stroke too large"), "paint.remove: {err}"); +} + +/// The review on #6110: the estimate from the input points is not the bound. Brush dynamics place +/// dabs beyond those points, so the budget is applied to the extent the renderer actually produced, +/// before the dense buffer is allocated. An injected budget makes that observable without asking +/// for a stroke big enough to exhaust anything. +#[test] +fn the_budget_is_applied_to_the_rendered_extent_not_the_input_points() { + use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; + let mut brush = BrushSettings { size: 24.0, hardness: 1.0, ..Default::default() }; + brush.scattering.enabled = true; + brush.scattering.scatter.jitter = 6.0; + let stroke = Stroke { brush, points: vec![StrokePoint::new(10.0, 10.0, 1.0), StrokePoint::new(40.0, 10.0, 1.0)] }; + + // What the renderer really covered, once scattering has placed every dab. + let (bounds, cov) = super::coverage_within("t", &stroke, u64::MAX).unwrap(); + let rendered = u64::from(bounds.width()) * u64::from(bounds.height()); + assert_eq!(cov.len() as u64, rendered, "the dense buffer is exactly the rendered extent"); + + // Scattering reaches past the points plus half the tip, which is what the estimate alone sees. + let points_only = (40.0 - 10.0 + 24.0 + 8.0) * (24.0 + 8.0); + assert!(rendered as f64 > points_only, "scattering expanded the stroke: {rendered} vs {points_only}"); + + // A budget one pixel under what it rendered refuses it; exactly the rendered extent fits. + let err = super::coverage_within("t", &stroke, rendered - 1).unwrap_err().to_string(); + assert!(err.contains("stroke too large"), "{err}"); + assert!(super::coverage_within("t", &stroke, rendered).is_ok(), "the rendered extent itself fits"); +} + #[test] fn history_brush_reads_a_source_when_its_pixels_were_locked() { // Given a white layer locked in history state 1, then unlocked and filled red. diff --git a/crates/engine/src/sampler_cmds.rs b/crates/engine/src/sampler_cmds.rs index 472ecb672a..57787b2e83 100644 --- a/crates/engine/src/sampler_cmds.rs +++ b/crates/engine/src/sampler_cmds.rs @@ -365,7 +365,7 @@ mod tests { #[test] fn a_right_angle_rotation_moves_points() { - // 90° clockwise about the centre: the doc centre stays put. + // 90° clockwise about the centre: pixel (x, y) of the 100×80 canvas goes to (79 - y, x). let mut s = session(); s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); s.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "cw"})).unwrap(); @@ -373,19 +373,78 @@ mod tests { assert_eq!(p.len(), 1); let pos = p[0]["position"].as_array().unwrap(); let (x, y) = (pos[0].as_f64().unwrap(), pos[1].as_f64().unwrap()); - // The new canvas is 80×100, so the centre is (40, 50). - assert!((x - 40.0).abs() < 1e-6 && (y - 50.0).abs() < 1e-6, "{pos:?}"); + assert!((x - 39.0).abs() < 1e-6 && (y - 50.0).abs() < 1e-6, "{pos:?}"); + } + + #[test] + fn flips_and_right_angle_turns_keep_points_on_their_pixel() { + use crate::canvas_geom::Turn; + for (id, turn) in [ + ("image.imageRotation.flipCanvasHorizontal", Turn::FlipHorizontal), + ("image.imageRotation.flipCanvasVertical", Turn::FlipVertical), + ("image.imageRotation.180", Turn::Rotate180), + ("image.imageRotation.90cw", Turn::Cw90), + ("image.imageRotation.90ccw", Turn::Ccw90), + ] { + // A black pixel at (3, 3) of a white 100×80 document, with a point on it. + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &black); + Ok(()) + }) + .unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + s.execute(id, json!({})).unwrap(); + let (x, y) = turn.pixel_map(100, 80)(3, 3); + let p = points(&mut s); + assert_eq!(p.len(), 1, "{id}"); + assert_eq!(p[0]["position"], json!([f64::from(x), f64::from(y)]), "{id}"); + assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{id}"); + } + } + + #[test] + fn an_arbitrary_rotation_keeps_points_on_their_pixel() { + // The pixel at (3, 3) of the 100×80 document, and where each turn moves it. + for (angle, direction, at) in [(90, "cw", [76.0, 3.0]), (90, "ccw", [3.0, 96.0]), (180, "cw", [96.0, 76.0])] { + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &black); + Ok(()) + }) + .unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 0, "y": 0})).unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": angle, "direction": direction})).unwrap(); + assert_eq!(s.take_samplers_removed(), 0, "{angle} {direction}: the corner point stays on the canvas"); + let p = points(&mut s); + assert_eq!(p.len(), 2, "{angle} {direction}: the corner point stays on the canvas"); + assert_eq!(p[0]["position"], json!(at), "{angle} {direction}"); + assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{angle} {direction}"); + } } #[test] fn a_rotated_crop_moves_points() { - // The crop frame is centred on the point, so the point lands at the new canvas centre. + // The crop frame is centred on the point's pixel; turned 90° that pixel lands at (10, 9). let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(50, 40, 51, 41), &black); + Ok(()) + }) + .unwrap(); s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20, "angle": 90})).unwrap(); let p = points(&mut s); assert_eq!(p.len(), 1); - assert_eq!(p[0]["position"], json!([10.0, 10.0])); + assert_eq!(p[0]["position"], json!([10.0, 9.0])); + assert_eq!(p[0]["rgb"], json!([0, 0, 0])); } #[test] diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs index 6ffc89e67d..3ca10083b9 100644 --- a/crates/engine/src/smart_cmds.rs +++ b/crates/engine/src/smart_cmds.rs @@ -77,8 +77,13 @@ fn base_name(path: &str) -> String { path.rsplit(['/', '\\']).next().unwrap_or(path).to_string() } +/// A linked file's bytes; `None` when it is missing or its path is not followed +/// ([`crate::doc_path::resolve`]). fn read_file(path: &str) -> Option> { - if path.is_empty() { None } else { photocraft_format::read_file(std::path::Path::new(path)).ok() } + if path.is_empty() { + return None; + } + photocraft_format::read_file(&crate::doc_path::resolve(path).ok()?).ok() } /// The source file of a smart object: embedded bytes, the PSD's embedded linked-layer data (PSD @@ -492,10 +497,14 @@ fn refresh_or_fail(doc: &mut Document, id: LayerId) -> Result<()> { fn refresh_or_fail_in(doc: &mut Document, id: LayerId, ctx: &JobCtx) -> Result<()> { if refresh_in(doc, id, ctx)? { - Ok(()) - } else { - Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered")) + return Ok(()); } + if let SmartSource::Linked { path } = &smart(doc, id)?.source + && let Err(why @ crate::doc_path::NotFollowed::Refused(_)) = crate::doc_path::resolve(path) + { + return Err(crate::doc_path::refusal("the linked file", path, why)); + } + Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered")) } fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> { @@ -1056,6 +1065,9 @@ fn delete_filter(s: &mut Session, p: &Value) -> Result { edit_filters(s, p, "Delete Smart Filter", |sm| { let i = filter_index("layer.smartFilter.delete", p, sm)?; sm.smart_filters.remove(i); + if sm.smart_filters.is_empty() { + sm.filter_mask = None; + } Ok(()) }) } @@ -1125,6 +1137,9 @@ fn transfer_filters(s: &mut Session, p: &Value) -> Result { match index { Some(i) => { src.smart_filters.remove(i); + if src.smart_filters.is_empty() { + src.filter_mask = None; + } } None => { src.smart_filters.clear(); diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rs index 1caaff6ce2..51d8d007f7 100644 --- a/crates/engine/src/smart_cmds/tests.rs +++ b/crates/engine/src/smart_cmds/tests.rs @@ -330,6 +330,37 @@ fn selection_becomes_the_filter_mask() { assert!(!s.is_enabled("layer.smartFilter.deleteFilterMask")); } +/// #5619: deleting (or dragging away) the last smart filter removes the filter mask with it, so +/// the next filter takes the new selection instead of the old one. +#[test] +fn removing_the_last_filter_removes_its_filter_mask() { + let mut s = session(8); + paint(&mut s); + let original = flat(&s); + let a = convert(&mut s); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 48})).unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(); + assert!(active_smart(&s).filter_mask.is_some()); + s.execute("layer.smartFilter.delete", json!({})).unwrap(); + assert!(active_smart(&s).filter_mask.is_none(), "the last filter takes its mask along"); + s.execute("select.rect", json!({"x": 20, "y": 0, "width": 20, "height": 48})).unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(); + let px = flat(&s); + let at = |v: &Vec<[f32; 4]>, x: i32, y: i32| v[(y * W + x) as usize]; + assert_eq!(at(&px, 6, 20), at(&original, 6, 20), "the old selection is not filtered"); + assert_ne!(at(&px, 30, 20), at(&original, 30, 20), "the new selection is filtered"); + + // Dragging the only filter to another smart object leaves no mask behind either. + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + paint(&mut s); + let b = convert(&mut s); + s.execute("layer.smartFilter.transfer", json!({"from": a, "to": b, "filter": 0})).unwrap(); + let doc = &s.active().unwrap().doc; + let LayerContent::Smart(sm) = &doc.layer(LayerId(a)).unwrap().content else { panic!("not smart") }; + assert!(sm.smart_filters.is_empty() && sm.filter_mask.is_none()); +} + /// Scales `id` to 10 % around the origin and back, returning the composite. fn shrink_and_grow(s: &mut Session, id: u64) -> Vec<[f32; 4]> { s.execute("edit.transform", json!({"layer": id, "matrix": [0.1, 0, 0, 0.1, 0, 0]})).unwrap(); diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 3ab1ad73bf..ef0e72f5db 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -89,10 +89,21 @@ pub fn layer_rect(doc: &Document, id: LayerId) -> Option<[f64; 4]> { } fn rect_of(doc: &Document, l: &photocraft_doc::Layer) -> Option<[f64; 4]> { - if l.is_group() || (matches!(l.content, LayerContent::Adjustment(_)) && l.mask.is_none()) { - return None; - } - let b = crate::transform_cmds::transform_bounds(doc, l); + snappable(l).then(|| crate::transform_cmds::transform_bounds(doc, l)).and_then(to_rect) +} + +/// Bounds of a layer as a Snap To Layers target: all of its content, whatever the selection +/// holds of it (#6290: clipped to the selection, every layer's edges and centre were the +/// selection's, so a moved selection snapped back to where it started). +fn target_rect_of(l: &photocraft_doc::Layer) -> Option<[f64; 4]> { + snappable(l).then(|| crate::transform_cmds::whole_layer_bounds(l)).and_then(to_rect) +} + +fn snappable(l: &photocraft_doc::Layer) -> bool { + !(l.is_group() || (matches!(l.content, LayerContent::Adjustment(_)) && l.mask.is_none())) +} + +fn to_rect(b: photocraft_geom::Rect) -> Option<[f64; 4]> { (!b.is_empty()).then_some([b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]) } @@ -121,7 +132,7 @@ impl SnapTargets { if !l.visible || exclude.contains(&l.id) { continue; } - if let Some(r) = rect_of(doc, l) { + if let Some(r) = target_rect_of(l) { t.add_rect(r, SnapKind::LayerEdge, SnapKind::LayerCenter); } } @@ -365,6 +376,17 @@ mod tests { let t = SnapTargets::from_document(&doc, &SnapOptions { guides: false, ..opts }, &[id]); assert!(!t.x.iter().any(|t| t.kind == SnapKind::Guide || (t.kind == SnapKind::LayerEdge && t.pos == 30.0))); assert_eq!(layer_rect(&doc, id), Some([10.0, 20.0, 30.0, 60.0])); + // #6290: a selection doesn't move the layers' targets onto its own bounds. + let mut sel = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); + sel.fill_rect(photocraft_geom::Rect::new(64, 66, 124, 86), &[1.0]); + doc.selection = Some(sel); + let t = SnapTargets::from_document(&doc, &SnapOptions { selection: false, ..opts }, &[]); + assert!(t.x.iter().any(|t| t.kind == SnapKind::LayerEdge && t.pos == 30.0)); + assert!( + !t.x.iter() + .chain(&t.y) + .any(|t| matches!(t.kind, SnapKind::LayerEdge | SnapKind::LayerCenter) && [64.0, 66.0, 76.0, 86.0, 94.0, 124.0].contains(&t.pos)) + ); assert_eq!(union([[0.0, 0.0, 1.0, 1.0], [2.0, -1.0, 3.0, 0.5]]), Some([0.0, -1.0, 3.0, 1.0])); } } diff --git a/crates/engine/src/stamp_cmds.rs b/crates/engine/src/stamp_cmds.rs index a525d138b5..85ac4078c7 100644 --- a/crates/engine/src/stamp_cmds.rs +++ b/crates/engine/src/stamp_cmds.rs @@ -1,7 +1,8 @@ //! Stamping (#217): merge layers into a layer while keeping the originals. //! //! - **Stamp Visible** (⌘⌥⇧E, or ⌥ + Layer › Merge Visible): every visible layer composited into a -//! new layer above the active one. +//! new layer above the active one, or into the active layer when it is an empty pixel layer (as +//! in Photoshop, so a recorded New Layer + Stamp Visible leaves one layer, #6785). //! - **Stamp Down** (⌘⌥E, or ⌥ + Layer › Merge Down): a copy of the active layer merged into the //! pixel layer below it; with several layers selected, a copy of them merged into a new layer //! above the top one. @@ -65,6 +66,13 @@ fn stamp_visible(s: &mut Session, p: &Value) -> Result { if !doc.walk().iter().any(|(path, _, l)| !l.is_group() && (1..=path.len()).all(|n| doc.layer_at(&path[..n]).is_some_and(|a| a.visible))) { return Err(EngineError::Other("there are no visible layers to stamp".into())); } + // Like Photoshop, an empty pixel layer that is active (Layer > New > Layer, then Stamp + // Visible, as recorded actions do) takes the stamp itself instead of getting a second layer. + if let Some(empty) = (*active).filter(|id| is_empty_pixel_layer(doc, *id)) { + let surf = photocraft_compose::flatten_to_surface(doc, with_alpha(doc), None); + *crate::pixels_mut(doc.layer_mut(empty).ok_or(EngineError::NoLayer(empty))?)? = surf; + return Ok(empty); + } let layer = stamp_layer(doc, doc.next_layer_name("Layer"))?; let id = doc.insert_above(*active, layer); *active = Some(id); @@ -74,6 +82,18 @@ fn stamp_visible(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": id.0 })) } +/// A plain, unlocked pixel layer with no pixels, mask or clipping: safe to stamp into. +fn is_empty_pixel_layer(doc: &Document, id: LayerId) -> bool { + let Some(l) = doc.layer(id) else { return false }; + let locks = doc.effective_locks(id); + matches!(&l.content, LayerContent::Raster(s) if s.content_bounds().is_empty()) + && l.visible + && l.mask.is_none() + && l.vector_mask.is_none() + && !l.clipped + && !(locks.all || locks.pixels || locks.transparency) +} + fn stamp_down(s: &mut Session, p: &Value) -> Result { object(p, "layer.stampDown")?; let sel = crate::layer_multi_cmds::selected(s); @@ -148,7 +168,7 @@ pub fn specs() -> Vec { label: "Stamp Visible", menu: &[], shortcut: Some("Cmd+Alt+Shift+E"), - params: r##"{} → {layer} (every visible layer merged into a new layer above the active one; the originals stay)"##, + params: r##"{} → {layer} (visible layers merged into a new layer above the active one, or into the active one if it is an empty pixel layer)"##, enabled: has_doc, journal: true, run: stamp_visible, @@ -235,6 +255,25 @@ mod tests { } } + /// Recorded actions do New Layer, then Stamp Visible: the stamp lands in the new empty layer. + #[test] + fn stamp_visible_fills_an_empty_active_layer_instead_of_adding_one() { + let (mut s, bg, hidden, blue) = session(8); + s.execute("layer.new.layer", json!({"name": "Empty"})).unwrap(); + let empty = s.active().unwrap().active_layer.unwrap(); + let r = s.execute("layer.stampVisible", json!({})).unwrap(); + assert_eq!(r["layer"].as_u64(), Some(empty.0)); + assert_eq!(ids(&s), [bg, hidden, blue, empty], "no extra layer"); + let st = s.active().unwrap(); + assert_eq!((st.active_layer, st.selected_layers.clone()), (Some(empty), vec![empty])); + assert!(close(rgba(&s, empty, 30, 30), [0.0, 0.0, 1.0, 1.0])); + assert!(close(rgba(&s, empty, 2, 2), [1.0, 0.0, 0.0, 1.0])); + // A second stamp: the layer now has pixels, so this one adds a layer. + let r2 = s.execute("layer.stampVisible", json!({})).unwrap(); + assert_ne!(r2["layer"].as_u64(), Some(empty.0)); + assert_eq!(ids(&s).len(), 5); + } + #[test] fn stamp_visible_respects_opacity_blend_and_groups() { let (mut s, bg, _, blue) = session(8); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 04063d3073..0849cd941a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -702,6 +702,38 @@ fn fill_layer_pixel_rewrites_refresh_the_effect_maps() { assert_eq!(after, fresh, "the effect maps track the cache surface, not the Fill spec alone"); } +#[test] +fn growing_the_canvas_re_renders_a_cached_fill_layer() { + // A PSD fill layer keeps its stored pixels as a fill cache covering only the old canvas. + // Canvas Size, an extending Crop and Reveal All must re-render the fill over the new area, + // as Photoshop does, instead of leaving the added bands transparent (#7362). + let grow: [(&str, Value); 2] = [ + ("image.canvasSize", json!({"width": 100, "anchor": "left"})), + ("image.crop", json!({"x": 0, "y": 0, "width": 100, "height": 48, "deleteCroppedPixels": false})), + ]; + for (cmd, params) in grow { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "transparent"})).unwrap(); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})).unwrap(); + s.edit("cache", |doc, active| { + let fmt = doc.pixel_format(); + let l = doc.layer_mut(active.unwrap()).unwrap(); + let photocraft_doc::LayerContent::Fill(f) = &l.content else { return Err(EngineError::Other("not a fill layer".into())) }; + let fill = f.clone(); + let mut surface = photocraft_raster::Surface::new(fmt); + surface.fill_rect(photocraft_geom::Rect::new(0, 0, 64, 48), &[1.0, 0.0, 0.0, 1.0]); + l.fill_cache = Some(photocraft_doc::FillCache { fill, surface }); + Ok(()) + }) + .unwrap(); + s.execute(cmd, params).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.size.width, 100, "{cmd} grows the canvas"); + let px = photocraft_compose::render(d, d.bounds()).get(90, 20); + assert!(px[3] > 0.99 && px[0] > 0.99 && px[1] < 0.01, "{cmd}: the fill covers the added area, got {px:?}"); + } +} + #[test] fn group_effect_maps_follow_child_visibility_and_opacity() { // A styled group's maps come from its children's composite: hiding a child or changing its diff --git a/crates/engine/src/timeline_cmds.rs b/crates/engine/src/timeline_cmds.rs index 9baa077608..716fc8b4c8 100644 --- a/crates/engine/src/timeline_cmds.rs +++ b/crates/engine/src/timeline_cmds.rs @@ -59,7 +59,7 @@ fn duration_param(cmd: &str, p: &Value) -> Result> { } /// The optional `fps` param, rejected unless it's a finite number in `(0, MAX_FPS]` (#1009). -fn fps_param(cmd: &str, p: &Value) -> Result> { +pub(crate) fn fps_param(cmd: &str, p: &Value) -> Result> { let Some(v) = p.get("fps").filter(|v| !v.is_null()) else { return Ok(None) }; v.as_f64() .filter(|f| f.is_finite() && *f > 0.0 && *f <= f64::from(MAX_FPS)) diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs index 1c0153a42e..2452e7443b 100644 --- a/crates/engine/src/transform_cmds.rs +++ b/crates/engine/src/transform_cmds.rs @@ -1,6 +1,6 @@ //! Edit › Free Transform / Transform: projective transforms of layers (and the selection). -use photocraft_algo::transform::{Homography, Interp, warp_output_bounds, warp_surface, warp_surface_with}; +use photocraft_algo::transform::{Homography, Interp, warp_output_size, warp_surface, warp_surface_with}; use photocraft_color::PixelFormat; use photocraft_doc::{Document, Layer, LayerContent, LayerId, Locks}; use photocraft_geom::{Affine, Rect}; @@ -54,7 +54,7 @@ fn framed_by_selection(doc: &Document, bounds: Rect) -> Rect { } /// A group moves all its descendants, so its frame must not clip raster children to the selection. -fn whole_layer_bounds(layer: &Layer) -> Rect { +pub(crate) fn whole_layer_bounds(layer: &Layer) -> Rect { let content = match &layer.content { LayerContent::Group(g) => g.children.iter().map(whole_layer_bounds).fold(Rect::EMPTY, |a, b| a.union(&b)), _ => layer.surface().map_or(Rect::EMPTY, photocraft_compose::bounds::content_bounds), @@ -273,10 +273,13 @@ const BUDGET: u64 = 1 << 20; /// Refuse a warp of the content inside `src` by `h` whose result would exceed the pixel budget, /// before anything is built. `what` names the surface in the message. pub(crate) fn check_budget(src: Rect, h: &Homography, what: &str) -> Result<()> { - let Some(b) = warp_output_bounds(src, h) else { return Ok(()) }; - let (w, ht) = (u64::from(b.width()), u64::from(b.height())); - if w.saturating_mul(ht) > BUDGET { - let detail = format!("the transformed {what} would be {w} x {ht} px, more than the {BUDGET} px limit"); + check_budget_with_limit(src, h, what, BUDGET) +} + +fn check_budget_with_limit(src: Rect, h: &Homography, what: &str, budget: u64) -> Result<()> { + let Some((w, ht)) = warp_output_size(src, h) else { return Ok(()) }; + if w.saturating_mul(ht) > budget { + let detail = format!("the transformed {what} would be {w} x {ht} px, more than the {budget} px limit"); return Err(crate::allocation::error("transforming pixels", &detail)); } Ok(()) @@ -375,6 +378,9 @@ fn apply_transform( // With a selection only the selected pixels move, and so only the same region of a linked // mask (#205). Groups, type, shapes and smart objects move whole. let mask_sel = doc_sel.filter(|_| !moves_whole(l)); + // The masks (and so a fill's frame) move, but a fill layer's cached render isn't warped: + // drop it, the fill re-renders from its model (as `transform_layer_geometry` does). + l.fill_cache = None; match &mut l.content { LayerContent::Group(g) => { for c in g.children.iter_mut() { @@ -735,6 +741,24 @@ mod tests { // ---- Pixel budget (#3773). Tests run with a 2²⁰ px budget, so nothing here comes near the real one. ---- + #[test] + fn huge_transform_scales_exceed_the_production_budget_before_clipping() { + let src = Rect::new(0, 0, 24, 16); + for scale in [1e7, 1e28, 1e306] { + for (sx, sy) in [(scale, 1.0), (1.0, scale), (-scale, 1.0)] { + let h = Homography([sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0]); + assert!(check_budget_with_limit(src, &h, "layer", MAX_TRANSFORM_PIXELS).is_err(), "{sx} x {sy} must be refused"); + } + } + } + + #[test] + fn an_ordinary_transform_remains_within_the_production_budget() { + let src = Rect::new(0, 0, 24, 16); + let h = Homography([10_000.0, 0.0, 900_000.0, 0.0, 1.0, -900_000.0, 0.0, 0.0, 1.0]); + assert!(check_budget_with_limit(src, &h, "layer", MAX_TRANSFORM_PIXELS).is_ok()); + } + /// A 16 x 16 document whose active layer is a 1 x 8 column at x = 10. fn column() -> Session { let mut s = Session::new(); @@ -971,6 +995,57 @@ mod tests { assert!(!active_bounds(&s).is_empty()); } + /// A gradient fill layer whose mask (a selection when it was made) frames the gradient over + /// 10..40, with the cached render a PSD import gives it: exactly the pixels the fill renders. + fn cached_gradient_fill() -> Session { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + s.execute("layer.newFillLayer.gradient", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.edit("cache", |doc, active| { + let (fmt, canvas) = (doc.pixel_format(), doc.bounds()); + let l = doc.layer_mut(active.unwrap()).unwrap(); + let LayerContent::Fill(f) = &l.content else { panic!("a fill layer") }; + let buf = photocraft_compose::render_fill_content(l, f, canvas, &[]); + let mut surface = Surface::new(fmt); + let vals: Vec = buf.px.iter().flat_map(|p| photocraft_raster::from_rgba(&fmt, *p)).collect(); + surface.write_region(canvas, &vals); + l.fill_cache = Some(photocraft_doc::FillCache { fill: f.clone(), surface }); + Ok(()) + }) + .unwrap(); + s + } + + /// How far the composite is from the composite with the fill re-rendered from its model + /// (cache dropped): the largest channel difference. + fn off_from_fresh(s: &Session) -> f32 { + let st = s.active().unwrap(); + let mut fresh: Document = (*st.doc).clone(); + fresh.layer_mut(st.active_layer.unwrap()).unwrap().fill_cache = None; + let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).px, photocraft_compose::render(&fresh, fresh.bounds()).px); + a.iter().zip(&b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs())).fold(0.0, f32::max) + } + + #[test] + fn transforming_a_fill_layer_drops_its_stale_cached_render() { + let mut s = cached_gradient_fill(); + let off = off_from_fresh(&s); + assert!(off < 0.01, "the cache is the fill's own render: {off}"); + // The mask (and so the gradient's frame) moves 50 px right and doubles in height. + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 2, 50, 0]})).unwrap(); + let off = off_from_fresh(&s); + assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); + } + + #[test] + fn warping_a_fill_layer_drops_its_stale_cached_render() { + let mut s = cached_gradient_fill(); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); + let off = off_from_fresh(&s); + assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); + } + #[test] fn type_moves_with_the_move_command() { let mut s = session(); diff --git a/crates/engine/src/trap_cmds.rs b/crates/engine/src/trap_cmds.rs index 03d899472c..6bd99200ac 100644 --- a/crates/engine/src/trap_cmds.rs +++ b/crates/engine/src/trap_cmds.rs @@ -24,6 +24,7 @@ fn trap(s: &mut Session, p: &Value) -> Result { } s.edit("Trap", |doc, active| { let id = active.ok_or(EngineError::NoDocument)?; + crate::commands::check_pixels_unlocked(doc, id)?; let bounds = doc.bounds(); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let LayerContent::Raster(surf) = &mut l.content else { @@ -63,11 +64,8 @@ mod tests { use super::*; use photocraft_geom::Rect; - #[test] - fn traps_a_cmyk_document() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 4, "mode": "cmyk"})).unwrap(); - // Paint cyan | magenta halves on the Background. + /// Paints cyan | magenta halves on the active layer. + fn paint_halves(s: &mut Session) { s.edit("paint", |doc, active| { let id = active.unwrap(); let fmt = doc.pixel_format(); @@ -93,6 +91,13 @@ mod tests { Ok(()) }) .unwrap(); + } + + #[test] + fn traps_a_cmyk_document() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 4, "mode": "cmyk"})).unwrap(); + paint_halves(&mut s); let r = s.execute("image.trap", json!({"width": 1})).unwrap(); assert_eq!(r["trapped"], true); @@ -109,6 +114,35 @@ mod tests { assert_eq!(st.history.entries().last().map(|e| e.as_str()), Some("Trap")); } + #[test] + fn refuses_locked_layers() { + // Lock All or the pixel lock, on the layer itself or on its group: Trap refuses, leaving the + // pixels and the history as they were. + for lock in [json!({"all": true}), json!({"pixels": true})] { + for on_group in [false, true] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 4, "mode": "cmyk"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + paint_halves(&mut s); + let layer = s.active().unwrap().active_layer.unwrap(); + if on_group { + s.execute("layer.new.groupFromLayers", json!({})).unwrap(); + } + s.execute("layer.lockLayers", lock.clone()).unwrap(); + s.execute("layer.select", json!({"layer": layer.0})).unwrap(); + let locks = s.active().unwrap().doc.effective_locks(layer); + assert!(locks.all || locks.pixels, "the lock reaches the layer ({lock}, group: {on_group})"); + let steps = s.active().unwrap().history.past_len(); + let before = s.active().unwrap().doc.layer(layer).unwrap().surface().cloned(); + let r = s.execute("image.trap", json!({"width": 1})); + assert!(r.is_err(), "trapped a layer locked with {lock} (group: {on_group}): {r:?}"); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(layer).unwrap().surface().cloned(), before, "{lock} group: {on_group}"); + assert_eq!(st.history.past_len(), steps, "{lock} group: {on_group}: no history step"); + } + } + } + #[test] fn rejects_non_cmyk() { let mut s = Session::new(); diff --git a/crates/engine/src/type_caret_cmds.rs b/crates/engine/src/type_caret_cmds.rs index 419d305ee6..3b9b244f70 100644 --- a/crates/engine/src/type_caret_cmds.rs +++ b/crates/engine/src/type_caret_cmds.rs @@ -482,7 +482,7 @@ mod tests { bad(&mut s, "type.navigate", json!({"layer": id, "index": 9, "move": "end"})); bad(&mut s, "type.navigate", json!({"layer": id, "index": 0, "move": "lineNext", "x": "no"})); bad(&mut s, "type.navigate", json!({"layer": pixel, "index": 0, "move": "start"})); - assert!(matches!(s.execute("type.caret", json!({"layer": u64::MAX, "index": 0})), Err(EngineError::NoLayer(_)))); + assert!(matches!(s.execute("type.caret", json!({"layer": u64::MAX, "index": 0})), Err(EngineError::UnknownLayer { .. }))); // A point on the named layer but outside its text still returns a caret, marked outside. let far = s.execute("type.hitTest", json!({"layer": id, "x": 390, "y": 290})).unwrap(); assert_eq!(far["inside"], false); diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs index d6b92e840c..439d1f008b 100644 --- a/crates/engine/src/type_cmds.rs +++ b/crates/engine/src/type_cmds.rs @@ -34,14 +34,14 @@ fn bad(cmd: &str, msg: impl Into) -> EngineError { } fn f32p(p: &Value, k: &str) -> Option { - p.get(k).and_then(Value::as_f64).map(|v| v as f32) + p.get(k).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite()) } fn color(v: &Value) -> Option { match v { Value::Array(a) if a.len() >= 3 => { let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); - Some(Color::rgba(c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0))) + c.iter().take(4).all(|v| v.is_finite()).then(|| Color::rgba(c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0))) } Value::String(s) => { let s = s.trim_start_matches('#'); @@ -89,6 +89,8 @@ pub const TYPE_SIZE_MIN_PT: f64 = 0.1; pub const TYPE_SIZE_MAX_PT: f64 = 1296.0; pub const TRACKING_MIN: f64 = -1000.0; pub const TRACKING_MAX: f64 = 10_000.0; +/// Photoshop's horizontal and vertical scale range, in percent. +pub const SCALE_MAX_PERCENT: f64 = 1000.0; /// Validates the `kerning` key of character params: a number in [`KERN_MIN`]..=[`KERN_MAX`] or /// `"metrics"`, `"optical"`, `"off"` (`"none"`, `"0"`). @@ -104,7 +106,8 @@ pub fn check_kerning(p: &Value) -> std::result::Result<(), String> { } } -/// Validates text metrics that can otherwise exceed the rasterizer's supported range. +/// Validates text metrics (size, tracking, leading, baseline shift, scales) that can otherwise +/// exceed the rasterizer's supported range or overflow `f32`, which a .pcraft manifest cannot hold. pub fn check_size_tracking(p: &Value) -> std::result::Result<(), String> { if let Some(v) = p.get("size") { match v.as_f64() { @@ -118,6 +121,30 @@ pub fn check_size_tracking(p: &Value) -> std::result::Result<(), String> { _ => return Err(format!("tracking must be between {TRACKING_MIN} and {TRACKING_MAX} (1/1000 em)")), } } + if let Some(v) = p.get("leading") { + let (min, max) = (f64::from(LEADING_MIN_PT), f64::from(LEADING_MAX_PT)); + match v { + Value::Null => {} + Value::String(a) if a == "auto" => {} + Value::Number(n) if n.as_f64().is_some_and(|x| x.is_finite() && (min..=max).contains(&x)) => {} + _ => return Err(format!("leading must be between {min} and {max} pt, or \"auto\"")), + } + } + if let Some(v) = p.get("baselineShift") { + let max = f64::from(BASELINE_SHIFT_MAX_PT); + match v.as_f64() { + Some(shift) if shift.is_finite() && shift.abs() <= max => {} + _ => return Err(format!("baselineShift must be between -{max} and {max} pt")), + } + } + for key in ["horizontalScale", "verticalScale"] { + if let Some(v) = p.get(key) { + match v.as_f64() { + Some(scale) if scale.is_finite() && (0.0..=SCALE_MAX_PERCENT).contains(&scale) => {} + _ => return Err(format!("{key} must be between 0 and {SCALE_MAX_PERCENT} %")), + } + } + } Ok(()) } @@ -477,8 +504,9 @@ pub fn style_paragraphs(t: &mut TextLayer, a: usize, b: usize, f: &dyn Fn(&mut P t.paragraphs = out.into_iter().map(|(len, style)| ParagraphRun { len, style }).collect(); } -/// Replaces bytes `a..b` with `new`, keeping styles: inserted text takes the style of the -/// character before it (or after it at the start). +/// Replaces bytes `a..b` with `new`, keeping styles: replacing a selection keeps the style of its +/// first character (as Photoshop does, so retyping a smaller second line stays small); inserting +/// at a caret takes the style of the character before it (or after it at the start). pub fn replace_text(t: &mut TextLayer, a: usize, b: usize, new: &str) { fn adjust(runs: Vec<(usize, S)>, a: usize, b: usize, ins: usize, trailing_paragraph: bool) -> Vec<(usize, S)> { let mut out: Vec<(usize, S)> = Vec::new(); @@ -494,7 +522,15 @@ pub fn replace_text(t: &mut TextLayer, a: usize, b: usize, new: &str) { *acc += r.0; Some((s, s + r.0)) }) - .position(|(s, e)| if a == 0 { e > 0 || s == 0 } else { a > s && a <= e }) + .position(|(s, e)| { + if a == 0 { + e > 0 || s == 0 + } else if a < b { + a >= s && a < e + } else { + a > s && a <= e + } + }) .unwrap_or(0) }; for (i, (len, st)) in runs.into_iter().enumerate() { @@ -628,6 +664,10 @@ pub(crate) fn with_text_targets( mut f: impl FnMut(&mut TextLayer, (usize, usize)) -> Result<()>, ) -> Result> { let ids = format_targets(s, p)?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + for id in &ids { + check_text_unlocked(doc, *id)?; + } let damage = s.edit(label, |doc, _| { let snapshot = doc.clone(); let mut damage = Some(photocraft_geom::Rect::EMPTY); @@ -743,6 +783,7 @@ fn info(s: &Session, p: &Value) -> Result { /// paragraph `box`, `orientation`, character and paragraph keys, starting from the default type /// styles in the foreground colour. Shared with the Type Mask tools' `type.createSelection`. pub(crate) fn new_text_layer(s: &Session, p: &Value, cmd: &str) -> Result { + crate::commands::check_f32_values(cmd, p)?; let orientation = match p.get("orientation") { None => Orientation::Horizontal, Some(Value::String(value)) if value == "horizontal" => Orientation::Horizontal, @@ -1384,6 +1425,35 @@ mod tests { assert_eq!(s.active().unwrap().history.past_len(), history); } + #[test] + fn all_locked_type_layer_rejects_formatting_without_history() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 20, "text": "a", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + let other = s.execute("type.create", json!({"x": 20, "y": 60, "text": "b", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); + let before = text_layer(&s, id); + let history = s.active().unwrap().history.past_len(); + + for (cmd, p) in [ + ("type.setStyle", json!({"layer": id, "size": 40, "fauxBold": true})), + ("type.setStyle", json!({"layers": [other, id], "size": 40})), + ("type.warpText", json!({"layer": id, "style": "arc"})), + ("type.antiAlias.none", json!({"layer": id})), + ("type.orientation.vertical", json!({"layer": id})), + ("type.openType.swash", json!({"layer": id})), + ] { + let result = s.execute(cmd, p); + assert!(matches!(&result, Err(EngineError::Other(message)) if message.contains("locked")), "{cmd}: {result:?}"); + } + assert_eq!(text_layer(&s, id), before); + assert_eq!(text_layer(&s, other).size_pt, 12.0); + assert_eq!(s.active().unwrap().history.past_len(), history); + + s.execute("layer.setProps", json!({"layer": id, "locked": false})).unwrap(); + s.execute("type.setStyle", json!({"layer": id, "size": 40})).unwrap(); + assert_eq!(text_layer(&s, id).size_pt, 40.0); + } + #[test] fn trailing_empty_paragraph_styles_without_changing_previous_lines() { let mut s = session(); @@ -1519,6 +1589,25 @@ mod tests { assert_eq!(t.runs[0].style.size_pt, 40.0); } + /// Replacing a selected smaller second line (by typing or pasting) keeps its size, not the + /// first line's, whose line break precedes the selection. + #[test] + fn replacing_a_selection_keeps_its_first_characters_style() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "BIG\nsmall", "size": 40})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": id, "runs": [{"start": 4, "end": 9, "size": 12}]})).unwrap(); + s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 9, "text": "AIR"}})).unwrap(); + let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| (r.len, r.style.size_pt)).collect::>(); + assert_eq!(text_layer(&s, id).text, "BIG\nAIR"); + assert_eq!(sizes(&s), [(4, 40.0), (3, 12.0)]); + // A mixed selection takes its first character's style. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 2, "end": 6, "text": "xy"}})).unwrap(); + assert_eq!(sizes(&s), [(4, 40.0), (1, 12.0)]); + // Inserting at a caret still follows the character before it. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 4, "text": "!"}})).unwrap(); + assert_eq!(sizes(&s), [(5, 40.0), (1, 12.0)]); + } + fn kerning_of(s: &Session, id: u64) -> Vec<(Kerning, f32)> { let t = text_layer(s, id); let mut out = Vec::new(); diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/type_extra_cmds.rs index efa2d791cc..91d75f033e 100644 --- a/crates/engine/src/type_extra_cmds.rs +++ b/crates/engine/src/type_extra_cmds.rs @@ -13,7 +13,7 @@ use photocraft_geom::Point; use photocraft_text::render::PathEl; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, layer_param}; +use crate::commands::{CommandSpec, explicit_layer, layer_param}; use crate::type_cmds::{ check_text_unlocked, format_targets, has_format_target, is_auto_named, layer_name, refresh, replace_text, style_paragraphs, style_range, with_text_targets, }; @@ -477,7 +477,10 @@ fn toggle_opentype(s: &mut Session, p: &Value, tag: &'static str) -> Result Result { - if has_text(s).is_ok() && p.get("new").and_then(Value::as_bool) != Some(true) { + // Into the layer `with_text` edits: an explicit "layer" (an error unless it is a type layer), + // else the active layer when it is a type layer. + let new = p.get("new").and_then(Value::as_bool) == Some(true); + if !new && (explicit_layer(s, p)?.is_some() || has_text(s).is_ok()) { let caret = with_text(s, p, "Paste Lorem Ipsum", |t, _| { let at = p.get("at").and_then(Value::as_u64).map_or(t.text.len(), |c| byte_index(&t.text, c as usize)); replace_text(t, at, at, LOREM_IPSUM); diff --git a/crates/engine/src/type_extra_cmds/tests.rs b/crates/engine/src/type_extra_cmds/tests.rs index 7386927bb7..687a56471a 100644 --- a/crates/engine/src/type_extra_cmds/tests.rs +++ b/crates/engine/src/type_extra_cmds/tests.rs @@ -329,6 +329,27 @@ fn all_locked_layer_rejects_paste_lorem_ipsum_without_history() { } } +#[test] +fn paste_lorem_ipsum_inserts_into_the_layer_param_not_the_active_layer() { + // #5659: with a pixel layer active, an explicit type "layer" got a new text box instead. + let mut s = session(8); + let id = text_layer(&mut s, "Hi"); + s.execute("layer.new.layer", json!({})).unwrap(); + let pixel = s.active().unwrap().active_layer.unwrap(); + assert_ne!(pixel, id); + let count = s.active().unwrap().doc.walk().len(); + let r = s.execute("type.pasteLoremIpsum", json!({"layer": id.0, "at": 0})).unwrap(); + assert!(text(&s, id).text.starts_with(LOREM_IPSUM), "{}", text(&s, id).text); + assert!(text(&s, id).text.ends_with("Hi")); + assert_eq!(r["caret"], LOREM_IPSUM.chars().count()); + assert_eq!(s.active().unwrap().doc.walk().len(), count); + // An explicit layer that is not a type layer is an error, not a new layer. + let history = s.active().unwrap().history.past_len(); + assert!(s.execute("type.pasteLoremIpsum", json!({"layer": pixel.0})).is_err()); + assert_eq!(s.active().unwrap().doc.walk().len(), count); + assert_eq!(s.active().unwrap().history.past_len(), history); +} + /// A type layer stored with a family label that is not installed, as a PSD keeps the family it /// guessed from a PostScript name whose face was absent when the file was opened. fn guessed_family_layer(s: &mut Session, text: &str, ps: Option<&str>) -> (LayerId, Value) { @@ -399,3 +420,21 @@ fn exact_postscript_face_outside_the_guessed_family_is_not_missing() { assert!(!fonts.has_family(&photocraft_text::fonts::guess_from_postscript("UnrelatedPS30").family)); assert_eq!((style_font_missing(&mut fonts, &style("UnrelatedPS30")), style_font_missing(&mut fonts, &style("UnrelatedPS31"))), (false, true)); } + +/// #5044: PostScript names whose family has its space elsewhere (`BMDoHyeon`, family +/// "BM DoHyeon") or an underscore style suffix (`Daum_SemiBold`). Guessing splits them as +/// "BM Do Hyeon" and "Daum_Semi Bold", neither installed; the exact installed face resolves them. +#[test] +fn camel_case_and_underscore_postscript_names_resolve_to_their_installed_faces() { + let mut fonts = photocraft_text::FontDb::new(); + fonts.register_font_data(renamed_face(&photocraft_text::fonts::INTER_REGULAR, "BM DoHyeon", "BMDoHyeon")); + fonts.register_font_data(renamed_face(&photocraft_text::fonts::INTER_REGULAR, "Daum", "Daum_SemiBold")); + for (ps, family) in [("BMDoHyeon", "BM DoHyeon"), ("Daum_SemiBold", "Daum")] { + let guess = photocraft_text::fonts::guess_from_postscript(ps).family; + assert!(!fonts.has_family(&guess), "{ps}: the guess {guess:?} is not an installed family"); + let r = fonts.resolve_postscript(ps); + assert_eq!((r.family.as_str(), r.exact), (family, true), "{ps}"); + let style = photocraft_doc::text::CharStyle { font_family: guess.clone(), postscript_name: Some(ps.into()), ..Default::default() }; + assert!(!style_font_missing(&mut fonts, &style), "{ps} stored as {guess:?} is not missing"); + } +} diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/variables_cmds.rs index f42b744844..0a49d780d5 100644 --- a/crates/engine/src/variables_cmds.rs +++ b/crates/engine/src/variables_cmds.rs @@ -199,7 +199,9 @@ fn replace_pixels(doc: &mut Document, layer: LayerId, path: &str, method: PixelM return Ok(()); } let fmt = doc.pixel_format(); - let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("read `{path}`: {e}")))?; + // The path is stored in the document's data sets. + let file = crate::doc_path::resolve(path).map_err(|why| crate::doc_path::refusal("the image", path, why))?; + let bytes = std::fs::read(&file).map_err(|e| EngineError::Other(format!("read `{path}`: {e}")))?; let src = crate::file_cmds::import(path, &bytes)?; let img = crate::file_cmds::flattened(&src, fmt); let (iw, ih) = (src.size.width.max(1) as f64, src.size.height.max(1) as f64); @@ -284,6 +286,8 @@ fn import_data_sets(s: &mut Session, p: &Value) -> Result { /// file beneath its read root and hands the text over (#3216). pub fn import_data_sets_text(s: &mut Session, text: &str, p: &Value) -> Result { let delim = p.get("delimiter").and_then(Value::as_str).and_then(|d| d.bytes().next()).unwrap_or(b','); + // Excel's "CSV UTF-8" starts with a byte order mark that is not part of the first header cell. + let text = text.strip_prefix('\u{feff}').unwrap_or(text); let vars = s.active().ok_or(EngineError::NoDocument)?.doc.variables.clone(); let mut records = csv_records(text).filter(|r| !r.trim().is_empty()); let header: Vec = records.next().map(|h| split_csv(h, delim)).unwrap_or_default(); diff --git a/crates/engine/src/variables_cmds/tests.rs b/crates/engine/src/variables_cmds/tests.rs index c2a30cab68..8a0c591e71 100644 --- a/crates/engine/src/variables_cmds/tests.rs +++ b/crates/engine/src/variables_cmds/tests.rs @@ -136,6 +136,38 @@ fn csv_import_and_apply() { assert_eq!(text_of(&s, title), "On Sale"); } +#[test] +fn csv_import_ignores_utf8_bom() { + let dir = tmp("csv-bom"); + let csv = format!("{dir}/sets.csv"); + + // BOM before the `DataSet` name column: sets keep their names. + let (mut s, _p, badge, title) = session(); + s.execute( + "image.variables.define", + json!({"defs": [ + {"name": "showBadge", "layer": badge.0, "type": "visibility"}, + {"name": "headline", "layer": title.0, "type": "textReplacement"}, + ]}), + ) + .unwrap(); + std::fs::write(&csv, "\u{feff}DataSet,showBadge,headline\nrow-on,true,On Sale\n").unwrap(); + let r = s.execute("file.import.variableDataSets", json!({"path": csv})).unwrap(); + assert_eq!(r["imported"], 1); + s.execute("image.applyDataSet", json!({"name": "row-on"})).unwrap(); + assert!(doc(&s).layer(badge).unwrap().visible); + assert_eq!(text_of(&s, title), "On Sale"); + + // BOM before a variable column (no name column): the variable is still imported. + let (mut s, _p, badge, title) = session(); + s.execute("image.variables.define", json!({"defs": [{"name": "headline", "layer": title.0, "type": "textReplacement"}]})).unwrap(); + let _ = badge; + let r = import_data_sets_text(&mut s, "\u{feff}headline\nHello\n", &json!({})).unwrap(); + assert_eq!(r["imported"], 1); + s.execute("image.applyDataSet", json!({"index": 0})).unwrap(); + assert_eq!(text_of(&s, title), "Hello"); +} + #[test] fn csv_fields_preserve_unicode_and_quoting() { for (line, delimiter, expected) in [ diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rs index 14579e5954..15c14e5a1c 100644 --- a/crates/engine/src/vector_cmds.rs +++ b/crates/engine/src/vector_cmds.rs @@ -1091,9 +1091,25 @@ fn path_rename(s: &mut Session, p: &Value) -> Result { fn path_to_selection(s: &mut Session, p: &Value) -> Result { let path = resolve_path(s, p.get("name").and_then(Value::as_str))?; - let feather = f64p(p, "feather").unwrap_or(0.0) as f32; - let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); - let mode = SelectionMode::parse(p.get("mode").and_then(Value::as_str).unwrap_or("replace")); + // Validate before rasterizing or touching selection history. An unchecked feather value + // could silently become zero (negative/string), or expand into an excessive blur. + let feather = match p.get("feather") { + None => 0.0, + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && (0.0..=1000.0).contains(n)) + .ok_or_else(|| bad("path.toSelection", "`feather` must be a finite number within 0..1000"))? as f32, + }; + let aa = match p.get("antiAlias") { + None => true, + Some(Value::Bool(v)) => *v, + _ => return Err(bad("path.toSelection", "`antiAlias` must be a boolean")), + }; + let mode = match p.get("mode") { + None => SelectionMode::Replace, + Some(Value::String(v)) if matches!(v.as_str(), "replace" | "add" | "subtract" | "intersect") => SelectionMode::parse(v), + _ => return Err(bad("path.toSelection", "`mode` must be replace, add, subtract or intersect")), + }; let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds(); let mut mask = vector::fill_rasterizer(&path, vector::DEFAULT_TOLERANCE).render(area); if !aa { diff --git a/crates/engine/src/vector_cmds/tests.rs b/crates/engine/src/vector_cmds/tests.rs index 7e1c871dff..a2e8047115 100644 --- a/crates/engine/src/vector_cmds/tests.rs +++ b/crates/engine/src/vector_cmds/tests.rs @@ -335,6 +335,63 @@ fn path_to_selection_matches_analytic_shape() { assert!(m[100 * 200 + 160] > 0.2 && m[100 * 200 + 160] < 0.8); } +#[test] +fn path_make_selection_rejects_invalid_options_without_changing_history() { + let mut s = session(80, 80, 8); + s.execute("path.set", json!({"path": {"subpaths": [{"knots": [[12, 12], [60, 12], [60, 60], [12, 60]]}]}})).unwrap(); + s.execute("select.rect", json!({"x": 20, "y": 20, "width": 12, "height": 12})).unwrap(); + let before = doc(&s).clone(); + let history = s.active().unwrap().history.past_len(); + for opts in [ + json!({"feather": -1}), + json!({"feather": 1001}), + json!({"feather": 1e100}), + json!({"feather": "4"}), + json!({"feather": true}), + json!({"antiAlias": "false"}), + json!({"antiAlias": 1}), + json!({"mode": "union"}), + json!({"mode": 42}), + ] { + assert!(s.execute("path.toSelection", opts.clone()).is_err(), "accepted invalid Make Selection options: {opts}"); + assert_eq!(*doc(&s), before, "invalid Make Selection modified the document: {opts}"); + assert_eq!(s.active().unwrap().history.past_len(), history, "invalid Make Selection changed history: {opts}"); + } +} + +#[test] +fn open_pen_paths_make_the_same_selection_as_closed_paths() { + // The pen's unfinished work path should be implicitly closed when rasterized into a selection. + let mut s = session(80, 80, 8); + let knots = json!([[12, 12], [52, 12], [52, 52], [12, 52]]); + for (aa, feather) in [(false, 0.0), (true, 0.0), (false, 3.0), (true, 3.0)] { + let mut masks = Vec::new(); + for closed in [false, true] { + s.execute("path.set", json!({"path": {"subpaths": [{"closed": closed, "knots": knots}]}})).unwrap(); + s.execute("path.toSelection", json!({"antiAlias": aa, "feather": feather, "mode": "replace"})).unwrap(); + masks.push(selection_mask(&s)); + } + assert_eq!(masks[0], masks[1], "open and closed paths differ (antiAlias={aa}, feather={feather})"); + assert!(masks[0][32 * 80 + 32] > 0.99); + assert_eq!(masks[0][4 * 80 + 4], 0.0); + if feather > 0.0 { + assert!(masks[0].iter().any(|v| *v > 0.0 && *v < 1.0), "feather did not soften the selection"); + } + } + + // All boolean operations should use the same selection semantics for an open Pen path. + for mode in ["replace", "add", "subtract", "intersect"] { + s.execute("select.rect", json!({"x": 30, "y": 30, "width": 34, "height": 25})).unwrap(); + s.execute("path.set", json!({"path": {"subpaths": [{"closed": false, "knots": knots}]}})).unwrap(); + s.execute("path.toSelection", json!({"mode": mode, "antiAlias": false})).unwrap(); + let mask = selection_mask(&s); + let at = |x: usize, y: usize| mask[y * 80 + x]; + assert_eq!(at(20, 20), if matches!(mode, "replace" | "add") { 1.0 } else { 0.0 }, "{mode}: path-only"); + assert_eq!(at(60, 40), if matches!(mode, "add" | "subtract") { 1.0 } else { 0.0 }, "{mode}: previous-only"); + assert_eq!(at(40, 40), if mode == "subtract" { 0.0 } else { 1.0 }, "{mode}: overlap"); + } +} + #[test] fn selection_to_work_path_roundtrip_iou() { let mut s = session(240, 180, 8); diff --git a/crates/engine/src/video_cmds.rs b/crates/engine/src/video_cmds.rs index 6fb9ab4574..0d27d3c827 100644 --- a/crates/engine/src/video_cmds.rs +++ b/crates/engine/src/video_cmds.rs @@ -301,7 +301,7 @@ fn new_from_file(s: &mut Session, p: &Value) -> Result { let fmt = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format(); let Footage { frames, fps: footage_fps } = load_frames(&path, fmt)?; // An explicit `fps` wins, then the rate the footage implies, then 30. - let fps = p.get("fps").and_then(Value::as_f64).map(|f| f as f32).or(footage_fps).unwrap_or(30.0); + let fps = crate::timeline_cmds::fps_param("layer.videoLayers.newVideoLayerFromFile", p)?.or(footage_fps).unwrap_or(30.0); let n = frames.len(); let id = s.edit("New Video Layer from File", |doc, active| { store(doc); @@ -341,10 +341,10 @@ fn replace_footage(s: &mut Session, p: &Value) -> Result { } fn interpret_footage(s: &mut Session, p: &Value) -> Result { - let fps = p.get("fps").and_then(Value::as_f64); + let fps = crate::timeline_cmds::fps_param("layer.videoLayers.interpretFootage", p)?; edit_video(s, "Interpret Footage", move |v, _| { if let Some(f) = fps { - v.fps = f as f32; + v.fps = f; } Ok(()) }) @@ -365,7 +365,9 @@ fn reload_frame(s: &mut Session, _p: &Value) -> Result { let photocraft_doc::VideoSource::File { path } = src else { return Err(EngineError::BadParams { cmd: "layer.videoLayers.reloadFrame".into(), msg: "this layer has no file source to reload".into() }); }; - let frames = load_frames(&path, fmt)?.frames; + // The footage path is stored in the document. + let file = crate::doc_path::resolve(&path).map_err(|why| crate::doc_path::refusal("the footage", &path, why))?; + let frames = load_frames(&file.to_string_lossy(), fmt)?.frames; edit_video(s, "Reload Frame", move |v, _| { v.original_frames = Some(frames.clone()); v.frames = frames; @@ -424,7 +426,9 @@ pub fn render_video_with( if frames > crate::timeline_cmds::MAX_DURATION { return Err(EngineError::Other(format!("the timeline is {frames} frames; Render Video is limited to {} frames", crate::timeline_cmds::MAX_DURATION))); } - let fps = base.timeline.as_ref().map_or(30.0, |t| t.fps).max(1.0); + // Only the GIF delay reads the rate (frames come from the duration); rates under 1 fps are + // valid timelines, so only an unusable loaded rate falls back to 30. + let fps = base.timeline.as_ref().map(|t| t.fps).filter(|f| f.is_finite() && *f > 0.0).unwrap_or(30.0); let stem = base.name.rsplit_once('.').map_or(base.name.as_str(), |(a, _)| a).to_string(); let fmt = base.pixel_format(); let bounds = base.bounds(); diff --git a/crates/engine/src/video_cmds/tests.rs b/crates/engine/src/video_cmds/tests.rs index c16c7f8e39..3cdda8adc0 100644 --- a/crates/engine/src/video_cmds/tests.rs +++ b/crates/engine/src/video_cmds/tests.rs @@ -151,6 +151,39 @@ fn a_fully_transparent_animated_gif_frame_encodes() { assert!(f.indices.iter().all(|&i| Some(i) == f.transparent)); } +/// The GIF frame delays (centiseconds, from each Graphic Control Extension) of a Render Video. +fn rendered_gif_delays(s: &Session) -> Vec { + let mut gif = Vec::new(); + render_video_with( + s, + &json!({"format": "gif"}), + |_, bytes| { + gif = bytes.to_vec(); + Ok(()) + }, + |_, _| true, + ) + .unwrap(); + gif.windows(6).filter(|w| w[..3] == [0x21, 0xF9, 0x04]).map(|w| u16::from_le_bytes([w[4], w[5]])).collect() +} + +#[test] +fn animated_gif_delay_follows_timelines_under_one_fps() { + // 0.5 fps is a valid timeline rate; its frames last 2 s, not the 1 s a 1 fps floor gave. + let mut s = session(); + s.execute("timeline.create", json!({"duration": 2, "fps": 0.5})).unwrap(); + assert_eq!(rendered_gif_delays(&s), [200, 200]); + // A loaded timeline with an unusable rate falls back to 30 fps (3 cs), as with no timeline. + let mut doc = (*s.active().unwrap().doc).clone(); + doc.timeline = Some(Timeline::new(2, f32::NAN)); + { + let st = s.active_mut().unwrap(); + st.doc = std::sync::Arc::new(doc); + st.revision += 1; + } + assert_eq!(rendered_gif_delays(&s), [3, 3]); +} + #[test] fn inspect_reports_video_layer() { let dir = tmpdir("vinsp"); @@ -330,6 +363,32 @@ fn a_still_gif_is_one_frame_at_the_default_rate() { assert_eq!(s.active().unwrap().doc.layer(id).unwrap().video.as_ref().unwrap().fps, 10.0); } +/// Interpret Footage and New Video Layer from File reject an fps that isn't a finite number in +/// `(0, MAX_FPS]` and keep the layer as it was (#5657). 1e39 used to become an infinite rate the +/// next `.pcraft` save refused. +#[test] +fn an_invalid_frame_rate_is_an_error_and_changes_nothing() { + let mut s = session(); + let id = LayerId(s.execute("layer.videoLayers.newBlankVideoLayer", json!({})).unwrap()["layer"].as_u64().unwrap()); + let fps = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().video.as_ref().unwrap().fps; + assert_eq!(fps(&s), 30.0); + for bad in [json!(0), json!(-1), json!(1e39), json!("x")] { + assert!(s.execute("layer.videoLayers.interpretFootage", json!({"fps": bad})).is_err(), "fps {bad}"); + assert_eq!(fps(&s), 30.0, "fps {bad}"); + } + s.execute("layer.videoLayers.interpretFootage", json!({"fps": 24})).unwrap(); + assert_eq!(fps(&s), 24.0); + + let dir = tmpdir("gifin-badfps"); + let path = format!("{dir}/anim.gif"); + write_gif(&path, 8, 8, &[([255, 0, 0], 10), ([0, 255, 0], 10)]); + let layers = s.active().unwrap().doc.layer_count(); + for bad in [json!(0), json!(-1), json!(1e39), json!("x")] { + assert!(s.execute("layer.videoLayers.newVideoLayerFromFile", json!({"path": path, "fps": bad})).is_err(), "fps {bad}"); + assert_eq!(s.active().unwrap().doc.layer_count(), layers, "fps {bad}"); + } +} + #[test] fn video_frames_to_layers_takes_every_gif_frame() { let dir = tmpdir("gifin-ftl"); diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 5142b0a940..8e2ab3c4fd 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -121,6 +121,9 @@ fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp, // A selection limits the linked mask exactly as it limits the pixels (#4175, as Free Transform // and Perspective Warp do, #3083); a layer that moves whole takes its whole mask along. let mask_sel = doc_sel.filter(|_| !crate::transform_cmds::moves_whole(l)); + // The masks (and so a fill's frame) move, but a fill layer's cached render isn't warped: + // drop it, the fill re-renders from its model. + l.fill_cache = None; match &mut l.content { LayerContent::Group(g) => { for c in g.children.iter_mut() { diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rs index 595ad21956..755ba07320 100644 --- a/crates/engine/src/web_cmds.rs +++ b/crates/engine/src/web_cmds.rs @@ -70,6 +70,9 @@ pub enum WebMetadata { None, Copyright, CopyrightAndContact, + /// All the XMP, none of the photo's EXIF (camera, date taken, GPS). + AllExceptCameraInfo, + /// All the XMP and the photo's EXIF. All, } @@ -203,8 +206,9 @@ impl WebSettings { "none" => WebMetadata::None, "copyright" => WebMetadata::Copyright, "copyrightAndContact" | "contact" => WebMetadata::CopyrightAndContact, - "all" | "allExceptCameraInfo" => WebMetadata::All, - m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|all)"))), + "allExceptCameraInfo" => WebMetadata::AllExceptCameraInfo, + "all" => WebMetadata::All, + m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|allExceptCameraInfo|all)"))), }; } if let Some(table) = p.get("colorTable") { @@ -262,6 +266,7 @@ impl WebSettings { WebMetadata::None => "none", WebMetadata::Copyright => "copyright", WebMetadata::CopyrightAndContact => "copyrightAndContact", + WebMetadata::AllExceptCameraInfo => "allExceptCameraInfo", WebMetadata::All => "all", }; let matte = self.matte.map_or("none".to_string(), |c| format!("#{:02x}{:02x}{:02x}", to8(c[0]), to8(c[1]), to8(c[2]))); @@ -387,7 +392,7 @@ pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option { let xmp = doc.metadata.xmp.as_deref()?; match m { WebMetadata::None => None, - WebMetadata::All => Some(xmp.to_string()), + WebMetadata::All | WebMetadata::AllExceptCameraInfo => Some(xmp.to_string()), WebMetadata::Copyright | WebMetadata::CopyrightAndContact => { let info = crate::file_cmds::read_file_info(Some(xmp)); let mut keep = serde_json::Map::new(); @@ -405,10 +410,33 @@ pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option { } } +/// The photo's EXIF to embed for the metadata choice: only "All" carries it (#7436). +pub fn web_exif(doc: &Document, m: WebMetadata) -> Option<&[u8]> { + doc.metadata.exif.as_deref().map(Vec::as_slice).filter(|_| m == WebMetadata::All) +} + +/// The response's warnings: EXIF that a JPEG couldn't hold (one segment, about 64 KB). +fn web_warnings(st: &WebSettings, exif: Option<&[u8]>, dpi: f32) -> Vec { + exif.filter(|x| st.format == WebFormat::Jpeg && !photocraft_codecs::web::jpeg_exif_fits(x, Some(dpi))) + .map(|x| photocraft_codecs::FidelityWarning::MetadataTooLarge { what: "EXIF", bytes: x.len() }.to_string()) + .into_iter() + .collect() +} + /// Optimises `rect` of `px` (straight RGBA, `bw` wide) with `st`. `preview` also returns what /// the file looks like (the dialog's panes); exports skip it. #[allow(clippy::too_many_arguments)] -pub fn optimize(px: &[[f32; 4]], bw: usize, rect: Rect, st: &WebSettings, icc: Option<&[u8]>, xmp: Option<&str>, dpi: f32, preview: bool) -> Result { +pub fn optimize( + px: &[[f32; 4]], + bw: usize, + rect: Rect, + st: &WebSettings, + icc: Option<&[u8]>, + exif: Option<&[u8]>, + xmp: Option<&str>, + dpi: f32, + preview: bool, +) -> Result { if bw == 0 || rect.x0 < 0 || rect.y0 < 0 || rect.is_empty() || rect.x1 as usize > bw || (rect.y1 as usize).checked_mul(bw).is_none_or(|end| end > px.len()) { return Err(other("slice is outside the pixel buffer")); @@ -460,8 +488,9 @@ pub fn optimize(px: &[[f32; 4]], bw: usize, rect: Rect, st: &WebSettings, icc: O } // Save for Web's 0–100 quality → encoder 1–100. let q = st.quality.max(1); - let bytes = photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), xmp) - .map_err(e)?; + let bytes = + photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), exif, xmp) + .map_err(e)?; if preview { // The preview shows the compression artefacts. look = match photocraft_codecs::decode(&bytes) { @@ -557,7 +586,7 @@ pub fn optimize(px: &[[f32; 4]], bw: usize, rect: Rect, st: &WebSettings, icc: O let bytes = if st.format == WebFormat::Gif { photocraft_codecs::web::encode_gif_indexed(ww, hh, &idx, &pal, tt, st.interlaced).map_err(e)? } else { - photocraft_codecs::encode_png_indexed(ww, hh, &idx, &pal, tt, None).map_err(e)? + photocraft_codecs::encode_png_indexed(ww, hh, &idx, &pal, tt, None, None).map_err(e)? }; if preview { indices = idx; @@ -873,7 +902,9 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u let bw = wdoc.size.width as usize; let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice()); let xmp = web_xmp(&doc, st.metadata); + let exif = web_exif(&doc, st.metadata); let dpi = wdoc.resolution_dpi; + let warnings = web_warnings(&st, exif, dpi); let all = slices::resolve(&doc); let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all"); let numbers: Option> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()); @@ -895,18 +926,18 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u } // Estimate only (the dialog's annotations): the whole image, or each chosen slice. if single.is_none() && dir.is_none() { - let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?; + let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; return Ok( json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "colorTable": o.color_table.iter().map(|c| rgb_hex(*c)).collect::>(), "transparentIndex": o.transparent_index}), ); } if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) { - let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?; + let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; write(path, &o.bytes)?; remember_web_settings(s, cmd, &last_web); s.file_menu.last_web = Some(last_web); crate::automate_cmds::fire_event(s, "export"); - return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors})); + return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "warnings": warnings})); } let dir = dir.map(str::to_string).or_else(|| single.and_then(|f| std::path::Path::new(f).parent().map(|d| d.to_string_lossy().into_owned()))).unwrap_or_default(); @@ -961,7 +992,7 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u cells.push((piece, bg, text)); continue; } - let o = optimize(&buf.px, bw, piece, &st, icc, xmp.as_deref(), dpi, false)?; + let o = optimize(&buf.px, bw, piece, &st, icc, exif, xmp.as_deref(), dpi, false)?; let stem = if split { format!("{}_{:02}", slice_file(&r.name), k + 1) } else { slice_file(&r.name) }; let name = unique(&stem, o.ext); let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") }; @@ -997,7 +1028,9 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u remember_web_settings(s, cmd, &last_web); s.file_menu.last_web = Some(last_web); crate::automate_cmds::fire_event(s, "export"); - Ok(json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height})) + Ok( + json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height, "warnings": warnings}), + ) } // ---------- Export Preferences / Quick Export ---------- @@ -1024,27 +1057,48 @@ fn export_preferences(s: &mut Session, p: &Value) -> Result { Ok(json!({"section": "export", "values": s.prefs().get("export").unwrap_or(Value::Null)})) } +/// The Quick Export format's extension (Export Preferences › Format). +fn quick_export_ext(s: &Session) -> String { + serde_json::to_value(s.prefs().export.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into()) +} + +/// Where Quick Export writes the active document with no `path` given: `.` beside +/// its file, when Export Preferences › Location is Same Folder and the document has a file. +pub fn quick_export_target(s: &Session) -> Option { + let same = s.prefs().export.quick_export_location == crate::prefs::ExportLocation::SameFolder; + let dp = s.active()?.path.as_deref().filter(|_| same)?; + let dir = std::path::Path::new(dp).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); + Some(join(&dir, &format!("{}.{}", stem(dp), quick_export_ext(s)))) +} + +/// Whether [`quick_export_target`] is the active document's own file (a document opened from +/// `photo.png` and exported as PNG), which Quick Export must not replace without asking (#6599). +pub fn quick_export_target_is_own_file(s: &Session) -> bool { + let own = s.active().and_then(|d| d.path.as_deref()); + quick_export_target(s).zip(own).is_some_and(|(target, own)| crate::file_cmds::same_file(&target, own)) +} + /// File › Export › Quick Export as : the format, quality, metadata, colour space and /// location from Export Preferences. `path` overrides the location ("ask" needs one). fn quick_export(s: &mut Session, p: &Value) -> Result { let cmd = "file.export.quickExport"; let prefs = s.prefs().export.clone(); - let fmt = serde_json::to_value(prefs.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into()); - let d = s.active().ok_or(EngineError::NoDocument)?; - let doc = d.doc.clone(); + let fmt = quick_export_ext(s); let path = match p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()) { Some(v) => v.to_string(), None => { - let same = serde_json::to_value(prefs.quick_export_location).ok().and_then(|v| v.as_str().map(str::to_string)).is_some_and(|v| v == "sameFolder"); - match (&d.path, same) { - (Some(dp), true) => { - let dir = std::path::Path::new(dp).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); - join(&dir, &format!("{}.{fmt}", stem(dp))) - } - _ => return Err(bad(cmd, "missing `path` (Export Preferences › Location is \"ask\", or the document was never saved)")), + let Some(target) = quick_export_target(s) else { + return Err(bad(cmd, "missing `path` (Export Preferences › Location is \"ask\", or the document was never saved)")); + }; + // The document's own file is never replaced by an export the user didn't name (#6599). + if quick_export_target_is_own_file(s) { + return Err(bad(cmd, format!("the export would replace the document's own file {target}; give a `path`"))); } + target } }; + let d = s.active().ok_or(EngineError::NoDocument)?; + let doc = d.doc.clone(); let metadata = serde_json::to_value(prefs.metadata).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); let mut o = serde_json::Map::new(); o.insert( @@ -1087,19 +1141,21 @@ fn quick_export(s: &mut Session, p: &Value) -> Result { let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?; let buf = photocraft_compose::flatten(&wdoc); let xmp = web_xmp(&doc, st.metadata); + let exif = web_exif(&doc, st.metadata); let opt = optimize( &buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, wdoc.icc_profile.as_deref().map(|v| v.as_slice()), + exif, xmp.as_deref(), wdoc.resolution_dpi, false, )?; write_file(&path, &opt.bytes)?; crate::automate_cmds::fire_event(s, "export"); - Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len()})) + Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)})) } // ---------- Generate › Image Assets ---------- @@ -1168,8 +1224,12 @@ fn parse_size(item: &str, dpi: f64) -> (Option, Option, Option, & && toks[1].eq_ignore_ascii_case("x") && let (Some(w), Some(h)) = (unit_px(toks[0], dpi), unit_px(toks[2], dpi)) { - let pos = item.find(toks[3]).unwrap_or(item.len()); - return (None, w, h, &item[pos..]); + // Skip exactly the three size tokens; searching for the name's first word could match inside the size. + let mut rest = item; + for _ in 0..3 { + rest = rest.trim_start().trim_start_matches(|c: char| !c.is_whitespace()); + } + return (None, w, h, rest.trim_start()); } (None, None, None, item) } @@ -1337,10 +1397,15 @@ fn asset_output_path(dir: &str, relative: &str) -> Result<(String, String)> { } /// Exports every asset named by `doc`'s layers into `dir`. Returns (files, errors). +/// +/// Each file is written once per run (#6614): when two layers (or two default variants) name the +/// same file, the one higher in the Layers panel keeps it and the other is reported in `errors`. +/// Names are compared ignoring case, as `Logo.png` and `logo.png` are one file on Windows and +/// macOS. pub fn generate_assets(doc: &Document, dir: &str) -> (Vec, Vec) { let dpi = f64::from(doc.resolution_dpi.max(1.0)); let mut defaults: Option> = None; - let mut jobs: Vec<(LayerId, AssetSpec)> = Vec::new(); + let mut by_layer: Vec> = Vec::new(); for (_, _, l) in doc.walk() { if let Some(d) = parse_defaults(&l.name, dpi) { defaults = Some(d); @@ -1349,22 +1414,26 @@ pub fn generate_assets(doc: &Document, dir: &str) -> (Vec, Vec) { if matches!(l.content, LayerContent::Adjustment(_)) { continue; } - for spec in parse_asset_name(&l.name, dpi) { - jobs.push((l.id, spec)); - } + by_layer.push(parse_asset_name(&l.name, dpi).into_iter().map(|spec| (l.id, spec)).collect()); } + // Top layer first, as the Layers panel lists them (`walk` goes bottom to top). + let jobs: Vec<(LayerId, AssetSpec)> = by_layer.into_iter().rev().flatten().collect(); let variants: Vec = match defaults { Some(d) if !d.is_empty() => d, _ => vec![AssetDefault::default()], }; let mut files = Vec::new(); let mut errors = Vec::new(); + let mut written = std::collections::HashSet::new(); for (id, spec) in &jobs { for v in &variants { let r = (|| -> Result { let (name_stem, ext) = spec.file.rsplit_once('.').unwrap_or((spec.file.as_str(), "png")); let rel = format!("{}{}{}.{ext}", v.folder, name_stem, v.suffix); - asset_path_components(&rel)?; + let key = asset_path_components(&rel)?.join("/").to_lowercase(); + if written.contains(&key) { + return Err(other(format!("{rel}: another layer already writes this file; rename one of the layers"))); + } let mut one = crate::layer_menu_cmds::layer_document(doc, *id)?; one.metadata = Default::default(); let (w0, h0) = (f64::from(one.size.width), f64::from(one.size.height)); @@ -1392,12 +1461,14 @@ pub fn generate_assets(doc: &Document, dir: &str) -> (Vec, Vec) { if spec.format == "webp" { let (out, reported) = asset_output_path(dir, &rel)?; crate::file_cmds::save_doc(&wdoc, &out, None)?; + written.insert(key); return Ok(reported); } let buf = photocraft_compose::flatten(&wdoc); - let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, wdoc.resolution_dpi, false)?; + let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?; let (out, reported) = asset_output_path(dir, &rel)?; write_file(&out, &o.bytes)?; + written.insert(key); Ok(reported) })(); match r { @@ -1468,7 +1539,7 @@ pub fn specs() -> Vec { "Save for Web (Legacy)…", &["File", "Export"], Some("Cmd+Alt+Shift+S"), - r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|all"="copyright","convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes}"##, + r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##, has_doc, save_for_web ), @@ -1486,7 +1557,7 @@ pub fn specs() -> Vec { "Quick Export", &[], None, - r##"{"path":str? (required unless Export Preferences › Location is "sameFolder" and the document is saved)} → {path, format, bytes}"##, + r##"{"path":str? (required unless Export Preferences › Location is "sameFolder" and the document is saved)} → {path, format, bytes, warnings}"##, native_doc, quick_export ), diff --git a/crates/engine/src/web_cmds/color_table_tests.rs b/crates/engine/src/web_cmds/color_table_tests.rs index 1d319cb382..0c25ce0d24 100644 --- a/crates/engine/src/web_cmds/color_table_tests.rs +++ b/crates/engine/src/web_cmds/color_table_tests.rs @@ -7,13 +7,13 @@ fn color_replacement_preserves_pixel_membership_and_transparency() { for dither in ["none", "diffusion", "pattern", "noise"] { let p = json!({"format": format, "colorTable": ["#ff0000", "#0000ff"], "dither": dither, "matte": "none"}); let original = WebSettings::from_params(&p, "test").unwrap(); - let before = optimize(&px, 4, Rect::new(0, 0, 4, 1), &original, None, None, 72.0, true).unwrap(); + let before = optimize(&px, 4, Rect::new(0, 0, 4, 1), &original, None, None, None, 72.0, true).unwrap(); let mut edited = p.clone(); // Replace red with blue: re-quantization would now send all opaque pixels to blue. edited["colorTableEdits"] = json!({"0": "#0000ff", "1": "#00ff00"}); let settings = WebSettings::from_params(&edited, "test").unwrap(); assert_eq!(WebSettings::from_params(&settings.to_params(), "test").unwrap(), settings); - let after = optimize(&px, 4, Rect::new(0, 0, 4, 1), &settings, None, None, 72.0, true).unwrap(); + let after = optimize(&px, 4, Rect::new(0, 0, 4, 1), &settings, None, None, None, 72.0, true).unwrap(); for (old, new) in before.preview.as_chunks::<4>().0.iter().zip(after.preview.as_chunks::<4>().0) { if old[3] == 0 { assert_eq!(new[3], 0); @@ -81,8 +81,8 @@ fn malformed_tables_and_out_of_bounds_slices_return_errors() { } let settings = WebSettings::default(); for (bw, rect) in [(0, Rect::new(0, 0, 1, 1)), (1, Rect::new(-1, 0, 1, 1)), (1, Rect::new(0, 0, 2, 1)), (1, Rect::new(0, 0, 1, i32::MAX))] { - assert!(optimize(&[[0.0; 4]], bw, rect, &settings, None, None, 72.0, false).is_err()); + assert!(optimize(&[[0.0; 4]], bw, rect, &settings, None, None, None, 72.0, false).is_err()); } let settings = WebSettings::from_params(&json!({"format": "gif", "colorTable": vec!["#000000"; 256]}), "test").unwrap(); - assert!(optimize(&[[0.0; 4]], 1, Rect::new(0, 0, 1, 1), &settings, None, None, 72.0, true).is_err()); + assert!(optimize(&[[0.0; 4]], 1, Rect::new(0, 0, 1, 1), &settings, None, None, None, 72.0, true).is_err()); } diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rs index c3ffe6edce..5791e5f27c 100644 --- a/crates/engine/src/web_cmds/tests.rs +++ b/crates/engine/src/web_cmds/tests.rs @@ -437,6 +437,51 @@ fn export_preferences_drive_quick_export() { s.execute("prefs.reset", json!({"path": "export"})).unwrap(); } +/// #6599: with Location = Same Folder, a document opened from `photo.png` would be exported over +/// `photo.png` itself. Without a `path` that is refused and the file is left alone; named +/// explicitly (the save dialog's answer) it is written. +#[test] +fn quick_export_never_replaces_the_documents_own_file_unasked() { + let dir = tmp("quick_own_file"); + let mut s = session(8); + s.execute("file.export.exportPreferences", json!({"quickExportLocation": "sameFolder", "quickExportFormat": "png"})).unwrap(); + let own = format!("{dir}/photo.png"); + std::fs::write(&own, b"original").unwrap(); + s.active_mut().unwrap().path = Some(own.clone()); + assert_eq!(quick_export_target(&s), Some(own.clone())); + assert!(quick_export_target_is_own_file(&s)); + let e = s.execute("file.export.quickExport", json!({})).unwrap_err().to_string(); + assert!(e.contains("own file"), "{e}"); + assert_eq!(std::fs::read(&own).unwrap(), b"original", "the source is untouched"); + s.execute("file.export.quickExport", json!({"path": own})).unwrap(); + assert_eq!(decode(&own).dimensions(), (64, 48)); + // Another format, or a PSD's earlier export beside it, is still written without asking. + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg"})).unwrap(); + assert!(!quick_export_target_is_own_file(&s)); + assert_eq!(s.execute("file.export.quickExport", json!({})).unwrap()["path"], json!(format!("{dir}/photo.jpg"))); + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "png"})).unwrap(); + s.active_mut().unwrap().path = Some(format!("{dir}/photo.psd")); + assert!(!quick_export_target_is_own_file(&s)); + assert_eq!(s.execute("file.export.quickExport", json!({})).unwrap()["path"], json!(own)); + s.execute("prefs.reset", json!({"path": "export"})).unwrap(); +} + +#[test] +fn same_file_sees_through_other_names_for_one_file() { + let dir = tmp("same_file"); + let (a, b, c) = (format!("{dir}/a.png"), format!("{dir}/b.png"), format!("{dir}/c.png")); + std::fs::write(&a, b"a").unwrap(); + std::fs::write(&c, b"c").unwrap(); + assert!(crate::file_cmds::same_file(&a, &a)); + assert!(crate::file_cmds::same_file(&a, &format!("{dir}/./a.png"))); + assert!(!crate::file_cmds::same_file(&a, &c)); + assert!(!crate::file_cmds::same_file(&a, &b), "a missing file is not the same file"); + std::fs::hard_link(&a, &b).unwrap(); + assert!(crate::file_cmds::same_file(&a, &b), "a hard link is the same file"); + #[cfg(windows)] + assert!(crate::file_cmds::same_file(&a, &format!("{dir}/A.PNG")), "NTFS names ignore case"); +} + #[test] fn webp_export_preferences_select_lossless_or_lossy_output() { let dir = tmp("quick_webp_quality"); @@ -485,6 +530,20 @@ fn webp_export_preferences_select_lossless_or_lossy_output() { } } +#[test] +fn generator_spaced_size_keeps_only_the_file_name() { + for (name, w, h, file) in [ + ("2 x 2 2 icon.png", 2.0, 2.0, "2 icon.png"), + ("1in x 1in in.png", 72.0, 72.0, "in.png"), + ("2px x 1px x.png", 2.0, 1.0, "x.png"), + ("2in x 1in label name.png", 144.0, 72.0, "label name.png"), + ] { + let a = parse_asset_name(name, 72.0); + assert_eq!(a.len(), 1, "{name}"); + assert_eq!((a[0].width, a[0].height, a[0].file.as_str()), (Some(w), Some(h), file), "{name}"); + } +} + #[test] fn generator_naming_grammar() { let a = parse_asset_name("200% foo@2x.png, 48x48 icons/bar.png8 + photo.jpg8", 72.0); @@ -546,6 +605,47 @@ fn image_assets_are_generated_now_and_on_save() { assert_eq!(decode(&files[0]).dimensions(), (128, 80)); } +/// #6614: two layers, or two default variants, naming one file never overwrite each other: the +/// layer higher in the Layers panel keeps the file, whatever the case of its name, and the +/// others are reported. +#[test] +fn image_assets_never_write_one_file_twice() { + let dir = tmp("asset-collisions"); + let mut s = session(8); + s.edit("paint", |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Top", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(()) + }) + .unwrap(); + let mut d = (*s.active().unwrap().doc).clone(); + let id = |d: &photocraft_doc::Document, name: &str| d.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id; + let (top, logo) = (id(&d, "Top"), id(&d, "Logo")); + d.layer_mut(top).unwrap().name = "Logo.PNG".into(); + d.layer_mut(logo).unwrap().name = "logo.png, logo.png".into(); + let (files, errors) = generate_assets(&d, &dir); + assert_eq!(files.iter().map(|p| std::path::PathBuf::from(p.as_str())).collect::>(), vec![std::path::Path::new(&dir).join("Logo.png")]); + assert_eq!(decode(&files[0]).dimensions(), (4, 4), "the top layer keeps the file"); + assert_eq!(errors.len(), 2, "{errors:?}"); + assert!(errors.iter().all(|e| e["error"].as_str().unwrap().contains("another layer already writes this file")), "{errors:?}"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "one file, not a second one under another case"); + + // Two default variants that land on one name: the first keeps it. + let dir = tmp("asset-variant-collisions"); + d.layer_mut(top).unwrap().name = "icon.png".into(); + d.layer_mut(logo).unwrap().name = "Logo".into(); + d.layers + .push(Layer::new("default 50% + 200% + 200% @2x", LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None }))); + let (files, errors) = generate_assets(&d, &dir); + let names: Vec<_> = files.iter().map(|p| std::path::Path::new(p).file_name().unwrap().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["icon.png", "icon@2x.png"]); + assert_eq!(decode(&files[0]).dimensions(), (2, 2), "the 50% variant keeps icon.png"); + assert_eq!(errors.len(), 1, "{errors:?}"); +} + #[test] fn image_assets_reject_traversal_from_names_and_defaults() { let base = tmp("asset-path-guard"); @@ -635,7 +735,7 @@ fn previews_show_the_optimised_pixels() { let buf = photocraft_compose::flatten(&wd); for f in ["jpeg", "gif", "png8", "png24", "wbmp"] { let st = WebSettings::from_params(&json!({"format": f, "quality": 90, "transparency": false}), "x").unwrap(); - let o = optimize(&buf.px, 64, wd.bounds(), &st, None, None, 72.0, true).unwrap(); + let o = optimize(&buf.px, 64, wd.bounds(), &st, None, None, None, 72.0, true).unwrap(); assert_eq!(o.preview.len(), 64 * 48 * 4, "{f}"); // Red square centre stays red (WBMP: dark). let i = (16 * 64 + 16) * 4; @@ -645,7 +745,7 @@ fn previews_show_the_optimised_pixels() { } else { assert!(px[0] > 200 && px[1] < 60 && px[2] < 60, "{f}: {px:?}"); } - let none = optimize(&buf.px, 64, wd.bounds(), &st, None, None, 72.0, false).unwrap(); + let none = optimize(&buf.px, 64, wd.bounds(), &st, None, None, None, 72.0, false).unwrap(); assert!(none.preview.is_empty()); assert_eq!(none.bytes, o.bytes); } @@ -656,7 +756,7 @@ fn jpeg_preview_at_odd_sizes() { for (w, h, q) in [(640usize, 431usize, 90), (640, 430, 60), (333, 222, 30)] { let px: Vec<[f32; 4]> = (0..w * h).map(|i| [((i % w) as f32 / w as f32), 0.3, ((i / w) as f32 / h as f32), 1.0]).collect(); let st = WebSettings::from_params(&json!({"format": "jpeg", "quality": q}), "x").unwrap(); - let o = optimize(&px, w, Rect::new(0, 0, w as i32, h as i32), &st, None, None, 72.0, true).unwrap(); + let o = optimize(&px, w, Rect::new(0, 0, w as i32, h as i32), &st, None, None, None, 72.0, true).unwrap(); for &(x, y) in &[(10usize, 10usize), (w - 10, h / 2), (w / 2, h - 5)] { let i = (y * w + x) * 4; let want = [(x as f32 / w as f32 * 255.0) as i32, 76, (y as f32 / h as f32 * 255.0) as i32]; @@ -714,3 +814,166 @@ fn overlapping_slices_keep_the_later_slice_in_html() { #[path = "color_table_tests.rs"] mod color_table_tests; + +/// A little-endian camera EXIF: IFD0 with Make, Orientation 6, 300 ppi and pointers to an Exif +/// IFD (DateTimeOriginal) and a GPS IFD (GPSLatitudeRef); IFD0 links to an IFD1 thumbnail. +fn camera_exif() -> Vec { + let entry = |v: &mut Vec, tag: u16, ty: u16, count: u32, value: u32| { + v.extend_from_slice(&tag.to_le_bytes()); + v.extend_from_slice(&ty.to_le_bytes()); + v.extend_from_slice(&count.to_le_bytes()); + v.extend_from_slice(&value.to_le_bytes()); + }; + let (ifd0, data0) = (8u32, 8 + 2 + 7 * 12 + 4); + let (make, xres, yres) = (data0, data0 + 10, data0 + 18); + let exif_ifd = data0 + 26; + let date = exif_ifd + 2 + 12 + 4; + let gps_ifd = date + 20; + let ifd1 = gps_ifd + 2 + 12 + 4; + let mut v = b"II*\0".to_vec(); + v.extend_from_slice(&ifd0.to_le_bytes()); + v.extend_from_slice(&7u16.to_le_bytes()); + entry(&mut v, 0x010F, 2, 9, make); + entry(&mut v, 0x0112, 3, 1, 6); + entry(&mut v, 282, 5, 1, xres); + entry(&mut v, 283, 5, 1, yres); + entry(&mut v, 296, 3, 1, 2); + entry(&mut v, 0x8769, 4, 1, exif_ifd); + entry(&mut v, 0x8825, 4, 1, gps_ifd); + v.extend_from_slice(&ifd1.to_le_bytes()); + v.extend_from_slice(b"TestMake\0\0"); + for _ in 0..2 { + v.extend_from_slice(&300u32.to_le_bytes()); + v.extend_from_slice(&1u32.to_le_bytes()); + } + v.extend_from_slice(&1u16.to_le_bytes()); + entry(&mut v, 0x9003, 2, 20, date); + v.extend_from_slice(&0u32.to_le_bytes()); + v.extend_from_slice(b"2024:05:01 10:30:00\0"); + v.extend_from_slice(&1u16.to_le_bytes()); + entry(&mut v, 0x0001, 2, 2, u32::from_le_bytes(*b"N\0\0\0")); + v.extend_from_slice(&0u32.to_le_bytes()); + v.extend_from_slice(&1u16.to_le_bytes()); + entry(&mut v, 0x0103, 3, 1, 6); + v.extend_from_slice(&0u32.to_le_bytes()); + assert_eq!(v.len(), ifd1 as usize + 18); + v +} + +/// The payload (after `Exif\0\0`) of the file's EXIF APP1 segment, read from the markers. +fn exif_app1(bytes: &[u8]) -> Option> { + let mut i = 2; + while i + 4 <= bytes.len() && bytes[i] == 0xFF && bytes[i + 1] != 0xDA { + let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize; + let body = &bytes[i + 4..i + 2 + len]; + if bytes[i + 1] == 0xE1 && body.starts_with(b"Exif\0\0") { + return Some(body[6..].to_vec()); + } + i += 2 + len; + } + None +} + +/// IFD0's entries (tag → inline value) and its link to the next IFD, little-endian only. +fn ifd0(tiff: &[u8]) -> (std::collections::HashMap, u32) { + let u16_at = |o: usize| u16::from_le_bytes([tiff[o], tiff[o + 1]]); + let u32_at = |o: usize| u32::from_le_bytes([tiff[o], tiff[o + 1], tiff[o + 2], tiff[o + 3]]); + assert_eq!(&tiff[..4], b"II*\0"); + let at = u32_at(4) as usize; + let n = u16_at(at) as usize; + let tags = (0..n) + .map(|k| { + let e = at + 2 + k * 12; + let value = if u16_at(e + 2) == 3 { u32::from(u16_at(e + 8)) } else { u32_at(e + 8) }; + (u16_at(e), value) + }) + .collect(); + (tags, u32_at(at + 2 + n * 12)) +} + +fn photo_session(exif: Vec) -> Session { + let mut s = session(8); + s.execute("file.fileInfo", json!({"copyright": "© Example"})).unwrap(); + s.edit("exif", |doc, _| { + doc.metadata.exif = Some(std::sync::Arc::new(exif)); + Ok(()) + }) + .unwrap(); + s +} + +/// #7436: Save for Web's "All" writes the photo's EXIF, as Save a Copy does: upright +/// (Orientation 1), without the source's thumbnail and at the exported resolution. Every other +/// choice, "All Except Camera Info" included, leaves the camera data (and GPS) out. +#[test] +fn save_for_web_all_writes_the_photos_exif() { + let dir = tmp("exif"); + let mut s = photo_session(camera_exif()); + let export = |s: &mut Session, metadata: &str| { + let path = format!("{dir}/{metadata}.jpg"); + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "metadata": metadata, "path": path})).unwrap(); + (std::fs::read(&path).unwrap(), r) + }; + let (all, r) = export(&mut s, "all"); + let exif = exif_app1(&all).expect("an EXIF APP1 segment"); + let camera = photocraft_algo::exif::read(&exif); + assert_eq!(camera.make.as_deref(), Some("TestMake")); + assert_eq!(camera.date_taken.as_deref(), Some("2024:05:01 10:30:00")); + let (tags, next) = ifd0(&exif); + assert_eq!(tags.get(&0x0112), Some(&1), "the exported pixels are already upright"); + assert!(tags.contains_key(&0x8825), "GPS kept"); + assert_eq!(next, 0, "the source's thumbnail is not linked"); + assert_eq!(photocraft_codecs::exif_resolution(&exif), Some((72.0, 72.0)), "the document's resolution, not the source's 300"); + assert!(decode(&format!("{dir}/all.jpg")).meta.xmp.unwrap_or_default().contains("Example")); + for m in ["none", "copyright", "copyrightAndContact", "allExceptCameraInfo"] { + let (bytes, r) = export(&mut s, m); + assert_eq!(exif_app1(&bytes), None, "{m}"); + assert_eq!(r["warnings"], json!([]), "{m}"); + } + assert_eq!(r["warnings"], json!([]), "it fits"); + let xmp = decode(&format!("{dir}/allExceptCameraInfo.jpg")).meta.xmp.unwrap_or_default(); + assert!(xmp.contains("Example"), "all the XMP"); + assert_eq!(WebSettings::from_params(&json!({"metadata": "allExceptCameraInfo"}), "x").unwrap().to_params()["metadata"], "allExceptCameraInfo"); +} + +#[test] +fn quick_export_all_writes_the_photos_exif() { + let dir = tmp("quick_exif"); + let mut s = photo_session(camera_exif()); + let export = |s: &mut Session, metadata: &str| { + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg", "metadata": metadata})).unwrap(); + let path = format!("{dir}/{metadata}.jpg"); + let r = s.execute("file.export.quickExport", json!({"path": path})).unwrap(); + (std::fs::read(&path).unwrap(), r) + }; + let (all, r) = export(&mut s, "all"); + assert_eq!(photocraft_algo::exif::read(&exif_app1(&all).expect("EXIF")).make.as_deref(), Some("TestMake")); + assert_eq!(r["warnings"], json!([])); + assert_eq!(exif_app1(&export(&mut s, "copyright").0), None); + assert_eq!(exif_app1(&export(&mut s, "none").0), None); + s.execute("prefs.reset", json!({"path": "export"})).unwrap(); +} + +/// EXIF too large for its one segment is left out and said so; a truncated one doesn't panic. +#[test] +fn web_exif_that_does_not_fit_is_reported_and_bad_exif_is_harmless() { + let dir = tmp("exif_bad"); + let mut big = camera_exif(); + big.resize(70_000, 0); + let mut s = photo_session(big); + let path = format!("{dir}/big.jpg"); + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "metadata": "all", "path": path})).unwrap(); + assert_eq!(exif_app1(&std::fs::read(&path).unwrap()), None); + assert!(r["warnings"][0].as_str().is_some_and(|w| w.contains("EXIF (70000 bytes)")), "{r}"); + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg", "metadata": "all"})).unwrap(); + let r = s.execute("file.export.quickExport", json!({"path": format!("{dir}/quick.jpg")})).unwrap(); + assert!(r["warnings"][0].as_str().is_some_and(|w| w.contains("EXIF")), "{r}"); + s.execute("prefs.reset", json!({"path": "export"})).unwrap(); + + for cut in [3, 9, 40, 100] { + let mut s = photo_session(camera_exif()[..cut].to_vec()); + let path = format!("{dir}/cut{cut}.jpg"); + s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "metadata": "all", "path": path})).unwrap(); + assert_eq!(decode(&path).dimensions(), (64, 48)); + } +} diff --git a/crates/engine/tests/artboard_export_names.rs b/crates/engine/tests/artboard_export_names.rs new file mode 100644 index 0000000000..f9c46f3eb7 --- /dev/null +++ b/crates/engine/tests/artboard_export_names.rs @@ -0,0 +1,103 @@ +//! #6613: each artboard must have its own output even when names collide on disk. +#![cfg(not(target_arch = "wasm32"))] + +use std::collections::HashSet; +use std::path::Path; + +use photocraft_engine::Session; +use serde_json::json; + +struct Board { + id: u64, + width: u32, + color: [f32; 4], +} + +fn fixture(depth: u32, names: &[&str]) -> (Session, Vec) { + let mut s = Session::new(); + s.execute("file.new", json!({"name": "Board Export", "width": 96, "height": 32, "depth": depth})).unwrap(); + let mut boards = Vec::new(); + for (i, name) in names.iter().enumerate() { + let width = 3 + i as u32; + let color = if i % 2 == 0 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] }; + let result = s.execute("layer.new.artboard", json!({"name": name, "rect": [12 * i, 0, width, 2], "background": "custom", "color": color})).unwrap(); + boards.push(Board { id: result["layer"].as_u64().unwrap(), width, color }); + } + (s, boards) +} + +fn check_export(depth: u32, names: &[&str], prefix: Option<&str>, format: &str, selected: Option<&[usize]>) { + let (mut s, boards) = fixture(depth, names); + let dir = tempfile::tempdir().unwrap(); + let mut params = json!({"dir": dir.path(), "format": format}); + if let Some(prefix) = prefix { + params["prefix"] = json!(prefix); + } + if let Some(selected) = selected { + params["artboards"] = json!(selected.iter().map(|i| boards[*i].id).collect::>()); + } + let expected: Vec<_> = boards.iter().enumerate().rev().filter(|(i, _)| selected.is_none_or(|ids| ids.contains(i))).map(|(_, b)| b).collect(); + let before = photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap(); + let revision = s.active().unwrap().revision; + let history = s.active().unwrap().history.past_len(); + let result = s.execute("file.export.artboardsToFiles", params).unwrap(); + let files: Vec<_> = result["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + assert_eq!(files.len(), expected.len()); + // Also require uniqueness on filesystems that compare names without letter case. + assert_eq!(files.iter().map(|f| f.to_lowercase()).collect::>().len(), files.len(), "export paths collide: {files:?}"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), files.len(), "one physical output per returned path"); + for (file, board) in files.iter().zip(expected) { + assert_eq!(Path::new(file).parent(), Some(dir.path())); + let bytes = std::fs::read(file).unwrap(); + let doc = photocraft_io::import(file, &bytes).unwrap().document; + assert_eq!((doc.size.width, doc.size.height), (board.width, 2), "wrong artboard in {file}"); + let px = photocraft_compose::flatten(&doc).px[0]; + for (actual, expected) in px.iter().zip(board.color) { + assert!((actual - expected).abs() < 1e-3, "wrong pixels in {file}: {px:?}"); + } + } + let after = s.active().unwrap(); + assert_eq!(photocraft_format::save_to_bytes(&after.doc, &Default::default()).unwrap(), before); + assert_eq!(after.revision, revision, "export must not edit the source document"); + assert_eq!(after.history.past_len(), history); +} + +#[test] +fn duplicate_names_preserve_each_board_at_every_depth_and_prefix() { + for depth in [8, 16, 32] { + for prefix in [None, Some(""), Some("Launch/Run")] { + check_export(depth, &["Artboard 1", "Artboard 1"], prefix, "png", None); + } + } +} + +#[test] +fn sanitized_and_empty_names_preserve_each_tiff() { + check_export(16, &["Hero/1", "Hero:1", "Hero?1", ".", " ", "layer"], Some(""), "tiff", None); +} + +#[test] +fn case_only_and_index_like_names_remain_distinct() { + check_export(8, &["Logo", "logo", "Logo_0001", "0000_Logo", "Лого", "лого"], Some("site"), "png", None); +} + +#[test] +fn selected_duplicate_names_keep_their_psd_contents_in_stack_order() { + check_export(16, &["Same", "Skip", "Same"], Some("chosen"), "psd", Some(&[0, 2])); +} + +#[test] +fn distinct_names_keep_their_corresponding_contents() { + check_export(8, &["Red", "Blue"], None, "png", None); +} + +#[test] +fn invalid_export_params_fail_before_creating_files() { + let (mut s, _) = fixture(8, &["One", "Two"]); + let dir = tempfile::tempdir().unwrap(); + for params in [json!({"dir": 3}), json!({"dir": dir.path(), "artboards": []}), json!({"dir": dir.path(), "artboards": [u64::MAX]})] { + assert!(s.execute("file.export.artboardsToFiles", params).is_err()); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); + } + assert!(Session::new().execute("file.export.artboardsToFiles", json!({"dir": dir.path()})).is_err()); +} diff --git a/crates/engine/tests/camera_raw_exposure_clamp.rs b/crates/engine/tests/camera_raw_exposure_clamp.rs new file mode 100644 index 0000000000..ee624f7e28 --- /dev/null +++ b/crates/engine/tests/camera_raw_exposure_clamp.rs @@ -0,0 +1,40 @@ +//! `filter.cameraRaw` must clamp `exposure` to its documented -5..5 range. Before the fix, +//! `raw_params` passed it through, so an exposure of 128 or more overflowed `2^exposure` to +//! infinity and a 32-bit layer was left with non-finite samples. + +use photocraft_engine::Session; +use serde_json::json; + +#[test] +fn camera_raw_clamps_exposure() { + let hi = photocraft_engine::lens_cmds::raw_params("filter.cameraRaw", &json!({"exposure": 255.0})).expect("params parse"); + assert_eq!(hi.exposure, 5.0, "exposure 255 must clamp to 5"); + let lo = photocraft_engine::lens_cmds::raw_params("filter.cameraRaw", &json!({"exposure": -255.0})).expect("params parse"); + assert_eq!(lo.exposure, -5.0, "exposure -255 must clamp to -5"); + let mid = photocraft_engine::lens_cmds::raw_params("filter.cameraRaw", &json!({"exposure": 1.5})).expect("params parse"); + assert_eq!(mid.exposure, 1.5, "in-range exposure stays untouched"); +} + +#[test] +fn camera_raw_out_of_range_exposure_keeps_32_bit_layer_finite() { + for exposure in [255.0, -255.0] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("filter.cameraRaw", json!({"exposure": exposure})).unwrap(); + let st = s.active().unwrap(); + let layer = st.active_layer.and_then(|id| st.doc.layer(id)).unwrap(); + let surf = layer.surface().unwrap(); + let mut bad = Vec::new(); + for y in 0..8 { + for x in 0..8 { + let px = surf.rgba(x, y); + if px.iter().any(|v| !v.is_finite()) { + bad.push(px); + } + } + } + assert!(bad.is_empty(), "exposure {exposure}: {} non-finite pixels, e.g. {:?}", bad.len(), bad.first()); + } +} diff --git a/crates/engine/tests/duplicate_slices.rs b/crates/engine/tests/duplicate_slices.rs new file mode 100644 index 0000000000..5f5d21c621 --- /dev/null +++ b/crates/engine/tests/duplicate_slices.rs @@ -0,0 +1,35 @@ +use photocraft_doc::SliceOrigin; +use photocraft_engine::Session; +use serde_json::{Value, json}; + +fn sliced() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.execute("layer.new.layer", json!({"name": "logo"})).unwrap(); + s.execute("paint.stroke", json!({"points": [[5, 10], [20, 10]], "size": 8, "hardness": 1.0, "color": "#ff0000"})).unwrap(); + s.execute("layer.newLayerBasedSlice", json!({"url": "https://example.com", "alt": "logo"})).unwrap(); + s +} + +fn layer_slice(s: &mut Session) -> Option { + let list = s.execute("slice.list", json!({})).unwrap(); + list["slices"].as_array().unwrap().iter().find(|sl| sl["origin"] == "layer").cloned() +} + +#[test] +fn duplicating_a_document_keeps_its_layer_based_slices() { + for cmd in ["image.duplicate", "history.newDocument"] { + let mut s = sliced(); + s.execute(cmd, json!({})).unwrap(); + let st = s.active().unwrap(); + let logo = st.doc.walk().into_iter().find(|(_, _, l)| l.name == "logo").unwrap().2.id; + let slices: Vec<_> = st.doc.slices.list.iter().filter(|sl| sl.origin == SliceOrigin::Layer).collect(); + assert_eq!(slices.len(), 1, "{cmd}"); + assert_eq!(slices[0].layer, Some(logo), "{cmd}"); + assert_eq!((slices[0].url.as_str(), slices[0].alt.as_str()), ("https://example.com", "logo"), "{cmd}"); + let before = layer_slice(&mut s).unwrap()["rect"].clone(); + s.execute("layer.translate", json!({"dx": 5, "dy": 3})).unwrap(); + let after = layer_slice(&mut s).unwrap_or_else(|| panic!("{cmd} lost the slice after a move"))["rect"].clone(); + assert_ne!(before, after, "{cmd}: the slice no longer follows its layer"); + } +} diff --git a/crates/engine/tests/finite_command_params.rs b/crates/engine/tests/finite_command_params.rs new file mode 100644 index 0000000000..0350d74493 --- /dev/null +++ b/crates/engine/tests/finite_command_params.rs @@ -0,0 +1,154 @@ +//! #6424: rejecting an overflowing f32 parameter must leave a saveable document and history. +use photocraft_engine::{EngineError, Session}; +use serde_json::{Value, json}; + +fn fresh(mode: &str, depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 12, "mode": mode, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn saved(s: &Session) -> Vec { + photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap() +} + +fn rejected(cases: Vec<(&str, Value)>) { + let mut failures = Vec::new(); + for (id, p) in cases { + let mut s = fresh("rgb", 8); + let before = saved(&s); + let undo = s.active().unwrap().history.undo_label().map(str::to_owned); + let result = s.execute(id, p.clone()); + let save = photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()); + if !matches!(result, Err(EngineError::BadParams { .. })) { + failures.push(format!("{id} {p}: result={result:?}, save error={:?}", save.as_ref().err())); + continue; + } + assert_eq!(save.unwrap(), before, "rejected {id} must not change the document"); + assert_eq!(s.active().unwrap().history.undo_label(), undo.as_deref(), "rejected {id} must not add history"); + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +#[test] +fn overflowing_layer_styles_are_rejected_before_mutation() { + let mut cases = Vec::new(); + for value in [1e39, -1e39] { + for (kind, key) in [ + ("dropShadow", "angle"), + ("innerShadow", "angle"), + ("outerGlow", "size"), + ("innerGlow", "size"), + ("stroke", "size"), + ("satin", "angle"), + ("bevelEmboss", "depth"), + ("gradientOverlay", "angle"), + ("patternOverlay", "phaseX"), + ] { + let id = match kind { + "dropShadow" => "layer.layerStyle.dropShadow", + "innerShadow" => "layer.layerStyle.innerShadow", + "outerGlow" => "layer.layerStyle.outerGlow", + "innerGlow" => "layer.layerStyle.innerGlow", + "stroke" => "layer.layerStyle.stroke", + "satin" => "layer.layerStyle.satin", + "bevelEmboss" => "layer.layerStyle.bevelEmboss", + "gradientOverlay" => "layer.layerStyle.gradientOverlay", + _ => "layer.layerStyle.patternOverlay", + }; + let params = json!({key: value}); + cases.push((id, params.clone())); + cases.push(("layer.layerStyle.replace", json!({"effects": [{"kind": kind, "params": params}]}))); + } + cases.push(("layer.layerStyle.colorOverlay", json!({"color": [value, 0, 0]}))); + } + rejected(cases); +} + +#[test] +fn overflowing_document_colors_are_rejected_before_mutation() { + let mut cases = Vec::new(); + for id in ["layer.newFillLayer.solidColor", "channel.new", "channel.newSpot", "layer.new.artboard", "count.newGroup"] { + for value in [1e39, -1e39] { + for component in 0..4 { + let mut color = [0.5; 4]; + color[component] = value; + cases.push((id, json!({"color": color}))); + } + } + } + rejected(cases); +} + +#[test] +fn overflowing_type_positions_and_colors_are_rejected_before_mutation() { + rejected(vec![ + ("type.create", json!({"text": "hello", "x": 1e39})), + ("type.create", json!({"text": "hello", "y": -1e39})), + ("type.create", json!({"text": "hello", "color": [1e39, 0, 0]})), + ]); +} + +#[test] +fn valid_color_and_style_edits_still_save_and_undo_at_each_depth() { + for mode in ["rgb", "gray", "cmyk", "lab"] { + for depth in [8, 16, 32] { + let mut s = fresh(mode, depth); + let before = saved(&s); + s.execute("layer.layerStyle.dropShadow", json!({"angle": -45, "color": [0.1, 0.3, 0.8]})).unwrap(); + let edited = saved(&s); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(saved(&s), edited); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#4080c0"})).unwrap(); + let bytes = saved(&s); + photocraft_format::load_from_bytes(&bytes).unwrap(); + } + } +} + +#[test] +fn effect_snapshots_cannot_bypass_numeric_validation() { + let mut fx = serde_json::to_value(photocraft_engine::layer_style::effect_from_params("dropShadow", &json!({})).unwrap()).unwrap(); + fx["DropShadow"]["angle"] = json!(1e39); + rejected(vec![( + "layer.layerStyle.replace", + json!({"effects": [ + {"kind": "colorOverlay", "params": {"color": "#00ff00"}}, + {"kind": "dropShadow", "fx": fx, "params": {}} + ]}), + )]); +} + +#[test] +fn direct_effect_helpers_do_not_introduce_infinity() { + let original = photocraft_engine::layer_style::effect_from_params("dropShadow", &json!({})).unwrap(); + for p in [json!({"angle": 1e39}), json!({"color": [0, -1e39, 0]})] { + assert!(photocraft_engine::layer_style::effect_from_params("dropShadow", &p).is_none()); + let mut edited = original.clone(); + photocraft_engine::layer_style::overlay_effect(&mut edited, &p); + assert_eq!(edited, original); + } +} + +#[test] +fn bad_background_color_does_not_partially_change_tool_colors() { + let mut s = fresh("rgb", 32); + let before = (s.tools.foreground, s.tools.background); + let result = s.execute("tools.setColors", json!({"foreground": "#40a0c0", "background": [0, 1e39, 0]})); + assert!(matches!(result, Err(EngineError::BadParams { .. }))); + assert_eq!((s.tools.foreground, s.tools.background), before); +} + +#[test] +fn finite_hdr_colors_are_preserved_without_unit_clamping() { + let mut s = fresh("rgb", 32); + let id = s.execute("layer.newFillLayer.solidColor", json!({"color": [4.0, -0.5, 0.25]})).unwrap()["layer"].as_u64().unwrap(); + let bytes = saved(&s); + let reopened = photocraft_format::load_from_bytes(&bytes).unwrap(); + let layer = reopened.layer(photocraft_doc::LayerId(id)).unwrap(); + let photocraft_doc::LayerContent::Fill(photocraft_doc::Fill::Solid(c)) = &layer.content else { panic!("expected a solid fill") }; + assert_eq!(c.to_rgb(), [4.0, -0.5, 0.25]); +} diff --git a/crates/engine/tests/gradient_overlay_strokes.rs b/crates/engine/tests/gradient_overlay_strokes.rs new file mode 100644 index 0000000000..e233f8984d --- /dev/null +++ b/crates/engine/tests/gradient_overlay_strokes.rs @@ -0,0 +1,89 @@ +//! A Gradient Overlay spans one gradient over the layer's current bounds, so a stroke that grows +//! the layer re-lays the gradient out over all of it (#4053). The damage a stroke reports must +//! cover that, or a canvas that redraws only the damage keeps the old gradient around the earlier +//! strokes: one gradient per stroke instead of one over the whole layer. + +use photocraft_engine::Session; +use serde_json::json; + +/// What a canvas that redraws only each edit's damage shows: the cold render before the edit, +/// with the edit's damage (grown by the effects' reach, as the canvas grows it) rendered again. +fn redraw_damage(shown: &mut photocraft_compose::Buffer, s: &Session) { + let st = s.active().unwrap(); + let reach = st.doc.layers.iter().filter(|l| photocraft_compose::effects::has_effects(l)).map(photocraft_compose::effects::margin).max().unwrap_or(0); + let damage = st.last_damage.expect("a stroke reports bounded damage").inflate(reach).intersect(&st.doc.bounds()); + let (w, h) = (st.doc.size.width, st.doc.size.height); + let patch = photocraft_compose::render_reduced_damage(&st.doc, w, h, damage); + for y in patch.rect.y0..patch.rect.y1 { + for x in patch.rect.x0..patch.rect.x1 { + let i = (y * w as i32 + x) as usize; + shown.px[i] = patch.get(x, y); + } + } +} + +fn session(effect: &str, params: serde_json::Value) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 160, "height": 80, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute(effect, params).unwrap(); + s +} + +const GREY: &str = "#808080"; + +/// Each stroke redrawn over the last cold render equals a cold render after it. +fn strokes_redraw_like_a_cold_render(mut s: Session, strokes: &[serde_json::Value]) { + s.execute("paint.stroke", json!({"points": [[20, 20], [40, 30]], "size": 12, "hardness": 1.0, "color": GREY})).unwrap(); + for (i, p) in strokes.iter().enumerate() { + let st = s.active().unwrap(); + let mut shown = photocraft_compose::render(&st.doc, st.doc.bounds()); + s.execute("paint.stroke", p.clone()).unwrap(); + redraw_damage(&mut shown, &s); + let st = s.active().unwrap(); + let cold = photocraft_compose::render(&st.doc, st.doc.bounds()); + let worst = shown.px.iter().zip(&cold.px).map(|(a, b)| (0..4).map(|c| (a[c] - b[c]).abs()).fold(0.0f32, f32::max)).fold(0.0f32, f32::max); + assert!(worst < 1e-6, "after stroke {i} the redrawn canvas differs from a cold render by {worst}"); + } +} + +#[test] +fn a_gradient_overlay_is_laid_out_again_after_each_stroke() { + let s = session("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})); + strokes_redraw_like_a_cold_render( + s, + &[ + // Far from the first: the layer grows to the right and down. + json!({"points": [[120, 50], [140, 64]], "size": 12, "hardness": 1.0, "color": GREY}), + // Up and to the left of both. + json!({"points": [[6, 6], [10, 8]], "size": 6, "hardness": 1.0, "color": GREY}), + // Erasing the far stroke shrinks the layer again. + json!({"points": [[110, 40], [150, 74]], "size": 40, "hardness": 1.0, "erase": true}), + ], + ); +} + +#[test] +fn a_stroke_inside_the_layer_keeps_its_own_damage() { + let mut s = session("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})); + s.execute("paint.stroke", json!({"points": [[10, 10], [150, 70]], "size": 12, "hardness": 1.0, "color": GREY})).unwrap(); + // Within the layer's bounds: the gradient's frame stays, so only the stroke repaints. + let r = s.execute("paint.stroke", json!({"points": [[60, 40], [70, 40]], "size": 6, "hardness": 1.0, "color": GREY})).unwrap(); + let d = &r["damage"]; + let reported = photocraft_geom::Rect::new( + d[0].as_i64().unwrap() as i32, + d[1].as_i64().unwrap() as i32, + (d[0].as_i64().unwrap() + d[2].as_i64().unwrap()) as i32, + (d[1].as_i64().unwrap() + d[3].as_i64().unwrap()) as i32, + ); + assert_eq!(s.active().unwrap().last_damage, Some(reported)); +} + +#[test] +fn effects_not_laid_out_over_the_layer_keep_the_stroke_damage() { + let mut s = session("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"})); + s.execute("paint.stroke", json!({"points": [[20, 20], [40, 30]], "size": 12, "hardness": 1.0, "color": GREY})).unwrap(); + s.execute("paint.stroke", json!({"points": [[120, 50], [140, 64]], "size": 12, "hardness": 1.0, "color": GREY})).unwrap(); + let d = s.active().unwrap().last_damage.unwrap(); + assert!(d.x0 >= 100, "a Color Overlay repaints only the stroke: {d:?}"); +} diff --git a/crates/engine/tests/missing_layer_error.rs b/crates/engine/tests/missing_layer_error.rs new file mode 100644 index 0000000000..5764f5d85c --- /dev/null +++ b/crates/engine/tests/missing_layer_error.rs @@ -0,0 +1,68 @@ +//! A `"layer"` param that names no layer says which layers there are (#5058): ids are not +//! positions (a freshly opened PNG's Background is layer 2), and an agent should be able to +//! recover from the error alone. A name matches regardless of case as a fallback. + +use photocraft_engine::{EngineError, Session}; +use serde_json::json; + +fn session() -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 6})).unwrap(); + let bg = s.active().unwrap().active_layer.unwrap().0; + (s, bg) +} + +fn unused_id(s: &Session) -> u64 { + let doc = &s.active().unwrap().doc; + (1..).find(|id| doc.layer(photocraft_doc::LayerId(*id)).is_none()).unwrap() +} + +#[test] +fn an_unknown_layer_id_lists_the_documents_layers() { + let (mut s, bg) = session(); + let layer = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + let missing = unused_id(&s); + let err = s.execute("layer.setProps", json!({"layer": missing, "visible": false})).unwrap_err(); + assert!(matches!(err, EngineError::UnknownLayer { id, .. } if id.0 == missing), "{err}"); + let err = err.to_string(); + assert!(err.contains(&format!("no such layer {missing};")), "{err}"); + assert!(err.contains(&format!("{layer} \"Layer 1\", {bg} \"Background\"")), "top-down ids and names: {err}"); +} + +#[test] +fn an_unknown_layer_name_lists_the_documents_layers() { + let (mut s, bg) = session(); + let err = s.execute("layer.setProps", json!({"layer": "Nope", "visible": false})).unwrap_err().to_string(); + assert!(err.contains("no layer named \"Nope\""), "{err}"); + assert!(err.contains(&format!("{bg} \"Background\"")), "{err}"); +} + +#[test] +fn a_layer_name_matches_regardless_of_case() { + let (mut s, bg) = session(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.setProps", json!({"layer": "background", "name": "Base"})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer(photocraft_doc::LayerId(bg)).unwrap().name, "Base"); +} + +#[test] +fn an_exact_name_wins_over_a_case_insensitive_one() { + let (mut s, _) = session(); + let lower = s.execute("layer.new.layer", json!({"name": "shadow"})).unwrap()["layer"].as_u64().unwrap(); + let upper = s.execute("layer.new.layer", json!({"name": "Shadow"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": "shadow", "visible": false})).unwrap(); + let doc = &s.active().unwrap().doc; + assert!(!doc.layer(photocraft_doc::LayerId(lower)).unwrap().visible); + assert!(doc.layer(photocraft_doc::LayerId(upper)).unwrap().visible); +} + +#[test] +fn a_long_layer_name_is_shortened_in_the_listing() { + let (mut s, _) = session(); + let long = "é".repeat(500); + let layer = s.execute("layer.new.layer", json!({"name": long})).unwrap()["layer"].as_u64().unwrap(); + let err = s.execute("layer.setProps", json!({"layer": "Nope", "visible": false})).unwrap_err().to_string(); + let shown = format!("{layer} \"{}…\"", "é".repeat(64)); + assert!(err.contains(&shown), "the name is cut at 64 characters: {err}"); + assert!(err.chars().count() < 300, "{err}"); +} diff --git a/crates/engine/tests/nonfinite_style.rs b/crates/engine/tests/nonfinite_style.rs new file mode 100644 index 0000000000..994f3dbe6e --- /dev/null +++ b/crates/engine/tests/nonfinite_style.rs @@ -0,0 +1,56 @@ +//! Character style numbers that overflow `f32` are refused, so the document stays saveable. + +use photocraft_engine::{EngineError, Session}; +use serde_json::json; + +fn fixture() -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + let id = s.execute("type.create", json!({"text": "Hi", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + (s, id) +} + +#[test] +fn out_of_range_style_numbers_are_refused() { + for key in ["leading", "baselineShift", "horizontalScale", "verticalScale"] { + let (mut s, id) = fixture(); + let past = s.active().unwrap().history.past_len(); + for value in [1e39, -1e39, 1e12] { + let r = s.execute("type.setStyle", json!({"layer": id, key: value})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{key}={value}: {r:?}"); + } + assert_eq!(s.active().unwrap().history.past_len(), past, "{key}: no history step"); + let r = s.execute("type.create", json!({"text": "x", key: 1e39})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "create {key}: {r:?}"); + let dir = std::env::temp_dir().join(format!("pc_nonfinite_style_{key}_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("t.pcraft"); + let saved = s.execute("file.saveACopy", json!({"path": path.to_string_lossy()})); + std::fs::remove_dir_all(&dir).ok(); + saved.unwrap_or_else(|e| panic!("{key}: save failed: {e:?}")); + } +} + +#[test] +fn in_range_style_numbers_still_apply_and_save() { + let (mut s, id) = fixture(); + s.execute("type.setStyle", json!({"layer": id, "leading": 30, "baselineShift": -4, "horizontalScale": 120, "verticalScale": 80})).unwrap(); + s.execute("type.setStyle", json!({"layer": id, "leading": "auto"})).unwrap(); + let dir = std::env::temp_dir().join(format!("pc_nonfinite_style_ok_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("t.pcraft"); + let saved = s.execute("file.saveACopy", json!({"path": path.to_string_lossy()})); + std::fs::remove_dir_all(&dir).ok(); + saved.unwrap_or_else(|e| panic!("save failed: {e:?}")); +} + +#[test] +fn non_numeric_leading_is_refused() { + let (mut s, id) = fixture(); + let past = s.active().unwrap().history.past_len(); + for value in [json!("18pt"), json!("Auto "), json!(true), json!([12])] { + let r = s.execute("type.setStyle", json!({"layer": id, "leading": value})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "leading={value}: {r:?}"); + } + assert_eq!(s.active().unwrap().history.past_len(), past, "no history step"); +} diff --git a/crates/engine/tests/transform_budget_unclamped.rs b/crates/engine/tests/transform_budget_unclamped.rs new file mode 100644 index 0000000000..c603bee7b5 --- /dev/null +++ b/crates/engine/tests/transform_budget_unclamped.rs @@ -0,0 +1,49 @@ +//! #6430: integration tests use the production pixel budget, not the unit tests' reduced one. +use photocraft_engine::Session; +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +fn painted() -> Session { + let mut session = Session::new(); + session.execute("file.new", json!({"width": 24, "height": 16})).unwrap(); + session.execute("layer.new.layer", json!({})).unwrap(); + session + .edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 2, 11, 10), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + session +} + +fn assert_refused_without_changes(session: &mut Session, command: &str, params: Value) { + let state = session.active().unwrap(); + let (document, revision, history) = (state.doc.clone(), state.revision, state.history.past_len()); + let error = session.execute(command, params).unwrap_err().to_string(); + assert!(error.contains("limit"), "{error}"); + let state = session.active().unwrap(); + assert!(state.doc == document, "refusal changed the document"); + assert_eq!((state.revision, state.history.past_len()), (revision, history)); +} + +#[test] +fn extreme_layer_scales_are_refused_before_a_clipped_strip_is_warped() { + let mut session = painted(); + session.execute("filter.render.clouds", json!({})).unwrap(); + for scale in [1e9, 1e30, 1e308, -1e308] { + for axis in ["scaleX", "scaleY"] { + assert_refused_without_changes(&mut session, "edit.transform", json!({(axis): scale})); + } + } +} + +#[test] +fn extreme_selection_scales_are_refused_without_losing_the_selection() { + let mut session = painted(); + session.execute("select.rect", json!({"x": 10, "y": 2, "width": 1, "height": 8})).unwrap(); + for scale in [1e30, 1e308] { + for axis in ["scaleX", "scaleY"] { + assert_refused_without_changes(&mut session, "select.transformSelection", json!({(axis): scale})); + } + } +} diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 113d9ba026..4267746633 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -16,7 +16,7 @@ photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-codecs = { workspace = true } serde = { workspace = true } -serde_json = { workspace = true, features = ["unbounded_depth"] } +serde_json = { workspace = true, features = ["unbounded_depth", "float_roundtrip"] } thiserror = { workspace = true } flate2 = { workspace = true } # Same IEEE CRC-32 the ZIP container needs; already in Cargo.lock through flate2. @@ -34,5 +34,16 @@ rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } [target.'cfg(target_vendor = "apple")'.dependencies] libc = "0.2" +# Replacing a file keeps its ACL (#7073). `fcopyfile(COPYFILE_ACL)` is an `unsafe fn` and +# `fclonefileat(CLONE_ACL)` is APFS-only; exacl is a safe wrapper over acl_get_file/acl_set_file. +[target.'cfg(target_os = "macos")'.dependencies] +exacl = "0.13" + +# `ReplaceFileW` is how Windows replaces a file without dropping its DACL, named streams +# (Zone.Identifier, the Mark of the Web) and creation time (#7094, #7096). winsafe's `kernel` +# feature is a dependency-free safe wrapper; the workspace forbids writing the FFI call here. +[target.'cfg(windows)'.dependencies] +winsafe = { version = "0.0.29", features = ["kernel"] } + [dev-dependencies] proptest = { workspace = true } diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index bf39fe2761..3a4aeca6c0 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -13,6 +13,10 @@ //! if it does anyway, the save fails with a clear error. It never falls back to writing the //! destination in place. //! - **Unwritable folder:** the save fails with a clear error instead of writing in place. +//! - **Read-only file:** the save is refused before anything is written (#6600). A rename only +//! needs the folder to be writable, so without this check Linux and macOS would silently replace +//! a `chmod 444` file while Windows refuses; now every platform refuses, as Photoshop does, and +//! the user saves a copy with Save As. //! - **Network shares (macOS):** `sync_all` asks for a full flush to the disk's platters //! (`F_FULLFSYNC`), which SMB shares and some virtual file systems refuse while a plain `fsync` //! works. [`sync_file`] falls back to the plain one there (#1336). @@ -21,8 +25,15 @@ //! this module is never reached there; on `wasm32` every call returns the `std` "unsupported" //! error. //! +//! Replacing a file also carries its metadata across — permission bits, extended attributes, +//! the "downloaded from the internet" mark and the access-control list — so that saving a +//! document does not quietly undo a security decision someone made about the file. That part is +//! [`meta`], and it is best effort: it never fails a save and never touches the bytes. +//! //! [`atomic_write_with`] takes an [`AtomicFs`] so tests can inject failures at each step. +pub mod meta; + use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -30,6 +41,12 @@ use std::sync::atomic::{AtomicU64, Ordering}; /// The file-system steps [`atomic_write_with`] performs. [`RealFs`] is the real thing; tests /// wrap it to inject failures. pub trait AtomicFs { + /// Whether the existing file at `path` is marked read-only (a missing file is not). A + /// read-only destination is never replaced (#6600). By default nothing is read-only. + fn is_readonly(&self, path: &Path) -> bool { + let _ = path; + false + } /// Create `tmp` (it must not exist), write all of `bytes` and flush it ([`sync_file`]). fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()>; /// [`write_new`](Self::write_new), reporting the fraction of `bytes` written so far to @@ -44,9 +61,16 @@ pub trait AtomicFs { fn remove(&self, path: &Path) -> io::Result<()>; /// Flush a directory entry change (Unix); a no-op elsewhere. fn sync_dir(&self, dir: &Path) -> io::Result<()>; - /// Copy the destination's permissions onto the temporary file, so replacing a file keeps its - /// mode. Best effort. - fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()>; + /// Copy the metadata a replacement should keep — mode, extended attributes, ACL — from the + /// file about to be replaced onto the temporary file. Best effort; see [`meta`]. + fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()>; + /// Replace the **existing** file `to` with `from`. Everywhere but Windows this is + /// [`rename`](Self::rename); on Windows it keeps the destination's DACL, named streams and + /// creation time ([`meta::replace_existing`]). The default is `rename`, which is what the + /// failure-injecting test file systems want. + fn replace_existing(&self, from: &Path, to: &Path) -> io::Result<()> { + self.rename(from, to) + } } /// The real file system. @@ -87,9 +111,14 @@ impl AtomicFs for RealFs { Ok(()) } } - fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()> { - let perms = std::fs::metadata(from)?.permissions(); - std::fs::set_permissions(to, perms) + fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()> { + meta::copy_metadata(from, to) + } + fn replace_existing(&self, from: &Path, to: &Path) -> io::Result<()> { + meta::replace_existing(from, to) + } + fn is_readonly(&self, path: &Path) -> bool { + std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().readonly()) } } @@ -162,13 +191,16 @@ pub fn atomic_write_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, byt /// [`atomic_write_with`] reporting write progress (see [`atomic_write_progress`]). pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> { - let target = resolve_symlink(path); + let target = resolve_symlink(path).map_err(|e| context(e, format!("cannot save {}", path.display())))?; let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; let dir = match target.parent() { Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), _ => PathBuf::from("."), }; std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; + if fs.is_readonly(&target) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("cannot save {}: the file is read-only; {UNCHANGED}", path.display()))); + } // Create a fresh temporary file next to the target (same directory, so the rename never // crosses a device). The name is unique per process and call; retry a few on collisions. @@ -190,12 +222,19 @@ pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: & } let tmp = tmp.ok_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display())))?; - // Keep the existing file's mode (e.g. 0600) instead of the process default. - if target.exists() { - let _ = fs.copy_permissions(&target, &tmp); + // Keep what the file being replaced carried: its mode (e.g. 0600) instead of the process + // default, its extended attributes, and its ACL. Best effort, and before the swap, so the + // file the user ends up with never passes through a more permissive state. + let replacing = target.exists(); + if replacing { + let _ = fs.copy_metadata(&target, &tmp); } - if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) { + // Replacing an existing file goes through `replace_existing`, which on Windows is the one + // call that can keep the destination's DACL and named streams; creating a new one is a + // plain rename, with nothing to preserve. + let swap = || if replacing { fs.replace_existing(&tmp, &target) } else { fs.rename(&tmp, &target) }; + if let Err(e) = retry_rename(retry, swap) { let _ = fs.remove(&tmp); return Err(rename_error(e, path)); } @@ -229,12 +268,37 @@ fn sleep_ms(ms: u64) { #[cfg(target_arch = "wasm32")] fn sleep_ms(_ms: u64) {} +/// How deep a symlink chain we follow before giving up, like the OS limit. +const MAX_LINK_DEPTH: u32 = 40; + /// Write through a symlink to the file it points at, instead of replacing the link. -fn resolve_symlink(path: &Path) -> PathBuf { - match std::fs::symlink_metadata(path) { - Ok(m) if m.file_type().is_symlink() => std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()), - _ => path.to_path_buf(), +/// +/// A dangling link (its target, or a folder on the way to it, doesn't exist yet) resolves to its +/// target too, so saving through one creates the target instead of silently turning the link +/// into a regular file (#6605). A chain that never ends is an error, never a link replacement. +fn resolve_symlink(path: &Path) -> io::Result { + if !std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) { + return Ok(path.to_path_buf()); } + // A resolvable chain: canonicalize follows every link and relative target in one go. + if let Ok(real) = std::fs::canonicalize(path) { + return Ok(real); + } + // Dangling chain: walk the links lexically; the final target may not exist yet. + let mut current = path.to_path_buf(); + for _ in 0..MAX_LINK_DEPTH { + let Ok(link) = std::fs::read_link(¤t) else { + return Ok(current); // not (or no longer) a link: the chain ends here + }; + let base = current.parent().unwrap_or(Path::new(".")).to_path_buf(); + // `..` stays in the path for the OS to resolve: folding it by text is wrong when a folder + // on the way is itself a symlink. + current = if link.is_absolute() { link } else { base.join(link) }; + if !std::fs::symlink_metadata(¤t).is_ok_and(|m| m.file_type().is_symlink()) { + return Ok(current); + } + } + Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{}: too many levels of symbolic links", path.display()))) } /// A unique hidden temporary file name to write beside `file` before renaming over it. diff --git a/crates/format/src/atomic/meta.rs b/crates/format/src/atomic/meta.rs new file mode 100644 index 0000000000..10008faa9f --- /dev/null +++ b/crates/format/src/atomic/meta.rs @@ -0,0 +1,280 @@ +//! What a replacement keeps from the file it replaces. +//! +//! Saving writes a new file and renames it over the old one, so the user gets a file with the +//! right bytes and none of the old file's history: everything the operating system and other +//! programs had attached to the file that was just unlinked is gone. Some of it is a security +//! decision — *this came from the internet*, *only these people may read it* — so a save that +//! drops it quietly weakens the user's protections (#6603, #7073, #7094, #7095, #7096). +//! +//! | | macOS | Linux | Windows | +//! |---|---|---|---| +//! | permission bits | [`copy_metadata`] | [`copy_metadata`] | [`copy_metadata`] (read-only flag) | +//! | extended attributes (Finder tags, `user.*`) | `copy_xattrs` | `copy_xattrs` | — | +//! | "downloaded from the internet" | `com.apple.quarantine`, an xattr | — | `Zone.Identifier`, a named stream kept by [`replace_existing`] | +//! | access-control list | `copy_acl` (`exacl`) | not carried over (see below) | DACL, kept by [`replace_existing`] | +//! | creation time | not carried over (#6603) | — | kept by [`replace_existing`] | +//! +//! Everything here except [`replace_existing`] is **best effort and never touches the file's +//! bytes**: a save that cannot carry a piece of metadata across is still a save, because a +//! document the user can open matters more than a Finder tag. [`replace_existing`] *is* the +//! replacement step, so it holds the atomicity guarantee instead: it never leaves the +//! destination missing, and it falls back to a plain rename rather than fail a save. +//! +//! Not carried over, and why: Linux POSIX ACLs live in `system.posix_acl_access`, which +//! `listxattr` does not report, so copying the listed attributes misses them; they would need +//! their own step. macOS creation time needs `setattrlist`, which has no safe wrapper here. + +use std::io; +use std::path::Path; + +#[cfg(unix)] +use std::os::fd::BorrowedFd; + +/// Largest attribute-name list [`copy_xattrs`] will read. Names are short; a file with a +/// megabyte of them is not something a save should spend memory on. +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +const MAX_XATTR_NAMES: usize = 1 << 20; + +/// Largest single attribute value [`copy_xattrs`] will carry over. Finder tags and `user.*` +/// attributes are tens of bytes; a resource fork can be large, and past this it is not worth +/// holding a copy of it in memory during a save. +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +const MAX_XATTR_VALUE: usize = 16 << 20; + +/// First read size for an attribute list or value; grown on `ERANGE`. +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +const XATTR_CHUNK: usize = 4 << 10; + +/// Copy, best effort, everything [`crate::atomic::atomic_write`] should carry from the file it +/// is about to replace (`from`) onto the temporary file that will replace it (`to`). +/// +/// Errors are the caller's to ignore: each piece is attempted on its own, and the first failure +/// is returned only so a caller that wants to log one can. +pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> { + // The permission bits go on last. Writing an attribute needs the destination open for + // writing, and replacing a read-only (0444) file would copy that mode onto the temporary + // file and then be unable to touch it again. + #[cfg(unix)] + let attributes = copy_xattrs_at(from, to); + #[cfg(not(unix))] + let attributes = Ok(()); + + #[cfg(target_os = "macos")] + let acl = copy_acl(from, to); + #[cfg(not(target_os = "macos"))] + let acl = Ok(()); + + // A save over a 0600 file must not widen it to whatever the process default is. + let permissions = std::fs::metadata(from).and_then(|m| std::fs::set_permissions(to, m.permissions())); + + attributes.and(acl).and(permissions) +} + +/// [`copy_metadata`]'s extended-attribute step, by path: open both files and hand the +/// descriptors to [`copy_xattrs`]. +#[cfg(unix)] +fn copy_xattrs_at(from: &Path, to: &Path) -> io::Result<()> { + use std::os::fd::AsFd; + let old = std::fs::File::open(from)?; + // Writing an attribute needs write access to the file, not only to its directory. + let new = std::fs::OpenOptions::new().write(true).open(to)?; + copy_xattrs(old.as_fd(), new.as_fd()) +} + +/// Copy every extended attribute of `from` onto `to`, best effort, through the two open files +/// rather than their paths. +/// +/// Descriptors, not paths, because the automation write path holds capability-checked handles +/// and must never reach back out to an ambient path to finish a write (#7095). The same reason +/// makes this the right shape for [`copy_metadata`] too. +/// +/// An attribute that cannot be read or cannot be set is skipped: `com.apple.provenance` and +/// `com.apple.rootless` on macOS and `security.*` on Linux belong to the system and refuse to +/// be written by an ordinary process, and failing a document save over one would be absurd. +/// `Err` means the attribute *list* could not be read, so nothing was copied. +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +pub fn copy_xattrs(from: BorrowedFd<'_>, to: BorrowedFd<'_>) -> io::Result<()> { + use rustix::fs::{XattrFlags, fsetxattr}; + + for name in list_xattrs(from)?.split(|b| *b == 0) { + if name.is_empty() || skip_xattr(name) { + continue; + } + let Some(value) = read_xattr(from, name) else { continue }; + let _ = fsetxattr(to, name, &value, XattrFlags::empty()); + } + Ok(()) +} + +/// [`copy_xattrs`] where rustix offers no extended-attribute calls (FreeBSD and the other BSDs): +/// nothing is copied, as on Windows. +#[cfg(all(unix, not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))))] +pub fn copy_xattrs(_from: BorrowedFd<'_>, _to: BorrowedFd<'_>) -> io::Result<()> { + Ok(()) +} + +/// Attributes that describe how the *old* file's bytes are stored rather than anything about +/// the document, and so must never be pinned onto a file holding different bytes. +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +fn skip_xattr(name: &[u8]) -> bool { + // `com.apple.decmpfs` marks a file whose data lives compressed inside the attribute itself. + // The kernel hides it from a plain `listxattr` and refuses to set it, but a file claiming + // compressed storage it does not have would read as garbage, so never try. + name == b"com.apple.decmpfs" +} + +/// The NUL-separated attribute names of `fd`. +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +fn list_xattrs(fd: BorrowedFd<'_>) -> io::Result> { + let mut buf = vec![0u8; XATTR_CHUNK]; + loop { + match rustix::fs::flistxattr(fd, buf.as_mut_slice()) { + Ok(len) => { + buf.truncate(len.min(buf.len())); + return Ok(buf); + } + Err(e) if e == rustix::io::Errno::RANGE && buf.len() < MAX_XATTR_NAMES => { + buf.resize(buf.len().saturating_mul(4).min(MAX_XATTR_NAMES), 0); + } + Err(e) => return Err(e.into()), + } + } +} + +/// The value of one attribute, or `None` if it cannot be read or is larger than +/// [`MAX_XATTR_VALUE`]. A missing value is normal: another process may remove an attribute +/// between the listing and the read. +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +fn read_xattr(fd: BorrowedFd<'_>, name: &[u8]) -> Option> { + let mut buf = vec![0u8; XATTR_CHUNK]; + loop { + match rustix::fs::fgetxattr(fd, name, buf.as_mut_slice()) { + Ok(len) => { + buf.truncate(len.min(buf.len())); + return Some(buf); + } + Err(e) if e == rustix::io::Errno::RANGE && buf.len() < MAX_XATTR_VALUE => { + buf.resize(buf.len().saturating_mul(4).min(MAX_XATTR_VALUE), 0); + } + Err(_) => return None, + } + } +} + +/// Copy an explicit macOS access-control list (`chmod +a`) from `from` onto `to` (#7073). +/// +/// `fcopyfile(COPYFILE_ACL)` is the obvious call and is an `unsafe fn`, which this workspace +/// forbids; `fclonefileat` with `CLONE_ACL` is safe but only works on APFS and would mean +/// writing every save as a clone-then-truncate. `exacl` is a small, safe wrapper over +/// `acl_get_file`/`acl_set_file` that works on every file system that has ACLs at all. +/// +/// An old file with no ACL leaves `to` alone: the new file may have picked up the folder's +/// inherited entries, and taking access away is a worse surprise than leaving it as the folder +/// says it should be. +#[cfg(target_os = "macos")] +fn copy_acl(from: &Path, to: &Path) -> io::Result<()> { + let entries = exacl::getfacl(from, None)?; + if entries.is_empty() { + return Ok(()); + } + exacl::setfacl(&[to], &entries, None) +} + +/// Replace the **existing** file `to` with `from`, keeping what the destination owns rather than +/// its bytes. +/// +/// Everywhere but Windows this is exactly [`std::fs::rename`], and the metadata is carried by +/// [`copy_metadata`] onto `from` beforehand. On Windows it is `ReplaceFileW`, which preserves +/// the replaced file's DACL (#7096), its named streams — `Zone.Identifier`, the Mark of the Web +/// (#7094) — its creation time, object identifier, compression and encryption, in the one call +/// Microsoft documents for the save-through-a-temporary-file pattern. None of those have a safe +/// path-based API to copy by hand. +pub fn replace_existing(from: &Path, to: &Path) -> io::Result<()> { + #[cfg(windows)] + { + windows_replace(from, to) + } + #[cfg(not(windows))] + { + std::fs::rename(from, to) + } +} + +/// `ReplaceFileW`, with the plain rename as the fallback. See [`replace_existing`]. +/// +/// **A backup name is not optional.** `ReplaceFile` without one deletes the replaced file before +/// the final rename, and documents `ERROR_UNABLE_TO_MOVE_REPLACEMENT`: "the replaced file no +/// longer exists and the replacement file exists under its original name" — the user's document +/// gone, its replacement left under a hidden temporary name. With a backup name the same failure +/// leaves both files where they were. So this always passes one, and deletes it on the way out. +/// +/// The failures and what each leaves behind (from the `ReplaceFileW` reference): +/// +/// - `ERROR_UNABLE_TO_MOVE_REPLACEMENT_2` (1177) is the only one that moves anything: the +/// replacement keeps its name but has already inherited the destination's streams and +/// attributes, and the destination's old content is at the backup name. Finishing the rename +/// by hand completes the save *with* its metadata; if even that fails, the backup goes back to +/// the destination so the user's file is where they left it. +/// - Every other error leaves the replaced and replacement files under their own names, so a +/// plain rename still saves the document — without the metadata, which is where this started. +#[cfg(windows)] +fn windows_replace(from: &Path, to: &Path) -> io::Result<()> { + use winsafe::co::REPLACEFILE; + + /// `ERROR_UNABLE_TO_MOVE_REPLACEMENT_2`: the destination now lives under the backup name. + const MOVE_REPLACEMENT_2: i32 = 1177; + + let backup = backup_path(to); + let paths = (to.to_str(), from.to_str(), backup.as_deref().and_then(Path::to_str)); + // `ReplaceFileW` takes `&str`; a path that is not valid Unicode, or one past MAX_PATH, is + // the plain rename's job. + let (Some(replaced), Some(replacement), Some(backup_str)) = paths else { + return std::fs::rename(from, to); + }; + + let flags = REPLACEFILE::IGNORE_MERGE_ERRORS | REPLACEFILE::IGNORE_ACL_ERRORS; + match winsafe::ReplaceFile(replaced, replacement, Some(backup_str), flags) { + Ok(()) => { + remove_backup(backup.as_deref()); + Ok(()) + } + Err(e) if e.raw() as i32 == MOVE_REPLACEMENT_2 => match std::fs::rename(from, to) { + Ok(()) => { + remove_backup(backup.as_deref()); + Ok(()) + } + Err(rename_failed) => { + if let Some(backup) = backup.as_deref() { + let _ = std::fs::rename(backup, to); + } + Err(rename_failed) + } + }, + Err(_) => { + remove_backup(backup.as_deref()); + std::fs::rename(from, to) + } + } +} + +/// A unique name beside `to` for `ReplaceFile` to park the replaced file under. It shares the +/// temporary-file suffix, so the save's own cleanup and the tests' leftover check cover it. +#[cfg(windows)] +fn backup_path(to: &Path) -> Option { + let name = to.file_name()?.to_string_lossy().into_owned(); + let dir = match to.parent() { + Some(d) if !d.as_os_str().is_empty() => d, + _ => Path::new("."), + }; + Some(dir.join(super::temp_name(&name))) +} + +#[cfg(windows)] +fn remove_backup(backup: Option<&Path>) { + if let Some(backup) = backup { + let _ = std::fs::remove_file(backup); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/format/src/atomic/meta/tests.rs b/crates/format/src/atomic/meta/tests.rs new file mode 100644 index 0000000000..834e87e66e --- /dev/null +++ b/crates/format/src/atomic/meta/tests.rs @@ -0,0 +1,310 @@ +//! What a save keeps from the file it replaces. +//! +//! The Unix tests run for real. The Windows ones exercise `ReplaceFileW` through +//! [`crate::atomic::atomic_write`] and can only run on Windows, so they are `#[cfg(windows)]` +//! and are covered by the Windows CI job, not by a developer on a Mac. + +use crate::atomic::atomic_write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +struct TempDir(PathBuf); +impl TempDir { + fn new(tag: &str) -> Self { + static N: AtomicU64 = AtomicU64::new(0); + let d = std::env::temp_dir().join(format!("pc-meta-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + Self(d) + } + fn join(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// No temporary or backup file is left beside the saved document. +fn assert_no_temp(dir: &Path) { + let leftovers: Vec<_> = + std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".tmp")).collect(); + assert!(leftovers.is_empty(), "temporary files left behind: {leftovers:?}"); +} + +// ---------------------------------------------------------------- extended attributes (Unix) + +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +mod xattrs { + use super::*; + + /// macOS wants a reverse-DNS name; Linux only lets an unprivileged process write `user.*`. + #[cfg(target_os = "macos")] + const TAG: &str = "com.apple.metadata:_kMDItemUserTags"; + #[cfg(not(target_os = "macos"))] + const TAG: &str = "user.photocraft.test"; + + fn set(path: &Path, name: &str, value: &[u8]) -> bool { + rustix::fs::setxattr(path, name, value, rustix::fs::XattrFlags::empty()).is_ok() + } + + fn get(path: &Path, name: &str) -> Option> { + let mut buf = vec![0u8; 1 << 20]; + let len = rustix::fs::getxattr(path, name, buf.as_mut_slice()).ok()?; + buf.truncate(len); + Some(buf) + } + + /// #6603: the attributes of the replaced file — a Finder tag, a `user.*` attribute — are on + /// the file the user is left with. + #[test] + fn replacing_a_file_keeps_its_extended_attributes() { + let d = TempDir::new("xattr"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + if !set(&p, TAG, b"tagged") { + // tmpfs and some CI file systems have no xattr support; nothing to assert. + return; + } + + atomic_write(&p, b"second, longer").unwrap(); + + assert_eq!(std::fs::read(&p).unwrap(), b"second, longer"); + assert_eq!(get(&p, TAG).as_deref(), Some(&b"tagged"[..]), "the replaced file's attribute was dropped"); + assert_no_temp(&d.0); + } + + /// A large value still comes across (and is not silently truncated). + #[test] + fn a_large_attribute_value_survives() { + let d = TempDir::new("xattr-big"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + // Comfortably past the first read buffer, so the grow-on-ERANGE path runs. + let value = vec![0xABu8; 64 << 10]; + if !set(&p, TAG, &value) { + return; + } + + atomic_write(&p, b"second").unwrap(); + + assert_eq!(get(&p, TAG), Some(value)); + } + + /// A read-only file is refused outright (#6600), so a save never reaches the metadata copy and + /// the file keeps everything it had. The writable cases above cover the copy itself. + #[test] + fn a_read_only_file_keeps_its_attributes_and_its_mode() { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("xattr-ro"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + if !set(&p, TAG, b"tagged") { + return; + } + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o444)).unwrap(); + + // #6600: a read-only file is refused before anything is written, so the question this test + // asks — does a replace keep the attributes and the mode — is answered by the save not + // happening. The writable case above covers attributes surviving a replace. + let e = atomic_write(&p, b"second, longer").expect_err("a read-only file is refused"); + assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied); + + assert_eq!(std::fs::read(&p).unwrap(), b"first", "the original was left alone"); + assert_eq!(get(&p, TAG).as_deref(), Some(&b"tagged"[..]), "a read-only file lost its attribute"); + assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o444); + } + + /// Creating a file that was not there sets no attributes and does not fail. + #[test] + fn creating_a_new_file_needs_no_source() { + let d = TempDir::new("xattr-new"); + let p = d.join("fresh.psd"); + atomic_write(&p, b"bytes").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"bytes"); + assert!(get(&p, TAG).is_none()); + } + + /// The descriptor-based copy is what the automation write path uses (#7095): it works on two + /// open files and never looks at a path. + #[test] + fn copy_xattrs_works_on_descriptors() { + use std::os::fd::AsFd; + let d = TempDir::new("xattr-fd"); + let (from, to) = (d.join("from"), d.join("to")); + std::fs::write(&from, b"a").unwrap(); + std::fs::write(&to, b"b").unwrap(); + if !set(&from, TAG, b"carried") { + return; + } + + let old = std::fs::File::open(&from).unwrap(); + let new = std::fs::OpenOptions::new().write(true).open(&to).unwrap(); + super::super::copy_xattrs(old.as_fd(), new.as_fd()).unwrap(); + + assert_eq!(get(&to, TAG).as_deref(), Some(&b"carried"[..])); + assert_eq!(std::fs::read(&to).unwrap(), b"b", "copying attributes must not touch the bytes"); + } +} + +// --------------------------------------------------------------------------- mode (Unix) + +/// The mode was already kept before any of this; it still is. +#[cfg(unix)] +#[test] +fn replacing_a_file_keeps_its_mode() { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("mode"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)).unwrap(); + + atomic_write(&p, b"second").unwrap(); + + assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600); + assert_no_temp(&d.0); +} + +// ----------------------------------------------------------------------------- ACL (macOS) + +#[cfg(target_os = "macos")] +mod acl { + use super::*; + + /// #7073: an ACL entry added with `chmod +a` is still there after a save. + #[test] + fn replacing_a_file_keeps_its_acl() { + let d = TempDir::new("acl"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + + // The same thing `chmod +a` does: one explicit entry for the user running the test, so + // no second account has to exist. + let Ok(user) = std::env::var("USER") else { return }; + let entries = [exacl::AclEntry::allow_user(&user, exacl::Perm::READ | exacl::Perm::WRITE, None)]; + if exacl::setfacl(&[&p], &entries, None).is_err() { + // A file system without ACL support (a RAM disk, some CI volumes). + return; + } + let before = exacl::getfacl(&p, None).unwrap(); + assert!(!before.is_empty(), "the test could not set an ACL to begin with"); + + atomic_write(&p, b"second, longer").unwrap(); + + assert_eq!(std::fs::read(&p).unwrap(), b"second, longer"); + assert_eq!(exacl::getfacl(&p, None).unwrap(), before, "the replaced file's ACL was dropped"); + assert_no_temp(&d.0); + } + + /// A file with no ACL keeps having no ACL, rather than gaining an empty one. + #[test] + fn a_file_without_an_acl_is_left_alone() { + let d = TempDir::new("acl-none"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + let before = exacl::getfacl(&p, None).unwrap(); + + atomic_write(&p, b"second").unwrap(); + + assert_eq!(exacl::getfacl(&p, None).unwrap(), before); + } +} + +// --------------------------------------------------------------- named streams and ACL (Windows) + +/// Unverified on a Mac: these run only on Windows (CI's Windows job). +#[cfg(windows)] +mod windows { + use super::*; + + /// Open a named stream of `path`, e.g. `Zone.Identifier`. + fn stream(path: &Path, name: &str) -> PathBuf { + let mut s = path.as_os_str().to_os_string(); + s.push(":"); + s.push(name); + PathBuf::from(s) + } + + /// #7094: a file marked as downloaded from the internet is still marked after a save, so the + /// shell and other applications keep warning about it. + #[test] + fn replacing_a_file_keeps_its_mark_of_the_web() { + let d = TempDir::new("motw"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + let motw = b"[ZoneTransfer]\r\nZoneId=3\r\n"; + std::fs::write(stream(&p, "Zone.Identifier"), motw).unwrap(); + + atomic_write(&p, b"second, longer").unwrap(); + + assert_eq!(std::fs::read(&p).unwrap(), b"second, longer"); + assert_eq!(std::fs::read(stream(&p, "Zone.Identifier")).unwrap(), motw, "the Mark of the Web was dropped"); + assert_no_temp(&d.0); + } + + /// Any other named stream rides along too, because `ReplaceFileW` keeps the lot. + #[test] + fn replacing_a_file_keeps_other_named_streams() { + let d = TempDir::new("ads"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + std::fs::write(stream(&p, "photocraft.test"), b"side data").unwrap(); + + atomic_write(&p, b"second").unwrap(); + + assert_eq!(std::fs::read(stream(&p, "photocraft.test")).unwrap(), b"side data"); + } + + /// #7096: an explicit ACL entry survives, instead of the file falling back to whatever the + /// folder hands down. Compared as the string `icacls` prints, which is what a user checks. + #[test] + fn replacing_a_file_keeps_its_explicit_acl() { + let d = TempDir::new("dacl"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + + // Grant the current user an entry that inheritance would not have produced. + let user = std::env::var("USERNAME").unwrap_or_default(); + if user.is_empty() { + return; + } + let granted = std::process::Command::new("icacls").arg(&p).arg("/grant").arg(format!("{user}:(RX)")).output(); + if !granted.map(|o| o.status.success()).unwrap_or(false) { + return; + } + let before = std::process::Command::new("icacls").arg(&p).output().unwrap().stdout; + + atomic_write(&p, b"second, longer").unwrap(); + + let after = std::process::Command::new("icacls").arg(&p).output().unwrap().stdout; + assert_eq!(String::from_utf8_lossy(&after), String::from_utf8_lossy(&before), "the explicit ACL was dropped"); + assert_no_temp(&d.0); + } + + /// `ReplaceFileW` also keeps the creation time, which the rename used to reset (#6603). + #[test] + fn replacing_a_file_keeps_its_creation_time() { + let d = TempDir::new("born"); + let p = d.join("doc.psd"); + atomic_write(&p, b"first").unwrap(); + let before = std::fs::metadata(&p).unwrap().created().unwrap(); + + std::thread::sleep(std::time::Duration::from_millis(50)); + atomic_write(&p, b"second").unwrap(); + + assert_eq!(std::fs::metadata(&p).unwrap().created().unwrap(), before); + } + + /// Creating a file where there was none still works: there is nothing to replace, so the + /// write never reaches `ReplaceFileW`. + #[test] + fn creating_a_new_file_still_works() { + let d = TempDir::new("new"); + let p = d.join("fresh.psd"); + atomic_write(&p, b"bytes").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"bytes"); + assert_no_temp(&d.0); + } +} diff --git a/crates/format/src/atomic/tests.rs b/crates/format/src/atomic/tests.rs index 8e71bc7ce3..d4381705a0 100644 --- a/crates/format/src/atomic/tests.rs +++ b/crates/format/src/atomic/tests.rs @@ -69,8 +69,8 @@ impl AtomicFs for Faulty { fn sync_dir(&self, dir: &Path) -> io::Result<()> { RealFs.sync_dir(dir) } - fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()> { - RealFs.copy_permissions(from, to) + fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.copy_metadata(from, to) } } @@ -176,6 +176,81 @@ fn lock_that_outlasts_the_retries_keeps_original() { assert_no_temp(&d.0); } +/// A file system that reports the target as read-only and records every write and rename. +#[derive(Default)] +struct ReadOnlyTarget { + writes: Cell, + renames: Cell, +} + +impl AtomicFs for ReadOnlyTarget { + fn is_readonly(&self, _path: &Path) -> bool { + true + } + fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()> { + self.writes.set(self.writes.get() + 1); + RealFs.write_new(tmp, bytes) + } + fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { + self.renames.set(self.renames.get() + 1); + RealFs.rename(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { + RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + RealFs.sync_dir(dir) + } + fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.copy_metadata(from, to) + } +} + +/// #6600: a read-only destination is refused before anything is written, with an error that says +/// so, instead of being replaced by the rename (which only needs the folder to be writable). +#[test] +fn read_only_target_is_refused_before_anything_is_written() { + let d = TempDir::new("rofake"); + let p = d.0.join("a.psd"); + std::fs::write(&p, ORIGINAL).unwrap(); + let fs = ReadOnlyTarget::default(); + let e = atomic_write_with(&fs, NO_RETRY, &p, b"new").unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::PermissionDenied); + assert!(e.to_string().contains("a.psd") && e.to_string().contains("read-only") && e.to_string().contains("not changed"), "{e}"); + assert_eq!((fs.writes.get(), fs.renames.get()), (0, 0), "nothing is written or renamed"); + assert_eq!(std::fs::read(&p).unwrap(), ORIGINAL); + assert_no_temp(&d.0); +} + +/// #6600 on the real file system: a file marked read-only (`chmod 444`, or the Windows read-only +/// attribute) keeps its bytes and the save says why; a writable one still saves. +#[test] +fn read_only_file_on_disk_is_never_replaced() { + let d = TempDir::new("rofile"); + let p = d.0.join("a.psd"); + std::fs::write(&p, ORIGINAL).unwrap(); + let mut perms = std::fs::metadata(&p).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&p, perms.clone()).unwrap(); + let r = atomic_write(&p, b"new"); + let unchanged = std::fs::read(&p).unwrap(); + let still_readonly = std::fs::metadata(&p).unwrap().permissions().readonly(); + // Make it writable again so the folder can be removed (Windows refuses to delete it otherwise). + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&p, perms).unwrap(); + let e = r.unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::PermissionDenied); + assert!(e.to_string().contains("the file is read-only;"), "a clear reason, not a failed rename: {e}"); + assert_eq!(unchanged, ORIGINAL); + assert!(still_readonly); + assert_no_temp(&d.0); + // New files and writable files are unaffected. + atomic_write(&p, b"new").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"new"); + atomic_write(&d.0.join("fresh.psd"), b"x").unwrap(); +} + #[cfg(unix)] #[test] fn read_only_folder_errors_clearly_and_never_writes_in_place() { @@ -221,6 +296,52 @@ fn writes_through_a_symlink() { assert_eq!(std::fs::read(&real).unwrap(), b"new"); } +/// #6605: saving onto a dangling symlink writes through to its target instead of replacing the +/// link with a regular file, even when a folder on the way to the target doesn't exist yet. +#[cfg(unix)] +#[test] +fn writes_through_a_dangling_symlink() { + let d = TempDir::new("dangling"); + let real = d.0.join("missing/dir/a.psd"); + let link = d.0.join("link.psd"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + atomic_write(&link, b"new").unwrap(); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link survives"); + assert_eq!(std::fs::read(&real).unwrap(), b"new", "the bytes land at the target"); + assert_no_temp(real.parent().unwrap_or(Path::new("."))); +} + +/// A dangling link with a relative target resolves against the link's own folder. +#[cfg(unix)] +#[test] +fn writes_through_a_dangling_relative_symlink() { + let d = TempDir::new("dangling-rel"); + let here = d.0.join("here"); + std::fs::create_dir(&here).unwrap(); + let link = here.join("link.psd"); + std::os::unix::fs::symlink("../elsewhere/real.psd", &link).unwrap(); + atomic_write(&link, b"new").unwrap(); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link survives"); + assert_eq!(std::fs::read(d.0.join("elsewhere/real.psd")).unwrap(), b"new"); + assert_no_temp(&d.0.join("elsewhere")); +} + +/// A symlink loop is an error; it never replaces either link. +#[cfg(unix)] +#[test] +fn symlink_loop_errors_without_replacing_the_links() { + let d = TempDir::new("loop"); + let a = d.0.join("a.psd"); + let b = d.0.join("b.psd"); + std::os::unix::fs::symlink(&b, &a).unwrap(); + std::os::unix::fs::symlink(&a, &b).unwrap(); + let e = atomic_write(&a, b"new").unwrap_err(); + assert!(e.to_string().contains("symbolic links"), "{e}"); + assert!(std::fs::symlink_metadata(&a).unwrap().file_type().is_symlink()); + assert!(std::fs::symlink_metadata(&b).unwrap().file_type().is_symlink()); + assert_no_temp(&d.0); +} + #[test] fn directory_target_or_bare_root_is_an_error_not_a_panic() { let d = TempDir::new("dir"); diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index d047668cb0..7da5dd6b53 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -163,6 +163,10 @@ pub(crate) fn read_manifest(src: &dyn ByteSource, opts: &LoadOptions) -> Result< let layers = take_array(&mut v, "/document/layers"); let mut m: Manifest = serde_json::from_value(v)?; m.document.layers = layers_from_json(layers)?; + // A number past f32's range decodes as infinity, which no save could write back (#6862). + if let Err(crate::finite::Problem::NonFinite { path }) = crate::finite::check(&m) { + return Err(FormatError::corrupt(format!("`{path}` is out of range"))); + } Ok(m) } diff --git a/crates/format/tests/corruption.rs b/crates/format/tests/corruption.rs index d293abed1e..727b37cb70 100644 --- a/crates/format/tests/corruption.rs +++ b/crates/format/tests/corruption.rs @@ -94,6 +94,24 @@ fn bad_manifest_json() { assert!(matches!(load_from_bytes(&b), Err(FormatError::Json(_)))); } +/// A number past f32's range would load as infinity, and every later save would then fail +/// (#6862): it is refused when the file is opened, naming the value. +#[test] +fn out_of_range_number_refused_on_open() { + let b = rebuild(&sample(), |n, d| { + Some(if n == "manifest.json" { + let mut v: serde_json::Value = serde_json::from_slice(&d).unwrap(); + v["document"]["layers"][0]["opacity"] = serde_json::json!(1e39); + serde_json::to_vec(&v).unwrap() + } else { + d + }) + }); + let Err(e) = load_from_bytes(&b) else { panic!("a manifest with opacity 1e39 opened") }; + assert!(matches!(e, FormatError::Corrupt(_)), "{e}"); + assert!(e.to_string().contains("document.layers[0].opacity"), "{e}"); +} + /// Hostile nesting fails with an error instead of overflowing the stack; nesting as deep as the /// deepest groups a bundle may hold (three JSON levels each) parses, and is then rejected for /// lacking a format version. diff --git a/crates/format/tests/float_roundtrip.rs b/crates/format/tests/float_roundtrip.rs new file mode 100644 index 0000000000..da6e7626d1 --- /dev/null +++ b/crates/format/tests/float_roundtrip.rs @@ -0,0 +1,27 @@ +//! `.pcraft` is lossless for f64: every coordinate reloads bit-for-bit. + +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Document, Layer, LayerContent, Size}; + +#[test] +fn f64_coordinates_reload_bit_exact() { + let x = 11.183221215612905_f64; + let y = 0.1 + 0.2; + let mut doc = Document::new("Floats", Size::new(2, 2), ColorMode::Rgb, SampleType::U8); + doc.layers.push(Layer::new( + "Shape", + LayerContent::Shape(photocraft_doc::ShapeLayer { + path: photocraft_doc::Path::new(vec![photocraft_doc::Subpath::polygon(&[(x, y), (40.0, 10.0), (25.0, 40.0)])]), + ..Default::default() + }), + )); + doc.guides.horizontal.push(x); + doc.guides.vertical.push(y); + doc.ruler_origin = [x, y]; + let bytes = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap(); + let back = photocraft_format::load_from_bytes(&bytes).unwrap(); + assert_eq!(back.guides.horizontal[0].to_bits(), x.to_bits()); + assert_eq!(back.guides.vertical[0].to_bits(), y.to_bits()); + assert_eq!(back.ruler_origin.map(f64::to_bits), [x, y].map(f64::to_bits)); + assert_eq!(back, doc); +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 0e76736013..d95e4b847f 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -1,4 +1,4 @@ -//! Geometry primitives shared by every Photocraft crate. +//! Geometry primitives shared by every PhotoCraft crate. //! //! Document space is integer pixels with the origin at the canvas top-left. //! Layers may extend beyond the canvas (negative coordinates are valid). diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index 2b9c1bbdf4..6457b1192c 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -1,4 +1,4 @@ -// Photocraft GPU compositor kernels. +// PhotoCraft GPU compositor kernels. // // Every pass renders one chunk of the canvas into a straight-alpha RGBA32F accumulator, reading // its inputs with `textureLoad` at the same pixel. Effect-map kernels (`fs_m*`) render diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 01e147d51a..994eb5e149 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -203,6 +203,11 @@ impl B { self.fields.push((kind, reach_for(width))); In::Field(kind) } + /// A chiselled bevel's inside and outside fields, always asked for together ([`bevel_fields`] + /// computes them as one). + fn bevel_fields(&mut self, width: f32) -> [In; 2] { + [FieldKind::BevelInside, FieldKind::BevelOutside].map(|k| self.field(k, width)) + } /// `Map::shifted` by whole pixels (`invert`: of `1 - a`); identity shifts of the plain map /// are skipped. fn shift(&mut self, src: In, dx: f32, dy: f32, outside: f32, invert: bool) -> In { @@ -374,8 +379,7 @@ pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool, let mut h = if bv.technique == BevelTechnique::Smooth { b.conv(In::Shape, photocraft_compose::effects::tent_kernel(g.width)) } else { - let din = b.field(FieldKind::BevelInside, size); - let dout = b.field(FieldKind::BevelOutside, size); + let [din, dout] = b.bevel_fields(size); let soft = g.chisel_soft > 0.0; let h = b.push(stage(Kernel::MBevelH, Some(din), Some(dout), [paint(g.paint), size, f32::from(u8::from(soft)), 0.0], 0)); // As `effects::bevel_height`: only emboss styles blur a Chisel Soft ramp. @@ -542,20 +546,51 @@ fn threaded_inside(kind: FieldKind) -> bool { /// fields run on all threads inside `distance_field`, from one window. That is also the window the CPU /// compositor computes them from, so a rebuilt field is exactly the one it gives. fn field_banded(kind: FieldKind, reach: i32, shape: &[f32], region: Rect, out: Rect, halo: i32) -> Vec { - if threaded_inside(kind) { - let win = out.inflate(halo).intersect(®ion); - if win.is_empty() { - return Vec::new(); - } - let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32); - return if win == out { f } else { crop(&f, win, out) }; - } - let parts = par_map(bands(out, BAND.max(halo)), |band| { - let win = band.inflate(halo).intersect(®ion); - let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32); - crop(&f, win, band) + let [f] = fields_in_windows(threaded_inside(kind), shape, region, out, halo, |s, w, h| { + [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)] }); - parts.concat() + f +} + +/// [`field`] of both bevel fields over the same `out`, `[BevelInside, BevelOutside]`, with the +/// sharp edges of each window found once (the two kinds have the same radius and threading). +pub(crate) fn bevel_fields(reach: i32, shape: &[f32], region: Rect, out: Rect) -> [Vec; 2] { + let kind = FieldKind::BevelInside; + fields_in_windows(threaded_inside(kind), shape, region, out, field_radius(kind, reach) + 1, |s, w, h| { + photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32) + }) +} + +/// The fields `compute` gives for a `w × h` window of the region-sized `shape`, over `out` (inside +/// `region`), each window grown by `halo`: `out` as one window when `whole` (the field spreads over +/// threads itself), else bands of it in parallel. +fn fields_in_windows( + whole: bool, + shape: &[f32], + region: Rect, + out: Rect, + halo: i32, + compute: impl Fn(Vec, usize, usize) -> [Vec; N] + Sync + Send, +) -> [Vec; N] { + let part = |r: Rect| -> [Vec; N] { + let win = r.inflate(halo).intersect(®ion); + if win.is_empty() { + return std::array::from_fn(|_| Vec::new()); + } + let f = compute(crop(shape, region, win), win.width() as usize, win.height() as usize); + if win == r { f } else { f.map(|f| crop(&f, win, r)) } + }; + if whole { + return part(out); + } + let parts = par_map(bands(out, BAND.max(halo)), part); + std::array::from_fn(|k| { + let mut f = Vec::with_capacity(parts.iter().map(|p| p[k].len()).sum()); + for p in &parts { + f.extend_from_slice(&p[k]); + } + f + }) } /// The layer's shape (`compose::layer_shape`) over `r`, in parallel bands. @@ -682,6 +717,8 @@ pub(crate) fn group_key(layer: &Layer, light: &GlobalLight, pin: &mut dyn FnMut( surface_fp(&m.surface, h, pin); } format!("{:?}{:?}", l.vector_mask, l.effects).hash(h); + l.blend_if.hash(h); + l.advanced.hash(h); h.write_u8(0xfe); } let mut h = std::collections::hash_map::DefaultHasher::new(); @@ -695,6 +732,7 @@ pub(crate) fn group_key(layer: &Layer, light: &GlobalLight, pin: &mut dyn FnMut( (m.enabled, m.density.to_bits(), m.feather.to_bits()).hash(&mut h); surface_fp(&m.surface, &mut h, pin); } + format!("{:?}", layer.vector_mask).hash(&mut h); } _ => walk(layer, &mut h, pin), } @@ -721,6 +759,36 @@ mod tests { assert_ne!(a.key, program(&Effect::DropShadow(s), &light, false).key); } + /// A styled group's effect shape follows its own vector mask and its children's Blend If and + /// Advanced Blending, so the cached shape must be rebuilt when any of them changes. + #[test] + fn group_key_follows_vector_mask_blend_if_and_advanced() { + use photocraft_doc::{BlendRange, Knockout, Path, PixelFormat, Subpath, VectorMask}; + let light = GlobalLight::default(); + let group = Layer::group("g", vec![Layer::raster("child", PixelFormat::RGBA8)]); + let base = group_key(&group, &light, &mut |_| {}); + + let mask = |x: f64| VectorMask::new(Path::new(vec![Subpath::polygon(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0)])])); + let mut masked = group.clone(); + masked.vector_mask = Some(mask(0.0)); + let with_mask = group_key(&masked, &light, &mut |_| {}); + assert_ne!(base, with_mask, "adding the group's vector mask"); + masked.vector_mask = Some(mask(5.0)); + assert_ne!(with_mask, group_key(&masked, &light, &mut |_| {}), "moving the group's vector mask"); + + fn child_mut(g: &mut Layer) -> &mut Layer { + let LayerContent::Group(gr) = &mut g.content else { unreachable!() }; + &mut gr.children[0] + } + let mut blend_if = group.clone(); + child_mut(&mut blend_if).blend_if.ranges = vec![[BlendRange { black: [128, 128], white: [255, 255] }, BlendRange::FULL]]; + assert_ne!(base, group_key(&blend_if, &light, &mut |_| {}), "a child's Blend If"); + + let mut advanced = group.clone(); + child_mut(&mut advanced).advanced.knockout = Knockout::Deep; + assert_ne!(base, group_key(&advanced, &light, &mut |_| {}), "a child's Advanced Blending"); + } + #[test] fn windows_grow_by_reach_and_temps_are_reused() { let light = GlobalLight::default(); @@ -842,6 +910,40 @@ mod tests { assert!(too_small_noticed, "a 2 row halo went unnoticed, so this test guards nothing"); } + /// Both bevel fields from one window (sharp edges found once) are bit for bit the fields + /// computed one at a time, over the whole region and over a part of it. + #[test] + fn paired_bevel_fields_equal_the_fields_one_at_a_time() { + let region = Rect::new(-20, -10, 300, 290); + let (w, h) = (region.width() as usize, region.height() as usize); + let mut shape = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); + let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); + shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; + } + } + let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + for reach in [3, 9, 40] { + for out in [region, Rect::new(40, 30, 170, 120), Rect::new(-20, 200, 300, 290)] { + let [inside, outside] = bevel_fields(reach, &shape, region, out); + assert_eq!(bits(&inside), bits(&field(FieldKind::BevelInside, reach, &shape, region, out)), "inside, reach {reach}, {out:?}"); + assert_eq!(bits(&outside), bits(&field(FieldKind::BevelOutside, reach, &shape, region, out)), "outside, reach {reach}, {out:?}"); + // The banded path (wasm) pairs them per band the same way. + let halo = field_radius(FieldKind::BevelInside, reach) + 1; + let banded = + fields_in_windows(false, &shape, region, out, halo, |s, w, h| photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32)); + for (k, kind) in [FieldKind::BevelInside, FieldKind::BevelOutside].into_iter().enumerate() { + let [one] = fields_in_windows(false, &shape, region, out, halo, |s, w, h| { + [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)] + }); + assert_eq!(bits(&banded[k]), bits(&one), "banded {kind:?}, reach {reach}, {out:?}"); + } + } + } + } + /// #3646: a stroke's outer edge is the fitted 5 × 5 chamfer while it is narrow and the exact /// Euclidean transform once it is wide — the chamfer's octagon facets a wide stroke. The GPU /// builds it from the field its width picks (`stroke_outside_exact`), while the spread of drop diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 690d144d68..7a4357becf 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -42,6 +42,7 @@ mod fx; pub mod health; pub mod plan; mod prefix; +pub mod timing; use std::collections::HashMap; use std::num::NonZeroU64; @@ -55,6 +56,7 @@ use photocraft_raster::{Surface, Tile}; pub use health::{DeviceHealth, Fault}; pub use plan::{Kernel, Plan, Role, Unsupported, plan}; +pub use timing::{GpuTimer, GpuTiming}; /// Accumulator format for intermediate buffers. Full float: discontinuous operations /// (Posterize, Threshold, Hard Mix, Dissolve) must land on the same side of their thresholds as @@ -107,6 +109,12 @@ pub struct ChunkOut<'a> { /// What a render did (for profiling and tests). #[derive(Clone, Copy, Debug, Default)] pub struct Stats { + /// How long the GPU spent executing a composite, once its timestamps came back. Because the + /// readback is asynchronous this belongs to an *earlier* render than the one returning it + /// (it carries that render's own pixel count, so the two are never confused), and it is + /// `None` unless [`Compositor::measure_gpu_time`] is on and a measurement has landed. + /// Always `None` from [`Compositor::encode`], which submits nothing of its own. + pub gpu_time: Option, pub passes: usize, pub chunks: usize, pub slots: u32, @@ -143,7 +151,9 @@ enum TexKind { Rgba16F, /// GRAY8 masks copied verbatim. R8Direct, - /// Other masks as R32F. + /// 16-bit masks as R16F (the precision 16-bit pixels get as RGBA16F). + R16F, + /// 32-bit masks as R32F. R32F, } @@ -154,7 +164,8 @@ impl TexKind { Role::Content | Role::Stroke if f.sample == SampleType::U8 => TexKind::Rgba8, Role::Content | Role::Stroke => TexKind::Rgba16F, Role::Mask if f == PixelFormat::GRAY8 => TexKind::R8Direct, - Role::Mask => TexKind::R32F, + Role::Mask if f.sample == SampleType::F32 => TexKind::R32F, + Role::Mask => TexKind::R16F, } } fn format(self) -> wgpu::TextureFormat { @@ -162,6 +173,7 @@ impl TexKind { TexKind::Rgba8Direct | TexKind::Rgba8 => wgpu::TextureFormat::Rgba8Unorm, TexKind::Rgba16F => wgpu::TextureFormat::Rgba16Float, TexKind::R8Direct => wgpu::TextureFormat::R8Unorm, + TexKind::R16F => wgpu::TextureFormat::R16Float, TexKind::R32F => wgpu::TextureFormat::R32Float, } } @@ -170,6 +182,7 @@ impl TexKind { TexKind::Rgba8Direct | TexKind::Rgba8 => 4, TexKind::Rgba16F => 8, TexKind::R8Direct => 1, + TexKind::R16F => 2, TexKind::R32F => 4, } } @@ -469,6 +482,9 @@ pub struct Compositor { cmyk: u64, /// The device's health (see [`Compositor::set_health`]); `None` = assumed healthy. health: Option, + /// Timestamp queries measuring how long the GPU spends on a refresh (see + /// [`Compositor::measure_gpu_time`]); `None` = not measured. + timer: Option, } fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { @@ -704,6 +720,7 @@ impl Compositor { effect_maps: map_error.is_none(), cmyk: 0, health: None, + timer: None, } .with_texture_limit(device.limits().max_texture_dimension_2d) } @@ -956,6 +973,41 @@ impl Compositor { self.health.as_ref().and_then(DeviceHealth::fault) } + /// Measure how long the GPU spends executing each [`Compositor::render`], with timestamp + /// queries read back asynchronously (nothing waits for the GPU). Returns whether the device + /// supports it: without [`timing::FEATURES`] there is no measurement at all, and callers + /// report no GPU time rather than the encode-and-submit cost `composite_ms` already is. + /// + /// A measurement arrives a frame or two after the refresh it belongs to, so it carries that + /// refresh's own pixel count; take it with [`Compositor::take_gpu_timing`]. + pub fn measure_gpu_time(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool { + // `PHOTOCRAFT_NO_GPU_TIMING` turns it off: a kill switch for a driver whose timestamp + // queries misbehave, and the control arm for measuring what the queries themselves + // cost — the device is identical either way, so only the instrumentation varies. + if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() { + return false; + } + if self.timer.is_none() { + self.timer = timing::GpuTimer::new(device, queue); + } + self.timer.is_some() + } + + /// Whether [`Compositor::measure_gpu_time`] is on for this compositor. + pub fn measures_gpu_time(&self) -> bool { + self.timer.is_some() + } + + /// The most recent finished GPU measurement, leaving none behind (a stale number is never + /// reported twice as new). `None` while unmeasured, unsupported, or still in flight. + /// + /// [`Compositor::render`] already drains this into [`Stats::gpu_time`], so the app never + /// calls it; it is how a bench or a test collects a measurement without issuing another + /// render to carry it. + pub fn take_gpu_timing(&mut self) -> Option { + self.timer.as_mut().and_then(timing::GpuTimer::take) + } + /// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is /// still open; the chunk texture is reused afterwards, so the sink must record any copies /// or passes that read it into the given encoder. Submits the work before returning; a @@ -971,8 +1023,47 @@ impl Compositor { ) -> Result { let result = scoped_work(device, self.health.is_some(), || { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") }); - let stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true)?; + if self.timer.as_ref().is_some_and(timing::GpuTimer::busy) { + // The readback map completes on a poll. The app polls every frame, but a + // non-blocking poll here keeps the measurements coming whatever the caller does. + match &self.health { + Some(h) => h.poll(device), + None => { + let _ = device.poll(wgpu::PollType::Poll); + } + } + } + // Whatever came back since the last render travels out with this one's stats, so + // nothing has to reach back into the compositor for it afterwards. + let landed = self.timer.as_mut().and_then(timing::GpuTimer::take); + if let Some(t) = &mut self.timer { + let r = region.intersect(&doc.bounds()); + t.start(&mut encoder, r.width() as u64 * r.height() as u64); + } + let mut stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true); + if let Ok(s) = &mut stats { + s.gpu_time = landed; + } + if let Some(t) = &mut self.timer { + // A refresh that failed part way measures nothing: its spans describe work the + // caller is about to redo on the CPU. + match stats { + Ok(_) => t.finish(&mut encoder), + Err(_) => { + t.cancel(); + // The refresh is lost, but a measurement that came back with it is not: + // hand it to the next render rather than drop it on the fallback path. + if let Some(landed) = landed { + t.restore(landed); + } + } + } + } + let stats = stats?; queue.submit([encoder.finish()]); + if let Some(t) = &mut self.timer { + t.submitted(); + } Ok(stats) }); if result.is_err() { @@ -1078,7 +1169,7 @@ impl Compositor { let aprons: Vec = plan.fx.iter().zip(&paged).map(|(f, &pg)| if pg { Self::fx_apron(doc, f) } else { 0 }).collect(); for (f, &pg) in plan.fx.iter().zip(&paged) { if !pg { - self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats); + self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats)?; } } let fr = self.frame_res(device, queue, canvas, &plan); @@ -1109,7 +1200,7 @@ impl Compositor { continue; } let window = pf.inflate(aprons.get(i).copied().unwrap_or(0)).intersect(&f.region); - self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats); + self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats)?; } let chunks = grid_rects(part, self.chunk); stats.chunks += chunks.len(); @@ -1124,7 +1215,7 @@ impl Compositor { stats.evicted += evicted; freed += bytes; if flush && (self.staged >= flush_bytes || work >= FLUSH_WORK || freed >= flush_bytes || self.recorded >= FLUSH_OPS) { - submit_batch(device, queue, encoder, self.health.as_ref(), &mut last_submit); + submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit); self.staged = 0; self.recorded = 0; work = 0; @@ -1399,7 +1490,7 @@ impl Compositor { if self.recorded >= FLUSH_OPS && let Some(last) = batch.as_deref_mut() { - submit_batch(device, queue, encoder, self.health.as_ref(), last); + submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), last); self.staged = 0; self.recorded = 0; stats.flushes += 1; @@ -1720,7 +1811,7 @@ impl Compositor { key: FxKey, region: Rect, stats: &mut Stats, - ) { + ) -> Result<(), Unsupported> { let layer = f.layer; let canvas = doc.bounds(); let is_group = matches!(layer.content, LayerContent::Group(_)); @@ -1791,13 +1882,13 @@ impl Compositor { } // Present: kept or (re)inserted above. let stamp = self.stamp; - let Some(e) = self.fx.get_mut(&key) else { return }; + let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; e.last_used = frame; e.stamp = stamp; e.doc = doc.id; e.tiles = [content_src.map(fx::snapshot), mask_src.map(fx::snapshot)]; if region.is_empty() { - return; + return Ok(()); } let t_trace = web_time_now(); @@ -1819,27 +1910,41 @@ impl Compositor { layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect(); let want = field_reaches(&progs); e.fields.retain(|k, _| want.contains_key(k)); - for (&kind, &reach) in &want { - let have = e.fields.get(&kind).map(|(r, _)| *r); - let out = match have { - Some(r) if r >= reach => { - if damage.is_empty() { - continue; - } - damage.inflate(fx::field_radius(kind, r)).intersect(®ion) + // Each field to recompute: over which rectangle, exact up to which reach. + let jobs: Vec<(FieldKind, Rect, i32)> = want + .iter() + .filter_map(|(&kind, &reach)| match e.fields.get(&kind).map(|(r, _)| *r) { + Some(r) if r >= reach => (!damage.is_empty()).then(|| (kind, damage.inflate(fx::field_radius(kind, r)).intersect(®ion), r)), + _ => Some((kind, region, reach)), + }) + .collect(); + // A chiselled bevel's two fields are asked for and kept together (`fx::bevel_fields`), so they + // are recomputed together, over one rectangle at one reach. + let job = |k: FieldKind| jobs.iter().find(|j| j.0 == k).map(|j| (j.1, j.2)); + let (bevel_in, bevel_out) = (job(FieldKind::BevelInside), job(FieldKind::BevelOutside)); + if bevel_in != bevel_out { + return Err(Unsupported(format!("bevel fields of `{}` out of step: inside {bevel_in:?}, outside {bevel_out:?}", layer.name))); + } + for (kind, out, reach) in jobs { + let fields = match kind { + FieldKind::BevelInside => { + let [inside, outside] = fx::bevel_fields(reach, &e.shape_cpu, region, out); + vec![(FieldKind::BevelInside, inside), (FieldKind::BevelOutside, outside)] } - _ => region, + // Computed with BevelInside, over the same rectangle at the same reach (checked above). + FieldKind::BevelOutside => continue, + _ => vec![(kind, fx::field(kind, reach, &e.shape_cpu, region, out))], }; - let reach = have.filter(|r| *r >= reach).unwrap_or(reach); - let v = fx::field(kind, reach, &e.shape_cpu, region, out); - if have.is_none_or(|r| r < reach) { - e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32))); + for (kind, v) in fields { + if e.fields.get(&kind).is_none_or(|(r, _)| *r < reach) { + e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32))); + } + if let Some((_, t)) = e.fields.get(&kind) { + t.write_r32(queue, region, out, &v); + } + staged += v.len() as u64 * 4; + stats.fx_pixels += out.width() as u64 * out.height() as u64; } - if let Some((_, t)) = e.fields.get(&kind) { - t.write_r32(queue, region, out, &v); - } - staged += v.len() as u64 * 4; - stats.fx_pixels += out.width() as u64 * out.height() as u64; } if let Some(t) = t_trace.filter(|_| !damage.is_empty()) { @@ -1854,7 +1959,7 @@ impl Compositor { if prog.maps == 0 { continue; } - let Some(e) = self.fx.get_mut(&key) else { return }; + let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; let same = e.progs[i].key == prog.key && e.progs[i].maps.len() == prog.maps; let d = if same { damage } else { region }; if d.is_empty() { @@ -1869,6 +1974,7 @@ impl Compositor { stats.fx_programs += 1; self.run_program(device, queue, encoder, key, i, prog, d, stats); } + Ok(()) } /// Record the passes of `prog` (maps of item `item` of `layer`) recomputing damage `d`. @@ -2034,9 +2140,14 @@ fn submit_batch( queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, health: Option<&DeviceHealth>, + timer: Option<&mut timing::GpuTimer>, last: &mut Option, ) { - let done = std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") })); + let mut done = std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") })); + if let Some(t) = timer { + // One refresh, several command buffers: the measurement spans all of them. + t.split(&mut done, encoder); + } let prev = last.replace(queue.submit([done.finish()])); #[cfg(not(target_arch = "wasm32"))] if let Some(prev) = prev { @@ -2203,6 +2314,7 @@ fn convert_tile(surface: &Surface, tile: Option<&Arc>, kind: TexKind, c: T } } TexKind::R8Direct => out.push((px[0].clamp(0.0, 1.0) * 255.0 + 0.5) as u8), + TexKind::R16F => out.extend(f32_to_f16(px[0]).to_le_bytes()), TexKind::R32F => out.extend(px[0].to_le_bytes()), } } @@ -2532,6 +2644,28 @@ mod tests { assert_eq!(op_words(&p, None, None, None).len() as u64, OP_UNIFORM); } + /// #6534: a 16-bit mask (16-bit documents, feathered or vector combined masks) costs two + /// bytes per pixel on the GPU, twice an 8-bit mask, not four; 32-bit masks stay R32Float. + #[test] + fn sixteen_bit_masks_upload_at_two_bytes_per_pixel() { + let gray = |sample| PixelFormat { sample, ..PixelFormat::GRAY8 }; + assert_eq!(TexKind::for_surface(Role::Mask, PixelFormat::GRAY8).bytes_per_pixel(), 1); + let k16 = TexKind::for_surface(Role::Mask, gray(SampleType::U16)); + assert_eq!(k16.bytes_per_pixel(), 2, "{k16:?}"); + assert_eq!(k16.format().block_copy_size(None), Some(2), "{k16:?}"); + let k32 = TexKind::for_surface(Role::Mask, gray(SampleType::F32)); + assert_eq!(k32.format(), wgpu::TextureFormat::R32Float); + // The texels hold the mask values (a half each), the default pixel included. + let mut s = Surface::with_default(gray(SampleType::U16), &[1.0]); + s.fill_rect(Rect::new(0, 0, 4, 1), &[0.25]); + let c = TileCoord::new(0, 0); + let bytes = convert_tile(&s, s.tile(c), k16, c); + assert_eq!(bytes.len(), (TILE_SIZE * TILE_SIZE) as usize * 2); + assert_eq!(bytes.get(..2), Some(f32_to_f16(0.25).to_le_bytes().as_slice())); + assert_eq!(bytes.get(8..10), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); + assert_eq!(convert_tile(&s, None, k16, c).get(..2), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); + } + /// #1774: a solid fill shares one tile across every coordinate; it is converted once, and /// every coordinate (shared or not) still gets exactly the bytes `convert_tile` gives it, at /// every depth and texture kind. @@ -2544,7 +2678,8 @@ mod tests { (PixelFormat::RGBA16, TexKind::Rgba16F), (PixelFormat::RGBA32F, TexKind::Rgba16F), (PixelFormat::GRAY8, TexKind::R8Direct), - (PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, TexKind::R32F), + (PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, TexKind::R16F), + (PixelFormat { sample: SampleType::F32, ..PixelFormat::GRAY8 }, TexKind::R32F), ] { let mut s = Surface::new(fmt); let px = [0.2, 0.4, 0.6, 1.0]; diff --git a/crates/gpu/src/prefix.rs b/crates/gpu/src/prefix.rs index 34c70916e0..cf53a62850 100644 --- a/crates/gpu/src/prefix.rs +++ b/crates/gpu/src/prefix.rs @@ -18,15 +18,16 @@ use std::collections::HashMap; use photocraft_doc::{Document, Layer}; use photocraft_geom::Rect; -use crate::Tex; use crate::plan::{Checkpoint, Plan}; pub(crate) const MAX_BYTES: u64 = 512 << 20; /// One whole grid chunk, with the document rectangles that hold valid pixels: a whole-chunk /// capture covers the cell in one entry, partial captures accumulate alongside each other. +/// The texture is only copied to and from, so it has no view: Vulkan rejects a view on an image +/// without a sampled/storage/attachment usage (VUID-VkImageViewCreateInfo-image-04441). pub(crate) struct Chunk { - tex: Tex, + tex: wgpu::Texture, covered: Vec, /// The checkpoint the covered pixels hold. checkpoint: Checkpoint, @@ -172,7 +173,7 @@ impl Prefix { let Some((chunk, (ox, oy))) = self.covered_by(rect) else { return false }; encoder.copy_texture_to_texture( wgpu::TexelCopyTextureInfo { - texture: &chunk.tex.texture, + texture: &chunk.tex, mip_level: 0, origin: wgpu::Origin3d { x: ox.unsigned_abs(), y: oy.unsigned_abs(), z: 0 }, aspect: wgpu::TextureAspect::All, @@ -198,8 +199,16 @@ impl Prefix { if cell_bytes == 0 || cell_bytes > self.budget.saturating_sub(self.bytes) { return; } - let tex = - Tex::new(device, "pc_compose_prefix", cell.width(), cell.height(), src.format(), wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST); + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_compose_prefix"), + size: wgpu::Extent3d { width: cell.width().max(1), height: cell.height().max(1), depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: src.format(), + usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); self.bytes = self.bytes.saturating_add(cell_bytes); self.chunks.insert(cell, Chunk { tex, covered: Vec::new(), checkpoint, bytes: cell_bytes }); } @@ -221,7 +230,7 @@ impl Prefix { encoder.copy_texture_to_texture( wgpu::TexelCopyTextureInfo { texture: src, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, wgpu::TexelCopyTextureInfo { - texture: &chunk.tex.texture, + texture: &chunk.tex, mip_level: 0, origin: wgpu::Origin3d { x: ox.unsigned_abs(), y: oy.unsigned_abs(), z: 0 }, aspect: wgpu::TextureAspect::All, diff --git a/crates/gpu/src/timing.rs b/crates/gpu/src/timing.rs new file mode 100644 index 0000000000..e79548d84c --- /dev/null +++ b/crates/gpu/src/timing.rs @@ -0,0 +1,308 @@ +//! GPU execution time of a composite (#7186), measured with wgpu timestamp queries. +//! +//! `GpuCanvas::refresh` reports `composite_ms`, the CPU cost of *encoding and submitting* the +//! composite. That is not the cost of running it: at 24 MP the encode costs ~7.7 ms and the GPU +//! then spends ~171 ms finishing the work, so every consumer of `composite_ms` under-reports a +//! GPU-bound canvas by more than an order of magnitude and cannot see a regression that moves +//! work onto the GPU. +//! +//! Waiting for the GPU to report the true number would serialise the two processors and make the +//! app slower, so this measures instead of waiting: a timestamp is written on the GPU timeline at +//! the start and end of every command encoder a refresh submits, and the values are read back +//! asynchronously. The sum of the spans is the time the GPU spent executing that refresh, with +//! the CPU encoding gaps between submissions excluded. Nothing blocks; the numbers simply arrive +//! a frame or two later, so each measurement carries the pixel count of the refresh it belongs to +//! and is never attributed to whichever refresh happens to be in flight when it lands. +//! +//! **What it does not count.** The spans run between bottom-of-pipe timestamps inside the +//! refresh's own command buffers. Two kinds of GPU work fall outside them: queue-level uploads +//! (`Queue::write_texture`), which wgpu executes in its own command buffer before ours, and +//! whatever the GPU still does after the final timestamp retires — the end-of-batch writeback of +//! the render targets. Measured against a waited-for wall clock on Intel UHD P630 / Mesa, with +//! no uploads outstanding, the uncounted remainder is **~5 % of the reported time**, and it is +//! proportional to the composite rather than a fixed submit latency (1.0 ms at 6 MP, 4.5 ms at +//! 24 MP, 7.6 ms at 42.6 MP, against 21 / 83 / 158 ms reported). So the number is a slight +//! under-report of the GPU's total contribution, by a few per cent rather than the ~22x of the +//! encode-and-submit time it replaces. +//! +//! **What it costs.** Nothing measurable. The same refresh on the same device with +//! `PHOTOCRAFT_NO_GPU_TIMING` set waits 88.1 ms against 87.9 ms measured — a difference of +//! −0.2 ms on an ~88 ms refresh, i.e. inside the noise of a shared host. Per refresh the +//! queries add two timestamp writes (two more per flush), one resolve and one copy of at most +//! 1 KiB, a `map_async` and an `Arc` allocation; the query set and both buffers are allocated +//! once per compositor and are size-independent, so a resize reallocates nothing. +//! +//! The measurement is *optional by construction*. Without `TIMESTAMP_QUERY` and +//! `TIMESTAMP_QUERY_INSIDE_ENCODERS` on the device (older drivers, most browsers, the Noop +//! backend), [`GpuTimer::new`] returns `None` and callers report no GPU time at all rather than a +//! plausible wrong number — reporting a plausible wrong number is the failure this fixes. + +use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; + +/// The GPU execution time of one composite, with the refresh it measured. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GpuTiming { + /// Time the GPU spent executing the refresh's command buffers (ms). Excludes queue-level + /// uploads, which run in wgpu's own command buffer ahead of ours, and the end-of-batch work + /// after the last timestamp: see the module doc for the size of that (~5 % here, more on a + /// refresh that uploads). + pub ms: f64, + /// Pixels that refresh composited (so a late measurement stays interpretable). + pub px: u64, + /// Command buffers the refresh submitted (1 unless it flushed). + pub spans: u32, +} + +/// Device features [`GpuTimer`] needs. +pub const FEATURES: wgpu::Features = wgpu::Features::TIMESTAMP_QUERY.union(wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS); + +/// Spans one measurement may hold. A refresh submits once per flush; a 200 MP document flushes a +/// handful of times, so this is far above anything real. A measurement that would exceed it is +/// dropped rather than truncated (a truncated sum is exactly the under-report being fixed). +const SPANS: u32 = 64; +/// Any span total above this is a wrapped or garbage timestamp, not a composite. +const SANE_MS: f64 = 600_000.0; + +/// Readback state of the buffer holding the resolved timestamps. +const UNMAPPED: u8 = 0; +const MAPPED: u8 = 1; +const FAILED: u8 = 2; + +/// Timestamp queries for one compositor, reused for every refresh. +/// +/// At most one measurement is in flight: while the last one is still being read back a refresh +/// goes unmeasured, which costs a sample rather than correctness. +pub struct GpuTimer { + set: wgpu::QuerySet, + /// Resolved timestamps (`QUERY_RESOLVE | COPY_SRC`). + resolve: wgpu::Buffer, + /// Host-visible copy of `resolve` (`MAP_READ | COPY_DST`). + read: wgpu::Buffer, + /// Nanoseconds per timestamp tick, as the queue reports it. + period_ns: f32, + /// Timestamps written into the current recording. + written: u32, + /// Whether a span is open (a start timestamp waiting for its end). + open: bool, + /// Pixels of the recording in progress. + px: u64, + /// The recording overflowed [`SPANS`]: finish without resolving. + overflowed: bool, + /// The recording in progress has already had command buffers submitted (it flushed), so its + /// query slots may still be in use by the GPU. + flushed: bool, + /// A recording was abandoned after it had already submitted timestamps. Writing a query + /// again resets that slot (wgpu-core resets per write), and resetting one an in-flight + /// submission is still writing is undefined, with no way to learn when it has drained. + /// That only happens when a refresh fails after a flush, which on this path means the + /// device faulted and the canvas is about to drop to the CPU compositor anyway, so + /// measuring simply stops: no number, which is the contract everywhere else here. + stopped: bool, + /// Timestamps and pixels of the measurement being read back, and its readback flag. + in_flight: Option<(u32, u64, Arc)>, + /// [`Self::finish`] recorded a readback that [`Self::submitted`] has yet to map. Without + /// this, a refresh that starts before the last measurement lands would map the readback + /// buffer a second time while the first map is still pending, which wgpu rejects. + unmapped: bool, + /// The most recent completed measurement, until a caller takes it. + ready: Option, +} + +impl std::fmt::Debug for GpuTimer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("GpuTimer").field("recording", &self.open).field("in_flight", &self.in_flight.is_some()).field("ready", &self.ready).finish() + } +} + +impl GpuTimer { + /// A timer for `device`, or `None` when it has no timestamp queries (the caller then reports + /// no GPU time, never an estimate). + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option { + if !device.features().contains(FEATURES) { + return None; + } + let period_ns = queue.get_timestamp_period(); + if !period_ns.is_finite() || period_ns <= 0.0 { + return None; + } + let bytes = u64::from(SPANS) * 2 * 8; + Some(Self { + set: device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("pc_compose_time"), ty: wgpu::QueryType::Timestamp, count: SPANS * 2 }), + resolve: device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_compose_time_resolve"), + size: bytes, + usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }), + read: device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_compose_time_read"), + size: bytes, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + period_ns, + written: 0, + open: false, + px: 0, + overflowed: false, + flushed: false, + stopped: false, + in_flight: None, + unmapped: false, + ready: None, + }) + } + + /// Start measuring a refresh of `px` pixels, opening its first span in `encoder`. Does + /// nothing while a previous measurement is still being read back (that refresh goes + /// unmeasured) — call [`Self::collect`] first to give it the chance to land. + pub fn start(&mut self, encoder: &mut wgpu::CommandEncoder, px: u64) { + if self.stopped || self.in_flight.is_some() || self.open { + return; + } + self.written = 0; + self.overflowed = false; + self.flushed = false; + self.px = px; + self.open = true; + self.stamp(encoder); + } + + /// Close the span in `done` and open the next in `next`: one refresh that submits several + /// command buffers is one measurement, summed over them. + pub fn split(&mut self, done: &mut wgpu::CommandEncoder, next: &mut wgpu::CommandEncoder) { + if !self.open { + return; + } + self.stamp(done); + self.stamp(next); + self.flushed = true; + } + + /// Close the last span and record the resolve and readback copy into `encoder`, which the + /// caller is about to submit. Call [`Self::submitted`] once it has. + pub fn finish(&mut self, encoder: &mut wgpu::CommandEncoder) { + if !self.open { + return; + } + self.stamp(encoder); + self.open = false; + let count = self.written; + if self.overflowed || count < 2 || !count.is_multiple_of(2) { + self.abandon(); + return; + } + let bytes = u64::from(count) * 8; + encoder.resolve_query_set(&self.set, 0..count, &self.resolve, 0); + encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, bytes); + self.in_flight = Some((count, self.px, Arc::new(AtomicU8::new(UNMAPPED)))); + self.unmapped = true; + self.written = 0; + // This recording is over: its slots are protected by `in_flight` until the readback + // lands, not by `flushed`. Leaving `flushed` set would let a later refresh that + // recorded nothing (because `start` found the readback still in flight) stop measuring + // for good when it failed, on the strength of this recording's flush. + self.flushed = false; + } + + /// Map the readback buffer after the caller submitted the encoder [`Self::finish`] wrote + /// into. The map completes on a later device poll; nothing blocks here. + pub fn submitted(&mut self) { + if !self.unmapped { + return; + } + self.unmapped = false; + let Some((count, _, flag)) = &self.in_flight else { return }; + let (bytes, flag) = (u64::from(*count) * 8, flag.clone()); + self.read.slice(0..bytes).map_async(wgpu::MapMode::Read, move |r| { + flag.store(if r.is_ok() { MAPPED } else { FAILED }, Ordering::Release); + }); + } + + /// Abandon the recording in progress (the refresh failed part way, so its spans mean + /// nothing). + pub fn cancel(&mut self) { + self.open = false; + self.abandon(); + } + + /// Drop the recording in progress. Once its timestamps have reached the GPU its slots can't + /// be reused safely, so measuring stops for good rather than resetting a live query. + fn abandon(&mut self) { + self.stopped |= self.flushed; + self.written = 0; + self.overflowed = false; + self.flushed = false; + } + + /// Whether a measurement is being read back (so this refresh won't be measured). + pub fn busy(&self) -> bool { + self.in_flight.is_some() + } + + /// Read back a finished measurement if the map completed, and return whatever is ready. + /// Cheap and non-blocking; callers poll it per refresh or per frame. + pub fn collect(&mut self) -> Option { + if let Some((count, px, flag)) = &self.in_flight { + match flag.load(Ordering::Acquire) { + MAPPED => { + let (count, px) = (*count, *px); + self.ready = self.value(count, px); + self.read.unmap(); + self.in_flight = None; + } + FAILED => { + self.in_flight = None; + } + _ => {} + } + } + self.ready + } + + /// Put a measurement back after a caller took it but could not use it (its refresh failed), + /// so the sample is reported by the next one instead of being lost on the fallback path. + /// A measurement that has landed since wins: it is the newer of the two. + pub fn restore(&mut self, t: GpuTiming) { + self.ready.get_or_insert(t); + } + + /// Take the most recent completed measurement, leaving none behind, so a stale number is + /// never reported twice as if it were new. + pub fn take(&mut self) -> Option { + self.collect(); + self.ready.take() + } + + /// Sum the resolved spans of a mapped readback. + fn value(&self, count: u32, px: u64) -> Option { + let bytes = u64::from(count) * 8; + let view = self.read.slice(0..bytes).get_mapped_range().ok()?; + let mut ticks = 0u64; + for pair in view.as_chunks::<16>().0 { + let (a, b) = pair.split_at(8); + let start = u64::from_le_bytes(a.try_into().ok()?); + let end = u64::from_le_bytes(b.try_into().ok()?); + // A driver that reset or wrapped its timer gives an end before its start: the whole + // measurement is then unusable, and no number is better than a wrong one. + if end < start { + return None; + } + ticks += end - start; + } + drop(view); + let ms = ticks as f64 * f64::from(self.period_ns) / 1.0e6; + (ms.is_finite() && ms < SANE_MS).then_some(GpuTiming { ms, px, spans: count / 2 }) + } + + /// Write one timestamp, noting an overflow instead of wrapping round the query set. + fn stamp(&mut self, encoder: &mut wgpu::CommandEncoder) { + if self.written >= SPANS * 2 { + self.overflowed = true; + return; + } + encoder.write_timestamp(&self.set, self.written); + self.written += 1; + } +} diff --git a/crates/gpu/tests/timing.rs b/crates/gpu/tests/timing.rs new file mode 100644 index 0000000000..24c2057253 --- /dev/null +++ b/crates/gpu/tests/timing.rs @@ -0,0 +1,282 @@ +//! The canvas timing must measure GPU *execution*, not encode-and-submit (#7186). +//! +//! `composite_ms` reports the CPU cost of handing the composite to the driver, which on a +//! GPU-bound refresh is a small fraction of what the refresh costs — at 24 MP it read 7.7 ms for +//! work that took ~171 ms. `Compositor::measure_gpu_time` adds timestamp queries whose spans are +//! summed into a [`GpuTiming`]. This test pins that down from both sides: the measurement must +//! track the waited-for wall clock and must be several times the submit time, so an accidental +//! return to timing the submit fails it. +//! +//! **Hardware only.** A software rasteriser composites on the CPU, where submit and execution +//! are the same work, so the whole premise disappears and the test would pass on a bug. It +//! therefore refuses to run on a CPU adapter and says so, as every GPU timing measurement in +//! this project must (egui_kittest's `default_wgpu_setup` prefers CPU adapters on purpose). + +use std::time::Instant; + +use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; +use photocraft_doc::{Document, Layer, Size}; +use photocraft_geom::Rect; +use photocraft_gpu::{Compositor, DeviceHealth, GpuTiming, timing}; + +/// Pixels in `r`, as the compositor counts them. +fn area(r: Rect) -> u64 { + r.width() as u64 * r.height() as u64 +} + +fn block_on(f: F) -> F::Output { + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + let mut f = std::pin::pin!(f); + loop { + if let std::task::Poll::Ready(v) = f.as_mut().poll(&mut cx) { + return v; + } + std::thread::yield_now(); + } +} + +/// A real GPU with timestamp queries, or `None` with the reason printed. +fn gpu() -> Option<(wgpu::Device, wgpu::Queue, Compositor)> { + let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }; + let Ok(adapter) = block_on(wgpu::Instance::default().request_adapter(&options)) else { + eprintln!("SKIP gpu timing: no adapter"); + return None; + }; + let info = adapter.get_info(); + if info.device_type == wgpu::DeviceType::Cpu || info.backend == wgpu::Backend::Noop { + // Not a skip we can be quiet about: a GPU timing test on llvmpipe measures nothing. + eprintln!("SKIP gpu timing: {} is a software adapter, which cannot show a GPU/CPU split", info.name); + return None; + } + if !adapter.features().contains(timing::FEATURES) { + eprintln!("SKIP gpu timing: {} has no timestamp queries", info.name); + return None; + } + let descriptor = wgpu::DeviceDescriptor { required_features: timing::FEATURES, ..Default::default() }; + let Ok((device, queue)) = block_on(adapter.request_device(&descriptor)) else { + eprintln!("SKIP gpu timing: no device with timestamp queries"); + return None; + }; + let mut comp = Compositor::new(&device); + assert!(comp.measure_gpu_time(&device, &queue), "the device has the features, so the timer must build"); + eprintln!("gpu timing on {} ({:?}, {:?})", info.name, info.device_type, info.backend); + Some((device, queue, comp)) +} + +fn rnd(seed: u32, i: u32) -> f32 { + let mut h = seed.wrapping_mul(0x9e37_79b9) ^ i.wrapping_mul(0x85eb_ca6b); + h ^= h >> 13; + h = h.wrapping_mul(0xc2b2_ae35); + h ^= h >> 16; + (h & 0xffff) as f32 / 65535.0 +} + +/// A document whose composite is clearly GPU-bound: several full-canvas blended photo layers. +fn document(size: Size) -> Document { + let mut doc = Document::with_background("timing", size, ColorMode::Rgb, SampleType::U8, Color::rgba(0.5, 0.5, 0.5, 1.0)); + let fmt = doc.pixel_format(); + let rect = Rect::from_xywh(0, 0, size.width, size.height); + for (i, blend) in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Overlay, BlendMode::SoftLight].into_iter().enumerate() { + let mut layer = Layer::raster(format!("l{i}"), fmt); + let channels = fmt.channels(); + let px: Vec = (0..rect.width() * rect.height()).flat_map(|p| (0..channels).map(move |c| rnd(7 + i as u32 * 131 + c as u32 * 7919, p))).collect(); + if let Some(s) = layer.surface_mut() { + s.write_region(rect, &px); + } + layer.blend = blend; + layer.opacity = 0.8; + doc.layers.push(layer); + } + doc +} + +/// Render `region` and return (submit ms, waited-for wall ms, the measurement). +fn measure(device: &wgpu::Device, queue: &wgpu::Queue, comp: &mut Compositor, doc: &Document, region: Rect) -> (f64, f64, Option) { + let t0 = Instant::now(); + comp.render(device, queue, doc, region, |_, _| {}).expect("the document composites on the GPU"); + let submit_ms = t0.elapsed().as_secs_f64() * 1000.0; + let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); + let wall_ms = t0.elapsed().as_secs_f64() * 1000.0; + // The readback map completes on a poll, and its callback runs on the next one. + let mut timing = None; + for _ in 0..4 { + timing = comp.take_gpu_timing(); + if timing.is_some() { + break; + } + let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); + } + (submit_ms, wall_ms, timing) +} + +#[test] +fn gpu_time_tracks_execution_not_submission() { + let Some((device, queue, mut comp)) = gpu() else { return }; + let size = Size::new(3000, 2000); + let doc = document(size); + let full = Rect::from_xywh(0, 0, size.width, size.height); + + // Warm the residency and pipelines: the first refresh uploads every layer. + let _ = measure(&device, &queue, &mut comp, &doc, full); + + // Best of three, by the smallest encode. Everything below is a ratio against `submit_ms`, + // and CPU contention on a shared machine only ever inflates it — one run that happened to + // encode behind a busy scheduler (8.2 ms against a typical 1.0 ms) failed the comparison + // while the measurement itself was right. The GPU side is unaffected by that contention, + // so taking the least-disturbed encode tests the same property without the false failure. + let mut best: Option<(f64, f64, Option)> = None; + for _ in 0..3 { + let run = measure(&device, &queue, &mut comp, &doc, full); + if run.2.is_some() && best.as_ref().is_none_or(|b| run.0 < b.0) { + best = Some(run); + } + } + let (submit_ms, wall_ms, timing) = best.expect("at least one of three refreshes reports a GPU time"); + let t = timing.expect("a hardware device with timestamp queries must report a GPU time"); + eprintln!("full {}x{}: submit {submit_ms:.1} ms, waited wall {wall_ms:.1} ms, gpu {:.1} ms", size.width, size.height, t.ms); + + assert_eq!(t.px, area(full), "the measurement carries the pixels of the refresh it measured"); + assert!(t.spans >= 1, "at least one command buffer was timed"); + + // The premise: on this adapter the refresh really is dominated by GPU execution. A machine + // fast enough that it isn't cannot tell the two timings apart, so say so instead of failing. + if wall_ms < 3.0 * submit_ms { + eprintln!("SKIP the comparison: this GPU finishes a 6 MP composite in {wall_ms:.1} ms against {submit_ms:.1} ms of encoding"); + return; + } + + // Timing the submit again (the bug) would report roughly `submit_ms` here. + assert!(t.ms > 3.0 * submit_ms, "gpu time {:.1} ms looks like the submit time {submit_ms:.1} ms, not the execution", t.ms); + // …and it must be the real execution, not merely a bigger number: the waited-for wall clock + // is encode + execute, so the GPU span sits below it and accounts for most of it. + assert!(t.ms <= wall_ms * 1.25, "gpu time {:.1} ms exceeds the whole waited-for refresh {wall_ms:.1} ms", t.ms); + assert!(t.ms >= (wall_ms - submit_ms) * 0.5, "gpu time {:.1} ms is far below the {:.1} ms the refresh waited", t.ms, wall_ms - submit_ms); + + // A quarter of the canvas is a quarter of the per-pixel work: a constant or a stale value + // would not follow it. + let quarter = Rect::from_xywh(0, 0, size.width / 2, size.height / 2); + let (_, _, small) = measure(&device, &queue, &mut comp, &doc, quarter); + let s = small.expect("the smaller refresh is measured too"); + eprintln!("quarter: gpu {:.1} ms for {} px against {:.1} ms for {} px", s.ms, s.px, t.ms, t.px); + assert_eq!(s.px, area(quarter)); + assert!(s.ms < t.ms * 0.6, "a quarter-canvas refresh took {:.1} ms against the full canvas's {:.1} ms", s.ms, t.ms); +} + +#[test] +fn an_unmeasured_compositor_reports_nothing() { + let Some((device, queue, _)) = gpu() else { return }; + let mut comp = Compositor::new(&device); + assert!(!comp.measures_gpu_time(), "timing is off until it is asked for"); + let doc = document(Size::new(256, 256)); + comp.render(&device, &queue, &doc, Rect::from_xywh(0, 0, 256, 256), |_, _| {}).expect("composites"); + let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); + assert_eq!(comp.take_gpu_timing(), None, "no measurement is reported rather than a wrong one"); +} + +#[test] +fn a_refresh_that_submits_several_times_is_one_measurement() { + let Some((device, queue, mut comp)) = gpu() else { return }; + // A budget far below the document's layer pages makes the refresh evict as it goes, which is + // what makes it submit in batches: the measurement must span all of them, not just the last. + comp.set_memory_budget(24 << 20); + let size = Size::new(3000, 2000); + let doc = document(size); + let full = Rect::from_xywh(0, 0, size.width, size.height); + + let _ = measure(&device, &queue, &mut comp, &doc, full); + let (submit_ms, wall_ms, timing) = measure(&device, &queue, &mut comp, &doc, full); + let t = timing.expect("a batched refresh is measured like any other"); + eprintln!("batched: {} command buffers, gpu {:.1} ms, submit {submit_ms:.1} ms, waited wall {wall_ms:.1} ms", t.spans, t.ms); + assert_eq!(t.px, area(full)); + if t.spans < 2 { + eprintln!("SKIP the sum: this refresh still fit one command buffer"); + return; + } + assert!(t.ms <= wall_ms * 1.25, "summed gpu time {:.1} ms exceeds the whole waited-for refresh {wall_ms:.1} ms", t.ms); + // What this bound excludes is summing only the last command buffer. A correct sum measures + // ~85 % of the waited-for GPU time here; the flush thresholds split on accumulated work, so + // no single buffer of the several carries much over half of it, and timing only the last + // would land near 40 %. 0.6 sits between the two with room on both sides for a machine + // whose split is less even than this one's. + assert!( + t.ms >= (wall_ms - submit_ms) * 0.6, + "summed gpu time {:.1} ms is far below the {:.1} ms the refresh waited: is only the last command buffer timed?", + t.ms, + wall_ms - submit_ms + ); +} + +#[test] +fn refreshes_faster_than_the_readback_stay_valid() { + let Some((device, queue, mut comp)) = gpu() else { return }; + // Refreshes arriving before the last measurement has been read back must simply go + // unmeasured. Mapping the readback buffer again while its first map is still pending is a + // validation error, and an unusable device drops the whole canvas to the CPU compositor. + let health = DeviceHealth::watch(&device); + comp.set_health(health.clone()); + let size = Size::new(600, 400); + let doc = document(size); + let full = Rect::from_xywh(0, 0, size.width, size.height); + for i in 0..16 { + comp.render(&device, &queue, &doc, full, |_, _| {}).unwrap_or_else(|e| panic!("refresh {i} failed: {e}")); + } + let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); + assert_eq!(comp.fault(), None, "hurried refreshes must not fault the device"); + assert_eq!(health.errors(), 0, "no uncaptured wgpu errors"); +} + +/// A refresh that recorded nothing must not stop the timer for good. `finish` leaves the +/// measurement's slots protected by the pending readback, not by `flushed`; if `flushed` +/// survived a successful finish, the next refresh to fail while that readback was still in +/// flight would set `stopped` on the strength of the *earlier* refresh's flush — even though it +/// wrote no timestamps itself — and the compositor would silently never measure again. +#[test] +fn a_failed_refresh_that_recorded_nothing_keeps_the_timer_alive() { + let Some((device, queue, _)) = gpu() else { return }; + let mut timer = timing::GpuTimer::new(&device, &queue).expect("the device has timestamp queries"); + + // A refresh that flushes once, then succeeds. + let mut first = device.create_command_encoder(&Default::default()); + let mut second = device.create_command_encoder(&Default::default()); + timer.start(&mut first, 1024); + timer.split(&mut first, &mut second); + queue.submit([first.finish()]); + timer.finish(&mut second); + queue.submit([second.finish()]); + timer.submitted(); + + // A later refresh fails before recording anything, because the readback is still in flight. + let mut third = device.create_command_encoder(&Default::default()); + timer.start(&mut third, 2048); + timer.cancel(); + drop(third); + + // The first measurement still lands... + let mut first_timing = None; + for _ in 0..8 { + let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); + first_timing = timer.take(); + if first_timing.is_some() { + break; + } + } + let landed = first_timing.expect("the flushed measurement completes"); + assert_eq!(landed.spans, 2, "both command buffers are one measurement"); + + // ...and the timer still measures afterwards, which is what the bug destroyed. + let mut next = device.create_command_encoder(&Default::default()); + timer.start(&mut next, 4096); + timer.finish(&mut next); + queue.submit([next.finish()]); + timer.submitted(); + let mut after = None; + for _ in 0..8 { + let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); + after = timer.take(); + if after.is_some() { + break; + } + } + let after = after.expect("the timer still measures after a refresh that recorded nothing"); + assert_eq!(after.px, 4096, "the measurement belongs to the refresh that produced it"); +} diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 9bd4c559c5..eb8c0b00d7 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -31,6 +31,7 @@ photocraft-text = { workspace = true } photocraft-paint = { workspace = true } photocraft-vector = { workspace = true } photocraft-format = { path = "../format" } +craft-docpath = { workspace = true } thiserror = { workspace = true } serde_json = { workspace = true } blake3 = { version = "1.8", default-features = false, features = ["pure"] } diff --git a/crates/io/src/doc_path.rs b/crates/io/src/doc_path.rs new file mode 100644 index 0000000000..37e7daf214 --- /dev/null +++ b/crates/io/src/doc_path.rs @@ -0,0 +1,59 @@ +//! Files named by paths stored in a document: linked smart objects, the Displace map and Color +//! Lookup file of a smart filter, data-set images, video footage. +//! +//! Such a path is followed only through [`resolve`]: a relative path is taken from the document's +//! folder, and only local files, or files on the network share the document itself is on, are +//! opened (see `craft_docpath`). A refused path is treated like a missing file. + +use std::fmt; +use std::path::{Path, PathBuf}; + +pub use craft_docpath::Refused; + +/// Why a stored path is not followed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NotFollowed { + /// The path is not a local file, or is not on the document's own share. + Refused(Refused), + /// The path is relative and the document has no file to take it from. + NoDocumentFolder, +} + +impl fmt::Display for NotFollowed { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Refused(r) => r.fmt(f), + Self::NoDocumentFolder => f.write_str("the path is relative and the document has not been saved"), + } + } +} + +impl std::error::Error for NotFollowed {} + +/// The file to open for `stored`, a path or `file:` URL stored in a document, or why it is not +/// followed. `document` is the path of the document it is stored in, if the document has a file; +/// a relative `document` is taken from the working directory, where it was opened from. +pub fn resolve(stored: &str, document: Option<&Path>) -> Result { + let document = document.map(|d| if d.is_relative() { std::path::absolute(d).unwrap_or_else(|_| d.to_path_buf()) } else { d.to_path_buf() }); + let path = craft_docpath::resolve(stored, document.as_deref()).map_err(NotFollowed::Refused)?; + // A path that is still relative would be taken from the working directory, which the + // document does not choose. + if path.is_relative() { + return Err(NotFollowed::NoDocumentFolder); + } + Ok(path) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relative_paths_are_taken_from_the_document_folder() { + let doc = std::env::temp_dir().join("art").join("poster.pcraft"); + assert_eq!(resolve("logo.png", Some(&doc)), Ok(std::env::temp_dir().join("art").join("logo.png"))); + assert_eq!(resolve("logo.png", None), Err(NotFollowed::NoDocumentFolder)); + assert_eq!(resolve(r"\\192.0.2.1\share\x.png", Some(&doc)), Err(NotFollowed::Refused(Refused::Network))); + assert_eq!(resolve("//192.0.2.1/share/x.png", None), Err(NotFollowed::Refused(Refused::Network))); + } +} diff --git a/crates/io/src/exr_parts.rs b/crates/io/src/exr_parts.rs index 7e25feb984..3e9d2e1154 100644 --- a/crates/io/src/exr_parts.rs +++ b/crates/io/src/exr_parts.rs @@ -181,7 +181,8 @@ fn layer_surface(img: &Image, max: &mut (u32, u32)) -> Result<(Surface, ColorMod } /// Imports the chosen entries as the layers of one document: parts whole, groups from their -/// own channels, F16 kept losslessly as F32, the linear-light EXR values tagged linear sRGB. +/// own channels, F16 kept losslessly as F32, the linear-light EXR values tagged linear sRGB +/// or linear gray. /// `precomp` adds the additive sum of the file's AOV groups as a top layer and fails, /// naming the missing AOVs, when the light-path set is incomplete. pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result { @@ -270,10 +271,9 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result photocraft_doc::FileEncoding { file_encoding_as(codecs::detect(bytes), bytes) } @@ -78,6 +79,7 @@ fn file_encoding_as(format: Option, bytes: &[u8]) -> photocraft_doc::Fil let mut e = photocraft_doc::FileEncoding::default(); match format { Some(Format::Jpeg) => e.jpeg_quality = codecs::jpeg_quality(bytes), + Some(Format::Png) => e.png_stereo = codecs::png_stereo(bytes).map(codecs::PngStereo::mode), Some(Format::WebP) => match codecs::webp_encoding(bytes) { Some(codecs::WebpEncoding::Lossless) => e.webp_lossless = Some(true), Some(codecs::WebpEncoding::Lossy { quality }) => { @@ -95,8 +97,8 @@ fn file_encoding_as(format: Option, bytes: &[u8]) -> photocraft_doc::Fil pub const DEFAULT_LOSSY_WEBP_QUALITY: u8 = 75; /// Applies the settings `doc`'s file was encoded with (see [`file_encoding`]) to `opts`: what a -/// save that chose no quality writes, so a JPEG keeps its quality and a WebP stays lossy or -/// lossless. +/// save that chose no quality writes, so a JPEG keeps its quality, a WebP stays lossy or lossless, +/// and a stereo PNG keeps its `sTER` pairing (#6063). pub fn apply_file_encoding(doc: &Document, opts: &mut codecs::EncodeOptions) { let e = &doc.file_encoding; if let Some(q) = e.jpeg_quality { @@ -108,6 +110,7 @@ pub fn apply_file_encoding(doc: &Document, opts: &mut codecs::EncodeOptions) { if let Some(q) = e.webp_quality { opts.webp_quality = q.min(100); } + opts.png_stereo = e.png_stereo.and_then(codecs::PngStereo::from_mode); } /// Photoshop opens a 32-bit Targa as an opaque Background plus an "Alpha 1" channel holding the @@ -241,6 +244,11 @@ pub(crate) fn image_to_document(name: &str, img: &Image) -> Result, color: usize, alpha: usize) { } /// Whether every pixel of `s` over `r` is fully opaque (read from the tiles, no copy). -fn opaque_surface(s: &Surface, r: Rect) -> bool { +pub(crate) fn opaque_surface(s: &Surface, r: Rect) -> bool { let fmt = s.format(); let (ch, bps) = (fmt.channels(), fmt.sample.bytes()); let a = ch - 1; @@ -559,9 +567,10 @@ pub(crate) fn export_flat_with(doc: &Document, format: Format, opts: &ExportOpti } else if let Some(linear) = convert_gray(&img, photocraft_cms::builtin::linear_gray(), CSample::F32)? { img = linear; } - } else if !format.caps().icc { - // Untagged files read back as sRGB/sGray: convert to it (as Quick Export does) rather than - // write values that only mean something under the dropped profile. + } else if !format.caps().icc || (img.layout().is_gray() && !format.caps().layouts.iter().any(|l| l.is_gray())) { + // Untagged files read back as sRGB/sGray. Even an ICC-capable format like WebP loses a + // gray profile when the codec expands gray to RGB. Convert first (as Quick Export does) + // rather than write values that only mean something under the dropped profile. if let Some(srgb) = convert_rgb(&img, Builtin::Srgb.profile(), Intent::Perceptual, true, img.sample_type())? { img = srgb; warnings.push(format!("colours converted to sRGB; {format:?} can't embed the document's colour profile")); @@ -809,17 +818,27 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> match doc.mode { ColorMode::Indexed if format == Format::Png => { let Some(table) = doc.color_table.as_ref().filter(|t| !t.colors.is_empty() && t.colors.len() <= 256) else { return Ok(None) }; + // PNG transparency belongs to a palette index, not its RGB value. Keep the + // transparent entry out of opaque lookup, even when it duplicates an opaque colour. + let (opaque_indices, colors): (Vec, Vec<_>) = + table.colors.iter().copied().enumerate().filter(|(i, _)| Some(*i) != table.transparent.map(usize::from)).map(|(i, c)| (i as u8, c)).unzip(); + let opaque = photocraft_doc::ColorTable { colors, transparent: None }; let mut idx = try_buffer(doc.size.area() as usize, 1)?; - let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), ()> { - idx.extend(band.px.iter().map(|p| match table.transparent { - Some(t) if p[3] < 0.5 => t, - _ => table.nearest([p[0], p[1], p[2]]) as u8, - })); + photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), IoError> { + for p in &band.px { + let i = match table.transparent { + Some(t) if p[3] < 0.5 => t, + _ => *opaque_indices + .get(opaque.nearest([p[0], p[1], p[2]])) + .ok_or_else(|| IoError::Unsupported("Indexed PNG palette has no opaque entry; add an opaque colour or convert to RGB".into()))?, + }; + idx.push(i); + } Ok(()) - }); + })?; // Same rule as the ordinary PNG encoder: the resolution goes into `pHYs` with the metadata. let dpi = opts.encode.embed_metadata.then_some((doc.resolution_dpi, doc.resolution_dpi)); - let bytes = codecs::encode_png_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, dpi)?; + let bytes = codecs::encode_png_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, dpi, opts.encode.png_stereo)?; let mut warnings = vec![format!("written as an 8-bit palette PNG ({} colours)", table.colors.len())]; if opts.encode.embed_metadata && opts.xmp == XmpEmbed::All && !doc.metadata.text.is_empty() { warnings.push("text metadata is not supported by the palette PNG exporter; it will be dropped".into()); diff --git a/crates/io/src/guides_map.rs b/crates/io/src/guides_map.rs new file mode 100644 index 0000000000..6137011e2c --- /dev/null +++ b/crates/io/src/guides_map.rs @@ -0,0 +1,157 @@ +//! Guides ⇄ PSD beyond image resource 1032. +//! +//! Photoshop writes two undocumented resources next to 1032 (Grid and Guides), layout +//! inferred from the psd-tools, ag-psd and Photoshop-authored corpora (#5965): +//! +//! * 1092, Grid and Guides version 2: `u32` version 2, `u32` horizontal and vertical grid +//! cycle (576 = 18 px in 1/32 px, as in 1032), `u32` count, then per guide 9 bytes: `i32` +//! position in 1/32 px, `u8` direction (0 vertical, 1 horizontal), one `u8` that is always 0 +//! in the corpora, and the guide's colour as `u8` R, G, B. In every corpus file its guides +//! equal 1032's, in the same order. +//! * 1097: `u32` count (1092's), then per guide a length-prefixed ASCII GUID, a `u32` 0 and a +//! second length-prefixed GUID, always all zeros. +//! +//! Import takes the guides' own colours from 1092 (a guide in Photoshop's default colour keeps +//! following the preference colour). Export keeps both resources only while 1092 still +//! describes the document's guides and colours; otherwise it leaves both out, so the file +//! carries 1032 alone, as Photoshop files before version 2 did (#5966). + +use photocraft_doc::{Document, Guides}; + +/// Grid and Guides, version 2 (positions, directions and colours). +pub const GUIDES_V2: u16 = 1092; +/// One GUID per guide, in 1092's order. +pub const GUIDE_IDS: u16 = 1097; +/// Photoshop's default guide colour (Cyan, `#4affff`), which 1092 also stores for guides +/// that use the preference colour. +pub const DEFAULT_GUIDE_RGB: [u8; 3] = [0x4a, 0xff, 0xff]; + +/// One guide of a 1092 resource. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct GuideV2 { + /// Position in 1/32 px. + pub location: i32, + pub vertical: bool, + pub rgb: [u8; 3], +} + +fn be_u32(data: &[u8], at: usize) -> Option { + let b = data.get(at..at.checked_add(4)?)?; + Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]])) +} + +/// The guides of a 1092 resource, or `None` when it is not version 2 or is cut short. +pub fn parse_v2(data: &[u8]) -> Option> { + if be_u32(data, 0)? != 2 { + return None; + } + let count = usize::try_from(be_u32(data, 12)?).ok()?; + // Each guide takes 9 bytes: a count the data can't hold is not a 1092 we understand. + if count > data.len().saturating_sub(16) / 9 { + return None; + } + (0..count) + .map(|i| { + let at = 16 + i * 9; + let g = data.get(at..at + 9)?; + Some(GuideV2 { location: i32::from_be_bytes([g[0], g[1], g[2], g[3]]), vertical: g[4] != 1, rgb: [g[6], g[7], g[8]] }) + }) + .collect() +} + +/// The number of entries a 1097 resource declares. +pub fn ids_count(data: &[u8]) -> Option { + be_u32(data, 0) +} + +/// The document's guides as 1092 would store them, sorted. +fn expected(guides: &Guides) -> Vec { + let mut v: Vec = [(&guides.vertical, true), (&guides.horizontal, false)] + .into_iter() + .flat_map(|(list, vertical)| { + list.iter().map(move |&p| GuideV2 { location: (p * 32.0).round() as i32, vertical, rgb: guides.color(vertical, p).unwrap_or(DEFAULT_GUIDE_RGB) }) + }) + .collect(); + v.sort(); + v +} + +/// Whether an imported 1092 still describes the document's guides: the same positions, +/// directions and colours, in any order. +pub fn describes(doc: &Document, data: &[u8]) -> bool { + let Some(mut stored) = parse_v2(data) else { return false }; + stored.sort(); + stored == expected(&doc.guides) +} + +/// Whether to write back an imported 1092 or 1097: only while 1092 describes the guides +/// (and, for 1097, holds as many entries as 1092). +pub fn keep_resource(doc: &Document, id: u16, data: &[u8]) -> bool { + match id { + GUIDES_V2 => describes(doc, data), + GUIDE_IDS => { + let v2 = doc.metadata.psd_resources.iter().find(|(rid, _, _)| *rid == GUIDES_V2); + v2.is_some_and(|(_, _, d)| describes(doc, d) && parse_v2(d).map(|g| g.len()).and_then(|n| u32::try_from(n).ok()) == ids_count(data)) + } + _ => true, + } +} + +/// Gives the document's guides the colours an imported 1092 stores. Only guides that 1032 +/// also has are coloured, and Photoshop's default colour is left to the preference. +pub fn apply_colors(doc: &mut Document) { + let Some(stored) = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == GUIDES_V2).and_then(|(_, _, d)| parse_v2(d)) else { + return; + }; + for g in stored { + if g.rgb == DEFAULT_GUIDE_RGB { + continue; + } + let pos = f64::from(g.location) / 32.0; + let list = if g.vertical { &doc.guides.vertical } else { &doc.guides.horizontal }; + if list.contains(&pos) { + doc.guides.set_color(g.vertical, pos, Some(g.rgb)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v2(guides: &[(i32, u8, [u8; 3])]) -> Vec { + let mut v = Vec::new(); + for n in [2u32, 576, 576, guides.len() as u32] { + v.extend_from_slice(&n.to_be_bytes()); + } + for (loc, dir, rgb) in guides { + v.extend_from_slice(&loc.to_be_bytes()); + v.extend_from_slice(&[*dir, 0]); + v.extend_from_slice(rgb); + } + v + } + + #[test] + fn parses_corpus_layout() { + // clipping-mask4.psd (psd-tools): one vertical and one horizontal guide at 16 px. + let d = v2(&[(512, 0, DEFAULT_GUIDE_RGB), (512, 1, DEFAULT_GUIDE_RGB)]); + let g = parse_v2(&d).unwrap(); + assert_eq!(g.len(), 2); + assert!(g[0].vertical && !g[1].vertical); + assert_eq!(g[1].location, 512); + } + + #[test] + fn rejects_other_versions_and_short_or_hostile_data() { + let mut d = v2(&[(512, 0, DEFAULT_GUIDE_RGB)]); + assert!(parse_v2(&d[..d.len() - 1]).is_none()); + d[3] = 1; + assert!(parse_v2(&d).is_none()); + let mut huge = v2(&[]); + huge[12..16].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(parse_v2(&huge).is_none()); + assert!(parse_v2(&[]).is_none()); + assert!(ids_count(&[0, 0]).is_none()); + } +} diff --git a/crates/io/src/kra/tests.rs b/crates/io/src/kra/tests.rs index 4316a74c10..92e951cdb8 100644 --- a/crates/io/src/kra/tests.rs +++ b/crates/io/src/kra/tests.rs @@ -28,7 +28,8 @@ fn tile_file(pixel_size: usize, tiles: &[(i32, i32, Vec)]) -> Vec { planar[k * n + p] = px[p * pixel_size + k]; } } - let body: Vec = if i % 2 == 1 { [vec![1], lzf_literal(&planar)].concat() } else { [vec![0], planar].concat() }; + // Krita splits only LZF tiles into byte planes; raw tiles stay interleaved. + let body: Vec = if i % 2 == 1 { [vec![1], lzf_literal(&planar)].concat() } else { [&[0][..], px].concat() }; out.extend(format!("{x},{y},LZF,{}\n", body.len()).into_bytes()); out.extend(body); } @@ -160,6 +161,22 @@ fn a_nonzero_default_pixel_fills_untouched_areas() { assert_eq!(s.to_interleaved(Rect::from_xywh(100, 100, 1, 1)), [0, 0, 255, 255]); } +#[test] +fn raw_tiles_hold_interleaved_pixels() { + // Krita writes a tile uncompressed (flag 0) when LZF can't shrink it, and then the pixels + // stay interleaved: only LZF tiles are split into byte planes. + let mut body = vec![0u8]; + body.extend((0..T * T).flat_map(|_| [10u8, 20, 30, 255])); + let mut file = format!("VERSION 2\nTILEWIDTH {T}\nTILEHEIGHT {T}\nPIXELSIZE 4\nDATA 1\n0,0,LZF,{}\n", body.len()).into_bytes(); + file.extend(body); + let doc = maindoc("RGBA", r#""#); + let r = crate::import("a.kra", &archive(&doc, &[("img/layers/l", file)])).unwrap(); + let s = layer(&r.document, "L").surface().unwrap(); + for (x, y) in [(0, 0), (1, 0), (3, 3)] { + assert_eq!(s.to_interleaved(Rect::from_xywh(x, y, 1, 1)), [30, 20, 10, 255], "pixel {x},{y}"); + } +} + fn merged_png() -> Vec { let img = Image::from_raw(12, 8, ChannelLayout::Rgba, CSample::U8, vec![90; 12 * 8 * 4]).unwrap(); photocraft_codecs::encode(&img, Format::Png, &Default::default()).unwrap() diff --git a/crates/io/src/kra/tiles.rs b/crates/io/src/kra/tiles.rs index 8af6638aa8..67fd02fca5 100644 --- a/crates/io/src/kra/tiles.rs +++ b/crates/io/src/kra/tiles.rs @@ -231,19 +231,22 @@ impl<'a> TileFile<'a> { for &(x, y, data) in &self.tiles { ctl.check().map_err(|_| IoError::Cancelled)?; let (flag, payload) = data.split_first().ok_or_else(|| invalid("empty tile"))?; - let planar: std::borrow::Cow<'_, [u8]> = match flag { - 1 => lzf_decompress(payload, expected)?.into(), - 0 if payload.len() == expected => payload.into(), - 0 => return Err(invalid("raw tile has the wrong size")), - f => return Err(invalid(format!("unknown tile compression flag {f}"))), - }; - // Byte planes: byte k of pixel i is at k * n + i. - for (k, plane) in planar.chunks_exact(n).enumerate() { - for (i, b) in plane.iter().enumerate() { - if let Some(slot) = interleaved.get_mut(i * self.pixel_size + k) { - *slot = *b; + match flag { + 1 => { + // LZF tiles hold byte planes: byte k of pixel i is at k * n + i. + let planar = lzf_decompress(payload, expected)?; + for (k, plane) in planar.chunks_exact(n).enumerate() { + for (i, b) in plane.iter().enumerate() { + if let Some(slot) = interleaved.get_mut(i * self.pixel_size + k) { + *slot = *b; + } + } } } + // Raw tiles (written when LZF doesn't shrink them) are already interleaved. + 0 if payload.len() == expected => interleaved.copy_from_slice(payload), + 0 => return Err(invalid("raw tile has the wrong size")), + f => return Err(invalid(format!("unknown tile compression flag {f}"))), } space.convert(&interleaved, fmt, &mut out); let (x0, y0) = diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 24b8b3f948..f604b8c174 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -40,10 +40,12 @@ pub mod blocks; pub mod camera_raw_xmp; mod channel_map; pub mod comps_map; +pub mod doc_path; pub mod effects_map; pub mod exr_parts; mod flat; mod gradient_bake; +pub mod guides_map; pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient}; mod kra; pub mod linked; @@ -66,9 +68,9 @@ pub mod text_styles_map; pub mod tiff_layers; pub mod vector_map; -pub use photocraft_codecs::DpxBits; use photocraft_codecs::{CodecError, EncodeOptions}; -use photocraft_doc::Document; +pub use photocraft_codecs::{DdsCompression, DdsOptions, DpxBits}; +use photocraft_doc::{Adjustment, Document, Layer, LayerContent}; use photocraft_psd::{PsdError, PsdFile}; pub use adjust_map::ADJUSTMENT_KEYS; @@ -139,6 +141,34 @@ pub(crate) fn unequal_resolution_warning(x: f64, y: f64) -> Option { .then(|| format!("the vertical resolution ({y:.2} ppi) differs from the horizontal ({x:.2} ppi); the document keeps {x:.2} ppi for both")) } +/// Warnings about a loaded document's layers that render without their stored effect, for +/// sources that carry no import warnings of their own (a crafted `.pcraft`): a Color Lookup +/// whose table can't be applied silently renders as the identity instead (#1763). +pub fn open_warnings(doc: &Document) -> Vec { + let mut out = Vec::new(); + // Iterative, so no document's nesting can make this recurse. + let mut stack: Vec<&Layer> = doc.layers.iter().rev().collect(); + while let Some(l) = stack.pop() { + if let LayerContent::Adjustment(Adjustment::ColorLookup { name: _, size, lut, .. }) = &l.content { + match lut.as_deref().zip(photocraft_doc::adjust::lut3d_len(*size)) { + Some((table, len)) if table.len() >= len => {} + Some((table, len)) => out.push(format!( + "layer \"{}\": its Color Lookup table has {} values, but a {size}³ lookup needs {len}; the layer renders without the lookup", + l.name, + table.len() + )), + None => { + out.push(format!("layer \"{}\": its Color Lookup has no usable table for a {size}³ lookup; the layer renders without the lookup", l.name)) + } + } + } + if let Some(children) = l.children() { + stack.extend(children.iter().rev()); + } + } + out +} + /// Result of [`export`]. #[derive(Debug, Clone)] pub struct ExportResult { @@ -187,6 +217,9 @@ pub struct ExportOptions { /// File Compatibility (see [`PsdExportOptions::maximize_compatibility`]). On by default, as /// Photoshop's Always. pub psd_maximize_compatibility: bool, + /// The path of the document's own file, which linked smart objects that PSD/PSB and layered + /// TIFF embed are resolved against ([`doc_path::resolve`]). + pub document_path: Option, } impl Default for ExportOptions { @@ -199,6 +232,7 @@ impl Default for ExportOptions { tga_bits: None, image_previews: true, psd_maximize_compatibility: true, + document_path: None, } } } @@ -271,7 +305,8 @@ pub fn import_with_svg_group_depth_and_interrupt( fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, max_group_depth: usize) -> Result { // A declared native extension must reach its loader so malformed bundles retain format errors. if has_extension(name, photocraft_format::EXTENSION) || photocraft_format::is_pcraft(bytes) { - return Ok(ImportResult { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new(), source_read_only: false, preview_only: false }); + let document = photocraft_format::load_from_bytes(bytes)?; + return Ok(ImportResult { warnings: open_warnings(&document), document, source_read_only: false, preview_only: false }); } if is_psd(bytes) { // A merged image the import reads is decoded with the parse: a ZIP one is inflated once. @@ -411,7 +446,12 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & return Ok(ExportResult { bytes: photocraft_format::save_to_bytes(doc.as_ref(), &previews)?, warnings: Vec::new() }); } if ext == "psd" || ext == "psb" { - let o = PsdExportOptions { force_psb: opts.force_psb || ext == "psb", maximize_compatibility: opts.psd_maximize_compatibility, ..Default::default() }; + let o = PsdExportOptions { + force_psb: opts.force_psb || ext == "psb", + maximize_compatibility: opts.psd_maximize_compatibility, + document_path: opts.document_path.clone(), + ..Default::default() + }; let (mut file, mut warnings) = with_span(ctl, 0.0, PSD_MODEL_DONE, |ctl| psd_export::document_to_psd_interruptible(doc, &o, ctl)); // A cancelled conversion stops early with an incomplete model: never write it. ctl.check().map_err(|_| IoError::Cancelled)?; diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs index 42b2ab7a33..6d1bcfd87f 100644 --- a/crates/io/src/ora.rs +++ b/crates/io/src/ora.rs @@ -258,9 +258,23 @@ fn props(node: roxmltree::Node<'_, '_>, layer: &mut Layer, index: usize, warning Ok(()) } +/// OpenRaster 0.0.6 defaults to isolated groups and makes `auto` explicitly pass-through. +/// Older files used inference from the group's blend mode; keep that behavior when the +/// version is absent or unrecognized, too. Compare the numeric core, not version strings. +fn uses_explicit_group_isolation(version: Option<&str>) -> bool { + let Some(core) = version.and_then(|v| v.trim().split(['-', '+']).next()) else { return false }; + let mut parts = core.split('.'); + let number = |part: Option<&str>| part.and_then(|s| s.parse::().ok()); + match (number(parts.next()), number(parts.next()), number(parts.next()), parts.next()) { + (Some(major), Some(minor), Some(patch), None) => [major, minor, patch] >= [0, 0, 6], + _ => false, + } +} + struct Reader<'a, 'c> { zip: ZipReader<'a>, ctl: &'c Interrupt<'c>, + explicit_group_isolation: bool, nodes: usize, budget: usize, warnings: Warnings, @@ -325,10 +339,15 @@ impl Reader<'_, '_> { "stack" => { let mut layer = Layer::group("", Vec::new()); props(child, &mut layer, index, &mut self.warnings)?; - // `auto` (the default) isolates only when something needs it: an - // OpenRaster group without its own blend mode is a pass-through group. - let isolate = child.attribute("isolation").map(str::trim) == Some("isolate"); - if !isolate && layer.blend == BlendMode::Normal { + let isolation = child.attribute("isolation").map(str::trim); + let pass_through = if self.explicit_group_isolation { + // Since 0.0.6 only explicit `auto` passes through, ignoring the + // group's composite-op. An omitted isolation means `isolate`. + isolation == Some("auto") + } else { + isolation != Some("isolate") && layer.blend == BlendMode::Normal + }; + if pass_through { layer.blend = BlendMode::PassThrough; } let children = self.stack(child, depth + 1)?; @@ -415,7 +434,15 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result"))?; - let mut reader = Reader { zip, ctl, nodes: 0, budget: MAX_PIXEL_BYTES, warnings: Warnings::default(), images: Vec::new() }; + let mut reader = Reader { + zip, + ctl, + explicit_group_isolation: uses_explicit_group_isolation(image.attribute("version")), + nodes: 0, + budget: MAX_PIXEL_BYTES, + warnings: Warnings::default(), + images: Vec::new(), + }; let nodes = reader.stack(root, 1)?; ctl.progress(0.8); let depth = document_depth(&reader.images); @@ -539,6 +566,15 @@ impl Writer<'_> { if layer.locks.all || layer.locks.pixels { attrs.push_str(" edit-locked=\"true\""); } + // OpenRaster's one edit lock reopens as Lock All; it has no position lock (#7018). + if layer.locks.pixels && !layer.locks.all { + self.warnings.layer(&layer.name, "Lock Image Pixels was saved as OpenRaster's edit lock; it reopens as Lock All"); + } + // The Background's position lock is part of being the Background, not one the user set: + // every new document has it, and OpenRaster has no Background to keep it on. + if layer.locks.position && !layer.locks.all && !self.doc.is_background(layer.id) { + self.warnings.layer(&layer.name, "Lock Position is not saved to OpenRaster"); + } if layer.locks.transparency { attrs.push_str(" alpha-preserve=\"true\""); } diff --git a/crates/io/src/ora/tests.rs b/crates/io/src/ora/tests.rs index 319414a94d..c7c253ef29 100644 --- a/crates/io/src/ora/tests.rs +++ b/crates/io/src/ora/tests.rs @@ -205,6 +205,84 @@ fn gray16_png(w: u32, h: u32) -> Vec { codecs::encode(&Image::from_raw(w, h, ChannelLayout::Gray, CSample::U16, data).unwrap(), Format::Png, &Default::default()).unwrap() } +/// A green Multiply layer over a red backdrop distinguishes isolation (green) from +/// pass-through (black), even though both groups use Normal compositing by default. +fn group_isolation_document(version: Option<&str>, attributes: &str, depth: SampleType) -> Document { + let version = version.map(|v| format!("version=\"{v}\"")).unwrap_or_default(); + let xml = format!( + r#" + + + + + "# + ); + let fmt = PixelFormat::new(ColorMode::Rgb, depth, true); + let png = |rgba| { + let image = Image::from_raw(1, 1, ChannelLayout::Rgba, csample(depth), px(fmt, rgba)).unwrap(); + codecs::encode(&image, Format::Png, &Default::default()).unwrap() + }; + let bytes = archive(&xml, &[("green.png", png([0.0, 1.0, 0.0, 1.0])), ("red.png", png([1.0, 0.0, 0.0, 1.0]))]); + let result = crate::import("isolation.ora", &bytes).unwrap(); + assert!(result.warnings.is_empty(), "{:?}", result.warnings); + assert_eq!(result.document.depth, depth); + result.document +} + +#[test] +fn omitted_group_isolation_defaults_to_isolated_since_version_0_0_6() { + for depth in [SampleType::U8, SampleType::U16] { + for version in ["0.0.6", " 0.0.6 ", "0.0.6+app.1", "0.0.6-rc.1", "0.0.10", "0.1.0", "1.0.0"] { + let d = group_isolation_document(Some(version), "", depth); + assert_eq!(d.layers[1].blend, BlendMode::Normal, "{version}, {depth:?}"); + assert_eq!(photocraft_compose::flatten(&d).px, [[0.0, 1.0, 0.0, 1.0]], "{version}, {depth:?}"); + } + } +} + +#[test] +fn explicit_group_isolation_preserves_isolate_and_auto() { + for depth in [SampleType::U8, SampleType::U16] { + for version in ["0.0.3", "0.0.5", "0.0.6"] { + for (attributes, blend, expected) in [ + ("isolation=' isolate '", BlendMode::Normal, [0.0, 1.0, 0.0, 1.0]), + ("isolation=' auto '", BlendMode::PassThrough, [0.0, 0.0, 0.0, 1.0]), + ("isolation='isolate' composite-op='svg:multiply'", BlendMode::Multiply, [0.0, 0.0, 0.0, 1.0]), + ] { + let d = group_isolation_document(Some(version), attributes, depth); + assert_eq!(d.layers[1].blend, blend, "{version}, {attributes}, {depth:?}"); + assert_eq!(photocraft_compose::flatten(&d).px, [expected], "{version}, {attributes}, {depth:?}"); + } + } + } +} + +#[test] +fn auto_group_ignores_its_composite_op_since_version_0_0_6() { + for depth in [SampleType::U8, SampleType::U16] { + let d = group_isolation_document(Some("0.0.6"), "isolation='auto' composite-op='svg:screen'", depth); + assert_eq!(d.layers[1].blend, BlendMode::PassThrough); + assert_eq!(photocraft_compose::flatten(&d).px, [[0.0, 0.0, 0.0, 1.0]], "{depth:?}"); + } +} + +#[test] +fn legacy_group_isolation_keeps_inference_from_blend_mode() { + for depth in [SampleType::U8, SampleType::U16] { + for version in [None, Some("0.0.3"), Some("0.0.5"), Some("unknown"), Some("0.0"), Some("0.0.6.0")] { + for (attributes, blend, expected) in [ + ("", BlendMode::PassThrough, [0.0, 0.0, 0.0, 1.0]), + ("composite-op='svg:screen'", BlendMode::Screen, [1.0, 1.0, 0.0, 1.0]), + ("isolation='auto' composite-op='svg:screen'", BlendMode::Screen, [1.0, 1.0, 0.0, 1.0]), + ] { + let d = group_isolation_document(version, attributes, depth); + assert_eq!(d.layers[1].blend, blend, "{version:?}, {attributes}, {depth:?}"); + assert_eq!(photocraft_compose::flatten(&d).px, [expected], "{version:?}, {attributes}, {depth:?}"); + } + } + } +} + #[test] fn reads_other_applications_stacks() { // The shapes Krita, MyPaint and GIMP write: a root stack with attributes, `auto` @@ -416,6 +494,9 @@ fn lossy_documents() -> Vec<(&'static str, Document)> { }), ("clipped", with(&|d| d.layers[1].clipped = true)), ("fill opacity", with(&|d| d.layers[0].fill_opacity = 0.5)), + ("pixel lock", with(&|d| d.layers[0].locks.pixels = true)), + // Not the bottom layer: with its transparency lock, `Base` would become the Background. + ("position lock", with(&|d| d.layers[1].locks.position = true)), ("float", doc(SampleType::F32)), ("profile", with(&|d| d.icc_profile = Some(photocraft_cms::Builtin::DisplayP3.profile().to_bytes()))), ("metadata", with(&|d| d.metadata.xmp = Some("".into()))), @@ -442,6 +523,15 @@ fn plain_documents_lose_nothing() { d.icc_profile = Some(photocraft_cms::Builtin::Srgb.profile().to_bytes()); assert_eq!(losses(&d), Vec::::new(), "{depth:?} tagged sRGB"); assert_eq!(export(&d).unwrap().warnings, Vec::::new()); + // OpenRaster's edit-locked and alpha-preserve hold Lock All and Lock Transparent Pixels. + d.layers[0].locks.all = true; + d.layers[1].locks.transparency = true; + assert_eq!(losses(&d), Vec::::new(), "{depth:?} locked"); + // A Background (every new document's bottom layer) loses nothing for its position lock. + d.layers[0].locks.all = false; + d.layers[0].locks.position = true; + assert!(d.background().is_some()); + assert_eq!(losses(&d), Vec::::new(), "{depth:?} Background"); } let mut cmyk = doc(SampleType::U8); cmyk.mode = ColorMode::Cmyk; diff --git a/crates/io/src/pixels.rs b/crates/io/src/pixels.rs index 0167eb3b3f..0251f83755 100644 --- a/crates/io/src/pixels.rs +++ b/crates/io/src/pixels.rs @@ -43,40 +43,43 @@ pub fn interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: Sampl let ch = planes.len(); let row = ch * bps; let mut out = vec![0u8; n * row]; - // One band of rows per core, written straight into its slice of the shared output: the - // per-pixel channel loop stays, but a band holds ~1/cores of a 20 MP image's iterations - // instead of all of them. + if out.is_empty() { + return out; + } let bs = bands(n); - let parts: Vec> = par_map(bs.clone(), |band| { - let mut part = vec![0u8; band.len() * row]; - for (i, p) in band.clone().enumerate() { - for (c, plane) in planes.iter().enumerate() { - let dst = &mut part[(i * ch + c) * bps..(i * ch + c + 1) * bps]; - match plane { - Some(pl) if pl.len() >= (p + 1) * bps => { - let src = &pl[p * bps..(p + 1) * bps]; - for k in 0..bps { - dst[k] = src[bps - 1 - k]; - } - if cfg!(target_endian = "big") { - dst.copy_from_slice(src); - } - if invert[c] { - invert_sample(dst, s); - } - } - _ => dst.copy_from_slice(&fill[c]), - } + let step = bs.first().map_or(n, |b| b.len()) * row; + par_map(bs.into_iter().zip(out.chunks_mut(step)).collect(), |(band, part)| { + for (c, plane) in planes.iter().enumerate() { + let src = plane.and_then(|p| p.get(band.start * bps..)).unwrap_or_default(); + let inv = src.len() >= bps && invert[c]; + let fill = fill.get(c).map(Vec::as_slice).unwrap_or_default(); + match s { + SampleType::U8 => write_channel(part, ch, c, src, fill, |[v]| [if inv { 255 - v } else { v }]), + SampleType::U16 => write_channel(part, ch, c, src, fill, |v| { + let v = u16::from_be_bytes(v); + (if inv { 65535 - v } else { v }).to_ne_bytes() + }), + SampleType::F32 => write_channel(part, ch, c, src, fill, |v| { + // Preserve float bits when no inversion is requested. + if inv { (1.0 - f32::from_be_bytes(v)).to_ne_bytes() } else { u32::from_be_bytes(v).to_ne_bytes() } + }), } } - part }); - for (band, part) in bs.into_iter().zip(parts) { - out[band.start * row..band.end * row].copy_from_slice(&part); - } out } +fn write_channel(out: &mut [u8], ch: usize, c: usize, src: &[u8], fill: &[u8], decode: impl Fn([u8; N]) -> [u8; N]) { + let mut samples = src.as_chunks::().0.iter(); + for pixel in out.chunks_exact_mut(ch * N) { + let dst = &mut pixel[c * N..(c + 1) * N]; + match samples.next() { + Some(sample) => dst.copy_from_slice(&decode(*sample)), + None => dst.copy_from_slice(fill), + } + } +} + /// Splits interleaved native-endian bytes into big-endian planes. pub fn deinterleave(bytes: &[u8], ch: usize, s: SampleType, invert: &[bool]) -> Vec> { let bps = s.bytes(); @@ -217,21 +220,29 @@ pub fn bands(n: usize) -> Vec> { mod tests { use super::*; - #[test] - fn banded_shuffles_match_a_sequential_reference() { - fn seq_interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: SampleType, invert: &[bool]) -> Vec { - let bps = s.bytes(); - let ch = planes.len(); - let mut out = vec![0u8; n * ch * bps]; - for (c, plane) in planes.iter().enumerate() { - for i in 0..n { - let dst = &mut out[(i * ch + c) * bps..(i * ch + c + 1) * bps]; + pub(super) fn previous_interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: SampleType, invert: &[bool]) -> Vec { + let bps = s.bytes(); + let ch = planes.len(); + let row = ch * bps; + let mut out = vec![0u8; n * row]; + // One band of rows per core, written straight into its slice of the shared output: the + // per-pixel channel loop stays, but a band holds ~1/cores of a 20 MP image's iterations + // instead of all of them. + let bs = bands(n); + let parts: Vec> = par_map(bs.clone(), |band| { + let mut part = vec![0u8; band.len() * row]; + for (i, p) in band.clone().enumerate() { + for (c, plane) in planes.iter().enumerate() { + let dst = &mut part[(i * ch + c) * bps..(i * ch + c + 1) * bps]; match plane { - Some(p) if p.len() >= (i + 1) * bps => { - let src = &p[i * bps..(i + 1) * bps]; + Some(pl) if pl.len() >= (p + 1) * bps => { + let src = &pl[p * bps..(p + 1) * bps]; for k in 0..bps { dst[k] = src[bps - 1 - k]; } + if cfg!(target_endian = "big") { + dst.copy_from_slice(src); + } if invert[c] { invert_sample(dst, s); } @@ -240,8 +251,16 @@ mod tests { } } } - out + part + }); + for (band, part) in bs.into_iter().zip(parts) { + out[band.start * row..band.end * row].copy_from_slice(&part); } + out + } + + #[test] + fn banded_shuffles_match_a_sequential_reference() { fn seq_deinterleave(bytes: &[u8], ch: usize, s: SampleType, invert: &[bool]) -> Vec> { let bps = s.bytes(); let n = bytes.len() / (ch * bps).max(1); @@ -260,16 +279,17 @@ mod tests { planes } // Odd pixel counts cross band boundaries; a missing plane exercises the fill path. - for n in [1usize, 7, 64, 1000] { + for n in [0usize, 1, 7, 64, 1000] { for s in [SampleType::U8, SampleType::U16, SampleType::F32] { let bps = s.bytes(); let planes: Vec> = (0..4).map(|c| (0..n * bps).map(|i| (i * 13 + c * 5) as u8).collect()).collect(); let mut refs: Vec> = planes.iter().map(|p| Some(&p[..])).collect(); refs[2] = None; + refs[3] = Some(&planes[3][..(n * bps).saturating_sub(1)]); let fill: Vec> = (0..4).map(|c| vec![c as u8 * 40; bps]).collect(); let invert = [false, true, false, true]; let got = interleave(&refs, &fill, n, s, &invert); - let want = seq_interleave(&refs, &fill, n, s, &invert); + let want = previous_interleave(&refs, &fill, n, s, &invert); assert_eq!(got, want, "interleave n={n}"); let planes_back = deinterleave(&got, 4, s, &invert); let want_back = seq_deinterleave(&got, 4, s, &invert); @@ -287,6 +307,7 @@ mod tests { let fill = vec![zero_sample(s); 3]; let inv = [false, true, false]; let il = interleave(&refs, &fill, 4, s, &inv); + assert_eq!(interleave(&refs, &[], 4, s, &inv), il); let back = deinterleave(&il, 3, s, &inv); if s == SampleType::F32 { // 1 - (1 - v) may not be exact for floats; only check non-inverted planes. @@ -302,6 +323,12 @@ mod tests { fn missing_planes_use_fill() { let il = interleave(&[None, Some(&[5, 6])], &[vec![9], vec![0]], 2, SampleType::U8, &[false, false]); assert_eq!(il, vec![9, 5, 9, 6]); + for s in [SampleType::U8, SampleType::U16, SampleType::F32] { + for n in [1, 1000] { + let fill = vec![vec![9; s.bytes()]; 2]; + assert_eq!(interleave(&[None, Some(&[1, 2, 3][..s.bytes() - 1])], &fill, n, s, &[]), vec![9; n * 2 * s.bytes()]); + } + } } #[test] @@ -343,3 +370,35 @@ mod tests { assert_eq!(decode_be(&f, 0, SampleType::F32), 2.5); } } + +#[cfg(test)] +mod measurement { + use super::*; + #[test] + #[ignore = "manual 24 MP release benchmark"] + fn benchmark_interleave() { + use std::{hint::black_box, time::Instant}; + const N: usize = 24_000_000; + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let bps = sample.bytes(); + let planes: Vec> = (0..4).map(|c| (0..N * bps).map(|i| (i * 13 + c * 5) as u8).collect()).collect(); + let refs: Vec<_> = planes.iter().map(|p| Some(p.as_slice())).collect(); + let fill = vec![vec![0; bps]; 4]; + let invert = [false, true, false, true]; + assert_eq!(tests::previous_interleave(&refs, &fill, N, sample, &invert), interleave(&refs, &fill, N, sample, &invert)); + for trial in 0..6 { + let mut paths = [("main", tests::previous_interleave as fn(_, _, _, _, _) -> _), ("split", interleave)]; + if trial % 2 == 1 { + paths.reverse(); + } + for (name, path) in paths { + let t = Instant::now(); + let out = black_box(path)(&refs, &fill, N, sample, &invert); + let elapsed = t.elapsed().as_secs_f64() * 1000.0; + black_box(&out); + println!("interleave,{sample:?},{trial},{name},{elapsed:.6}"); + } + } + } + } +} diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 8ba30d83c4..68842b2691 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -29,6 +29,12 @@ const PSD_ESTIMATE_LAYER_OVERHEAD: u64 = 64 * 1024; pub struct PsdExportOptions { /// Write PSB even when the document fits PSD limits. pub force_psb: bool, + /// Switch to PSB when the estimated encoded size exceeds PSD's 2 GB limit. The estimate + /// counts every layer plane uncompressed, so a document with many canvas-sized layers can + /// pass it while its real file is far smaller. A writer that can measure the real size + /// instead turns this off: the layered TIFF writes PSD-style layer data and falls back to + /// PSB only when a length really overflows 32 bits. + pub size_limit_psb: bool, /// Matte the merged image against white where it is translucent, as Photoshop does /// (`false` keeps straight colour under the alpha: for containers that store the composite /// with its own alpha, such as a layered TIFF). @@ -41,11 +47,21 @@ pub struct PsdExportOptions { /// readers that only show the merged image see white. A document without layer records always /// gets the real image, since its pixels live nowhere else. pub maximize_compatibility: bool, + /// The path of the document's own file: linked smart objects are resolved against it + /// ([`crate::doc_path::resolve`]) before they are read and embedded. + pub document_path: Option, } impl Default for PsdExportOptions { fn default() -> Self { - PsdExportOptions { force_psb: false, merged_matte: true, merged_compression: Compression::Rle, maximize_compatibility: true } + PsdExportOptions { + force_psb: false, + size_limit_psb: true, + merged_matte: true, + merged_compression: Compression::Rle, + maximize_compatibility: true, + document_path: None, + } } } @@ -53,6 +69,8 @@ struct Ex { fmt: PixelFormat, /// Document resolution (for generated type-layer data). dpi: f32, + /// The document's own file, which linked smart objects are resolved against. + document: Option, /// Character/paragraph styles written into every type layer's engine data. text_styles: photocraft_doc::TextStyles, mask_fmt: PixelFormat, @@ -102,9 +120,7 @@ fn psd_background(doc: &Document) -> Option { if canvas.is_empty() || s.content_bounds() != canvas { return None; } - let n = s.channels(); - let opaque = s.read_region(canvas).chunks_exact(n).all(|p| p.last().is_some_and(|a| *a >= 1.0)); - opaque.then_some(l.id) + crate::flat::opaque_surface(s, canvas).then_some(l.id) } /// How deep embedded documents are exported inside each other before a smart object is written @@ -929,7 +945,8 @@ impl Ex { SmartSource::Linked { path } => { #[cfg(not(target_arch = "wasm32"))] { - let bytes = std::fs::read(path).map_err(|e| format!("the linked file {path} can't be read: {e}"))?; + let file = crate::doc_path::resolve(path, self.document.as_deref()).map_err(|e| format!("the linked file {path} is not opened: {e}"))?; + let bytes = std::fs::read(file).map_err(|e| format!("the linked file {path} can't be read: {e}"))?; let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_string(); self.warnings.push(format!("the linked smart object {name} was embedded (PSD export keeps no external links)")); self.embed(sm.contents_id, &name, &bytes) @@ -998,8 +1015,12 @@ impl Ex { return Err(format!("smart objects nest more than {MAX_NESTING} deep")); } let doc = photocraft_format::load_from_bytes(bytes).map_err(|e| format!("its contents can't be read: {e}"))?; - let (file, warnings) = - document_to_psd_nested(&doc, &PsdExportOptions { force_psb: true, ..Default::default() }, self.smart.depth + 1, &Interrupt::NONE); + let (file, warnings) = document_to_psd_nested( + &doc, + &PsdExportOptions { force_psb: true, document_path: self.document.clone(), ..Default::default() }, + self.smart.depth + 1, + &Interrupt::NONE, + ); let data = file.to_bytes().map_err(|e| format!("its contents can't be written: {e}"))?; let stem = file_name.rsplit_once('.').map_or(file_name, |(a, _)| a); self.warnings.extend(warnings.into_iter().map(|w| format!("smart object {stem}: {w}"))); @@ -1253,6 +1274,10 @@ pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bo if !crate::annotations_map::keep_resource(doc, id) { return false; } + // Guides v2 and guide GUIDs: only while they still describe the document's guides. + if !crate::guides_map::keep_resource(doc, id, data) { + return false; + } // A preserved clipping-path resource is only valid while it names the current one. if id == crate::vector_map::CLIPPING_PATH { let n = usize::from(data.first().copied().unwrap_or(0)); @@ -1514,11 +1539,12 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c let sample = fmt.sample; let cc = fmt.mode.color_channels(); let big = doc.size.width > 30_000 || doc.size.height > 30_000; - let size_exceeds_limit = !opts.force_psb && !big && psd_size_exceeds_limit(doc); + let size_exceeds_limit = opts.size_limit_psb && !opts.force_psb && !big && psd_size_exceeds_limit(doc); let version = psd_version(doc, opts.force_psb, size_exceeds_limit); let mut ex = Ex { fmt, dpi: doc.resolution_dpi, + document: opts.document_path.clone(), text_styles: doc.text_styles.clone(), text_index: Default::default(), mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false), diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 12307f32ba..2c1a734b1c 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -686,7 +686,7 @@ fn write_rgba8(s: &mut Surface, canvas: Rect, data: &[u8]) { } } -fn parse_guides(data: &[u8], doc: &mut Document) { +pub(crate) fn parse_guides(data: &[u8], doc: &mut Document) { let rd = |at: usize| data.get(at..at + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]])); let Some(count) = rd(12) else { return }; for i in 0..count as usize { @@ -836,6 +836,7 @@ pub(crate) fn psd_to_document_decoded( id => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone()))), } } + crate::guides_map::apply_colors(&mut doc); for b in &file.global_blocks { doc.metadata.psd_global_blocks.push((b.signature, b.key, Arc::new(b.data.clone()))); } diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 04fc4bee3a..8afefb733d 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -28,6 +28,10 @@ use crate::{ImportResult, IoError}; pub const MAX_SIDE: u32 = 16_384; /// A rasterised fallback layer or a smart-object render never exceeds this many pixels. const MAX_RASTER_PIXELS: u64 = 24_000_000; +/// Aggregate memory for retained fallback surfaces in the document's pixel format. +const MAX_PIXEL_BYTES: u64 = 1 << 30; +/// Estimated peak during raster conversion (retained surfaces + RGBA8 pixmap + f32 staging + tiles). +const MAX_PEAK_PIXEL_BYTES: u64 = 3 << 29; /// Past this many drawable elements the whole drawing opens as one pixel layer. const MAX_NODES: usize = 2_000; /// Nesting past which a subtree is rasterised instead of walked (bounded recursion). @@ -212,6 +216,10 @@ pub fn import_svg_with_group_depth(name: &str, bytes: &[u8], max_group_depth: us } fn import_parsed(name: &str, parsed: Parsed, max_group_depth: usize) -> Result { + import_parsed_with_budget(name, parsed, max_group_depth, MAX_PIXEL_BYTES) +} + +fn import_parsed_with_budget(name: &str, parsed: Parsed, max_group_depth: usize, pixel_budget: u64) -> Result { let Parsed { tree, fontless_text } = parsed; let mut warnings = Vec::new(); if fontless_text { @@ -222,7 +230,8 @@ fn import_parsed(name: &str, parsed: Parsed, max_group_depth: usize) -> Result MAX_NODES { conv.warnings.push(format!("SVG: more than {MAX_NODES} elements; opened as one pixel layer instead of shapes")); let (w, h) = (cv.size.width, cv.size.height); @@ -311,6 +320,10 @@ struct Conv { noted: Vec<&'static str>, /// Unnamed shapes, groups, images and texts so far, for "Shape 3"-style names. counts: [usize; 4], + /// Remaining budget for retained rasterised surfaces, in actual sample bytes. + pixel_budget: u64, + /// Successfully retained raster surface memory; rejected nodes are never counted. + retained_pixel_bytes: u64, } impl Conv { @@ -321,6 +334,23 @@ impl Conv { } } + /// Check both retained and transient memory before rendering; charge only retained output. + fn can_retain_pixels(&mut self, pixels: u64) -> bool { + let bytes = pixels.saturating_mul(self.fmt.bytes_per_pixel() as u64); + if bytes > self.pixel_budget { + self.note("pixel-budget", "SVG: some rasterised elements were omitted because they exceeded the remaining pixel memory budget".into()); + return false; + } + // surface() converts the RGBA8 pixmap into f32 scratch space before writing + // sample-format tiles. All three buffers briefly coexist with retained layers. + let temporary = pixels.saturating_mul(4 + self.fmt.channels() as u64 * 4 + self.fmt.bytes_per_pixel() as u64); + if self.retained_pixel_bytes.saturating_add(temporary) > MAX_PEAK_PIXEL_BYTES { + self.note("pixel-peak", "SVG: some rasterised elements were omitted to bound temporary conversion memory".into()); + return false; + } + true + } + /// The element's `id`, or a numbered name by kind (0 shape, 1 group, 2 image, 3 text). fn name(&mut self, id: &str, kind: usize) -> String { if !id.is_empty() { @@ -337,6 +367,11 @@ impl Conv { /// `nodes` in paint order (first = bottom), as layers in the same order. `parent` is the /// absolute transform of the group holding them (what resvg needs to render one of them /// alone, since a node's own data is in its parent's space). + /// + /// Transforms are composed from `parent` down rather than read from `abs_transform()`: the + /// glyph outlines usvg builds for a text element (`Text::flattened`) keep identity absolute + /// transforms, so text placed by its own or an ancestor's `transform` (Illustrator writes + /// `matrix(1 0 0 1 x y)` on every text element) would lose it (#4806). Elsewhere the two agree. fn convert_children(&mut self, nodes: &[usvg::Node], depth: usize, rec: usize, parent: tiny_skia::Transform) -> Vec { let mut out = Vec::new(); for node in nodes { @@ -350,7 +385,7 @@ impl Conv { usvg::Node::Group(g) => { // A clip-path of one plain path becomes the group's vector mask (#4266); others // are rasterised with the group. - let clip = g.clip_path().and_then(|cp| self.clip_mask(g, cp)); + let clip = g.clip_path().and_then(|cp| self.clip_mask(parent.pre_concat(g.transform()), cp)); let dropped: [(bool, &'static str); 3] = [(!g.filters().is_empty(), "filter"), (g.clip_path().is_some() && clip.is_none(), "clip-path"), (g.mask().is_some(), "mask")]; let too_deep = self.max_group_depth.is_some_and(|limit| depth >= limit) || depth >= MAX_GROUP_DEPTH || rec >= MAX_RECURSION; @@ -370,7 +405,8 @@ impl Conv { // A group that only carries a transform (baked into its paths by usvg) or that // usvg inserted for its own bookkeeping adds nothing to the layer tree. let plain = clip.is_none() && g.id().is_empty() && g.opacity().get() >= 1.0 && g.blend_mode() == usvg::BlendMode::Normal; - let children = self.convert_children(g.children(), if plain { depth } else { depth + 1 }, rec + 1, g.abs_transform()); + let abs = parent.pre_concat(g.transform()); + let children = self.convert_children(g.children(), if plain { depth } else { depth + 1 }, rec + 1, abs); if children.is_empty() { return; } @@ -404,7 +440,9 @@ impl Conv { out.extend(self.raster_layer(node, name, parent)); } usvg::Node::Text(t) => { - let children = self.convert_children(t.flattened().children(), depth + 1, rec + 1, t.flattened().abs_transform()); + // The outlines are in the text element's own space. + let abs = t.abs_transform().pre_concat(t.flattened().transform()); + let children = self.convert_children(t.flattened().children(), depth + 1, rec + 1, abs); if children.is_empty() { self.note("text", "SVG: text needs a font the drawing can use; none matched, so it was dropped".to_string()); return; @@ -421,10 +459,10 @@ impl Conv { } } - /// The vector mask for group `g` clipped by `cp`, when the clip is one visible path with no - /// clip of its own: what resvg draws for the clip (the group's transform, then the clip's, - /// then the path), in canvas pixels, with the clip rule as its fill rule. - fn clip_mask(&self, g: &usvg::Group, cp: &usvg::ClipPath) -> Option { + /// The vector mask for a group clipped by `cp`, when the clip is one visible path with no + /// clip of its own: what resvg draws for the clip (the group's absolute transform `abs`, then + /// the clip's, then the path), in canvas pixels, with the clip rule as its fill rule. + fn clip_mask(&self, abs: tiny_skia::Transform, cp: &usvg::ClipPath) -> Option { if cp.clip_path().is_some() { return None; } @@ -432,7 +470,7 @@ impl Conv { if !p.is_visible() { return None; } - let ts = g.abs_transform().pre_concat(cp.transform()).post_concat(self.global); + let ts = abs.pre_concat(cp.transform()).post_concat(self.global); let subpaths = knots(&(*p.data()).clone().transform(ts)?); if subpaths.is_empty() { return None; @@ -455,7 +493,8 @@ impl Conv { let name = self.name(p.id(), 0); return self.raster_layer(node, name, parent); } - let ts = p.abs_transform().post_concat(self.global); + // A path has no transform of its own: its data is in its parent's space. + let ts = parent.post_concat(self.global); let data = (*p.data()).clone().transform(ts)?; let subpaths = knots(&data); if subpaths.is_empty() { @@ -542,7 +581,14 @@ impl Conv { /// The node rendered by resvg into a pixel layer over its bounding box, clipped to the canvas. /// `parent` is the absolute transform of the node's parent group. fn raster_layer(&mut self, node: &usvg::Node, name: String, parent: tiny_skia::Transform) -> Option { - let bb = node.abs_layer_bounding_box()?; + // Where the node lands, from its box in its parent's space (as usvg computes its absolute + // box, but through `parent`, which is right inside text too). + let bb = match node { + usvg::Node::Group(g) => g.layer_bounding_box().transform(parent.pre_concat(g.transform()))?, + _ => node.bounding_box().to_non_zero_rect()?.transform(parent)?, + }; + // What resvg shifts the node by before drawing it. + let shift = node.abs_layer_bounding_box()?; let k = self.global.sx; let x0 = ((bb.x() * k).floor() as i32).max(self.canvas.x0); let y0 = ((bb.y() * k).floor() as i32).max(self.canvas.y0); @@ -551,17 +597,31 @@ impl Conv { if x1 <= x0 || y1 <= y0 { return None; } - let Some(mut pixmap) = pixmap((x1 - x0) as u32, (y1 - y0) as u32) else { + let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32); + let pixels = u64::from(w) * u64::from(h); + // Preflight the pixmap limit first, without charging the shared allowance. + if pixels > MAX_RASTER_PIXELS { self.note("raster-size", "SVG: an element too large to rasterise was dropped".to_string()); return None; + } + if !self.can_retain_pixels(pixels) { + return None; + } + let Some(mut pixmap) = pixmap(w, h) else { + self.note("raster-alloc", "SVG: a rasterised element could not be allocated".to_string()); + return None; }; // resvg renders the node in its parent's space after shifting its absolute bounding box // to the origin: undo that shift, apply the parent's transform, then scale to the canvas // and shift so the pixmap starts at (x0, y0). let canvas = tiny_skia::Transform::from_row(k, 0.0, 0.0, k, -(x0 as f32), -(y0 as f32)); - let ts = canvas.pre_concat(parent).pre_translate(bb.x(), bb.y()); + let ts = canvas.pre_concat(parent).pre_translate(shift.x(), shift.y()); resvg::render_node(node, ts, &mut pixmap.as_mut())?; - Some(Layer::new(name, LayerContent::Raster(surface(&pixmap, Rect::new(x0, y0, x1, y1), self.fmt)))) + let layer = Layer::new(name, LayerContent::Raster(surface(&pixmap, Rect::new(x0, y0, x1, y1), self.fmt))); + let bytes = pixels * self.fmt.bytes_per_pixel() as u64; + self.pixel_budget -= bytes; + self.retained_pixel_bytes += bytes; + Some(layer) } } @@ -768,6 +828,59 @@ mod tests { assert!(r.warnings.iter().any(|w| w.contains("clip-path")), "{:?}", r.warnings); } + #[test] + fn rasterized_groups_stop_at_the_aggregate_pixel_budget() { + let mut svg = String::from(""); + svg.push_str(""); + for i in 0..8 { + svg.push_str(&format!("")); + } + svg.push_str(""); + // Enough for one retained 256×256 RGBA8 surface, not eight of them. + let budget = 256u64 * 256 * 4; + let result = import_parsed_with_budget("budget", parse(svg.as_bytes()).unwrap(), MAX_GROUP_DEPTH, budget).unwrap(); + assert_eq!(result.document.layers.len(), 1, "one U8 surface fills the retained-byte allowance"); + assert_eq!(result.document.layers[0].name, "g0"); + assert!(result.warnings.iter().any(|warning| warning.contains("pixel memory")), "{:?}", result.warnings); + } + + #[test] + fn oversized_raster_does_not_consume_budget_for_later_layers() { + let svg = br##" + + + + + + + + + + + "##; + let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 64 * 64 * 4).unwrap(); + assert_eq!(result.document.layers.len(), 1, "the oversized group must not debit the budget"); + assert_eq!(result.document.layers[0].name, "small"); + assert!(result.warnings.iter().any(|w| w.contains("too large to rasterise")), "{:?}", result.warnings); + assert!(!result.warnings.iter().any(|w| w.contains("pixel memory budget")), "{:?}", result.warnings); + } + + #[test] + fn skipped_expensive_raster_does_not_hide_a_smaller_one() { + let svg = br##" + + + + + + + "##; + let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 32 * 32 * 4).unwrap(); + assert_eq!(result.document.layers.len(), 1); + assert_eq!(result.document.layers[0].name, "small"); + assert!(result.warnings.iter().any(|w| w.contains("some rasterised elements were omitted")), "{:?}", result.warnings); + } + #[test] fn huge_drawings_scale_to_the_side_limit() { let tree = parse(b"").unwrap().tree; diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 3cd8de5b4c..7da61fa466 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -202,14 +202,38 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr let big = doc.size.width > 30_000 || doc.size.height > 30_000; // The PSD exporter renders the composite we need for the TIFF itself: unmatted (the TIFF // keeps straight alpha) and uncompressed (its planes are interleaved below). - let psd_opts = - PsdExportOptions { force_psb: opts.force_psb || big, merged_matte: false, merged_compression: Compression::Raw, maximize_compatibility: true }; - let (file, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psd_opts, ctl)); + // Layer data is written PSD-style ("Adobe Photoshop Document Data Block", 4-byte lengths), as + // Photoshop writes it: Photoshop does not read the PSB-style header ("... Data V0002") in a + // TIFF and opens only the composite, as one locked Background. The exporter's size estimate + // counts layer planes uncompressed, so a document with many canvas-sized layers passes 2 GB + // while its real layer data is a small fraction of that; it is not used here. PSB-style data + // is written only past 30000 px, when asked for, or when a length really overflows 32 bits. + let force_psb = opts.force_psb || big; + let psd_opts = PsdExportOptions { + force_psb, + size_limit_psb: false, + merged_matte: false, + merged_compression: Compression::Raw, + maximize_compatibility: true, + document_path: opts.document_path.clone(), + }; + let (mut file, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psd_opts, ctl)); // A cancelled conversion stops early with an incomplete model: never encode it. ctl.check().map_err(|_| IoError::Cancelled)?; warnings.extend(w); let order = if codecs::tiff_writes_little_endian() { ByteOrder::Little } else { ByteOrder::Big }; - let (layers, w) = ImageSourceData::from_psd(&file).to_bytes(order)?; + let (layers, w) = match ImageSourceData::from_psd(&file).to_bytes(order) { + Err(photocraft_psd::PsdError::LimitExceeded(_)) if !force_psb => { + let psb_opts = PsdExportOptions { force_psb: true, ..psd_opts }; + let (psb, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psb_opts, ctl)); + ctl.check().map_err(|_| IoError::Cancelled)?; + warnings.extend(w); + warnings.push("layer data exceeds 4 GB; written with PSB-sized lengths, which some readers do not open".into()); + file = psb; + ImageSourceData::from_psd(&file).to_bytes(order)? + } + r => r?, + }; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(TIFF_LAYERS_DONE); warnings.extend(w.into_iter().map(|w| format!("layer data: {w}"))); @@ -279,3 +303,54 @@ pub fn strip_foreign_order_blocks(file: &mut photocraft_psd::PsdFile) -> Vec", END), rec("b", None), rec("c", None)]); + assert_eq!(names(&f, &f.layer_tree()), "a,b,c"); + assert_eq!(names(&f, &f.layer_tree_max_depth(1)), "a,b,c"); + assert_eq!(names(&f, &f.layer_tree_max_depth(0)), "a,b,c"); +} + +/// #5758: a closed group inside unclosed dividers sits at the depth it ends up at after hoisting, +/// so the cap keeps its node and drops only its deeper children. +#[test] +fn layer_tree_max_depth_keeps_closed_group_inside_unclosed_dividers() { + let mut v = vec![rec("", END), rec("", END)]; + v.extend([rec("", END), rec("", END), rec("x", None), rec("g1", OPEN), rec("g0", OPEN)]); + let f = file_with(v); + assert_eq!(names(&f, &f.layer_tree()), "g0[g1[x]]"); + assert_eq!(names(&f, &f.layer_tree_max_depth(1)), "g0[g1[]]"); + assert_eq!(names(&f, &f.layer_tree_max_depth(0)), "g0[]"); +} + +/// #5758: thousands of unclosed dividers around a closed chain stay bounded by the cap and keep +/// every layer the full tree has. +#[test] +fn layer_tree_max_depth_bounds_deep_unclosed_chain() { + let mut v = Vec::new(); + for i in 0..16_000 { + v.push(rec("", END)); + v.push(rec(&format!("l{i}"), None)); + } + v.extend([rec("", END), rec("", END), rec("", END), rec("x", None)]); + v.extend([rec("g2", OPEN), rec("g1", OPEN), rec("g0", OPEN)]); + let f = file_with(v); + let full = f.layer_tree(); + assert_eq!(full.len(), 16_001); + assert_eq!(depth(&full), 4); + let capped = f.layer_tree_max_depth(1); + assert!(depth(&capped) <= 2); + assert_eq!(capped.len(), 16_001); + assert_eq!(names(&f, &capped[16_000..]), "g0[g1[]]"); + assert_eq!(names(&f, &capped[..2]), "l0,l1"); +} #[test] fn folder_without_divider_is_empty_group() { let f = file_with(vec![rec("a", None), rec("G", OPEN), rec("b", None)]); diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index 956d1c9545..41b188a94f 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -12,5 +12,9 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } serde = { workspace = true } +# Native only: converting a region's tiles is independent per tile, so it runs on all cores. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +rayon = { workspace = true } + [dev-dependencies] proptest = { workspace = true } diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 20b809764a..958ab38b53 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -117,6 +117,16 @@ pub struct Surface { tiles: BTreeMap>, } +/// Use stack storage when it fits, otherwise reuse a dynamically sized sample buffer. +fn sample_buffer<'a>(channels: usize, stack: &'a mut [f32], heap: &'a mut Vec) -> &'a mut [f32] { + if let Some(samples) = stack.get_mut(..channels) { + samples + } else { + heap.resize(channels, 0.0); + heap + } +} + /// Tiles of one pixel value met while moving a surface ([`Surface::translated`]): each scanned /// once, and one tile kept per value so the targets share it. #[derive(Default)] @@ -166,6 +176,55 @@ impl PartialEq for Surface { } } +/// Converts the `data` span covering one tile into that tile's bytes. +fn write_tile(t: &mut Tile, tc: TileCoord, r: Rect, data: &[f32], w: usize, n: usize, sample: SampleType) { + let tr = tc.rect().intersect(&r); + // Convert contiguous channel samples a row at a time. Dispatching on depth here removes the + // per-pixel channel loop and lets the compiler vectorise conversion. + let span = tr.width() as usize * n; + for y in tr.y0..tr.y1 { + let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n; + let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; + let src = &data[o..o + span]; + let bytes = sample.bytes(); + let dst = &mut t.data[base * bytes..(base + span) * bytes]; + match sample { + SampleType::U8 => { + for (d, v) in dst.iter_mut().zip(src) { + *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + } + } + SampleType::U16 => { + for (d, v) in dst.as_chunks_mut::<2>().0.iter_mut().zip(src) { + let q = (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; + d.copy_from_slice(&q.to_ne_bytes()); + } + } + SampleType::F32 => { + for (d, v) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) { + d.copy_from_slice(&v.to_ne_bytes()); + } + } + } + } +} + +/// Converts the tiles of a region write. A tile holds no state another tile reads, so the tiles +/// are converted on all cores; each writes only its own bytes, in the same arithmetic. +#[cfg(not(target_arch = "wasm32"))] +fn convert_tiles(tiles: &mut [(TileCoord, Arc)], r: Rect, data: &[f32], w: usize, n: usize, sample: SampleType) { + use rayon::prelude::*; + tiles.par_iter_mut().for_each(|(tc, t)| write_tile(Arc::make_mut(t), *tc, r, data, w, n, sample)); +} + +/// Serial counterpart, for the web build (there are no threads to spread tiles over). +#[cfg(target_arch = "wasm32")] +fn convert_tiles(tiles: &mut [(TileCoord, Arc)], r: Rect, data: &[f32], w: usize, n: usize, sample: SampleType) { + for (tc, t) in tiles.iter_mut() { + write_tile(Arc::make_mut(t), *tc, r, data, w, n, sample); + } +} + impl Surface { /// Reads a region into a newly allocated buffer, returning an error instead of aborting if /// the requested pixel buffer cannot be represented or reserved. @@ -239,11 +298,20 @@ impl Surface { decode_pixel(&self.format, &self.default_pixel) } + /// Decode the default pixel, using dynamic storage only when the stack buffer is too small. + fn default_samples<'a>(&self, stack: &'a mut [f32], heap: &'a mut Vec) -> &'a mut [f32] { + let px = sample_buffer(self.channels(), stack, heap); + for (i, v) in px.iter_mut().enumerate() { + *v = read_sample(&self.default_pixel, self.format.sample, i); + } + px + } + /// Mutable access to a tile, allocating it (filled with the default pixel) or un-sharing it. pub fn tile_mut(&mut self, c: TileCoord) -> &mut Tile { let fmt = self.format; - let dp = self.default_pixel.clone(); - let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, &dp))); + let dp = &self.default_pixel; + let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, dp))); Arc::make_mut(arc) } @@ -319,9 +387,9 @@ impl Surface { /// Drop tiles that are entirely the default pixel. pub fn prune(&mut self) { - let dp = self.default_pixel.clone(); + let dp = self.default_pixel.as_ref(); let bpp = dp.len(); - self.tiles.retain(|_, t| t.data.chunks_exact(bpp).any(|px| px != &*dp)); + self.tiles.retain(|_, t| t.data.chunks_exact(bpp).any(|px| px != dp)); } #[inline] @@ -411,14 +479,27 @@ impl Surface { let w = r.width() as usize; out.clear(); out.resize(w * r.height() as usize * n, 0.0); - let dp = self.default_pixel(); + self.read_samples_into(r, out); + } + + /// Copy samples into a zero-initialized buffer sized for `r`. + fn read_samples_into(&self, r: Rect, out: &mut [f32]) { + let n = self.channels(); + let w = r.width() as usize; + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let dp = self.default_samples(&mut stack, &mut heap); + let zero = self.default_pixel.iter().all(|&b| b == 0); for tc in r.tiles() { let tr = tc.rect().intersect(&r); let tile = self.tiles.get(&tc); + if tile.is_none() && zero { + continue; + } for y in tr.y0..tr.y1 { let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n; let span = tr.width() as usize * n; - let dst = &mut out[o..o + span]; + let Some(dst) = out.get_mut(o..o + span) else { continue }; match tile { Some(t) => { let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; @@ -426,9 +507,10 @@ impl Surface { *d = read_sample(&t.data, self.format.sample, base + i); } } + None if n == 1 => dst.fill(dp[0]), None => { for px in dst.chunks_exact_mut(n) { - px.copy_from_slice(&dp); + px.copy_from_slice(dp); } } } @@ -445,7 +527,10 @@ impl Surface { debug_assert_eq!(out.len(), w * r.height() as usize); let fmt = self.format; let n = fmt.channels(); - let dp = to_rgba(&fmt, &self.default_pixel()); + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let px = self.default_samples(&mut stack, &mut heap); + let dp = to_rgba(&fmt, px); for tc in r.tiles() { let tr = tc.rect().intersect(&r); let tile = self.tiles.get(&tc); @@ -489,12 +574,11 @@ impl Surface { } } _ => { - let mut px = [0.0f32; 8]; for (i, d) in dst.iter_mut().enumerate() { - for (c, v) in px.iter_mut().enumerate().take(n) { + for (c, v) in px.iter_mut().enumerate() { *v = read_sample(&t.data, fmt.sample, base + i * n + c); } - *d = to_rgba(&fmt, &px[..n]); + *d = to_rgba(&fmt, px); } } } @@ -510,7 +594,9 @@ impl Surface { let fmt = self.format; let rgba8 = matches!((fmt.mode, fmt.sample, fmt.alpha), (ColorMode::Rgb, SampleType::U8, true)); let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let dp = to_rgba(&fmt, &self.default_pixel()); + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let dp = to_rgba(&fmt, self.default_samples(&mut stack, &mut heap)); let dp8 = [q(dp[0]), q(dp[1]), q(dp[2]), q(dp[3])]; let mut row = Vec::new(); for tc in r.tiles() { @@ -551,68 +637,43 @@ impl Surface { let n = self.channels(); let w = r.width() as usize; let mut out = vec![0.0f32; w * r.height() as usize * n]; - let dp = self.default_pixel(); - for tc in r.tiles() { - let tr = tc.rect().intersect(&r); - let tile = self.tiles.get(&tc); - for y in tr.y0..tr.y1 { - for x in tr.x0..tr.x1 { - let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; - match tile { - Some(t) => { - let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; - for i in 0..n { - out[o + i] = read_sample(&t.data, self.format.sample, base + i); - } - } - None => out[o..o + n].copy_from_slice(&dp), - } - } - } - } + self.read_samples_into(r, &mut out); out } - /// Write interleaved normalised floats into a rectangle. + /// Write interleaved normalised floats into a rectangle, on the calling thread. + /// + /// This never enters Rayon, so it is safe inside a `OnceLock` initializer or any other + /// section that must not run another Rayon job on its stack. [`Surface::write_region_par`] + /// writes the same bytes on all cores. pub fn write_region(&mut self, r: Rect, data: &[f32]) { let n = self.channels(); let w = r.width() as usize; assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); let sample = self.format.sample; for tc in r.tiles() { - let tr = tc.rect().intersect(&r); - let t = self.tile_mut(tc); - // Convert contiguous channel samples a row at a time. Dispatching on depth here - // removes the per-pixel channel loop and lets the compiler vectorise conversion. - let span = tr.width() as usize * n; - for y in tr.y0..tr.y1 { - let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n; - let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; - let src = &data[o..o + span]; - let bytes = sample.bytes(); - let dst = &mut t.data[base * bytes..(base + span) * bytes]; - match sample { - SampleType::U8 => { - for (d, v) in dst.iter_mut().zip(src) { - *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - } - } - SampleType::U16 => { - for (d, v) in dst.as_chunks_mut::<2>().0.iter_mut().zip(src) { - let q = (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; - d.copy_from_slice(&q.to_ne_bytes()); - } - } - SampleType::F32 => { - for (d, v) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) { - d.copy_from_slice(&v.to_ne_bytes()); - } - } - } - } + write_tile(self.tile_mut(tc), tc, r, data, w, n, sample); } } + /// [`Surface::write_region`] with the tiles converted on all cores (serially on the web). + /// + /// This enters Rayon: while it waits for its tiles, the calling worker may run any other + /// queued Rayon job. Callers inside a `OnceLock` initializer or another section that must + /// not do that use [`Surface::write_region`]. + pub fn write_region_par(&mut self, r: Rect, data: &[f32]) { + let n = self.channels(); + let w = r.width() as usize; + assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); + let sample = self.format.sample; + // The tiles are disjoint, so converting them in any order (and on any thread) writes + // exactly the same bytes. `take_tiles` gives the missing tiles as one shared + // default-filled tile, copied per tile by `Arc::make_mut` in `convert_tiles`. + let mut tiles = self.take_tiles(r); + convert_tiles(&mut tiles, r, data, w, n, sample); + self.put_tiles(tiles); + } + /// Take the tiles covering `r` out of the surface (missing ones filled with the default /// pixel), so they can be edited elsewhere, e.g. in parallel: `Arc::unwrap_or_clone` copies a /// tile only if an undo snapshot still shares it. Give them back with [`Surface::put_tiles`]. @@ -1102,6 +1163,60 @@ pub fn is_hdr(sample: SampleType) -> bool { #[cfg(test)] mod tests { + + /// Manually compare allocating reads with the previous implementation. + #[test] + #[ignore = "manual 24 MP release benchmark"] + fn benchmark_sparse_reads() { + use std::{hint::black_box, time::Instant}; + let rect = Rect::new(0, 0, 6000, 4000); + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for default in [0.0, 0.25] { + let mut s = Surface::with_default(PixelFormat::GRAY8.with_sample(depth), &[default]); + s.fill_rect(Rect::new(257, 257, 266, 266), &[0.75]); + assert_eq!(s.read_region(rect), previous_read_region(&s, rect)); + for trial in 0..6 { + let mut paths = [("main", previous_read_region as fn(&Surface, Rect) -> Vec), ("split", Surface::read_region)]; + if trial % 2 == 1 { + paths.reverse(); + } + for (name, path) in paths { + let t = Instant::now(); + let out = black_box(path)(&s, rect); + let elapsed = t.elapsed().as_secs_f64() * 1000.0; + black_box(&out); + println!("sparse,{depth:?}-{default},{trial},{name},{elapsed:.6}"); + } + } + } + } + } + /// Previous allocating read path, retained as the bitwise-equivalence oracle. + fn previous_read_region(surface: &Surface, r: Rect) -> Vec { + let n = surface.channels(); + let w = r.width() as usize; + let mut out = vec![0.0f32; w * r.height() as usize * n]; + let dp = surface.default_pixel(); + for tc in r.tiles() { + let tr = tc.rect().intersect(&r); + let tile = surface.tiles.get(&tc); + for y in tr.y0..tr.y1 { + for x in tr.x0..tr.x1 { + let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; + match tile { + Some(t) => { + let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; + for i in 0..n { + out[o + i] = read_sample(&t.data, surface.format.sample, base + i); + } + } + None => out[o..o + n].copy_from_slice(&dp), + } + } + } + } + out + } /// Distinct tile allocations in `s`. fn distinct_tiles(s: &Surface) -> usize { let mut seen: Vec<*const Tile> = s.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); @@ -1213,19 +1328,52 @@ mod tests { .collect(); let snapshot = actual.clone(); let snapshot_bytes = snapshot.to_interleaved(rect.inflate(1)); + let mut par = actual.clone(); actual.write_region(rect, &data); + par.write_region_par(rect, &data); write_region_reference(&mut expected, rect, &data); assert_eq!(actual, expected, "{fmt:?}, {rect:?}"); + assert_eq!(par, expected, "parallel {fmt:?}, {rect:?}"); assert_eq!(snapshot.to_interleaved(rect.inflate(1)), snapshot_bytes, "COW snapshot changed"); // Repeat against already materialised, unshared tiles too. actual.write_region(rect, &data); + par.write_region_par(rect, &data); assert_eq!(actual, expected); + assert_eq!(par, expected); } } } } } + /// Mask builds call `write_region` inside a `OnceLock` initializer, where entering Rayon can + /// run another tile's job that waits on the same lock. With every global worker held, a write + /// that queued work on Rayon could not finish. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn write_region_does_not_enter_rayon() { + use std::sync::{Barrier, mpsc}; + let workers = rayon::current_num_threads(); + let held = Arc::new(Barrier::new(workers + 1)); + let release = Arc::new(Barrier::new(workers + 1)); + let (h, rel) = (held.clone(), release.clone()); + rayon::spawn_broadcast(move |_| { + h.wait(); + rel.wait(); + }); + held.wait(); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let r = Rect::new(0, 0, 2 * TILE_SIZE, 2 * TILE_SIZE); + let mut s = Surface::new(PixelFormat::RGBA8); + s.write_region(r, &vec![0.5; (r.width() * r.height() * 4) as usize]); + tx.send(()).ok(); + }); + let done = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); + release.wait(); + assert!(done, "write_region waited on the Rayon pool"); + } + #[test] fn from_rgba_into_matches_from_rgba() { for fmt in [PixelFormat::RGBA8, PixelFormat::GRAY8, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::new(ColorMode::Lab, SampleType::F32, true)] { @@ -1235,29 +1383,74 @@ mod tests { } } + /// Sample counts above the stack capacity use writable storage without truncating channels. + #[test] + fn sample_buffer_keeps_stack_fast_path_and_supports_dynamic_channels() { + for channels in [1, 8, 9, 32] { + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let samples = sample_buffer(channels, &mut stack, &mut heap); + assert_eq!(samples.len(), channels); + samples.fill(0.25); + if channels <= stack.len() { + assert!(heap.is_empty()); + assert_eq!(&stack[..channels], vec![0.25; channels]); + } else { + assert_eq!(heap, vec![0.25; channels]); + } + } + } + + /// Compare sparse reads and converted accessors with the previous allocating path. #[test] fn zero_alloc_accessors_match_read_region() { - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::GRAY8] { - let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + for (fmt, default) in [ + PixelFormat::RGBA8, + PixelFormat::RGBA16, + PixelFormat::RGBA32F, + PixelFormat::GRAYA8, + PixelFormat::CMYKA8, + PixelFormat::GRAY8, + PixelFormat::GRAY8.with_sample(SampleType::F32), + PixelFormat::new(ColorMode::Lab, SampleType::U16, true), + ] + .into_iter() + .flat_map(|fmt| [0.0, 0.25, -0.0].map(|default| (fmt, default))) + { + let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + for capacity in [0, stack.len()] { + let decoded = s.default_samples(&mut stack[..capacity], &mut heap); + assert!(decoded.iter().map(|v| v.to_bits()).eq(s.default_pixel().into_iter().map(f32::to_bits))); + } let r = Rect::new(-300, -20, 300, 40); for (i, (x, y)) in [(-299, -19), (0, 0), (255, 39), (256, 10), (299, 0)].into_iter().enumerate() { let px: Vec = (0..fmt.channels()).map(|c| ((i * 3 + c) % 5) as f32 / 4.0).collect(); s.write_pixel(x, y, &px); } let region = s.read_region(r); + assert!(region.iter().map(|v| v.to_bits()).eq(previous_read_region(&s, r).into_iter().map(f32::to_bits))); let mut into = vec![9.0; 3]; s.read_region_into(r, &mut into); assert_eq!(region, into); let mut rgba = vec![[0.0; 4]; (r.width() * r.height()) as usize]; s.read_rgba_into(r, &mut rgba); + let mut rgba8 = vec![[0; 4]; rgba.len()]; + s.read_rgba8_into(r, &mut rgba8); let n = fmt.channels(); for (i, p) in region.chunks_exact(n).enumerate() { let want = to_rgba(&fmt, p); + assert_eq!(rgba8[i], want.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); for c in 0..4 { assert!((rgba[i][c] - want[c]).abs() < 1e-6, "{fmt:?} px {i}"); } let (x, y) = (r.x0 + (i % r.width() as usize) as i32, r.y0 + (i / r.width() as usize) as i32); - assert_eq!(s.sample_channel(x, y, 0), p[0]); + for c in 0..n { + let bits = s.sample_channel(x, y, c).to_bits(); + assert_eq!(bits, p[c].to_bits()); + assert_eq!(bits, into[i * n + c].to_bits()); + } } assert!(s.has_tiles_in(Rect::new(0, 0, 1, 1))); assert!(!s.has_tiles_in(Rect::new(1000, 1000, 1001, 1001))); diff --git a/crates/raw/src/cr3.rs b/crates/raw/src/cr3.rs index bb2119e7d4..04e7e2ec5f 100644 --- a/crates/raw/src/cr3.rs +++ b/crates/raw/src/cr3.rs @@ -141,11 +141,7 @@ fn walk<'a>(raw: &'a [u8], b: &'a [u8], depth: usize, budget: &mut usize, found: } boxes(b, budget, |item, budget| match item.kind { b"moov" => walk(raw, item.body, depth + 1, budget, found), - b"trak" => { - if found.previews.len() < 128 { - found.previews.extend(track_preview(raw, item.body, budget, &found.media)); - } - } + b"trak" if found.previews.len() < 128 => found.previews.extend(track_preview(raw, item.body, budget, &found.media)), b"uuid" => { if item.body.get(..16) == Some(META_UUID) && let Some(children) = item.body.get(16..) diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index e3ab70b0c7..5d28508750 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -535,7 +535,8 @@ pub(crate) fn tone(curve: &[[f32; 2]], v: f32) -> f32 { } let i = curve.partition_point(|p| p[0] <= v).clamp(1, curve.len() - 1); let ([x0, y0], [x1, y1]) = (curve[i - 1], curve[i]); - let f = (v.log2() - x0.log2()) / (x1.log2() - x0.log2()); + // Logarithmic between knots; linear from a knot at black, where log₂ has no value. + let f = if x0 > 0.0 { (v.log2() - x0.log2()) / (x1.log2() - x0.log2()) } else { (v - x0) / (x1 - x0) }; y0 + (y1 - y0) * f } diff --git a/crates/raw/src/tone.rs b/crates/raw/src/tone.rs index 80a80bfdd6..1c2730bd2c 100644 --- a/crates/raw/src/tone.rs +++ b/crates/raw/src/tone.rs @@ -710,6 +710,19 @@ mod tests { assert!(Haze::new(w, h, |i| px[i], 0.0).is_none()); } + #[test] + fn retone_lifts_shadows_with_a_curve_from_black() { + // A curve whose first knot is black: its first segment must not divide by log₂ 0. + let (w, h) = (96, 64); + let curve = [[0.0, 0.0], [0.05, 0.12], [0.3, 0.6], [1.0, 1.0]]; + let px: Vec<[f32; 4]> = (0..w * h).map(|i| if i % w < 48 { [0.12, 0.11, 0.1, 1.0] } else { [0.7, 0.63, 0.56, 1.0] }).collect(); + let mut out = px.clone(); + retone(&mut out, w, h, &curve, SHADOWS); + assert!(out.iter().flatten().all(|v| v.is_finite())); + assert!(out[30 * w + 10][0] > px[30 * w + 10][0] + 0.05, "{:?}", out[30 * w + 10]); + assert!((out[30 * w + 80][0] - px[30 * w + 80][0]).abs() < 0.03, "{:?}", out[30 * w + 80]); + } + #[test] fn retone_changes_nothing_at_zero_and_matches_the_develop_stage() { let (w, h) = (300, 120); diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 0d69300d90..3e8bbed919 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -14,5 +14,7 @@ photocraft-raster = { workspace = true } serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -# In-process resident memory for the benchmarks (`perf`; MIT OR Apache-2.0). -memory-stats = "1.2" +# In-process resident memory for the benchmarks (`perf`; MIT OR Apache-2.0). `always_use_statm`: +# on Linux read /proc/self/statm, not /proc/self/smaps, which walks every mapping under the mmap +# lock and made the 2 ms sampler thread a fifth of a large bench's CPU time. +memory-stats = { version = "1.2", features = ["always_use_statm"] } diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 985f627e90..0c251d1639 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -25,8 +25,10 @@ flate2 = { workspace = true } # line breaking. Native only: the CJK dictionary alone is 3.8 MB of wasm, and the web build must # stay under Cloudflare's 25 MiB per-file cap (packaging/web/package.sh). The web build falls back # to the generic Unicode rules for those scripts. +# Native only: the glyph rasteriser composites and converts its pixel buffers on all cores. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] parley = { version = "0.11", default-features = false, features = ["std", "complex-scripts"] } +rayon = { workspace = true } [build-dependencies] # Deflates the bundled fonts (build.rs); `flate2` above inflates them. diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index 5ce71e59ac..756ce87455 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -35,7 +35,7 @@ pub static INTER_MEDIUM: LazyLock> = LazyLock::new(|| inflate_font(bundl pub static INTER_SEMIBOLD: LazyLock> = LazyLock::new(|| inflate_font(bundled_font!("Inter-SemiBold.ttf"))); pub static JETBRAINS_MONO_REGULAR: LazyLock> = LazyLock::new(|| inflate_font(bundled_font!("JetBrainsMono-Regular.ttf"))); -/// Fonts shipped with Photocraft (OFL; licences in `assets/fonts`). +/// Fonts shipped with PhotoCraft (OFL; licences in `assets/fonts`). pub static BUNDLED: [(&str, &LazyLock>); 4] = [ ("Inter-Regular.ttf", &INTER_REGULAR), ("Inter-Medium.ttf", &INTER_MEDIUM), diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index e2bd223b3b..b79f4e3ceb 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -442,6 +442,8 @@ struct KernSlot { blank: bool, /// Advance along the line (px, horizontal scale included). advance: f32, + /// What horizontal scale adds to the shaped advance (px; negative below 100%). + growth: f32, /// A tab, shaped as a space; it advances to the next tab stop. tab: bool, /// Vertical type, upright glyph (its outline doesn't run along the column). @@ -586,6 +588,12 @@ impl Layouter { for p in style_props(&out.styles[si0], k, &fallback, si0 as u32, small_caps[si0]) { b.push_default(p); } + // Paragraph text breaks a word wider than the box at the box edge, as Photoshop + // does (#6694): parley's default only breaks at UAX #14 opportunities and lets the + // word run out of the box. Point text has no width to overflow. + if is_box { + b.push_default(StyleProperty::OverflowWrap(parley::style::OverflowWrap::BreakWord)); + } for (ri, st) in out.styles.iter().enumerate() { let rs = run_starts[ri]; let (a, z) = (rs.max(prange.start), (rs + runs[ri].len).min(content_end)); @@ -629,6 +637,11 @@ impl Layouter { for (range, size) in &synthetic_small_caps { b.push(StyleProperty::FontSize(*size), range.clone()); } + // Korean breaks lines at spaces, between words, as Photoshop sets it; Unicode's + // default rules break between any two Hangul syllables, mid-word (#5959). + for range in hangul_runs(&ptext) { + b.push(StyleProperty::WordBreak(parley::WordBreak::KeepAll), range); + } for (&at, &spacing) in tabs.iter().zip(tab_spacing) { b.push(StyleProperty::LetterSpacing(spacing), at..at + 1); } @@ -640,11 +653,29 @@ impl Layouter { // Box extent along the lines: width, or height for vertical type (columns). let (line_origin, line_len) = if vertical { (box_rect.1, box_rect.3) } else { (box_rect.0, box_rect.2) }; let avail = if is_box { Some((line_len - indent_start - indent_end).max(1.0)) } else { None }; + // Horizontal scale is applied after shaping, so paragraph text breaks at the box + // width divided by it (#5565). Mixed scales break at the largest, so no line + // overflows the box. + let break_scale = if is_box { + let si0 = style_at(prange.start); + (0..out.styles.len()) + .filter(|&ri| { + let rs = run_starts.get(ri).copied().unwrap_or(0); + let end = rs.saturating_add(runs.get(ri).map_or(0, |r| r.len)); + ri == si0 || (rs.max(prange.start) < end.min(content_end)) + }) + .filter_map(|ri| out.styles.get(ri)) + .map(effective_horizontal_scale) + .fold(0.0f32, f32::max) + } else { + 1.0 + }; + let break_scale = if break_scale > 0.0 { break_scale } else { 1.0 }; let break_lines = |layout: &mut Layout| { if first_indent != 0.0 { - layout.set_text_indent(first_indent, IndentOptions::default()); + layout.set_text_indent(first_indent / break_scale, IndentOptions::default()); } - layout.break_all_lines(avail); + layout.break_all_lines(avail.map(|a| a / break_scale)); }; // Paragraph text: a tab is never wider than a space plus one tab interval, so breaking // lines at that width keeps the expanded tabs inside the box, but can wrap early. @@ -773,6 +804,7 @@ impl Layouter { blank: first.is_none() || c.is_space_or_nbsp() || c.text_range().end <= prefix.len(), upright: vertical && c.first_style().brush.1 != VClass::Rotate as u8, advance: c.advance() * hs, + growth: c.advance() * (hs - 1.0), tab: tabs.binary_search(&c.text_range().start).is_ok(), }); } @@ -817,10 +849,15 @@ impl Layouter { // moves the whole line). let mut pos = indent_start + if li == 0 { first_indent } else { 0.0 }; let mut trailing_tabs = 0.0f32; + let mut trailing_growth = 0.0f32; for (j, s) in slots.iter().enumerate() { + // Trailing whitespace is outside the line's extent (`adv`). + let trailing = s.blank && slots[j + 1..].iter().all(|n| n.blank); + if trailing { + trailing_growth += s.growth; + } if s.tab { kern_px[j] = next_tab_stop(pos, tab_px) - pos - s.advance; - // Trailing whitespace is outside the line's extent (`adv`). if slots[j + 1..].iter().all(|n| n.blank) { trailing_tabs += kern_px[j]; } @@ -858,15 +895,18 @@ impl Layouter { }; let dx = if is_box { let base = line_origin + indent_start - kern_align; - let slack = avail.unwrap_or(0.0) - adv - line_kern; + let slack = avail.unwrap_or(0.0) - adv * break_scale - line_kern; + // Parley aligned the unscaled line in `avail / break_scale`: scale its + // indent and alignment offset back to the box. + let scaled_offset = m.offset * (break_scale - 1.0); base + if last_line { match ps.align { TextAlign::JustifyCenter => slack * 0.5 - m.offset, TextAlign::JustifyRight => slack - m.offset, - _ => 0.0, + _ => scaled_offset, } } else { - 0.0 + scaled_offset } } else { let target = match ps.align { @@ -1031,7 +1071,7 @@ impl Layouter { range: map(lr.start)..map(lr.end).min(content_end), baseline, x0, - x1: x0 + adv + extra - trailing_tabs, + x1: x0 + adv + extra - trailing_tabs - trailing_growth, ascent, descent, paragraph: pi, @@ -1043,6 +1083,11 @@ impl Layouter { } } +/// A style's horizontal scale; unset (zero or negative) is 100%. +fn effective_horizontal_scale(st: &CharStyle) -> f32 { + if st.horizontal_scale > 0.0 && st.horizontal_scale.is_finite() { st.horizontal_scale } else { 1.0 } +} + /// The first tab stop after `pos` (px from the anchor or box edge); stops are `interval` apart. fn next_tab_stop(pos: f32, interval: f32) -> f32 { if interval > 0.0 && pos.is_finite() { ((pos + 1e-3) / interval).floor() * interval + interval } else { pos } @@ -1375,6 +1420,23 @@ fn first_ascent(line: &parley::Line<'_, RunBrush>) -> Option { best } +/// Hangul (syllables and jamo). +fn is_hangul(c: char) -> bool { + matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7AF}' | '\u{D7B0}'..='\u{D7FF}') +} + +/// The byte ranges of `text` made of Hangul, each as long as it runs. +pub(crate) fn hangul_runs(text: &str) -> Vec> { + let mut runs: Vec> = Vec::new(); + for (i, c) in text.char_indices().filter(|&(_, c)| is_hangul(c)) { + match runs.last_mut() { + Some(r) if r.end == i => r.end = i + c.len_utf8(), + _ => runs.push(i..i + c.len_utf8()), + } + } + runs +} + #[cfg(test)] mod tests { use super::{SmallCapsMode, feature_list, small_caps_mode, variation_list}; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index ad5e90ae35..af4de19f52 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -1,4 +1,4 @@ -//! Photocraft's type engine. +//! PhotoCraft's type engine. //! //! * [`fonts::FontDb`]: bundled fonts (Inter, JetBrains Mono; always available, including on the //! web), optional system fonts from platform directory scans plus Fontconfig's Linux file list, diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 0092fcf92e..8c502c75af 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -351,11 +351,14 @@ pub fn text_layer_from_tysh(data: &[u8], dpi: f32) -> Option { if let Some(w) = &t.warp { let style = enum_value(w, "warpStyle").unwrap_or_else(|| "warpNone".into()); if style != "warpNone" { + // Bend and distortion are percentages in -100..100 (as `type.warpText` clamps them); + // clamping before the cast keeps a value beyond f32 from becoming inf. + let pct = |k: &str| dnum(w.get(k)).unwrap_or(0.0).clamp(-100.0, 100.0) as f32; layer.warp = Some(TextWarp { style, - value: dnum(w.get("warpValue")).unwrap_or(0.0) as f32, - horizontal_distortion: dnum(w.get("warpPerspective")).unwrap_or(0.0) as f32, - vertical_distortion: dnum(w.get("warpPerspectiveOther")).unwrap_or(0.0) as f32, + value: pct("warpValue"), + horizontal_distortion: pct("warpPerspective"), + vertical_distortion: pct("warpPerspectiveOther"), horizontal: enum_value(w, "warpRotate").as_deref() != Some("Vrtc"), }); } @@ -1362,6 +1365,19 @@ mod nonfinite_tests { assert_eq!(char_style(None, &d, &[], 1.0).size_pt, 24.0); } + #[test] + fn warp_values_beyond_f32_clamp_to_the_warp_range() { + let warp = Descriptor::new("warp") + .with("warpStyle", enumv("warpStyle", "warpArc")) + .with("warpValue", D::Double(1e39)) + .with("warpPerspective", D::Double(-1e39)) + .with("warpPerspectiveOther", D::Double(250.0)) + .with("warpRotate", enumv("Ornt", "Hrzn")); + let tysh = write_tysh(&TySh { transform: Affine::IDENTITY, text: Descriptor::new("TxLr"), warp: Some(warp), bounds: [0.0; 4] }); + let w = text_layer_from_tysh(&tysh, 72.0).and_then(|l| l.warp).unwrap(); + assert_eq!((w.value, w.horizontal_distortion, w.vertical_distortion), (100.0, -100.0, 100.0)); + } + #[test] fn infinite_dpi_does_not_write_a_zero_size() { let layer = diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index af29dd10d6..39eef20757 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -12,6 +12,9 @@ use crate::layout::{GlyphOrient, PlacedGlyph, TextLayout}; use crate::raster::{Bounds, Coverage, LineSink, Pen, Xform, rect_to}; use crate::warp::{Placement, Warp}; +#[cfg(not(target_arch = "wasm32"))] +use rayon::prelude::*; + /// Faux-italic slant in degrees (Photoshop-like). pub const FAUX_ITALIC_DEG: f32 = 12.0; /// Faux-bold ring radius as a fraction of the font size (tuned so stem weight stays close to the old summed-coverage look). @@ -276,35 +279,57 @@ pub fn rasterize_warped(layout: &TextLayout, transform: &Affine, format: PixelFo } let comps = color_in(&format, c); let a = c.alpha.clamp(0.0, 1.0); - for (i, &cv) in cov.iter().enumerate() { - let cv = if antialias == AntiAlias::None { if cv >= 0.5 { 1.0 } else { 0.0 } } else { cv }; + composite(&mut acc, &cov, w, stride, &comps, a, antialias); + } + // Unpremultiply. + unpremultiply(&mut acc, n, stride, format.sample); + surface.write_region_par(rect, &acc); + surface.prune(); + Rendered { surface, rect } +} + +/// Composites one colour's coverage over the premultiplied accumulator, resolving `AntiAlias::None` +/// to 0/1 first. A pixel's maths reads and writes only its own slots, so the rows are done in any +/// order — one per thread — for exactly the same bytes. +fn composite(acc: &mut [f32], cov: &[f32], width: usize, stride: usize, comps: &[f32], a: f32, antialias: AntiAlias) { + let n = comps.len(); + let row = |acc: &mut [f32], cov: &[f32]| { + for (cv, px) in cov.iter().zip(acc.chunks_exact_mut(stride)) { + let cv = if antialias == AntiAlias::None { if *cv >= 0.5 { 1.0 } else { 0.0 } } else { *cv }; let s = cv * a; if s <= 0.0 { continue; } - let px = &mut acc[i * stride..(i + 1) * stride]; let keep = 1.0 - s; for j in 0..n { px[j] = comps[j] * s + px[j] * keep; } px[n] = s + px[n] * keep; } - } - // Unpremultiply. - for px in acc.chunks_exact_mut(stride) { + }; + #[cfg(not(target_arch = "wasm32"))] + acc.par_chunks_mut(width * stride).zip(cov.par_chunks(width)).for_each(|(a, c)| row(a, c)); + #[cfg(target_arch = "wasm32")] + acc.chunks_mut(width * stride).zip(cov.chunks(width)).for_each(|(a, c)| row(a, c)); +} + +/// Divides the premultiplied accumulator back to straight colour. Each pixel stands alone. +fn unpremultiply(acc: &mut [f32], n: usize, stride: usize, sample: SampleType) { + let one = |px: &mut [f32]| { let a = px[n]; if a > 0.0 { for v in &mut px[..n] { let straight = *v / a; // Float text can carry HDR and signed colours. Keep integer output bounded // and retain the old handling of non-finite intermediate values. - *v = if format.sample == SampleType::F32 && straight.is_finite() { straight } else { straight.clamp(0.0, 1.0) }; + *v = if sample == SampleType::F32 && straight.is_finite() { straight } else { straight.clamp(0.0, 1.0) }; } } - } - surface.write_region(rect, &acc); - surface.prune(); - Rendered { surface, rect } + }; + #[cfg(not(target_arch = "wasm32"))] + acc.par_chunks_exact_mut(stride).for_each(one); + #[cfg(target_arch = "wasm32")] + acc.chunks_exact_mut(stride).for_each(one); } /// One element of a glyph outline in document space (see [`outlines`]). diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 13de665ccd..a6c24e5da0 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1,6 +1,6 @@ use photocraft_color::{Color, PixelFormat, SampleType}; use photocraft_doc::TextLayer; -use photocraft_doc::text::{Caps, CharStyle, FontFeature, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape}; +use photocraft_doc::text::{AntiAlias, Caps, CharStyle, FontFeature, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape}; use photocraft_geom::Affine; use crate::{TextEngine, fonts}; @@ -13,6 +13,38 @@ fn styled(text: &str, style: CharStyle) -> TextLayer { TextLayer { text: text.into(), runs: vec![TextRun { len: text.len(), style }], ..Default::default() } } +/// The rasteriser's pixel stages — composing one colour's coverage, unpremultiplying it, and +/// converting the tiles — are per pixel: no pixel reads a slot another pixel wrote. Spreading them +/// over threads therefore has to leave every byte as it was, which a one-thread pool checks. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn parallel_raster_matches_a_single_thread() { + let one = rayon::ThreadPoolBuilder::new().num_threads(1).build().expect("one-thread pool"); + let mut e = TextEngine::new(); + let boxed = TextShape::Box { x: 0.0, y: 0.0, width: 220.0, height: 90.0 }; + let paragraph = TextLayer { + text: "A paragraph box that wraps over several lines and covers many tiles, so the whole raster is exercised.".into(), + font_family: "Inter".into(), + size_pt: 18.0, + shape: boxed, + ..Default::default() + }; + let no_aa = TextLayer { text: "No AA edge".into(), font_family: "Inter".into(), size_pt: 30.0, antialias: AntiAlias::None, ..Default::default() }; + let cases: Vec<(TextLayer, f32, PixelFormat)> = vec![ + (point("Parallel", 48.0), 72.0, PixelFormat::RGBA8), + (styled("Bold italic", CharStyle { size_pt: 40.0, faux_bold: true, faux_italic: true, ..Default::default() }), 300.0, PixelFormat::RGBA8), + (no_aa, 150.0, PixelFormat::RGBA16), + (styled("Wide gamut", CharStyle { size_pt: 36.0, color: Color::rgba(2.5, -0.25, 0.5, 0.4), ..Default::default() }), 96.0, PixelFormat::RGBA32F), + (with_para(paragraph, ParagraphStyle::default()), 144.0, PixelFormat::RGBA8), + ]; + for (layer, dpi, format) in cases { + let (_, spread) = e.render(&layer, dpi, format); + let (_, single) = one.install(|| e.render(&layer, dpi, format)); + assert_eq!(spread.rect, single.rect, "{}", layer.text); + assert_eq!(spread.surface, single.surface, "{}", layer.text); + } +} + #[test] fn raster_preserves_hdr_and_signed_float_text_colors() { let mut e = TextEngine::new(); @@ -272,6 +304,44 @@ fn box_text_wraps_inside_width() { assert_eq!(l2.lines.len(), 2); } +/// #5565: paragraph text breaks at its horizontally scaled width. At 60% it breaks like 100% +/// text in a box 1/0.6 as wide, and the lines fill the box instead of wrapping early. +#[test] +fn horizontal_scale_breaks_paragraph_lines_at_the_scaled_width() { + let mut e = TextEngine::new(); + let text = "The quick brown fox jumps over the lazy dog again and again until the paragraph wraps"; + let boxed = |scale: f32, width: f32, align: TextAlign| { + let style = CharStyle { font_family: "Inter".into(), size_pt: 12.0, horizontal_scale: scale, ..Default::default() }; + let t = TextLayer { shape: TextShape::Box { x: 10.0, y: 0.0, width, height: 1000.0 }, ..styled(text, style) }; + with_para(t, ParagraphStyle { align, ..Default::default() }) + }; + let ranges = |l: &crate::TextLayout| l.lines.iter().map(|ln| ln.range.clone()).collect::>(); + for scale in [0.6f32, 1.5] { + let scaled = e.layout(&boxed(scale, 120.0, TextAlign::Left), 72.0); + let plain = e.layout(&boxed(1.0, 120.0 / scale, TextAlign::Left), 72.0); + assert!(scaled.lines.len() > 1, "{scale}"); + assert_eq!(ranges(&scaled), ranges(&plain), "{scale}: same breaks as unscaled text in the widened box"); + for (li, ln) in scaled.lines.iter().enumerate() { + assert!(ln.x0 >= 10.0 - 1e-3 && ln.x1 <= 130.0 + 1e-3, "{scale}: {ln:?}"); + // The extent ends at the last glyph, not after the scaled trailing space. + let ink = scaled.clusters.iter().filter(|c| c.line == li && !text[c.range.clone()].trim().is_empty()); + assert!((ink.map(|c| c.x + c.advance).fold(0.0, f32::max) - ln.x1).abs() < 0.01, "{scale}: {ln:?}"); + } + } + // At 60% the lines use the box: the first would not fit at 100%. + let scaled = e.layout(&boxed(0.6, 120.0, TextAlign::Left), 72.0); + assert!(scaled.lines[0].x1 > 110.0, "{:?}", scaled.lines[0]); + // Centred and right-aligned lines are placed by their scaled width. + let c = e.layout(&boxed(0.6, 120.0, TextAlign::Center), 72.0); + for ln in &c.lines { + assert!(((ln.x0 + ln.x1) * 0.5 - 70.0).abs() < 0.5, "{ln:?}"); + } + let r = e.layout(&boxed(0.6, 120.0, TextAlign::Right), 72.0); + for ln in &r.lines { + assert!((ln.x1 - 130.0).abs() < 0.5, "{ln:?}"); + } +} + #[test] fn alignment_point_and_box() { let mut e = TextEngine::new(); @@ -1452,6 +1522,23 @@ fn japanese_box_text_preserves_wrap_boundaries() { assert_eq!(end, text.text.len()); } +/// #5959: Korean box text broke between Hangul syllables, mid-word ("설 / 정이나"). Lines break at +/// the spaces between words, as Photoshop sets Korean; a word longer than the box still breaks. +#[test] +fn korean_box_text_wraps_between_words() { + let mut engine = TextEngine::new(); + let mut text = point("여기서는 각종 설정이나 캐릭터 제작을 진행합니다.", 12.0); + text.shape = TextShape::Box { x: 0.0, y: 0.0, width: 60.0, height: 1000.0 }; + let layout = engine.layout(&text, 72.0); + assert!(layout.lines.len() > 2, "{}", layout.lines.len()); + let words: Vec<&str> = text.text.split(' ').collect(); + for line in &layout.lines { + let content = text.text.get(line.range.clone()).expect("UTF-8 line boundaries").trim(); + assert!(content.split(' ').all(|w| words.contains(&w)), "a line holds whole words only: {content:?}"); + } + assert_eq!(super::layout::hangul_runs("a 한국어 b"), vec![2..11]); +} + /// Which craft-fonts family drew the glyphs of `l` (matched by the embedded bytes). fn craft_family_of(l: &crate::TextLayout) -> Vec<&'static str> { let mut v = Vec::new(); @@ -2008,3 +2095,37 @@ fn hyphenless_postscript_names_split_trailing_styles() { assert_eq!((r.family.as_str(), r.weight, r.italic), (family, weight, italic), "{ps}"); } } + +/// A word wider than its paragraph box wraps at the box edge instead of running past it (#6694); +/// a normal break opportunity still wins, and a box that fits the word lays out exactly as before. +#[test] +fn a_word_wider_than_the_paragraph_box_breaks_at_the_box_edge() { + let mut e = TextEngine::new(); + let word = "BLOQUEADO?!"; + let alone = e.layout(&point(word, 12.0), 72.0); + assert_eq!(alone.lines.len(), 1, "{:?}", alone.lines); + let word_width = width(&alone); + let narrow = 30.0; + assert!(word_width > narrow * 2.0, "{word_width}"); + + let mut t = point(word, 12.0); + t.shape = TextShape::Box { x: 0.0, y: 0.0, width: narrow, height: 200.0 }; + let l = e.layout(&t, 72.0); + assert!(l.lines.len() >= 2, "{:?}", l.lines); + for line in &l.lines { + assert!(line.x1 <= narrow + 0.5, "{line:?}"); + } + let joined: String = l.lines.iter().map(|l| &word[l.range.clone()]).collect(); + assert_eq!(joined, word); + + t.shape = TextShape::Box { x: 0.0, y: 0.0, width: word_width + 20.0, height: 200.0 }; + let fits = e.layout(&t, 72.0); + assert_eq!(fits.lines.len(), 1, "{:?}", fits.lines); + assert!((width(&fits) - word_width).abs() < 0.01, "{} vs {word_width}", width(&fits)); + + let mut spaced = point("ab cd", 12.0); + spaced.shape = TextShape::Box { x: 0.0, y: 0.0, width: narrow, height: 200.0 }; + let l = e.layout(&spaced, 72.0); + assert_eq!(l.lines.len(), 2, "{:?}", l.lines); + assert_eq!(l.lines[1].range.start, 3, "{:?}", l.lines); +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 61f21885f9..e5bf497c81 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -35,6 +35,8 @@ eframe = { workspace = true, features = ["wgpu", "accesskit"] } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# Display order of right-to-left labels (`bidi_text.rs`); already linked through usvg. +unicode-bidi = "0.3" base64 = "0.22" # Inflating the translation catalogs, stored deflated (build.rs); already linked through photocraft-io. flate2 = { workspace = true } diff --git a/crates/ui-egui/examples/snapshot.rs b/crates/ui-egui/examples/snapshot.rs index 31e4c60301..c6ca4cd605 100644 --- a/crates/ui-egui/examples/snapshot.rs +++ b/crates/ui-egui/examples/snapshot.rs @@ -1,4 +1,4 @@ -//! Render the full Photocraft UI offscreen (no window, no focus stealing) and save a PNG. +//! Render the full PhotoCraft UI offscreen (no window, no focus stealing) and save a PNG. //! //! ```sh //! cargo run --release -p photocraft-ui-egui --example snapshot -- \ @@ -54,6 +54,7 @@ fn main() { opts.encode.webp_quality = q; } opts.tga_bits = settings.tga_bits; + opts.encode.dds = settings.dds; photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) })), write: Some(Box::new(|path: &str, bytes: &[u8]| photocraft_format::atomic_write(std::path::Path::new(path), bytes).map_err(|e| e.to_string()))), diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rs index a5c2f15e9b..8b52ba88c5 100644 --- a/crates/ui-egui/src/actions.rs +++ b/crates/ui-egui/src/actions.rs @@ -435,21 +435,29 @@ pub fn insert_stop_confirm(app: &mut PhotocraftApp, fields: &serde_json::Map) { - let Some(r) = fields.get(RESUME) else { return }; +pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) -> Result<(), String> { + let Some(r) = fields.get(RESUME) else { return Ok(()) }; // The dialog's command may run as a background job; the next step needs its result. if let Some(doc) = app.session.active().map(|d| d.doc.id) && let Some(job) = app.session.job_on(doc) + && let Err(e) = app.session.wait_job(job.id) { - let _ = app.session.wait_job(job.id); + let template = "Action playback failed: {error}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e.to_string())]); + app.ui.status_error = true; + return Err(e.to_string()); } let params = json!({"action": r.get("action").cloned().unwrap_or(Value::Null), "from": r.get("from").cloned().unwrap_or(Value::Null)}); match play(app, ¶ms) { - Ok(v) => report_play(app, &v), + Ok(v) => { + report_play(app, &v); + Ok(()) + } Err(e) => { let template = "Action playback failed: {error}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); app.ui.status_error = true; + Err(e) } } } @@ -816,16 +824,28 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.actions.expanded[i] = !expanded; } } - resp.context_menu(|ui| { + // Clicks inside stay open, so Shift and Command can both be ticked; every item that + // finishes closes the menu itself. + egui::Popup::context_menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { ui.label(tl!("Keyboard Shortcuts")); let current = app.session.prefs().shortcuts.get(&shortcut_id(name)).cloned().unwrap_or_default(); - for key in std::iter::once(String::new()).chain((1..=12).map(|n| format!("F{n}"))) { - let label = if key.is_empty() { tl!("None").to_string() } else { key.clone() }; - if ui.selectable_label(current == key, label).clicked() { - let _ = assign_shortcut(app, name, &key); + // Photoshop's Action Options: a function key, with Shift and Command (#7646). + let (key, mut shift, mut command) = photocraft_engine::atn_cmds::parse_function_key(¤t).unwrap_or((0, false, false)); + for n in std::iter::once(0).chain(1..=12) { + let label = if n == 0 { tl!("None").to_string() } else { format!("F{n}") }; + if ui.selectable_label(key == n, label).clicked() { + let chosen = if n == 0 { String::new() } else { photocraft_engine::atn_cmds::function_key_name(n, shift, command) }; + let _ = assign_shortcut(app, name, &chosen); ui.close(); } } + ui.add_enabled_ui(key > 0, |ui| { + let command_label = if cfg!(target_os = "macos") { tl!("Command") } else { tl!("Ctrl") }; + let toggled = ui.checkbox(&mut shift, tl!("Shift")).changed() | ui.checkbox(&mut command, command_label).changed(); + if toggled { + let _ = assign_shortcut(app, name, &photocraft_engine::atn_cmds::function_key_name(key, shift, command)); + } + }); ui.separator(); ui.menu_button(tl!("Color"), |ui| { for (id, label) in [ @@ -1026,6 +1046,44 @@ mod tests { assert!(crate::dock::Group::History.scrolls_itself(1)); } + /// #7646: an action's function key can take Shift and Command, as in Photoshop's Action + /// Options, and only that combination plays it. + #[test] + fn a_function_key_with_shift_and_command_plays_its_action() { + use egui::{Event, Key, Modifiers}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.session.actions.list.push(Action { + name: "Action 1".into(), + steps: vec![("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let key = photocraft_engine::atn_cmds::function_key_name(2, true, true); + assert_eq!(key, "Cmd+Shift+F2"); + assign_shortcut(&mut app, "Action 1", &key).unwrap(); + let ctx = egui::Context::default(); + let press = |app: &mut PhotocraftApp, modifiers| { + ctx.begin_pass(egui::RawInput { + events: vec![ + Event::ModifiersChanged(modifiers), + Event::Key { key: Key::F2, physical_key: None, pressed: true, repeat: false, modifiers }, + Event::Key { key: Key::F2, physical_key: None, pressed: false, repeat: false, modifiers }, + ], + ..Default::default() + }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + let layers = |app: &PhotocraftApp| app.session.active().unwrap().doc.layers.len(); + let before = layers(&app); + press(&mut app, Modifiers::NONE); + press(&mut app, Modifiers::SHIFT); + assert_eq!(layers(&app), before, "F2 and Shift+F2 alone don't play it"); + press(&mut app, Modifiers::SHIFT | Modifiers::COMMAND); + assert_eq!(layers(&app), before + 1, "Cmd+Shift+F2 plays it"); + } + #[test] fn double_clicking_an_action_name_renames_it_in_place() { use egui_kittest::{Harness, kittest::Queryable}; @@ -1543,6 +1601,43 @@ mod tests { assert_eq!(app.session.actions.list[0].steps.len(), 3); } + #[test] + fn dialog_worker_failure_stops_action_before_following_steps() { + for (background, locked) in [(true, true), (false, true), (true, false)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 6, "background": "#203040"})).unwrap(); + let mut action = Action::new( + "Worker Result", + vec![ + ("layer.setProps".into(), json!({"name": "Prefix", "locks": {"pixels": locked}})), + ("filter.blur.gaussianBlur".into(), json!({"radius": 1.5})), + ("layer.new.layer".into(), json!({"name": "Suffix"})), + ], + ); + action.dialogs.insert(1); + app.session.actions.list.push(action); + app.background_jobs = background; + let paused = play(&mut app, &json!({"action": "Worker Result"})).unwrap(); + let dialog = paused["paused"]["dialog"].as_u64().unwrap(); + let result = crate::dialogs::confirm(&mut app, dialog); + let suffix = app.session.active().unwrap().doc.walk().iter().any(|(_, _, layer)| layer.name == "Suffix"); + + assert_eq!(suffix, !locked, "background={background}, locked={locked}: {result:?}"); + if locked && background { + assert!(result.as_ref().is_err_and(|e| e.contains("locked")), "failed worker must fail the dialog confirmation: {result:?}"); + assert!(app.ui.status_error, "the action must report the worker failure"); + assert!(app.ui.status.contains("locked"), "{}", app.ui.status); + assert_eq!(app.session.jobs_with_recent()[0].state, "failed"); + } else if locked { + assert!(result.is_err(), "the foreground command rejects the locked layer"); + } else { + assert!(result.is_ok(), "the successful worker lets the action continue: {result:?}"); + } + assert_eq!(app.session.actions.playing, 0); + assert!(app.session.actions.playback_stack.is_empty()); + } + } + #[test] fn a_dialog_toggled_step_pauses_playback_and_resumes_on_ok() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rs index be9acde2e8..fe483caef9 100644 --- a/crates/ui-egui/src/adjust_dialog.rs +++ b/crates/ui-egui/src/adjust_dialog.rs @@ -79,6 +79,101 @@ pub fn sample_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { true } +/// Whether the top modal is the Curves dialog. +pub fn curves_on_top(app: &PhotocraftApp) -> bool { + app.ui.dialogs.last().is_some_and(|d| d.fields.get("__adjust").and_then(Value::as_str) == Some("curves")) +} + +/// ⌘/Ctrl-click on the image with Curves on top (#7325): a point on the curve shown in the dialog +/// at the clicked pixel's tone, at the output the curve gives there rounded to a whole level, so the +/// image barely changes (where the curve is clipped at 0 or 255 the point re-shapes it, as a click on +/// the graph there does); with `every_channel` (Shift) one on each colour channel instead, at that +/// channel's value. +/// The pixel comes from the same merged composite as the eyedroppers. Returns true when Curves is +/// on top: the click is the dialog's even when nothing is added (pencil curve, Lab or CMYK, a mask +/// or saved channel target, outside the image, a full curve). +pub fn add_point_at(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64, every_channel: bool) -> bool { + if !curves_on_top(app) { + return false; + } + let Some((id, mut values)) = app.ui.dialogs.last().map(|d| (d.id, crate::filter_dialog::params_of(&d.fields))) else { return false }; + if values.get("pencil").and_then(Value::as_bool) == Some(true) { + return true; + } + let Some(mode) = app.session.active().map(|s| s.doc.mode) else { return true }; + if !matches!(mode, photocraft_doc::ColorMode::Rgb | photocraft_doc::ColorMode::Grayscale) { + app.ui.status = tl!("Unavailable in this color mode").into(); + return true; + } + // A mask, saved channel or Quick Mask holds its own gray levels, not the composite's. + let isolated = isolated(app); + if isolated.as_ref().is_some_and(|c| c.gray.is_some()) { + return true; + } + let Some(sample) = crate::canvas::composite_color(app, x, y) else { return true }; + let gray = adjust_editors::is_gray(mode); + let (shown, shown_key) = match &isolated { + Some(c) => (0, c.key), + None => { + let ch: usize = ctx.data(|d| d.get_temp(dialog_mem("curves").with("curves-ch"))).unwrap_or(0); + let chans = adjust_editors::tone_channels(adjust_editors::space_of(&values), gray); + (ch, chans.get(ch).map_or("", |c| c.key)) + } + }; + let keys: &[&str] = if every_channel && !gray && isolated.is_none() { &["red", "green", "blue"] } else { &[shown_key] }; + let mut selected = None; + let mut changed = false; + for &key in keys { + let level = match key { + "red" => sample[0], + "green" => sample[1], + "blue" => sample[2], + // The composite's tone: Gray's mean, as the Grayscale eyedroppers read it, and RGB's + // Rec. 709 luma, as the Neutral Gray eyedropper does (`adjust_params::rgb_luma`). + _ if gray => (sample[0] + sample[1] + sample[2]) / 3.0, + _ => sample[0] * 0.2126 + sample[1] * 0.7152 + sample[2] * 0.0722, + }; + let input = (level.clamp(0.0, 1.0) * 255.0).round(); + let field = if key.is_empty() { "points" } else { key }; + let mut pts = adjust_editors::read_curve(&values, field); + let curve: Vec<_> = pts.iter().map(|q| photocraft_doc::adjust::CurvePoint { input: q[0] / 255.0, output: q[1] / 255.0 }).collect(); + let lut = photocraft_compose::adjust::curve_lut(&curve); + let at = (input / 255.0 * lut.len().saturating_sub(1) as f32).round() as usize; + let Some(output) = lut.get(at).map(|o| (o * 255.0).round()) else { continue }; + let before = pts.len(); + let Some(i) = crate::point_curve::insert(&mut pts, [input, output]) else { continue }; + if pts.len() > before { + // Whole levels, as the editor writes a point clicked on the graph. + values[field] = json!(pts.iter().map(|q| [q[0].round(), q[1].round()]).collect::>()); + changed = true; + } + if key == shown_key { + selected = Some(i); + } + } + if let Some(i) = selected { + let state = dialog_mem("curves").with("curves"); + ctx.data_mut(|d| { + let mut st: crate::state::CurvesEditorState = d.get_temp(state).unwrap_or_default(); + st.channel = shown; + st.gesture = crate::state::PointCurveState { selected: Some(i), drag: None }; + d.insert_temp(state, st); + }); + } + if changed + && let Some(dialog) = app.ui.dialog_mut(id) + && let Value::Object(v) = values + { + dialog.fields.retain(|k, _| k.starts_with("__")); + dialog.fields.extend(v); + if picker(dialog.fields.get(CURVE_PICKER)).is_some() { + let base = crate::filter_dialog::params_of(&dialog.fields); + dialog.fields.insert(CURVE_PICKER_BASE.into(), base); + } + } + true +} + pub(crate) fn picker_button(ui: &mut egui::Ui, selected: bool, enabled: bool, tooltip: &str, color: egui::Color32) -> egui::Response { let response = ui.add_enabled_ui(enabled, |ui| crate::icons::button(ui, "pipette", 28.0, selected, tooltip)).inner; let tokens = crate::theme::Tokens::get(ui.ctx()); @@ -767,6 +862,139 @@ mod tests { } } + fn pointer_down(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64, modifiers: Value) { + let (request, _receiver) = + crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": x, "y": y}], "modifiers": modifiers})); + let _ = crate::control::handle(app, ctx, &request); + } + + /// The Curves curve `pts` (0-255 levels) as a 256-entry 0-255 map. + fn curve_levels(pts: &[[f64; 2]]) -> Vec { + let cp: Vec<_> = pts.iter().map(|q| photocraft_doc::adjust::CurvePoint { input: q[0] as f32 / 255.0, output: q[1] as f32 / 255.0 }).collect(); + let lut = photocraft_compose::adjust::curve_lut(&cp); + (0..256).map(|k| lut[(k as f32 / 255.0 * (lut.len() - 1) as f32).round() as usize] * 255.0).collect() + } + + /// #7325: ⌘/Ctrl-click on the image puts a point on the shown curve at the pixel's tone + /// (#b04020: Rec. 709 luma 85.5 → level 86) and at the curve's own output there, so the + /// image does not change; the new point is the selected one, and the document waits for OK. + #[test] + fn command_click_on_the_image_adds_a_point_on_the_composite_curve() { + let mut app = app_with_image(); + let original = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + let base = [[0.0, 0.0], [128.0, 200.0], [255.0, 255.0]]; + app.ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!(base)); + let ctx = egui::Context::default(); + let sample = crate::canvas::composite_color(&mut app, 8.0, 8.0).unwrap(); + let level = ((sample[0] * 0.2126 + sample[1] * 0.7152 + sample[2] * 0.0722) * 255.0).round(); + assert_eq!(level, 86.0); + let output = f64::from(curve_levels(&base)[86].round()); + assert_ne!(output, 86.0, "the base curve is not the identity at the sampled level"); + + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); + let points = channel_points(&app, "points"); + assert_eq!(points, vec![base[0], [86.0, output], base[1], base[2]]); + let (before, after) = (curve_levels(&base), curve_levels(&points)); + assert!(before.iter().zip(&after).all(|(a, b)| (a - b).abs() <= 0.5), "the curve keeps its shape:\n{before:?}\n{after:?}"); + let st: crate::state::CurvesEditorState = ctx.data(|d| d.get_temp(dialog_mem("curves").with("curves"))).unwrap(); + assert_eq!((st.channel, st.gesture.selected), (0, Some(1)), "the new point is selected"); + for key in ["red", "green", "blue"] { + assert_eq!(channel_points(&app, key), vec![[0.0, 0.0], [255.0, 255.0]], "{key} untouched"); + } + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + } + + /// #7325: Shift+⌘-click puts a point on each colour channel at that channel's own value + /// (176, 64, 32), and leaves the composite curve alone. + #[test] + fn shift_command_click_adds_a_point_on_each_colour_channel() { + let mut app = app_with_image(); + open(&mut app, "image.adjustments.curves").unwrap(); + let ctx = egui::Context::default(); + let composite = channel_points(&app, "points"); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true, "shift": true})); + for (key, level) in [("red", 176.0), ("green", 64.0), ("blue", 32.0)] { + assert_eq!(channel_points(&app, key), vec![[0.0, 0.0], [level, level], [255.0, 255.0]], "{key}"); + } + assert_eq!(channel_points(&app, "points"), composite); + } + + /// #7325: with Red shown in the Channel popup the point goes on the red curve, at red's value. + #[test] + fn command_click_adds_the_point_on_the_channel_shown_in_the_dialog() { + let mut app = app_with_image(); + open(&mut app, "image.adjustments.curves").unwrap(); + let ctx = egui::Context::default(); + ctx.data_mut(|d| d.insert_temp(dialog_mem("curves").with("curves-ch"), 1usize)); + let composite = channel_points(&app, "points"); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); + assert_eq!(channel_points(&app, "red"), vec![[0.0, 0.0], [176.0, 176.0], [255.0, 255.0]]); + for key in ["green", "blue"] { + assert_eq!(channel_points(&app, key), vec![[0.0, 0.0], [255.0, 255.0]], "{key} untouched"); + } + assert_eq!(channel_points(&app, "points"), composite); + let st: crate::state::CurvesEditorState = ctx.data(|d| d.get_temp(dialog_mem("curves").with("curves"))).unwrap(); + assert_eq!((st.channel, st.gesture.selected), (1, Some(1))); + } + + /// #7325: a plain click, a full curve and an armed eyedropper add nothing. + #[test] + fn command_click_adds_nothing_without_the_modifier_on_a_full_curve_or_with_an_eyedropper() { + let mut app = app_with_image(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + let ctx = egui::Context::default(); + let before = crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({})); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before, "no modifier, no point"); + // Space and the middle button pan, as with the mouse. + for extra in [json!({"modifiers": {"command": true, "space": true}}), json!({"command": true, "button": "middle"})] { + let mut params = json!({"events": [{"kind": "down", "x": 8, "y": 8}]}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", params); + let _ = crate::control::handle(&mut app, &ctx, &request); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before, "{extra}"); + } + + // Sixteen points (the most a curve holds), none within reach of level 86. + let full: Vec<[f64; 2]> = + [0, 10, 20, 30, 40, 50, 60, 70, 80, 100, 120, 140, 160, 180, 200, 255].iter().map(|&i| [f64::from(i), f64::from(i)]).collect(); + app.ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!(full)); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); + assert_eq!(channel_points(&app, "points"), full, "a full curve takes no more points and moves none"); + + let mut app = app_with_image(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + arm(&mut app, id, "black"); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); + assert_eq!(channel_points(&app, "points").len(), 2, "the armed eyedropper samples instead"); + assert_eq!(channel_points(&app, "red")[0], [176.0, 0.0]); + } + + /// #7325: Lab and CMYK curves and a targeted mask are left to a later change: nothing is added. + #[test] + fn command_click_adds_nothing_in_lab_or_on_a_targeted_mask() { + let ctx = egui::Context::default(); + let mut lab = app_in_mode("lab"); + lab.run("edit.fill", json!({"color": "#b04020"})).unwrap(); + let id = open(&mut lab, "image.adjustments.curves").unwrap(); + let before = crate::filter_dialog::params_of(&lab.ui.dialog_mut(id).unwrap().fields); + assert!(add_point_at(&mut lab, &ctx, 4.0, 4.0, false)); + assert_eq!(crate::filter_dialog::params_of(&lab.ui.dialog_mut(id).unwrap().fields), before); + + let mut masked = app_with_image(); + masked.run("layer.layerMask.revealAll", json!({})).unwrap(); + masked.run("channel.target", json!({"channel": "mask"})).unwrap(); + let id = open(&mut masked, "image.adjustments.curves").unwrap(); + let before = crate::filter_dialog::params_of(&masked.ui.dialog_mut(id).unwrap().fields); + assert!(add_point_at(&mut masked, &ctx, 8.0, 8.0, false)); + assert_eq!(crate::filter_dialog::params_of(&masked.ui.dialog_mut(id).unwrap().fields), before); + } + #[test] fn ui_pointer_drives_an_armed_curves_picker() { let mut app = app_with_image(); diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs index 87a81b8c35..0c4d5ae268 100644 --- a/crates/ui-egui/src/adjust_editors.rs +++ b/crates/ui-egui/src/adjust_editors.rs @@ -216,7 +216,7 @@ fn sliders(ui: &mut egui::Ui, v: &mut Value, rows: &[SliderRow]) -> Edit { for &(key, text, min, max, default, unit, decimals) in rows { let mut x = num(v, key, default).clamp(min, max); // A double-click on the slider puts it back to its default (Photoshop). - let gestures = widgets::RowGestures { reset: Some(default), wheel_step: None }; + let gestures = widgets::RowGestures { reset: Some(default), wheel_step: None, ..Default::default() }; let r = widgets::slider_row_prec(ui, text, &mut x, min..=max, unit, None, gestures, decimals); if r.changed() { v[key] = json!(row_value(x, min, max, decimals)); @@ -362,7 +362,7 @@ fn curve_graph(full: Rect, side: f32) -> Rect { Rect::from_min_max(base.min + vec2(CURVE_GRAPH_PADDING, CURVE_GRAPH_PADDING), base.max - vec2(CURVE_GRAPH_PADDING, CURVE_GRAPH_PADDING)) } -fn read_curve(v: &Value, key: &str) -> Vec<[f32; 2]> { +pub(crate) fn read_curve(v: &Value, key: &str) -> Vec<[f32; 2]> { let pts: Vec<[f32; 2]> = v .get(key) .and_then(Value::as_array) @@ -1095,7 +1095,7 @@ fn color_balance(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { ]; // Photoshop: a double-click on a slider zeroes it (this tone only); the dialog's sliders step // with the wheel; Up/Down step the fields; Shift makes those steps 10. - let gestures = widgets::RowGestures { reset: Some(0.0), wheel_step: cx.dialog.then_some(1.0) }; + let gestures = widgets::RowGestures { reset: Some(0.0), wheel_step: cx.dialog.then_some(1.0), ..Default::default() }; let mut changed = false; for (i, (text, a, b)) in rows.iter().enumerate() { let r = Edit::of(&widgets::slider_row_with(ui, text, &mut vals[i], -100.0..=100.0, "", Some(&[*a, *b]), gestures)); diff --git a/crates/ui-egui/src/adjust_preview.rs b/crates/ui-egui/src/adjust_preview.rs index d94d58bff6..f74afc8595 100644 --- a/crates/ui-egui/src/adjust_preview.rs +++ b/crates/ui-egui/src/adjust_preview.rs @@ -436,6 +436,9 @@ pub(crate) fn retain_documents(app: &mut PhotocraftApp) { if app.adjust_preview.as_ref().is_some_and(|p| !app.session.documents().iter().any(|st| st.doc.id == p.doc)) { app.adjust_preview = None; } + if app.live_adjust_preview.as_ref().is_some_and(|p| !app.session.documents().iter().any(|st| st.doc.id == p.doc)) { + app.live_adjust_preview = None; + } } /// GPU texture keys the preview uses besides the documents' own (keep them alive). @@ -444,6 +447,108 @@ pub fn gpu_keys(app: &PhotocraftApp) -> Option { p.proxy.as_ref().map(|g| g.base.id.0) } +// --------------------------------------------------------------------------------------------- +// The Properties panel's live adjustment-layer preview (`canvas::display_doc`'s `live_adjust`). +// +// Dragging a control there shows the document with that layer's adjustment replaced. Unlike the +// dialog above it needs no temporary layer: the layer is already in the document. What it did +// lack was a damage region, so every parameter value recomposited the whole document — on the +// GPU canvas at 100 % zoom that is the full size, measured at about 7 ms per megapixel, which +// made #5778 a latency regression (#6839). These give that path the same treatment the dialog +// gets: a session-tagged key, the layer's area as the damage, and of that only what the view +// shows, catching up as the view moves. + +/// Tag of the Properties-panel live-adjust preview keys. Distinct from [`TAG`], so a key is +/// never mistaken for the dialog's. +pub const LIVE_TAG: u64 = 1 << 58; +/// Bits of a live-adjust key that identify the session (document, revision, layer); below them +/// the settings hash. The session occupies bits 40..58, under [`LIVE_TAG`]. +const LIVE_SESSION_SHIFT: u32 = 40; +/// Mask of the session part of a live-adjust key (18 bits). +const LIVE_SESSION_MASK: u64 = (1 << 18) - 1; + +/// One Properties-panel drag: which layer of which document revision, the area its adjustment +/// can change, and what the canvas has composited of it so far. +pub struct LiveAdjust { + doc: DocId, + revision: u64, + session: u64, + region: Rect, + /// The main canvas texture shows preview `key` only within this rect; elsewhere in the + /// region it is older (see [`live_uncovered`]). + covered: Option<(u64, Rect)>, +} + +/// The area an adjustment layer can change: the whole document. +/// +/// It is deliberately not narrowed by the layer's mask. A mask's coverage can live entirely in +/// its surface's *default pixel* with no tiles written — [`LayerMask::reveal_all`], which is what +/// `layer.newAdjustmentLayer` gives every adjustment layer — and such a mask reports an empty +/// `content_bounds()`. Intersecting with that emptied the region, so the damage was empty and the +/// compositor drew nothing at all for the whole drag. A mask only bounds the effect when it hides +/// outside its content (default pixel 0); that narrowing is worth little here, since the damage is +/// clipped to the view anyway ([`live_switch_damage`]), and is not worth the risk of showing stale +/// pixels. Too large only costs pixels; too small freezes the preview. +fn live_region(doc: &Document, layer: LayerId) -> Rect { + if doc.layer(layer).is_none() { + return Rect::EMPTY; + } + doc.bounds() +} + +/// The preview key for `params` on `layer` of `doc` at `revision`, starting a session (and +/// measuring its region) when the document, revision or layer changes. +pub fn live_key(app: &mut PhotocraftApp, doc: &Document, revision: u64, layer: LayerId, params: &Value) -> u64 { + let session = hash(&[&doc.id.0.to_le_bytes(), &revision.to_le_bytes(), &layer.0.to_le_bytes()]); + if app.live_adjust_preview.as_ref().is_none_or(|p| p.session != session) { + app.live_adjust_preview = Some(LiveAdjust { doc: doc.id, revision, session, region: live_region(doc, layer), covered: None }); + } + let h = hash(&[params.to_string().as_bytes()]); + LIVE_TAG | ((session & LIVE_SESSION_MASK) << LIVE_SESSION_SHIFT) | (h & ((1 << LIVE_SESSION_SHIFT) - 1)) +} + +/// The canvas area to recomposite when document `doc` (at `revision`) switches between two of +/// this drag's previews, or between one and the committed document (0). +pub fn live_switch_region(app: &PhotocraftApp, doc: DocId, revision: u64, from: u64, to: u64) -> Option { + let p = app.live_adjust_preview.as_ref()?; + if p.doc != doc || p.revision != revision { + return None; + } + let prefix = LIVE_TAG | ((p.session & LIVE_SESSION_MASK) << LIVE_SESSION_SHIFT); + let ours = |k: u64| k == 0 || k >> LIVE_SESSION_SHIFT == prefix >> LIVE_SESSION_SHIFT; + (ours(from) && ours(to) && (from != 0 || to != 0)).then_some(p.region) +} + +/// The part of a switch's region to composite now: to a preview, only what the view shows, +/// remembered so [`live_uncovered`] catches up as the view moves; back to the committed +/// document (key 0), the whole region. +pub fn live_switch_damage(app: &mut PhotocraftApp, to: u64, region: Rect, visible: Rect) -> Rect { + let Some(p) = app.live_adjust_preview.as_mut() else { return region }; + if to == 0 { + p.covered = None; + return region; + } + let shown = region.intersect(&visible); + p.covered = Some((to, shown)); + shown +} + +/// Where the main canvas texture (showing preview `key`) is out of date within `visible`: the +/// region's visible part when the view moved past what was composited. Marks it covered. +pub fn live_uncovered(app: &mut PhotocraftApp, doc: DocId, key: u64, visible: Rect) -> Option { + let p = app.live_adjust_preview.as_mut().filter(|p| p.doc == doc)?; + let (k, cov) = p.covered?; + if k != key { + return None; + } + let want = p.region.intersect(&visible); + if want.is_empty() || cov.contains_rect(&want) { + return None; + } + p.covered = Some((k, want)); + Some(want) +} + #[cfg(test)] #[path = "adjust_preview_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/adjust_preview_tests.rs b/crates/ui-egui/src/adjust_preview_tests.rs index f3e33a723b..0b5337da7a 100644 --- a/crates/ui-egui/src/adjust_preview_tests.rs +++ b/crates/ui-egui/src/adjust_preview_tests.rs @@ -333,3 +333,60 @@ fn proxy_preview_has_its_own_ids() { } assert!(proxy_with_settings(&proxy, "levels", &json!({"gamma": "x"})).is_err()); } + +/// A Properties-panel drag damages the layer's area and only the part of it the view shows, +/// catching up as the view moves; a new document revision ends the session (#6839). +#[test] +fn a_live_adjust_drag_damages_only_the_visible_part_of_its_layer() { + let (doc, target) = document(ColorMode::Rgb, SampleType::U8, false); + let (id, bounds) = (doc.id, doc.bounds()); + let mut app = app_with(doc.clone(), target); + + let k1 = live_key(&mut app, &doc, 7, target, &json!({"gamma": 1.1})); + let k2 = live_key(&mut app, &doc, 7, target, &json!({"gamma": 1.4})); + assert_ne!(k1, k2, "a different setting is a different key"); + assert_eq!(k1 & LIVE_TAG, LIVE_TAG, "keys carry the live tag"); + assert_eq!(k1 >> LIVE_SESSION_SHIFT, k2 >> LIVE_SESSION_SHIFT, "the same drag is one session"); + assert_ne!(k1 >> LIVE_SESSION_SHIFT, TAG >> LIVE_SESSION_SHIFT, "never the dialog's tag"); + + // Between two of the drag's previews, and between one and the committed document. + let region = live_switch_region(&app, id, 7, k1, k2).expect("same session"); + assert_eq!(region, bounds, "the region is the whole document"); + assert!(live_switch_region(&app, id, 7, 0, k2).is_some(), "from the committed document"); + assert!(live_switch_region(&app, id, 7, k1, 0).is_some(), "back to the committed document"); + assert!(live_switch_region(&app, id, 7, 0, 0).is_none(), "the document to itself is no switch"); + assert!(live_switch_region(&app, id, 8, k1, k2).is_none(), "another revision is another session"); + + // Only the visible part is composited now; moving the view asks for the rest. + let mid = region.x0 + region.width() as i32 / 2; + let left = Rect::new(region.x0, region.y0, mid, region.y1); + assert_eq!(live_switch_damage(&mut app, k2, region, left), region.intersect(&left)); + assert!(live_uncovered(&mut app, id, k2, left).is_none(), "what was just composited is covered"); + let right = Rect::new(mid, region.y0, region.x1, region.y1); + assert_eq!(live_uncovered(&mut app, id, k2, right), Some(region.intersect(&right)), "the view moved"); + assert!(live_uncovered(&mut app, id, k2, right).is_none(), "and is covered once composited"); + assert!(live_uncovered(&mut app, id, k1, right).is_none(), "another preview's coverage is not this one's"); + + // Switching back to the document composites the whole region, not just the view. + assert_eq!(live_switch_damage(&mut app, 0, region, left), region); +} + +/// A reveal-all mask stores its coverage in the surface's default pixel and reports an empty +/// `content_bounds()`. Narrowing the region by it emptied the damage and the canvas drew nothing +/// for a whole drag — every adjustment layer `layer.newAdjustmentLayer` creates has one (#6839). +#[test] +fn a_reveal_all_mask_does_not_empty_the_damage_region() { + let (mut doc, target) = document(ColorMode::Rgb, SampleType::U8, false); + let bounds = doc.bounds(); + let mask = photocraft_doc::LayerMask::reveal_all(); + assert!(mask.surface.content_bounds().is_empty(), "a reveal-all mask has no written content"); + doc.layer_mut(target).expect("target").mask = Some(mask); + let id = doc.id; + let mut app = app_with(doc.clone(), target); + + let k1 = live_key(&mut app, &doc, 3, target, &json!({"gamma": 1.1})); + let k2 = live_key(&mut app, &doc, 3, target, &json!({"gamma": 1.4})); + let region = live_switch_region(&app, id, 3, k1, k2).expect("same session"); + assert_eq!(region, bounds, "the whole document, not the mask's empty content"); + assert!(!live_switch_damage(&mut app, k2, region, bounds).is_empty(), "something is composited"); +} diff --git a/crates/ui-egui/src/analysis_ui.rs b/crates/ui-egui/src/analysis_ui.rs index 09aaf17670..527d58eda0 100644 --- a/crates/ui-egui/src/analysis_ui.rs +++ b/crates/ui-egui/src/analysis_ui.rs @@ -281,7 +281,8 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> set_ruler(app, r); } (Tool::Ruler, ToolEvent::Up { .. }) => { - if app.ui.analysis.drag.take() == Some(Drag::RulerNew) && doc.measurement.ruler.is_some_and(|r| dist(r.start, r.end) < 0.5) { + let drag = app.ui.analysis.drag.take(); + if drag == Some(Drag::RulerNew) && doc.measurement.ruler.is_some_and(|r| dist(r.start, r.end) < 0.5) { let _ = app.run("image.analysis.rulerTool", json!({"clear": true})); } } @@ -743,7 +744,8 @@ pub fn windows(app: &mut PhotocraftApp, ctx: &egui::Context) { } } Some((id, p)) => { - if app.run(id, p).is_ok() { + let result = app.run(id, p); + if result.is_ok() { app.ui.analysis.log_selected.clear(); } } diff --git a/crates/ui-egui/src/artboard_tool.rs b/crates/ui-egui/src/artboard_tool.rs index 0b12c36127..7f8ee838c6 100644 --- a/crates/ui-egui/src/artboard_tool.rs +++ b/crates/ui-egui/src/artboard_tool.rs @@ -182,7 +182,9 @@ fn follow(d: &mut ArtboardDrag, p: [f64; 2], mods: egui::Modifiers) { /// Pointer input for the Artboard tool. Returns true when the event was its own. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { - if app.ui.tool != Tool::Artboard { + // ⌘ is the Move tool (`hold_keys::cmd_moves`): a press with it held is not this tool's, + // so it drags a guide or the layer (#6288). A drag already under way keeps its events. + if app.ui.tool != Tool::Artboard || (app.ui.artboard_tool.drag.is_none() && crate::canvas::event_tool(app, mods) != Tool::Artboard) { return false; } let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return true }; diff --git a/crates/ui-egui/src/bidi_text.rs b/crates/ui-egui/src/bidi_text.rs new file mode 100644 index 0000000000..babb0d0c48 --- /dev/null +++ b/crates/ui-egui/src/bidi_text.rs @@ -0,0 +1,203 @@ +//! Right-to-left text in labels that egui draws (#5159). +//! +//! egui shapes text in runs of one font face and places the runs left to right. An Arabic or +//! Hebrew word is one run, which the shaper draws right to left, but the space between two words +//! comes from another font, so a phrase came out with every word correct and the word order +//! reversed ("THIS IS A TEXT" read as "TEXT A IS THIS"). [`visual`] puts a label into display +//! order with the Unicode Bidirectional Algorithm before egui lays it out: words of a +//! right-to-left script stay in logical order (the shaper reverses them itself), and everything +//! else in a right-to-left run is reversed around them, with brackets mirrored. +//! +//! For display only: never store the result or put it in an editable field. + +use std::borrow::Cow; + +use unicode_bidi::{BidiClass, BidiInfo, Level, bidi_class}; + +/// `text` in the order egui should lay it out from left to right. Text without right-to-left +/// characters comes back unchanged, without allocating. +pub fn visual(text: &str) -> Cow<'_, str> { + visual_at(text, None) +} + +/// [`visual`] for a line that reads left to right as a whole even when it starts with a +/// right-to-left name, such as the title bar's "*صورة.psd — PhotoCraft": with the paragraph +/// direction taken from the name, the "— PhotoCraft" tail moved to the left. +pub fn visual_ltr(text: &str) -> Cow<'_, str> { + visual_at(text, Some(Level::ltr())) +} + +/// Whether `text` reads right to left as a paragraph: its first strong letter is Hebrew, Arabic… +pub fn is_rtl_paragraph(text: &str) -> bool { + text.chars() + .find_map(|c| match bidi_class(c) { + BidiClass::L => Some(false), + BidiClass::R | BidiClass::AL => Some(true), + _ => None, + }) + .unwrap_or(false) +} + +/// `text` in display order, cut with "…" where it doesn't fit (`fits` measures a display-order +/// string). A right-to-left name is cut in logical order before it is reordered, so its *start* +/// stays and the "…" lands at the left, the end of a right-to-left line; cutting after the +/// reordering lost the start of the name instead. `None`: `text` fits as it is (or a +/// left-to-right one, which the caller elides at its right end as usual). +pub fn elide(text: &str, fits: impl Fn(&str) -> bool) -> Option { + if !is_rtl_paragraph(text) || fits(&visual(text)) { + return None; + } + // The longest logical prefix (whole characters) that fits with "…" after it. + let ends: Vec = text.char_indices().map(|(i, _)| i).skip(1).chain(std::iter::once(text.len())).collect(); + let cut = |n: usize| -> String { + let end = if n == 0 { 0 } else { ends.get(n - 1).copied().unwrap_or(text.len()) }; + visual(&format!("{}…", text.get(..end).unwrap_or_default().trim_end())).into_owned() + }; + let (mut lo, mut hi) = (0usize, ends.len()); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + if fits(&cut(mid)) { lo = mid } else { hi = mid - 1 } + } + Some(cut(lo)) +} + +fn visual_at(text: &str, level: Option) -> Cow<'_, str> { + if !text.chars().any(is_rtl) { + return Cow::Borrowed(text); + } + let info = BidiInfo::new(text, level); + let mut out = String::with_capacity(text.len()); + for para in &info.paragraphs { + let (levels, runs) = info.visual_runs(para, para.range.clone()); + for run in runs { + let Some(slice) = text.get(run.clone()) else { continue }; + if levels.get(run.start).is_some_and(|level| level.is_rtl()) { + push_reversed(slice, &mut out); + } else { + out.push_str(slice); + } + } + } + Cow::Owned(out) +} + +/// A strong right-to-left letter, or any character of a right-to-left script block (Arabic +/// punctuation such as "،" belongs with the word it follows: the same font shapes both). +fn is_rtl(c: char) -> bool { + matches!(bidi_class(c), BidiClass::R | BidiClass::AL) || matches!(c, '\u{0590}'..='\u{08FF}' | '\u{FB1D}'..='\u{FDFF}' | '\u{FE70}'..='\u{FEFC}') +} + +/// Characters that stay inside a right-to-left word: its letters, combining marks, and joiners. +fn keeps_with_word(c: char) -> bool { + is_rtl(c) || matches!(bidi_class(c), BidiClass::NSM | BidiClass::BN) +} + +/// Append a right-to-left run in left-to-right display order: right-to-left words stay whole and +/// in logical order, every other character is reversed around them, and brackets are mirrored. +fn push_reversed(run: &str, out: &mut String) { + let mut units: Vec<&str> = Vec::new(); + let mut word: Option = None; + for (i, c) in run.char_indices() { + if keeps_with_word(c) { + word.get_or_insert(i); + continue; + } + if let Some(start) = word.take() + && let Some(w) = run.get(start..i) + { + units.push(w); + } + if let Some(single) = run.get(i..i + c.len_utf8()) { + units.push(single); + } + } + if let Some(start) = word + && let Some(w) = run.get(start..) + { + units.push(w); + } + for unit in units.into_iter().rev() { + let mut chars = unit.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) if !keeps_with_word(c) => out.push(mirror(c)), + _ => out.push_str(unit), + } + } +} + +/// The mirrored form of a bracket shown in right-to-left text. +fn mirror(c: char) -> char { + match c { + '(' => ')', + ')' => '(', + '[' => ']', + ']' => '[', + '{' => '}', + '}' => '{', + '<' => '>', + '>' => '<', + '«' => '»', + '»' => '«', + other => other, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn left_to_right_text_is_untouched_and_not_copied() { + for text in ["PhotoCraft", "Layer 1", "", "Background copy (2)", "日本語のレイヤー"] { + assert!(matches!(visual(text), Cow::Borrowed(t) if t == text), "{text}"); + } + } + + /// #5159: the reported layer name. Each word stays as typed; the word order flips so that + /// egui, placing words left to right, shows the first word at the right. + #[test] + fn arabic_words_are_placed_right_to_left() { + assert_eq!(visual("لاشي مكتوب هنا"), "هنا مكتوب لاشي"); + assert_eq!(visual("שלום עולם"), "עולם שלום"); + } + + #[test] + fn numbers_and_latin_keep_their_own_order() { + // A number inside right-to-left text reads left to right, at the start of the line. + assert_eq!(visual("طبقة 2"), "2 طبقة"); + assert_eq!(visual("طبقة 12"), "12 طبقة"); + // A left-to-right name with an Arabic word at the end is left as it is. + assert_eq!(visual("Layer 1 نص"), "Layer 1 نص"); + // Latin inside an Arabic name stays readable. + assert_eq!(visual("نص PhotoCraft هنا"), "هنا PhotoCraft نص"); + } + + /// #5385 review: the title bar's line is left to right as a whole, so a right-to-left + /// document name keeps "— PhotoCraft" after it, at the right. + #[test] + fn the_title_line_stays_left_to_right_around_a_right_to_left_name() { + assert_eq!(visual_ltr("*صورة.psd — PhotoCraft"), "*صورة.psd — PhotoCraft"); + assert_eq!(visual_ltr("لاشي مكتوب.png — PhotoCraft"), "مكتوب لاشي.png — PhotoCraft"); + assert!(matches!(visual_ltr("Untitled-1 — PhotoCraft"), Cow::Borrowed(_))); + } + + /// #5385 review: a right-to-left name that doesn't fit keeps its first words and ends with + /// "…" at the left; a left-to-right or fitting name is left to the caller. + #[test] + fn right_to_left_names_are_cut_at_their_logical_end() { + let fits = |n: usize| move |s: &str| s.chars().count() <= n; + // Cut anywhere, as egui elides: the first word and the start of the second. + assert_eq!(elide("لاشي مكتوب هنا", fits(8)).as_deref(), Some("…مك لاشي")); + assert_eq!(elide("לשלום עולם גדול", fits(11)).as_deref(), Some("…עולם לשלום")); + assert_eq!(elide("لاشي مكتوب هنا", fits(40)), None, "fits"); + assert_eq!(elide("Layer copy 12", fits(4)), None, "left to right: elided by egui at its end"); + assert_eq!(elide("نص", fits(0)).as_deref(), Some("…"), "nothing fits: just the ellipsis"); + assert!(is_rtl_paragraph("12 نص") && !is_rtl_paragraph("Layer نص") && !is_rtl_paragraph("123")); + } + + #[test] + fn brackets_mirror_and_arabic_punctuation_stays_with_its_word() { + assert_eq!(visual("نص (1)"), "(1) نص"); + assert_eq!(visual("مرحبا، عالم"), "عالم مرحبا،"); + } +} diff --git a/crates/ui-egui/src/blend_preview.rs b/crates/ui-egui/src/blend_preview.rs index a466e2f375..06e7a208e1 100644 --- a/crates/ui-egui/src/blend_preview.rs +++ b/crates/ui-egui/src/blend_preview.rs @@ -29,6 +29,8 @@ pub(crate) struct BlendPreview { area: Option, /// The document shown for `mode`, with its key. shown: Option<(u64, Arc)>, + /// GPU preview key, affected region (including effects), and rectangles already refreshed. + covered: Option<(u64, Rect, Vec)>, } /// The Layers panel, each frame it draws `layer`'s blend-mode dropdown: the mode under the @@ -54,7 +56,7 @@ pub(crate) fn hover(app: &mut PhotocraftApp, layers: &[LayerId], mode: Option None, }; } - Some(BlendPreview { doc, revision, layers: layers.to_vec(), mode: Some(mode), frame, area, shown: None }) + Some(BlendPreview { doc, revision, layers: layers.to_vec(), mode: Some(mode), frame, area, shown: None, covered: None }) }); } @@ -96,6 +98,41 @@ pub(crate) fn damage(app: &PhotocraftApp, doc: DocId, revision: u64, seen: u64, (seen != now && ours(seen) && ours(now) && (is_preview_key(seen) || is_preview_key(now))).then_some(p.area)? } +/// Limit an active preview to the view. Returning to the document restores the whole region. +pub(crate) fn clip_damage(app: &mut PhotocraftApp, doc: DocId, revision: u64, key: u64, region: Rect, visible: Rect) -> Rect { + let Some(p) = app.blend_preview.as_mut().filter(|p| p.doc == doc && p.revision == revision) else { return region }; + if !p.shown.as_ref().is_some_and(|(shown, _)| *shown == key) { + p.covered = None; + return region; + } + let shown = region.intersect(&visible); + p.covered = Some((key, region, vec![shown])); + shown +} + +/// A pan or zoom can expose pixels not yet rendered for the current preview key. +pub(crate) fn uncovered(app: &mut PhotocraftApp, doc: DocId, revision: u64, key: u64, visible: Rect) -> Option { + let p = app.blend_preview.as_mut().filter(|p| p.doc == doc && p.revision == revision)?; + let (covered_key, region, covered) = p.covered.as_mut()?; + if *covered_key != key { + return None; + } + let want = region.intersect(&visible); + if want.is_empty() || covered.iter().any(|r| r.contains_rect(&want)) { + return None; + } + // Keep disjoint views without marking the unrendered gaps between them as covered. + // Bound bookkeeping during long pans: after eight rectangles, render the whole affected + // region once. A different mode/revision resets coverage through `clip_damage`. + covered.retain(|r| !want.contains_rect(r)); + let refresh = if covered.len() < 8 { want } else { *region }; + if refresh == *region { + covered.clear(); + } + covered.push(refresh); + Some(refresh) +} + fn is_preview_key(key: u64) -> bool { (BASE..BASE << 1).contains(&key) } diff --git a/crates/ui-egui/src/blend_preview/tests.rs b/crates/ui-egui/src/blend_preview/tests.rs index 22908ac248..72e809f786 100644 --- a/crates/ui-egui/src/blend_preview/tests.rs +++ b/crates/ui-egui/src/blend_preview/tests.rs @@ -138,3 +138,37 @@ fn a_hovered_mode_previews_on_every_selected_layer() { hover(&mut app, &[top], Some(BlendMode::Multiply)); assert_ne!(display_doc(&mut app, 0).unwrap().1, key); } + +#[test] +fn blend_hover_disjoint_coverage_retains_views_without_hiding_gaps() { + let (s, top) = session(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + hover(&mut app, &[top], Some(BlendMode::Multiply)); + let (_, key) = display_doc(&mut app, 0).unwrap(); + let st = app.session.active().unwrap(); + let (id, revision, region) = (st.doc.id, st.revision, st.doc.bounds()); + let a = photocraft_geom::Rect::new(0, 0, 2, 2); + let b = photocraft_geom::Rect::new(4, 0, 6, 2); + assert_eq!(super::clip_damage(&mut app, id, revision, key, region, a), a); + assert_eq!(super::uncovered(&mut app, id, revision, key, b), Some(b)); + assert_eq!(super::uncovered(&mut app, id, revision, key, a), None); + let gap = photocraft_geom::Rect::new(2, 0, 4, 2); + assert_eq!(super::uncovered(&mut app, id, revision, key, gap), Some(gap)); + // Repeated distinct views have bounded bookkeeping, then the whole region is current. + let mut fell_back = false; + for x in (8..40).step_by(4) { + let visible = photocraft_geom::Rect::new(x, 0, x + 2, 2); + if super::uncovered(&mut app, id, revision, key, visible) == Some(region) { + fell_back = true; + break; + } + } + assert!(fell_back); + assert_eq!(super::uncovered(&mut app, id, revision, key, region), None); + hover(&mut app, &[top], Some(BlendMode::Screen)); + let (_, next) = display_doc(&mut app, 0).unwrap(); + assert_eq!(super::clip_damage(&mut app, id, revision, next, region, a), a); + assert_eq!(super::uncovered(&mut app, id, revision, next, b), Some(b)); + hover(&mut app, &[top], None); + assert_eq!(super::clip_damage(&mut app, id, revision, 0, region, a), region); +} diff --git a/crates/ui-egui/src/caf_ui.rs b/crates/ui-egui/src/caf_ui.rs new file mode 100644 index 0000000000..747e9d4bcf --- /dev/null +++ b/crates/ui-egui/src/caf_ui.rs @@ -0,0 +1,1972 @@ +//! Edit › Content-Aware Fill…: Photoshop's Content-Aware Fill workspace, a full-window dialog +//! like Liquify's. +//! +//! Measured on Photoshop 25.4 (black box) and laid out the same way: the tools on the left +//! (Sampling Brush, Lasso, Hand, Zoom) with their options bar above, the document in the middle +//! with the sampling area tinted (green, 50 %) and the fill area outlined, a Preview panel, and +//! the Content-Aware Fill panel (Sampling Area Overlay, Sampling Area Options, Fill Settings, +//! Output Settings) with OK, Apply and Cancel. +//! +//! * **Sampling Brush**: a hard round brush. In Auto and Rectangular it subtracts from the +//! sampling area, in Custom (which starts empty) it adds; Alt reverses. Painting keeps the +//! sampling option, and added strokes may reach past the sampling window. Its starting size is +//! a tenth of the window's side (20 px for a 50 px selection). +//! * **Lasso**: edits the fill area itself (New, Add, Subtract, Intersect; Expand and Contract by +//! a few pixels). The window and the Auto area follow the new fill area; brush strokes stay. +//! * **Preview**: the fill computed in the background after each change, opening framed on the +//! sampling window. +//! * **Apply** fills (one history step) and keeps the workspace open; **OK** fills and closes; +//! **Cancel** closes, keeping what was applied. Ctrl+Z undoes the last stroke or lasso edit. +//! +//! What the workspace holds is plain data (the sampling option, brush strokes, lasso edits and +//! fill settings); OK and Apply run `edit.contentAwareFill` with it, and the preview runs the same +//! plan ([`photocraft_engine::edit_menu_cmds::content_aware_plan`]), so the preview is exactly +//! what gets written. The settings are remembered for the next time (`prefs.dialogs`). + +use egui::{Align2, Color32, FontId, Pos2, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2}; +use photocraft_algo::content_aware::{SamplingStroke, paint_strokes}; +use photocraft_doc::LayerId; +use photocraft_engine::edit_menu_cmds::{MAX_CAF_EDITS, MAX_CAF_POINTS}; +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::ToolEvent; +use crate::theme::Tokens; +use crate::widgets; + +/// Longest side of the document proxy shown in the view (px). +const PROXY_SIDE: usize = 1600; +const LEFT_W: f32 = 48.0; +const BAR_H: f32 = 36.0; +const PANEL_W: f32 = 300.0; +const PREVIEW_W: f32 = 380.0; +const UNDO_LIMIT: usize = 100; +/// Outlines with more edges than this are drawn at the proxy's resolution. +const MAX_OUTLINE_EDGES: usize = 200_000; +/// Photoshop's overlay colour as it shows (a 50 % tint of grey 200 reads 171, 204, 153). +const OVERLAY_COLOR: [u8; 3] = [142, 208, 106]; +/// The `prefs.dialogs` key under which the settings are remembered. +const REMEMBERED: &str = "edit.contentAwareFill.workspace"; +const CMD: &str = "edit.contentAwareFill"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CafTool { + Brush, + Lasso, + Hand, + Zoom, +} + +impl CafTool { + fn name(self) -> &'static str { + match self { + CafTool::Brush => "brush", + CafTool::Lasso => "lasso", + CafTool::Hand => "hand", + CafTool::Zoom => "zoom", + } + } + fn from_name(s: &str) -> Option { + Some(match s { + "brush" => CafTool::Brush, + "lasso" => CafTool::Lasso, + "hand" => CafTool::Hand, + "zoom" => CafTool::Zoom, + _ => return None, + }) + } +} + +/// The lasso's selection modes, in options-bar order. +const LASSO_OPS: [&str; 4] = ["new", "add", "subtract", "intersect"]; + +/// The panel's settings (remembered between uses). +#[derive(Clone, Debug, PartialEq)] +pub struct CafOpts { + pub show_overlay: bool, + /// Overlay opacity, 0..100. + pub opacity: f32, + pub color: [u8; 3], + /// The overlay marks what is left out (Indicates: Excluded Area) rather than the sampling area. + pub excluded: bool, + /// auto | rectangular | custom + pub sampling: String, + pub sample_all: bool, + /// default | none | high | veryHigh + pub color_adaptation: String, + /// none | low | medium | high | full + pub rotation: String, + pub scale: bool, + pub mirror: bool, + /// current | new | duplicate (Photoshop opens on New Layer) + pub output: String, +} + +impl Default for CafOpts { + fn default() -> Self { + CafOpts { + show_overlay: true, + opacity: 50.0, + color: OVERLAY_COLOR, + excluded: false, + sampling: "auto".into(), + sample_all: false, + color_adaptation: "default".into(), + rotation: "none".into(), + scale: false, + mirror: false, + output: "new".into(), + } + } +} + +impl CafOpts { + /// Applies the settings named in `v` (control channel and remembered keys); others stay. + pub fn apply(&mut self, v: &Value) -> Result<(), String> { + let flag = |k: &str| v.get(k).and_then(Value::as_bool); + let text = |k: &str| v.get(k).and_then(Value::as_str); + for (k, slot) in [ + ("showOverlay", &mut self.show_overlay), + ("excluded", &mut self.excluded), + ("sampleAllLayers", &mut self.sample_all), + ("scale", &mut self.scale), + ("mirror", &mut self.mirror), + ] { + if let Some(b) = flag(k) { + *slot = b; + } + } + if let Some(n) = v.get("opacity").and_then(Value::as_f64).filter(|n| n.is_finite()) { + self.opacity = (n as f32).clamp(0.0, 100.0); + } + if let Some(c) = v.get("color").and_then(Value::as_array).filter(|c| c.len() == 3) { + let ch = |i: usize| c[i].as_u64().map(|v| v.min(255) as u8); + if let (Some(r), Some(g), Some(b)) = (ch(0), ch(1), ch(2)) { + self.color = [r, g, b]; + } + } + let pick = |k: &str, allowed: &[&str]| -> Result, String> { + match text(k) { + None => Ok(None), + Some(s) if allowed.contains(&s) => Ok(Some(s.to_string())), + Some(s) => Err(format!("bad {k} `{s}` ({})", allowed.join("|"))), + } + }; + if let Some(s) = pick("sampling", &["auto", "rectangular", "custom"])? { + self.sampling = s; + } + if let Some(s) = pick("colorAdaptation", &["none", "default", "high", "veryHigh"])? { + self.color_adaptation = s; + } + if let Some(s) = pick("rotationAdaptation", &["none", "low", "medium", "high", "full"])? { + self.rotation = s; + } + if let Some(s) = pick("output", &["current", "new", "duplicate"])? { + self.output = s; + } + Ok(()) + } + + /// The settings as [`CafOpts::apply`] reads them. + pub fn to_json(&self) -> Value { + json!({ + "showOverlay": self.show_overlay, + "opacity": self.opacity, + "color": self.color, + "excluded": self.excluded, + "sampling": self.sampling, + "sampleAllLayers": self.sample_all, + "colorAdaptation": self.color_adaptation, + "rotationAdaptation": self.rotation, + "scale": self.scale, + "mirror": self.mirror, + "output": self.output, + }) + } +} + +/// One undoable step. +#[derive(Clone, Debug)] +enum Step { + Stroke(SamplingStroke), + Fill(Value), + /// A change of the sampling option (or a reset), with what it replaced. + State { + sampling: String, + strokes: Vec, + fill_edits: Vec, + }, +} + +fn stroke_json(s: &SamplingStroke) -> Value { + json!({"mode": if s.add { "add" } else { "subtract" }, "size": s.size, "points": s.points}) +} + +/// What the plan (without the brush strokes) says: the window, the fill area and the sampling +/// option's area, over `rect`. +struct Base { + window: Rect, + rect: Rect, + hole: Vec, + base: Vec, +} + +impl Base { + /// The index into `hole` and `base` of document point `(x, y)`, when it is inside `rect`. + fn index(&self, x: f64, y: f64) -> Option { + let (xi, yi) = (x.floor() as i32, y.floor() as i32); + self.rect.contains(xi, yi).then(|| (yi - self.rect.y0) as usize * self.rect.width() as usize + (xi - self.rect.x0) as usize) + } +} + +/// A computed preview: the filled rectangle as an image, or why it failed. +#[cfg(not(target_arch = "wasm32"))] +type PreviewResult = Result<(Rect, egui::ColorImage), String>; + +/// The preview being computed or shown. +#[derive(Default)] +struct Preview { + /// Bumped whenever the state changes; a result for an older generation is dropped. + want: u64, + #[cfg(not(target_arch = "wasm32"))] + running: Option<(u64, std::sync::mpsc::Receiver, photocraft_engine::jobs::JobCtx)>, + shown: u64, + /// A finished preview waiting to be uploaded (on the UI thread, which has the context). + pending_image: Option<(Rect, egui::ColorImage)>, + tex: Option<(TextureHandle, Rect)>, + /// Screen px per document px (0 = frame the window on the next frame) and the view centre. + zoom: f32, + center: [f64; 2], + error: Option, +} + +impl Preview { + /// Takes the result of the preview of state `generation`: an image to upload, or the error, + /// which stands for that state until it changes (the same preview is not started again). + fn finish(&mut self, generation: u64, r: Result<(Rect, egui::ColorImage), String>) { + self.shown = generation; + self.tex = None; + match r { + Ok(img) => { + self.pending_image = Some(img); + self.error = None; + } + Err(e) => { + self.pending_image = None; + self.error = Some(e); + } + } + } +} + +pub struct CafWorkspace { + pub layer: LayerId, + layer_name: String, + canvas: Rect, + /// The document revision the textures and the base were made from. + revision: u64, + pub opts: CafOpts, + pub tool: CafTool, + pub brush_add: bool, + pub brush_size: f64, + pub lasso_op: usize, + pub expand_by: f32, + pub strokes: Vec, + pub fill_edits: Vec, + undo: Vec, + redo: Vec, + cur: Option, + /// The lasso polygon being drawn and its selection mode. + lasso: Option<(usize, Vec<[f64; 2]>)>, + base: Base, + /// Fill-area outline edges (document px), or `None` when there are too many. + outline: Option>, + /// Document px per proxy px, and the proxy size. + k: usize, + pw: usize, + ph: usize, + /// Per proxy pixel: the sampling option's area (before the strokes), the fill area, and the + /// sampling area after the strokes so far (the first painted with them in order, as the + /// engine's `paint_strokes` paints the full-resolution one). + base_px: Vec, + hole_px: Vec, + mask: Vec, + /// The pointer is down on the view with a tool: one press is one `Down`, egui's drag (which + /// starts a few pixels later) continues it. + pressed: bool, + /// The device's texture side limit, as the context reports it each frame. + texture_limit: usize, + image_tex: Option, + overlay_tex: Option, + overlay_dirty: bool, + zoom: f32, + center: [f64; 2], + hover: Option<[f64; 2]>, + preview: Preview, + pub error: Option, +} + +/// The plan of the current state (without strokes when `strokes` is false). +fn plan_params(w: &CafWorkspace, strokes: bool) -> Value { + let o = &w.opts; + let mut p = json!({ + "sampling": o.sampling, + "sampleAllLayers": o.sample_all, + "colorAdaptation": o.color_adaptation, + "rotationAdaptation": o.rotation, + "scale": o.scale, + "mirror": o.mirror, + "output": o.output, + "layer": w.layer.0, + "fillEdits": w.fill_edits, + }); + if strokes && !w.strokes.is_empty() { + p["samplingStrokes"] = Value::Array(w.strokes.iter().map(stroke_json).collect()); + } + p +} + +impl CafWorkspace { + pub fn describe(&self) -> Value { + let sampled = self.mask.iter().zip(&self.hole_px).filter(|(m, h)| **m && !**h).count(); + json!({ + "layer": self.layer.0, + "tool": self.tool.name(), + "brushSize": self.brush_size, + "brushMode": if self.brush_add { "add" } else { "subtract" }, + "lassoMode": LASSO_OPS[self.lasso_op], + "expandBy": self.expand_by, + "strokes": self.strokes.len() + usize::from(self.cur.is_some()), + "fillEdits": self.fill_edits.len(), + "undo": self.undo.len(), + "redo": self.redo.len(), + "window": [self.base.window.x0, self.base.window.y0, self.base.window.width(), self.base.window.height()], + "fillArea": self.base.hole.iter().filter(|h| **h).count(), + "sampledProxyPixels": sampled, + "proxyScale": self.k, + "settings": self.opts.to_json(), + "previewReady": self.preview.tex.is_some() && self.preview.shown == self.preview.want, + "previewError": self.preview.error, + "error": self.error, + }) + } + + /// The proxy, in proxy px. + fn proxy_area(&self) -> Rect { + Rect::new(0, 0, self.pw as i32, self.ph as i32) + } + + /// `s` in proxy coordinates: proxy pixel `(px, py)` is centred on document point + /// `canvas.x0 + (px + 0.5) k`, so the stroke's points and size scale by `1 / k`. + fn proxy_stroke(&self, s: &SamplingStroke) -> SamplingStroke { + let k = self.k as f64; + let (ox, oy) = (f64::from(self.canvas.x0), f64::from(self.canvas.y0)); + SamplingStroke { add: s.add, size: s.size / k, points: s.points.iter().map(|p| [(p[0] - ox) / k, (p[1] - oy) / k]).collect() } + } + + /// Paints `s` (a stroke, or one segment of the one being drawn) into the proxy's sampling + /// area: only the pixels within the brush of its path are visited, whatever came before. + fn paint(&mut self, s: &SamplingStroke) { + let (s, area) = (self.proxy_stroke(s), self.proxy_area()); + paint_strokes(&mut self.mask, area, &[s]); + self.overlay_dirty = true; + } + + /// Takes a new base: its option's area and fill area at the proxy's pixel centres, then the + /// strokes over it. + fn set_base(&mut self, b: Base) { + self.outline = outline(&b); + let k = self.k as f64; + for py in 0..self.ph { + for px in 0..self.pw { + let (x, y) = (f64::from(self.canvas.x0) + (px as f64 + 0.5) * k, f64::from(self.canvas.y0) + (py as f64 + 0.5) * k); + let i = b.index(x, y); + let at = |v: &[bool]| i.is_some_and(|i| v.get(i).copied().unwrap_or(false)); + self.base_px[py * self.pw + px] = at(&b.base); + self.hole_px[py * self.pw + px] = at(&b.hole); + } + } + self.base = b; + self.restate_all(); + } + + /// Rebuilds the proxy's sampling area: the base painted with every stroke in order. Each + /// stroke costs its own pixels, so this is linear in the strokes, not strokes × pixels. + fn restate_all(&mut self) { + self.mask.clone_from(&self.base_px); + let strokes: Vec = self.strokes.iter().chain(self.cur.iter()).map(|s| self.proxy_stroke(s)).collect(); + let area = self.proxy_area(); + paint_strokes(&mut self.mask, area, &strokes); + self.overlay_dirty = true; + } + + /// Points in the strokes and lasso edits so far, against the engine's budget. + fn points_used(&self) -> usize { + let strokes: usize = self.strokes.iter().chain(self.cur.iter()).map(|s| s.points.len()).sum(); + let lassos: usize = self.fill_edits.iter().map(|e| e.get("points").and_then(Value::as_array).map_or(0, Vec::len)).sum(); + strokes + lassos + } + + /// The preview is out of date. + fn stale(&mut self) { + self.preview.want += 1; + } + + fn begin_stroke(&mut self, p: [f64; 2], alt: bool) { + // The engine takes at most MAX_CAF_EDITS strokes and MAX_CAF_POINTS points in all: the + // brush stops there, so Apply and the preview never fail on what was painted. + if self.strokes.len() >= MAX_CAF_EDITS { + self.error = Some(format!("at most {MAX_CAF_EDITS} sampling strokes: undo some, or reset the sampling area")); + return; + } + if self.points_used() >= MAX_CAF_POINTS { + self.error = Some(points_limit()); + return; + } + self.error = None; + let add = self.brush_add != alt; + let s = SamplingStroke { add, size: self.brush_size, points: vec![p] }; + self.paint(&s); + self.cur = Some(s); + } + + fn extend_stroke(&mut self, p: [f64; 2]) { + if self.cur.is_none() { + return; + } + if self.points_used() >= MAX_CAF_POINTS { + self.error = Some(points_limit()); + return; + } + let Some(s) = self.cur.as_mut() else { return }; + if s.points.last().is_some_and(|l| l[0] == p[0] && l[1] == p[1]) { + return; + } + let last = *s.points.last().unwrap_or(&p); + s.points.push(p); + let seg = SamplingStroke { add: s.add, size: s.size, points: vec![last, p] }; + self.paint(&seg); + } + + fn end_stroke(&mut self) { + if let Some(s) = self.cur.take() { + self.strokes.push(s.clone()); + self.push(Step::Stroke(s)); + self.stale(); + } + } + + fn push(&mut self, s: Step) { + self.redo.clear(); + if self.undo.len() == UNDO_LIMIT { + self.undo.remove(0); + } + self.undo.push(s); + } +} + +fn points_limit() -> String { + format!("at most {MAX_CAF_POINTS} points in all sampling strokes and lasso edits: undo some, or reset") +} + +/// The plan without strokes: the window, fill area and the option's area. Custom starts empty +/// (the window and fill area are those of Rectangular). +fn compute_base(app: &PhotocraftApp, w: &CafWorkspace) -> Result { + let st = app.session.active().ok_or("no document")?; + let mut p = plan_params(w, false); + let custom = w.opts.sampling == "custom"; + if custom { + p["sampling"] = json!("rectangular"); + } + let plan = photocraft_engine::edit_menu_cmds::content_aware_plan(&st.doc, w.layer, &p, CMD).map_err(|e| e.to_string())?; + let base = if custom { vec![false; plan.base.len()] } else { plan.base }; + Ok(Base { window: plan.window, rect: plan.rect, hole: plan.hole, base }) +} + +/// Unit edges between the fill area and the rest, in document px. +fn outline(b: &Base) -> Option> { + let (w, h) = (b.rect.width() as usize, b.rect.height() as usize); + let (ox, oy) = (b.rect.x0 as f32, b.rect.y0 as f32); + let at = |x: i64, y: i64| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && b.hole.get(y as usize * w + x as usize).copied().unwrap_or(false); + let mut out = Vec::new(); + for y in 0..h as i64 { + for x in 0..w as i64 { + if !at(x, y) { + continue; + } + let (fx, fy) = (ox + x as f32, oy + y as f32); + if !at(x - 1, y) { + out.push([[fx, fy], [fx, fy + 1.0]]); + } + if !at(x + 1, y) { + out.push([[fx + 1.0, fy], [fx + 1.0, fy + 1.0]]); + } + if !at(x, y - 1) { + out.push([[fx, fy], [fx + 1.0, fy]]); + } + if !at(x, y + 1) { + out.push([[fx, fy + 1.0], [fx + 1.0, fy + 1.0]]); + } + if out.len() > MAX_OUTLINE_EDGES { + return None; + } + } + } + Some(out) +} + +/// Recompute the base after a change of the fill area, the sampling option or the document. +fn rebase(app: &mut PhotocraftApp) { + let Some(w) = app.distort.caf.as_ref() else { return }; + let r = compute_base(app, w); + let Some(w) = app.distort.caf.as_mut() else { return }; + match r { + Ok(b) => { + w.set_base(b); + w.error = None; + } + Err(e) => { + w.error = Some(e); + w.restate_all(); + } + } + w.stale(); +} + +/// Opens the workspace on the active layer and its selection. +pub fn open(app: &mut PhotocraftApp) -> Result<(), String> { + if !app.session.is_enabled(CMD) { + return Err("Content-Aware Fill needs a selection on a pixel layer".into()); + } + let st = app.session.active().ok_or("no document")?; + let layer = st.active_layer.ok_or("no active layer")?; + let canvas = st.doc.bounds(); + let revision = st.revision; + let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default(); + let k = (canvas.width().max(canvas.height()) as usize).div_ceil(PROXY_SIDE).max(1); + let (pw, ph) = ((canvas.width() as usize).div_ceil(k), (canvas.height() as usize).div_ceil(k)); + let mut opts = CafOpts::default(); + if let Some(saved) = app.session.prefs().dialogs.get(REMEMBERED) { + let _ = opts.apply(saved); + } + let mut w = CafWorkspace { + layer, + layer_name: name, + canvas, + revision, + opts, + tool: CafTool::Brush, + brush_add: false, + brush_size: 20.0, + lasso_op: 0, + expand_by: 3.0, + strokes: Vec::new(), + fill_edits: Vec::new(), + undo: Vec::new(), + redo: Vec::new(), + cur: None, + lasso: None, + base: Base { window: Rect::EMPTY, rect: Rect::EMPTY, hole: Vec::new(), base: Vec::new() }, + outline: None, + k, + pw, + ph, + base_px: vec![false; pw * ph], + hole_px: vec![false; pw * ph], + mask: vec![false; pw * ph], + pressed: false, + texture_limit: 2048, + image_tex: None, + overlay_tex: None, + overlay_dirty: true, + zoom: 0.0, + center: [f64::from(canvas.x0 + canvas.x1) / 2.0, f64::from(canvas.y0 + canvas.y1) / 2.0], + hover: None, + preview: Preview::default(), + error: None, + }; + w.brush_add = w.opts.sampling == "custom"; + let base = compute_base(app, &w)?; + w.brush_size = photocraft_algo::content_aware::default_brush_size(bounds(&base)); + w.set_base(base); + w.stale(); + app.distort.caf = Some(w); + Ok(()) +} + +/// Bounds of the fill area. +fn bounds(b: &Base) -> Rect { + let w = b.rect.width() as usize; + b.hole.iter().enumerate().filter(|(_, h)| **h).fold(Rect::EMPTY, |r, (i, _)| { + let (x, y) = (b.rect.x0 + (i % w) as i32, b.rect.y0 + (i / w) as i32); + r.union(&Rect::new(x, y, x + 1, y + 1)) + }) +} + +fn remember(app: &mut PhotocraftApp, opts: &CafOpts) { + let v = opts.to_json(); + app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), v)); +} + +/// Apply: fill with the current state (one history step); the workspace stays open. +pub fn apply(app: &mut PhotocraftApp) -> Result { + let Some(w) = app.distort.caf.as_mut() else { return Err("Content-Aware Fill is not open".into()) }; + w.end_stroke(); + let p = plan_params(w, true); + let opts = w.opts.clone(); + remember(app, &opts); + let r = app.run(CMD, p); + if r.is_ok() { + refresh(app); + } + r +} + +/// OK: fill and close. +pub fn commit(app: &mut PhotocraftApp) { + let ok = apply(app); + if let Err(e) = ok { + app.ui.status = e; + app.ui.status_error = true; + } + close(app); +} + +/// Cancel (button, Esc): closes; what was applied stays. The settings are kept. +pub fn cancel(app: &mut PhotocraftApp) { + if let Some(w) = app.distort.caf.as_ref() { + let opts = w.opts.clone(); + remember(app, &opts); + } + close(app); +} + +fn close(app: &mut PhotocraftApp) { + if let Some(w) = app.distort.caf.take() { + cancel_preview(w); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn cancel_preview(w: CafWorkspace) { + if let Some((_, _, job)) = w.preview.running { + job.cancel(); + } +} + +#[cfg(target_arch = "wasm32")] +fn cancel_preview(_: CafWorkspace) {} + +/// The document changed under the workspace (an Apply): new textures, a new base. +fn refresh(app: &mut PhotocraftApp) { + let rev = app.session.active().map(|s| s.revision); + if let Some(w) = app.distort.caf.as_mut() { + w.image_tex = None; + w.revision = rev.unwrap_or(w.revision); + } + rebase(app); +} + +fn undo(app: &mut PhotocraftApp) { + let Some(w) = app.distort.caf.as_mut() else { return }; + w.end_stroke(); + let Some(step) = w.undo.pop() else { return }; + let rebuild = match &step { + Step::Stroke(_) => { + w.strokes.pop(); + w.redo.push(step); + w.restate_all(); + w.stale(); + false + } + Step::Fill(_) => { + w.fill_edits.pop(); + w.redo.push(step); + true + } + Step::State { sampling, strokes, fill_edits } => { + let now = Step::State { sampling: w.opts.sampling.clone(), strokes: w.strokes.clone(), fill_edits: w.fill_edits.clone() }; + w.opts.sampling = sampling.clone(); + w.strokes = strokes.clone(); + w.fill_edits = fill_edits.clone(); + w.brush_add = w.opts.sampling == "custom"; + w.redo.push(now); + true + } + }; + if rebuild { + rebase(app); + } +} + +fn redo(app: &mut PhotocraftApp) { + let Some(w) = app.distort.caf.as_mut() else { return }; + w.end_stroke(); + let Some(step) = w.redo.pop() else { return }; + let rebuild = match &step { + Step::Stroke(s) => { + w.strokes.push(s.clone()); + w.undo.push(step); + w.restate_all(); + w.stale(); + false + } + Step::Fill(e) => { + w.fill_edits.push(e.clone()); + w.undo.push(step); + true + } + Step::State { sampling, strokes, fill_edits } => { + let now = Step::State { sampling: w.opts.sampling.clone(), strokes: w.strokes.clone(), fill_edits: w.fill_edits.clone() }; + w.opts.sampling = sampling.clone(); + w.strokes = strokes.clone(); + w.fill_edits = fill_edits.clone(); + w.brush_add = w.opts.sampling == "custom"; + w.undo.push(now); + true + } + }; + if rebuild { + rebase(app); + } +} + +/// A lasso edit of the fill area (or Expand / Contract), undoable. +fn fill_edit(app: &mut PhotocraftApp, edit: Value) { + let Some(w) = app.distort.caf.as_mut() else { return }; + w.end_stroke(); + // The engine's limits, kept here (see `begin_stroke`). + if w.fill_edits.len() >= MAX_CAF_EDITS { + w.error = Some(format!("at most {MAX_CAF_EDITS} lasso edits: undo some, or reset the fill area")); + return; + } + if w.points_used() + edit.get("points").and_then(Value::as_array).map_or(0, Vec::len) > MAX_CAF_POINTS { + w.error = Some(points_limit()); + return; + } + w.fill_edits.push(edit.clone()); + w.push(Step::Fill(edit)); + rebase(app); + // An edit that empties the fill area is refused (the plan says so): undo it. + if app.distort.caf.as_ref().is_some_and(|w| w.error.is_some()) { + let msg = app.distort.caf.as_ref().and_then(|w| w.error.clone()); + undo(app); + if let Some(w) = app.distort.caf.as_mut() { + w.redo.clear(); + w.error = msg; + } + } +} + +/// A new sampling option (Auto, Rectangular, Custom): the brush strokes start over and the brush +/// takes the option's mode (Custom adds, the others subtract). +fn set_sampling(app: &mut PhotocraftApp, sampling: &str) { + let Some(w) = app.distort.caf.as_mut() else { return }; + if w.opts.sampling == sampling && w.strokes.is_empty() { + return; + } + w.end_stroke(); + let prev = Step::State { sampling: w.opts.sampling.clone(), strokes: std::mem::take(&mut w.strokes), fill_edits: w.fill_edits.clone() }; + w.push(prev); + w.opts.sampling = sampling.to_string(); + w.brush_add = sampling == "custom"; + rebase(app); +} + +/// Reset buttons: the sampling options, the fill settings, or everything. +fn reset(app: &mut PhotocraftApp, what: &str) { + let Some(w) = app.distort.caf.as_mut() else { return }; + let d = CafOpts::default(); + match what { + "fill" => { + w.opts.color_adaptation = d.color_adaptation; + w.opts.rotation = d.rotation; + w.opts.scale = d.scale; + w.opts.mirror = d.mirror; + w.stale(); + } + "sampling" => { + w.opts.sample_all = false; + set_sampling(app, "auto"); + } + "lasso" => { + if !w.fill_edits.is_empty() { + let prev = Step::State { sampling: w.opts.sampling.clone(), strokes: w.strokes.clone(), fill_edits: std::mem::take(&mut w.fill_edits) }; + w.push(prev); + rebase(app); + } + } + _ => { + let prev = + Step::State { sampling: w.opts.sampling.clone(), strokes: std::mem::take(&mut w.strokes), fill_edits: std::mem::take(&mut w.fill_edits) }; + w.push(prev); + w.opts = CafOpts::default(); + w.brush_add = false; + rebase(app); + } + } +} + +/// Control channel: `edit.contentAwareFill {"ui": {...}}` while the workspace is open. +pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { + let flag = |k: &str| ui.get(k).and_then(Value::as_bool) == Some(true); + if flag("cancel") { + cancel(app); + return Ok(json!({"cancelled": true})); + } + let before = app.distort.caf.as_ref().ok_or("Content-Aware Fill is not open")?.opts.clone(); + { + let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?; + let mut o = w.opts.clone(); + o.apply(ui)?; + // The sampling option goes through `set_sampling` (it resets the strokes). + let sampling = std::mem::replace(&mut o.sampling, w.opts.sampling.clone()); + w.opts = o; + if let Some(t) = ui.get("tool").and_then(Value::as_str) { + w.tool = CafTool::from_name(t).ok_or(format!("bad tool `{t}` (brush|lasso|hand|zoom)"))?; + } + if let Some(n) = ui.get("brushSize").and_then(Value::as_f64).filter(|n| n.is_finite()) { + w.brush_size = n.clamp(1.0, 5000.0); + } + if let Some(m) = ui.get("brushMode").and_then(Value::as_str) { + w.brush_add = m == "add"; + } + if let Some(m) = ui.get("lassoMode").and_then(Value::as_str) { + w.lasso_op = LASSO_OPS.iter().position(|o| *o == m).ok_or(format!("bad lassoMode `{m}`"))?; + } + if let Some(n) = ui.get("expandBy").and_then(Value::as_f64).filter(|n| n.is_finite()) { + w.expand_by = (n as f32).clamp(1.0, 100.0); + } + if sampling != w.opts.sampling { + set_sampling(app, &sampling); + } + } + let after = app.distort.caf.as_ref().map(|w| w.opts.clone()); + if after.as_ref().is_some_and(|a| a.sample_all != before.sample_all) { + rebase(app); + } else if after.as_ref().is_some_and(|a| *a != before) + && let Some(w) = app.distort.caf.as_mut() + { + w.stale(); + w.restate_all(); + } + if let Some(s) = ui.get("stroke") { + let pts: Vec<[f64; 2]> = serde_json::from_value(s.get("points").cloned().unwrap_or(Value::Null)).map_err(|e| format!("bad stroke points: {e}"))?; + let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?; + if let Some(n) = s.get("size").and_then(Value::as_f64) { + w.brush_size = n.clamp(1.0, 5000.0); + } + let alt = s.get("alt").and_then(Value::as_bool).unwrap_or(false); + if let Some(first) = pts.first() { + w.begin_stroke(*first, alt); + for p in &pts[1..] { + w.extend_stroke(*p); + } + w.end_stroke(); + } + } + if let Some(l) = ui.get("lasso") { + let pts: Vec<[f64; 2]> = serde_json::from_value(l.get("points").cloned().unwrap_or(Value::Null)).map_err(|e| format!("bad lasso points: {e}"))?; + let op = match l.get("op").and_then(Value::as_str) { + Some(o) if LASSO_OPS.contains(&o) => o.to_string(), + Some(o) => return Err(format!("bad lasso op `{o}`")), + None => LASSO_OPS[app.distort.caf.as_ref().map_or(0, |w| w.lasso_op)].to_string(), + }; + fill_edit(app, json!({"op": op, "points": pts})); + } + for k in ["expand", "contract"] { + if let Some(n) = ui.get(k).and_then(Value::as_f64) { + fill_edit(app, json!({"op": k, "by": n.clamp(1.0, 100.0)})); + } + } + if let Some(r) = ui.get("reset").and_then(Value::as_str) { + reset(app, r); + } + if flag("undo") { + undo(app); + } + if flag("redo") { + redo(app); + } + if flag("apply") { + apply(app)?; + } + if flag("waitPreview") { + wait_preview(app)?; + } + // OK last, with the settings given alongside. + if flag("commit") { + let r = apply(app); + close(app); + return r.map(|v| json!({"committed": true, "result": v})); + } + Ok(app.distort.caf.as_ref().map(CafWorkspace::describe).unwrap_or(Value::Null)) +} + +/// Computes the preview now, on this thread (tests and the control channel). +fn wait_preview(app: &mut PhotocraftApp) -> Result<(), String> { + let (doc, layer, p, want, limit) = { + let w = app.distort.caf.as_ref().ok_or("Content-Aware Fill is not open")?; + let st = app.session.active().ok_or("no document")?; + (st.doc.clone(), w.layer, plan_params(w, true), w.preview.want, w.texture_limit) + }; + let r = compute_preview(&doc, layer, &p, &photocraft_raster::Interrupt::NONE, limit); + let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?; + let err = r.as_ref().err().cloned(); + w.preview.finish(want, r); + err.map_or(Ok(()), Err) +} + +/// The filled rectangle as an image (what Apply would write there), as a texture no wider than +/// `max_side`: past the device's limit it is box-averaged to fit (the rectangle it is drawn over +/// stays the plan's). +fn compute_preview( + doc: &photocraft_doc::Document, + layer: LayerId, + p: &Value, + ctl: &photocraft_raster::Interrupt, + max_side: usize, +) -> Result<(Rect, egui::ColorImage), String> { + let plan = photocraft_engine::edit_menu_cmds::content_aware_plan_with(doc, layer, p, CMD, ctl).map_err(|e| match e { + photocraft_engine::EngineError::Cancelled => "cancelled".to_string(), + e => e.to_string(), + })?; + let (w, h) = (plan.rect.width() as usize, plan.rect.height() as usize); + let n = plan.fmt.channels(); + let filled = + photocraft_algo::content_aware::fill_with(w, h, n, &plan.img, &plan.hole, &plan.source, &plan.opts, ctl).map_err(|_| "cancelled".to_string())?; + let own = plan.layer_pixels(); + // Pixel `i`: the fill over the fill area (a partly selected pixel by its coverage), the + // layer's own pixels elsewhere. + let pixel = |i: usize| -> [f32; 4] { + let src = if plan.hole[i] { &filled[i * n..(i + 1) * n] } else { &own[i * n..(i + 1) * n] }; + let mut c = photocraft_raster::to_rgba(&plan.fmt, src); + if plan.hole[i] { + let k = plan.cover[i]; + let under = photocraft_raster::to_rgba(&plan.fmt, &own[i * n..(i + 1) * n]); + for j in 0..4 { + c[j] = under[j] + (c[j] - under[j]) * k; + } + } + c + }; + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let color = |c: [f32; 4]| Color32::from_rgba_unmultiplied(b(c[0]), b(c[1]), b(c[2]), b(c[3])); + let f = crate::filter_preview_ui::texture_factor(w as u32, h as u32, max_side) as usize; + if f == 1 { + let px = (0..w * h).map(|i| color(pixel(i))).collect(); + return Ok((plan.rect, egui::ColorImage::new([w, h], px))); + } + let (tw, th) = (w.div_ceil(f), h.div_ceil(f)); + let mut px = Vec::with_capacity(tw * th); + for ty in 0..th { + for tx in 0..tw { + // The block's premultiplied average. + let (mut acc, mut count) = ([0.0f32; 4], 0.0f32); + for y in ty * f..((ty + 1) * f).min(h) { + for x in tx * f..((tx + 1) * f).min(w) { + let c = pixel(y * w + x); + for j in 0..3 { + acc[j] += c[j] * c[3]; + } + acc[3] += c[3]; + count += 1.0; + } + } + let c = if acc[3] > 0.0 { [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3] / count] } else { [0.0; 4] }; + px.push(color(c)); + } + } + Ok((plan.rect, egui::ColorImage::new([tw, th], px))) +} + +/// Starts a background preview when the shown one is out of date (and the pointer is up), and +/// collects a finished one. +#[cfg(not(target_arch = "wasm32"))] +fn drive_preview(app: &mut PhotocraftApp, ctx: &egui::Context, dragging: bool) { + let doc = app.session.active().map(|s| s.doc.clone()); + let Some(w) = app.distort.caf.as_mut() else { return }; + let pv = &mut w.preview; + if let Some((generation, rx, _)) = &pv.running { + match rx.try_recv() { + Ok(r) => { + let generation = *generation; + pv.running = None; + if generation == pv.want { + match r { + Err(e) if e == "cancelled" => {} + r => pv.finish(generation, r), + } + } + } + Err(std::sync::mpsc::TryRecvError::Empty) => { + // Superseded: stop it, a new one starts when it has gone. + if *generation != pv.want + && let Some((_, _, job)) = &pv.running + { + job.cancel(); + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + return; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => pv.running = None, + } + } + if pv.running.is_some() || pv.shown == pv.want || dragging { + return; + } + let Some(doc) = doc else { return }; + let (layer, p, generation, limit) = (w.layer, plan_params(w, true), w.preview.want, w.texture_limit); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let job = photocraft_engine::jobs::JobCtx::new(); + let work = job.clone(); + let repaint = ctx.clone(); + let spawned = std::thread::Builder::new().name("caf-preview".into()).spawn(move || { + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work.stage(0.0, 1.0, "", |ctl| compute_preview(&doc, layer, &p, ctl, limit)))) + .unwrap_or_else(|_| Err("the preview failed".into())); + let _ = tx.send(r); + repaint.request_repaint(); + }); + match spawned { + Ok(_) => w.preview.running = Some((generation, rx, job)), + Err(e) => w.preview.error = Some(format!("could not start the preview: {e}")), + } +} + +/// The web build has no threads: the preview is computed when the pointer comes up. +#[cfg(target_arch = "wasm32")] +fn drive_preview(app: &mut PhotocraftApp, _ctx: &egui::Context, dragging: bool) { + let stale = app.distort.caf.as_ref().is_some_and(|w| w.preview.shown != w.preview.want); + if stale && !dragging { + let _ = wait_preview(app); + } +} + +/// Pointer in document coordinates (from the view or the control channel). +pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { + let Some(w) = app.distort.caf.as_mut() else { return }; + match (w.tool, ev) { + (CafTool::Brush, ToolEvent::Down { x, y, .. }) => w.begin_stroke([x, y], mods.alt), + (CafTool::Brush, ToolEvent::Move { x, y, .. }) => { + w.hover = Some([x, y]); + w.extend_stroke([x, y]); + } + (CafTool::Brush, ToolEvent::Up { x, y }) => { + w.extend_stroke([x, y]); + w.end_stroke(); + } + (CafTool::Lasso, ToolEvent::Down { x, y, .. }) => { + // Shift adds, Alt subtracts, both intersect (as Photoshop's selection tools). + let op = match (mods.shift, mods.alt) { + (true, true) => 3, + (true, false) => 1, + (false, true) => 2, + _ => w.lasso_op, + }; + w.lasso = Some((op, vec![[x, y]])); + } + (CafTool::Lasso, ToolEvent::Move { x, y, .. }) => { + if let Some((_, pts)) = &mut w.lasso + && pts.last().is_none_or(|l| l[0] != x || l[1] != y) + { + pts.push([x, y]); + } + } + (CafTool::Lasso, ToolEvent::Up { .. }) => { + if let Some((op, pts)) = w.lasso.take() + && pts.len() >= 3 + { + fill_edit(app, json!({"op": LASSO_OPS[op], "points": pts})); + } + } + (CafTool::Zoom, ToolEvent::Down { x, y, .. }) => { + let f = if mods.alt { 0.5 } else { 2.0 }; + w.zoom = (w.zoom * f).clamp(0.01, 32.0); + w.center = [x, y]; + } + _ => {} + } +} + +pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { + let cmd_shift = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT; + if ctx.input_mut(|i| i.consume_key(cmd_shift, egui::Key::Z)) { + redo(app); + return; + } + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Z)) { + undo(app); + return; + } + let Some(w) = app.distort.caf.as_mut() else { return }; + // Ctrl+H hides the overlay (Hide Extras). + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) { + w.opts.show_overlay = !w.opts.show_overlay; + w.overlay_dirty = true; + } + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::OpenBracket)) { + w.brush_size = (w.brush_size * 0.9).max(1.0).round(); + } + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::CloseBracket)) { + w.brush_size = (w.brush_size * 1.1).min(5000.0).round().max(w.brush_size + 1.0); + } + for (k, t) in [(egui::Key::B, CafTool::Brush), (egui::Key::L, CafTool::Lasso), (egui::Key::H, CafTool::Hand), (egui::Key::Z, CafTool::Zoom)] { + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, k)) { + w.tool = t; + } + } +} + +fn tool_icon(t: CafTool) -> &'static str { + match t { + CafTool::Brush => "brush", + CafTool::Lasso => "lasso", + CafTool::Hand => "hand", + CafTool::Zoom => "zoom-in", + } +} + +fn tool_tip(t: CafTool) -> String { + match t { + CafTool::Brush => format!("{} (B)", tl!("Sampling Brush Tool")), + CafTool::Lasso => format!("{} (L)", tl!("Lasso Tool")), + CafTool::Hand => format!("{} (H)", tl!("Hand Tool")), + CafTool::Zoom => format!("{} (Z)", tl!("Zoom Tool")), + } +} + +/// A view: screen px per document px and the document point at the centre of `area`. +#[derive(Clone, Copy)] +struct View { + area: ERect, + zoom: f32, + center: [f64; 2], +} + +impl View { + fn to_screen(self, p: [f64; 2]) -> Pos2 { + let c = self.area.center(); + pos2(c.x + ((p[0] - self.center[0]) as f32) * self.zoom, c.y + ((p[1] - self.center[1]) as f32) * self.zoom) + } + fn to_doc(self, s: Pos2) -> [f64; 2] { + let c = self.area.center(); + [self.center[0] + f64::from((s.x - c.x) / self.zoom), self.center[1] + f64::from((s.y - c.y) / self.zoom)] + } + fn rect(self, r: Rect) -> ERect { + ERect::from_min_max(self.to_screen([f64::from(r.x0), f64::from(r.y0)]), self.to_screen([f64::from(r.x1), f64::from(r.y1)])) + } +} + +/// Upload what changed: the document proxy, the overlay, a finished preview. +fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) { + let need_image = app.distort.caf.as_ref().is_some_and(|w| w.image_tex.is_none()); + if need_image { + let img = view_image(app); + if let (Some(w), Some(img)) = (app.distort.caf.as_mut(), img) { + w.image_tex = Some(ctx.load_texture("caf-image", img, egui::TextureOptions::LINEAR)); + } + } + let Some(w) = app.distort.caf.as_mut() else { return }; + if w.overlay_dirty || w.overlay_tex.is_none() { + w.overlay_dirty = false; + let [r, g, b] = w.opts.color; + let a = (w.opts.opacity / 100.0 * 255.0).round() as u8; + let tint = Color32::from_rgba_unmultiplied(r, g, b, a); + // The tint marks the sampling area (with Indicates: Excluded Area, what is left out); + // the fill area is never tinted. + let px: Vec = + w.mask.iter().zip(&w.hole_px).map(|(m, h)| if w.opts.show_overlay && !*h && *m != w.opts.excluded { tint } else { Color32::TRANSPARENT }).collect(); + let img = egui::ColorImage::new([w.pw, w.ph], px); + match &mut w.overlay_tex { + Some(t) => t.set(img, egui::TextureOptions::NEAREST), + None => w.overlay_tex = Some(ctx.load_texture("caf-overlay", img, egui::TextureOptions::NEAREST)), + } + } + if let Some((rect, img)) = w.preview.pending_image.take() { + w.preview.tex = Some((ctx.load_texture("caf-preview", img, egui::TextureOptions::LINEAR), rect)); + } +} + +/// The document as the view shows it: the visible layers composited, as on the canvas (so an +/// Apply to a new layer shows), reduced to the proxy. +fn view_image(app: &PhotocraftApp) -> Option { + let w = app.distort.caf.as_ref()?; + let st = app.session.active()?; + let buf = photocraft_compose::render_reduced(&st.doc, w.pw as u32, w.ph as u32); + let (display, _) = crate::canvas::canvas_display(app, &st.doc, None); + Some(crate::canvas::display_image(display.as_deref(), &buf)) +} + +/// Draws the workspace (a full-window layer over the app). +pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { + // An Apply (or anything else) changed the document: refresh. + let rev = app.session.active().map(|s| s.revision); + if app.distort.caf.as_ref().is_some_and(|w| Some(w.revision) != rev) { + refresh(app); + } + upload(app, ctx); + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let mut action: Option<&str> = None; + let mut events: Vec = Vec::new(); + let mut mods = egui::Modifiers::NONE; + let mut new_sampling: Option<&str> = None; + let mut fill_btn: Option = None; + let mut reset_what: Option<&str> = None; + let mut rebase_needed = false; + let mut dragging = false; + egui::Area::new(egui::Id::new("caf-workspace")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| { + let Some(w) = app.distort.caf.as_mut() else { return }; + let before = w.opts.clone(); + w.texture_limit = ctx.input(|i| i.max_texture_side); + let (full, _) = ui.allocate_exact_size(screen.size(), Sense::hover()); + let painter = ui.painter().clone(); + painter.rect_filled(full, 0.0, t.chrome); + // Title strip. + let title = ERect::from_min_size(full.min, vec2(full.width(), 30.0)); + painter.rect_filled(title, 0.0, t.dock); + painter.line_segment([title.left_bottom(), title.right_bottom()], Stroke::new(1.0, t.separator)); + let pct = if w.zoom > 0.0 { w.zoom * 100.0 } else { 100.0 }; + painter.text( + title.center(), + Align2::CENTER_CENTER, + format!("{} ({}, {:.0}%)", tl!("Content-Aware Fill…").trim_end_matches('…'), w.layer_name, pct), + FontId::proportional(13.0), + t.text, + ); + // Options bar. + let bar = ERect::from_min_size(pos2(full.left(), title.bottom()), vec2(full.width(), BAR_H)); + painter.rect_filled(bar, 0.0, t.dock); + painter.line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.separator)); + let mut bui = + ui.new_child(egui::UiBuilder::new().max_rect(bar.shrink2(vec2(LEFT_W + 8.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); + match w.tool { + CafTool::Brush => { + if crate::icons::button(&mut bui, "plus", 26.0, w.brush_add, tl!("Add")).clicked() { + w.brush_add = true; + } + if crate::icons::button(&mut bui, "minus", 26.0, !w.brush_add, tl!("Subtract")).clicked() { + w.brush_add = false; + } + bui.add_space(8.0); + bui.label(tl!("Size:")); + let mut size = w.brush_size as f32; + if widgets::value_field(&mut bui, &mut size, 1.0..=5000.0, " px", 64.0).changed() { + w.brush_size = f64::from(size); + } + } + CafTool::Lasso => { + // The selection tools' mode buttons (the lasso here edits the fill area). + let tips = [ + tl!("New selection").to_string(), + crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))]), + crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))]), + crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]), + ]; + for (i, (icon, tip)) in ["square", "plus", "minus", "squares-subtract"].into_iter().zip(tips.iter()).enumerate() { + if crate::icons::button(&mut bui, icon, 26.0, w.lasso_op == i, tip).clicked() { + w.lasso_op = i; + } + } + bui.add_space(8.0); + if widgets::secondary_button(&mut bui, tl!("Expand"), 70.0).clicked() { + fill_btn = Some(json!({"op": "expand", "by": w.expand_by})); + } + if widgets::secondary_button(&mut bui, tl!("Contract"), 70.0).clicked() { + fill_btn = Some(json!({"op": "contract", "by": w.expand_by})); + } + widgets::value_field(&mut bui, &mut w.expand_by, 1.0..=100.0, " px", 56.0); + if crate::icons::button(&mut bui, "undo-2", 26.0, false, tl!("Reset")).clicked() { + reset_what = Some("lasso"); + } + } + _ => {} + } + let body = ERect::from_min_max(pos2(full.left(), bar.bottom()), full.max); + // Left tool strip. + let left = ERect::from_min_size(pos2(full.left(), title.bottom()), vec2(LEFT_W, full.height() - title.height())); + painter.rect_filled(left, 0.0, t.dock); + painter.line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.separator)); + let mut strip = ui.new_child(egui::UiBuilder::new().max_rect(left.shrink2(vec2(6.0, 8.0)))); + strip.spacing_mut().item_spacing.y = 4.0; + for tool in [CafTool::Brush, CafTool::Lasso, CafTool::Hand, CafTool::Zoom] { + if crate::icons::button(&mut strip, tool_icon(tool), 34.0, w.tool == tool, &tool_tip(tool)).clicked() { + w.tool = tool; + } + } + // Right: the Content-Aware Fill panel. + let right = ERect::from_min_size(pos2(body.right() - PANEL_W, body.top()), vec2(PANEL_W, body.height())); + painter.rect_filled(right, 0.0, t.dock); + painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator)); + let mut props = + ui.new_child(egui::UiBuilder::new().max_rect(ERect::from_min_max(right.min + vec2(14.0, 12.0), pos2(right.right() - 14.0, right.bottom() - 60.0)))); + egui::ScrollArea::vertical().id_salt("caf-props").show(&mut props, |ui| { + ui.spacing_mut().item_spacing.y = 6.0; + egui::CollapsingHeader::new(tl!("Sampling Area Overlay")).id_salt("caf-overlay").default_open(false).show(ui, |ui| { + widgets::checkbox(ui, &mut w.opts.show_overlay, tl!("Show Sampling Area")); + widgets::slider_row(ui, tl!("Opacity"), &mut w.opts.opacity, 0.0..=100.0, "%", None); + ui.horizontal(|ui| { + ui.label(tl!("Color")); + widgets::color_edit_button_srgb(ui, &mut w.opts.color); + ui.add_space(8.0); + ui.label(tl!("Indicates")); + widgets::dropdown(ui, "caf-indicates", &mut w.opts.excluded, &[(false, tl!("Sampling Area")), (true, tl!("Excluded Area"))], 120.0); + }); + }); + widgets::hairline(ui); + ui.horizontal(|ui| { + widgets::section_label(ui, tl!("Sampling Area Options")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { + reset_what = Some("sampling"); + } + }); + }); + ui.horizontal(|ui| { + for (k, l) in [("auto", tl!("Auto")), ("rectangular", tl!("Rectangular")), ("custom", tl!("Custom"))] { + if ui.selectable_label(w.opts.sampling == k, l).clicked() && w.opts.sampling != k { + new_sampling = Some(k); + } + } + }); + if widgets::checkbox(ui, &mut w.opts.sample_all, tl!("Sample All Layers")).changed() { + rebase_needed = true; + } + widgets::hairline(ui); + ui.horizontal(|ui| { + widgets::section_label(ui, tl!("Fill Settings")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { + reset_what = Some("fill"); + } + }); + }); + ui.horizontal(|ui| { + ui.label(tl!("Color Adaptation")); + let o = [ + ("none".to_string(), tl!("None")), + ("default".to_string(), tl!("Default")), + ("high".to_string(), tl!("High")), + ("veryHigh".to_string(), tl!("Very High")), + ]; + widgets::dropdown(ui, "caf-color", &mut w.opts.color_adaptation, &o, 110.0); + }); + ui.horizontal(|ui| { + ui.label(tl!("Rotation Adaptation")); + let o = [ + ("none".to_string(), tl!("None")), + ("low".to_string(), tl!("Low")), + ("medium".to_string(), tl!("Medium")), + ("high".to_string(), tl!("High")), + ("full".to_string(), tl!("Full")), + ]; + widgets::dropdown(ui, "caf-rotation", &mut w.opts.rotation, &o, 110.0); + }); + ui.horizontal(|ui| { + widgets::checkbox(ui, &mut w.opts.scale, tl!("Scale")); + widgets::checkbox(ui, &mut w.opts.mirror, tl!("Mirror")); + }); + widgets::hairline(ui); + widgets::section_label(ui, tl!("Output Settings")); + ui.horizontal(|ui| { + ui.label(tl!("Output To")); + let o = + [("current".to_string(), tl!("Current Layer")), ("new".to_string(), tl!("New Layer")), ("duplicate".to_string(), tl!("Duplicate Layer"))]; + widgets::dropdown(ui, "caf-output", &mut w.opts.output, &o, 140.0); + }); + if let Some(e) = w.error.as_ref().or(w.preview.error.as_ref()) { + ui.label(egui::RichText::new(e.as_str()).color(t.danger).size(11.0)); + } + }); + // Footer, in Photoshop's order on every platform: reset all at the left, then OK, Apply, + // Cancel against the right edge. + let foot = ERect::from_min_size(pos2(right.left() + 10.0, right.bottom() - 48.0), vec2(PANEL_W - 20.0, 32.0)); + let mut fb = ui.new_child(egui::UiBuilder::new().max_rect(foot).layout(egui::Layout::right_to_left(egui::Align::Center))); + if widgets::secondary_button(&mut fb, tl!("Cancel"), 70.0).clicked() { + action = Some("cancel"); + } + if widgets::secondary_button(&mut fb, tl!("Apply"), 70.0).clicked() { + action = Some("apply"); + } + if widgets::primary_button(&mut fb, tl!("OK"), 64.0).clicked() { + action = Some("ok"); + } + if crate::icons::button(&mut fb, "undo-2", 24.0, false, tl!("Reset")).clicked() { + reset_what = Some("all"); + } + // The Preview panel. + let pv_rect = ERect::from_min_size(pos2(right.left() - PREVIEW_W, body.top()), vec2(PREVIEW_W, body.height())); + painter.rect_filled(pv_rect, 0.0, t.dock); + painter.line_segment([pv_rect.left_top(), pv_rect.left_bottom()], Stroke::new(1.0, t.separator)); + painter.text(pv_rect.left_top() + vec2(12.0, 10.0), Align2::LEFT_TOP, tl!("Preview"), FontId::proportional(12.0), t.text); + let pv_area = ERect::from_min_max(pv_rect.min + vec2(0.0, 30.0), pv_rect.max - vec2(0.0, 44.0)); + painter.rect_filled(pv_area, 0.0, t.canvas); + if w.preview.zoom <= 0.0 { + // Opens framed on the sampling window, as Photoshop's. + let win = w.base.window; + if !win.is_empty() { + w.preview.zoom = (pv_area.width() / win.width().max(win.height()) as f32).clamp(0.01, 32.0); + w.preview.center = [f64::from(win.x0 + win.x1) / 2.0, f64::from(win.y0 + win.y1) / 2.0]; + } + } + let pv = View { area: pv_area, zoom: w.preview.zoom.max(0.01), center: w.preview.center }; + let pclip = painter.with_clip_rect(pv_area); + let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + let img_rect = pv.rect(w.canvas); + widgets::checker(&pclip, img_rect.intersect(pv_area), 8.0); + if let Some(tex) = &w.image_tex { + pclip.image(tex.id(), img_rect, uv, Color32::WHITE); + } + if let Some((tex, r)) = &w.preview.tex { + pclip.image(tex.id(), pv.rect(*r), uv, Color32::WHITE); + } + if w.preview.shown != w.preview.want { + // Being recomputed: a spinner in the corner. + let sp = ERect::from_min_size(pv_area.right_bottom() - vec2(26.0, 26.0), vec2(18.0, 18.0)); + ui.put(sp, egui::Spinner::new().size(16.0)); + } + let presp = ui.interact(pv_area, egui::Id::new("caf-preview-view"), Sense::click_and_drag()); + if presp.dragged() { + let d = presp.drag_delta(); + w.preview.center = [w.preview.center[0] - f64::from(d.x / pv.zoom), w.preview.center[1] - f64::from(d.y / pv.zoom)]; + } + if presp.hovered() { + let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if scroll != 0.0 { + w.preview.zoom = (w.preview.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); + } + } + let zrow = ERect::from_min_size(pos2(pv_rect.left() + 10.0, pv_rect.bottom() - 38.0), vec2(PREVIEW_W - 20.0, 30.0)); + let mut zr = ui.new_child(egui::UiBuilder::new().max_rect(zrow).layout(egui::Layout::left_to_right(egui::Align::Center))); + let mut pct = (w.preview.zoom * 100.0).round(); + if widgets::value_field(&mut zr, &mut pct, 1.0..=3200.0, "%", 64.0).changed() { + w.preview.zoom = pct / 100.0; + } + let mut lz = pct.max(1.0).ln(); + if zr.add(egui::Slider::new(&mut lz, 0.0..=3200f32.ln()).show_value(false)).changed() { + w.preview.zoom = lz.exp() / 100.0; + } + // The document view. + let area = ERect::from_min_max(pos2(left.right(), body.top()), pos2(pv_rect.left(), body.bottom())); + painter.rect_filled(area, 0.0, t.canvas); + let (cw, chh) = (w.canvas.width() as f32, w.canvas.height() as f32); + if w.zoom <= 0.0 { + w.zoom = ((area.width() - 40.0) / cw).min((area.height() - 40.0) / chh).clamp(0.01, 4.0); + } + let resp = ui.interact(area, egui::Id::new("caf-view"), Sense::click_and_drag()); + if resp.hovered() { + let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if scroll != 0.0 + && let Some(hp) = resp.hover_pos() + { + let v = View { area, zoom: w.zoom, center: w.center }; + let before = v.to_doc(hp); + w.zoom = (w.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); + let after = View { area, zoom: w.zoom, center: w.center }.to_doc(hp); + w.center = [w.center[0] + before[0] - after[0], w.center[1] + before[1] - after[1]]; + } + } + let v = View { area, zoom: w.zoom, center: w.center }; + let clip = painter.with_clip_rect(area); + let img = v.rect(w.canvas); + widgets::checker(&clip, img.intersect(area), 8.0); + if let Some(tex) = &w.image_tex { + clip.image(tex.id(), img, uv, Color32::WHITE); + } + if let Some(tex) = &w.overlay_tex { + // The proxy's blocks are `k` document px; its last row and column may reach past the + // canvas, so the overlay is clipped to it. + let pr = ERect::from_min_size(img.min, vec2((w.pw * w.k) as f32 * v.zoom, (w.ph * w.k) as f32 * v.zoom)); + clip.with_clip_rect(img.intersect(area)).image(tex.id(), pr, uv, Color32::WHITE); + } + // The fill area's outline (marching ants: black dashes on white). + let phase = (ui.input(|i| i.time) * 8.0) as usize; + match &w.outline { + Some(edges) => { + for e in edges { + let (a, b) = (v.to_screen([f64::from(e[0][0]), f64::from(e[0][1])]), v.to_screen([f64::from(e[1][0]), f64::from(e[1][1])])); + let dark = ((e[0][0] + e[0][1]) as usize / 4 + phase).is_multiple_of(2); + clip.line_segment([a, b], Stroke::new(1.0, if dark { Color32::BLACK } else { Color32::WHITE })); + } + } + None => { + let b = v.rect(bounds(&w.base)); + clip.rect_stroke(b, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Outside); + } + } + ctx.request_repaint_after(std::time::Duration::from_millis(120)); + if let Some((_, pts)) = &w.lasso + && pts.len() > 1 + { + let line: Vec = pts.iter().map(|p| v.to_screen(*p)).collect(); + clip.add(egui::Shape::line(line, Stroke::new(1.0, t.accent))); + } + if let Some(hp) = resp.hover_pos() { + if w.tool == CafTool::Brush { + let r = w.brush_size as f32 * 0.5 * v.zoom; + clip.circle_stroke(hp, r, Stroke::new(1.5, Color32::BLACK)); + clip.circle_stroke(hp, r, Stroke::new(0.75, Color32::WHITE)); + } + w.hover = Some(v.to_doc(hp)); + } + clip.rect_stroke(img, 0.0, Stroke::new(1.0, t.separator), egui::StrokeKind::Outside); + // Mouse → tools (Space, the middle button or the Hand pan). + let pan = ui.input(|i| i.key_down(egui::Key::Space) || i.pointer.middle_down()) || w.tool == CafTool::Hand; + if pan && resp.dragged() { + let dl = resp.drag_delta(); + w.center = [w.center[0] - f64::from(dl.x / w.zoom), w.center[1] - f64::from(dl.y / w.zoom)]; + } else if !pan + && resp.is_pointer_button_down_on() + && let Some(pp) = resp.interact_pointer_pos() + { + // The press is the first point; the frames before egui's drag threshold and the drag + // itself continue it (a second `Down` would start the stroke over, dropping them). + let q = v.to_doc(pp); + mods = ui.input(|i| i.modifiers); + if w.pressed { + events.push(ToolEvent::Move { x: q[0], y: q[1], pressure: 1.0 }); + ctx.request_repaint(); + } else { + w.pressed = true; + events.push(ToolEvent::Down { x: q[0], y: q[1], pressure: 1.0 }); + } + dragging = true; + } + if w.pressed && !resp.is_pointer_button_down_on() { + w.pressed = false; + let q = w.hover.unwrap_or(w.center); + events.push(ToolEvent::Up { x: q[0], y: q[1] }); + dragging = false; + } + // Settings changed in the panel: the overlay and the preview follow. + if w.opts != before { + w.overlay_dirty = true; + w.stale(); + } + }); + if let Some(s) = new_sampling { + set_sampling(app, s); + } + if let Some(r) = reset_what { + reset(app, r); + } + if let Some(e) = fill_btn { + fill_edit(app, e); + } + if rebase_needed { + rebase(app); + } + for ev in events { + pointer(app, ev, mods); + } + drive_preview(app, ctx, dragging); + match action { + Some("ok") => commit(app), + Some("cancel") => cancel(app), + Some("apply") => { + if let Err(e) = apply(app) { + app.ui.status = e; + app.ui.status_error = true; + } + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A textured layer (a checker of two colours over a gradient) with a 20 px square selected. + fn app_with_selection() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 200, "height": 160, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..160 { + for x in 0..200 { + let v = ((x / 6 + y / 6) % 2) as f32 * 0.5 + x as f32 / 400.0; + s.write_pixel(x, y, &[v, 0.3, 1.0 - v, 1.0]); + } + } + // A red blemish to remove. + for y in 72..88 { + for x in 92..108 { + s.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + app.session.execute("select.rect", json!({"x": 90, "y": 70, "width": 20, "height": 20})).unwrap(); + app.sync_views(); + app + } + + fn px(app: &PhotocraftApp, layer: LayerId, x: i32, y: i32) -> Vec { + app.session.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().pixel(x, y) + } + + fn ws(app: &PhotocraftApp) -> &CafWorkspace { + app.distort.caf.as_ref().unwrap() + } + + /// Photoshop opens the workspace with the Sampling Brush subtracting at a tenth of the + /// window's side, Auto sampling, output to a new layer. + #[test] + fn opens_like_photoshop() { + let mut app = app_with_selection(); + app.session.prefs.edit(|p| { + p.dialogs.remove(REMEMBERED); + }); + open(&mut app).unwrap(); + let d = ws(&app).describe(); + assert_eq!(d["window"], json!([0, 0, 200, 160]), "a 200 px window, clipped to the 200 × 160 canvas"); + assert_eq!((d["tool"].as_str(), d["brushMode"].as_str(), d["brushSize"].as_f64()), (Some("brush"), Some("subtract"), Some(20.0))); + assert_eq!((d["settings"]["sampling"].as_str(), d["settings"]["output"].as_str()), (Some("auto"), Some("new"))); + assert_eq!(d["fillArea"], json!(400)); + assert!(d["sampledProxyPixels"].as_u64().unwrap() > 1000); + } + + #[test] + fn brush_strokes_change_the_sampling_area_and_undo() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"sampling": "rectangular"})).unwrap(); + let all = ws(&app).describe()["sampledProxyPixels"].as_u64().unwrap(); + assert_eq!(all, 200 * 160 - 400, "Rectangular: the whole window but the fill area"); + // Subtracting (the default): a 10 px stroke takes about 10 × 60 px away. + let d = control(&mut app, &json!({"stroke": {"points": [[20.0, 20.0], [80.0, 20.0]], "size": 10}})).unwrap(); + let less = d["sampledProxyPixels"].as_u64().unwrap(); + assert!((all - less).abs_diff(10 * 60 + 79) < 120, "{all} → {less}"); + // Undo brings it back; redo takes it again. + assert_eq!(control(&mut app, &json!({"undo": true})).unwrap()["sampledProxyPixels"].as_u64(), Some(all)); + assert_eq!(control(&mut app, &json!({"redo": true})).unwrap()["sampledProxyPixels"].as_u64(), Some(less)); + // Custom starts empty and the brush adds; Alt reverses it. + let d = control(&mut app, &json!({"sampling": "custom"})).unwrap(); + assert_eq!((d["sampledProxyPixels"].as_u64(), d["brushMode"].as_str(), d["strokes"].as_u64()), (Some(0), Some("add"), Some(0))); + let d = control(&mut app, &json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8}})).unwrap(); + assert!(d["sampledProxyPixels"].as_u64().unwrap() > 300); + let d = control(&mut app, &json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8, "alt": true}})).unwrap(); + assert_eq!(d["sampledProxyPixels"].as_u64(), Some(0)); + // Undoing the change of option restores Rectangular with its stroke. + control(&mut app, &json!({"undo": true})).unwrap(); + control(&mut app, &json!({"undo": true})).unwrap(); + let d = control(&mut app, &json!({"undo": true})).unwrap(); + assert_eq!((d["settings"]["sampling"].as_str(), d["strokes"].as_u64(), d["brushMode"].as_str()), (Some("rectangular"), Some(1), Some("subtract"))); + } + + #[test] + fn the_lasso_edits_the_fill_area_and_the_window_follows() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let d = control(&mut app, &json!({"lasso": {"op": "add", "points": [[130.0, 70.0], [150.0, 70.0], [150.0, 90.0], [130.0, 90.0]]}})).unwrap(); + assert_eq!(d["fillArea"], json!(800)); + let d = control(&mut app, &json!({"expand": 2})).unwrap(); + assert!(d["fillArea"].as_u64().unwrap() > 900); + let d = control(&mut app, &json!({"undo": true, "lassoMode": "subtract"})).unwrap(); + assert_eq!((d["fillArea"].as_u64(), d["lassoMode"].as_str()), (Some(800), Some("subtract"))); + // Subtracting everything is refused: the fill area can't be empty. + let d = control(&mut app, &json!({"lasso": {"points": [[0.0, 0.0], [200.0, 0.0], [200.0, 160.0], [0.0, 160.0]]}})).unwrap(); + assert_eq!(d["fillArea"], json!(800)); + assert!(d["error"].as_str().is_some_and(|e| e.contains("empty")), "{d}"); + // The reset button goes back to the selection. + let d = control(&mut app, &json!({"reset": "lasso"})).unwrap(); + assert_eq!(d["fillArea"], json!(400)); + } + + #[test] + fn apply_fills_and_stays_open_ok_closes_cancel_keeps_what_was_applied() { + let mut app = app_with_selection(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + open(&mut app).unwrap(); + // The preview is what Apply writes. + control(&mut app, &json!({"output": "current", "colorAdaptation": "none", "waitPreview": true})).unwrap(); + let (rect, img) = ws(&app).preview.pending_image.clone().unwrap(); + control(&mut app, &json!({"apply": true})).unwrap(); + assert!(app.distort.caf.is_some(), "Apply keeps the workspace open"); + let after = px(&app, layer, 100, 80); + assert!(after[0] < 0.9 || after[1] > 0.1, "the blemish is filled: {after:?}"); + let i = ((80 - rect.y0) * rect.width() as i32 + (100 - rect.x0)) as usize; + let shown = img.pixels[i]; + assert!( + (f32::from(shown.r()) / 255.0 - after[0]).abs() < 0.01 && (f32::from(shown.b()) / 255.0 - after[2]).abs() < 0.01, + "preview {shown:?} vs {after:?}" + ); + let steps = app.session.active().unwrap().history.past_len(); + cancel(&mut app); + assert!(app.distort.caf.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "Cancel keeps the applied fill"); + // OK with New Layer: a new layer holds the fill; the original stays. + app.session.execute("edit.undo", json!({})).unwrap(); + open(&mut app).unwrap(); + control(&mut app, &json!({"output": "new", "commit": true})).unwrap(); + assert!(app.distort.caf.is_none()); + assert_eq!(px(&app, layer, 100, 80)[0], 1.0, "the original layer keeps its blemish"); + let top = app.session.active().unwrap().active_layer.unwrap(); + assert_ne!(top, layer); + assert!(px(&app, top, 100, 80)[3] > 0.99, "the new layer holds the fill"); + } + + /// #5092: the workspace left open does not follow the user to another document, and closing + /// the document it was opened on closes it. + #[test] + fn the_workspace_is_dropped_when_another_document_becomes_active() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.caf.is_some()); + app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap(); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.caf.is_none()); + assert!(app.session.set_active(0)); + open(&mut app).unwrap(); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.caf.is_some()); + assert!(app.session.close(0).is_some()); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.caf.is_none()); + } + + #[test] + fn settings_are_remembered_and_the_menu_opens_the_workspace() { + let ctx = egui::Context::default(); + let mut app = app_with_selection(); + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap(); + assert!(r["contentAwareFill"]["window"].is_array(), "{r}"); + let set = json!({"opacity": 30, "color": [200, 40, 40], "excluded": true, "colorAdaptation": "high", "rotationAdaptation": "low", "mirror": true, "output": "duplicate"}); + crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": set})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": {"cancel": true}})).unwrap(); + open(&mut app).unwrap(); + let mut want = CafOpts::default(); + want.apply(&set).unwrap(); + assert_eq!(ws(&app).opts, want); + // Bad values are errors; the engine command with params still runs directly. + assert!(control(&mut app, &json!({"sampling": "everywhere"})).is_err()); + assert!(control(&mut app, &json!({"tool": "pencil"})).is_err()); + cancel(&mut app); + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"colorAdaptation": "none"})).unwrap(); + assert_eq!(r["filled"], json!(400)); + assert!(app.distort.caf.is_none()); + } + + /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill + /// area. + fn engine_source(app: &PhotocraftApp) -> (Rect, Vec, Vec) { + let w = ws(app); + let st = app.session.active().unwrap(); + let plan = photocraft_engine::edit_menu_cmds::content_aware_plan(&st.doc, w.layer, &plan_params(w, true), CMD).unwrap(); + (plan.rect, plan.source, plan.hole) + } + + /// Each stroke is painted into the proxy once, over its own pixels: 400 strokes of 50 points + /// and the undo and redo that rebuild the proxy stay cheap (they used to test every proxy + /// pixel against every segment), and the overlay is exactly what the engine samples (at one + /// proxy px per document px). + #[test] + fn strokes_are_painted_once_and_the_overlay_is_the_engines_sampling_area() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"sampling": "rectangular"})).unwrap(); + let start = std::time::Instant::now(); + for i in 0..400u32 { + // Lines across the document, most subtracting, every fifth adding (Alt). + let y = 2.0 + f64::from(i % 40) * 4.0; + let pts: Vec<[f64; 2]> = (0..50).map(|j| [f64::from(j) * 4.0 + f64::from(i % 3), y + f64::from(j % 2)]).collect(); + control(&mut app, &json!({"stroke": {"points": pts, "size": 6 + (i % 4) * 3, "alt": i % 5 == 0}})).unwrap(); + } + let painted = start.elapsed(); + let start = std::time::Instant::now(); + control(&mut app, &json!({"undo": true})).unwrap(); + control(&mut app, &json!({"redo": true})).unwrap(); + let rebuilt = start.elapsed(); + assert!(painted.as_secs_f64() < 10.0 && rebuilt.as_secs_f64() < 10.0, "400 strokes {painted:?}, undo + redo {rebuilt:?}"); + let w = ws(&app); + assert_eq!((w.k, w.strokes.len()), (1, 400)); + let (rect, source, hole) = engine_source(&app); + assert_eq!(rect, w.canvas, "Rectangular's window is the whole 200 × 160 canvas"); + let differ = (0..source.len()).filter(|&i| (w.mask[i] && !w.hole_px[i]) != (source[i] && !hole[i])).count(); + assert_eq!(differ, 0, "proxy pixels that differ from the engine's sampling area"); + assert!(w.describe()["sampledProxyPixels"].as_u64().unwrap() > 1000); + } + + /// `edit.contentAwareFill {"ui": …}` addresses the workspace: with it closed that is an + /// error, not a fill with the default settings (an agent polling the state after an Esc + /// used to add a fill per poll). + #[test] + fn ui_params_with_the_workspace_closed_are_an_error_not_a_fill() { + let ctx = egui::Context::default(); + let mut app = app_with_selection(); + let steps = app.session.active().unwrap().history.past_len(); + for ui in [json!({}), json!({"cancel": true}), json!({"sampling": "rectangular"})] { + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": ui})); + assert!(r.as_ref().is_err_and(|e| e.contains("not open")), "{r:?}"); + } + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "nothing was filled"); + assert!(app.distort.caf.is_none()); + } + + /// The press is the first point of a stroke (and of a lasso), and the pointer's moves before + /// egui's drag threshold are its next ones: the drag, which starts a few pixels later, goes + /// on with the same stroke rather than beginning another over it. + #[test] + fn a_stroke_keeps_its_points_from_before_the_drag_threshold() { + use egui::{Modifiers, PointerButton}; + for tool in ["brush", "lasso"] { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"tool": tool, "sampling": "rectangular"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + // The document view sits between the tool strip and the Preview panel, under the + // title and the options bar; its centre shows the document's centre. + let view = ERect::from_min_max(pos2(LEFT_W, 30.0 + BAR_H), pos2(1600.0 - PANEL_W - PREVIEW_W, 1000.0)); + let c = view.center(); + let at = |dx: f32, dy: f32| pos2(c.x + dx, c.y + dy); + let press = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, down: bool, p: Pos2| { + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE }); + h.run_steps(1); + }; + h.event(egui::Event::PointerMoved(at(0.0, 0.0))); + h.run_steps(1); + press(&mut h, true, at(0.0, 0.0)); + // Within egui's click distance (6 px): no drag yet, but these are the stroke's points. + // Then past it: the drag starts. (Not collinear: the lasso's polygon needs an area.) + for (dx, dy) in [(2.0, 1.0), (4.0, 2.0), (30.0, 20.0), (60.0, -10.0), (90.0, 40.0)] { + h.event(egui::Event::PointerMoved(at(dx, dy))); + h.run_steps(1); + } + press(&mut h, false, at(90.0, 40.0)); + h.run_steps(2); + let w = h.state().distort.caf.as_ref().unwrap(); + let points: Vec<[f64; 2]> = match tool { + "brush" => { + assert_eq!(w.strokes.len(), 1, "one stroke"); + w.strokes[0].points.clone() + } + _ => { + assert_eq!(w.fill_edits.len(), 1, "one lasso edit"); + serde_json::from_value(w.fill_edits[0]["points"].clone()).unwrap() + } + }; + let centre = [f64::from(w.canvas.x0 + w.canvas.x1) / 2.0, f64::from(w.canvas.y0 + w.canvas.y1) / 2.0]; + assert_eq!(points.len(), 6, "{tool}: the press and every move are points: {points:?}"); + let d = ((points[0][0] - centre[0]).powi(2) + (points[0][1] - centre[1]).powi(2)).sqrt(); + assert!(d < 1.0, "{tool}: the first point is the press ({:?} vs {centre:?})", points[0]); + assert!(w.cur.is_none() && w.lasso.is_none() && !w.pressed, "{tool}: the release ended it"); + } + } + + /// The preview texture fits the device: a plan rectangle wider than the texture limit is + /// box-averaged to fit, and is still drawn over the plan's rectangle. + #[test] + fn the_preview_texture_respects_the_device_limit() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 2200, "height": 40, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + s.fill_rect(Rect::new(0, 0, 2200, 40), &[0.2, 0.6, 0.4, 1.0]); + s.fill_rect(Rect::new(1090, 10, 1110, 30), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.session.execute("select.rect", json!({"x": 1090, "y": 10, "width": 20, "height": 20})).unwrap(); + app.sync_views(); + open(&mut app).unwrap(); + // Custom sampling with a stroke across the whole width: the plan's rectangle is 2200 px wide. + control(&mut app, &json!({"sampling": "custom", "stroke": {"points": [[0.0, 5.0], [2200.0, 5.0]], "size": 8}})).unwrap(); + for (limit, want) in [(2048usize, 1100usize), (4096, 2200)] { + let w = app.distort.caf.as_mut().unwrap(); + w.texture_limit = limit; + w.stale(); + control(&mut app, &json!({"waitPreview": true})).unwrap(); + let (rect, img) = ws(&app).preview.pending_image.clone().unwrap(); + assert_eq!((rect.width(), img.size[0]), (2200, want), "limit {limit}"); + assert!(img.size.iter().all(|s| *s <= limit), "limit {limit}: {:?}", img.size); + let (sum, n) = img.pixels.iter().fold((0u32, 0u32), |(s, n), p| (s + u32::from(p.g()), n + 1)); + assert!(sum / n > 100, "limit {limit}: the reduced preview keeps the image ({})", sum / n); + } + } + + /// A preview that fails stands for that state: nothing is shown, the error is reported, and + /// the same preview is not started again on every frame. + #[test] + fn a_failing_preview_is_reported_once_not_restarted() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"waitPreview": true})).unwrap(); + assert!(ws(&app).preview.pending_image.is_some()); + // The selection goes away under the workspace: there is nothing to fill. + app.session.execute("select.deselect", json!({})).unwrap(); + app.distort.caf.as_mut().unwrap().stale(); + assert!(control(&mut app, &json!({"waitPreview": true})).is_err()); + let pv = &ws(&app).preview; + assert_eq!(pv.shown, pv.want, "the failed state counts as shown: no retry"); + assert!(pv.pending_image.is_none() && pv.tex.is_none()); + let d = ws(&app).describe(); + assert_eq!(d["previewReady"], json!(false)); + assert!(d["previewError"].as_str().is_some_and(|e| e.contains("selection")), "{d}"); + } + + /// The view shows the document, not the layer alone: after Apply to a new layer the fill + /// (on that layer) covers the blemish. + #[test] + fn the_view_shows_the_document_after_an_apply_to_a_new_layer() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let red = |img: &egui::ColorImage| { + let p = img.pixels[80 * img.size[0] + 100]; + p.r() > 200 && p.g() < 60 + }; + let before = view_image(&app).unwrap(); + assert_eq!(before.size, [200, 160]); + assert!(red(&before), "the blemish shows before the fill"); + control(&mut app, &json!({"output": "new", "colorAdaptation": "none", "apply": true})).unwrap(); + assert!(!red(&view_image(&app).unwrap()), "the fill on the new layer shows"); + } + + /// The engine's limits (MAX_CAF_EDITS strokes or lasso edits, MAX_CAF_POINTS points in all) + /// hold at the brush: a stroke past them is refused with a message, so Apply and the + /// preview never fail on what was painted. + #[test] + fn strokes_past_the_engines_limits_are_refused_at_the_brush() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"sampling": "rectangular"})).unwrap(); + for i in 0..MAX_CAF_EDITS { + let x = (i % 190) as f64; + control(&mut app, &json!({"stroke": {"points": [[x, 5.0], [x + 3.0, 5.0]], "size": 2}})).unwrap(); + } + let d = control(&mut app, &json!({"stroke": {"points": [[10.0, 50.0], [20.0, 50.0]], "size": 2}})).unwrap(); + assert_eq!(d["strokes"], json!(MAX_CAF_EDITS)); + assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); + control(&mut app, &json!({"waitPreview": true})).unwrap(); + // The points budget: a long stroke stops at it. + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let pts: Vec<[f64; 2]> = (0..MAX_CAF_POINTS + 100).map(|i| [10.0 + i as f64 * 0.0005, 5.0]).collect(); + let d = control(&mut app, &json!({"stroke": {"points": pts, "size": 2}})).unwrap(); + assert_eq!(ws(&app).points_used(), MAX_CAF_POINTS); + assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); + control(&mut app, &json!({"waitPreview": true})).unwrap(); + // A lasso edit past the points budget is refused too. + let d = control(&mut app, &json!({"lasso": {"op": "add", "points": [[130.0, 70.0], [150.0, 70.0], [150.0, 90.0]]}})).unwrap(); + assert_eq!(d["fillEdits"], json!(0)); + assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); + } +} diff --git a/crates/ui-egui/src/camera_raw_scope_ui.rs b/crates/ui-egui/src/camera_raw_scope_ui.rs index c9f98080c9..9cb5233d00 100644 --- a/crates/ui-egui/src/camera_raw_scope_ui.rs +++ b/crates/ui-egui/src/camera_raw_scope_ui.rs @@ -384,7 +384,8 @@ fn graph(ui: &mut egui::Ui, d: &mut CameraRawDialog, view: &mut CameraRawScopeSt response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, ui.is_enabled(), tl!("Tone Histogram"))); ui.painter().rect_filled(rect, t.radius_sm, t.histogram_background()); let plot = rect.shrink(4.0); - crate::rgb_histogram::paint(ui.painter(), plot, d.histogram(), &t); + // Camera Raw's scale: the typical columns set it and a shadow or highlight spike runs off the top. + crate::rgb_histogram::paint_with(ui.painter(), plot, d.histogram(), &t, crate::rgb_histogram::Spikes::Clip); let corner = 18.0; if let Some(sample) = d.hover_sample(false) { crate::rgb_histogram::paint_sample(ui.painter(), plot, sample.rgb, &t); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ea7a78c4f4..165f6d5033 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -516,12 +516,22 @@ pub(crate) struct CommittedStroke { pub(crate) revision: u64, key: u64, damage: Vec, + /// What the commit repaints beyond the stroke whatever a cache showed: the layer's whole + /// composite when effects laid out over its frame moved with it (a Gradient Overlay spans the + /// grown layer, #4053; `photocraft_compose::relayout_damage`). + relayout: DRect, } impl CommittedStroke { #[cfg(test)] pub(crate) fn for_test(key: u64, damage: Vec) -> Self { - Self { doc: photocraft_doc::DocId(0), revision: 0, key, damage } + Self { doc: photocraft_doc::DocId(0), revision: 0, key, damage, relayout: DRect::EMPTY } + } + + /// The raw preview key of the live stroke's last step: what a cache showed at release. + #[cfg(test)] + pub(crate) fn last_key(&self) -> u64 { + self.key + self.damage.len() as u64 } /// What a cache that showed raw preview `key` of this stroke at the revision before misses. @@ -1224,12 +1234,13 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Ar return (doc.clone(), key); } } + let revision = st.revision; let snapshot = st.doc.clone(); if let Some((layer, params)) = app.live_adjust.clone() && let Some(l) = snapshot.layer(layer) && let LayerContent::Adjustment(a) = &l.content { - let key = 1 + params.to_string().bytes().fold(0u64, |h, b| h.wrapping_mul(31).wrapping_add(b as u64)); + let key = crate::adjust_preview::live_key(app, &snapshot, revision, layer, ¶ms); let shown = memo_display(app, &snapshot, key, || { let kind = photocraft_engine::commands::adjustment_kind(a); let preview = photocraft_engine::adjust_params::from_params(kind, ¶ms, Some(a), snapshot.mode).unwrap_or_else(|_| a.clone()); @@ -1492,6 +1503,13 @@ pub(crate) fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), no && let Some(c) = app.committed_stroke.as_ref().filter(|c| c.doc == st.doc.id && c.revision == now.0) && let Some(r) = c.since(seen.1 ^ display_key) { + let r = if c.relayout.is_empty() { + r + } else if r.is_empty() { + c.relayout + } else { + r.union(&c.relayout) + }; return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); } if seen.1 == now.1 ^ display_key && seen.0 + 1 == now.0 { @@ -1510,6 +1528,14 @@ pub(crate) fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), no { return Some(r); } + // Between a Properties-panel adjustment-layer drag's previews (and the document): the + // layer's area. Without this every parameter value recomposited the whole document (#6839). + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::adjust_preview::live_switch_region(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(r); + } // Between a Move drag's offsets: where the moving layers were and are (Auto-Select's pick // at the press changes no pixels). if (seen.0 == now.0 || (seen.0 + 1 == now.0 && last_damage.is_some_and(|r| r.is_empty()))) @@ -1603,16 +1629,28 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: }; let (doc, raw_key) = display_doc(app, idx); let (display, _) = canvas_display(app, &doc, None); + // Repeated pattern tiles sample the same texture, including pixels outside the unwrapped + // viewport. Refresh the affected document region while Pattern Preview is enabled. + let blend_visible = if app.ui.view.pattern_preview { doc.bounds() } else { visible }; // The texture is shared by every display: only what it stores counts, not the monitor. let display_key = texture_key(display.as_deref()); let seen = app.canvases.get(&(id, GPU_OUTPUT)).map(|c| (c.revision, c.preview_key)); let mut damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, raw_key), display_key, last_damage)); + if let Some(region) = damage { + damage = Some(crate::blend_preview::clip_damage(app, id, revision, raw_key, region, blend_visible)); + } // To an adjustment dialog's preview: only what the view shows now (the rest as it moves there). if damage.is_some() && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::switch_region(app, id, revision, s.1 ^ display_key, raw_key)) { damage = Some(crate::adjust_preview::switch_damage(app, raw_key, r, visible)); } + // The same for a Properties-panel drag's previews. + if damage.is_some() + && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::live_switch_region(app, id, revision, s.1 ^ display_key, raw_key)) + { + damage = Some(crate::adjust_preview::live_switch_damage(app, raw_key, r, visible)); + } let preview_key = raw_key ^ display_key; // The Navigator may draw this texture only while it holds the plain document (no live // preview, which can be composited only where the view is). @@ -1654,9 +1692,18 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: // An adjustment preview composited where the view was: catch up where it moved to. if let Some(r) = crate::adjust_preview::uncovered(app, id, raw_key, visible) { let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref()); - app.perf.record(r.kind, r.px, r.composite_ms, r.upload_ms); + app.perf.record_refresh(&r); + } + if let Some(r) = crate::adjust_preview::live_uncovered(app, id, raw_key, visible) { + let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref()); + app.perf.record_refresh(&r); + } + // Blend previews keep offscreen pixels untouched until the view reaches them. + // Use the normal refresh path so CPU fallback and pending redraws stay synchronized. + damage = crate::blend_preview::uncovered(app, id, revision, raw_key, blend_visible); + if damage.is_none() { + return true; } - return true; } // Display textures for a canvas this large would not fit the GPU: the reduced CPU canvas // draws it (checked before the memory budget, which walks the history, every frame). @@ -1695,7 +1742,7 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: log::info!("{e}; using the CPU compositor"); } if r.kind != crate::gpu_canvas::REFRESH_DEFERRED { - app.perf.record(r.kind, r.px, r.composite_ms, r.upload_ms); + app.perf.record_refresh(&r); } if r.kind == "full" { crate::notices::slow_cpu_refresh(app, id.0, r.composite_ms + r.upload_ms, r.fallback.as_deref()); @@ -1741,6 +1788,27 @@ fn budget_allowance(app: &PhotocraftApp) -> (u64, u64) { (u64::from(performance.memory_usage_mb).saturating_mul(1 << 20), u64::from(performance.gpu_memory_mb).saturating_mul(1 << 20)) } +/// The proxy factor of a live preview of filter `cmd` with `params` on `doc`, the active document: +/// reduced on a large document (Preferences › Performance › Low Resolution Previews), except for +/// filters whose features don't scale with a proxy (#2063), and never coarser than the active view, +/// so at 100 % the preview shows every pixel instead of k-pixel blocks (#6326, as adjustment +/// previews have since #5764). Zoomed out, the proxy keeps previews of large documents fast. +/// +/// The in-dialog preview window ([`crate::filter_preview_ui`]) sizes its own textures from this +/// too, so the canvas and the window never disagree about the factor. +/// +/// Full resolution costs a whole filter per parameter change, which only the background worker +/// absorbs. The web build has no worker and computes the preview inline on the UI thread (#1676), +/// where that would freeze the page: there the document's proxy stands. The test and +/// `PHOTOCRAFT_INLINE_JOBS` inline paths keep the cap deliberately, because `background_jobs` is +/// flipped mid-session (a shell save during `actions.play`): a factor that followed it would change +/// [`crate::filter_dialog::FilterPreviewKey`] under a finished preview and recompute it inline, +/// the very stall this avoids. +pub(crate) fn filter_preview_factor(app: &PhotocraftApp, doc: &Document, cmd: &str, params: &serde_json::Value) -> u32 { + let k = crate::filter_dialog::preview_factor(cmd, params, crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app))); + if cfg!(target_arch = "wasm32") { k } else { crate::proxy::view_factor(k, app.current_zoom()) } +} + /// Live preview for an open filter dialog: run the filter on the proxy and upload it. With /// background jobs (the desktop app) it computes on one background worker /// (`filter_preview_worker`); otherwise (web, tests, `PHOTOCRAFT_INLINE_JOBS`) it keeps the @@ -1762,8 +1830,14 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e return None; } let cmd = d.fields.get("__command")?.as_str()?.to_string(); - // Previews edit what the command will: a targeted layer mask included (#780). - let mut params = app.with_mask_target(&cmd, crate::filter_dialog::params_of(&d.fields)); + // Previews edit what the command will: a targeted layer mask included (#780), and a smart + // filter being edited is replaced in its stack rather than stacked again (#6324). + let (cmd, mut params) = if d.fields.contains_key("__smartFilter") { + crate::smart_ui::confirm_command(&d.fields, cmd, crate::filter_dialog::params_of(&d.fields)) + } else { + let params = app.with_mask_target(&cmd, crate::filter_dialog::params_of(&d.fields)); + (cmd, params) + }; // Select and Mask previews in its view mode; holding X shows the image without one. if crate::select_mask_view::owns(&d.fields) { if crate::select_mask_view::hides_view(&d.fields) { @@ -1772,8 +1846,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e params = crate::select_mask_view::request_params(&d.fields, params); } let st = app.session.documents().get(idx)?; - // Filters whose features don't scale with a proxy preview at full resolution (#2063). - let k = crate::filter_dialog::preview_factor(&cmd, ¶ms, crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app))); + let k = filter_preview_factor(app, &st.doc, &cmd, ¶ms); let request = crate::filter_dialog::FilterPreviewKey { doc: st.doc.id, revision: st.revision, @@ -1820,6 +1893,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e if !fresh && !app.filter_preview_worker.busy() { let doc = app.session.documents().get(idx)?.doc.clone(); let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let color = app.session.color.settings.clone(); let task = request.clone(); if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move |cancel| { let t0 = crate::gpu_canvas::now_ms(); @@ -1832,6 +1906,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e Some(cancel), task.target, &documents, + &color, ) .map(|doc| { let buffer = photocraft_compose::flatten(&doc); @@ -1856,12 +1931,13 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e } // Web and explicitly inline sessions keep the deterministic synchronous path (#1676): // computed inline, uploaded when a GPU texture exists, still inspectable without one. + // Flattened once, as the background worker does; `publish_filter_preview` uploads it (#7490). let _ = ctx; if app.filter_preview.as_ref().is_none_or(|p| p.key != request) { let doc = app.session.documents().get(idx)?.doc.clone(); let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); let t0 = crate::gpu_canvas::now_ms(); - let result = crate::filter_dialog::preview_document_for_target( + let computed = crate::filter_dialog::preview_document_for_target( &doc, request.active, &request.command, @@ -1870,19 +1946,13 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e None, request.target, &documents, + &app.session.color.settings, ) - .map(std::sync::Arc::new); - if let Some(r) = &result { - let buf = photocraft_compose::flatten(r); - let t1 = crate::gpu_canvas::now_ms(); - let (display, _) = canvas_display(app, &doc, None); - if let Some(gpu) = app.gpu.as_ref() { - gpu.upload_buffer_full(key, &texture_buffer(display.as_deref(), &buf), doc.depth); - } - app.perf.record("filter-preview", r.size.area(), t1 - t0, crate::gpu_canvas::now_ms() - t1); - } - let buffer = result.as_ref().map(|r| photocraft_compose::flatten(r)); - publish_filter_preview(app, idx, request, result.zip(buffer), crate::gpu_canvas::now_ms() - t0); + .map(|doc| { + let buffer = photocraft_compose::flatten(&doc); + (std::sync::Arc::new(doc), buffer) + }); + publish_filter_preview(app, idx, request, computed, crate::gpu_canvas::now_ms() - t0); } let preview = app.filter_preview.as_ref()?; let result = preview.result.as_ref()?; @@ -1911,7 +1981,9 @@ fn publish_filter_preview( let result = computed.and_then(|(result, buffer)| { let t0 = crate::gpu_canvas::now_ms(); let doc = app.session.documents().get(idx)?.doc.clone(); - let (display, _) = canvas_display(app, &doc, None); + // Shown through the preview's own colour management, as the result will be: Assign and + // Convert to Profile change the profile (and Convert the mode), not just the pixels. + let (display, _) = canvas_display(app, &result, None); // A GPU texture is an optimisation: headless/CPU tests must still see the preview. if let Some(gpu) = app.gpu.as_ref() { gpu.upload_buffer_full(request.doc.0 ^ (1u64 << 61), &texture_buffer(display.as_deref(), &buffer), doc.depth); @@ -1922,6 +1994,16 @@ fn publish_filter_preview( app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request, result, committing: false }); } +/// The document whose colour management the canvas texture under `key` is shown through: a filter +/// preview's own result (it keeps the document's id, so Proof Colors still apply), else `doc`. +/// Assign Profile changes only the profile, so through `doc`'s its preview looked unchanged. +fn filter_preview_display_doc(app: &PhotocraftApp, doc: &std::sync::Arc, key: u64) -> std::sync::Arc { + if key != doc.id.0 ^ (1u64 << 61) { + return doc.clone(); + } + app.filter_preview.as_ref().and_then(|p| p.result.clone()).filter(|r| r.id == doc.id).unwrap_or_else(|| doc.clone()) +} + /// After a filter dialog's OK: `Some(shown)` while its preview stands in for the background job /// that commits it (the document unchanged and the job still running, for this document's views), /// `None` otherwise (other documents' views included). A job that lands, fails or is cancelled @@ -1975,6 +2057,9 @@ fn ensure_adjust_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option let (display, _) = canvas_display(app, &doc, None); let r = gpu.refresh(key, &frame.doc, frame.damage, display.as_deref()); app.perf.record(if r.kind.starts_with("gpu") { "gpu-adjust-proxy" } else { "adjust-proxy" }, r.px, r.composite_ms, r.upload_ms); + if let Some(t) = r.gpu { + app.perf.record_gpu(t); + } crate::adjust_preview::proxy_drawn(app, &frame); } Some((frame.k, key, size)) @@ -2078,9 +2163,12 @@ pub(crate) fn arranged_cells(app: &PhotocraftApp, rect: Rect) -> Option = (0..n).map(|k| (idx + k) % n).zip(cells).collect(); - shown.sort_by_key(|(d, _)| *d); - Some(shown) + // Each document keeps its tile: a click into another one activates it where it is (#6017; it + // used to move to the first tile). With more documents than tiles, the shown run stays put + // while the active document is in it, and otherwise slides only as far as it must. + let start = app.arrange_start.min(n.saturating_sub(cells.len())); + let start = if idx < start { idx } else { start.max((idx + 1).saturating_sub(cells.len())) }; + Some((start..n).zip(cells).collect()) } fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -2126,6 +2214,7 @@ fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Window › Arrange: tiled / n-up layouts show several documents side by side; the active one // takes input, a click elsewhere activates that document. if let Some(shown) = arranged_cells(app, rect) { + app.arrange_start = shown.first().map_or(0, |(d, _)| *d); let t = crate::theme::Tokens::get(ui.ctx()); for (d, cell) in shown { let cell = cell.shrink(1.0); @@ -2196,7 +2285,7 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); let frame = egui::Frame::NONE.fill(t.canvas).inner_margin(egui::Margin { left: 8, right: 8, top: 6, bottom: 4 }).show(ui, |ui| { let (row, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), tab_h), Sense::hover()); - let f = crate::tab_strip::fit(&natural, selected, row.width(), DOC_TAB_MIN_W, crate::tab_strip::CHEVRON_W); + let f = fit_doc_tabs(&natural, selected, row.width()); let mut x = row.left(); let mut placed: Vec<(usize, Rect)> = Vec::with_capacity(f.shown.len()); for &(i, w) in &f.shown { @@ -2294,7 +2383,10 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { let labels: Vec<&str> = app.session.documents().iter().map(|st| st.doc.name.as_str()).chain(opening.iter().map(|(_, name, _)| name.as_str())).collect(); let mut picked = None; - crate::tab_strip::overflow_button(ui, ui.id().with("dtab-overflow"), r, tl!("More documents"), &labels, &f.overflow, &mut picked); + // Like Photoshop's, the menu lists every open document, not only the hidden ones, and checks + // the active one (#4487). + let every: Vec = (0..labels.len()).collect(); + crate::tab_strip::overflow_button(ui, ui.id().with("dtab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); match picked { Some(i) if i < tab_count => activate = Some(i), Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), @@ -2468,23 +2560,39 @@ fn open_tab_clicks( } } -/// Document tabs: the chrome around a title (the × and its gaps), and the width a tab shrinks to -/// before it moves into the » overflow menu. +/// Document tabs: the chrome around a title (the × and its gaps). const DOC_TAB_PAD: f32 = 42.0; -const DOC_TAB_MIN_W: f32 = 72.0; /// The Studio strip's tabs carried 4 pt of spacing between them and 44 pt of chrome; `fit` sees /// one number per tab, so the gap rides in the natural width and comes back out when painted. const STUDIO_TAB_PAD: f32 = 48.0; const STUDIO_TAB_GAP: f32 = 4.0; +/// Fit document tabs as Photoshop does (#4487): a tab never shrinks below its whole title, so the +/// tabs that don't fit move into the » menu instead. Only the active tab, when it alone is wider +/// than the strip, is cut. +fn fit_doc_tabs(natural: &[f32], selected: usize, avail: f32) -> crate::tab_strip::TabFit { + let widest = natural.iter().copied().filter(|w| w.is_finite()).fold(0.0, f32::max); + crate::tab_strip::fit(natural, selected, avail, widest, crate::tab_strip::CHEVRON_W) +} + /// Photoshop's tab title: "name @ 50% (Layer 1, RGB/8)", "(Layer 1, Layer Mask/8)" when the mask -/// is targeted; the Background layer's name is omitted. +/// is targeted, "(Quick Mask/8)" in Quick Mask mode; the Background layer's name is omitted. fn pro_tab_title(app: &PhotocraftApp, i: usize) -> String { + use photocraft_engine::channel_cmds::ChannelTarget; let Some(st) = app.session.documents().get(i) else { return String::new() }; let zoom = app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0); - let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !st.doc.is_background(l.id)); + // Quick Mask mode targets the mask, not the layer (see `paint_target`): painting and Free + // Transform change the red overlay, so the tab says so, as Photoshop's does. + let quick_mask = st.doc.quick_mask.is_some() && st.channel_view.target == ChannelTarget::Composite; + let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !quick_mask && !st.doc.is_background(l.id)); let mask = app.session.active_index() == Some(i) && app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some()); - let model = if mask { tl!("Layer Mask").to_string() } else { mode_label(&st.doc).to_string() }; + let model = if quick_mask { + tl!("Quick Mask").to_string() + } else if mask { + tl!("Layer Mask").to_string() + } else { + mode_label(&st.doc).to_string() + }; let layer = active_layer.map(|l| format!("{}, ", l.name)).unwrap_or_default(); // A save in progress: "name @ 100% (Layer 1, RGB/16) - Saving 45%", as Photoshop does (#3389). let saving = crate::jobs_ui::save_progress(app, st.doc.id).map(|s| format!(" - {s}")).unwrap_or_default(); @@ -2498,8 +2606,8 @@ fn studio_tab_name(app: &PhotocraftApp, st: &photocraft_engine::DocState) -> Str } /// Photoshop document tabs: "name @ 33.3% (RGB/8)" on a dark strip; active tab matches panels. -/// Tabs that don't fit shrink and elide, and the ones that still don't fit move into a » menu at -/// the end of the strip; the active document's tab always stays on the strip (#1276). +/// Tabs keep their whole titles, and the ones that don't fit move into a » menu at the end of the +/// strip; the active document's tab always stays on the strip (#1276, #4487). fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { let t = crate::theme::Tokens::get(ui.ctx()); let active = app.session.active_index().filter(|_| app.jobs.focus.is_none()); @@ -2528,7 +2636,7 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { .focus .and_then(|job| opening.iter().position(|(open, _, _)| *open == job)) .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); - let f = crate::tab_strip::fit(&natural, selected, strip.width(), DOC_TAB_MIN_W, crate::tab_strip::CHEVRON_W); + let f = fit_doc_tabs(&natural, selected, strip.width()); let mut x = strip.left(); let mut placed: Vec<(usize, Rect)> = Vec::with_capacity(f.shown.len()); for &(i, w) in &f.shown { @@ -2607,7 +2715,10 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { let r = Rect::from_min_size(egui::pos2(left, strip.top()), egui::vec2(crate::tab_strip::CHEVRON_W, strip.height())); let labels: Vec<&str> = titles.iter().map(String::as_str).collect(); let mut picked = None; - crate::tab_strip::overflow_button(ui, ui.id().with("ptab-overflow"), r, tl!("More documents"), &labels, &f.overflow, &mut picked); + // Like Photoshop's, the menu lists every open document, not only the hidden ones, and checks + // the active one (#4487). + let every: Vec = (0..labels.len()).collect(); + crate::tab_strip::overflow_button(ui, ui.id().with("ptab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); match picked { Some(i) if i < tab_count => activate = Some(i), Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), @@ -2745,6 +2856,13 @@ fn open_on_double_click(app: &mut PhotocraftApp, ui: &egui::Ui, area: Rect) { } } +/// The Home screen's card is this wide when the canvas has room, and as wide as the canvas when it doesn't. +const HOME_CARD_WIDTH: f32 = 460.0; +/// Least width of each of the Home screen's New document and Open buttons. +const HOME_BUTTON_WIDTH: f32 = 190.0; +/// Space between the Home screen's two buttons. +const HOME_BUTTON_GAP: f32 = 12.0; + fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = crate::theme::Tokens::get(ui.ctx()); let area = ui.available_rect_before_wrap(); @@ -2755,9 +2873,16 @@ fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let recent: Vec = if cfg!(target_arch = "wasm32") || !show_recent { Vec::new() } else { app.ui.recent_files.iter().take(HOME_RECENT).cloned().collect() }; let recent_h = if recent.is_empty() { 0.0 } else { 34.0 + recent.len() as f32 * HOME_RECENT_ROW }; - let card = Rect::from_center_size(area.center(), egui::vec2(460.0, 330.0 + recent_h)); + // A tiling window manager can give the canvas less room than the card wants: shrink the card + // to fit, and stack the buttons when they don't fit side by side. let new_label = crate::shortcuts::command_label(app, "New document…", "file.new"); let open_label = crate::shortcuts::command_label(app, "Open…", "file.open"); + let card_width = HOME_CARD_WIDTH.min(area.width()); + let button_width = HOME_BUTTON_WIDTH.max(crate::widgets::button_width(ui, &[&new_label, &open_label])); + let side_by_side = 2.0 * button_width + HOME_BUTTON_GAP <= card_width; + // Stacked buttons take one more row. + let stacked_h = if side_by_side { 0.0 } else { 44.0 }; + let card = Rect::from_center_size(area.center(), egui::vec2(card_width, 330.0 + recent_h + stacked_h)); ui.scope_builder(egui::UiBuilder::new().max_rect(card), |ui| { ui.vertical_centered(|ui| { ui.horizontal(|ui| { @@ -2773,17 +2898,26 @@ fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.add_space(6.0); ui.label(egui::RichText::new(tl!("Create a new document or open an existing file.")).color(t.text_dim).size(14.0)); ui.add_space(22.0); - ui.horizontal(|ui| { - ui.add_space(((card.width() - 2.0 * 190.0 - 12.0) / 2.0).max(0.0)); - ui.spacing_mut().item_spacing.x = 12.0; - if crate::widgets::primary_button(ui, &new_label, 190.0).clicked() { - let fields = app.new_document_fields(); - app.ui.open_dialog(crate::state::DialogKind::NewDocument, fields); - } - if crate::widgets::secondary_button(ui, &open_label, 190.0).clicked() { - let _ = app.open_dialog_file(); - } - }); + let (mut new_clicked, mut open_clicked) = (false, false); + if side_by_side { + ui.horizontal(|ui| { + ui.add_space(((card.width() - 2.0 * button_width - HOME_BUTTON_GAP) / 2.0).max(0.0)); + ui.spacing_mut().item_spacing.x = HOME_BUTTON_GAP; + new_clicked = crate::widgets::primary_button(ui, &new_label, button_width).clicked(); + open_clicked = crate::widgets::secondary_button(ui, &open_label, button_width).clicked(); + }); + } else { + new_clicked = crate::widgets::primary_button(ui, &new_label, button_width).clicked(); + ui.add_space(HOME_BUTTON_GAP); + open_clicked = crate::widgets::secondary_button(ui, &open_label, button_width).clicked(); + } + if new_clicked { + let fields = app.new_document_fields(); + app.ui.open_dialog(crate::state::DialogKind::NewDocument, fields); + } + if open_clicked { + let _ = app.open_dialog_file(); + } ui.add_space(22.0); ui.horizontal(|ui| { let msg = start_screen_drop_hint(app); @@ -2962,7 +3096,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: crate::monitor_status::check_window(app, &ctx); } let full = rect; - let rect = if primary { crate::rulers::content_rect(app, rect) } else { rect }; + // Every document view has its rulers, the tiles of Window › Arrange and floating windows + // too, as in Photoshop (#6017). + let rect = crate::rulers::content_rect(app, rect); let doc = app.session.documents()[idx].doc.clone(); let size = [doc.size.width, doc.size.height]; if view.doc_size != size { @@ -3033,6 +3169,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: on_gpu = true; app.navigator_gpu.remove(&doc.id); let original_size = [doc.size.width.div_ceil(k), doc.size.height.div_ceil(k)]; + let shown = filter_preview_display_doc(app, &doc, key); let params = crate::gpu_canvas::ViewParams { doc: key, doc_size: preview_size, @@ -3049,7 +3186,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: }, pixel_grid: false, view_key: egui::Id::new(("pc-canvas-proxy", ctx.viewport_id(), idx)).value(), - display: sync_display_lut(app, &doc, key, output), + display: sync_display_lut(app, &shown, key, output), output: output.unwrap_or(0), hdr: hdr_preview(app, &doc), offset: [0.0, 0.0], @@ -3262,6 +3399,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let over_bars = ctx.data(|d| d.get_temp::(bars_id)).unwrap_or(false); let nav_hovered = response.hovered() || free_hover || over_bars; // Interface › Enable Animations off: the wheel moves the canvas without a glide (#5721). + // Enhanced Controls › Enable Gestures off: two fingers on a touch screen neither zoom nor + // turn the view (#204); the mouse and trackpad are unaffected. + let touch_gestures = app.session.prefs().enhanced_controls.touch_gestures; let wheel = crate::wheel_nav::read_with( &ctx, app.session.prefs().general.zoom_with_scroll_wheel, @@ -3269,6 +3409,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: response.id.with("wheel"), nav_hovered, app.session.prefs().interface.enable_animations, + touch_gestures, ); if nav_hovered { let pointer = ui.input(|i| i.pointer.hover_pos()); @@ -3301,7 +3442,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: _ => {} } let rotate_trackpad = app.session.prefs().enhanced_controls.rotate_view_with_trackpad; - if let Some(delta) = crate::rotate_view::trackpad_delta(&ctx, rotate_trackpad) { + if let Some(delta) = crate::rotate_view::trackpad_delta(&ctx, rotate_trackpad, touch_gestures) { let next = view.rotation + crate::rotate_view::screen_delta(delta, xf.flip); if next.is_finite() { view.rotation = crate::rotate_view::wrap_deg(next); @@ -3373,7 +3514,21 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // Layer Style on a Drop or Inner Shadow page: a drag on the image moves the shadow (#5701). let shadow_drag = !picking && app.ui.dialogs.last().is_some_and(|d| d.kind == crate::state::DialogKind::LayerStyle && crate::layer_style::drags_shadow(&d.fields)); - let hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning && !shadow_drag; + // ⌘/Ctrl-click with Curves open: a point at the pixel's tone (#7325), whatever the tool. The + // press's own modifiers decide, and only the press adds: a drag would add one per frame. + let curve_point_press = (primary && !middle && crate::adjust_dialog::curves_on_top(app)) + .then(|| { + ctx.input(|i| { + i.events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { button: PointerButton::Primary, pressed: true, modifiers, .. } => Some(*modifiers), + _ => None, + }) + }) + }) + .flatten() + .map(|m| crate::workspace_ui::sticky_mods(app, m)) + .filter(|m| m.command); + let hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning && !shadow_drag && curve_point_press.is_none(); if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, hand) { let d = xf.unmap_vec(d) / (view.zoom / ppp); view.center[0] -= d.x; @@ -3418,6 +3573,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: { let press = crate::dialogs::free_press(&ctx, rect).map(|q| xf.to_doc(q)); crate::select_mask_view::canvas_brush(app, &painter, p, press, xf.zoom_x()); + } else if let Some(mods) = curve_point_press + && let Some(p) = crate::dialogs::free_press(&ctx, rect) + { + let d = xf.to_doc(p); + crate::adjust_dialog::add_point_at(app, &ctx, d[0], d[1], mods.shift); } else if primary && !middle && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect).filter(|p| img_rect.contains(*p)) @@ -4112,6 +4272,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if primary && hand_pan && response.dragged() { crate::transform_tool::draw_content(app, &painter, &xf); crate::transform_tool::draw_overlay(app, &painter, &xf); + // The Pen's path in progress survives a Space pan, and stays on screen through it (#6592). + crate::vector_ui::draw_overlay(app, &painter, &xf, &doc); } app.tool_override = None; if let Some(b) = layer_edges_rect(app, idx) { @@ -4145,6 +4307,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } if primary && app.ui.extras.rulers { crate::rulers::draw_rulers(app, ui, full, &xf); + } else if app.ui.extras.rulers { + crate::rulers::paint_rulers(app, ui, full, &xf, &doc); } crate::rotate_view::overlay(app, &ctx, &painter, &xf, &mut view, &response); if primary { @@ -4353,7 +4517,7 @@ pub(crate) fn marching_ants_lines(painter: &egui::Painter, lines: impl Iterator< }; for (pa, pb) in lines { // A transformed outline can land anywhere, or nowhere (a point on a Distort's horizon). - if !(pa.is_finite() && pb.is_finite()) || !clip.intersects(Rect::from_two_pos(pa, pb).expand(1.0)) { + if !(pa.is_finite() && pb.is_finite() && clip.intersects(Rect::from_two_pos(pa, pb).expand(1.0))) { continue; } let (pa, pb) = if pa.distance(pb) > LONG { @@ -4909,8 +5073,9 @@ fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &View Tool::QuickSelection => Color32::from_white_alpha(40), // The Remove Tool tints what it will remove, like Photoshop's. Tool::Remove => crate::theme::Tokens::get(painter.ctx()).danger.gamma_multiply(0.45), - // The Spot Healing Brush darkens the area it will heal, as Photoshop's does while - // dragging; the heal itself is computed on release. + // Photoshop paints the area to heal in half-opaque dark grey while dragging; a faint + // white trail barely showed on light pixels (#7342). The heal itself is computed on + // release. Tool::SpotHealing => SPOT_HEALING_TRAIL, _ => Color32::from_white_alpha(60), }; @@ -5231,7 +5396,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) if crate::gradient_ui::pointer(app, ev, mods) { return; } - // ⌘ with a selection tool over a guide takes the guide (#2690); the guide drag below moves it. + // ⌘ over a guide takes the guide (#2690, #6288); the guide drag below moves it. if let ToolEvent::Down { x, y, .. } = raw && let Some((vertical, i)) = command_guide_at(app, app.active_tool(), [x, y], mods) { @@ -5438,7 +5603,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) Tool::MagicWand => { let o = app.ui.tool_options.clone(); let mode = selection_mode(app, mods); - let _ = app.run("select.magicWand", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all_layers, "mode": mode})); + let _ = app.run("select.magicWand", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.magic_wand, "mode": mode})); return; } Tool::MagicEraser => { @@ -5448,7 +5613,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) Tool::PaintBucket => { let o = app.ui.tool_options.clone(); let contents = if o.bucket_fill_pattern { "pattern" } else { "foreground" }; - let _ = app.run("paint.bucket", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all_layers, "opacity": o.fill_opacity, "contents": contents, "target": paint_target(app)})); + let _ = app.run("paint.bucket", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.paint_bucket, "opacity": o.fill_opacity, "contents": contents, "target": paint_target(app)})); return; } Tool::RedEye => { @@ -5520,6 +5685,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { e.dragging = false; e.resize = None; + app.ui.caret_blink_time = app.last_frame_time; } if tool == Tool::Pen { crate::vector_ui::pen_up(app); @@ -5625,13 +5791,16 @@ pub(crate) fn command_moves_layer(app: &PhotocraftApp, tool: Tool, p: [f64; 2], selection_tool && mods.command && !mods.shift && !floating && app.ui.polygon.is_empty() && !inside_selection(app, p) } -/// The guide a ⌘ press with selection tool `tool` at `p` drags (vertical?, index), as the Move -/// tool's press would (#2690): ⌘ is the Move tool, and a guide under the pointer comes before the -/// layer or the selected pixels. Not while a polygon or lasso outline is being drawn. +/// The guide a ⌘ press with `tool` at `p` drags (vertical?, index), as the Move tool's press +/// would (#2690): ⌘ is the Move tool, and a guide under the pointer comes before the layer or the +/// selected pixels. The selection tools, and every tool on which ⌘ is the Move tool +/// (`hold_keys::cmd_moves`, #6288); the canvas shows the guide cursor where this finds a guide. +/// Not while a polygon or lasso outline, a stroke, Free Transform or type editing is under way. pub(crate) fn command_guide_at(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option<(bool, usize)> { let selection_tool = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand); - let idle = app.ui.polygon.is_empty() && !crate::lasso_ui::active(app) && app.ui.transform.is_none(); - (selection_tool && mods.command && idle).then(|| crate::rulers::guide_at(app, p[0], p[1])).flatten() + let moves = selection_tool || crate::hold_keys::cmd_moves(tool); + let idle = app.ui.polygon.is_empty() && !crate::lasso_ui::active(app) && app.ui.transform.is_none() && app.ui.text_edit.is_none() && app.drag.is_none(); + (moves && mods.command && idle).then(|| crate::rulers::guide_at(app, p[0], p[1])).flatten() } /// Photoshop's cursor over a selection: what a press (or the drag under way) would do. @@ -5752,6 +5921,7 @@ fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) { } } let LiveStroke { stroke, doc, key, damage, .. } = l; + let before = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.doc.clone()); if let EngineStroke::Brush(stroke) = stroke && app.session.offer_live_stroke(*stroke).is_err() { @@ -5762,14 +5932,15 @@ fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) { app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started); app.session.clear_live_stroke(); let Ok(r) = result else { return }; - let revision = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.revision); + let after = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| (st.revision, st.doc.clone())); if r.get("fromLive").and_then(serde_json::Value::as_bool) == Some(true) - && let Some(revision) = revision + && let Some((revision, after)) = after { - app.committed_stroke = Some(CommittedStroke { doc, revision, key, damage }); + let relayout = before.map_or(DRect::EMPTY, |b| photocraft_compose::relayout_damage(&b, &after)); + app.committed_stroke = Some(CommittedStroke { doc, revision, key, damage, relayout }); } else { // Rendered again from scratch: the commit's damage rect refreshes the stroke. - let shown = CommittedStroke { doc, revision: 0, key, damage }; + let shown = CommittedStroke { doc, revision: 0, key, damage, relayout: DRect::EMPTY }; // Raw preview key 0 = the document itself (its colour display folded in). shown_as_document(app, doc, |k| shown.since(k).is_some()); } @@ -5867,14 +6038,12 @@ pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { let _ = app.run("select.deselect", json!({})); } } - Tool::Gradient => { - if (end[0] - d.start[0]).abs() + (end[1] - d.start[1]).abs() >= 2.0 { - let o = app.ui.tool_options.clone(); - let _ = app.run( - "paint.gradient", - json!({"from": [d.start[0], d.start[1]], "to": [end[0], end[1]], "style": o.gradient_style, "reverse": o.gradient_reverse, "dither": o.gradient_dither, "opacity": o.fill_opacity, "mode": o.gradient_blend_mode.label(), "target": paint_target(app)}), - ); - } + Tool::Gradient if (end[0] - d.start[0]).abs() + (end[1] - d.start[1]).abs() >= 2.0 => { + let o = app.ui.tool_options.clone(); + let _ = app.run( + "paint.gradient", + json!({"from": [d.start[0], d.start[1]], "to": [end[0], end[1]], "style": o.gradient_style, "reverse": o.gradient_reverse, "dither": o.gradient_dither, "opacity": o.fill_opacity, "mode": o.gradient_blend_mode.label(), "target": paint_target(app)}), + ); } Tool::Move => { let (dx, dy) = ((end[0] - d.start[0]).round(), (end[1] - d.start[1]).round()); @@ -6015,6 +6184,8 @@ pub fn commit_crop(app: &mut PhotocraftApp) { crate::crop_ui::cancel_stale(app); // Committing ends the box's own Undo/Redo: from here Edit › Undo reverts the document. crate::crop_ui::clear_history(app); + // ↵ during a drag ends it: the release must not bring back the old document's frame. + app.crop.drag = None; let Some(r) = app.ui.crop_rect.take() else { return }; // The crop's default mode leaves the view upright (`crop_mode`). crate::crop_mode::upright(app); @@ -6131,6 +6302,79 @@ mod tests { assert_eq!(super::display_image(Some(&d), &buf).pixels, reference(d.to_rgba8(&buf)).pixels); } + /// #7490: the inline (web) preview path composites and uploads each changed preview once, as + /// the background worker does. It used to flatten and upload it twice and record it twice, + /// so the frame's refresh time counted the preview twice. + #[test] + fn inline_filter_preview_is_composited_and_recorded_once() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); + crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); + app.perf.frame_refresh_ms = 0.0; + let (_, _, size) = ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("a preview"); + assert_eq!(size, [320, 240]); + assert_eq!(app.perf.last_refresh, "filter-preview"); + assert_eq!(app.perf.last_refresh_px, 320 * 240); + assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms, "one record per preview"); + // Unchanged request: nothing is recomputed or recorded again. + ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("the same preview"); + assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms); + } + + /// #6326: a filter's live preview is never coarser than the screen. On a document big enough + /// for a reduced proxy, the view at 100 % previews at full resolution, and only a view zoomed + /// out far enough uses the proxy. Through `ensure_filter_preview`, so the factor the canvas + /// actually requests is the one under test. + #[test] + fn filter_preview_at_100_percent_is_full_resolution() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 2400, "height": 2200})).unwrap(); + assert_eq!(crate::proxy::preview_factor(&app.session.active().unwrap().doc, true), 2, "big enough for a proxy"); + crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); + let ctx = egui::Context::default(); + let preview_at = |app: &mut PhotocraftApp, zoom: f32| { + app.ui.views.get_mut(0).expect("the new document's view").zoom = zoom; + assert_eq!(app.current_zoom(), zoom); + let (k, _, size) = ensure_filter_preview(app, 0, &ctx).expect("a preview"); + (k, size) + }; + assert_eq!(preview_at(&mut app, 1.0), (1, [2400, 2200]), "100 %: every pixel"); + assert_eq!(preview_at(&mut app, 0.25), (2, [1200, 1100]), "zoomed out: the document's proxy"); + // Low Resolution Previews off: full resolution at any zoom, exactly as before #6326. + app.run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": false})).unwrap(); + assert_eq!(preview_at(&mut app, 0.25), (1, [2400, 2200]), "the preference still decides"); + } + + /// The factor itself over the zoom range, and that Preferences › Performance › Low + /// Resolution Previews still decides whether there is a proxy at all (#6326). + #[test] + fn filter_preview_factor_caps_at_the_view_without_overriding_the_preference() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + // 9 MP: reduced previews halve it (empty tiles, so nothing is allocated). + app.run("file.new", json!({"width": 3000, "height": 3000, "background": "transparent"})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let params = json!({"amount": 100, "radius": 4.0, "threshold": 0}); + let k = |app: &mut PhotocraftApp, zoom: f32| { + app.ui.views.get_mut(0).expect("the new document's view").zoom = zoom; + super::filter_preview_factor(app, &doc, "filter.sharpen.unsharpMask", ¶ms) + }; + assert_eq!(k(&mut app, 0.25), 2, "zoomed out the preview stays reduced"); + assert_eq!(k(&mut app, 0.5), 2); + assert_eq!(k(&mut app, 0.75), 1, "past the proxy's resolution it shows every pixel"); + assert_eq!(k(&mut app, 1.0), 1); + assert_eq!(k(&mut app, 4.0), 1); + // A corrupt or unset zoom must not pick a coarser proxy than the document's own. + assert_eq!(k(&mut app, f32::NAN), 1); + assert_eq!(k(&mut app, 0.0), 1); + // Low Resolution Previews off: full resolution at any zoom, the cap a no-op. + app.run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": false})).unwrap(); + for zoom in [0.1, 0.25, 1.0, 4.0] { + assert_eq!(k(&mut app, zoom), 1, "zoom {zoom}"); + } + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() { @@ -6229,13 +6473,21 @@ mod tests { app.filter_preview_worker .start(key.clone(), ctx.clone(), move |_| { wait.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job"); - let result = - crate::filter_dialog::preview_document_for_target(&doc, key.active, &key.command, &key.params, key.k, None, key.target, &documents).map( - |d| { - let buffer = photocraft_compose::flatten(&d); - (std::sync::Arc::new(d), buffer) - }, - ); + let result = crate::filter_dialog::preview_document_for_target( + &doc, + key.active, + &key.command, + &key.params, + key.k, + None, + key.target, + &documents, + &Default::default(), + ) + .map(|d| { + let buffer = photocraft_compose::flatten(&d); + (std::sync::Arc::new(d), buffer) + }); crate::filter_preview_worker::Computed { result, ms: 0.0 } }) .expect("the worker starts"); @@ -7082,6 +7334,33 @@ mod tests { assert!(hint.ends_with(&format!("paste a copied image with {}.", crate::notices::paste_hint(&wayland))), "{hint}"); } + /// A tiling window manager can hand PhotoCraft a canvas narrower than the Home card (460 + /// points): the two buttons must stay inside the window instead of being clipped at its edges. + #[test] + fn start_screen_buttons_stay_inside_a_narrow_canvas() { + use egui_kittest::kittest::Queryable; + for width in [390.0, 420.0, 520.0] { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(width, 760.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.state_mut().1 = true; + h.run_steps(3); + for label in ["New document", "Join us on Discord"] { + for node in h.query_all_by_label_contains(label) { + let r = node.rect(); + assert!(r.left() >= 0.0 && r.right() <= width, "`{label}` is clipped in a {width}-point-wide canvas: {r:?}"); + } + } + } + } + /// #4382: Interface › Show home recent files off hides the Home screen's list, not the recents. #[test] fn home_recent_list_hides_when_the_preference_is_off() { @@ -8611,6 +8890,64 @@ mod rotation_preview_isolation_tests { } } + /// Assign and Convert to Profile have Photoshop's Preview. Assign changes only the profile, so + /// its preview must be shown through the profile it assigns (through the document's own it + /// looked unchanged); Convert keeps the look of in-gamut colours. Their `working` is the + /// working space from Color Settings, not the built-in default. + #[test] + fn profile_dialogs_preview_through_the_profile_they_choose() { + let mut session = photocraft_engine::Session::new(); + session.color.settings.monitor_profile = "srgb".into(); + session.color.settings.working_rgb = "display-p3".into(); + session.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + session.execute("edit.assignProfile", json!({"profile": "srgb"})).unwrap(); + session + .edit("Fixture", |doc, _| { + let layer = doc.layers.last_mut().unwrap(); + for y in 0..4 { + for x in 0..4 { + layer.surface_mut().unwrap().write_pixel(x, y, &[0.6, 0.35, 0.25, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let shown_pixels = |app: &PhotocraftApp, doc: &Document| { + let (display, _) = canvas_display(app, doc, None); + display_image(display.as_deref(), &photocraft_compose::flatten(doc)).pixels[0] + }; + let original = app.session.active().unwrap().doc.clone(); + let before = shown_pixels(&app, &original); + let preview = |app: &mut PhotocraftApp, command: &str, profile: &str| { + crate::filter_dialog::open(app, command).unwrap(); + let fields = &mut app.ui.dialogs.last_mut().unwrap().fields; + assert_eq!(fields.get("__preview"), Some(&json!(true)), "{command} has a Preview checkbox, on"); + fields.insert("profile".into(), json!(profile)); + ensure_filter_preview(app, 0, &egui::Context::default()).expect("a preview"); + let result = app.filter_preview.as_ref().unwrap().result.clone().unwrap(); + let key = original.id.0 ^ (1u64 << 61); + assert_eq!(filter_preview_display_doc(app, &original, key).icc_profile, result.icc_profile, "the canvas shows it through its own profile"); + assert_eq!(app.session.active().unwrap().doc.icc_profile, original.icc_profile, "previewing changes nothing"); + app.ui.dialogs.clear(); + app.filter_preview = None; + result + }; + let description = |doc: &Document| photocraft_engine::color_cmds::profile_from_bytes(doc.icc_profile.as_ref().unwrap()).unwrap().description.clone(); + + let assigned = preview(&mut app, "edit.assignProfile", "prophoto-compat"); + assert_eq!(description(&assigned), photocraft_cms::Builtin::ProPhotoCompat.description()); + let shown = shown_pixels(&app, &assigned); + assert!(shown.r().abs_diff(before.r()) > 10 || shown.b().abs_diff(before.b()) > 10, "the assigned profile shows: {before:?} → {shown:?}"); + + let converted = preview(&mut app, "edit.convertToProfile", "working"); + assert_eq!(description(&converted), photocraft_cms::Builtin::DisplayP3.description(), "`working` is Color Settings' working space"); + let shown = shown_pixels(&app, &converted); + for (a, b) in [(shown.r(), before.r()), (shown.g(), before.g()), (shown.b(), before.b())] { + assert!(a.abs_diff(b) <= 2, "converting keeps the look: {before:?} → {shown:?}"); + } + } + /// A CPU-only app must be able to generate the actual rotation preview without a /// GPU adapter; checking the result also verifies Preview off and document integrity. #[test] @@ -8655,3 +8992,7 @@ mod rotation_preview_isolation_tests { #[cfg(test)] #[path = "canvas_display_memo_tests.rs"] mod display_memo_tests; + +#[cfg(test)] +#[path = "canvas/blend_viewport_tests.rs"] +mod blend_viewport_regression; diff --git a/crates/ui-egui/src/canvas/blend_viewport_tests.rs b/crates/ui-egui/src/canvas/blend_viewport_tests.rs new file mode 100644 index 0000000000..ae6a01742d --- /dev/null +++ b/crates/ui-egui/src/canvas/blend_viewport_tests.rs @@ -0,0 +1,198 @@ +use super::*; +use photocraft_color::BlendMode; +use serde_json::json; + +fn render_state() -> Option { + match std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) { + Ok(rs) => Some(rs), + Err(error) => { + if std::env::var_os("PHOTOCRAFT_REQUIRE_GPU_TESTS").is_some() { + std::panic::resume_unwind(error); + } + eprintln!("skipping blend viewport regression: no GPU adapter"); + None + } + } +} + +#[test] +fn blend_hover_refresh_is_limited_to_visible_canvas() { + check_blend_viewport(false, false); +} + +#[test] +fn blend_hover_cpu_fallback_refresh_tracks_visible_canvas() { + check_blend_viewport(true, false); +} + +#[test] +fn blend_hover_multiple_layers_tracks_visible_canvas() { + check_blend_viewport(false, true); +} + +#[test] +fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() { + let _guard = photocraft_testkit::gpu_lock(); + let Some(rs) = render_state() else { return }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.set_wgpu(rs); + app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap(); + let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); + let ctx = egui::Context::default(); + let a = DRect::new(724, 200, 1324, 500); + let b = DRect::new(0, 200, 300, 500); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + app.ui.view.pattern_preview = true; + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply)); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert_visible_pixels(&mut app, b); + let bounds = app.session.active().unwrap().doc.bounds(); + assert_visible_pixels(&mut app, bounds); + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert_visible_pixels(&mut app, bounds); + + app.ui.view.pattern_preview = false; + for mode in [BlendMode::Multiply, BlendMode::Screen] { + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(mode)); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert!(ensure_gpu(&mut app, &ctx, 0, b)); + for visible in [a, b, a, b] { + app.perf.last_refresh_px = 0; + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_eq!(app.perf.last_refresh_px, 0, "unchanged views must retain coverage together"); + assert_visible_pixels(&mut app, visible.intersect(&bounds)); + } + } + // Enabling periodic display during an existing hover must catch up the unseen gap too. + app.ui.view.pattern_preview = true; + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert_visible_pixels(&mut app, bounds); + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert_visible_pixels(&mut app, bounds); +} + +#[test] +fn blend_hover_during_background_redraw_restores_committed_pixels() { + let _guard = photocraft_testkit::gpu_lock(); + let Some(rs) = render_state() else { return }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.set_wgpu(rs); + app.background_jobs = true; + app.run("file.new", json!({"width":2600,"height":1700,"background":"#336699"})).unwrap(); + let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); + app.run("layer.layerStyle.blendingOptions", json!({"knockout":"shallow"})).unwrap(); + let ctx = egui::Context::default(); + let visible = DRect::new(256, 256, 512, 512); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert!(!app.redraws.is_empty(), "fixture must start a deferred full redraw"); + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply)); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + let panned = DRect::new(2048, 1024, 2304, 1280); + assert!(ensure_gpu(&mut app, &ctx, 0, panned)); + settle_redraw(&mut app); + assert_visible_pixels(&mut app, panned); + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); + assert!(ensure_gpu(&mut app, &ctx, 0, panned)); + settle_redraw(&mut app); + let bounds = app.session.active().unwrap().doc.bounds(); + assert_visible_pixels(&mut app, bounds); +} + +fn settle_redraw(app: &mut PhotocraftApp) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + let gpu = app.gpu.clone().unwrap(); + let id = app.session.active().unwrap().doc.id; + while !app.redraws.is_empty() { + crate::background_redraw::poll(app, &gpu, id); + assert!(std::time::Instant::now() < deadline, "background redraw did not finish"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } +} + +fn assert_visible_pixels(app: &mut PhotocraftApp, visible: DRect) { + let (doc, _) = display_doc(app, 0); + let gpu = app.gpu.clone().unwrap(); + let reference = doc.id.0 ^ (1u64 << 60); + let (display, _) = canvas_display(app, &doc, None); + gpu.upload_composite(reference, &doc, display.as_deref()); + let (_, size, shown) = gpu.read_texels(doc.id.0).unwrap(); + let (_, _, want) = gpu.read_texels(reference).unwrap(); + for y in visible.y0..visible.y1 { + for x in visible.x0..visible.x1 { + let index = y as usize * size[0] as usize + x as usize; + for channel in 0..4 { + assert!((shown[index][channel] - want[index][channel]).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel{channel}"); + } + } + } +} + +fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { + let _guard = photocraft_testkit::gpu_lock(); + let Some(rs) = render_state() else { return }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.set_wgpu(rs); + app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap(); + let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); + if cpu_fallback { + app.run("layer.layerStyle.blendingOptions", json!({"knockout":"shallow"})).unwrap(); + } + let mut layers = vec![photocraft_doc::LayerId(layer)]; + if multiple_layers { + let other = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + app.run("edit.fill", json!({"color": "#4488cc"})).unwrap(); + app.run("layer.setProps", json!({"layer": other, "opacity": 0.5})).unwrap(); + layers.push(photocraft_doc::LayerId(other)); + } + let ctx = egui::Context::default(); + let visible = DRect::new(256, 256, 512, 512); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert!(app.redraws.is_empty(), "small fixture must finish synchronously"); + if cpu_fallback { + assert!(!app.perf.last_refresh.starts_with("gpu"), "fixture must exercise CPU composition fallback"); + } + let id = app.session.active().unwrap().doc.id; + let gpu = app.gpu.clone().unwrap(); + let original = gpu.read_texels(id.0).unwrap(); + crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Multiply)); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 256 * 256, app.perf.gpu_info); + assert_eq!(app.perf.last_refresh_px, 256 * 256, "hover must not recomposite offscreen pixels of a full-canvas layer"); + assert_visible_pixels(&mut app, visible); + app.perf.last_refresh_px = 0; + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_eq!(app.perf.last_refresh_px, 0, "unchanged view and mode must reuse the texture"); + let zoomed_out = DRect::new(128, 128, 640, 640); + assert!(ensure_gpu(&mut app, &ctx, 0, zoomed_out)); + assert_eq!(app.perf.last_refresh_px, 512 * 512, "zooming out catches up the larger visible area"); + let panned = DRect::new(640, 256, 896, 512); + assert!(ensure_gpu(&mut app, &ctx, 0, panned)); + assert_eq!(app.perf.last_refresh_px, 256 * 256, "newly exposed pixels must catch up without a mode change"); + crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Screen)); + assert!(ensure_gpu(&mut app, &ctx, 0, panned)); + assert_eq!(app.perf.last_refresh_px, 256 * 256); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_eq!(app.perf.last_refresh_px, 256 * 256, "returning view must show the current mode"); + assert_visible_pixels(&mut app, visible); + assert_visible_pixels(&mut app, panned); + crate::blend_preview::hover(&mut app, &layers, None); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_eq!(gpu.read_texels(id.0).unwrap(), original, "cancel must restore the whole texture, including previously previewed offscreen pixels"); + crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Multiply)); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + app.run("layer.setProps", json!({"layer":layer,"blend":"Multiply"})).unwrap(); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + let bounds = app.session.active().unwrap().doc.bounds(); + assert_visible_pixels(&mut app, bounds); + app.run("file.new", json!({"width":1024,"height":768,"background":"white"})).unwrap(); + assert!(ensure_gpu(&mut app, &ctx, 1, visible)); + app.session.set_active(0); + app.sync_views(); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_visible_pixels(&mut app, bounds); +} diff --git a/crates/ui-egui/src/canvas/tabs_tests.rs b/crates/ui-egui/src/canvas/tabs_tests.rs index 4cc2bca0f0..42f5c58d8e 100644 --- a/crates/ui-egui/src/canvas/tabs_tests.rs +++ b/crates/ui-egui/src/canvas/tabs_tests.rs @@ -1,5 +1,6 @@ -//! #1276: a document tab strip with more tabs than fit keeps the active document's tab on the -//! strip, shrinks and elides the others, and moves the rest into a » menu (whole app, real tree). +//! #1276, #4487: a document tab strip with more tabs than fit keeps the active document's tab on +//! the strip, keeps whole titles on the tabs it shows, and moves the rest into a » menu (whole +//! app, real tree). use egui::vec2; use egui_kittest::Harness; @@ -166,3 +167,60 @@ fn ctrl_tab_with_one_document_or_a_focused_field() { } assert!(!Focus::Widget.allows(&crate::shortcuts::parse("Tab").unwrap()), "a focused widget keeps plain Tab"); } + +#[test] +fn quick_mask_mode_names_the_quick_mask_in_the_tab() { + let mut h = harness(1, ThemeKind::Pro); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + assert_eq!(pro_tab_title(h.state(), 0), "ch1-p01.png @ 100% (Layer 1, RGB/8)*"); + h.state_mut().run("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + assert_eq!(pro_tab_title(h.state(), 0), "ch1-p01.png @ 100% (Quick Mask/8)*"); + h.state_mut().run("select.editInQuickMaskMode", json!({"on": false})).unwrap(); + assert_eq!(pro_tab_title(h.state(), 0), "ch1-p01.png @ 100% (Layer 1, RGB/8)*"); +} + +/// Whether any title painted on the strip was cut with '…'. +fn elided_on_strip(h: &Harness<'_, PhotocraftApp>) -> bool { + fn elided(shape: &egui::Shape, strip: egui::Rect) -> bool { + match shape { + egui::Shape::Text(text) => text.galley.elided && strip.intersects(text.visual_bounding_rect()), + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| elided(shape, strip)), + _ => false, + } + } + let strip = strip(h).rect; + h.output().shapes.iter().any(|shape| elided(&shape.shape, strip)) +} + +/// #4487: a crowded strip keeps whole names on the tabs it shows and moves the rest into the » +/// menu instead of shrinking them all, and the menu lists every open document with the active one +/// checked, as Photoshop's does. +#[test] +fn crowded_tabs_keep_their_whole_names_and_the_menu_lists_every_document() { + for theme in [ThemeKind::Pro, ThemeKind::Studio] { + let mut h = harness(14, theme); + let s = strip(&h); + assert!(s.tabs.len() > 1 && s.tabs.len() < 14, "{theme:?}: {} shown", s.tabs.len()); + assert!(!elided_on_strip(&h), "{theme:?}: no tab title is cut"); + // The last new document is active; then one that was behind the menu, then the first. + for active in [13, 5, 0] { + h.state_mut().session.set_active(active); + h.run_steps(2); + let pro = crate::theme::Tokens::get(&h.ctx).pro; + let labels: Vec = + (0..14).map(|i| if pro { pro_tab_title(h.state(), i) } else { h.state().session.documents()[i].doc.name.clone() }).collect(); + h.get_by_label("More documents").click(); + h.run_steps(2); + for (i, label) in labels.iter().enumerate() { + // The menu bar's padding: an unchecked row keeps the check mark's room, so names line up. + let (on, off) = (format!("✔ {label}"), format!(" {label}")); + let (want, other) = if i == active { (&on, &off) } else { (&off, &on) }; + assert_eq!(h.query_all_by_label(want).count(), 1, "{theme:?}, active {active}: document {i} is in the menu as {want:?}"); + assert_eq!(h.query_all_by_label(other).count(), 0, "{theme:?}, active {active}: document {i} is not {other:?}"); + } + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.query_by_label(&format!("✔ {}", labels[active])).is_none(), "{theme:?}: the menu closed"); + } + } +} diff --git a/crates/ui-egui/src/canvas_menu_tests.rs b/crates/ui-egui/src/canvas_menu_tests.rs index f1bbbe8d0c..839dc1f765 100644 --- a/crates/ui-egui/src/canvas_menu_tests.rs +++ b/crates/ui-egui/src/canvas_menu_tests.rs @@ -248,6 +248,22 @@ fn control_channel_opening_uses_the_same_dismissal_guard() { } } +/// #7324: an agent's right-click on committed type opens the type layer menu, as on the canvas. +#[test] +fn control_channel_right_click_on_committed_type_opens_the_type_layer_menu() { + let mut h = harness(Tool::Type, false, 1.0); + h.state_mut().run("type.create", json!({"text": "Hello", "size": 72, "x": 100, "y": 180})).unwrap(); + h.run_steps(3); + let at = fractional_point(&h, 1.0); + let before = document_state(&h); + control_tap(&mut h, at, Popup::Tool); + let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); + assert!(menu.type_layer && !menu.text); + assert!(h.state().ui.text_edit.is_none()); + // The new type is already the active layer, so the menu selects nothing either. + assert!(document_state(&h) == before, "opening the menu changes nothing"); +} + #[test] fn brush_picker_taps_preserve_pixels_selection_and_history_after_reopening() { for tool in [Tool::Brush, Tool::Eraser, Tool::QuickSelection] { diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rs index da835a786f..43418d5ff9 100644 --- a/crates/ui-egui/src/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas_tool_menu.rs @@ -1,5 +1,6 @@ //! Canvas context menus for the selection tools, the Pen, the Zoom and Hand tools, an active Free -//! Transform box, text being edited with a Type tool, the pasteboard (outside the image) and a guide. +//! Transform box, text being edited with a Type tool, committed type under a Type tool, the +//! pasteboard (outside the image) and a guide. use egui::Context; use photocraft_doc::LayerContent; @@ -31,6 +32,9 @@ pub struct CanvasToolMenu { /// Opened while a Type tool edits text: the text and type rows instead of the tool's actions. #[serde(default)] pub text: bool, + /// Opened with a Type tool over committed type (no edit running): the type layer rows. + #[serde(default)] + pub type_layer: bool, /// Opened on a guide: the guide menu (`guide_select`) instead of the tool's actions. #[serde(default)] pub guide: bool, @@ -137,6 +141,33 @@ pub const TYPE_EDIT_MENU: &[Row] = &[ Some(("Warp Text…", "type.warpText")), ]; +/// Right-click with a Type tool over type that isn't being edited (#7324): the type edit menu's +/// layer rows. Its edit rows would act on the document instead of the text, and Faux Bold/Italic +/// on characters being edited, so they are left out. +pub const TYPE_LAYER_MENU: &[Row] = &[ + Some(("Check Spelling…", "edit.checkSpelling")), + Some(("Find and Replace Text…", "edit.findAndReplaceText")), + None, + Some(("Rasterize Type", "type.rasterizeTypeLayer")), + Some(("Create Work Path", "type.createWorkPath")), + Some(("Convert to Shape", "type.convertToShape")), + None, + Some(("Horizontal", "type.orientation.horizontal")), + Some(("Vertical", "type.orientation.vertical")), + None, + Some(("None", "type.antiAlias.none")), + Some(("Sharp", "type.antiAlias.sharp")), + Some(("Crisp", "type.antiAlias.crisp")), + Some(("Strong", "type.antiAlias.strong")), + Some(("Smooth", "type.antiAlias.smooth")), + Some(("Windows LCD", "type.antiAlias.windowsLcd")), + Some(("Windows", "type.antiAlias.windows")), + None, + Some(("Convert to Paragraph Text", "type.convertToParagraphText")), + Some(("Convert to Point Text", "type.convertToPointText")), + Some(("Warp Text…", "type.warpText")), +]; + /// The type edit menu's Faux Bold and Faux Italic rows. pub const FAUX_BOLD: &str = "type.fauxBold"; pub const FAUX_ITALIC: &str = "type.fauxItalic"; @@ -284,8 +315,14 @@ pub fn applies(tool: Tool) -> bool { | Tool::MagneticLasso | Tool::MagicWand | Tool::ObjectSelection - | Tool::Pen - ) + ) || path_menu(tool) +} + +/// Tools whose canvas right-click opens the path menu ([`PEN_MENU`]): the Pen, and the Path +/// Selection and Direct Selection tools, whose Photoshop menu offers the same whole-path actions +/// for the selected path (#1056). +pub fn path_menu(tool: Tool) -> bool { + matches!(tool, Tool::Pen | Tool::PathSelection | Tool::DirectSelection) } /// Tools whose plain canvas right-click offers the view menu. @@ -310,7 +347,9 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { VIEW_MENU } else if menu.text { TYPE_EDIT_MENU - } else if menu.tool == Tool::Pen { + } else if menu.type_layer { + TYPE_LAYER_MENU + } else if path_menu(menu.tool) { PEN_MENU } else { selection_rows(menu.has_selection) @@ -332,7 +371,7 @@ pub(crate) fn mode_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: if menu.pasteboard { return pasteboard_choice(command) == Some(app.session.prefs().interface.canvas_color); } - if menu.text { + if menu.text || menu.type_layer { return type_checked(app, command); } menu.transform @@ -358,6 +397,32 @@ pub fn editing_text(app: &PhotocraftApp, tool: Tool) -> bool { tool.is_type() && app.ui.text_edit.is_some() } +/// The committed type layer under document point `doc` when a right-click there with a Type tool +/// opens the type layer menu (#7324). The Type Mask tools are left out: to them existing type is +/// just pixels. +pub fn type_layer_at(app: &mut PhotocraftApp, tool: Tool, doc: [f64; 2]) -> Option { + if !tool.is_type() || tool.is_type_mask() || app.ui.text_edit.is_some() || !doc.iter().all(|v| v.is_finite()) { + return None; + } + crate::type_tool::hit_layer(app, doc[0], doc[1]) +} + +/// Make the right-clicked type layer `id` the active layer, which the structural rows (Rasterize +/// Type, Convert to Shape…) act on and the checks show. Inside a multiselection the selection stays, +/// so the formatting rows still act on every selected type layer, as the Type menu's do; outside it +/// the type replaces the selection, as a click with the Type tool does. +fn target_type_layer(app: &mut PhotocraftApp, id: photocraft_doc::LayerId) -> bool { + let Some(st) = app.session.active() else { return false }; + let selected = st.selected_layers(); + if st.active_layer == Some(id) { + true + } else if selected.contains(&id) { + photocraft_engine::layer_multi_cmds::set_selection(&mut app.session, selected, Some(id), Some(id)).is_ok() + } else { + app.session.select_layer(id).is_ok() + } +} + /// The misspelled word of the edited text under document point `doc`, with its suggestions. fn spelling_at(app: &mut PhotocraftApp, doc: [f64; 2]) -> Option { let layer = app.ui.text_edit.as_ref()?.layer; @@ -418,6 +483,7 @@ pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) -> pasteboard: false, anchor: None, text: false, + type_layer: false, guide: false, spelling: None, }); @@ -471,7 +537,7 @@ pub fn pasteboard_at(app: &PhotocraftApp, tool: Tool, doc: [f64; 2]) -> bool { let Some(st) = app.session.active() else { return false }; let (w, h) = (f64::from(st.doc.size.width), f64::from(st.doc.size.height)); let outside = doc.iter().all(|v| v.is_finite()) && (doc[0] < 0.0 || doc[1] < 0.0 || doc[0] >= w || doc[1] >= h); - outside && tool != Tool::Pen && !crate::paint_mouse::has_brush_picker(tool) && !crate::paint_mouse::right_erases(app, tool) && app.ui.text_edit.is_none() + outside && !path_menu(tool) && !crate::paint_mouse::has_brush_picker(tool) && !crate::paint_mouse::right_erases(app, tool) && app.ui.text_edit.is_none() } /// Right-click on the pasteboard: its colour menu at screen point `pos`. @@ -491,6 +557,7 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: pasteboard: true, anchor: None, text: false, + type_layer: false, guide: false, spelling: None, }); @@ -499,7 +566,8 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: } /// Right-click at document point `doc` on a guide that `tool` could drag (the Move tool, or ⌘ with -/// a selection tool): select the guide and open the guide menu at screen point `pos`. +/// a tool on which ⌘ moves guides, `canvas::command_guide_at`): select the guide and open the guide +/// menu at screen point `pos`. pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui::Modifiers, pos: [f32; 2], doc: [f64; 2]) -> bool { if !pos.iter().all(|v| v.is_finite()) || !doc.iter().all(|v| v.is_finite()) { return false; @@ -519,6 +587,7 @@ pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui pasteboard: false, anchor: None, text: false, + type_layer: false, guide: true, spelling: None, }); @@ -572,7 +641,10 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) c => TYPE_EDIT_MENU.iter().flatten().any(|(_, id)| *id == c) && crate::menus::is_enabled(app, c), }; } - if menu.transform || menu.tool != Tool::Pen { + if menu.type_layer { + return TYPE_LAYER_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command); + } + if menu.transform || !path_menu(menu.tool) { return crate::menus::is_enabled(app, command); } let Some(st) = app.session.active() else { return false }; @@ -615,10 +687,15 @@ pub fn open(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]) - } /// [`open`] for a right-click at document point `doc`: over a misspelled word of the text being -/// edited, the menu starts with its spelling suggestions. +/// edited, the menu starts with its spelling suggestions; over committed type with a Type tool, the +/// type layer menu. pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2], doc: Option<[f64; 2]>) -> bool { let text = editing_text(app, tool); - if !(applies(tool) || text) || !pos.iter().all(|v| v.is_finite()) { + if !pos.iter().all(|v| v.is_finite()) { + return false; + } + let type_layer = !text && doc.and_then(|d| type_layer_at(app, tool, d)).is_some_and(|id| target_type_layer(app, id)); + if !(applies(tool) || text || type_layer) { return false; } app.ui.brush_picker = None; @@ -627,8 +704,20 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] let has_path = crate::vector_ui::active_path_name(app).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); let path_name = crate::vector_ui::active_path_name(app); let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None }; - app.ui.canvas_tool_menu = - Some(CanvasToolMenu { pos, tool, has_selection, has_path, path_name, transform: false, pasteboard: false, anchor: None, text, guide: false, spelling }); + app.ui.canvas_tool_menu = Some(CanvasToolMenu { + pos, + tool, + has_selection, + has_path, + path_name, + transform: false, + pasteboard: false, + anchor: None, + text, + type_layer, + guide: false, + spelling, + }); crate::canvas_popup::mark_open(ctx, menu_id()); true } @@ -651,6 +740,7 @@ pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; pasteboard: false, anchor: Some(doc), text: false, + type_layer: false, guide: false, spelling: None, }); @@ -697,9 +787,9 @@ pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { choose_view(app, ctx, &menu, command) } else if menu.text && is_spelling(&menu, command) { choose_spelling(app, &menu, command) - } else if menu.text { + } else if menu.text || menu.type_layer { choose_type(app, ctx, command) - } else if menu.tool == Tool::Pen && !menu.transform { + } else if path_menu(menu.tool) && !menu.transform { choose_pen(app, ctx, &menu, command) } else if command == "select.toWorkPath" { // Photoshop's Make Work Path… asks for the tolerance first. @@ -834,6 +924,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { || app.ui.tool != menu.tool || (menu.transform && app.ui.transform.is_none()) || (menu.text && app.ui.text_edit.is_none()) + || (menu.type_layer && app.ui.text_edit.is_some()) { app.ui.canvas_tool_menu = None; return; @@ -1049,6 +1140,91 @@ mod tests { assert!(app.ui.text_edit.is_none() && text_of(&app, id).is_none(), "the type layer is pixels now"); } + /// A committed type layer reading "Hello" over the middle of the canvas, no edit running. + fn committed_type(app: &mut PhotocraftApp) -> u64 { + app.ui.tool = Tool::Type; + let id = app.run("type.create", json!({"text": "Hello", "size": 14, "x": 1, "y": 22})).unwrap()["layer"].as_u64().unwrap(); + assert!(app.ui.text_edit.is_none()); + id + } + + #[test] + fn right_click_on_committed_type_opens_the_type_layer_menu() { + use photocraft_doc::text::Orientation; + let mut app = app(); + let id = committed_type(&mut app); + assert_eq!(crate::type_tool::hit_layer(&mut app, 16.0, 16.0).map(|l| l.0), Some(id), "the canvas centre is on the type"); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on committed type opens a menu (#7324)"); + assert!(menu.type_layer && !menu.text && !menu.pasteboard); + assert_eq!(rows(&menu), TYPE_LAYER_MENU); + assert!(h.state().ui.text_edit.is_none(), "the right-click doesn't start an edit"); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the menu stays open without an edit"); + // An edit started some other way (here, as an agent's Type › Edit Text would) closes the + // menu, which has no text edit rows. + crate::menus::invoke(h.state_mut(), &Context::default(), "type.editText", json!({})).unwrap(); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "an edit closes the type layer menu"); + crate::type_tool::commit(h.state_mut()); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("committed again, the menu opens again"); + assert!(menu.type_layer && mode_checked(h.state(), &menu, "type.orientation.horizontal")); + choose(h.state_mut(), &Context::default(), "type.orientation.vertical"); + assert_eq!(text_of(h.state(), id).unwrap().orientation, Orientation::Vertical); + } + + #[test] + fn type_layer_menu_targets_the_type_under_the_pointer() { + let mut app = app(); + let id = committed_type(&mut app); + app.run("layer.new.layer", json!({})).unwrap(); + let ctx = Context::default(); + let active = |app: &PhotocraftApp| app.session.active().unwrap().active_layer.map(|l| l.0); + assert_ne!(active(&app), Some(id)); + // Away from the type, or with a Type Mask tool, nothing opens and nothing is selected. + assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([30.0, 2.0]))); + assert!(!open_at(&mut app, &ctx, Tool::HorizontalTypeMask, [10.0, 10.0], Some([16.0, 16.0]))); + assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([f64::NAN, 16.0]))); + assert_ne!(active(&app), Some(id)); + // Over the type: its layer becomes the target, and the menu has no text edit rows. + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([16.0, 16.0]))); + assert_eq!(active(&app), Some(id)); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for edit_row in ["edit.undo", "edit.cut", "edit.copy", "edit.paste", "select.all", FAUX_BOLD, FAUX_ITALIC] { + assert!(!available(&app, &menu, edit_row), "{edit_row} belongs to the edit menu only"); + } + assert!(entry_enabled(&app, &menu, "type.convertToParagraphText") && !entry_enabled(&app, &menu, "type.convertToPointText")); + choose(&mut app, &ctx, "type.rasterizeTypeLayer"); + assert!(text_of(&app, id).is_none(), "the type layer is pixels now"); + assert!(app.ui.text_edit.is_none()); + } + + /// Two selected type layers: the one right-clicked becomes active, and the selection stays. + #[test] + fn type_layer_menu_in_a_multiselection_acts_on_the_clicked_type() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.ui.tool = Tool::Type; + let top = app.run("type.create", json!({"text": "Top", "size": 30, "x": 10, "y": 40})).unwrap()["layer"].as_u64().unwrap(); + let bottom = app.run("type.create", json!({"text": "Low", "size": 30, "x": 10, "y": 90})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.select", json!({"layer": bottom})).unwrap(); + app.run("layer.select", json!({"layer": top, "mode": "add"})).unwrap(); + let at = [25.0, 80.0]; + assert_eq!(crate::type_tool::hit_layer(&mut app, at[0], at[1]).map(|l| l.0), Some(bottom)); + assert_eq!(app.session.active().unwrap().active_layer.map(|l| l.0), Some(top)); + let ctx = Context::default(); + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some(at))); + let st = app.session.active().unwrap(); + assert_eq!(st.active_layer.map(|l| l.0), Some(bottom), "the clicked type is the target"); + assert_eq!(st.selected_layers().len(), 2, "the multiselection stays"); + choose(&mut app, &ctx, "type.rasterizeTypeLayer"); + assert!(text_of(&app, bottom).is_none(), "the clicked type is rasterized"); + assert!(text_of(&app, top).is_some(), "not the other selected type"); + } + #[test] fn type_edit_menu_lists_spelling_suggestions_for_the_word_under_the_pointer() { let mut app = app(); @@ -1492,6 +1668,32 @@ mod tests { assert!(app.session.active().unwrap().doc.selection.is_some()); } + /// #1056: the Path Selection and Direct Selection tools' right-click opens the path menu for + /// the selected path, as the Pen's does, instead of nothing. + #[test] + fn path_selection_tools_open_the_path_menu() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + crate::vector_ui::pen_commit(&mut app, false); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + app.ui.tool = tool; + assert!(applies(tool)); + assert!(open(&mut app, &Context::default(), tool, [10.0, 10.0]), "{tool:?}"); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert_eq!(rows(&menu), PEN_MENU, "{tool:?}"); + assert!(menu.has_path && entry_enabled(&app, &menu, "path.toSelection"), "{tool:?}"); + choose(&mut app, &Context::default(), "path.toSelection"); + let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_some(), "{tool:?}: Make Selection made one"); + } + } + #[test] fn pen_menu_has_all_reference_rows_in_order_and_guards_unavailable_actions() { let labels: Vec<_> = PEN_MENU.iter().map(|row| row.map(|(label, _)| label)).collect(); diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rs index 09a3ce8d4c..19272a62ed 100644 --- a/crates/ui-egui/src/color_picker_ui.rs +++ b/crates/ui-egui/src/color_picker_ui.rs @@ -171,7 +171,7 @@ pub fn open(app: &mut PhotocraftApp, target: &str) -> u64 { let c = if target == "background" { app.session.tools.background } else { app.session.tools.foreground }; let rgb = [c[0], c[1], c[2]]; let label = if target == "background" { "Color Picker (Background Color)" } else { "Color Picker (Foreground Color)" }; - let mut fields = initial_fields(target, label, rgb); + let mut fields = fields_with_web(app, target, label, rgb); // A colour that was picked as CMYK shows the inks it was picked as, not what its sRGB stand-in converts to (#4196). if let Some(cmyk) = app.session.tools.picked_cmyk(rgb) { fields.insert("__cmyk".into(), json!(cmyk)); @@ -192,10 +192,23 @@ pub(crate) fn initial_fields(target: &str, label: &str, rgb: [f32; 3]) -> Map Map { + let mut f = initial_fields(target, label, rgb); + f.insert("__webOnly".into(), json!(app.ui.color_panel.web_only)); + if app.ui.color_panel.web_only { + set_rgb(&mut f, rgb, Keep::Nothing); + f.insert("__orig".into(), f["color"].clone()); + } + f +} + /// Open the picker on `rgb` for something other than the tool colours: OK runs `command` with /// `params` plus `"color": "#rrggbb"` (e.g. a gradient stop's colour). pub fn open_for_command(app: &mut PhotocraftApp, label: &str, rgb: [f32; 3], command: &str, params: Value) -> u64 { - let mut f = initial_fields("command", label, rgb); + let mut f = fields_with_web(app, "command", label, rgb); f.insert("__command".into(), json!(command)); f.insert("__params".into(), params); app.ui.open_dialog(DialogKind::Command, f) @@ -204,33 +217,16 @@ pub fn open_for_command(app: &mut PhotocraftApp, label: &str, rgb: [f32; 3], com /// Open the picker on `rgb` for a colour field of another dialog (e.g. Edit › Fill's Color…): OK /// writes `"#rrggbb"` into `field` of dialog `dialog`, which stays open; Cancel leaves it alone. pub fn open_for_field(app: &mut PhotocraftApp, label: &str, rgb: [f32; 3], dialog: u64, field: &str) -> u64 { - let hsv = rgb_to_hsv(rgb); - let mut f = Map::new(); - f.insert("__colorPicker".into(), json!("field")); - f.insert("__label".into(), json!(label)); + let mut f = fields_with_web(app, "field", label, rgb); f.insert("__dialog".into(), json!(dialog)); f.insert("__field".into(), json!(field)); - f.insert("color".into(), json!(hex(rgb))); - f.insert("__orig".into(), json!(hex(rgb))); - f.insert("__hsv".into(), json!(hsv)); - f.insert("__mode".into(), json!("h")); - f.insert("__webOnly".into(), json!(false)); app.ui.open_dialog(DialogKind::Command, f) } /// Open the picker on `rgb` for a colour the shell keeps itself (e.g. the Crop shield's custom /// colour): OK hands `"#rrggbb"` to `target`'s setter in [`confirm`]; Cancel leaves it alone. pub fn open_for_target(app: &mut PhotocraftApp, target: &str, label: &str, rgb: [f32; 3]) -> u64 { - let hsv = rgb_to_hsv(rgb); - let mut f = Map::new(); - f.insert("__colorPicker".into(), json!(target)); - f.insert("__label".into(), json!(label)); - f.insert("color".into(), json!(hex(rgb))); - f.insert("__orig".into(), json!(hex(rgb))); - f.insert("__hsv".into(), json!(hsv)); - f.insert("__mode".into(), json!("h")); - f.insert("__webOnly".into(), json!(false)); - app.ui.open_dialog(DialogKind::Command, f) + app.ui.open_dialog(DialogKind::Command, fields_with_web(app, target, label, rgb)) } /// Set by a dialog body (to the picker's title) to open the Color Picker on its `color` field. @@ -367,7 +363,7 @@ pub fn current(f: &Map) -> Components { fn set_rgb(f: &mut Map, rgb: [f32; 3], keep: Keep) { let web = f.get("__webOnly").and_then(Value::as_bool).unwrap_or(false); - let (rgb, keep) = if web { (rgb.map(|v| (v * 5.0).round() / 5.0), Keep::Nothing) } else { (rgb, keep) }; + let (rgb, keep) = if web { (web_safe(rgb), Keep::Nothing) } else { (rgb, keep) }; f.insert("color".into(), json!(hex(rgb))); for key in ["__hsv", "__lab", "__cmyk"] { f.remove(key); @@ -688,9 +684,14 @@ fn fields(ui: &mut egui::Ui, f: &mut Map, mode: &str, now: &Compo let focused = ui.memory(|m| m.has_focus(id)); let pasted = if focused { take_hex_paste(ui) } else { None }; let typing = if focused { ui.data(|d| d.get_temp::(id)) } else { None }; + // Drop stale typing when another path (web snap, field drag, Current) changed `color`. + let shown = hex(rgb); let mut h = match pasted { Some(c) => hex(c).trim_start_matches('#').to_ascii_uppercase(), - None => typing.unwrap_or_else(|| hex(rgb).trim_start_matches('#').to_ascii_uppercase()), + None => match typing { + Some(t) if parse_hex(&t).is_none() || parse_hex(&t).map(hex).as_deref() == Some(shown.as_str()) => t, + _ => shown.trim_start_matches('#').to_ascii_uppercase(), + }, }; let r = crate::widgets::text_field_ex(ui, id, &mut h, "", 64.0, true, Some(6)); if let Some(c) = pasted { @@ -783,6 +784,9 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result err("missing `path`"), }, - "app.save" => match crate::targa_options_ui::bits_param(p, "app.save") { - Ok(tga_bits) => { + "app.save" => match crate::FormatChoices::from_params(p, "app.save") { + Ok(choices) => { let path = s("path").map(str::to_string); - run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), move |app| app.save_automation_with(path, tga_bits)) + run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), move |app| app.save_automation_with(path, choices)) } Err(e) => err(e), }, @@ -2431,6 +2441,37 @@ mod tests { assert_eq!(written.borrow().len(), 3, "a bad tgaBits writes nothing"); } + /// `app.save` takes the DDS options (`ddsCompression`, `ddsMipmaps`) and never stops at DDS + /// Options. + #[test] + fn automation_save_passes_dds_options_without_asking() { + use photocraft_io::{DdsCompression, DdsOptions}; + use std::cell::RefCell; + use std::rc::Rc; + let asked: Rc>> = Rc::default(); + let a = asked.clone(); + let services = crate::Services { + export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| { + a.borrow_mut().push(s.dds); + Ok((b"out".to_vec(), Vec::new())) + })), + automation_write: Some(Box::new(|_: &str, _: &[u8]| Ok(()))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for params in [json!({"path": "a.dds"}), json!({"path": "b.dds", "ddsCompression": "bc1", "ddsMipmaps": true})] { + let r = call(&mut app, &ctx, "app.save", params.clone()); + assert_eq!(r["result"]["path"], params["path"], "{r}"); + assert!(app.dds_options.is_none(), "automation saves never prompt"); + } + assert_eq!(*asked.borrow(), [DdsOptions::default(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }]); + let r = call(&mut app, &ctx, "app.save", json!({"path": "c.dds", "ddsCompression": "bc9"})); + assert!(r["error"].as_str().unwrap().contains("ddsCompression"), "{r}"); + assert_eq!(asked.borrow().len(), 2, "a bad ddsCompression writes nothing"); + } + #[test] fn automation_open_and_save_use_the_roots_and_reply_with_warnings() { use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/ui-egui/src/crop_mode.rs b/crates/ui-egui/src/crop_mode.rs index 676c97dbec..a1264126bf 100644 --- a/crates/ui-egui/src/crop_mode.rs +++ b/crates/ui-egui/src/crop_mode.rs @@ -212,10 +212,11 @@ fn remap(p: [f64; 2], from: PressView, to: PressView, flip: bool) -> [f64; 2] { } /// A pointer point `p` the canvas mapped through the view as it is now, read in the press-time -/// view `press` (unchanged without one). +/// view `press` (unchanged without one, or while the view hasn't moved: the `f32` round trip +/// would nudge a click). pub fn to_press(app: &PhotocraftApp, press: Option, p: [f64; 2]) -> [f64; 2] { match (press, press_view(app)) { - (Some(press), Some(now)) => remap(p, now, press, app.ui.view.flip_horizontal), + (Some(press), Some(now)) if press != now => remap(p, now, press, app.ui.view.flip_horizontal), _ => p, } } @@ -239,7 +240,7 @@ pub fn control_point(app: &PhotocraftApp, p: [f64; 2]) -> [f64; 2] { _ => None, }; match (press, press_view(app)) { - (Some(press), Some(now)) if app.ui.tool == Tool::Crop => remap(p, press, now, app.ui.view.flip_horizontal), + (Some(press), Some(now)) if app.ui.tool == Tool::Crop && press != now => remap(p, press, now, app.ui.view.flip_horizontal), _ => p, } } @@ -452,6 +453,30 @@ mod tests { assert!(((c1[0] - c0[0]).hypot(c1[1] - c0[1]) - 30.0).abs() < 1e-3); } + /// A `ui.pointer` click (down and up at the same point, no move) changes nothing, upright or + /// turned: reading the point in the press view used to round it through `f32` and the view, + /// nudging the frame by a hair and pushing a box Undo step that undid nothing visible. + #[test] + fn a_ui_pointer_click_changes_nothing() { + let ctx = egui::Context::default(); + for deg in [0.0, -30.0, 41.5] { + let mut app = app(); + with_frame(&mut app); + app.ui.crop_angle = deg; + sync_frame(&mut app); + let (rect, angle) = (app.ui.crop_rect, app.ui.crop_angle); + // Inside the frame (moves the image) and outside it (turns the image). + for p in [[70.3, 50.7], [55.17, 41.9], [83.01, 59.33], [150.3, 50.7], [10.9, 90.1]] { + let ev = json!([{"kind": "down", "x": p[0], "y": p[1]}, {"kind": "up", "x": p[0], "y": p[1]}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": ev})); + let crate::control::Outcome::Done(v) = crate::control::handle(&mut app, &ctx, &req) else { panic!("ui.pointer didn't finish") }; + assert_eq!(v["ok"], true, "{v}"); + assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (rect, angle), "click at {p:?}, frame at {deg}°"); + assert_eq!(crate::crop_ui::is_enabled(&app, "edit.undo"), None, "click at {p:?}, frame at {deg}°: a box Undo step"); + } + } + } + #[test] fn the_readout_is_the_images_turn_clockwise_positive() { let mut app = app(); diff --git a/crates/ui-egui/src/crop_presets.rs b/crates/ui-egui/src/crop_presets.rs index e049fdfa8c..e30b0d1cfc 100644 --- a/crates/ui-egui/src/crop_presets.rs +++ b/crates/ui-egui/src/crop_presets.rs @@ -109,7 +109,7 @@ pub fn savable(o: &ToolOptions) -> Option<(Map, String)> { if !(a.is_finite() && b.is_finite() && a > 0.0 && b > 0.0) { return None; } - let name = format!("{} : {}", crate::widgets::fmt_num(a), crate::widgets::fmt_num(b)); + let name = format!("{} : {}", crop_size::fmt_ratio(a), crop_size::fmt_ratio(b)); let mut fields = Map::new(); fields.insert("crop_ratio".into(), json!(o.crop_ratio)); Some((fields, name)) diff --git a/crates/ui-egui/src/crop_size.rs b/crates/ui-egui/src/crop_size.rs index 28a6a0e12f..b30cdd8c4a 100644 --- a/crates/ui-egui/src/crop_size.rs +++ b/crates/ui-egui/src/crop_size.rs @@ -146,6 +146,14 @@ pub fn ratio(o: &ToolOptions, doc_dpi: f64) -> Option { Some(w / h).filter(|k| k.is_finite() && *k > 0.0) } +/// Decimals a custom ratio side keeps and shows: 1.414 : 1 (ISO A sizes) as in Photoshop (#6487). +pub const RATIO_DECIMALS: u32 = 3; + +/// A ratio side as stored in a `crop_ratio` key ("1.414", "16"). +pub fn fmt_ratio(v: f64) -> String { + crate::widgets::fmt_num_prec(v, RATIO_DECIMALS) +} + /// Editable W and H shown for a custom aspect ratio. An existing valid ratio is authoritative; /// when either side is zero, use the in-progress values retained in ToolOptions. pub fn custom_ratio_fields(o: &ToolOptions, doc_size: (f64, f64)) -> (f32, f32) { @@ -170,7 +178,7 @@ pub fn set_custom_ratio_fields(o: &mut ToolOptions, width: f32, height: f32) { o.crop_custom_ratio_width = width; o.crop_custom_ratio_height = height; if width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0 { - o.crop_ratio = format!("{}:{}", crate::widgets::fmt_num(f64::from(width)), crate::widgets::fmt_num(f64::from(height))); + o.crop_ratio = format!("{}:{}", fmt_ratio(f64::from(width)), fmt_ratio(f64::from(height))); } else { o.crop_ratio.clear(); } @@ -347,6 +355,15 @@ mod tests { assert_eq!(width / height, 4.0 / 3.0); } + #[test] + fn custom_ratio_keeps_three_decimals() { + // #6487: 1.414 : 1 (ISO A sizes) stays 1.414, not 1.4, as in Photoshop. + let mut options = ToolOptions::default(); + set_custom_ratio_fields(&mut options, 1.414, 1.0); + assert_eq!(options.crop_ratio, "1.414:1"); + assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (1.414, 1.0)); + } + #[test] fn selecting_free_ratio_clears_previous_custom_dimensions() { let mut options = ToolOptions { crop_ratio: "16:9".into(), ..ToolOptions::default() }; diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 78f8d44b50..00700ae5c0 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -645,7 +645,7 @@ pub fn swapped(r: [f64; 4]) -> [f64; 4] { /// no ratio is set; "original" becomes the document's size turned on its side. pub fn swapped_ratio(key: &str, doc_w: f64, doc_h: f64) -> Option { let (w, h) = crate::chrome_ui::crop_ratio(key, doc_w, doc_h).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0)?; - Some(format!("{}:{}", crate::widgets::fmt_num(h), crate::widgets::fmt_num(w))) + Some(format!("{}:{}", crate::crop_size::fmt_ratio(h), crate::crop_size::fmt_ratio(w))) } /// X: swaps the pending frame between portrait and landscape about its centre, keeping its angle, @@ -1724,6 +1724,22 @@ mod tests { } } + #[test] + fn enter_during_a_drag_ends_the_drag() { + // ↵ while the frame is still being dragged commits it; the release after must not bring + // back a frame in the old document's coordinates as a pending crop. + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([20.0, 20.0, 120.0, 70.0]); + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 40.0, pressure: 1.0 }, NONE); + crate::canvas::commit_crop(&mut app); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, NONE); + ensure_frame(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 50)); + assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 100.0, 50.0])); + assert!(!pending(&app)); + } + #[test] fn degenerate_and_bad_input_never_panics() { let mut app = app(SampleType::U8); @@ -1949,6 +1965,7 @@ mod tests { app.ui.tool_options.crop_ratio = String::new(); assert!(swap_orientation(&mut app)); assert_eq!(app.ui.tool_options.crop_ratio, "", "no ratio stays none"); + assert_eq!(swapped_ratio("1.414:1", 1.0, 1.0).as_deref(), Some("1:1.414"), "decimals survive the swap (#6487)"); assert_eq!(swapped_ratio("0:5", 1.0, 1.0), None); assert_eq!(swapped_ratio("nonsense", 1.0, 1.0), None); // No frame, or another tool: X is Switch Foreground and Background Colors. diff --git a/crates/ui-egui/src/dds_options_ui.rs b/crates/ui-egui/src/dds_options_ui.rs new file mode 100644 index 0000000000..c795643a7d --- /dev/null +++ b/crates/ui-egui/src/dds_options_ui.rs @@ -0,0 +1,148 @@ +//! DDS Options: the compression and mip chain File › Save As and Save a Copy ask for before +//! writing a DirectDraw Surface texture (#1327). Photoshop has no DDS writer of its own (a plug-in +//! adds one), so this follows the texture tools' usual choices: uncompressed, or BC1/BC2/BC3 +//! (DXT1/DXT3/DXT5), and whether to generate mipmaps (see `photocraft_io::DdsOptions`). +//! +//! The save is parked in [`Prompt`] while the modal is up (egui is immediate-mode) and written +//! once answered. Cancel drops the save. Scripts skip the prompt by passing `ddsCompression` or +//! `ddsMipmaps`. + +use photocraft_io::{DdsCompression, DdsOptions}; + +use crate::{ExportSettings, PhotocraftApp}; + +/// A save waiting on the DDS Options answer. +pub struct Prompt { + /// The document that requested the save, even if tabs change while this is open. + doc: photocraft_doc::DocId, + /// Where the texture goes. + pub path: String, + /// The options chosen, starting uncompressed without mipmaps. + pub options: DdsOptions, + /// Save a Copy: the document keeps its path and unsaved changes. + pub copy: bool, + /// The step the answered save is recorded as (`file.saveAs` or `file.saveACopy`), so an + /// action being recorded keeps it; `file.save` when File › Save confirmed the document's own + /// texture (#3531), which plays back on the file the action is played on. + pub record: &'static str, +} + +/// `true` when `path` names a DDS texture. +pub fn wants_prompt(path: &str) -> bool { + photocraft_engine::file_cmds::extension(path).and_then(|e| photocraft_codecs::from_extension(&e)) == Some(photocraft_codecs::Format::Dds) +} + +/// The DDS options a command or control call asks for (`"ddsCompression"`, `"ddsMipmaps"`), +/// which skip the prompt. +pub fn options_param(params: &serde_json::Value, cmd: &str) -> Result, String> { + photocraft_engine::file_cmds::dds_param(params, cmd).map_err(|e| e.to_string()) +} + +/// The params a save with `options` is recorded with. +pub fn record(options: DdsOptions, step: &mut serde_json::Value) { + step["ddsCompression"] = options.compression.name().into(); + step["ddsMipmaps"] = options.mipmaps.into(); +} + +/// Parks the save behind the prompt. A prompt already waiting is never replaced. +pub fn park(app: &mut PhotocraftApp, path: String, copy: bool, record: &'static str) -> Result<(), String> { + if app.save_options_open() { + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); + } + let doc = app.active_doc_id()?; + app.dds_options = Some(Prompt { doc, path, options: DdsOptions::default(), copy, record }); + Ok(()) +} + +/// The block compressions go by their format names, which stay untranslated like other +/// technology names. +fn label(c: DdsCompression) -> &'static str { + match c { + DdsCompression::None => tl!("None"), + DdsCompression::Bc1 => "BC1 / DXT1", + DdsCompression::Bc2 => "BC2 / DXT3", + DdsCompression::Bc3 => "BC3 / DXT5", + } +} + +pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some(p) = &mut app.dds_options else { return }; + let (mut ok, mut cancel) = (false, false); + let mut options = p.options; + let modal = egui::Modal::new(egui::Id::new("dds-options")).show(ctx, |ui| { + ui.set_max_width(340.0); + ui.label(egui::RichText::new(tl!("DDS Options")).font(crate::theme::semibold(15.0))); + ui.add_space(4.0); + crate::widgets::hairline(ui); + ui.add_space(8.0); + crate::widgets::section_label(ui, tl!("Compression")); + for c in DdsCompression::ALL { + ui.radio_value(&mut options.compression, c, label(c)); + } + ui.add_space(8.0); + crate::widgets::checkbox(ui, &mut options.mipmaps, tl!("Generate Mipmaps")); + ui.add_space(12.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 10.0; + ok = crate::widgets::primary_button(ui, tl!("OK"), 84.0).clicked(); + cancel = crate::widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked(); + }); + }); + cancel |= modal.should_close(); + p.options = options; + // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels. + if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) { + let Some(p) = app.dds_options.take() else { return }; + let settings = ExportSettings { dds: p.options, ..app.save_settings() }; + let mut step = if p.record == "file.save" { serde_json::json!({}) } else { serde_json::json!({"path": p.path}) }; + record(p.options, &mut step); + let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy)); + if written.is_ok() { + // An action being recorded keeps the Save As or Save a Copy with this answer. + app.session.journal.push((p.record.into(), step)); + } + match written { + Err(e) => { + app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]); + app.ui.status_error = true; + } + Ok(Some(_)) if !p.copy => crate::discard_ui::saved_document(app, ctx, p.doc), + // A background save releases the close prompt when it finishes (`jobs_ui`). + Ok(_) => {} + } + } else if cancel { + app.dds_options = None; + app.ui.status = tl!("Save cancelled").into(); + app.ui.status_error = false; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dds_names() { + assert!(wants_prompt("a.dds")); + assert!(wants_prompt("dir/sub/a.DDS")); + assert!(wants_prompt("C:\\x\\y.dds")); + assert!(!wants_prompt("a.dds.psd")); + assert!(!wants_prompt(".dds")); + assert!(!wants_prompt("a.png")); + } + + #[test] + fn options_params() { + use serde_json::json; + assert_eq!(options_param(&json!({}), "file.saveAs"), Ok(None)); + assert_eq!(options_param(&json!({"ddsCompression": "bc3"}), "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::Bc3, mipmaps: false }))); + assert_eq!(options_param(&json!({"ddsMipmaps": true}), "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::None, mipmaps: true }))); + for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsCompression": 3}), json!({"ddsMipmaps": "yes"})] { + assert!(options_param(&bad, "file.saveAs").is_err(), "{bad}"); + } + let mut step = json!({"path": "a.dds"}); + record(DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }, &mut step); + assert_eq!(step, json!({"path": "a.dds", "ddsCompression": "bc1", "ddsMipmaps": true})); + assert_eq!(options_param(&step, "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }))); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 013c79e825..e27411b7e0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -104,15 +104,22 @@ fn older_dialog_above(ctx: &egui::Context, live: egui::LayerId, dialogs: &[Dialo ctx.memory(|m| m.layer_ids().skip_while(|l| *l != live).skip(1).any(|l| others.contains(&l))) } -fn resizable_dialog(fields: &serde_json::Map) -> bool { - fields.contains_key("__web") || crate::prefs_ui::is_preferences(fields) +/// The size a resizable dialog opens at, or `None` for a dialog sized by its contents. +fn resizable_dialog(fields: &serde_json::Map) -> Option { + if crate::prefs_ui::is_preferences(fields) { + Some(crate::prefs_ui::PREFERENCES_SIZE) + } else if fields.contains_key("__web") { + Some(egui::vec2(960.0, 900.0)) + } else { + None + } } fn show_modal( modal: egui::Modal, ctx: &egui::Context, id: egui::Id, - resizable: bool, + resizable: Option, interactive: bool, contents: impl FnOnce(&mut egui::Ui) -> T, ) -> egui::ModalResponse { @@ -121,14 +128,9 @@ fn show_modal( if !interactive { ui.disable(); } - if resizable { + if let Some(size) = resizable { let max = (ctx.content_rect().size() - egui::vec2(40.0, 40.0)).max(egui::vec2(560.0, 400.0)); - egui::Resize::default() - .id(id.with("resize")) - .default_size(egui::vec2(960.0, 900.0).min(max)) - .min_size(egui::vec2(560.0, 400.0)) - .max_size(max) - .show(ui, contents) + egui::Resize::default().id(id.with("resize")).default_size(size.min(max)).min_size(egui::vec2(560.0, 400.0)).max_size(max).show(ui, contents) } else { contents(ui) } @@ -207,7 +209,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // Photoshop doesn't dim the window behind dialogs: previews must be judged at true contrast. let web = fields.contains_key("__web"); let web_popup_open = web && egui::Popup::is_any_open(ctx); - let modal = show_modal(modal, ctx, id, resizable_dialog(&fields), interactive, |ui| { + let resizable = resizable_dialog(&fields); + let modal = show_modal(modal, ctx, id, resizable, interactive, |ui| { sizing = ui.is_sizing_pass(); let available = ui.available_size(); // A dialog of a few short fields (`__compact`, Fit Image) is narrower (#4673): the title @@ -218,7 +221,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { if !compact { ui.set_min_width(if curves { 300.0 } else { 380.0 }); } - let wide = crate::prefs_ui::width(&d.fields, (ctx.content_rect().width() - 48.0).max(380.0)); + // A resizable dialog's contents fill its resizable area (#7420), the others the window. + let room = if resizable.is_some() { available.x } else { (ctx.content_rect().width() - 48.0).max(380.0) }; + let wide = crate::prefs_ui::width(&d.fields, room); if let Some(w) = wide { ui.set_min_width(w.min(460.0)); } @@ -321,6 +326,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { DialogKind::Command if crate::channel_options_ui::owns_new_spot(&fields) => crate::channel_options_ui::new_spot_body(ui, &mut fields), DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields), DialogKind::Command if crate::delete_layer_prompt::owns(&fields) => crate::delete_layer_prompt::body(ui, &mut fields), + DialogKind::Command if crate::disk_change_prompt::owns(&fields) => crate::disk_change_prompt::body(ui, &fields), DialogKind::Command if crate::actions::owns_insert_stop(&fields) => crate::actions::insert_stop_body(ui, &mut fields), DialogKind::Command if crate::new_layer_ui::owns(&fields) => crate::new_layer_ui::body(ui, &mut fields), DialogKind::Command if crate::mask_trash_prompt::owns(&fields) => crate::mask_trash_prompt::body(ui, &fields), @@ -330,10 +336,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { DialogKind::Command if crate::tool_reset::owns(&fields) => crate::tool_reset::body(ui), DialogKind::Command if crate::crop_presets::owns(&fields) => crate::crop_presets::body(app, ui, &mut fields), DialogKind::Command if crate::variables_ui::owns(&fields) => crate::variables_ui::body(app, ui, &mut fields), - DialogKind::Command if crate::file_ui::owns(&fields) => crate::file_ui::body(app, ui, &mut fields), + DialogKind::Command if crate::file_ui::owns(&fields) => crate::file_ui::body(app, ui, &mut fields, d.id), DialogKind::Command if crate::color_picker_ui::owns(&fields) => { outcome = crate::color_picker_ui::body(ui, &mut fields); crate::color_picker_ui::take_add_swatch(app, &mut fields); + if let Some(web) = fields.get("__webOnly").and_then(Value::as_bool) { + app.ui.color_panel.web_only = web; + } } DialogKind::Command if crate::color_range_ui::owns(&fields) => crate::color_range_ui::body(app, ui, &mut fields), DialogKind::Command if crate::prefs_ui::owns(&fields) => crate::prefs_ui::body(app, ui, &mut fields), @@ -401,6 +410,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { tl!("Create") } else if crate::delete_layer_prompt::owns(&d.fields) { tl!("Delete") + } else if crate::disk_change_prompt::owns(&d.fields) { + tl!("Replace") } else if d.fields.contains_key("__export") { tl!("Export") } else { @@ -614,6 +625,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { DialogKind::Command if crate::channel_options_ui::owns_new_spot(&d.fields) => crate::channel_options_ui::confirm_new_spot(app, &d.fields), DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields), DialogKind::Command if crate::delete_layer_prompt::owns(&d.fields) => crate::delete_layer_prompt::confirm(app, &d.fields), + DialogKind::Command if crate::disk_change_prompt::owns(&d.fields) => crate::disk_change_prompt::confirm(app, &d.fields), DialogKind::Command if crate::actions::owns_insert_stop(&d.fields) => crate::actions::insert_stop_confirm(app, &d.fields), DialogKind::Command if crate::new_layer_ui::owns(&d.fields) => crate::new_layer_ui::confirm(app, &d.fields), DialogKind::Command if crate::mask_trash_prompt::owns(&d.fields) => crate::mask_trash_prompt::confirm(app, &d.fields), @@ -652,7 +664,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { if result.is_ok() { crate::filter_dialog::remember(app, &cmd, &d.fields); // A step dialog of a playing action: the action continues after it. - crate::actions::resume(app, &d.fields); + crate::actions::resume(app, &d.fields)?; } result } @@ -1125,9 +1137,68 @@ mod preference_resize_tests { let ordinary = json!({}); let web = json!({"__web": true}); - assert!(resizable_dialog(prefs.as_object().unwrap())); - assert!(!resizable_dialog(shortcuts.as_object().unwrap())); - assert!(!resizable_dialog(ordinary.as_object().unwrap())); - assert!(resizable_dialog(web.as_object().unwrap())); + assert_eq!(resizable_dialog(prefs.as_object().unwrap()), Some(crate::prefs_ui::PREFERENCES_SIZE)); + assert_eq!(resizable_dialog(shortcuts.as_object().unwrap()), None); + assert_eq!(resizable_dialog(ordinary.as_object().unwrap()), None); + assert_eq!(resizable_dialog(web.as_object().unwrap()), Some(egui::vec2(960.0, 900.0))); + } + + /// Drags the dialog's resize grip (its frame's bottom-right corner) by `by`. + fn drag_corner(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, by: egui::Vec2) { + let corner = frame(h).max - egui::vec2(14.0, 14.0); + h.event(egui::Event::PointerMoved(corner)); + h.step(); + h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.step(); + h.event(egui::Event::PointerMoved(corner + by)); + h.step(); + h.event(egui::Event::PointerButton { pos: corner + by, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(4); + } + + fn frame(h: &egui_kittest::Harness<'_, PhotocraftApp>) -> egui::Rect { + let rects: Vec = h.ctx.data(|m| m.get_temp(egui::Id::new(RECTS))).unwrap(); + rects[0] + } + + /// The button row sits in the frame's bottom-right corner (its order follows the platform): + /// the contents fill the dialog, no empty space. + fn assert_buttons_in_corner(h: &egui_kittest::Harness<'_, PhotocraftApp>, when: &str) { + use egui_kittest::kittest::Queryable; + let f = frame(h); + let row = ["OK", "Cancel", "Apply"].map(|l| h.get_by_label(l).rect()).into_iter().reduce(|a, b| a.union(b)).unwrap(); + // Inside the frame (not past its edge) and near it. + let near = |gap: f32| (0.0..24.0).contains(&gap); + assert!(near(f.bottom() - row.bottom()) && near(f.right() - row.right()), "{when}: frame {f:?}, buttons {row:?}"); + } + + #[test] + fn preferences_contents_follow_the_dialog_when_it_is_resized() { + // #7420: the dialog resized but its contents kept a size from the window, leaving the + // buttons part-way up a dialog that opened, or was dragged, larger than them. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + crate::prefs_ui::open_preferences(&mut app, "interface"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state( + |ui, app| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) { + show(app, ui.ctx()); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(5); + assert_buttons_in_corner(&h, "on open"); + let opened = frame(&h); + drag_corner(&mut h, egui::vec2(220.0, 80.0)); + assert!(frame(&h).width() > opened.width() + 150.0 && frame(&h).height() > opened.height() + 50.0, "wider: {:?}", frame(&h)); + assert_buttons_in_corner(&h, "wider"); + drag_corner(&mut h, egui::vec2(-500.0, -300.0)); + let smaller = frame(&h); + assert!(smaller.width() < opened.width() - 200.0 && smaller.height() < opened.height() - 150.0, "smaller: {smaller:?}"); + assert_buttons_in_corner(&h, "smaller"); + // The contents never ask for more than the dialog gives them, so it keeps its size. + h.run_steps(10); + assert_eq!(frame(&h), smaller); } } diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rs index 30e5f47deb..e9b5504bea 100644 --- a/crates/ui-egui/src/discard_ui.rs +++ b/crates/ui-egui/src/discard_ui.rs @@ -21,6 +21,8 @@ pub struct Prompt { /// The document the command was aimed at (`document` param, else the active one), if it has one. target: Option, docs: Vec, + /// The document whose question has already put keyboard focus on its default answer. + focused: Option, } fn index_of(app: &PhotocraftApp, id: DocId) -> Option { @@ -69,7 +71,7 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str, params: &Value) -> bool { if docs.is_empty() { return false; } - let prompt = Prompt { id: id.to_string(), params: params.clone(), target, docs }; + let prompt = Prompt { id: id.to_string(), params: params.clone(), target, docs, focused: None }; match &app.discard { None => ask(app, prompt), // Quitting overrides whatever is pending: it covers every document, so nothing is lost. @@ -155,6 +157,25 @@ fn advance(app: &mut PhotocraftApp, ctx: &egui::Context) { if next.is_some() { return; } + // A save or close hook may have dirtied a document that was clean when the prompt opened (or + // made a new one): ask about those before the final close, which discards without checking. + if one_by_one && let Some(p) = app.discard.as_ref() { + let (id, target) = (p.id.clone(), p.target); + let rest: Vec = app + .session + .documents() + .iter() + .filter(|d| d.is_dirty() && (matches!(reach(&id), Some(Reach::All)) || Some(d.doc.id) != target)) + .map(|d| d.doc.id) + .collect(); + if !rest.is_empty() { + show_tab(app, rest.first().copied()); + if let Some(p) = app.discard.as_mut() { + p.docs = rest; + } + return; + } + } let Some(Prompt { id, mut params, target, .. }) = app.discard.take() else { return }; if id == EXIT { app.allow_close = true; @@ -193,7 +214,12 @@ fn save(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId) -> bool { } match saved { // A Save Document script may have edited the document after it was written: still dirty. - Ok(_) => !app.save_options_open() && !app.saving() && index_of(app, doc).is_some_and(|i| !app.session.documents()[i].is_dirty()), + // A write the platform can't confirm (a web download) leaves it dirty too, and counts. + Ok(_) => { + !app.save_options_open() + && !app.saving() + && index_of(app, doc).is_some_and(|i| app.services.write_unconfirmed || !app.session.documents()[i].is_dirty()) + } // Backing out of the file dialog is the user's choice, not an error. Err(e) if e == crate::file_dialog::CANCELLED => false, Err(e) => { @@ -206,12 +232,12 @@ fn save(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId) -> bool { /// A completed save may release the close prompt. Choosing a path only starts a layered TIFF /// save; TIFF Options calls this after the write, and `jobs_ui` when a background save ends. -/// Copies and failed writes leave the doc dirty. +/// Copies and failed writes leave the doc dirty; so does any write when it is unconfirmed. pub(crate) fn saved_document(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId) { // Still the prompt that asked (quitting may have replaced it meanwhile). if !app.save_options_open() && app.discard.as_ref().and_then(|p| p.docs.first()) == Some(&doc) - && index_of(app, doc).is_some_and(|i| !app.session.documents()[i].is_dirty()) + && index_of(app, doc).is_some_and(|i| app.services.write_unconfirmed || !app.session.documents()[i].is_dirty()) { advance(app, ctx); } @@ -226,6 +252,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // Save can ask for a path and then TIFF or Targa Options, and then write in the background. // Wait for all three; cancellation or a failed save brings us back. if app.file_dialog_open() || app.save_options_open() || app.saving() { + // Hidden meanwhile: the question takes focus again when it comes back. + if let Some(p) = app.discard.as_mut() { + p.focused = None; + } return; } let Some(p) = &app.discard else { return }; @@ -246,6 +276,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { }; (tl!("Unsaved changes"), crate::i18n::fmt(template, &[("name", &name)])) }; + // Each question comes up with its default answer focused, as in Photoshop: the arrow keys then + // move between the answers and Enter presses the focused one (#6441). + let focus = p.focused != Some(doc); + if let Some(p) = app.discard.as_mut() { + p.focused = Some(doc); + } let mac = ctx.os() == egui::os::OperatingSystem::Mac; // The answers in the platform's words; `dialog_buttons` puts them in its order. Windows (and // Linux) ask Yes / No / Cancel with Y, N and Esc, as Photoshop does there; macOS asks @@ -266,7 +302,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { }; let mut answer = ctx.input_mut(|i| buttons.iter().find(|b| b.2.is_some_and(|k| i.consume_key(egui::Modifiers::NONE, k))).map(|b| b.4)); let labels = button_labels(mac, &buttons.iter().map(|b| (b.1, b.2)).collect::>()); - let row: Vec = buttons.iter().zip(&labels).map(|(b, label)| DialogButton::new(b.0, label, b.3)).collect(); + let row: Vec = + buttons.iter().zip(&labels).map(|(b, label)| DialogButton::new(b.0, label, b.3).focus(focus && b.0 == ButtonRole::Default)).collect(); let modal = egui::Modal::new(egui::Id::new("discard-prompt")).show(ctx, |ui| { ui.set_max_width(420.0); ui.label(egui::RichText::new(tl!(&title)).font(crate::theme::semibold(15.0))); @@ -482,6 +519,38 @@ mod tests { assert!(app.session.documents().is_empty()); } + /// A document that became dirty while the prompt was up is asked about before the final close (#4954). + #[test] + fn a_document_dirtied_during_the_prompt_is_asked_about_before_the_final_close() { + for command in ["file.closeAll", EXIT] { + let mut app = app_with_docs(2); + let ctx = egui::Context::default(); + make_dirty(&mut app, 0); + let late = doc_id(&app, 1); + crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap(); + make_dirty(&mut app, 1); + advance(&mut app, &ctx); + assert_eq!(app.discard.as_ref().map(|p| p.docs.clone()), Some(vec![late]), "{command}: asks about the newly dirty document"); + assert!(!app.allow_close, "{command}"); + assert_eq!(app.session.documents().len(), 1, "{command}: it is not discarded unasked"); + advance(&mut app, &ctx); + assert!(app.discard.is_none(), "{command}"); + } + // Close Others asks about the others too, but still not about the document it keeps. + let mut app = app_with_docs(3); + let ctx = egui::Context::default(); + make_dirty(&mut app, 0); + let (late, kept) = (doc_id(&app, 1), doc_id(&app, 2)); + crate::menus::invoke(&mut app, &ctx, "file.closeOthers", json!({"document": 2})).unwrap(); + make_dirty(&mut app, 1); + make_dirty(&mut app, 2); + advance(&mut app, &ctx); + assert_eq!(app.discard.as_ref().map(|p| p.docs.clone()), Some(vec![late]), "file.closeOthers: asks about the newly dirty other document"); + advance(&mut app, &ctx); + assert!(app.discard.is_none()); + assert_eq!(app.session.documents().iter().map(|d| d.doc.id).collect::>(), [kept]); + } + #[test] fn close_others_closes_each_answered_document_and_keeps_its_target() { let mut app = app_with_docs(3); @@ -582,31 +651,60 @@ mod tests { v.into_iter().map(|(_, l)| l).collect() } - /// Tab walks `labels` left to right and wraps; Shift+Tab steps back. - fn tab_walks(h: &mut Prompted, labels: [&str; 3]) { - use egui_kittest::kittest::Queryable; - let focused = |h: &Prompted| labels.into_iter().find(|l| h.get_by_label(l).is_focused()); - for want in [labels[0], labels[1], labels[2], labels[0]] { + /// Tab walks `labels` left to right from the focused default answer, `labels[default]`, and + /// wraps; Shift+Tab steps back. + fn tab_walks(h: &mut Prompted, labels: [&str; 3], default: usize) { + assert_eq!(focused(h, &labels), Some(labels[default])); + for step in 1..=3 { h.key_press(Key::Tab); h.run_steps(2); - assert_eq!(focused(h), Some(want)); + assert_eq!(focused(h, &labels), Some(labels[(default + step) % 3])); } h.key_press_modifiers(egui::Modifiers::SHIFT, Key::Tab); h.run_steps(2); - assert_eq!(focused(h), Some(labels[2])); + assert_eq!(focused(h, &labels), Some(labels[(default + 2) % 3])); } fn docs_left(h: &Prompted) -> Option { h.state().discard.as_ref().map(|p| p.docs.len()) } + /// Which of `labels` has keyboard focus. + fn focused<'a>(h: &Prompted, labels: &[&'a str]) -> Option<&'a str> { + use egui_kittest::kittest::Queryable; + labels.iter().copied().find(|l| h.get_by_label(l).is_focused()) + } + + /// The default answer has keyboard focus as each question comes up, so the arrow keys move + /// between the answers and Enter presses the one they reached, as in Photoshop (#6441). + #[test] + fn each_question_comes_up_with_the_default_answer_focused() { + let mut h = prompt_on(egui::os::OperatingSystem::Windows); + let labels = ["(Y)es", "(N)o", "(C)ancel"]; + assert_eq!(focused(&h, &labels), Some("(Y)es")); + h.key_press(Key::ArrowRight); + h.run_steps(2); + assert_eq!(focused(&h, &labels), Some("(N)o")); + h.key_press(Key::Enter); + h.run_steps(2); + assert_eq!(docs_left(&h), Some(1), "Enter pressed No"); + assert_eq!(focused(&h, &labels), Some("(Y)es"), "the next question starts on the default again"); + + let mut h = prompt_on(egui::os::OperatingSystem::Mac); + let labels = ["Don't Save", "Cancel", "Save"]; + assert_eq!(focused(&h, &labels), Some("Save")); + h.key_press(Key::ArrowLeft); + h.run_steps(2); + assert_eq!(focused(&h, &labels), Some("Cancel")); + } + #[test] fn windows_and_linux_ask_yes_no_cancel_with_the_default_first() { for os in [egui::os::OperatingSystem::Windows, egui::os::OperatingSystem::Nix] { let mut h = prompt_on(os); let labels = ["(Y)es", "(N)o", "(C)ancel"]; assert_eq!(drawn_order(&h, labels), labels, "{os:?}"); - tab_walks(&mut h, labels); + tab_walks(&mut h, labels, 0); h.key_press(Key::N); h.run_steps(2); assert_eq!(docs_left(&h), Some(1), "N answered the first document"); @@ -699,7 +797,7 @@ mod tests { let mut h = prompt_on(egui::os::OperatingSystem::Mac); let labels = ["Don't Save", "Cancel", "Save"]; assert_eq!(drawn_order(&h, labels), labels); - tab_walks(&mut h, labels); + tab_walks(&mut h, labels, 2); h.key_press(Key::D); h.run_steps(2); assert_eq!(docs_left(&h), Some(1), "D answered the first document"); @@ -736,11 +834,9 @@ mod tests { h.run_steps(2); assert_eq!(asked.borrow().len(), 1, "Enter answered Yes, which saves"); assert_eq!(docs_left(&h), Some(2)); - // Tab to No: Enter now presses it. - for _ in 0..2 { - h.key_press(Key::Tab); - h.run_steps(2); - } + // Tab from the focused Yes to No: Enter now presses it. + h.key_press(Key::Tab); + h.run_steps(2); h.key_press(Key::Enter); h.run_steps(2); assert_eq!(asked.borrow().len(), 1, "no second dialog"); @@ -776,7 +872,7 @@ mod tests { assert!(h.query_by_label("(Y)es").is_none(), "the prompt waits behind the dialog"); answer(&mut h, None); assert_eq!(docs_left(&h), Some(1)); - assert!(h.query_by_label("(Y)es").is_some()); + assert_eq!(focused(&h, &["(Y)es", "(N)o", "(C)ancel"]), Some("(Y)es"), "the prompt comes back with Yes focused"); // Saving closes the document. h.key_press(Key::Y); h.run_steps(3); @@ -833,12 +929,39 @@ mod tests { assert!(h.state().session.documents().is_empty(), "closed once saved"); } + /// #6414: on the web a save stays dirty (the download isn't confirmed), and answering Save + /// still closes the tab after one write. + #[test] + fn saving_from_the_prompt_closes_after_an_unconfirmed_write() { + use std::{cell::RefCell, rc::Rc}; + let written: Rc>> = Rc::default(); + let w = written.clone(); + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + app.session.active_mut().unwrap().path = Some("/pics/kept.psd".into()); + app.services.write_unconfirmed = true; + app.services.export = Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))); + app.services.write = Some(Box::new(move |p: &str, _: &[u8]| { + w.borrow_mut().push(p.to_string()); + Ok(()) + })); + let mut h = prompt_for(app, "file.close", egui::os::OperatingSystem::Windows); + h.key_press(Key::Y); + h.run_steps(3); + assert_eq!(*written.borrow(), ["/pics/kept.psd"]); + assert!(h.state().discard.is_none()); + assert!(h.state().session.documents().is_empty(), "closed after one write"); + } + #[path = "tiff_tests.rs"] mod tiff_tests; #[path = "targa_tests.rs"] mod targa_tests; + #[path = "dds_tests.rs"] + mod dds_tests; + /// One frame with the window's close button pressed; the commands the guard sent. fn window_close_commands(app: &mut PhotocraftApp) -> Vec { let mut info = egui::ViewportInfo::default(); diff --git a/crates/ui-egui/src/discard_ui/tests/dds_tests.rs b/crates/ui-egui/src/discard_ui/tests/dds_tests.rs new file mode 100644 index 0000000000..f1c88dec81 --- /dev/null +++ b/crates/ui-egui/src/discard_ui/tests/dds_tests.rs @@ -0,0 +1,217 @@ +//! DDS Options on Save As and Save a Copy: the compression and mipmaps it asks for, the scripted +//! `ddsCompression` and `ddsMipmaps` that skip it, and action recording and playback (#1327). +use super::*; +use crate::{FileDialogAnswer, dds_options_ui}; +use egui_kittest::kittest::Queryable; +use photocraft_io::{DdsCompression, DdsOptions}; +use std::{cell::RefCell, rc::Rc}; + +/// Each write: the path, and the DDS options the export was asked for. +type Writes = Rc>>; + +const PLAIN: DdsOptions = DdsOptions { compression: DdsCompression::None, mipmaps: false }; + +/// One 8×8 RGB document whose exports record their DDS options, in a harness showing DDS Options +/// and answering a save dialog with `to`. +fn dds_app(to: &str) -> (Prompted, Writes) { + let mut app = app_with_docs(1); + let writes: Writes = Rc::default(); + let (asked, written) = (Rc::new(RefCell::new(PLAIN)), writes.clone()); + let seen = asked.clone(); + app.services.file_dialog = Some(crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo(to.into()))]).0); + app.services.export = Some(Box::new(move |_, _, settings| { + *seen.borrow_mut() = settings.dds; + Ok((Vec::new(), Vec::new())) + })); + app.services.write = Some(Box::new(move |path, _| { + written.borrow_mut().push((path.to_string(), *asked.borrow())); + Ok(()) + })); + let h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state( + |ui, app| { + show(app, ui.ctx()); + dds_options_ui::show(app, ui.ctx()); + app.poll_file_dialog(ui.ctx(), None); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.ctx.set_os(egui::os::OperatingSystem::Windows); + (h, writes) +} + +/// Save As to a DDS texture asks first, starting uncompressed without mipmaps, and writes only +/// what is chosen once answered. +#[test] +fn save_as_to_a_dds_texture_asks_for_its_compression() { + let (mut h, writes) = dds_app("unused.dds"); + h.state_mut().save_as(Some("t.dds".into())).unwrap(); + h.run_steps(2); + assert_eq!(h.state().dds_options.as_ref().map(|p| (p.options, p.copy)), Some((PLAIN, false))); + assert!(writes.borrow().is_empty(), "nothing is written before the answer"); + assert!(h.state_mut().save_as(Some("other.dds".into())).is_err(), "one save at a time"); + h.get_by_label("BC3 / DXT5").click(); + h.run_steps(2); + h.get_by_label("Generate Mipmaps").click(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(3); + let chosen = DdsOptions { compression: DdsCompression::Bc3, mipmaps: true }; + assert_eq!(writes.borrow().as_slice(), &[("t.dds".to_string(), chosen)]); + assert!(h.state().dds_options.is_none()); + assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("t.dds")); + + // Cancel writes nothing. + h.state_mut().save_as(Some("c.dds".into())).unwrap(); + h.run_steps(2); + h.key_press(Key::Escape); + h.run_steps(3); + assert!(h.state().dds_options.is_none()); + assert_eq!(writes.borrow().len(), 1, "cancelled: nothing more written"); + assert_eq!(h.state().ui.status, "Save cancelled"); +} + +/// Scripts choose with `ddsCompression` or `ddsMipmaps` and are never asked; bad values write +/// nothing, and other formats aren't asked. +#[test] +fn scripted_dds_options_and_other_formats_skip_the_prompt() { + let (mut h, writes) = dds_app("unused.dds"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "s.dds", "ddsCompression": "bc1"})).unwrap(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "m.dds", "ddsMipmaps": true})).unwrap(); + assert!(h.state().dds_options.is_none()); + for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsMipmaps": 1})] { + let mut p = bad.clone(); + p["path"] = json!("bad.dds"); + assert!(crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", p).is_err(), "{bad}"); + } + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "p.png"})).unwrap(); + assert!(h.state().dds_options.is_none()); + assert_eq!( + writes.borrow().as_slice(), + &[ + ("s.dds".to_string(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }), + ("m.dds".to_string(), DdsOptions { compression: DdsCompression::None, mipmaps: true }), + ("p.png".to_string(), PLAIN), + ] + ); +} + +/// Save a Copy to a DDS texture asks too, and the copy leaves the document's path and unsaved +/// state. +#[test] +fn save_a_copy_to_a_dds_texture_asks_and_keeps_the_document_unsaved() { + let (mut h, writes) = dds_app("copy.dds"); + make_dirty(h.state_mut(), 0); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveACopy", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(h.state().dds_options.as_ref().map(|p| (p.options, p.copy)), Some((PLAIN, true))); + assert!(dds_options_ui::park(h.state_mut(), "other.dds".into(), false, "file.saveAs").is_err(), "the waiting prompt is kept"); + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(writes.borrow().as_slice(), &[("copy.dds".to_string(), PLAIN)]); + let st = h.state().session.active().unwrap(); + assert!(st.is_dirty()); + assert_eq!(st.path, None); +} + +/// An action being recorded keeps a DDS Save As or Save a Copy with its options, answered in DDS +/// Options or scripted, and plays them back without asking. +#[test] +fn recorded_dds_saves_keep_their_options_and_replay_without_asking() { + let (mut h, writes) = dds_app("copy.dds"); + let ctx = h.ctx.clone(); + h.state_mut().run("actions.record", json!({})).unwrap(); + h.state_mut().save_as(Some("t.dds".into())).unwrap(); + h.run_steps(2); + h.get_by_label("BC1 / DXT1").click(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(3); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveACopy", json!({})).unwrap(); + h.run_steps(3); + h.get_by_label("Generate Mipmaps").click(); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "s.dds", "ddsCompression": "bc2"})).unwrap(); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let want = [ + ("t.dds".to_string(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }), + ("copy.dds".to_string(), DdsOptions { compression: DdsCompression::None, mipmaps: true }), + ("s.dds".to_string(), DdsOptions { compression: DdsCompression::Bc2, mipmaps: false }), + ]; + assert_eq!(writes.borrow().as_slice(), &want); + let steps = &h.state().session.actions.list[0].steps; + assert_eq!( + steps, + &[ + ("file.saveAs".into(), json!({"path": "t.dds", "ddsCompression": "bc1", "ddsMipmaps": false})), + ("file.saveACopy".into(), json!({"path": "copy.dds", "ddsCompression": "none", "ddsMipmaps": true})), + ("file.saveAs".into(), json!({"path": "s.dds", "ddsCompression": "bc2", "ddsMipmaps": false})) + ] + ); + writes.borrow_mut().clear(); + let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert!(h.state().dds_options.is_none(), "playback doesn't ask"); + assert_eq!(writes.borrow().as_slice(), &want); +} + +/// File › Save confirming the document's own texture asks DDS Options, and an action being +/// recorded keeps it as a plain Save with the answer (scripted options too): played back, it +/// writes the texture the action is played on as recorded, without asking (#3531). +#[test] +fn recorded_plain_save_of_a_dds_texture_keeps_its_options() { + let (mut h, writes) = dds_app("own.dds"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "own.dds", "ddsCompression": "none"})).unwrap(); + assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("own.dds")); + h.state_mut().run("actions.record", json!({})).unwrap(); + crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({})).unwrap(); + h.run_steps(3); + assert!(h.state().dds_options.is_some(), "confirming its own texture asks DDS Options"); + h.get_by_label("BC1 / DXT1").click(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(3); + h.state_mut().services.file_dialog = Some(crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo("own.dds".into()))]).0); + crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({"ddsCompression": "bc3", "ddsMipmaps": true})).unwrap(); + h.run_steps(3); + assert!(h.state().dds_options.is_none(), "scripted options don't ask"); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let bc1 = DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }; + let bc3 = DdsOptions { compression: DdsCompression::Bc3, mipmaps: true }; + assert_eq!(&writes.borrow()[1..], &[("own.dds".to_string(), bc1), ("own.dds".to_string(), bc3)]); + let steps = &h.state().session.actions.list[0].steps; + assert_eq!( + steps, + &[ + ("file.save".into(), json!({"ddsCompression": "bc1", "ddsMipmaps": false})), + ("file.save".into(), json!({"ddsCompression": "bc3", "ddsMipmaps": true})) + ] + ); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "other.dds", "ddsCompression": "none"})).unwrap(); + writes.borrow_mut().clear(); + let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert!(h.state().dds_options.is_none(), "playback doesn't ask"); + assert_eq!(writes.borrow().as_slice(), &[("other.dds".to_string(), bc1), ("other.dds".to_string(), bc3)]); +} + +/// Enter on a focused Cancel cancels: egui clicks the focused button on Enter without consuming +/// the key, so the dialog's Enter-for-OK must not save as well. +#[test] +fn enter_on_a_focused_cancel_writes_nothing() { + let (mut h, writes) = dds_app("unused.dds"); + h.state_mut().save_as(Some("t.dds".into())).unwrap(); + h.run_steps(2); + h.get_by_label("Cancel").focus(); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + assert!(h.state().dds_options.is_none()); + assert!(writes.borrow().is_empty(), "nothing written"); + assert_eq!(h.state().ui.status, "Save cancelled"); +} diff --git a/crates/ui-egui/src/discard_ui/tests/targa_tests.rs b/crates/ui-egui/src/discard_ui/tests/targa_tests.rs index 565fe01037..0a05370ecf 100644 --- a/crates/ui-egui/src/discard_ui/tests/targa_tests.rs +++ b/crates/ui-egui/src/discard_ui/tests/targa_tests.rs @@ -201,3 +201,46 @@ fn closing_after_a_targa_save_waits_for_targa_options() { assert!(h.state().discard.is_none()); assert!(h.state().session.documents().is_empty()); } + +/// File › Save confirming the document's own Targa asks Targa Options, and an action being +/// recorded keeps it as a plain Save with the bits chosen: played back, it writes the Targa the +/// action is played on with them, without asking (#3531). +#[test] +fn recorded_plain_save_of_a_targa_keeps_its_bits() { + let (mut h, writes) = targa_app(false, "own.tga"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "own.tga", "tgaBits": 24})).unwrap(); + h.state_mut().run("actions.record", json!({})).unwrap(); + crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({})).unwrap(); + h.run_steps(3); + assert!(h.state().targa_options.is_some(), "confirming its own Targa asks Targa Options"); + h.get_by_label("32 bits/pixel").click(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(3); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let steps = &h.state().session.actions.list[0].steps; + assert_eq!(steps, &[("file.save".into(), json!({"tgaBits": 32}))]); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "other.tga", "tgaBits": 24})).unwrap(); + writes.borrow_mut().clear(); + let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert!(h.state().targa_options.is_none(), "playback doesn't ask"); + assert_eq!(writes.borrow().as_slice(), &[("other.tga".to_string(), asked(Some(32)))]); +} + +/// Enter on a focused Cancel cancels: egui clicks the focused button on Enter without consuming +/// the key, so the dialog's Enter-for-OK must not save as well. +#[test] +fn enter_on_a_focused_cancel_writes_nothing() { + let (mut h, writes) = targa_app(false, "unused.tga"); + h.state_mut().save_as(Some("t.tga".into())).unwrap(); + h.run_steps(2); + h.get_by_label("Cancel").focus(); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + assert!(h.state().targa_options.is_none()); + assert!(writes.borrow().is_empty(), "nothing written"); + assert_eq!(h.state().ui.status, "Save cancelled"); +} diff --git a/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs b/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs index f42de68ea0..eb52dfb5a8 100644 --- a/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs +++ b/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs @@ -79,7 +79,7 @@ fn closing_after_tiff_save_waits_for_options_and_writes_the_requested_document() #[test] fn cancelling_failing_or_copying_a_tiff_keeps_the_original_unsaved() { - for outcome in ["cancel", "export error", "write error", "copy"] { + for outcome in ["cancel", "enter on cancel", "export error", "write error", "copy"] { let (mut h, writes, saved, _) = tiff_prompt("file.close"); h.key_press(Key::Y); h.run_steps(3); @@ -90,6 +90,11 @@ fn cancelling_failing_or_copying_a_tiff_keeps_the_original_unsaved() { h.get_by_label("Discard Layers and Save a Copy").click(); h.run_steps(2); } + // Enter on a focused Cancel is its click, not OK. + "enter on cancel" => { + h.get_by_label("Cancel").focus(); + h.run_steps(2); + } _ => {} } h.key_press(if outcome == "cancel" { Key::Escape } else { Key::Enter }); diff --git a/crates/ui-egui/src/disk_change_prompt.rs b/crates/ui-egui/src/disk_change_prompt.rs new file mode 100644 index 0000000000..b65985cd40 --- /dev/null +++ b/crates/ui-egui/src/disk_change_prompt.rs @@ -0,0 +1,57 @@ +//! File › Save asks before replacing the document's own file when another app changed it after +//! the document was opened from it or last saved to it (#6596). Replace writes the document over +//! it anyway; Cancel leaves the file and the document as they are, and File › Save As keeps both. +//! +//! The prompt is an ordinary dialog in the UI state: `ui.dialog.confirm` replaces the file and +//! `ui.dialog.cancel` keeps it. Recorded actions and automation saves don't ask. + +use photocraft_doc::DocId; +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::state::DialogKind; + +const MARK: &str = "__diskChanged"; + +pub fn owns(fields: &Map) -> bool { + fields.contains_key(MARK) +} + +/// Opens the prompt instead of saving `doc` to its own file at `path` when another app changed +/// that file; `None` saves as usual. `flat` is a flat file confirmed in the Save dialog, which +/// is saved (and recorded) the way [`PhotocraftApp::save_dialog_flow`] does it. +pub(crate) fn intercept(app: &mut PhotocraftApp, doc: DocId, path: &str, flat: bool) -> Option> { + if !app.changed_on_disk(doc, path) { + return None; + } + if app.ui.dialogs.iter().any(|d| owns(&d.fields)) { + return Some(Ok(json!({"confirmationPending": true}))); + } + let name = crate::file_open::display_name(path); + let message = crate::i18n::fmt(tl!("{name} was changed by another app after it was opened or saved here."), &[("name", name.as_str())]); + let fields = json!({MARK: true, "__label": "Save", "message": message, "document": doc.0, "path": path, "flat": flat}); + let id = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap_or_default()); + Some(Ok(json!({"dialog": id, "confirmationPending": true}))) +} + +pub fn body(ui: &mut egui::Ui, fields: &Map) { + ui.label(fields.get("message").and_then(Value::as_str).unwrap_or_default()); + ui.add_space(6.0); + ui.label(tl!("Replace it with this document, or cancel and use File › Save As to keep both.")); +} + +/// Replace: the save the prompt held back. +pub fn confirm(app: &mut PhotocraftApp, fields: &Map) -> Result { + let doc = fields.get("document").and_then(Value::as_u64).map(DocId).ok_or(tl!("The document is closed"))?; + let path = fields.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); + let flat = fields.get("flat").and_then(Value::as_bool) == Some(true); + app.with_document(doc, |app| { + if flat { + let r = app.save_to(path.clone(), crate::FormatChoices::default())?; + app.journal_as_plain_save(&path); + Ok(r) + } else { + app.save_in_place(path, crate::FormatChoices::default()) + } + }) +} diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/distort_ui.rs index 1f12b129f1..4987d8cc4d 100644 --- a/crates/ui-egui/src/distort_ui.rs +++ b/crates/ui-egui/src/distort_ui.rs @@ -22,6 +22,8 @@ use crate::canvas::{ToolEvent, ViewXform}; #[derive(Default)] pub struct Distort { pub liquify: Option, + /// Edit › Content-Aware Fill… (caf_ui). + pub caf: Option, pub puppet: Option, pub perspective: Option, pub vanishing: Option, @@ -33,13 +35,14 @@ pub struct Distort { impl Distort { pub fn active(&self) -> bool { - self.liquify.is_some() || self.puppet.is_some() || self.perspective.is_some() || self.vanishing.is_some() + self.liquify.is_some() || self.caf.is_some() || self.puppet.is_some() || self.perspective.is_some() || self.vanishing.is_some() } /// Short description for `ui.inspect`. pub fn describe(&self) -> Value { json!({ "liquify": self.liquify.as_ref().map(|d| d.describe()), + "contentAwareFill": self.caf.as_ref().map(|d| d.describe()), "puppet": self.puppet.as_ref().map(|p| p.describe()), "perspective": self.perspective.as_ref().map(|p| p.describe()), "vanishingPoint": self.vanishing.as_ref().map(|v| v.describe()), @@ -111,6 +114,9 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val "filter.filterGallery" if ui.is_some() && app.distort.gallery.is_some() => Some(crate::gallery_ui::control(app, ui.unwrap_or(&Value::Null))), "filter.liquify" if empty => Some(crate::liquify_ui::open(app, ctx).map(|_| json!({"liquify": app.distort.describe()["liquify"]}))), "filter.liquify" if ui.is_some() && app.distort.liquify.is_some() => Some(crate::liquify_ui::control(app, ui.unwrap_or(&Value::Null))), + "edit.contentAwareFill" if ui.is_some() && app.distort.caf.is_some() => Some(crate::caf_ui::control(app, ui.unwrap_or(&Value::Null))), + // `ui` addresses the workspace: closed, that is an error, not a fill with the defaults. + "edit.contentAwareFill" if ui.is_some() => Some(Err("Content-Aware Fill is not open".into())), "edit.puppetWarp" | "layer.smartObjects.puppetWarp" if empty => { Some(crate::puppet_ui::begin(app, ctx, id).map(|_| json!({"puppet": app.distort.describe()["puppet"]}))) } @@ -131,6 +137,10 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val /// Pointer events (document coordinates) while a mode is active. True when consumed. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { + if app.distort.caf.is_some() { + crate::caf_ui::pointer(app, ev, mods); + return true; + } if app.distort.liquify.is_some() { crate::liquify_ui::pointer(app, ev, mods); return true; @@ -164,6 +174,14 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } return true; } + if app.distort.caf.is_some() { + if enter(ctx) { + crate::caf_ui::commit(app); + } else if esc(ctx) { + crate::caf_ui::cancel(app); + } + return true; + } if app.distort.liquify.is_some() { if enter(ctx) { crate::liquify_ui::commit(app); @@ -248,6 +266,8 @@ pub fn drop_foreign(app: &mut PhotocraftApp) { app.distort.owner = current; } else if app.distort.owner != current { app.distort.liquify = None; + // Stops its background preview too; what Apply wrote stays, as with Cancel. + crate::caf_ui::cancel(app); app.distort.puppet = None; app.distort.perspective = None; app.distort.vanishing = None; @@ -256,9 +276,12 @@ pub fn drop_foreign(app: &mut PhotocraftApp) { } } -/// Full-window dialogs (Liquify, Filter Gallery). +/// Full-window dialogs (Liquify, Content-Aware Fill, Filter Gallery). pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { drop_foreign(app); + if app.distort.caf.is_some() { + crate::caf_ui::show(app, ctx); + } if app.distort.gallery.is_some() { crate::gallery_ui::show(app, ctx); } diff --git a/crates/ui-egui/src/doc_props_ui.rs b/crates/ui-egui/src/doc_props_ui.rs index fbdbc9a955..6a959c38d7 100644 --- a/crates/ui-egui/src/doc_props_ui.rs +++ b/crates/ui-egui/src/doc_props_ui.rs @@ -6,6 +6,7 @@ use egui::{Align2, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2}; use photocraft_doc::{ColorMode, Document, Layer, LayerId, SampleType}; use serde_json::{Value, json}; +use crate::props_layout::stacked_label; use crate::theme::Tokens; use crate::{PhotocraftApp, icons, widgets}; @@ -151,19 +152,19 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); ui.vertical(|ui| { ui.horizontal(|ui| { - field_label(ui, "W", 18.0); + stacked_label(ui, "W", &["W", "H"], 18.0, 4.0); if let Some(v) = committed_field(ui, "w", w as f32, lu) { run.extend(canvas_resize_params((w, h), Some(v), None, linked).map(|p| ("image.canvasSize".to_string(), p))); } - field_label(ui, "X", 22.0); + stacked_label(ui, "X", &["X", "Y"], 22.0, 4.0); dim_field(ui, "0 px"); }); ui.horizontal(|ui| { - field_label(ui, "H", 18.0); + stacked_label(ui, "H", &["W", "H"], 18.0, 4.0); if let Some(v) = committed_field(ui, "h", h as f32, lu) { run.extend(canvas_resize_params((w, h), None, Some(v), linked).map(|p| ("image.canvasSize".to_string(), p))); } - field_label(ui, "Y", 22.0); + stacked_label(ui, "Y", &["X", "Y"], 22.0, 4.0); dim_field(ui, "0 px"); }); }); @@ -342,6 +343,40 @@ mod tests { assert_eq!(st.history.entries().len(), undo, "no history step"); } + /// Horizontal centre of every single-letter label the panel drew, by letter. + fn letter_centres(h: &egui_kittest::Harness<'_, PhotocraftApp>) -> Vec<(String, f32)> { + h.output() + .shapes + .iter() + .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some(t) } else { None }) + .filter(|t| t.galley.text().chars().count() == 1) + .map(|t| (t.galley.text().to_string(), t.pos.x + t.galley.size().x * 0.5)) + .collect() + } + + /// #7314: the Canvas section's W over H (and X over Y) share a centre; a narrow "H" used to sit + /// flush right under the wider "W". + #[test] + fn canvas_size_labels_are_centred_on_each_other() { + use egui_kittest::Harness; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "white"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(320.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + properties(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(3); + let centres = letter_centres(&h); + let at = |l: &str| centres.iter().find(|(s, _)| s == l).map(|(_, x)| *x).unwrap_or_else(|| panic!("no {l} label in {centres:?}")); + assert!((at("W") - at("H")).abs() < 0.01, "W and H: {centres:?}"); + assert!((at("X") - at("Y")).abs() < 0.01, "X and Y: {centres:?}"); + } + #[test] fn document_dropdowns_map_to_live_mode_commands() { for id in MODES.iter().map(|m| m.2).chain(DEPTHS.iter().map(|d| d.2)) { diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index deaea4e783..0412c4fc67 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -521,10 +521,7 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bod ui.set_min_height(inner); body(app, ui, g, tab); } else { - // The pro Color field stretches to the group's height instead of a fixed 120 pt. - if t.pro && g == Group::Color && tab == 0 { - ui.data_mut(|d| d.insert_temp(crate::panels::color_field_fill_id(), inner)); - } + crate::panels::offer_color_field_fill(ui, t.pro, g, tab); // No scroll fade: it darkens real colours, swatches and previews at the edge // (#2726); the scroll bar already shows there is more. ui.spacing_mut().scroll.fade.strength = 0.0; diff --git a/crates/ui-egui/src/eraser_ui.rs b/crates/ui-egui/src/eraser_ui.rs index a6cd686d89..f92c3427e9 100644 --- a/crates/ui-egui/src/eraser_ui.rs +++ b/crates/ui-egui/src/eraser_ui.rs @@ -27,7 +27,7 @@ pub fn click(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { "tolerance": o.tolerance, "antiAlias": o.anti_alias, "contiguous": o.contiguous, - "sampleAllLayers": o.sample_all_layers, + "sampleAllLayers": o.sample_all.magic_eraser, "opacity": o.magic_eraser_opacity, }); let r = app.run("paint.magicEraser", p); @@ -98,7 +98,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo widgets::value_field(ui, &mut o.tolerance, 0.0..=255.0, "", 58.0); widgets::checkbox(ui, &mut o.anti_alias, tl!("Anti-alias")); widgets::checkbox(ui, &mut o.contiguous, tl!("Contiguous")); - widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers")); + widgets::checkbox(ui, &mut o.sample_all.magic_eraser, tl!("Sample All Layers")); widgets::vline(ui, 22.0); opt(ui, tl!("Opacity:")); widgets::value_field(ui, &mut o.magic_eraser_opacity, 1.0..=100.0, "%", 62.0); diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rs index 9367045aff..275221e050 100644 --- a/crates/ui-egui/src/export_dialog.rs +++ b/crates/ui-egui/src/export_dialog.rs @@ -907,7 +907,10 @@ pub fn quick_export_png(app: &mut PhotocraftApp) -> Result { let fmt = serde_json::to_value(prefs.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into()); let same = serde_json::to_value(prefs.quick_export_location).ok().is_some_and(|v| v == "sameFolder"); let saved = app.session.active().is_some_and(|d| d.path.is_some()); - if same && saved { + // Same Folder writes beside the document's file without asking, except when that would + // replace the file itself (a document opened from photo.png): then the save dialog asks, + // so replacing it is the user's choice (#6599). + if same && saved && !photocraft_engine::web_cmds::quick_export_target_is_own_file(&app.session) { return quick_export(app, json!({})); } let st = app.session.active().ok_or("no document")?; diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index 2a325ea2ce..bb827274ff 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -687,6 +687,53 @@ fn smart_source(app: &PhotocraftApp, id: u64) -> photocraft_doc::SmartSource { } } +#[test] +fn place_embedded_uses_the_single_file_picker_and_accepts_contents() { + let (mut app, open, _) = app(); + let ctx = egui::Context::default(); + assert!(menus::is_enabled(&app, "file.placeEmbedded")); + let source = photocraft_io::export(&app.session.active().unwrap().doc, "source.png", &Default::default()).unwrap().bytes; + let layers_before = app.session.active().unwrap().doc.layers.len(); + + // Cancel leaves the document alone and does not report an error. + menus::invoke(&mut app, &ctx, "file.placeEmbedded", json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + assert!(matches!(open.borrow().as_slice(), [(FileDialogRequest::Open { multiple: false, .. }, _)])); + answer(&open, None); + app.poll_file_dialog(&ctx, None); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers_before); + assert!(!app.ui.status_error, "{}", app.ui.status); + + // The Web picker returns the selected file's name and bytes instead of a filesystem path. + menus::invoke(&mut app, &ctx, "file.placeEmbedded", json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + answer(&open, Some(FileDialogAnswer::Contents("source.png".into(), source))); + app.poll_file_dialog(&ctx, None); + assert!(!app.ui.status_error, "{}", app.ui.status); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers.len(), layers_before + 1); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(layer.name, "source"); + assert_eq!(app.ui.transform.as_ref().and_then(|t| t.made), Some(crate::state::MadeLayer::Place)); + assert!(matches!( + &layer.content, + photocraft_doc::LayerContent::Smart(sm) + if matches!(&sm.source, photocraft_doc::SmartSource::Embedded { file_name, .. } if file_name == "source.png") + )); + + // Finish the successful placement before starting the next picker. + crate::transform_tool::commit(&mut app); + assert!(app.ui.transform.is_none()); + + // Invalid contents are reported without adding a layer. + menus::invoke(&mut app, &ctx, "file.placeEmbedded", json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + answer(&open, Some(FileDialogAnswer::Contents("broken.png".into(), b"not an image".to_vec()))); + app.poll_file_dialog(&ctx, None); + assert!(app.ui.status_error); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers_before + 1); +} + #[test] fn replace_contents_picks_a_file_for_every_instance() { let (mut app, open, _, ids) = smart_app(); @@ -791,6 +838,37 @@ fn quick_export_selected_layers_writes_separate_pngs_with_one_prompt() { assert!(!app.ui.status_error, "{}", app.ui.status); } +/// #6599: Quick Export as PNG with Location = Same Folder asks before replacing the document's +/// own file (a document opened from photo.png), and keeps writing beside a PSD without a prompt. +#[test] +fn same_folder_quick_export_asks_before_replacing_the_documents_own_file() { + let dir = std::env::temp_dir().join(format!("photocraft-quick-own-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let own = dir.join("photo.png").to_string_lossy().into_owned(); + std::fs::write(&own, b"original").unwrap(); + let (mut app, open, _) = app(); + app.run("prefs.set", json!({"path": "export.quickExportLocation", "value": "sameFolder"})).unwrap(); + app.session.active_mut().unwrap().path = Some(own.clone()); + let ctx = egui::Context::default(); + menus::invoke(&mut app, &ctx, "file.export.quickExportAsPng", Value::Null).unwrap(); + app.poll_file_dialog(&ctx, None); + assert_eq!(open.borrow().len(), 1, "the save dialog asks"); + assert_eq!(std::fs::read(&own).unwrap(), b"original", "nothing written before the answer"); + answer(&open, Some(FileDialogAnswer::SaveTo(own.clone()))); + app.poll_file_dialog(&ctx, None); + assert!(std::fs::read(&own).unwrap().starts_with(b"\x89PNG\r\n\x1a\n"), "replaced once confirmed: {}", app.ui.status); + + // Beside a PSD, Same Folder still writes without a prompt. + app.session.active_mut().unwrap().path = Some(dir.join("photo.psd").to_string_lossy().into_owned()); + std::fs::write(&own, b"earlier export").unwrap(); + menus::invoke(&mut app, &ctx, "file.export.quickExportAsPng", Value::Null).unwrap(); + app.poll_file_dialog(&ctx, None); + assert!(open.borrow().is_empty(), "no dialog"); + assert!(std::fs::read(&own).unwrap().starts_with(b"\x89PNG\r\n\x1a\n")); + std::fs::remove_dir_all(&dir).ok(); +} + #[test] fn cancelling_multi_layer_quick_export_writes_nothing() { let (mut app, open, written) = app(); @@ -963,3 +1041,90 @@ fn render_video_menu_asks_for_directory_and_writes_frames_only_after_confirmatio assert!(!app.file_dialog_open()); std::fs::remove_dir_all(&dir).unwrap(); } + +/// How many times each path was written, standing in for its size and modification time. +type Disk = Rc>>; + +/// Gives `app` file stamps from a fake disk that its own writes update too. +fn on_disk(app: &mut PhotocraftApp) -> Disk { + let disk = Disk::default(); + let (read, wrote) = (disk.clone(), disk.clone()); + app.services.file_stamp = Some(Box::new(move |path| read.borrow().get(path).map(|&n| crate::FileStamp { len: n, modified: None }))); + let mut write = app.services.write.take().unwrap(); + app.services.write = Some(Box::new(move |path, bytes| { + write(path, bytes)?; + *wrote.borrow_mut().entry(path.to_string()).or_default() += 1; + Ok(()) + })); + disk +} + +fn changed_by_another_app(disk: &Disk, path: &str) { + *disk.borrow_mut().entry(path.to_string()).or_default() += 1; +} + +fn disk_prompt(app: &PhotocraftApp) -> Option<&crate::state::Dialog> { + app.ui.dialogs.iter().find(|d| crate::disk_change_prompt::owns(&d.fields)) +} + +#[test] +fn save_asks_before_replacing_a_file_another_app_changed() { + let ctx = egui::Context::default(); + let (mut app, _open, written) = app(); + let disk = on_disk(&mut app); + changed_by_another_app(&disk, "/pics/a.psd"); + app.opened_from("/pics/a.psd"); + app.run("layer.new.layer", json!({})).unwrap(); + // Unchanged on disk: Save writes at once. + menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap(); + assert_eq!(*written.borrow(), ["/pics/a.psd"]); + assert!(disk_prompt(&app).is_none()); + + // Our own save isn't a change; another app's write after it is. + changed_by_another_app(&disk, "/pics/a.psd"); + app.run("layer.new.layer", json!({})).unwrap(); + let r = menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap(); + assert_eq!(r["confirmationPending"], true); + assert_eq!(written.borrow().len(), 1, "nothing is written before the answer"); + let prompt = disk_prompt(&app).expect("Save asks first"); + assert!(prompt.fields["message"].as_str().unwrap().contains("a.psd")); + + // Cancel leaves the file and the unsaved document alone. + let id = prompt.id; + app.ui.close_dialog(id); + assert_eq!(written.borrow().len(), 1); + assert!(app.session.active().unwrap().is_dirty()); + + // Replace writes it, and the next Save doesn't ask again. + let id = menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap()["dialog"].as_u64().unwrap(); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(written.borrow().len(), 2); + assert!(!app.session.active().unwrap().is_dirty()); + app.run("layer.new.layer", json!({})).unwrap(); + menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap(); + assert_eq!(written.borrow().len(), 3); + assert!(disk_prompt(&app).is_none()); +} + +#[test] +fn save_of_a_flat_file_asks_after_the_dialog_when_another_app_changed_it() { + let ctx = egui::Context::default(); + // Lowercase: the Save dialog lowercases a typed extension by default. + let path = "/pics/My image.jpg"; + let (mut app, open, written) = jpeg_app(None, false); + let disk = on_disk(&mut app); + changed_by_another_app(&disk, path); + app.opened_from(path); + app.run("image.adjustments.invert", json!({})).unwrap(); + changed_by_another_app(&disk, path); + menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + answer(&open, Some(FileDialogAnswer::SaveTo(path.into()))); + app.poll_file_dialog(&ctx, None); + assert!(written.borrow().is_empty(), "the changed file is not replaced before the answer"); + let id = disk_prompt(&app).expect("Save asks first").id; + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(*written.borrow(), [path]); + assert!(!app.session.active().unwrap().is_dirty()); + assert_eq!(app.session.journal.last().map(|s| s.0.as_str()), Some("file.save"), "still recorded as a plain Save"); +} diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 13105a321d..1cf61e98d3 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -33,6 +33,15 @@ pub enum DropTarget { Elsewhere, } +/// A file dropped on the canvas, waiting its turn to be placed. +pub(crate) enum DropPlace { + /// Dropped onto the window (desktop): read from its path, or through egui. + File(egui::DroppedFileHandle), + /// Read by the shell itself (the browser reads dropped files asynchronously): its name and + /// contents, delivered through [`Services::place_inbox`](crate::Services::place_inbox). + Bytes(String, Vec), +} + /// `warnings` from an import, plus one for each font family the active document's type uses that /// isn't installed (#4559): Photoshop warns about missing fonts as a file opens, and the CLI and /// automation already report them; the type would otherwise silently render in a fallback face. @@ -89,6 +98,8 @@ impl PhotocraftApp { && !st.source_read_only { st.path = Some(path.to_string()); + let doc = st.doc.id; + self.remember_stamp(doc, path); } self.push_recent(path); } @@ -105,6 +116,9 @@ impl PhotocraftApp { /// Read and open the file at `path` (see [`open_file`](Self::open_file)). #[cfg(not(target_arch = "wasm32"))] pub fn open_path(&mut self, path: &str) -> Result, String> { + if self.show_if_open(path) { + return Ok(Vec::new()); + } // Documents opening in the background are read on the worker too (a 2 GB PSB read // would block the window). Preset files (brushes, gradients) go the usual way. let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); @@ -131,6 +145,10 @@ impl PhotocraftApp { let batch = crate::jobs_ui::begin_batch(self); let mut opened = 0; for (seq, abs) in paths.iter().enumerate() { + // Not a member of the set: its tab is already in place. + if self.show_if_open(abs) { + continue; + } let order = crate::jobs_ui::OpenOrder { batch, seq }; let pending = self.jobs.opens.len(); match self.open_path(abs) { @@ -150,6 +168,26 @@ impl PhotocraftApp { opened } + /// Show the document already open from the file at `path`, or its tab while it is still + /// opening in the background, as Photoshop does, rather than open a second copy bound to the + /// same file (#6598). True when there was one. + pub(crate) fn show_if_open(&mut self, path: &str) -> bool { + let canon = canonical(path); + let same = |p: &str| same_file(p, path, canon.as_deref()); + if let Some(i) = self.session.documents().iter().position(|d| d.path.as_deref().is_some_and(same)) { + self.session.set_active(i); + self.jobs.focus = None; + } else if let Some(o) = self.jobs.opens.iter().find(|o| o.path.as_deref().is_some_and(|p| !is_template(p) && same(p))) { + // A template still loading opens as another Untitled, as it does once loaded. + self.jobs.focus = Some(o.job); + } else { + return false; + } + // The document count didn't change, so the Home screen wouldn't give way by itself. + self.ui.chrome.home = None; + true + } + /// Show "Couldn't open : " as an error (status bar + notice). pub fn open_failed(&mut self, name: &str, err: &str) { self.failed({ @@ -182,7 +220,7 @@ impl PhotocraftApp { for f in files { let name = dropped_name(&f); if target == DropTarget::Canvas && !crate::preset_files_ui::is_preset_file(&name) { - self.drop_places.push_back(f); + self.drop_places.push_back(DropPlace::File(f)); continue; } match self.open_dropped_file(&f, &name, slot) { @@ -193,6 +231,24 @@ impl PhotocraftApp { } } + /// Which of the files called `names`, dropped onto the window just now, are placed on the + /// active document's canvas rather than opened, for a shell that reads dropped files itself + /// (the browser reads them asynchronously, so the web shell can't hand them to + /// [`open_dropped`](Self::open_dropped)). It delivers those through + /// [`Services::place_inbox`](crate::Services::place_inbox) and the rest through + /// [`Services::inbox`](crate::Services::inbox). The pointer comes from + /// [`Services::cursor_pos`](crate::Services::cursor_pos). As with a desktop canvas drop, a Free + /// Transform still open is applied first (#4833). + pub fn dropped_on_canvas(&mut self, ctx: &egui::Context, names: &[String]) -> Vec { + let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx)); + let canvas = self.drop_target(ctx, at) == DropTarget::Canvas; + let places: Vec = names.iter().map(|n| canvas && !crate::preset_files_ui::is_preset_file(n)).collect(); + if places.contains(&true) && self.ui.transform.is_some() { + crate::transform_tool::commit(self); + } + places + } + /// Where a drop at `at` lands. Over a window or dialog it's neither the canvas nor the tabs. pub(crate) fn drop_target(&self, ctx: &egui::Context, at: Option) -> DropTarget { let Some(p) = at.filter(|p| ctx.layer_id_at(*p).is_none_or(|l| l.order == egui::Order::Background)) else { @@ -230,11 +286,20 @@ impl PhotocraftApp { /// transform is in progress (so several files are placed and transformed one after another). pub(crate) fn place_next_dropped(&mut self, ctx: &egui::Context) { while self.ui.transform.is_none() { - let Some(f) = self.drop_places.pop_front() else { return }; - let placed = if f.path().is_absolute() { - self.run("file.placeEmbedded", serde_json::json!({"path": f.path().to_string_lossy()})) - } else { - crate::read_dropped(&*f).and_then(|bytes| self.place_bytes(&dropped_name(&f), bytes, None)) + let Some(next) = self.drop_places.pop_front() else { return }; + let (name, placed) = match next { + DropPlace::File(f) if f.path().is_absolute() => { + (dropped_name(&f), self.run("file.placeEmbedded", serde_json::json!({"path": f.path().to_string_lossy()}))) + } + DropPlace::File(f) => { + let name = dropped_name(&f); + let placed = crate::read_dropped(&*f).and_then(|bytes| self.place_bytes(&name, bytes, None)); + (name, placed) + } + DropPlace::Bytes(name, bytes) => { + let placed = self.place_bytes(&name, bytes, None); + (name, placed) + } }; match placed { Ok(_) => { @@ -242,7 +307,7 @@ impl PhotocraftApp { self.ui.status = e; } } - Err(e) => self.failed(crate::i18n::fmt(tl!("Couldn't place {name}: {error}"), &[("name", &dropped_name(&f)), ("error", &e)])), + Err(e) => self.failed(crate::i18n::fmt(tl!("Couldn't place {name}: {error}"), &[("name", &name), ("error", &e)])), } } } @@ -336,5 +401,25 @@ fn absolute(p: &str) -> String { p.to_string() } +/// `path` with symlinks, `.` and `..` and (on case-insensitive volumes) letter case resolved; +/// `None` when it can't be (a missing file). +#[cfg(not(target_arch = "wasm32"))] +fn canonical(path: &str) -> Option { + std::fs::canonicalize(path).ok() +} + +#[cfg(target_arch = "wasm32")] +fn canonical(_path: &str) -> Option { + None +} + +/// Whether an open document's path `p` names the file at `path` (`canon`: its [`canonical`] +/// form). The cheap comparisons come first: `p` is resolved on disk only when they fail, so an +/// open of a file that isn't open costs one resolution per document. A file moved or deleted +/// since it was opened only matches its old path as written. +fn same_file(p: &str, path: &str, canon: Option<&std::path::Path>) -> bool { + p == path || canon.is_some_and(|c| std::path::Path::new(p) == c || canonical(p).is_some_and(|q| q == c)) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 4d6581cd6d..00db3ef96e 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -173,6 +173,35 @@ fn the_web_opens_every_selected_file() { assert!(app.ui.notices.iter().any(|n| n.error && n.title.contains("broken.png")), "{:?}", app.ui.notices); } +/// #5749: the web shell reads dropped files itself, so it asks where they landed: image files +/// dropped on the canvas are placed from their bytes, presets and drops elsewhere are opened. +#[test] +fn web_drops_onto_the_canvas_are_placed_from_their_bytes() { + let ctx = egui::Context::default(); + let mut app = app_with_canvas(); + let names = vec!["photo.png".to_string(), "brushes.abr".to_string()]; + // No pointer known: nothing is placed. + assert_eq!(app.dropped_on_canvas(&ctx, &names), [false, false]); + let at = Rc::new(std::cell::Cell::new(egui::pos2(400.0, 300.0))); + let reported = at.clone(); + app.services.cursor_pos = Some(Box::new(move |_: &egui::Context| Some(reported.get()))); + assert_eq!(app.dropped_on_canvas(&ctx, &names), [true, false]); + at.set(egui::pos2(20.0, 20.0)); + assert_eq!(app.dropped_on_canvas(&ctx, &names), [false, false], "off the canvas: opened"); + let layers = layer_count(&app); + app.drop_places.push_back(crate::file_open::DropPlace::Bytes("photo.png".into(), png_bytes(4, 3))); + app.drop_places.push_back(crate::file_open::DropPlace::Bytes("bad.png".into(), b"bad".to_vec())); + app.place_next_dropped(&ctx); + assert_eq!(layer_count(&app), layers + 1); + assert_eq!(app.ui.transform.as_ref().and_then(|t| t.made), Some(crate::state::MadeLayer::Place)); + crate::transform_tool::commit(&mut app); + // The undecodable one is reported, not placed. + app.place_next_dropped(&ctx); + assert_eq!(layer_count(&app), layers + 1); + assert!(app.ui.notices.iter().any(|n| n.error && n.title.contains("bad.png")), "{:?}", app.ui.notices); + assert!(app.drop_places.is_empty()); +} + #[test] fn pcraft_documents_save_in_place_but_flat_files_ask() { let (mut app, written) = app_with(vec![None]); @@ -928,3 +957,61 @@ fn opening_type_in_a_missing_font_warns() { // The importer's own warning for the same font isn't doubled. assert_eq!(app.open_bytes("warned.psd", b"x").unwrap(), vec![warning]); } + +/// #6598: opening a file that is already open shows its document, as Photoshop does, rather than +/// a second copy bound to the same file (saving one would overwrite the other). The path is +/// compared as the file it names: another spelling of it, a symlink to it or, with background +/// opens, a file still opening finds the same tab. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn opening_an_open_file_again_shows_its_tab() { + let (dir, paths) = files("already-open", &["a.psd", "b.psd"], b"x"); + let (a, b) = (&paths[0], &paths[1]); + let (mut app, _) = app_with(Vec::new()); + app.open_path(a).unwrap(); + app.open_path(b).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.chrome.home = Some(2); + // Open Recent, File › Open, a drop: all go through `open_path`. + #[allow(unused_mut)] + let mut spellings = vec![a.clone(), dir.join(".").join("a.psd").to_string_lossy().into_owned()]; + #[cfg(unix)] + { + let link = dir.join("link.psd"); + std::os::unix::fs::symlink(a, &link).unwrap(); + spellings.push(link.to_string_lossy().into_owned()); + } + for again in spellings { + app.session.set_active(1); + app.ui.chrome.home = Some(2); + app.open_path(&again).unwrap(); + assert_eq!(doc_names(&app), ["a.psd", "b.psd"], "{again}"); + assert_eq!(app.session.active_index(), Some(0), "{again}"); + assert_eq!(app.ui.chrome.home, None, "the Home screen gives way to the document"); + } + assert!(app.session.documents()[1].is_dirty(), "b keeps its unsaved changes"); + // A set holding an open file opens only the others. + let (dir2, more) = files("already-open-set", &["c.psd"], b"x"); + assert_eq!(app.open_paths(&[b.clone(), more[0].clone()]), 1); + assert_eq!(doc_names(&app), ["a.psd", "b.psd", "c.psd"]); + // In the background: an open document, then a file still opening, show their tabs. + app.background_jobs = true; + app.open_path(a).unwrap(); + assert!(app.jobs.opens.is_empty()); + assert_eq!(app.session.active_index(), Some(0)); + let (dir3, late) = files("already-open-bg", &["d.psd"], b"x"); + app.open_path(&late[0]).unwrap(); + let job = app.jobs.opens[0].job; + app.jobs.focus = None; + app.open_path(&late[0]).unwrap(); + assert_eq!(app.jobs.opens.len(), 1, "one tab for the file still opening"); + assert_eq!(app.jobs.focus, Some(job)); + // A template still loading opens again as another Untitled, as it does once loaded. + let (dir4, template) = files("already-open-template", &["e.psdt"], b"x"); + app.open_path(&template[0]).unwrap(); + app.open_path(&template[0]).unwrap(); + assert_eq!(app.jobs.opens.len(), 3, "two Untitleds from the template"); + for d in [dir, dir2, dir3, dir4] { + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 3f87f6339c..14a512c288 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -76,7 +76,7 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V app.session.active()?; json!({"dialog": open_print(app)}) } - "file.printOneCopy" if app.session.file_menu.last_print.is_none() => { + "file.printOneCopy" if photocraft_engine::print_cmds::last_print(&app.session).is_none() => { app.session.active()?; json!({"dialog": open_print(app)}) } @@ -168,11 +168,12 @@ pub fn ok_label(f: &Map) -> Option<&'static str> { } } -pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { +/// The body of Save for Web or Print (dialog `id`). +pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { if f.contains_key("__web") { web_body(app, ui, f); } else { - print_body(app, ui, f); + print_body(app, ui, f, id); } } @@ -729,7 +730,8 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { // Asked once per opening: the Printer menu lists what the spooler knows now. let printers = app.session.execute("file.printers", json!({})).unwrap_or_default(); f.insert("__systemPrinters".into(), printers["printers"].clone()); - if let Some(Value::Object(m)) = app.session.file_menu.last_print.clone() { + // The settings of the last print, also from an earlier session (#7410). + if let Some(Value::Object(m)) = photocraft_engine::print_cmds::last_print(&app.session) { f.extend(m); } for (k, v) in [ @@ -864,7 +866,22 @@ fn print_paper_controls(ui: &mut egui::Ui, f: &mut Map) { } } -fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { +/// Save as PDF › Browse…: where to write the PDF, into Print dialog `id` once the file dialog +/// answers. Without it the only way to save a PDF was to type a full path (#5328). +fn browse_pdf(app: &mut PhotocraftApp, id: u64, suggested: &str) { + let r = app.pick_save(suggested, move |app, path| { + let d = app.ui.dialog_mut(id).ok_or("the dialog was closed")?; + d.fields.insert("output".into(), json!(path)); + Ok(Value::Null) + }); + if let Err(e) = r + && e != crate::file_dialog::CANCELLED + { + app.ui.status = e; + } +} + +fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { let t = Tokens::get(ui.ctx()); let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; // PDF exports and previews retain editable paper on Windows too. Only a real native @@ -884,6 +901,7 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) -> Result { @@ -1452,6 +1478,45 @@ mod tests { assert!(params(f).get("__printers").is_none()); } + /// #7410: File › Print opens with the settings of the last print, also those remembered from + /// an earlier session (the preferences), before anything was printed in this one. + #[test] + fn print_dialog_opens_with_the_settings_remembered_from_an_earlier_session() { + let (mut app, _) = app(); + app.session.prefs.edit(|p| { + p.dialogs.insert( + photocraft_engine::print_cmds::REMEMBERED.into(), + json!({"paper": "a5", "scale": 50, "orientation": "landscape", "intent": "perceptual"}), + ); + }); + let id = open_print(&mut app); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!((&f["paper"], &f["scale"], &f["orientation"], &f["intent"]), (&json!("a5"), &json!(50), &json!("landscape"), &json!("perceptual"))); + assert_eq!(f["copies"], 1, "what wasn't remembered keeps its default"); + } + + /// #5328: Save as PDF has Browse…, which fills the field from a Save dialog (suggesting the + /// document's name as a PDF) rather than needing a typed path. + #[test] + fn save_as_pdf_browse_fills_the_output_from_a_save_dialog() { + use crate::file_dialog::{FileDialogAnswer, FileDialogRequest}; + use egui_kittest::{Harness, kittest::Queryable}; + let out = std::env::temp_dir().join(format!("pc-printui-browse-{}", std::process::id())).to_string_lossy().into_owned(); + let (show, asked) = crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo(out.clone()))]); + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(show), ..Default::default() }) + }); + h.state_mut().run("file.new", json!({"width": 120, "height": 80, "name": "poster"})).unwrap(); + let id = open_print(h.state_mut()); + h.run_steps(3); + h.get_by_label("Browse…").click(); + h.run_steps(4); + assert!(matches!(asked.borrow().as_slice(), [FileDialogRequest::Save { suggested }] if suggested.ends_with("poster.pdf")), "{:?}", asked.borrow()); + // A name chosen without an extension gets the suggested one. + assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["output"], json!(format!("{out}.pdf"))); + } + #[test] fn print_dialog_does_not_inherit_scripted_send_override() { for send in [false, true] { @@ -1656,7 +1721,7 @@ mod web_playback_tests { let doc = web_frame_document(&app.session.active().unwrap().doc, Some(frame)).unwrap(); let (proxy, _, _) = web_cmds::web_document(&doc, &json!({"width":16,"height":12}), &settings).unwrap(); let pixels = photocraft_compose::flatten(&proxy); - let optimized = web_cmds::optimize(&pixels.px, 16, photocraft_geom::Rect::new(0, 0, 16, 12), &settings, None, None, 72.0, true).unwrap(); + let optimized = web_cmds::optimize(&pixels.px, 16, photocraft_geom::Rect::new(0, 0, 16, 12), &settings, None, None, None, 72.0, true).unwrap(); assert_eq!(&optimized.preview[..4], expected, "depth={depth} frame={frame}"); } } diff --git a/crates/ui-egui/src/file_ui/web_preview.rs b/crates/ui-egui/src/file_ui/web_preview.rs index a9ee7a933c..b603584573 100644 --- a/crates/ui-egui/src/file_ui/web_preview.rs +++ b/crates/ui-egui/src/file_ui/web_preview.rs @@ -60,8 +60,8 @@ pub fn prepare_table(app: &PhotocraftApp, f: &mut Map) -> Result< let (doc, _, _) = web_cmds::web_document(&st.doc, &proxy, &settings).map_err(|e| e.to_string())?; f.insert("__paletteApproximate".into(), json!(scale < 1.0)); let buf = photocraft_compose::flatten(&doc); - let mut optimized = - web_cmds::optimize(&buf.px, doc.size.width as usize, doc.bounds(), &settings, None, None, doc.resolution_dpi, false).map_err(|e| e.to_string())?; + let mut optimized = web_cmds::optimize(&buf.px, doc.size.width as usize, doc.bounds(), &settings, None, None, None, doc.resolution_dpi, false) + .map_err(|e| e.to_string())?; // Tiny transparent features may disappear in the proxy; keep room for their index. if settings.transparency { optimized.color_table.truncate(255); @@ -137,7 +137,7 @@ pub fn optimized(ui: &mut egui::Ui, key: egui::Id, signature: &str, p: &Value, p } else { let settings = WebSettings::from_params(&base, "preview").map_err(|e| e.to_string())?; let encoded = Arc::new( - web_cmds::optimize(px, w as usize, photocraft_geom::Rect::new(0, 0, w as i32, h as i32), &settings, None, None, 72.0, true) + web_cmds::optimize(px, w as usize, photocraft_geom::Rect::new(0, 0, w as i32, h as i32), &settings, None, None, None, 72.0, true) .map_err(|e| e.to_string())?, ); ui.data_mut(|d| d.insert_temp(key, (signature, encoded.clone()))); diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index fa7cb9524d..a908df5eba 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -7,6 +7,8 @@ use std::sync::Arc; use photocraft_doc::Document; +use photocraft_engine::color_cmds::ColorSettings; +use photocraft_engine::installed_profiles::InstalledProfile; use serde_json::{Map, Value, json}; use crate::PhotocraftApp; @@ -110,7 +112,8 @@ pub fn parse_spec(spec: &str) -> Vec { Kind::Color(crate::color_picker_ui::parse_hex(default)) } else if v == "doc" { Kind::Document - } else if v == "json" || v.starts_with("layer id") || v.starts_with('[') || v.starts_with('{') { + } else if v == "json" || v.starts_with("layer id") || v.starts_with('[') || v.starts_with('{') || v.trim_end_matches('?') == "index|name" { + // `index|name`: a reference (an alpha channel…) the dialog sets through another control. Kind::Json } else if let Some(n) = v.strip_prefix("int[").and_then(|r| r.strip_suffix(']')).and_then(|n| n.parse().ok()) { Kind::Grid(n) @@ -200,6 +203,9 @@ fn is_pixel_param_of(command: &str, key: &str) -> bool { /// Sharpen, Sharpen More, Sharpen Edges, Find Edges, Emboss and Despeckle use fixed one-pixel /// kernels with no size parameter, so a proxy changes their look: edges average away, making /// the sharpening and edge detection invisible. These must preview at full resolution (#3929). +/// +/// Content-Aware Fill searches for matching patches, and the matches found on a reduced copy +/// differ from those found at full size, so its preview would not show what OK writes (#6530). const FULL_RESOLUTION_PREVIEW: &[&str] = &[ "filter.distort.ripple", "filter.stylize.diffuse", @@ -222,6 +228,7 @@ const FULL_RESOLUTION_PREVIEW: &[&str] = &[ "filter.stylize.findEdges", "filter.stylize.emboss", "filter.noise.despeckle", + "edit.contentAwareFill", ]; /// Whether `command` with `params` previews at full resolution: [`FULL_RESOLUTION_PREVIEW`], every @@ -279,6 +286,9 @@ pub const PREVIEWED: &[&str] = &[ "layer.matting.colorDecontaminate", "layer.layerStyle.scaleEffects", "type.warpText", + // The preview shows the image through the chosen profile, as Photoshop's Preview does. + "edit.assignProfile", + "edit.convertToProfile", ]; pub fn has_dialog(command: &str) -> bool { @@ -293,8 +303,6 @@ pub fn has_dialog(command: &str) -> bool { command, "image.trim" | "select.refineEdge" - | "edit.assignProfile" - | "edit.convertToProfile" | "view.proofSetup" | "layer.layerStyle.globalLight" | "image.mode.colorTable" @@ -388,6 +396,11 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map Option { if crate::blur_pins::handles(command) { crate::blur_pins::init(app, &mut fields); } + if command == LENS_BLUR { + lens_blur_channels(app, &mut fields); + } if parse_spec(spec.params).iter().any(|p| p.kind == Kind::Document) { // The document picker lists every open document (params refer to them by index). let names: Vec = app.session.documents().iter().map(|d| d.doc.name.clone()).collect(); @@ -556,6 +572,10 @@ pub(crate) fn source_label(key: &str) -> String { if key == "localized" { return "Localized Color Clusters".into(); } + // Convert to Profile's, Proof Setup's…: spelled out, as in Photoshop (not "Bpc"). + if key == "bpc" { + return "Black Point Compensation".into(); + } // A name that already reads as text ("iPhone 14 Pro Max", "Web 1920") is not camelCase. if key.contains(' ') { return key.to_string(); @@ -583,9 +603,63 @@ fn uses_logarithmic_slider(min: f32, max: f32) -> bool { min > 0.0 && max / min > 500.0 } +const LENS_BLUR: &str = "filter.blur.lensBlur"; + +/// Lens Blur's Depth Map Source lists the document's alpha channels after None, Transparency +/// and Layer Mask, as in Photoshop (#7400): their names go to `__channels`. A `channel` source +/// without a channel this document has (references aren't remembered) opens as None. +fn lens_blur_channels(app: &PhotocraftApp, f: &mut Map) { + let names: Vec = app.session.active().map(|d| d.doc.channels.iter().map(|c| c.name.clone()).collect()).unwrap_or_default(); + let known = f.get("depthChannel").and_then(|v| channel_index(v, &names)).is_some(); + if f.get("depthMap").and_then(Value::as_str) == Some("channel") && !known { + f.insert("depthMap".into(), json!("none")); + f.remove("depthChannel"); + } + f.insert("__channels".into(), json!(names)); +} + +/// Lens Blur's Source menu entry for the alpha channel at `index`. By index, not name: two +/// channels may share a name, and each must be choosable. +fn channel_choice(index: usize) -> String { + format!("channel:{index}") +} + +/// The alpha channel `v` names (an index, or a name: the first channel so named), as the +/// engine reads `depthChannel`. +fn channel_index(v: &Value, names: &[String]) -> Option { + match v { + Value::Number(n) => n.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < names.len()), + Value::String(name) => names.iter().position(|n| n == name), + _ => None, + } +} + /// Schema dialogs whose `profile` menu lists the installed profiles after the built-ins. const PROFILE_DIALOGS: &[&str] = &["edit.assignProfile", "edit.convertToProfile", "view.proofSetup"]; +/// Which installed profiles a menu of `cmd` lists after its built-ins, if it lists any: every +/// destination profile for the `profile` menus of [`PROFILE_DIALOGS`], and for Color Settings' +/// working spaces those of that space, as Photoshop lists them (#6323). An RGB working space is a +/// display or colour-space profile, not a scanner's or a printer's. +fn installed_filter(cmd: &str, key: &str) -> Option bool> { + use photocraft_cms::{ColorSpace, ProfileClass}; + match (cmd, key) { + (c, "profile") if PROFILE_DIALOGS.contains(&c) => Some(|_| true), + ("edit.colorSettings", "workingRgb") => { + Some(|i| i.color_space == ColorSpace::Rgb && matches!(i.class, ProfileClass::Display | ProfileClass::ColorSpace)) + } + ("edit.colorSettings", "workingCmyk") => Some(|i| i.color_space == ColorSpace::Cmyk), + ("edit.colorSettings", "workingGray") => Some(|i| i.color_space == ColorSpace::Gray), + _ => None, + } +} + +/// The `installed` profiles a menu of `cmd` lists (see [`installed_filter`]), by path and description. +fn installed_choices(cmd: &str, key: &str, installed: &[InstalledProfile]) -> Vec<(String, String)> { + let Some(fits) = installed_filter(cmd, key) else { return Vec::new() }; + installed.iter().filter(|i| i.is_destination() && fits(i)).map(|i| (i.path.clone(), i.description.clone())).collect() +} + /// Commands whose `angle` is a direction in document angles (counter-clockwise from three /// o'clock): a light or a blur direction, edited on a dial as in Photoshop's Motion Blur, Emboss /// and Global Light (#3152). Rotation amounts (Twirl, Rotate Arbitrary, Crop, Lens Correction, @@ -607,6 +681,8 @@ fn uses_angle_dial(command: &str, key: &str) -> bool { /// eyedropper like Photoshop's. While armed, the next click on the image writes the merged /// composite colour into the `color` field (the same sampler the Color Picker uses). const REPLACE_COLOR: &str = "image.adjustments.replaceColor"; +/// What OK on an edited smart filter runs (`smart_ui::confirm_command`); its preview too. +const SMART_FILTER_SET_PARAMS: &str = "layer.smartFilter.setParams"; const COLOR_EYEDROPPER: &str = "__colorEyedropper"; fn color_eyedropper_owns(f: &Map) -> bool { @@ -637,6 +713,49 @@ pub(crate) fn color_eyedropper_sample(app: &mut PhotocraftApp, x: f64, y: f64) - true } +/// The Color Picker of Replace Color's Result swatch writes here (#6278). +const RESULT_PICKED: &str = "__resultPicked"; +/// The Result the picker opened on: a picked colour that differs from it sets the sliders. +const RESULT_FROM: &str = "__resultFrom"; + +/// Replace Color's Result swatch (#6278), as in Photoshop: the sampled colour after the Hue, +/// Saturation and Lightness shift. Picking a Result in its Color Picker sets the three sliders so +/// the sampled colour becomes it. +fn replace_color_result(ui: &mut egui::Ui, f: &mut Map) { + use photocraft_algo::tone; + let t = Tokens::get(ui.ctx()); + let from = f.get("color").and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex).unwrap_or([0.0; 3]); + let picked = f.get(RESULT_PICKED).and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex); + if let Some(to) = picked + && f.get(RESULT_PICKED) != f.get(RESULT_FROM) + { + let (hue, saturation, lightness) = tone::replace_color_shift(from, to); + for (key, v) in [("hue", hue), ("saturation", saturation), ("lightness", lightness)] { + f.insert(key.into(), json!(v.round())); + } + f.remove(RESULT_PICKED); + f.remove(RESULT_FROM); + } + let num = |key: &str| f.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32; + let rgb = tone::replace_color_result(from, num("hue"), num("saturation"), num("lightness")); + let bytes = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + let name = tl!("Result"); + let mut clicked = false; + ui.horizontal(|ui| { + ui.label(egui::RichText::new(name).color(t.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + clicked = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), name).clicked(); + ui.label(egui::RichText::new(crate::color_picker_ui::hex(rgb)).color(t.text_dim).monospace()); + }); + }); + if clicked { + let hex = json!(crate::color_picker_ui::hex(rgb)); + f.insert(RESULT_PICKED.into(), hex.clone()); + f.insert(RESULT_FROM.into(), hex); + crate::color_picker_ui::request_field(f, RESULT_PICKED, &crate::color_picker_ui::title_for(name)); + } +} + /// Dialog body for filter commands. pub fn body(ui: &mut egui::Ui, f: &mut Map) { let t = Tokens::get(ui.ctx()); @@ -696,7 +815,7 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { ui.add_space(4.0); } else { // A double-click on the slider puts it back to the filter's default. - let gestures = crate::widgets::RowGestures { reset: Some(default), wheel_step: None }; + let gestures = crate::widgets::RowGestures { reset: Some(default), wheel_step: None, ..Default::default() }; crate::widgets::slider_row_with(ui, &label(&p.key), &mut v, min..=max, unit, None, gestures); } }); @@ -711,14 +830,29 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { let mut cur = f.get(&p.key).and_then(Value::as_str).unwrap_or(initial).to_string(); let labels: Vec = options.iter().map(|o| choice_label(o)).collect(); let mut opts: Vec<(String, &str)> = options.iter().cloned().zip(labels.iter().map(String::as_str)).collect(); - // Like Photoshop, the profile menus also list every profile installed in - // the system (printer and paper profiles), by description. - let installed = if p.key == "profile" && PROFILE_DIALOGS.contains(&cmd.as_str()) { - photocraft_engine::installed_profiles::installed().into_iter().filter(|i| i.is_destination()).collect() + // Lens Blur's Source: each alpha channel by its name, in place of `channel`. + let depth = cmd == LENS_BLUR && p.key == "depthMap"; + let names: Vec = if depth { + f.get("__channels").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect() } else { Vec::new() }; - opts.extend(installed.iter().map(|i| (i.path.clone(), i.description.as_str()))); + let channels: Vec = (0..names.len()).map(channel_choice).collect(); + if depth { + opts.retain(|(v, _)| v != "channel"); + opts.extend(channels.iter().cloned().zip(names.iter().map(String::as_str))); + if cur == "channel" + && let Some(i) = f.get("depthChannel").and_then(|v| channel_index(v, &names)) + { + cur = channel_choice(i); + } + } + // Like Photoshop, the profile menus also list the profiles installed in the + // system (printer and paper profiles, press conditions), by description. + let lists_installed = installed_filter(&cmd, &p.key).is_some(); + let installed = + if lists_installed { installed_choices(&cmd, &p.key, &photocraft_engine::installed_profiles::installed()) } else { Vec::new() }; + opts.extend(installed.iter().map(|(path, description)| (path.clone(), description.as_str()))); // Assign Profile: only what the document's colour mode can take (#4951). if p.key == "profile" && let Some(allowed) = f.get("__profiles").and_then(Value::as_array) @@ -728,10 +862,16 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { // A profile given by path that isn't listed (typed by an agent, or spelled with // different case) still shows, by its file name, instead of a blank menu. let stem = std::path::Path::new(&cur).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - if p.key == "profile" && PROFILE_DIALOGS.contains(&cmd.as_str()) && !opts.iter().any(|(v, _)| *v == cur) { + if lists_installed && !opts.iter().any(|(v, _)| *v == cur) { opts.push((cur.clone(), stem.as_str())); } crate::widgets::dropdown(ui, &format!("flt-{cmd}-{}", p.key), &mut cur, &opts, 170.0); + if let Some(i) = cur.strip_prefix("channel:").filter(|_| depth).and_then(|i| i.parse::().ok()) { + f.insert("depthChannel".into(), json!(i)); + cur = "channel".into(); + } else if depth { + f.remove("depthChannel"); + } f.insert(p.key.clone(), json!(cur)); }); } @@ -832,6 +972,9 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { } } } + if cmd == REPLACE_COLOR { + replace_color_result(ui, f); + } // Read-only context the dialog opener supplies (e.g. the monitor profile in use). if let Some(note) = f.get("__note").and_then(Value::as_str) { ui.add_space(4.0); @@ -875,12 +1018,23 @@ pub fn preview_document_with( k: u32, cancel: Option<&photocraft_engine::jobs::JobCtx>, ) -> Option { - preview_document_for_target(doc, active, command, params, k, cancel, photocraft_engine::channel_cmds::ChannelTarget::Composite, &[]) + preview_document_for_target( + doc, + active, + command, + params, + k, + cancel, + photocraft_engine::channel_cmds::ChannelTarget::Composite, + &[], + &ColorSettings::default(), + ) } /// Run the preview with the same pixel target as the final command, including individual channels. /// `documents` are the open documents in session order: document params (Match Color's Source, -/// Displace's map) index into them. +/// Displace's map) index into them. `color` is the app's Edit › Color Settings: Assign and Convert +/// to Profile's `working` is the working space chosen there, not the built-in default. #[allow(clippy::too_many_arguments)] pub(crate) fn preview_document_for_target( doc: &Document, @@ -891,15 +1045,18 @@ pub(crate) fn preview_document_for_target( cancel: Option<&photocraft_engine::jobs::JobCtx>, target: photocraft_engine::channel_cmds::ChannelTarget, documents: &[Arc], + color: &ColorSettings, ) -> Option { if command == crate::select_mask_view::COMMAND { return crate::select_mask_view::preview_document(doc, active, params, k, cancel); } // Warp Text renders the type again from the layer model (font size, position), which a - // reduced proxy doesn't scale: it runs at full size and the result is reduced (#218). - let (run_k, reduce_k) = if command == "type.warpText" { (1, k) } else { (k, 1) }; + // reduced proxy doesn't scale: it runs at full size and the result is reduced (#218). So does + // a smart filter being edited: the smart object renders again from its source (#6324). + let (run_k, reduce_k) = if command == "type.warpText" || command == SMART_FILTER_SET_PARAMS { (1, k) } else { (k, 1) }; let proxy = crate::proxy::proxy_document(doc, run_k); let mut s = photocraft_engine::Session::new(); + s.color.settings = color.clone(); s.set_inline_job_ctx(cancel.cloned()); let doc_id = proxy.id; s.add_document(proxy, None); @@ -1019,6 +1176,31 @@ impl FilterPreviewKey { mod tests { use super::*; + #[test] + fn color_settings_working_spaces_list_installed_profiles_of_their_space() { + // #6323: a press condition installed in the system can be the CMYK working space, as in + // Photoshop's Color Settings; each working-space menu lists only profiles of its space. + use photocraft_cms::{ColorSpace, ProfileClass}; + let p = |path: &str, class, color_space| InstalledProfile { path: path.into(), description: path.to_uppercase(), class, color_space }; + let installed = [ + p("gracol.icc", ProfileClass::Output, ColorSpace::Cmyk), + p("monitor.icc", ProfileClass::Display, ColorSpace::Rgb), + p("printer-rgb.icc", ProfileClass::Output, ColorSpace::Rgb), + p("scanner.icc", ProfileClass::Input, ColorSpace::Rgb), + p("gray.icc", ProfileClass::Output, ColorSpace::Gray), + p("link.icc", ProfileClass::DeviceLink, ColorSpace::Cmyk), + ]; + let paths = |key: &str| installed_choices("edit.colorSettings", key, &installed).into_iter().map(|(path, _)| path).collect::>(); + assert_eq!(paths("workingCmyk"), ["gracol.icc"]); + assert_eq!(paths("workingRgb"), ["monitor.icc"]); + assert_eq!(paths("workingGray"), ["gray.icc"]); + assert!(paths("policyCmyk").is_empty() && paths("intent").is_empty()); + assert_eq!(installed_choices("edit.colorSettings", "workingCmyk", &installed)[0].1, "GRACOL.ICC", "listed by description"); + // The profile dialogs keep listing every destination profile. + assert_eq!(installed_choices("edit.convertToProfile", "profile", &installed).len(), 5); + assert!(installed_choices("filter.blur.gaussianBlur", "profile", &installed).is_empty()); + } + /// #5710: the seed field's Random button always gives a different seed the field can hold. #[test] fn random_seeds_stay_in_range_and_change() { @@ -1050,6 +1232,16 @@ mod tests { assert_eq!(source_label("centerX"), "Center X"); } + /// Convert to Profile's and Proof Setup's `bpc` read "Bpc": spelled out, and translated. + #[test] + fn black_point_compensation_is_spelled_out() { + assert_eq!(source_label("bpc"), "Black Point Compensation"); + // English is the source: it has no catalog. + for lang in crate::i18n::Lang::all().filter(|l| l.code() != "en") { + assert!(crate::i18n::has(lang, "Black Point Compensation"), "{lang:?}"); + } + } + fn key() -> FilterPreviewKey { FilterPreviewKey { doc: photocraft_doc::DocId(7), @@ -1385,6 +1577,38 @@ mod tests { assert_eq!(params["amount"].as_f64(), Some(37.5)); } + /// #7400: Lens Blur's Source lists the document's alpha channels, by name, each choosable even + /// when two share a name; `depthChannel` is set through that menu, not shown as a field, and + /// like the other references it isn't remembered, so a remembered `channel` source opens as None. + #[test] + fn lens_blur_source_lists_the_alpha_channels() { + let spec = photocraft_engine::commands::find(LENS_BLUR).unwrap().params; + let params = parse_spec(spec); + assert!(params.iter().any(|p| p.key == "depthChannel" && p.kind == Kind::Json), "depthChannel is no dialog field"); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); + app.run("channel.new", json!({"name": "Depth Map", "fill": "white"})).unwrap(); + let id = open(&mut app, LENS_BLUR).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__channels"], json!(["Depth Map"])); + // The menu's values are channel indices, so two channels with one name are both choosable. + app.run("channel.new", json!({"name": "Depth Map", "fill": "black"})).unwrap(); + let id = open(&mut app, LENS_BLUR).unwrap(); + let names: Vec = serde_json::from_value(app.ui.dialog_mut(id).unwrap().fields["__channels"].clone()).unwrap(); + assert_eq!(names, ["Depth Map", "Depth Map"]); + assert_eq!((channel_choice(0), channel_choice(1)), ("channel:0".to_string(), "channel:1".to_string())); + assert_eq!(channel_index(&json!(1), &names), Some(1), "the second one by its index"); + assert_eq!(channel_index(&json!("Depth Map"), &names), Some(0), "a name is the first so named, as the engine reads it"); + assert_eq!(channel_index(&json!(2), &names), None); + + app.session.prefs.edit(|p| { + p.dialogs.insert(LENS_BLUR.into(), json!({"depthMap": "channel", "depthChannel": "Depth Map"})); + }); + let id = open(&mut app, LENS_BLUR).unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(f["depthMap"], "none", "no channel was remembered with it"); + assert!(f.get("depthChannel").is_none()); + } + #[test] fn wide_positive_ranges_use_the_logarithmic_slider_path() { assert!(uses_logarithmic_slider(0.1, 1000.0), "Gaussian Blur radius"); @@ -1569,6 +1793,7 @@ mod tests { None, photocraft_engine::channel_cmds::ChannelTarget::Composite, &documents, + &ColorSettings::default(), ) .unwrap_or_else(|| panic!("{label}: no preview")); let got = preview.layers[0].surface().unwrap().pixel(24, 16); @@ -1584,6 +1809,7 @@ mod tests { None, photocraft_engine::channel_cmds::ChannelTarget::Composite, &documents, + &ColorSettings::default(), ) .unwrap(); let px = preview.layers[0].surface().unwrap().pixel(12, 8); @@ -1872,6 +2098,15 @@ mod tests { assert_eq!(preview_factor("image.mode.bitmap", &json!({"method": "threshold"}), 4), 4); } + /// #6530: the Content-Aware Fill preview runs at full resolution, for every Sampling choice, + /// because its patch search finds different matches on a reduced copy. + #[test] + fn content_aware_fill_previews_at_full_resolution() { + for params in [json!({}), json!({"sampling": "auto"}), json!({"sampling": "rectangular"})] { + assert_eq!(preview_factor("edit.contentAwareFill", ¶ms, 4), 1, "{params}"); + } + } + /// #2063: proxy previews scaled what isn't a length (Tree's canvas fraction, Lens Correction's /// perspective), clamped negative lengths to +0.1 (Offset left/up), left Shadows/Highlights' /// radii in document pixels and rounded Mosaic's 10 px cells to 3 proxy px (12 px). @@ -2345,8 +2580,7 @@ mod tests { app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); let id = open(&mut app, REPLACE_COLOR).unwrap(); assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#ff0000"), "the dialog starts from the foreground colour"); - assert!(!color_eyedropper_armed(&app)); - app.ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(true)); + // #6279: armed as it opens, so the first click on the image samples. assert!(color_eyedropper_armed(&app)); assert!(color_eyedropper_sample(&mut app, 4.0, 4.0)); assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); @@ -2362,7 +2596,7 @@ mod tests { assert!(!color_eyedropper_sample(&mut app, 4.0, 4.0)); } - /// #4143: the eyedropper button arms and disarms the canvas picker. + /// #4143: the eyedropper button disarms and re-arms the canvas picker (#6279: it opens armed). #[test] fn replace_color_dialog_arms_the_eyedropper_button() { use egui_kittest::Harness; @@ -2375,12 +2609,52 @@ mod tests { PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); open(h.state_mut(), REPLACE_COLOR).unwrap(); h.run_steps(3); - h.get_by_label("Pick Color From Image").click(); - h.run_steps(2); - assert!(color_eyedropper_armed(h.state())); + assert!(color_eyedropper_armed(h.state()), "armed as the dialog opens"); h.get_by_label("Pick Color From Image").click(); h.run_steps(2); assert!(!color_eyedropper_armed(h.state())); + h.get_by_label("Pick Color From Image").click(); + h.run_steps(2); + assert!(color_eyedropper_armed(h.state())); + } + + /// #6278: the Result swatch shows the sampled colour after the shift, and a colour picked for + /// it sets Hue, Saturation and Lightness so the sampled colour becomes it. + #[test] + fn replace_color_result_swatch_sets_the_sliders() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.run("tools.setColors", json!({"foreground": "#cc3333"})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), REPLACE_COLOR).unwrap(); + h.run_steps(3); + // No shift yet: the Result is the sampled colour. + assert_eq!(h.get_all_by_label("#cc3333").count(), 2, "the sampled colour and the Result both read #cc3333"); + h.get_by_role_and_label(egui::accesskit::Role::ColorWell, "Result").click(); + h.run_steps(3); + let picker = h.state().ui.dialogs.last().unwrap(); + assert_ne!(picker.id, id, "the Color Picker opened over the dialog"); + assert_eq!(picker.fields["color"], json!("#cc3333"), "on the current Result"); + let picker = picker.id; + h.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), json!("#3355cc")); + crate::dialogs::confirm(h.state_mut(), picker).unwrap(); + h.state_mut().ui.dialogs.retain(|d| d.id != picker); + h.run_steps(3); + let f = h.state_mut().ui.dialog_mut(id).unwrap().fields.clone(); + let n = |k: &str| f[k].as_f64().unwrap() as f32; + let got = photocraft_algo::tone::replace_color_result([0.8, 0.2, 0.2], n("hue"), n("saturation"), n("lightness")); + let want = crate::color_picker_ui::parse_hex("#3355cc").unwrap(); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.02), "the sliders turn the sampled colour into the pick: {got:?}"); + assert!(n("hue") != 0.0, "the hue moved"); + // Moving a slider afterwards is not mistaken for another pick. + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("lightness".into(), json!(10.0)); + h.run_steps(2); + assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["lightness"], json!(10.0)); } /// #4457: Localized Color Clusters and its Range, as in Photoshop's dialog; the sampled point diff --git a/crates/ui-egui/src/filter_preview_ui.rs b/crates/ui-egui/src/filter_preview_ui.rs index 90eaf4f6fe..b068f3339d 100644 --- a/crates/ui-egui/src/filter_preview_ui.rs +++ b/crates/ui-egui/src/filter_preview_ui.rs @@ -43,12 +43,21 @@ pub(crate) fn window(app: &PhotocraftApp, dialog: u64, ui: &mut egui::Ui, f: &mu // decides whether the filtered result (rather than the original) is shown. let preview_on = f.get("__preview").and_then(Value::as_bool) == Some(true); let filtered: Option<(FilterPreviewKey, std::sync::Arc)> = app.filter_preview.as_ref().and_then(|p| { - (preview_on && p.key.dialog == dialog && p.key.doc == doc_id && p.key.command == cmd).then(|| p.result.clone().map(|r| (p.key.clone(), r))).flatten() + // An edited smart filter previews as `layer.smartFilter.setParams` (#6324). + let previewed = crate::smart_ui::preview_command(f, &cmd); + (preview_on && p.key.dialog == dialog && p.key.doc == doc_id && p.key.command == previewed) + .then(|| p.result.clone().map(|r| (p.key.clone(), r))) + .flatten() }); // The proxy factor the preview runs at (the filtered key's when it exists, else the request's). + // The fallback must be the factor the canvas will ask for, not the document's own: since #6326 + // the canvas caps it with the view's zoom, and a window that sized its textures from the + // uncapped factor built a proxy the canvas never asked for, then rebuilt it (a full-size copy + // and upload on the UI thread at 100 %) the moment the first result arrived, shifting this + // window's 100 % mapping and pan clamp for a frame. let base_k = filtered.as_ref().map(|(k, _)| k.k).unwrap_or_else(|| { let params = app.with_mask_target(&cmd, crate::filter_dialog::params_of(f)); - crate::filter_dialog::preview_factor(&cmd, ¶ms, crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app))) + crate::canvas::filter_preview_factor(app, &st.doc, &cmd, ¶ms) }); let t = Tokens::get(ui.ctx()); @@ -237,7 +246,7 @@ fn upload(ctx: &egui::Context, app: &PhotocraftApp, name: &str, doc: &Document) } /// The reduction that fits a `w`×`h` image inside a `max_side` texture (1: it already fits). -fn texture_factor(w: u32, h: u32, max_side: usize) -> u32 { +pub(crate) fn texture_factor(w: u32, h: u32, max_side: usize) -> u32 { let max_side = u32::try_from(max_side).unwrap_or(u32::MAX).max(1); w.max(h).div_ceil(max_side).max(1) } @@ -324,6 +333,7 @@ mod tests { None, ChannelTarget::Alpha(0), &[], + &Default::default(), ) .unwrap(); let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/frame_tool.rs b/crates/ui-egui/src/frame_tool.rs index 4a1210b874..b2102b1cfb 100644 --- a/crates/ui-egui/src/frame_tool.rs +++ b/crates/ui-egui/src/frame_tool.rs @@ -64,7 +64,9 @@ fn content_layer(app: &PhotocraftApp, r: [i64; 4]) -> Option { /// Pointer input for the Frame tool. Returns true when the event was its own. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { - if app.ui.tool != Tool::Frame { + // ⌘ is the Move tool (`hold_keys::cmd_moves`): a press with it held is not this tool's, + // so it drags a guide or the layer (#6288). A drag already under way keeps its events. + if app.ui.tool != Tool::Frame || (app.ui.frame_tool.drag.is_none() && crate::canvas::event_tool(app, mods) != Tool::Frame) { return false; } let (square, centred) = (mods.shift, mods.alt); diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index 012bcf801c..7ec4c192b2 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -36,6 +36,10 @@ pub use photocraft_gpu::{DeviceHealth, Fault}; /// Default tile side; documents up to this size (and the device limit) use a single texture. pub const DEFAULT_TILE: u32 = 8192; +/// Mip levels no larger than this on either side are redrawn whole on every edit rather than +/// just their damage (see [`mip_damage`], #6418). Every corrupted level measured was at most +/// 64 px; this leaves a factor of two. +const WHOLE_MIP_SIDE: u32 = 128; const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; /// Canvas texture format of high-bit documents (see [`GpuCanvas::format_for`]). const FORMAT_HIGH: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; @@ -295,6 +299,15 @@ impl GpuCanvas { } } + /// Take any GPU measurement that has landed since the last call, without compositing + /// anything. [`Compositor::render`] carries measurements out in its stats, but a refresh is + /// the only thing that collects them, so the last refresh before the app goes idle would + /// never be reported. The frame loop calls this so it is. + pub fn take_gpu_timing(&self) -> Option { + let mut r = self.rs.renderer.write(); + r.callback_resources.get_mut::()?.compositor.as_mut()?.take_gpu_timing() + } + /// GPU bytes the wgpu compositor holds: resident layer pages and caches (effect maps and /// lower-stack chunks). Keep the scorecard's memory measurements inclusive of reuse. pub fn compositor_bytes(&self) -> Option<(u64, usize)> { @@ -472,6 +485,8 @@ impl GpuCanvas { }, }; comp.set_health(self.health.clone()); + // Measured, not waited for: the timestamps come back a frame or two later. + comp.measure_gpu_time(device, queue); if let Some(b) = res.compositor_budget { comp.set_memory_budget(b); } @@ -636,8 +651,10 @@ impl GpuCanvas { Ok(stats) => { out.kind = if damage.is_some() { "gpu-rect" } else { "gpu-full" }; out.px = region.width() as u64 * region.height() as u64; + // Encoding and submitting only: the GPU is still running this work. out.composite_ms = now_ms() - t0; out.uploads = stats.tiles_uploaded as u64; + out.gpu = stats.gpu_time; return out; } Err(e) => out.fallback = Some(e.0), @@ -876,13 +893,21 @@ pub struct Refresh { pub upload_ms: f64, /// Layer tiles the wgpu compositor uploaded. pub uploads: u64, + /// How long the GPU spent executing a recent wgpu composite, once its timestamps came back + /// (a frame or two after that refresh, so usually an earlier one than this). It carries its + /// own pixel count and is never this refresh's unless they match. `None` when the device has + /// no timestamp queries, on the CPU compositor, and on wasm: no number at all is reported + /// rather than `composite_ms`, which measures encoding and submitting, not executing. It + /// leaves out layer-tile uploads (`uploads` above counts them), so a first refresh of a + /// document under-reports by more than the few per cent of a warm one. + pub gpu: Option, /// Why the wgpu compositor wasn't used. pub fallback: Option, } -/// How the app creates its wgpu device: egui's defaults, except that the texture and buffer size -/// limits are the adapter's own rather than egui's 8192 px cap, so large documents stay on the -/// GPU compositor. +/// How the app creates its wgpu device: egui's defaults clamped to the adapter's supported limits, +/// with the adapter's own texture and buffer sizes rather than egui's 8192 px cap, so large +/// documents stay on the GPU compositor. pub fn wgpu_setup() -> egui_wgpu::WgpuSetup { let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); use_adapter_limits(&mut setup); @@ -891,7 +916,8 @@ pub fn wgpu_setup() -> egui_wgpu::WgpuSetup { /// Make `setup` request the adapter's own texture and buffer size limits instead of egui's /// default 8192 px cap (which sent every document wider or taller than 8192 px to the CPU -/// compositor). Everything else (features, the WebGL2 base limits on GL) stays egui's default. +/// compositor). Other limits use egui's defaults (WebGL2's on GL), clamped to adapter support; +/// features stay egui's default. pub fn use_adapter_limits(setup: &mut egui_wgpu::WgpuSetup) { use_adapter_limits_with(setup, |_| {}); } @@ -902,16 +928,51 @@ pub fn use_adapter_limits_with(setup: &mut egui_wgpu::WgpuSetup, on_adapter: imp if let egui_wgpu::WgpuSetup::CreateNew(create) = setup { create.device_descriptor = std::sync::Arc::new(move |adapter| { on_adapter(adapter); - wgpu::DeviceDescriptor { label: Some("photocraft wgpu device"), required_limits: device_limits(adapter), ..Default::default() } + device_descriptor(adapter) }); } } -/// egui's base limits (WebGL2's on GL) with the adapter's maximum texture and buffer sizes. +/// How the app asks for its device: egui's defaults, the adapter's texture and buffer size +/// limits ([`device_limits`]), and timestamp queries where the adapter has them, so the canvas +/// can report how long the GPU actually spends compositing ([`photocraft_gpu::GpuTimer`]). +/// A bench or test that builds its own device should use this rather than [`device_limits`] +/// alone, or it measures a device the app never creates. (`bevel_bench`, `fx_bench` and +/// `interactive_bench` still call [`device_limits`] directly and so report no GPU time.) +pub fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> { + wgpu::DeviceDescriptor { + label: Some("photocraft wgpu device"), + required_limits: device_limits(adapter), + required_features: timing_features(adapter), + ..Default::default() + } +} + +/// The timestamp-query features when the adapter supports all of them, else none: asking for a +/// feature an adapter lacks fails device creation, and a canvas without GPU timing is far better +/// than no canvas. +/// +/// `PHOTOCRAFT_NO_GPU_TIMING` suppresses the request as well as the timer +/// ([`photocraft_gpu::Compositor::measure_gpu_time`]), so the variable also rescues a driver +/// that advertises the features and then fails or misbehaves on device creation — not only one +/// whose timestamps come back wrong. +pub fn timing_features(adapter: &wgpu::Adapter) -> wgpu::Features { + let want = photocraft_gpu::timing::FEATURES; + if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() { + return wgpu::Features::empty(); + } + if adapter.features().contains(want) { want } else { wgpu::Features::empty() } +} + +/// egui's base limits (WebGL2's on GL), clamped to adapter support, with its maximum texture and buffer sizes. pub fn device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits { - let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() }; - let a = adapter.limits(); - wgpu::Limits { max_texture_dimension_2d: a.max_texture_dimension_2d, max_buffer_size: a.max_buffer_size, ..base } + device_limits_for(adapter.get_info().backend, adapter.limits()) +} + +fn device_limits_for(backend: wgpu::Backend, supported: wgpu::Limits) -> wgpu::Limits { + let base = if backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() }; + let base = base.or_worse_values_from(&supported); + wgpu::Limits { max_texture_dimension_2d: supported.max_texture_dimension_2d, max_buffer_size: supported.max_buffer_size, ..base } } /// Milliseconds since first call (monotonic). Always 0 on wasm, where `std::time` is unavailable. @@ -933,7 +994,9 @@ pub struct Perf { pub ui_ms: f64, /// Worst UI frame of the last ~second (ms). pub ui_max_ms: f64, - /// Last canvas refresh: CPU composite (ms). + /// Last canvas refresh, CPU side (ms): the CPU composite on the CPU path, and on the GPU + /// path the cost of *encoding and submitting* the composite — not of running it, which is + /// `gpu_ms`. pub composite_ms: f64, /// Last canvas refresh: conversion + upload (ms). pub upload_ms: f64, @@ -945,6 +1008,16 @@ pub struct Perf { pub gpu: bool, /// Layer tiles uploaded by the last GPU composite. pub gpu_uploads: u64, + /// How long the GPU spent executing a recent composite (ms), from timestamp queries read + /// back after the fact. `None` on the CPU compositor, on a device without timestamp queries + /// and on wasm — there is then no honest number to report, and `composite_ms` is not one. + /// Excludes layer-tile uploads and end-of-batch work (see `photocraft_gpu::timing`), so it + /// is a few per cent under the GPU's full share of a warm refresh and further under a cold + /// one. + pub gpu_ms: Option, + /// Pixels of the refresh `gpu_ms` measured, which is a frame or two behind + /// `last_refresh_px` and may be a different size. + pub gpu_ms_px: u64, /// Why the last refresh fell back to the CPU compositor (None = GPU composited). pub gpu_fallback: Option, /// Adapter, backend, driver and fallback state (Help › System Info). @@ -1097,10 +1170,28 @@ impl Perf { self.upload_ms = upload_ms; if !kind.starts_with("gpu") { self.gpu_uploads = 0; + // The CPU compositor did this one: there is no GPU time, and the last GPU + // refresh's would be read as this refresh's. + self.gpu_ms = None; + self.gpu_ms_px = 0; } else { self.gpu_fallback = None; } } + + /// Record a canvas refresh and any GPU measurement that came back with it. + pub fn record_refresh(&mut self, r: &Refresh) { + self.record(r.kind, r.px, r.composite_ms, r.upload_ms); + if let Some(t) = r.gpu { + self.record_gpu(t); + } + } + + /// Record a GPU composite measurement that came back (see [`photocraft_gpu::GpuTiming`]). + pub fn record_gpu(&mut self, t: photocraft_gpu::GpuTiming) { + self.gpu_ms = Some(t.ms); + self.gpu_ms_px = t.px; + } pub fn span(&mut self, name: &'static str, ms: f64) { self.spans.insert(name, (ms * 100.0).round() / 100.0); } @@ -1760,6 +1851,20 @@ fn mip_count(w: u32, h: u32) -> u32 { 32 - w.max(h).max(1).leading_zeros() } +/// The rect (x0, y0, x1, y1) of a `lw`×`lh` mip level to redraw when `prev` changed in the level +/// above: that damage halved and padded by one texel for odd-size rounding, or the whole level +/// when it is at most [`WHOLE_MIP_SIDE`] on either side. On AMD's Vulkan driver a pass that draws +/// only part of a level of 64 px or less corrupts texels outside its scissor, at the level's +/// top-left (#6418: RX 6900 XT, driver 26.8.1; DX12 on the same card is fine). Such a level costs +/// next to nothing to redraw, so this holds for every adapter; the levels after it are smaller +/// still, so the rest of the chain is redrawn whole too. +fn mip_damage([x0, y0, x1, y1]: [u32; 4], lw: u32, lh: u32) -> [u32; 4] { + if lw.max(lh) <= WHOLE_MIP_SIDE { + return [0, 0, lw, lh]; + } + [(x0 / 2).saturating_sub(1), (y0 / 2).saturating_sub(1), (x1.div_ceil(2) + 1).min(lw), (y1.div_ceil(2) + 1).min(lh)] +} + /// A buffer holding `contents`, like `DeviceExt::create_buffer_init` but without its panic when /// the device was lost (an invalid buffer has no mapped range): the buffer is then just invalid. fn init_buffer(device: &wgpu::Device, label: &str, contents: &[u8], usage: wgpu::BufferUsages) -> wgpu::Buffer { @@ -1857,9 +1962,7 @@ impl DocTextures { (x0, y0, x1, y1) = (x0 - tx, y0 - ty, x1 - tx, y1 - ty); for level in 1..t.levels.len() { let (lw, lh) = ((tw >> level).max(1), (th >> level).max(1)); - // Damage at this level, padded by one texel for odd-size rounding. - (x0, y0) = ((x0 / 2).saturating_sub(1), (y0 / 2).saturating_sub(1)); - (x1, y1) = ((x1.div_ceil(2) + 1).min(lw), (y1.div_ceil(2) + 1).min(lh)); + [x0, y0, x1, y1] = mip_damage([x0, y0, x1, y1], lw, lh); let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_mip"), layout: &res.mip_bgl, @@ -2375,6 +2478,94 @@ mod mip_tests; mod tests { use super::*; + /// A GPU measurement arrives a frame or two after its refresh, so most GPU refreshes carry + /// none; the last one reported must stand until a newer one lands. A CPU refresh is + /// different: there is no GPU time at all then, and keeping the old number would show it as + /// this refresh's. Runs anywhere — the GPU timing tests need hardware and CI has none. + #[test] + fn a_gpu_measurement_stands_until_replaced_and_a_cpu_refresh_clears_it() { + let timing = |ms, px| photocraft_gpu::GpuTiming { ms, px, spans: 1 }; + let refresh = |kind, gpu| Refresh { kind, gpu, ..Default::default() }; + let mut perf = Perf::default(); + assert_eq!(perf.gpu_ms, None, "nothing is reported before a measurement"); + + perf.record_refresh(&refresh("gpu-full", Some(timing(83.9, 24_000_000)))); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000)); + + // The common case: a GPU refresh whose own measurement has not come back yet. + perf.record_refresh(&refresh("gpu-rect", None)); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000), "the last measurement stands"); + + perf.record_refresh(&refresh("gpu-rect", Some(timing(11.2, 1_098_640)))); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(11.2), 1_098_640), "a newer measurement replaces it"); + + // The CPU compositor did this one: the GPU number belongs to no refresh on screen. + perf.record_refresh(&refresh("full", None)); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (None, 0), "a CPU refresh clears it rather than showing a stale one"); + + // And it comes back on the next GPU refresh that carries one. + perf.record_refresh(&refresh("gpu-full", Some(timing(42.0, 6_000_000)))); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(42.0), 6_000_000)); + } + + #[test] + fn device_limits_support_v3d_shader_variable_limit() { + let supported = wgpu::Limits { max_texture_dimension_2d: 7680, max_inter_stage_shader_variables: 15, ..wgpu::Limits::default() }; + let requested = device_limits_for(wgpu::Backend::Vulkan, supported.clone()); + assert_eq!(requested.max_inter_stage_shader_variables, 15); + assert!(requested.check_limits(&supported)); + assert_eq!(requested.max_texture_dimension_2d, 7680); + assert_eq!(requested.max_buffer_size, supported.max_buffer_size); + } + + #[test] + fn device_limits_support_weaker_gl_adapters() { + let supported = wgpu::Limits { + max_texture_dimension_2d: 1024, + max_texture_dimension_3d: 128, + max_bind_groups: 2, + max_buffer_size: 128 << 20, + ..wgpu::Limits::downlevel_webgl2_defaults() + }; + let requested = device_limits_for(wgpu::Backend::Gl, supported.clone()); + assert!(requested.check_limits(&supported)); + assert_eq!(requested, supported); + } + + #[test] + fn device_limits_preserve_backend_defaults_on_capable_adapters() { + let supported = wgpu::Limits { + max_texture_dimension_2d: 16_384, + max_buffer_size: 1 << 30, + max_bind_groups: 8, + max_inter_stage_shader_variables: 32, + min_uniform_buffer_offset_alignment: 64, + min_storage_buffer_offset_alignment: 64, + ..wgpu::Limits::default() + }; + for (backend, base) in [ + (wgpu::Backend::Vulkan, wgpu::Limits::default()), + (wgpu::Backend::Dx12, wgpu::Limits::default()), + (wgpu::Backend::Metal, wgpu::Limits::default()), + (wgpu::Backend::Gl, wgpu::Limits::downlevel_webgl2_defaults()), + ] { + let requested = device_limits_for(backend, supported.clone()); + assert!(requested.check_limits(&supported)); + assert_eq!(requested, wgpu::Limits { max_texture_dimension_2d: 16_384, max_buffer_size: 1 << 30, ..base }, "{backend:?}"); + } + } + + #[test] + fn device_limits_support_larger_minimum_alignments() { + let supported = wgpu::Limits { min_uniform_buffer_offset_alignment: 512, min_storage_buffer_offset_alignment: 1024, ..wgpu::Limits::default() }; + for backend in [wgpu::Backend::Vulkan, wgpu::Backend::Gl] { + let requested = device_limits_for(backend, supported.clone()); + assert!(requested.check_limits(&supported)); + assert_eq!(requested.min_uniform_buffer_offset_alignment, 512); + assert_eq!(requested.min_storage_buffer_offset_alignment, 1024); + } + } + /// The scratch-texture workaround is for Intel's DX12 drivers (#892); other DX12 adapters /// render straight into the level like every other backend (#4515). #[test] @@ -2392,6 +2583,17 @@ mod tests { assert!(separate_mip_targets(Dx12, intel, Some("yes"))); } + /// #6418: levels of at most WHOLE_MIP_SIDE are redrawn whole; larger ones keep the damage. + #[test] + fn small_mip_levels_are_redrawn_whole() { + // A 3 × 3 dab at (800, 500) of a 1791 × 1083 tile, at mip 1 (895 × 541): halved and padded. + assert_eq!(mip_damage([800, 500, 803, 503], 895, 541), [399, 249, 403, 253]); + // At most 128 px on either side: the whole level, wherever the damage is. + assert_eq!(mip_damage([100, 60, 102, 63], 111, 67), [0, 0, 111, 67]); + assert_eq!(mip_damage([0, 0, 1, 1], 128, 2), [0, 0, 128, 2]); + assert_eq!(mip_damage([0, 0, 1, 1], 129, 2), [0, 0, 2, 2]); + } + #[test] fn gpu_budget_follows_memory_usage_and_ram() { const G: u64 = 1 << 30; diff --git a/crates/ui-egui/src/gpu_canvas_mip_tests.rs b/crates/ui-egui/src/gpu_canvas_mip_tests.rs index 82e911bae9..b9eac3e0b9 100644 --- a/crates/ui-egui/src/gpu_canvas_mip_tests.rs +++ b/crates/ui-egui/src/gpu_canvas_mip_tests.rs @@ -102,3 +102,47 @@ fn check_mips(gpu: &GpuCanvas) { } } } + +/// #6418: on AMD's Vulkan driver, a pass that drew only part of a small mip level corrupted texels +/// outside its scissor, at the level's top-left (RX 6900 XT, driver 26.8.1). Whether a texture is +/// hit depends on where the driver placed it, so this paints dabs on canvases of several sizes at +/// both depths and compares every level with a full rebuild of the same pixels. +#[test] +fn partial_updates_match_a_full_rebuild_at_every_mip_level() { + let _gpu = photocraft_testkit::gpu_lock(); + let rs = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| egui_kittest::wgpu::create_render_state(wgpu_setup(), Default::default()))); + let Ok(rs) = rs else { + eprintln!("skipping mip rebuild comparison: no GPU adapter"); + return; + }; + let gpu = GpuCanvas::new(&rs); + for (depth, w, h) in [(SampleType::U8, 255, 255), (SampleType::U8, 1024, 768), (SampleType::F32, 512, 512), (SampleType::F32, 1791, 1083)] { + let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.0; 4]); + for (i, px) in full.px.iter_mut().enumerate() { + let (x, y) = (i as u32 % w, i as u32 / w); + *px = [x as f32 / w as f32, y as f32 / h as f32, ((x + y) % 7) as f32 / 7.0, 1.0]; + } + gpu.upload_buffer_full(1, &full, depth); + let dabs = [Rect::from_xywh((w / 2) as i32, (h / 2) as i32, w / 3, h / 3), Rect::from_xywh(w as i32 - 1, h as i32 - 1, 1, 1)]; + for (dab, color) in dabs.into_iter().zip([[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]]) { + assert!(gpu.upload_buffer_rect(1, &Buffer::filled(dab, color))); + for y in dab.y0..dab.y1 { + for x in dab.x0..dab.x1 { + full.px[y as usize * w as usize + x as usize] = color; + } + } + gpu.upload_buffer_full(2, &full, depth); + for (level, (partial, rebuilt)) in read_mips(&gpu, 1).iter().zip(&read_mips(&gpu, 2)).enumerate() { + let lw = (w >> level).max(1) as usize; + for (i, (a, b)) in partial.iter().zip(rebuilt).enumerate() { + assert!( + a.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.005), + "{depth:?} {w}x{h} dab {dab:?} mip {level} at ({}, {}): {a:?} != {b:?}", + i % lw, + i / lw + ); + } + } + } + } +} diff --git a/crates/ui-egui/src/gradient_ui.rs b/crates/ui-egui/src/gradient_ui.rs index be35f66028..dd91c1a74d 100644 --- a/crates/ui-egui/src/gradient_ui.rs +++ b/crates/ui-egui/src/gradient_ui.rs @@ -219,6 +219,11 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> app.gradient.drag = None; return false; } + // ⌘ is the Move tool (`hold_keys::cmd_moves`): a press with it held drags a guide or the layer + // (#6288). A drag already under way keeps its events. + if app.gradient.drag.is_none() && crate::canvas::event_tool(app, mods) != Tool::Gradient { + return false; + } let zoom = app.point_zoom().max(0.01); match ev { ToolEvent::Down { x, y, .. } => { diff --git a/crates/ui-egui/src/gradient_ui/properties_panel.rs b/crates/ui-egui/src/gradient_ui/properties_panel.rs index 39b961ee20..d975102539 100644 --- a/crates/ui-egui/src/gradient_ui/properties_panel.rs +++ b/crates/ui-egui/src/gradient_ui/properties_panel.rs @@ -49,7 +49,8 @@ fn options(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) { if let Some(value) = numeric_row(ui, "angle", "Angle", angle, -180.0..=180.0, "°") { let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "angle": value})); } - if let Some(value) = numeric_row(ui, "scale", "Scale", scale * 100.0, 10.0..=150.0, "%") { + let (min, max) = cmds::SCALE_RANGE; + if let Some(value) = numeric_row(ui, "scale", "Scale", scale * 100.0, min * 100.0..=max * 100.0, "%") { let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "scale": value})); } ui.horizontal_wrapped(|ui| { diff --git a/crates/ui-egui/src/guide_cursor_tests.rs b/crates/ui-egui/src/guide_cursor_tests.rs new file mode 100644 index 0000000000..fd0e5c0595 --- /dev/null +++ b/crates/ui-egui/src/guide_cursor_tests.rs @@ -0,0 +1,204 @@ +//! #6288: ⌘ (Ctrl off the Mac) over a guide is the Move tool's guide drag with every tool on +//! which ⌘ is the Move tool, and the pointer shows it (the guide's double arrow), as in +//! Photoshop. Driven through real egui input, so the held key goes through `hold_keys`. + +use egui::{Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::state::Tool; + +fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = tool; + app.run("view.newGuide", json!({"orientation": "vertical", "position": 200})).unwrap(); + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [200.0, 150.0]; + v.fit_pending = false; + h.run_steps(2); + h +} + +fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 { + let app = h.state(); + let v = &app.ui.views[0]; + ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + aspect: app.ui.view.display_aspect(), + } + .to_screen(x, y) +} + +fn hover(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32, m: Modifiers) -> egui::CursorIcon { + h.event(egui::Event::ModifiersChanged(m)); + let p = screen(h, x, y); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(2); + h.output().platform_output.cursor_icon +} + +fn drag(h: &mut Harness<'static, PhotocraftApp>, from: f32, to: f32, m: Modifiers) { + let p = screen(h, from, 150.0); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: m }); + h.run_steps(1); + for k in 1..=4 { + let q = screen(h, from + (to - from) * k as f32 / 4.0, 150.0); + h.event(egui::Event::PointerMoved(q)); + h.run_steps(1); + } + let q = screen(h, to, 150.0); + h.event(egui::Event::PointerButton { pos: q, button: PointerButton::Primary, pressed: false, modifiers: m }); + h.run_steps(2); +} + +fn diagonal(h: &mut Harness<'static, PhotocraftApp>, a: [f32; 2], b: [f32; 2], m: Modifiers) { + h.event(egui::Event::ModifiersChanged(m)); + let p = screen(h, a[0], a[1]); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: m }); + h.run_steps(1); + for k in 1..=4 { + let t = k as f32 / 4.0; + let q = screen(h, a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t); + h.event(egui::Event::PointerMoved(q)); + h.run_steps(1); + } + let q = screen(h, b[0], b[1]); + h.event(egui::Event::PointerButton { pos: q, button: PointerButton::Primary, pressed: false, modifiers: m }); + h.run_steps(2); +} + +/// The cursor over the guide with ⌘ held, and where a ⌘-drag from 200 to 240 leaves it. +fn command_drag(tool: Tool, locked: bool) -> (egui::CursorIcon, Vec) { + let mut h = harness(tool); + h.state_mut().ui.extras.lock_guides = locked; + let c = hover(&mut h, 200.0, 150.0, Modifiers::COMMAND); + drag(&mut h, 200.0, 240.0, Modifiers::COMMAND); + (c, h.state().session.active().unwrap().doc.guides.vertical.clone()) +} + +const GUIDE: egui::CursorIcon = egui::CursorIcon::ResizeHorizontal; + +#[test] +fn command_over_a_guide_shows_the_guide_cursor_and_drags_it_with_painting_tools() { + for tool in [ + Tool::Brush, + Tool::Eraser, + Tool::Gradient, + Tool::PaintBucket, + Tool::CloneStamp, + Tool::Eyedropper, + Tool::Dodge, + Tool::SpotHealing, + Tool::Smudge, + Tool::QuickSelection, + Tool::RectMarquee, + Tool::Lasso, + ] { + assert_eq!(command_drag(tool, false), (GUIDE, vec![240.0]), "{tool:?}"); + } +} + +/// The Frame and Artboard tools took a ⌘ press as their own (a new frame or board) although ⌘ +/// is the Move tool on them, so the guide cursor promised a drag that never moved the guide. +#[test] +fn command_drags_a_guide_with_the_frame_and_artboard_tools() { + for tool in [Tool::Frame, Tool::Artboard] { + assert_eq!(command_drag(tool, false), (GUIDE, vec![240.0]), "{tool:?}"); + } + // Off a guide, ⌘ is the Move tool too: no frame is drawn. + let mut h = harness(Tool::Frame); + let layers = h.state().session.active().unwrap().doc.layers.len(); + diagonal(&mut h, [100.0, 100.0], [160.0, 140.0], Modifiers::COMMAND); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers, "⌘-drag with the Frame tool draws no frame"); + assert!(h.state().ui.frame_tool.drag.is_none()); + // Without ⌘ the Frame tool still draws its frame. + diagonal(&mut h, [20.0, 20.0], [120.0, 90.0], Modifiers::NONE); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers + 1, "a plain drag draws a frame"); +} + +#[test] +fn locked_guides_show_no_guide_cursor_and_do_not_move() { + for tool in [Tool::Brush, Tool::Eraser, Tool::Frame] { + let (cursor, guides) = command_drag(tool, true); + assert_ne!(cursor, GUIDE, "{tool:?}"); + assert_eq!(guides, vec![200.0], "{tool:?}"); + } +} + +/// Tools that keep ⌘ for themselves (Photoshop: the Pen's Direct Selection, the Hand, Zoom, Crop, +/// type, shapes, slices) neither show the guide cursor nor drag the guide. +#[test] +fn tools_with_their_own_command_keep_it() { + for tool in [Tool::Pen, Tool::Hand, Tool::Zoom, Tool::Crop, Tool::Type, Tool::Rectangle, Tool::Slice] { + let (cursor, guides) = command_drag(tool, false); + assert_ne!(cursor, GUIDE, "{tool:?}"); + assert_eq!(guides, vec![200.0], "{tool:?}"); + } +} + +/// Window › Modifier Keys: a latched ⌘ made the press take the guide but left the brush cursor. +#[test] +fn sticky_command_shows_the_guide_cursor() { + for tool in [Tool::Brush, Tool::Eraser, Tool::RectMarquee] { + let mut h = harness(tool); + h.state_mut().ui.shell.sticky_command = true; + assert_eq!(hover(&mut h, 200.0, 150.0, Modifiers::NONE), GUIDE, "{tool:?}"); + drag(&mut h, 200.0, 240.0, Modifiers::NONE); + assert_eq!(h.state().session.active().unwrap().doc.guides.vertical, vec![240.0], "{tool:?}"); + } +} + +/// The one decision for "a ⌘ press here takes the guide" outside the Move tool: not without ⌘, +/// not with a locked guide, not during a stroke, not for a tool that keeps ⌘. +#[test] +fn command_guide_at_decides_for_every_tool_that_moves_guides() { + use crate::canvas::command_guide_at; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 200})).unwrap(); + let cmd = Modifiers::COMMAND; + for tool in [Tool::Brush, Tool::Eraser, Tool::Gradient, Tool::PaintBucket, Tool::Eyedropper, Tool::Frame, Tool::Artboard, Tool::MagicWand] { + assert_eq!(command_guide_at(&app, tool, [200.0, 100.0], cmd), Some((true, 0)), "{tool:?}"); + assert_eq!(command_guide_at(&app, tool, [200.0, 100.0], Modifiers::NONE), None, "{tool:?} without ⌘"); + assert_eq!(command_guide_at(&app, tool, [120.0, 100.0], cmd), None, "{tool:?} off the guide"); + } + for tool in [Tool::Move, Tool::Pen, Tool::Hand, Tool::Zoom, Tool::Crop, Tool::Type, Tool::Rectangle, Tool::Slice, Tool::PathSelection] { + assert_eq!(command_guide_at(&app, tool, [200.0, 100.0], cmd), None, "{tool:?} keeps ⌘"); + } + app.ui.extras.lock_guides = true; + assert_eq!(command_guide_at(&app, Tool::Brush, [200.0, 100.0], cmd), None, "locked guides"); + app.ui.extras.lock_guides = false; + // A stroke under way keeps the pointer: ⌘ pressed mid-stroke does not take the guide. + app.ui.tool = Tool::Brush; + crate::canvas::tool_event(&mut app, crate::canvas::ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, Modifiers::NONE); + assert!(app.drag.is_some()); + assert_eq!(command_guide_at(&app, Tool::Brush, [200.0, 100.0], cmd), None, "during a stroke"); +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f3fb8c8c40..6789b75134 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2641,6 +2641,26 @@ cameraData Lens Objektiv Snap to Origin Přichytit k počátku Search settings… Hledat nastavení… No matching settings Žádná odpovídající nastavení +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Nástroj Štětec vzorkování + Sampling Area Overlay Překrytí oblasti vzorkování + Show Sampling Area Zobrazit oblast vzorkování + Indicates Označuje + Sampling Area Oblast vzorkování + Excluded Area Vyloučená oblast + Sampling Area Options Volby oblasti vzorkování + Rectangular Obdélníková + Fill Settings Nastavení výplně + Rotation Adaptation Přizpůsobení otočení + Very High Velmi vysoká + High Vysoká + Low Nízká + Full Úplná + Mirror Zrcadlit + Output Settings Nastavení výstupu + Output To Výstup do + Duplicate Layer Duplikovat vrstvu + Contract Zúžit # Dynamic labels the tl! literal scanner cannot see: filter and Filter Gallery parameter names and # choices (humanized from their keys), Camera Raw controls, render filters (Flame, Picture Frame, Tree), @@ -2781,7 +2801,6 @@ cameraData Lens Objektiv Content-Aware Fill Výplň s ohledem na obsah Content-Aware Move Přesun s ohledem na obsah Continue Pokračovat - Contract Zúžit Contrasty Kontrastní Conté Crayon Křída Conté Convert to Linked Převést na propojený @@ -2857,7 +2876,6 @@ cameraData Lens Objektiv Draft Koncept Dry Brush Suchý štětec Duplicate Duplikovat - Duplicate Layer Duplikovat vrstvu Duplicate Layer Comp Duplikovat kompozici vrstev Duplicate Layers Duplikovat vrstvy Duplicate Path Duplikovat cestu @@ -2984,7 +3002,6 @@ cameraData Lens Objektiv Hide Skrýt Hide Others Skrýt ostatní Hide {app} Skrýt {app} - High Vysoká High Pass Horní propust Highlight Světla Highlight Amount Míra světel @@ -3071,7 +3088,6 @@ cameraData Lens Objektiv Long Lines Dlouhé čáry Long Strokes Dlouhé tahy Loop Smyčka - Low Nízká Lower Dolní Lum Jas Lut LUT @@ -3782,6 +3798,10 @@ navigator Zoom Zvětšení # View › Guides › right-click a guide Edit Selected Guides Upravit vybraná vodítka Clear Selected Guides Vymazat vybraná vodítka + Pasting from other apps is unavailable Vkládání z jiných aplikací není k dispozici + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft v této relaci nemá přístup k systémové schránce. Na Waylandu sandbox Flatpaku skrývá protokol, přes který se čtou obrázky z jiných aplikací. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Chcete-li vkládat z jiných aplikací, spusťte PhotoCraft pod XWaylandem: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Není co vložit: PhotoCraft zde nemůže číst systémovou schránku Delete this set Smazat tuto sadu New Set… Nová sada… PhotoCraft Defaults Výchozí PhotoCraft @@ -3796,6 +3816,7 @@ navigator Zoom Zvětšení There are too many sets: delete one first. Sad je příliš mnoho: nejprve jednu smažte. set name název sady {set} (modified) {set} (změněno) + Show file name in title Zobrazit název souboru v titulu Accept and Go to Conflict Přijmout a přejít ke konfliktu Changes undone. Změny vráceny. Choose a new shortcut for this command, or leave it without one. Zvolte pro tento příkaz novou zkratku, nebo ho nechte bez ní. @@ -3816,3 +3837,22 @@ navigator Zoom Zvětšení This document's layers: {needed} of {budget} for layers Vrstvy tohoto dokumentu: {needed} z {budget} pro vrstvy This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Vrstvy tohoto dokumentu potřebují {needed}, ale mohou zabrat {budget}: překreslení celého dokumentu probíhá na CPU GPU Memory (MB, 0 = Automatic) Paměť GPU (MB, 0 = Automaticky) + {name} was changed by another app after it was opened or saved here. Soubor {name} změnila jiná aplikace poté, co byl zde otevřen nebo uložen. + Replace it with this document, or cancel and use File › Save As to keep both. Nahraďte ho tímto dokumentem, nebo zrušte a použijte Soubor › Uložit jako, abyste zachovali obojí. + Decrease Brush Size Zmenšit velikost štětce + Increase Brush Size Zvětšit velikost štětce + Decrease Brush Hardness Snížit tvrdost štětce + Increase Brush Hardness Zvýšit tvrdost štětce + Memory Usage Využití paměti + Per-document RAM limit (MB) Limit RAM na dokument (MB) + Installed RAM: {ram} MB; this limit: {percent}% Nainstalovaná RAM: {ram} MB; tento limit: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Omezuje pixely plus Historii každého otevřeného dokumentu. Nejstarší stavy zpět se při překročení limitu zahodí. + Applies immediately when saved. Memory is not reserved in advance. Platí hned po uložení. Paměť se předem nerezervuje. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Při GPU paměti Automaticky omezuje i GPU rozpočet. Strop je čtvrtina RAM a, je-li známo, tři osminy paměti karty, minimum 512 MB. Vyšší limit GPU rozpočet nezvýší. + Use Použít + In Front Vpředu + Behind Vzadu + +# DDS Options (#1327) + DDS Options Možnosti DDS + Generate Mipmaps Generovat mipmapy diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 48ebfba678..3aa7e7212b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2675,6 +2675,24 @@ cameraData Lens Objektiv Snap to Origin An Ursprung ausrichten Search settings… Einstellungen durchsuchen… No matching settings Keine passenden Einstellungen +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Aufnahmepinsel-Werkzeug + Sampling Area Overlay Überlagerung des Aufnahmebereichs + Show Sampling Area Aufnahmebereich einblenden + Indicates Kennzeichnet + Sampling Area Aufnahmebereich + Excluded Area Ausgeschlossener Bereich + Sampling Area Options Optionen für Aufnahmebereich + Rectangular Rechteckig + Fill Settings Füllungseinstellungen + Rotation Adaptation Drehungsanpassung + Very High Sehr hoch + Full Voll + Mirror Spiegeln + Output Settings Ausgabeeinstellungen + Output To Ausgabe in + Duplicate Layer Ebene duplizieren + Contract Verkleinern Loading fonts… Schriften werden geladen… Response curve Reaktionskurve Tool Werkzeug @@ -3176,6 +3194,10 @@ curves Smooth Glätten # View › Guides › right-click a guide Edit Selected Guides Ausgewählte Hilfslinien bearbeiten Clear Selected Guides Ausgewählte Hilfslinien löschen + Pasting from other apps is unavailable Einfügen aus anderen Apps ist nicht verfügbar + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft kann in dieser Sitzung nicht auf die Systemzwischenablage zugreifen. Unter Wayland verbirgt eine Flatpak-Sandbox das Protokoll, über das Bilder aus anderen Apps gelesen werden. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Um aus anderen Apps einzufügen, starte PhotoCraft unter XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Nichts einzufügen: PhotoCraft kann die Systemzwischenablage hier nicht lesen Delete this set Diesen Satz löschen New Set… Neuer Satz… PhotoCraft Defaults PhotoCraft-Standard @@ -3190,6 +3212,7 @@ curves Smooth Glätten There are too many sets: delete one first. Zu viele Sätze: Löschen Sie zuerst einen. set name Name des Satzes {set} (modified) {set} (geändert) + Show file name in title Dateiname im Titel anzeigen Accept and Go to Conflict Übernehmen und zum Konflikt Changes undone. Änderungen rückgängig gemacht. Choose a new shortcut for this command, or leave it without one. Wählen Sie einen neuen Kurzbefehl für diesen Befehl oder lassen Sie ihn ohne. @@ -3210,3 +3233,20 @@ curves Smooth Glätten This document's layers: {needed} of {budget} for layers Ebenen dieses Dokuments: {needed} von {budget} für Ebenen This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Die Ebenen dieses Dokuments brauchen {needed}, dürfen aber {budget} belegen: Das ganze Dokument wird auf der CPU neu gezeichnet GPU Memory (MB, 0 = Automatic) GPU-Speicher (MB, 0 = Automatisch) + {name} was changed by another app after it was opened or saved here. {name} wurde von einer anderen App geändert, nachdem es hier geöffnet oder gespeichert wurde. + Replace it with this document, or cancel and use File › Save As to keep both. Ersetze die Datei durch dieses Dokument oder brich ab und nutze Datei › Speichern unter, um beide zu behalten. + Memory Usage Speichernutzung + Per-document RAM limit (MB) RAM-Limit pro Dokument (MB) + Installed RAM: {ram} MB; this limit: {percent}% Installierter RAM: {ram} MB; dieses Limit: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Begrenzt Pixel plus Verlauf jedes offenen Dokuments. Die ältesten Widerrufsschritte werden verworfen, wenn das Limit überschritten wird. + Applies immediately when saved. Memory is not reserved in advance. Gilt sofort nach dem Speichern. Speicher wird nicht im Voraus reserviert. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Bei GPU-Speicher = Automatisch begrenzt dies auch das GPU-Ebenenbudget. Das Budget ist auf ein Viertel des RAM und, wenn bekannt, drei Achtel des Grafikspeichers begrenzt, mindestens 512 MB. Ein höheres Limit erhöht das GPU-Budget nicht. + Use Verwenden + In Front Davor + Behind Dahinter + Blend Mischen + +# DDS Options (#1327) + DDS Options DDS-Optionen + Compression Komprimierung + Generate Mipmaps Mipmaps erzeugen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f2c67c2c41..7b653fbbf6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3731,6 +3731,22 @@ cameraData Lens Φακός Snap to Origin Προσκόλληση στην αρχή Search settings… Αναζήτηση ρυθμίσεων… No matching settings Δεν βρέθηκαν ρυθμίσεις +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Εργαλείο πινέλου δειγματοληψίας + Sampling Area Overlay Επικάλυψη περιοχής δειγματοληψίας + Show Sampling Area Εμφάνιση περιοχής δειγματοληψίας + Indicates Υποδεικνύει + Sampling Area Περιοχή δειγματοληψίας + Excluded Area Εξαιρούμενη περιοχή + Sampling Area Options Επιλογές περιοχής δειγματοληψίας + Rectangular Ορθογώνια + Fill Settings Ρυθμίσεις γεμίσματος + Rotation Adaptation Προσαρμογή περιστροφής + Very High Πολύ υψηλή + Full Πλήρης + Mirror Κατοπτρισμός + Output Settings Ρυθμίσεις εξόδου + Output To Έξοδος σε Loading fonts… Φόρτωση γραμματοσειρών… Response curve Καμπύλη απόκρισης Simulate Pressure Προσομοίωση πίεσης @@ -3874,6 +3890,10 @@ curves Smooth Εξομάλυνση # View › Guides › right-click a guide Edit Selected Guides Επεξεργασία επιλεγμένων οδηγών Clear Selected Guides Απαλοιφή επιλεγμένων οδηγών + Pasting from other apps is unavailable Η επικόλληση από άλλες εφαρμογές δεν είναι διαθέσιμη + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. Το PhotoCraft δεν έχει πρόσβαση στο πρόχειρο του συστήματος σε αυτή τη συνεδρία. Στο Wayland, το sandbox του Flatpak κρύβει το πρωτόκολλο μέσω του οποίου διαβάζονται εικόνες από άλλες εφαρμογές. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Για επικόλληση από άλλες εφαρμογές, ξεκινήστε το PhotoCraft σε XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Τίποτα για επικόλληση: το PhotoCraft δεν μπορεί να διαβάσει εδώ το πρόχειρο του συστήματος Delete this set Διαγραφή αυτού του συνόλου New Set… Νέο σύνολο… PhotoCraft Defaults Προεπιλογές PhotoCraft @@ -3888,6 +3908,7 @@ curves Smooth Εξομάλυνση There are too many sets: delete one first. Υπάρχουν πάρα πολλά σύνολα: διαγράψτε πρώτα ένα. set name όνομα συνόλου {set} (modified) {set} (τροποποιημένο) + Show file name in title Εμφάνιση ονόματος αρχείου στον τίτλο Accept and Go to Conflict Αποδοχή και μετάβαση στη σύγκρουση Changes undone. Οι αλλαγές αναιρέθηκαν. Choose a new shortcut for this command, or leave it without one. Επιλέξτε νέα συντόμευση για αυτήν την εντολή ή αφήστε την χωρίς. @@ -3908,3 +3929,22 @@ curves Smooth Εξομάλυνση This document's layers: {needed} of {budget} for layers Επίπεδα αυτού του εγγράφου: {needed} από {budget} για επίπεδα This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Τα επίπεδα αυτού του εγγράφου χρειάζονται {needed} αλλά μπορούν να καταλάβουν {budget}: η επανασχεδίαση όλου του εγγράφου γίνεται στη CPU GPU Memory (MB, 0 = Automatic) Μνήμη GPU (MB, 0 = Αυτόματο) + {name} was changed by another app after it was opened or saved here. Το {name} άλλαξε από άλλη εφαρμογή αφού ανοίχτηκε ή αποθηκεύτηκε εδώ. + Replace it with this document, or cancel and use File › Save As to keep both. Αντικαταστήστε το με αυτό το έγγραφο ή ακυρώστε και χρησιμοποιήστε Αρχείο › Αποθήκευση ως για να κρατήσετε και τα δύο. + Decrease Brush Size Μείωση μεγέθους πινέλου + Increase Brush Size Αύξηση μεγέθους πινέλου + Decrease Brush Hardness Μείωση σκληρότητας πινέλου + Increase Brush Hardness Αύξηση σκληρότητας πινέλου + Memory Usage Χρήση μνήμης + Per-document RAM limit (MB) Όριο RAM ανά έγγραφο (MB) + Installed RAM: {ram} MB; this limit: {percent}% Εγκατεστημένη RAM: {ram} MB· αυτό το όριο: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Περιορίζει τα pixel συν το Ιστορικό κάθε ανοιχτού εγγράφου. Οι παλαιότερες καταστάσεις αναίρεσης απορρίπτονται όταν ξεπεραστεί το όριο. + Applies immediately when saved. Memory is not reserved in advance. Ισχύει αμέσως με την αποθήκευση. Η μνήμη δεν δεσμεύεται εκ των προτέρων. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Με Μνήμη GPU σε Αυτόματο, περιορίζει και τον προϋπολογισμό GPU. Ανώτατο όριο το 1/4 της RAM και, αν είναι γνωστό, τα 3/8 της μνήμης κάρτας, ελάχιστο 512 MB. Μεγαλύτερο όριο δεν αυξάνει τον προϋπολογισμό GPU. + Use Χρήση + In Front Μπροστά + Behind Πίσω + +# DDS Options (#1327) + DDS Options Επιλογές DDS + Generate Mipmaps Δημιουργία mipmap diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 45804fa2a4..eab6215dff 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2717,6 +2717,22 @@ cameraData Lens Objetivo Snap to Origin Ajustar a origen Search settings… Buscar ajustes… No matching settings No hay ajustes que coincidan +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Herramienta Pincel de muestreo + Sampling Area Overlay Superposición del área de muestreo + Show Sampling Area Mostrar área de muestreo + Indicates Indica + Sampling Area Área de muestreo + Excluded Area Área excluida + Sampling Area Options Opciones del área de muestreo + Rectangular Rectangular + Fill Settings Ajustes de relleno + Rotation Adaptation Adaptación de rotación + Very High Muy alta + Full Completa + Mirror Reflejar + Output Settings Ajustes de salida + Output To Salida a Loading fonts… Cargando fuentes… Response curve Curva de respuesta Tool Herramienta @@ -4136,6 +4152,10 @@ navigator Zoom Zoom # View › Guides › right-click a guide Edit Selected Guides Editar guías seleccionadas Clear Selected Guides Borrar guías seleccionadas + Pasting from other apps is unavailable Pegar desde otras aplicaciones no está disponible + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft no puede acceder al portapapeles del sistema en esta sesión. En Wayland, el entorno aislado de Flatpak oculta el protocolo con el que se leen las imágenes de otras aplicaciones. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Para pegar desde otras aplicaciones, inicia PhotoCraft en XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Nada que pegar: PhotoCraft no puede leer aquí el portapapeles del sistema Delete this set Eliminar este conjunto New Set… Nuevo conjunto… PhotoCraft Defaults Valores por defecto de PhotoCraft @@ -4150,6 +4170,7 @@ navigator Zoom Zoom There are too many sets: delete one first. Hay demasiados conjuntos: elimine uno primero. set name nombre del conjunto {set} (modified) {set} (modificado) + Show file name in title Mostrar nombre de archivo en el título Accept and Go to Conflict Aceptar e ir al conflicto Changes undone. Cambios deshechos. Choose a new shortcut for this command, or leave it without one. Elija un nuevo método abreviado para este comando o déjelo sin ninguno. @@ -4170,3 +4191,22 @@ navigator Zoom Zoom This document's layers: {needed} of {budget} for layers Capas de este documento: {needed} de {budget} para capas This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Las capas de este documento necesitan {needed} pero pueden ocupar {budget}: los redibujados de todo el documento usan la CPU GPU Memory (MB, 0 = Automatic) Memoria de GPU (MB, 0 = Automático) + {name} was changed by another app after it was opened or saved here. Otra aplicación cambió {name} después de abrirlo o guardarlo aquí. + Replace it with this document, or cancel and use File › Save As to keep both. Reemplázalo con este documento, o cancela y usa Archivo › Guardar como para conservar ambos. + Decrease Brush Size Reducir tamaño del pincel + Increase Brush Size Aumentar tamaño del pincel + Decrease Brush Hardness Reducir dureza del pincel + Increase Brush Hardness Aumentar dureza del pincel + Memory Usage Uso de memoria + Per-document RAM limit (MB) Límite de RAM por documento (MB) + Installed RAM: {ram} MB; this limit: {percent}% RAM instalada: {ram} MB; este límite: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Limita los píxeles más el Historial de cada documento abierto. Se descartan los estados de deshacer más antiguos al superar el límite. + Applies immediately when saved. Memory is not reserved in advance. Se aplica al guardar. La memoria no se reserva de antemano. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Con Memoria GPU en Automático, también limita el presupuesto GPU. Está topeado a un cuarto de la RAM y, si se conoce, tres octavos de la memoria de la tarjeta, mínimo 512 MB. Subir el límite no aumenta el presupuesto GPU. + Use Usar + In Front Delante + Behind Detrás + +# DDS Options (#1327) + DDS Options Opciones de DDS + Generate Mipmaps Generar mipmaps diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3e3451e096..80c7f110fe 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3051,6 +3051,24 @@ cameraData Lens Objectif Snap to Origin Aligner sur l'origine Search settings… Rechercher des réglages… No matching settings Aucun réglage correspondant +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Outil Pinceau d’échantillonnage + Sampling Area Overlay Incrustation de la zone d’échantillonnage + Show Sampling Area Afficher la zone d’échantillonnage + Indicates Indique + Sampling Area Zone d’échantillonnage + Excluded Area Zone exclue + Sampling Area Options Options de la zone d’échantillonnage + Rectangular Rectangulaire + Fill Settings Paramètres de remplissage + Rotation Adaptation Adaptation de la rotation + Very High Très élevée + Full Totale + Mirror Miroir + Output Settings Paramètres de sortie + Output To Sortie vers + Duplicate Layer Dupliquer le calque + Contract Contracter Loading fonts… Chargement des polices… Response curve Courbe de réponse Tool Outil @@ -3178,6 +3196,10 @@ curves Smooth Lisser # View › Guides › right-click a guide Edit Selected Guides Modifier les repères sélectionnés Clear Selected Guides Effacer les repères sélectionnés + Pasting from other apps is unavailable Le collage depuis d’autres applications est indisponible + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft ne peut pas accéder au presse-papiers du système dans cette session. Sous Wayland, le bac à sable Flatpak masque le protocole par lequel les images des autres applications sont lues. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Pour coller depuis d’autres applications, lancez PhotoCraft sous XWayland : `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Rien à coller : PhotoCraft ne peut pas lire ici le presse-papiers du système Delete this set Supprimer ce jeu New Set… Nouveau jeu… PhotoCraft Defaults Valeurs par défaut de PhotoCraft @@ -3193,6 +3215,7 @@ curves Smooth Lisser set name nom du jeu {set} (modified) {set} (modifié) Random Aléatoire + Show file name in title Afficher le nom de fichier dans le titre Accept and Go to Conflict Accepter et aller au conflit Changes undone. Modifications annulées. Choose a new shortcut for this command, or leave it without one. Choisissez un nouveau raccourci pour cette commande ou laissez-la sans raccourci. @@ -3213,3 +3236,24 @@ curves Smooth Lisser This document's layers: {needed} of {budget} for layers Calques de ce document : {needed} sur {budget} pour les calques This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Les calques de ce document ont besoin de {needed} mais peuvent occuper {budget} : le document entier se redessine sur le CPU GPU Memory (MB, 0 = Automatic) Mémoire GPU (Mo, 0 = Automatique) + Replace Remplacer + {name} was changed by another app after it was opened or saved here. {name} a été modifié par une autre application après avoir été ouvert ou enregistré ici. + Replace it with this document, or cancel and use File › Save As to keep both. Remplacez-le par ce document, ou annulez et utilisez Fichier › Enregistrer sous pour garder les deux. + Decrease Brush Size Réduire la taille du pinceau + Increase Brush Size Augmenter la taille du pinceau + Decrease Brush Hardness Réduire la dureté du pinceau + Increase Brush Hardness Augmenter la dureté du pinceau + Memory Usage Utilisation de la mémoire + Per-document RAM limit (MB) Limite RAM par document (Mo) + Installed RAM: {ram} MB; this limit: {percent}% RAM installée : {ram} Mo ; cette limite : {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Limite les pixels plus l’Historique de chaque document ouvert. Les plus anciens états d’annulation sont supprimés au-delà de la limite. + Applies immediately when saved. Memory is not reserved in advance. S’applique dès l’enregistrement. La mémoire n’est pas réservée à l’avance. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Si Mémoire GPU est Automatique, cela limite aussi le budget GPU. Il est plafonné à un quart de la RAM et, si connu, aux trois huitièmes de la mémoire de la carte, minimum 512 Mo. Dépasser ces plafonds n’augmente pas le budget GPU. + Use Utiliser + In Front Devant + Behind Derrière + +# DDS Options (#1327) + DDS Options Options DDS + Compression Compression + Generate Mipmaps Générer les mipmaps diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9dc9a47fbc..ca747637ce 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4017,6 +4017,22 @@ cameraRaw Yellow Sárga The layer or its mask changed. Drag the mask onto the Trash again. A réteg vagy a maszkja megváltozott. Húzd újra a maszkot a Kukába. Transform On Drop Átalakítás elengedéskor Vanishing Point is not active Az Enyészpont nem aktív +# Edit › Content-Aware Fill workspace + Excluded Area Kizárt terület + Fill Settings Kitöltési beállítások + Full Teljes + Indicates Jelzi + Mirror Tükrözés + Output Settings Kimeneti beállítások + Output To Kimenet célja + Rectangular Téglalap + Rotation Adaptation Elforgatás-adaptáció + Sampling Area Mintavételi terület + Sampling Area Options Mintavételi terület beállításai + Sampling Area Overlay Mintavételi terület átfedése + Sampling Brush Tool Mintavételi ecset + Show Sampling Area Mintavételi terület megjelenítése + Very High Nagyon magas Vanishing Point: click four corners to create a plane Enyészpont: sík létrehozásához kattints a négy sarokra Response curve Válaszgörbe Show home recent files Legutóbbi fájlok megjelenítése a kezdőképernyőn @@ -4093,6 +4109,10 @@ cameraRaw Yellow Sárga # View › Guides › right-click a guide Edit Selected Guides Kijelölt segédvonalak szerkesztése Clear Selected Guides Kijelölt segédvonalak törlése + Pasting from other apps is unavailable A beillesztés más alkalmazásokból nem érhető el + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. A PhotoCraft ebben a munkamenetben nem fér hozzá a rendszer vágólapjához. Waylanden a Flatpak homokozó elrejti azt a protokollt, amelyen keresztül más alkalmazások képei olvashatók. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Ha más alkalmazásokból szeretne beilleszteni, indítsa a PhotoCraftot XWayland alatt: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Nincs mit beilleszteni: a PhotoCraft itt nem tudja olvasni a rendszer vágólapját Delete this set Készlet törlése New Set… Új készlet… PhotoCraft Defaults PhotoCraft alapértelmezések @@ -4107,6 +4127,7 @@ cameraRaw Yellow Sárga There are too many sets: delete one first. Túl sok készlet van: előbb töröljön egyet. set name készlet neve {set} (modified) {set} (módosítva) + Show file name in title Fájlnév megjelenítése a címben Accept and Go to Conflict Elfogadás és ugrás az ütközéshez Changes undone. Változások visszavonva. Choose a new shortcut for this command, or leave it without one. Válasszon új billentyűparancsot ehhez a parancshoz, vagy hagyja nélküle. @@ -4127,3 +4148,22 @@ cameraRaw Yellow Sárga This document's layers: {needed} of {budget} for layers A dokumentum rétegei: {needed} / {budget} a rétegeknek This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU A dokumentum rétegeinek {needed} kell, de {budget} foglalhatnak: a teljes dokumentum újrarajzolása a CPU-n fut GPU Memory (MB, 0 = Automatic) GPU-memória (MB, 0 = Automatikus) + {name} was changed by another app after it was opened or saved here. A(z) {name} fájlt egy másik alkalmazás módosította, miután itt megnyitották vagy mentették. + Replace it with this document, or cancel and use File › Save As to keep both. Cserélje le erre a dokumentumra, vagy válassza a Mégse gombot, és a Fájl › Mentés másként paranccsal tartsa meg mindkettőt. + Decrease Brush Size Ecsetméret csökkentése + Increase Brush Size Ecsetméret növelése + Decrease Brush Hardness Ecsetkeménység csökkentése + Increase Brush Hardness Ecsetkeménység növelése + Memory Usage Memóriahasználat + Per-document RAM limit (MB) Dokumentumonkénti RAM-korlát (MB) + Installed RAM: {ram} MB; this limit: {percent}% Telepített RAM: {ram} MB; ez a korlát: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Minden nyitott dokumentum pixeljeit és előzményeit korlátozza. A legrégebbi visszavonási állapotok törlődnek a korlát túllépésekor. + Applies immediately when saved. Memory is not reserved in advance. Mentéskor azonnal érvényes. A memória nincs előre lefoglalva. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Automatikus GPU-memóriánál a GPU-rétegkeretet is korlátozza. Felső határ a RAM negyede és, ha ismert, a kártyamemória háromnyolcada, minimum 512 MB. Magasabb korlát a GPU-keretet nem növeli. + Use Használat + In Front Elöl + Behind Mögött + +# DDS Options (#1327) + DDS Options DDS-beállítások + Generate Mipmaps Mipmapek létrehozása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 81e850f293..4fd06fd88f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3038,6 +3038,24 @@ cameraData Lens Lensa Snap to Origin Jepret ke Titik Asal Search settings… Cari pengaturan… No matching settings Tidak ada pengaturan yang cocok +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Alat Kuas Pengambilan Sampel + Sampling Area Overlay Hamparan Area Pengambilan Sampel + Show Sampling Area Tampilkan Area Pengambilan Sampel + Indicates Menandai + Sampling Area Area Pengambilan Sampel + Excluded Area Area yang Dikecualikan + Sampling Area Options Opsi Area Pengambilan Sampel + Rectangular Persegi Panjang + Fill Settings Pengaturan Isian + Rotation Adaptation Adaptasi Rotasi + Very High Sangat Tinggi + Full Penuh + Mirror Cermin + Output Settings Pengaturan Keluaran + Output To Keluaran Ke + Duplicate Layer Duplikat Layer + Contract Ciutkan Loading fonts… Memuat font… Response curve Kurva respons Tool Alat @@ -3165,6 +3183,10 @@ curves Smooth Haluskan # View › Guides › right-click a guide Edit Selected Guides Edit Panduan Terpilih Clear Selected Guides Hapus Panduan Terpilih + Pasting from other apps is unavailable Menempel dari aplikasi lain tidak tersedia + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft tidak dapat mengakses papan klip sistem dalam sesi ini. Di Wayland, sandbox Flatpak menyembunyikan protokol yang digunakan untuk membaca gambar dari aplikasi lain. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Untuk menempel dari aplikasi lain, jalankan PhotoCraft di bawah XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Tidak ada yang ditempel: PhotoCraft tidak dapat membaca papan klip sistem di sini Delete this set Hapus set ini New Set… Set Baru… PhotoCraft Defaults Bawaan PhotoCraft @@ -3180,6 +3202,7 @@ curves Smooth Haluskan set name nama set {set} (modified) {set} (diubah) Random Acak + Show file name in title Tampilkan nama file di judul Accept and Go to Conflict Terima dan Buka Konflik Changes undone. Perubahan dibatalkan. Choose a new shortcut for this command, or leave it without one. Pilih pintasan baru untuk perintah ini, atau biarkan tanpa pintasan. @@ -3200,3 +3223,24 @@ curves Smooth Haluskan This document's layers: {needed} of {budget} for layers Layer dokumen ini: {needed} dari {budget} untuk layer This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Layer dokumen ini membutuhkan {needed} tetapi boleh memakai {budget}: penggambaran ulang seluruh dokumen memakai CPU GPU Memory (MB, 0 = Automatic) Memori GPU (MB, 0 = Otomatis) + Replace Ganti + {name} was changed by another app after it was opened or saved here. {name} diubah oleh aplikasi lain setelah dibuka atau disimpan di sini. + Replace it with this document, or cancel and use File › Save As to keep both. Ganti dengan dokumen ini, atau batalkan dan gunakan Berkas › Simpan Sebagai untuk menyimpan keduanya. + Decrease Brush Size Perkecil ukuran kuas + Increase Brush Size Perbesar ukuran kuas + Decrease Brush Hardness Kurangi kekerasan kuas + Increase Brush Hardness Tambah kekerasan kuas + Memory Usage Penggunaan memori + Per-document RAM limit (MB) Batas RAM per dokumen (MB) + Installed RAM: {ram} MB; this limit: {percent}% RAM terpasang: {ram} MB; batas ini: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Membatasi piksel plus Riwayat setiap dokumen terbuka. Status urungkan tertua dibuang jika batas terlampaui. + Applies immediately when saved. Memory is not reserved in advance. Berlaku segera setelah disimpan. Memori tidak dipesan di muka. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Jika Memori GPU Otomatis, ini juga membatasi anggaran GPU. Plafon seperempat RAM dan, jika diketahui, tiga per delapan memori kartu, minimum 512 MB. Menaikkan batas tidak menambah anggaran GPU. + Use Gunakan + In Front Di Depan + Behind Di Belakang + +# DDS Options (#1327) + DDS Options Opsi DDS + Compression Kompresi + Generate Mipmaps Buat mipmap diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c097ded29d..1143b138f9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2705,6 +2705,22 @@ cameraData Lens Obiettivo Snap to Origin Aggancia all'origine Search settings… Cerca impostazioni… No matching settings Nessuna impostazione corrispondente +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Strumento Pennello di campionamento + Sampling Area Overlay Sovrapposizione area di campionamento + Show Sampling Area Mostra area di campionamento + Indicates Indica + Sampling Area Area di campionamento + Excluded Area Area esclusa + Sampling Area Options Opzioni area di campionamento + Rectangular Rettangolare + Fill Settings Impostazioni di riempimento + Rotation Adaptation Adattamento rotazione + Very High Molto alta + Full Completa + Mirror Rifletti + Output Settings Impostazioni di output + Output To Output in Loading fonts… Caricamento font… Response curve Curva di risposta Tool Strumento @@ -4295,6 +4311,10 @@ shape Appearance Aspetto # View › Guides › right-click a guide Edit Selected Guides Modifica guide selezionate Clear Selected Guides Cancella guide selezionate + Pasting from other apps is unavailable Incollare da altre app non è disponibile + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft non può accedere agli appunti di sistema in questa sessione. Su Wayland, la sandbox di Flatpak nasconde il protocollo con cui vengono lette le immagini delle altre app. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Per incollare da altre app, avvia PhotoCraft in XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Niente da incollare: qui PhotoCraft non può leggere gli appunti di sistema Delete this set Elimina questo set New Set… Nuovo set… PhotoCraft Defaults Predefiniti di PhotoCraft @@ -4309,6 +4329,7 @@ shape Appearance Aspetto There are too many sets: delete one first. Ci sono troppi set: eliminane prima uno. set name nome del set {set} (modified) {set} (modificato) + Show file name in title Mostra nome file nel titolo Accept and Go to Conflict Accetta e vai al conflitto Changes undone. Modifiche annullate. Choose a new shortcut for this command, or leave it without one. Scegli una nuova scorciatoia per questo comando o lascialo senza. @@ -4329,3 +4350,18 @@ shape Appearance Aspetto This document's layers: {needed} of {budget} for layers Livelli di questo documento: {needed} su {budget} per i livelli This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU I livelli di questo documento richiedono {needed} ma possono occupare {budget}: i ridisegni dell'intero documento usano la CPU GPU Memory (MB, 0 = Automatic) Memoria GPU (MB, 0 = Automatico) + {name} was changed by another app after it was opened or saved here. {name} è stato modificato da un'altra app dopo essere stato aperto o salvato qui. + Replace it with this document, or cancel and use File › Save As to keep both. Sostituiscilo con questo documento, oppure annulla e usa File › Salva con nome per tenerli entrambi. + Memory Usage Utilizzo memoria + Per-document RAM limit (MB) Limite RAM per documento (MB) + Installed RAM: {ram} MB; this limit: {percent}% RAM installata: {ram} MB; questo limite: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Limita i pixel più la Cronologia di ogni documento aperto. Gli stati Annulla più vecchi vengono scartati oltre il limite. + Applies immediately when saved. Memory is not reserved in advance. Si applica al salvataggio. La memoria non è riservata in anticipo. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Con Memoria GPU Automatica limita anche il budget GPU. È limitato a un quarto della RAM e, se nota, a tre ottavi della memoria della scheda, minimo 512 MB. Alzare il limite non aumenta il budget GPU. + Use Usa + In Front Davanti + Behind Dietro + +# DDS Options (#1327) + DDS Options Opzioni DDS + Generate Mipmaps Genera mipmap diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b460965128..8564b9b308 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3646,6 +3646,22 @@ cameraData Lens レンズ Snap to Origin 原点にスナップ Search settings… 設定を検索… No matching settings 一致する設定はありません +# Edit › Content-Aware Fill workspace + Sampling Brush Tool サンプリングブラシツール + Sampling Area Overlay サンプリング領域のオーバーレイ + Show Sampling Area サンプリング領域を表示 + Indicates 表示対象 + Sampling Area サンプリング領域 + Excluded Area 除外された領域 + Sampling Area Options サンプリング領域オプション + Rectangular 長方形 + Fill Settings 塗りつぶし設定 + Rotation Adaptation 回転への適応 + Very High 非常に高い + Full フル + Mirror ミラー + Output Settings 出力設定 + Output To 出力先 Loading fonts… フォントを読み込み中… Response curve 応答カーブ Simulate Pressure 筆圧をシミュレート @@ -3850,6 +3866,10 @@ curves Smooth スムーズ # View › Guides › right-click a guide Edit Selected Guides 選択したガイドを編集 Clear Selected Guides 選択したガイドを消去 + Pasting from other apps is unavailable 他のアプリからの貼り付けは利用できません + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. このセッションでは PhotoCraft がシステムのクリップボードにアクセスできません。Wayland では、Flatpak のサンドボックスが他のアプリの画像を読み取るためのプロトコルを隠します。 + To paste from other apps, start PhotoCraft under XWayland: `{command}` 他のアプリから貼り付けるには、XWayland 上で PhotoCraft を起動してください: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here 貼り付けるものがありません: ここでは PhotoCraft がシステムのクリップボードを読み取れません Delete this set このセットを削除 New Set… 新規セット… PhotoCraft Defaults PhotoCraft 初期設定 @@ -3864,6 +3884,7 @@ curves Smooth スムーズ There are too many sets: delete one first. セットが多すぎます。先に 1 つ削除してください。 set name セット名 {set} (modified) {set}(変更あり) + Show file name in title タイトルにファイル名を表示 Accept and Go to Conflict 適用して競合へ移動 Changes undone. 変更を取り消しました。 Choose a new shortcut for this command, or leave it without one. このコマンドに新しいショートカットを選択するか、なしのままにしてください。 @@ -3884,3 +3905,24 @@ curves Smooth スムーズ This document's layers: {needed} of {budget} for layers このドキュメントのレイヤー: レイヤー用 {budget} のうち {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU このドキュメントのレイヤーには {needed} が必要ですが、使えるのは {budget} です: ドキュメント全体の再描画は CPU で行われます GPU Memory (MB, 0 = Automatic) GPU メモリ(MB、0 = 自動) + Replace 置き換え + {name} was changed by another app after it was opened or saved here. {name} は、ここで開くか保存した後に別のアプリで変更されました。 + Replace it with this document, or cancel and use File › Save As to keep both. この書類で置き換えるか、キャンセルしてファイル › 名前を付けて保存で両方を残してください。 + Decrease Brush Size ブラシサイズを小さく + Increase Brush Size ブラシサイズを大きく + Decrease Brush Hardness ブラシの硬さを下げる + Increase Brush Hardness ブラシの硬さを上げる + Memory Usage メモリ使用量 + Per-document RAM limit (MB) ドキュメントあたりの RAM 上限 (MB) + Installed RAM: {ram} MB; this limit: {percent}% 搭載 RAM: {ram} MB、この上限: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. 開いている各ドキュメントのピクセルと履歴を制限します。上限を超えると最も古い取り消し状態が破棄されます。 + Applies immediately when saved. Memory is not reserved in advance. 保存するとすぐに適用されます。メモリは事前に予約されません。 + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. GPU メモリが自動のとき、GPU レイヤー予算も制限します。上限は搭載 RAM の 1/4、判明していればグラフィックメモリの 3/8、最低 512 MB です。これ以上に上げても GPU 予算は増えません。 + Use 使用 + In Front 前面 + Behind 背面 + +# DDS Options (#1327) + DDS Options DDS オプション + Compression 圧縮 + Generate Mipmaps ミップマップを生成 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 361cef2e95..b99fde8236 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -507,7 +507,7 @@ Save Default Type Styles 기본 문자 스타일 저장 Deselect 선택 해제 Reselect 다시 선택 - Inverse 반대로 + Inverse 반전 Inverse Selection 선택 영역 반전 Similar 유사한 항목 Color Range… 색상 범위… @@ -743,6 +743,7 @@ Brush Settings 브러시 설정 Brushes 브러시 Channels 채널 + Channel 채널 Character 문자 Character Styles 문자 스타일 Clone Source 복제 원본 @@ -1210,6 +1211,7 @@ Levels 레벨 Lighten 밝게 하기 Lightness 명도 + Result 결과 Lights 밝은 계열 Limits: 제한: Linear Gradient 선형 그레이디언트 @@ -1399,10 +1401,10 @@ Imported {n} shortcuts from {file}. Click OK to keep them. {file}에서 단축키 {n}개를 가져왔습니다. 유지하려면 확인을 클릭하세요. {n} commands are not in PhotoCraft. 명령 {n}개는 PhotoCraft에 없습니다. Keyboard shortcuts imported 키보드 단축키를 가져왔습니다 - Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. 키보드 단축키 세트 {set}을(를) 여기서 사용합니다. 단축키 {n}개가 기본값과 다릅니다. 편집 › 키보드 단축키에서 확인할 수 있고, 모두 기본값으로 재설정으로 되돌릴 수 있습니다. - Import keyboard shortcuts? 키보드 단축키를 가져올까요? - PhotoCraft found your keyboard shortcut set {set} from another image editor on this computer: {n} of its shortcuts differ from PhotoCraft's. Import it? PhotoCraft가 이 컴퓨터에서 다른 이미지 편집기의 키보드 단축키 세트 {set}을(를) 찾았습니다. 단축키 {n}개가 PhotoCraft와 다릅니다. 가져올까요? - Edit › Keyboard Shortcuts › Reset All to Defaults undoes an import. 편집 › 키보드 단축키 › 모두 기본값으로 재설정으로 가져오기를 되돌릴 수 있습니다. + Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. 키보드 단축키 세트 {set}을(를) 여기서 사용합니다. 단축키 {n}개가 기본값과 다릅니다. 편집 › 키보드 단축키에서 확인할 수 있고, 모두 기본값으로 초기화로 되돌릴 수 있습니다. + Import keyboard shortcuts? 키보드 단축키를 가져오시겠습니까? + PhotoCraft found your keyboard shortcut set {set} from another image editor on this computer: {n} of its shortcuts differ from PhotoCraft's. Import it? PhotoCraft가 이 컴퓨터에서 다른 이미지 편집기의 키보드 단축키 세트 {set}을(를) 찾았습니다. 단축키 {n}개가 PhotoCraft와 다릅니다. 가져오시겠습니까? + Edit › Keyboard Shortcuts › Reset All to Defaults undoes an import. 편집 › 키보드 단축키 › 모두 기본값으로 초기화를 누르면 가져오기를 되돌릴 수 있습니다. Don't Import 가져오지 않음 The keyboard shortcut set was not imported: {error} 키보드 단축키 세트를 가져오지 못했습니다: {error} Reset Section 섹션 초기화 @@ -1817,8 +1819,8 @@ Zoom Tool 돋보기 도구 {name} Properties {name} 속성 Revert “{name}” to the last saved version? Your changes will be lost. “{name}”을(를) 마지막으로 저장한 버전으로 되돌릴까요? 변경 사항이 사라집니다. - Do you want to save the changes you made to “{name}” before quitting? 종료하기 전에 “{name}”의 변경 사항을 저장할까요? - Do you want to save the changes you made to “{name}” before closing? 닫기 전에 “{name}”의 변경 사항을 저장할까요? + Do you want to save the changes you made to “{name}” before quitting? 종료하기 전에 “{name}”의 변경 사항을 저장하시겠습니까? + Do you want to save the changes you made to “{name}” before closing? 닫기 전에 “{name}”의 변경 사항을 저장하시겠습니까? Doc: {flat}/{layered} 문서: {flat}/{layered} Scratch: {size} 스크래치: {size} Untagged {mode} 프로파일 없는 {mode} @@ -2127,12 +2129,12 @@ The current gradient (pick one in Window › Gradients) 현재 그레이디언트(창 › 그레이디언트에서 선택) Select a type layer to edit its character and paragraph settings. 문자 및 단락 설정을 편집하려면 문자 레이어를 선택하세요. # Gradient Editor window, opened from the options bar's gradient swatch. - Gradient Editor 그라디언트 편집기 - Gradient picker 그라디언트 선택기 - Save As Preset 프리셋으로 저장 - The gradient the Gradient tool paints with 그라디언트 도구가 칠하는 그라디언트입니다 - Adds the current gradient to the Gradients panel 현재 그라디언트를 그라디언트 패널에 추가합니다 - Gradient stops 그라디언트 스톱 + Gradient Editor 그레이디언트 편집기 + Gradient picker 그레이디언트 선택기 + Save As Preset 사전 설정으로 저장 + The gradient the Gradient tool paints with 그레이디언트 도구가 칠하는 그레이디언트입니다 + Adds the current gradient to the Gradients panel 현재 그레이디언트를 그레이디언트 패널에 추가합니다 + Gradient stops 그레이디언트 스톱 Text color 텍스트 색상 Type Options 문자 옵션 Anti-aliasing method 앤티 앨리어스 방식 @@ -3041,7 +3043,7 @@ fontWeight Italic 기울임 Rotate View 보기 회전 Rotate View Tool 보기 회전 도구 Reset View 보기 재설정 - Drag around the centre to rotate the view · Shift constrains to 15° 중심 주위를 드래그해 보기를 회전합니다 · Shift는 15°로 제한 + Drag around the centre to rotate the view · Shift constrains to 15° 중심 주위를 드래그해 보기 회전 · Shift로 15° 단위 제한 # Painting symmetry presets. Dual Axis 이중 축 @@ -3070,7 +3072,7 @@ fontWeight Italic 기울임 PhotoCraft — Screen Color Picker PhotoCraft — 화면 색상 선택기 Rasterize svg groups deeper than 이 깊이보다 깊은 SVG 그룹 래스터화 - 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0이면 이 임계값을 끕니다. 100단계보다 깊이 중첩된 SVG 그룹은 항상 래스터화됩니다. + 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0이면 이 한계값을 끕니다. 100단계보다 깊이 중첩된 SVG 그룹은 항상 래스터화됩니다. Rule of Thirds 삼등분 법칙 Golden Ratio 황금 비율 Golden Spiral 황금 나선 @@ -3140,15 +3142,15 @@ fontWeight Italic 기울임 Dashed line 파선 Dash 선 Gap 간격 - Dash / gap lengths × stroke width 선 / 간격 길이 × 획 너비 + Dash / gap lengths × stroke width 선 / 간격 길이 × 획 폭 Add pair 쌍 추가 Remove pair 쌍 제거 Dash offset 파선 오프셋 Open paths use centered strokes 열린 패스는 가운데 획을 사용합니다 Use finite lengths and a positive pattern total 유한한 길이와 양수 패턴 합계를 사용하세요 - No subject found — try Object Selection or the Lasso 피사체를 찾을 수 없습니다 — 개체 선택 또는 올가미를 사용해 보세요 + No subject found — try Object Selection or the Lasso 피사체를 찾을 수 없습니다 — 오브젝트 선택 또는 올가미를 사용해 보세요 Quick Selection found nothing there 빠른 선택으로 해당 위치에서 아무것도 찾지 못했습니다 - Object Selection found nothing there — try a tighter rectangle 개체 선택으로 해당 위치에서 아무것도 찾지 못했습니다 — 더 좁은 사각형을 사용해 보세요 + Object Selection found nothing there — try a tighter rectangle 오브젝트 선택으로 해당 위치에서 아무것도 찾지 못했습니다 — 더 좁은 사각형을 사용해 보세요 No subject found — try a rectangle around the object 피사체를 찾을 수 없습니다 — 개체 주위에 사각형을 그려 보세요 Auto Erase 자동 지우기 Click the first point or press {key} to close · {del} removes a point · Esc cancels 첫 점을 클릭하거나 {key}를 눌러 닫기 · {del}로 점 제거 · Esc로 취소 @@ -3219,6 +3221,22 @@ cameraData Lens 렌즈 Snap to Origin 원점에 스냅 Search settings… 설정 검색… No matching settings 일치하는 설정 없음 +# Edit › Content-Aware Fill workspace + Sampling Brush Tool 샘플링 브러시 도구 + Sampling Area Overlay 샘플링 영역 오버레이 + Show Sampling Area 샘플링 영역 표시 + Indicates 표시 대상 + Sampling Area 샘플링 영역 + Excluded Area 제외 영역 + Sampling Area Options 샘플링 영역 옵션 + Rectangular 사각형 + Fill Settings 채우기 설정 + Rotation Adaptation 회전 적응 + Very High 매우 높음 + Full 전체 + Mirror 미러 + Output Settings 출력 설정 + Output To 출력 위치 Loading fonts… 글꼴 불러오는 중… Response curve 응답 곡선 Simulate Pressure 압력 시뮬레이션 @@ -3352,6 +3370,10 @@ curves Smooth 매끄럽게 # View › Guides › right-click a guide Edit Selected Guides 선택한 안내선 편집 Clear Selected Guides 선택한 안내선 지우기 + Pasting from other apps is unavailable 다른 앱에서 붙여넣기를 사용할 수 없습니다 + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. 이 세션에서는 PhotoCraft가 시스템 클립보드에 접근할 수 없습니다. Wayland에서는 Flatpak 샌드박스가 다른 앱의 이미지를 읽는 데 쓰이는 프로토콜을 숨깁니다. + To paste from other apps, start PhotoCraft under XWayland: `{command}` 다른 앱에서 붙여넣으려면 XWayland에서 PhotoCraft를 실행하세요: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here 붙여넣을 내용 없음: 여기서는 PhotoCraft가 시스템 클립보드를 읽을 수 없습니다 Delete this set 이 세트 삭제 New Set… 새 세트… PhotoCraft Defaults PhotoCraft 기본값 @@ -3366,6 +3388,7 @@ curves Smooth 매끄럽게 There are too many sets: delete one first. 세트가 너무 많습니다. 먼저 하나를 삭제하세요. set name 세트 이름 {set} (modified) {set}(수정됨) + Show file name in title 제목에 파일 이름 표시 Accept and Go to Conflict 적용 후 충돌 항목으로 이동 Changes undone. 변경 사항을 취소했습니다. Choose a new shortcut for this command, or leave it without one. 이 명령의 새 단축키를 선택하거나 단축키 없이 두세요. @@ -3386,3 +3409,25 @@ curves Smooth 매끄럽게 This document's layers: {needed} of {budget} for layers 이 문서의 레이어: 레이어용 {budget} 중 {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU 이 문서의 레이어에 {needed}가 필요하지만 {budget}만 사용할 수 있습니다: 문서 전체 다시 그리기는 CPU를 사용합니다 GPU Memory (MB, 0 = Automatic) GPU 메모리(MB, 0 = 자동) + Replace 대치 + {name} was changed by another app after it was opened or saved here. {name}이(가) 여기서 열거나 저장한 뒤 다른 앱에서 변경되었습니다. + Replace it with this document, or cancel and use File › Save As to keep both. 이 문서로 대치하거나, 취소하고 파일 › 다른 이름으로 저장을 사용해 둘 다 보관하세요. + Decrease Brush Size 브러시 크기 줄이기 + Increase Brush Size 브러시 크기 늘리기 + Decrease Brush Hardness 브러시 경도 줄이기 + Increase Brush Hardness 브러시 경도 늘리기 + Memory Usage 메모리 사용량 + Per-document RAM limit (MB) 문서당 RAM 한도(MB) + Installed RAM: {ram} MB; this limit: {percent}% 설치된 RAM: {ram} MB; 이 한도: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. 열린 각 문서의 픽셀과 기록을 제한합니다. 한도를 넘으면 가장 오래된 실행 취소 상태가 버려집니다. + Applies immediately when saved. Memory is not reserved in advance. 저장하면 바로 적용됩니다. 메모리를 미리 예약하지 않습니다. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. GPU 메모리가 자동이면 GPU 레이어 예산도 제한합니다. 상한은 설치 RAM의 1/4, 알려진 경우 그래픽 메모리의 3/8, 최소 512MB입니다. 이보다 올려도 GPU 예산은 늘지 않습니다. + Use 사용 + In Front 앞 + Behind 뒤 + Blend 혼합 + +# DDS Options (#1327) + DDS Options DDS 옵션 + Compression 압축 + Generate Mipmaps 밉맵 생성 diff --git a/crates/ui-egui/src/i18n/live_tests.rs b/crates/ui-egui/src/i18n/live_tests.rs index 89c47ef1ac..7d8d6457ef 100644 --- a/crates/ui-egui/src/i18n/live_tests.rs +++ b/crates/ui-egui/src/i18n/live_tests.rs @@ -42,6 +42,46 @@ fn ukrainian_native_app_menu_keeps_product_and_language_names() { }); } +#[test] +fn ukrainian_color_picker_titles_draw_in_the_selected_language() { + with_language(Lang::EN, || { + for (target, expected) in [("foreground", "Вибір кольору (основний колір)"), ("background", "Вибір кольору (колір тла)")] + { + let mut h = harness(); + h.state_mut().run("prefs.set", json!({"path": "interface.language", "value": "uk"})).unwrap(); + crate::color_picker_ui::open(h.state_mut(), target); + h.run_steps(4); + let text = drawn_text(&h); + assert!(text.iter().any(|text| text == expected), "missing title {expected}"); + assert!(!text.iter().any(|text| text.starts_with("Color Picker")), "no English picker title"); + } + assert_eq!(tr(lang("uk"), "Color Picker (Custom Canvas Color)"), "Вибір кольору (власний колір полотна)"); + }); +} + +#[test] +fn ukrainian_rasterize_prompts_explain_the_loss_of_editable_content() { + use crate::rasterize_prompt::Kind; + + for kind in Kind::ALL { + let translated = tr(lang("uk"), kind.message()); + assert_ne!(translated, kind.message(), "{kind:?}: the warning must be translated"); + assert!(translated.contains("більше не можна буде редагувати"), "{kind:?}: explain the loss of editability"); + } + with_language(Lang::EN, || { + let mut h = harness(); + h.state_mut().run("prefs.set", json!({"path": "interface.language", "value": "uk"})).unwrap(); + h.state_mut().run("type.create", json!({"text": "Editable text"})).unwrap(); + let layer = h.state().session.active().unwrap().active_layer.unwrap(); + crate::rasterize_prompt::open(h.state_mut(), Kind::Type, layer, crate::state::Tool::Brush, [10.0, 10.0, 1.0]); + h.run_steps(4); + let expected = tr(lang("uk"), Kind::Type.message()); + let text = drawn_text(&h); + assert!(text.iter().any(|text| text == expected), "the actual dialog draws the Ukrainian warning"); + assert!(!text.iter().any(|text| text == Kind::Type.message())); + }); +} + #[test] fn french_and_korean_plural_messages_keep_placeholders() { for (n, expected) in [(0, "0 élément"), (1, "1 élément"), (2, "2 éléments"), (21, "21 éléments")] { diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index b976e395fc..c7a0d574b2 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -514,6 +514,21 @@ mod tests { assert_eq!(Lang::from_pref("xx-unknown"), Lang::EN); } + /// The brush size/hardness shortcut rows (`tools.*` commands without a menu item) must be translated in + /// every catalog, or they show English in the Keyboard Shortcuts dialog and cannot be found by searching. + #[test] + fn brush_size_and_hardness_shortcuts_are_translated_in_every_language() { + let keys = ["Decrease Brush Size", "Increase Brush Size", "Decrease Brush Hardness", "Increase Brush Hardness"]; + for lang in Lang::all().filter(|lang| *lang != Lang::EN) { + for key in keys { + assert!(has(lang, key), "{} has no translation for {key:?}", lang.code()); + } + } + let zh = Lang::from_code("zh-hans").expect("zh-hans registered"); + assert_eq!(tr(zh, "Decrease Brush Size"), "减小画笔大小"); + assert_eq!(tr(zh, "Increase Brush Size"), "增大画笔大小"); + } + #[test] fn simplified_chinese_covers_dynamic_shortcuts_and_layer_counts() { let zh = Lang::from_code("zh-hans").expect("zh-hans registered"); diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f1ac67961e..791d173cb0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3790,6 +3790,22 @@ cameraData Lens Lens Search settings… Instellingen zoeken… No matching settings Geen overeenkomende instellingen PhotoCraft — Screen Color Picker PhotoCraft — Schermkleurkiezer +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Gereedschap Monsterpenseel + Sampling Area Overlay Overlay van monstergebied + Show Sampling Area Monstergebied tonen + Indicates Geeft aan + Sampling Area Monstergebied + Excluded Area Uitgesloten gebied + Sampling Area Options Opties voor monstergebied + Rectangular Rechthoekig + Fill Settings Vulinstellingen + Rotation Adaptation Rotatieaanpassing + Very High Zeer hoog + Full Volledig + Mirror Spiegelen + Output Settings Uitvoerinstellingen + Output To Uitvoer naar Loading fonts… Lettertypen laden… Response curve Responscurve Simulate Pressure Druk simuleren @@ -3934,6 +3950,10 @@ curves Smooth Vloeiend maken # View › Guides › right-click a guide Edit Selected Guides Geselecteerde hulplijnen bewerken Clear Selected Guides Geselecteerde hulplijnen wissen + Pasting from other apps is unavailable Plakken vanuit andere apps is niet beschikbaar + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft heeft in deze sessie geen toegang tot het systeemklembord. Onder Wayland verbergt een Flatpak-sandbox het protocol waarmee afbeeldingen uit andere apps worden gelezen. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Om vanuit andere apps te plakken, start je PhotoCraft onder XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Niets om te plakken: PhotoCraft kan het systeemklembord hier niet lezen Delete this set Deze set verwijderen New Set… Nieuwe set… PhotoCraft Defaults PhotoCraft-standaard @@ -3948,6 +3968,7 @@ curves Smooth Vloeiend maken There are too many sets: delete one first. Er zijn te veel sets: verwijder er eerst een. set name naam van de set {set} (modified) {set} (gewijzigd) + Show file name in title Bestandsnaam in titel weergeven Accept and Go to Conflict Accepteren en naar conflict Changes undone. Wijzigingen ongedaan gemaakt. Choose a new shortcut for this command, or leave it without one. Kies een nieuwe sneltoets voor deze opdracht of laat hem zonder. @@ -3968,3 +3989,22 @@ curves Smooth Vloeiend maken This document's layers: {needed} of {budget} for layers Lagen van dit document: {needed} van {budget} voor lagen This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU De lagen van dit document hebben {needed} nodig maar mogen {budget} gebruiken: het hele document wordt op de CPU opnieuw getekend GPU Memory (MB, 0 = Automatic) GPU-geheugen (MB, 0 = Automatisch) + {name} was changed by another app after it was opened or saved here. {name} is door een andere app gewijzigd nadat het hier is geopend of bewaard. + Replace it with this document, or cancel and use File › Save As to keep both. Vervang het door dit document, of annuleer en gebruik Bestand › Opslaan als om beide te houden. + Decrease Brush Size Penseelgrootte verkleinen + Increase Brush Size Penseelgrootte vergroten + Decrease Brush Hardness Penseelhardheid verlagen + Increase Brush Hardness Penseelhardheid verhogen + Memory Usage Geheugengebruik + Per-document RAM limit (MB) RAM-limiet per document (MB) + Installed RAM: {ram} MB; this limit: {percent}% Geïnstalleerd RAM: {ram} MB; deze limiet: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Beperkt pixels plus Geschiedenis van elk geopend document. Oudste herstelstappen verdwijnen als de limiet wordt overschreden. + Applies immediately when saved. Memory is not reserved in advance. Geldt meteen na opslaan. Geheugen wordt niet vooraf gereserveerd. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Bij GPU-geheugen Automatisch beperkt dit ook het GPU-laagbudget. Maximum is een kwart RAM en, indien bekend, drie achtste van het videogeheugen, minstens 512 MB. Hoger zetten vergroot het GPU-budget niet. + Use Gebruiken + In Front Voor + Behind Achter + +# DDS Options (#1327) + DDS Options DDS-opties + Generate Mipmaps Mipmaps genereren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 04eb15609d..23e253d62d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3648,6 +3648,22 @@ cameraData Lens Obiektyw Snap to Origin Przyciągnij do początku Search settings… Szukaj ustawień… No matching settings Brak pasujących ustawień +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Narzędzie Pędzel próbkowania + Sampling Area Overlay Nakładka obszaru próbkowania + Show Sampling Area Pokaż obszar próbkowania + Indicates Wskazuje + Sampling Area Obszar próbkowania + Excluded Area Obszar wykluczony + Sampling Area Options Opcje obszaru próbkowania + Rectangular Prostokątny + Fill Settings Ustawienia wypełnienia + Rotation Adaptation Dopasowanie obrotu + Very High Bardzo wysoka + Full Pełna + Mirror Odbicie lustrzane + Output Settings Ustawienia wyjścia + Output To Wyjście do Loading fonts… Wczytywanie czcionek… Response curve Krzywa odpowiedzi Simulate Pressure Symuluj nacisk @@ -3772,6 +3788,10 @@ curves Smooth Wygładź # View › Guides › right-click a guide Edit Selected Guides Edytuj zaznaczone prowadnice Clear Selected Guides Usuń zaznaczone prowadnice + Pasting from other apps is unavailable Wklejanie z innych aplikacji jest niedostępne + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft nie ma w tej sesji dostępu do schowka systemowego. W Waylandzie piaskownica Flatpaka ukrywa protokół, przez który odczytywane są obrazy z innych aplikacji. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Aby wklejać z innych aplikacji, uruchom PhotoCraft pod XWaylandem: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Nie ma czego wkleić: PhotoCraft nie może tutaj odczytać schowka systemowego Delete this set Usuń ten zestaw New Set… Nowy zestaw… PhotoCraft Defaults Domyślne PhotoCraft @@ -3786,6 +3806,7 @@ curves Smooth Wygładź There are too many sets: delete one first. Zestawów jest za dużo: najpierw usuń jeden. set name nazwa zestawu {set} (modified) {set} (zmieniony) + Show file name in title Pokaż nazwę pliku w tytule Accept and Go to Conflict Akceptuj i przejdź do konfliktu Changes undone. Zmiany cofnięte. Choose a new shortcut for this command, or leave it without one. Wybierz nowy skrót dla tego polecenia lub zostaw je bez skrótu. @@ -3806,3 +3827,24 @@ curves Smooth Wygładź This document's layers: {needed} of {budget} for layers Warstwy tego dokumentu: {needed} z {budget} na warstwy This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Warstwy tego dokumentu potrzebują {needed}, ale mogą zająć {budget}: odświeżanie całego dokumentu używa CPU GPU Memory (MB, 0 = Automatic) Pamięć GPU (MB, 0 = Automatycznie) + Replace Zastąp + {name} was changed by another app after it was opened or saved here. Plik {name} został zmieniony przez inną aplikację po otwarciu lub zapisaniu go tutaj. + Replace it with this document, or cancel and use File › Save As to keep both. Zastąp go tym dokumentem albo anuluj i użyj Plik › Zapisz jako, aby zachować oba. + Decrease Brush Size Zmniejsz rozmiar pędzla + Increase Brush Size Zwiększ rozmiar pędzla + Decrease Brush Hardness Zmniejsz twardość pędzla + Increase Brush Hardness Zwiększ twardość pędzla + Memory Usage Użycie pamięci + Per-document RAM limit (MB) Limit RAM na dokument (MB) + Installed RAM: {ram} MB; this limit: {percent}% Zainstalowany RAM: {ram} MB; ten limit: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Ogranicza piksele plus Historię każdego otwartego dokumentu. Najstarsze stany cofania są usuwane po przekroczeniu limitu. + Applies immediately when saved. Memory is not reserved in advance. Obowiązuje zaraz po zapisaniu. Pamięć nie jest rezerwowana z góry. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Przy pamięci GPU = Automatycznie ogranicza też budżet GPU. Limit to 1/4 RAM i, jeśli znane, 3/8 pamięci karty, minimum 512 MB. Wyższy limit nie zwiększa budżetu GPU. + Use Użyj + In Front Z przodu + Behind Z tyłu + +# DDS Options (#1327) + DDS Options Opcje DDS + Compression Kompresja + Generate Mipmaps Generuj mipmapy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8d6b88fb54..327533ad88 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3054,6 +3054,25 @@ cameraData Lens Lente Snap to Origin Ajustar à origem Search settings… Pesquisar configurações… No matching settings Nenhuma configuração encontrada +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Ferramenta Pincel de amostragem + Sampling Area Overlay Sobreposição da área de amostragem + Show Sampling Area Mostrar área de amostragem + Indicates Indica + Sampling Area Área de amostragem + Excluded Area Área excluída + Sampling Area Options Opções da área de amostragem + Rectangular Retangular + Fill Settings Configurações de preenchimento + Rotation Adaptation Adaptação de rotação + Very High Muito alta + Full Completa + Mirror Espelhar + Output Settings Configurações de saída + Output To Saída para + New Layer Nova camada + Duplicate Layer Duplicar camada + Contract Contrair Loading fonts… Carregando fontes… Response curve Curva de resposta Tool Ferramenta @@ -3073,7 +3092,6 @@ curves Smooth Suavizar Smooth the curve values Suavizar os valores da curva Drag to draw the curve · {key}-click draws a straight line Arraste para desenhar a curva · {key}-clique traça uma linha reta Grid Size: Tamanho da grade: - New Layer Nova camada Vanishing Point: click four corners to create a plane Ponto de fuga: clique em quatro cantos para criar um plano Vanishing Point is not active Ponto de fuga não está ativo Apply Vanishing Point ({key}) Aplicar ponto de fuga ({key}) @@ -3118,7 +3136,6 @@ layerLabel No Color Sem cor Clear Selection Limpar seleção Invert Selection Inverter seleção Select Inverse Inverter seleção - Contract Contrair Sample Size Tamanho da amostra Strength Intensidade Gamma Gama @@ -3145,7 +3162,6 @@ layerLabel No Color Sem cor Workspaces Áreas de trabalho Show All Mostrar tudo Hidden Oculto - Duplicate Layer Duplicar camada Ungroup Desagrupar Lock Transparent Pixels Bloquear pixels transparentes Lock Image Pixels Bloquear pixels da imagem @@ -3964,6 +3980,10 @@ layerLabel No Color Sem cor # View › Guides › right-click a guide Edit Selected Guides Editar guias selecionadas Clear Selected Guides Limpar guias selecionadas + Pasting from other apps is unavailable Colar de outros aplicativos não está disponível + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. O PhotoCraft não consegue acessar a área de transferência do sistema nesta sessão. No Wayland, a sandbox do Flatpak oculta o protocolo pelo qual as imagens de outros aplicativos são lidas. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Para colar de outros aplicativos, execute o PhotoCraft no XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Nada para colar: o PhotoCraft não consegue ler a área de transferência do sistema aqui Delete this set Excluir este conjunto New Set… Novo conjunto… PhotoCraft Defaults Padrões do PhotoCraft @@ -3978,6 +3998,7 @@ layerLabel No Color Sem cor There are too many sets: delete one first. Há conjuntos demais: exclua um primeiro. set name nome do conjunto {set} (modified) {set} (modificado) + Show file name in title Exibir nome do arquivo no título Accept and Go to Conflict Aceitar e ir para o conflito Changes undone. Alterações desfeitas. Choose a new shortcut for this command, or leave it without one. Escolha um novo atalho para este comando ou deixe-o sem atalho. @@ -3998,3 +4019,22 @@ layerLabel No Color Sem cor This document's layers: {needed} of {budget} for layers Camadas deste documento: {needed} de {budget} para camadas This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU As camadas deste documento precisam de {needed} mas podem ocupar {budget}: o documento inteiro é redesenhado na CPU GPU Memory (MB, 0 = Automatic) Memória da GPU (MB, 0 = Automático) + {name} was changed by another app after it was opened or saved here. {name} foi alterado por outro app depois de ser aberto ou salvo aqui. + Replace it with this document, or cancel and use File › Save As to keep both. Substitua-o por este documento, ou cancele e use Arquivo › Salvar como para manter os dois. + Decrease Brush Size Diminuir tamanho do pincel + Increase Brush Size Aumentar tamanho do pincel + Decrease Brush Hardness Diminuir dureza do pincel + Increase Brush Hardness Aumentar dureza do pincel + Memory Usage Uso de memória + Per-document RAM limit (MB) Limite de RAM por documento (MB) + Installed RAM: {ram} MB; this limit: {percent}% RAM instalada: {ram} MB; este limite: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Limita os pixels mais o Histórico de cada documento aberto. Os estados de desfazer mais antigos são descartados ao exceder o limite. + Applies immediately when saved. Memory is not reserved in advance. Aplica-se ao salvar. A memória não é reservada antecipadamente. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Com Memória GPU Automática, também limita o orçamento GPU. O teto é um quarto da RAM e, se conhecido, três oitavos da memória da placa, mínimo 512 MB. Aumentar o limite não aumenta o orçamento GPU. + Use Usar + In Front Na frente + Behind Atrás + +# DDS Options (#1327) + DDS Options Opções de DDS + Generate Mipmaps Gerar mipmaps diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9d733f11a7..6b2e368454 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2975,6 +2975,24 @@ cameraData Lens Объектив Rasterize Layer Style Растрировать стиль слоя Search settings… Поиск настроек… No matching settings Нет подходящих настроек +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Кисть области выборки + Sampling Area Overlay Наложение области выборки + Show Sampling Area Показать область выборки + Indicates Обозначает + Sampling Area Область выборки + Excluded Area Исключённая область + Sampling Area Options Параметры области выборки + Rectangular Прямоугольная + Fill Settings Параметры заливки + Rotation Adaptation Адаптация поворота + Very High Очень высокая + Full Полная + Mirror Отражение + Output Settings Параметры вывода + Output To Вывод в + Duplicate Layer Дубликат слоя + Contract Сжать Loading fonts… Загрузка шрифтов… Response curve Кривая отклика Tool Инструмент @@ -3143,6 +3161,10 @@ curves Smooth Сгладить # View › Guides › right-click a guide Edit Selected Guides Изменить выбранные направляющие Clear Selected Guides Удалить выбранные направляющие + Pasting from other apps is unavailable Вставка из других приложений недоступна + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. В этом сеансе PhotoCraft не может получить доступ к системному буферу обмена. В Wayland песочница Flatpak скрывает протокол, через который читаются изображения из других приложений. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Чтобы вставлять из других приложений, запустите PhotoCraft под XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Нечего вставить: здесь PhotoCraft не может прочитать системный буфер обмена Delete this set Удалить этот набор New Set… Новый набор… PhotoCraft Defaults Стандартные PhotoCraft @@ -3158,6 +3180,7 @@ curves Smooth Сгладить set name имя набора {set} (modified) {set} (изменён) Random Случайно + Show file name in title Показывать имя файла в заголовке Accept and Go to Conflict Принять и перейти к конфликту Changes undone. Изменения отменены. Choose a new shortcut for this command, or leave it without one. Выберите новую комбинацию для этой команды или оставьте её без комбинации. @@ -3178,3 +3201,25 @@ curves Smooth Сгладить This document's layers: {needed} of {budget} for layers Слои этого документа: {needed} из {budget} для слоёв This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Слоям этого документа нужно {needed}, но занимать они могут {budget}: весь документ перерисовывается на CPU GPU Memory (MB, 0 = Automatic) Память GPU (МБ, 0 = автоматически) + Replace Заменить + {name} was changed by another app after it was opened or saved here. Файл {name} был изменён другим приложением после того, как его открыли или сохранили здесь. + Replace it with this document, or cancel and use File › Save As to keep both. Замените его этим документом или отмените и используйте Файл › Сохранить как, чтобы сохранить оба. + Decrease Brush Size Уменьшить размер кисти + Increase Brush Size Увеличить размер кисти + Decrease Brush Hardness Уменьшить жёсткость кисти + Increase Brush Hardness Увеличить жёсткость кисти + Memory Usage Использование памяти + Per-document RAM limit (MB) Лимит ОЗУ на документ (МБ) + Installed RAM: {ram} MB; this limit: {percent}% Установлено ОЗУ: {ram} МБ; этот лимит: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Ограничивает пиксели и историю каждого открытого документа. Старые состояния отмены удаляются при превышении лимита. + Applies immediately when saved. Memory is not reserved in advance. Применяется сразу после сохранения. Память заранее не резервируется. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. При GPU-памяти «Авто» это также ограничивает бюджет GPU. Потолок — четверть ОЗУ и, если известно, три восьмых памяти карты, минимум 512 МБ. Больший лимит GPU-бюджет не увеличивает. + Command Command + Use Использовать + In Front Спереди + Behind Сзади + +# DDS Options (#1327) + DDS Options Параметры DDS + Compression Сжатие + Generate Mipmaps Создать MIP-карты diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index d384c9badc..5530f81ce6 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4225,6 +4225,22 @@ shape Appearance Izgled Ink Characteristics Karakteristike mastila Solidity: Punoća: Redrawing Ponovno iscrtavanje +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Alatka četkica za uzorkovanje + Sampling Area Overlay Preklop oblasti uzorkovanja + Show Sampling Area Prikaži oblast uzorkovanja + Indicates Označava + Sampling Area Oblast uzorkovanja + Excluded Area Izuzeta oblast + Sampling Area Options Opcije oblasti uzorkovanja + Rectangular Pravougaona + Fill Settings Podešavanja popune + Rotation Adaptation Prilagođavanje rotacije + Very High Veoma visoka + Full Potpuna + Mirror Preslikavanje + Output Settings Podešavanja izlaza + Output To Izlaz u Response curve Kriva odziva # Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Koristi ugrađeni profil ({profile}) @@ -4247,6 +4263,10 @@ shape Appearance Izgled # View › Guides › right-click a guide Edit Selected Guides Uredi izabrane vodilje Clear Selected Guides Ukloni izabrane vodilje + Pasting from other apps is unavailable Lepljenje iz drugih aplikacija nije dostupno + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft u ovoj sesiji ne može da pristupi sistemskoj ostavi. Na Wayland-u, Flatpak sandbox skriva protokol preko kog se čitaju slike iz drugih aplikacija. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Da biste lepili iz drugih aplikacija, pokrenite PhotoCraft pod XWayland-om: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Nema šta da se nalepi: PhotoCraft ovde ne može da čita sistemsku ostavu Delete this set Obriši ovaj skup New Set… Novi skup… PhotoCraft Defaults Podrazumevano za PhotoCraft @@ -4261,6 +4281,7 @@ shape Appearance Izgled There are too many sets: delete one first. Previše skupova: prvo obrišite jedan. set name ime skupa {set} (modified) {set} (izmenjen) + Show file name in title Prikaži naziv datoteke u naslovu Accept and Go to Conflict Prihvati i idi na sukob Changes undone. Izmene su poništene. Choose a new shortcut for this command, or leave it without one. Izaberite novu prečicu za ovu komandu ili je ostavite bez prečice. @@ -4281,3 +4302,22 @@ shape Appearance Izgled This document's layers: {needed} of {budget} for layers Slojevi ovog dokumenta: {needed} od {budget} za slojeve This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Slojevima ovog dokumenta treba {needed}, a smeju da zauzmu {budget}: ceo dokument se ponovo iscrtava na CPU-u GPU Memory (MB, 0 = Automatic) GPU memorija (MB, 0 = Automatski) + {name} was changed by another app after it was opened or saved here. Datoteku {name} je izmenila druga aplikacija nakon što je ovde otvorena ili sačuvana. + Replace it with this document, or cancel and use File › Save As to keep both. Zameni je ovim dokumentom ili otkaži i koristi Datoteka › Sačuvaj kao da zadržiš obe. + Decrease Brush Size Smanji veličinu četkice + Increase Brush Size Povećaj veličinu četkice + Decrease Brush Hardness Smanji tvrdoću četkice + Increase Brush Hardness Povećaj tvrdoću četkice + Memory Usage Upotreba memorije + Per-document RAM limit (MB) RAM limit po dokumentu (MB) + Installed RAM: {ram} MB; this limit: {percent}% Instalisan RAM: {ram} MB; ovaj limit: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Ograničava piksele plus Istoriju svakog otvorenog dokumenta. Najstarija stanja opoziva se odbacuju kad se prekorači limit. + Applies immediately when saved. Memory is not reserved in advance. Važi odmah po čuvanju. Memorija se unapred ne rezerviše. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Kad je GPU memorija Automatski, ograničava i GPU budžet. Plafon je četvrtina RAM-a i, ako je poznato, tri osmine memorije kartice, najmanje 512 MB. Veći limit ne povećava GPU budžet. + Use Koristi + In Front Ispred + Behind Iza + +# DDS Options (#1327) + DDS Options DDS opcije + Generate Mipmaps Generiši mipmape diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5c35aba71c..2e6f96a0e7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3829,6 +3829,22 @@ cameraData Lens Lens @plural {n} step|{n} steps {n} adım @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} fırça ön ayarı uyarısı daha) @plural {what} with {n} warning|{what} with {n} warnings {what}, {n} uyarı ile +# Edit › Content-Aware Fill workspace + Excluded Area Hariç Tutulan Alan + Fill Settings Dolgu Ayarları + Full Tam + Indicates Gösterir + Mirror Yansıt + Output Settings Çıkış Ayarları + Output To Çıkış Hedefi + Rectangular Dikdörtgen + Rotation Adaptation Döndürme Uyarlaması + Sampling Area Örnekleme Alanı + Sampling Area Options Örnekleme Alanı Seçenekleri + Sampling Area Overlay Örnekleme Alanı Kaplaması + Sampling Brush Tool Örnekleme Fırçası Aracı + Show Sampling Area Örnekleme Alanını Göster + Very High Çok Yüksek Response curve Yanıt eğrisi Show home recent files Ana ekranda son dosyaları göster Clear Brush Controls Fırça Denetimlerini Temizle @@ -3904,6 +3920,10 @@ cameraData Lens Lens # View › Guides › right-click a guide Edit Selected Guides Seçili Kılavuzları Düzenle Clear Selected Guides Seçili Kılavuzları Temizle + Pasting from other apps is unavailable Diğer uygulamalardan yapıştırma kullanılamıyor + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft bu oturumda sistem panosuna erişemiyor. Wayland'de Flatpak korumalı alanı, diğer uygulamalardaki görüntülerin okunduğu protokolü gizler. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Diğer uygulamalardan yapıştırmak için PhotoCraft'ı XWayland altında başlatın: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Yapıştırılacak bir şey yok: PhotoCraft burada sistem panosunu okuyamıyor Delete this set Bu Kümeyi Sil New Set… Yeni Küme… PhotoCraft Defaults PhotoCraft Varsayılanları @@ -3918,6 +3938,7 @@ cameraData Lens Lens There are too many sets: delete one first. Çok fazla küme var: önce birini silin. set name küme adı {set} (modified) {set} (değiştirildi) + Show file name in title Başlıkta dosya adını göster Accept and Go to Conflict Kabul Et ve Çakışmaya Git Changes undone. Değişiklikler geri alındı. Choose a new shortcut for this command, or leave it without one. Bu komut için yeni bir kısayol seçin veya kısayolsuz bırakın. @@ -3938,3 +3959,22 @@ cameraData Lens Lens This document's layers: {needed} of {budget} for layers Bu belgenin katmanları: katmanlar için {budget} içinden {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Bu belgenin katmanlarının {needed} belleğe ihtiyacı var ama en fazla {budget} kullanabilirler: tüm belgenin yeniden çizimi CPU'yu kullanır GPU Memory (MB, 0 = Automatic) GPU Belleği (MB, 0 = Otomatik) + {name} was changed by another app after it was opened or saved here. {name}, burada açıldıktan veya kaydedildikten sonra başka bir uygulama tarafından değiştirildi. + Replace it with this document, or cancel and use File › Save As to keep both. Bu belgeyle değiştirin ya da iptal edip ikisini de korumak için Dosya › Farklı Kaydet'i kullanın. + Decrease Brush Size Fırça boyutunu küçült + Increase Brush Size Fırça boyutunu büyüt + Decrease Brush Hardness Fırça sertliğini azalt + Increase Brush Hardness Fırça sertliğini artır + Memory Usage Bellek kullanımı + Per-document RAM limit (MB) Belge başına RAM sınırı (MB) + Installed RAM: {ram} MB; this limit: {percent}% Kurulu RAM: {ram} MB; bu sınır: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Her açık belgenin piksellerini ve Geçmişini sınırlar. Sınır aşılınca en eski geri alma durumları atılır. + Applies immediately when saved. Memory is not reserved in advance. Kaydedilince hemen uygulanır. Bellek önceden ayrılmaz. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. GPU Belleği Otomatikken GPU katman bütçesini de sınırlar. Tavan, RAM’in dörtte biri ve biliniyorsa kart belleğinin sekizde üçü, en az 512 MB. Sınırı yükseltmek GPU bütçesini artırmaz. + Use Kullan + In Front Önde + Behind Arkada + +# DDS Options (#1327) + DDS Options DDS Seçenekleri + Generate Mipmaps Mipmap oluştur diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index cb6f883eb2..5280372cad 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3722,6 +3722,22 @@ cameraData Lens Об'єктив Search settings… Пошук налаштувань… No matching settings Немає відповідних налаштувань PhotoCraft — Screen Color Picker PhotoCraft — Піпетка кольору екрана +# Edit › Content-Aware Fill workspace + Sampling Brush Tool Пензель області вибірки + Sampling Area Overlay Накладання області вибірки + Show Sampling Area Показати область вибірки + Indicates Позначає + Sampling Area Область вибірки + Excluded Area Виключена область + Sampling Area Options Параметри області вибірки + Rectangular Прямокутна + Fill Settings Параметри заливки + Rotation Adaptation Адаптація повороту + Very High Дуже висока + Full Повна + Mirror Віддзеркалення + Output Settings Параметри виводу + Output To Вивести в Loading fonts… Завантаження шрифтів… Response curve Крива відгуку Simulate Pressure Імітувати натиск @@ -3873,6 +3889,10 @@ curves Smooth Згладити # View › Guides › right-click a guide Edit Selected Guides Редагувати вибрані напрямні Clear Selected Guides Очистити вибрані напрямні + Pasting from other apps is unavailable Вставлення з інших застосунків недоступне + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. У цьому сеансі PhotoCraft не має доступу до системного буфера обміну. У Wayland пісочниця Flatpak приховує протокол, через який читаються зображення з інших застосунків. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Щоб вставляти з інших застосунків, запустіть PhotoCraft під XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Нічого вставити: тут PhotoCraft не може прочитати системний буфер обміну Delete this set Видалити цей набір New Set… Новий набір… PhotoCraft Defaults Стандартні PhotoCraft @@ -3887,6 +3907,7 @@ curves Smooth Згладити There are too many sets: delete one first. Забагато наборів: спершу видаліть один. set name назва набору {set} (modified) {set} (змінено) + Show file name in title Показувати ім’я файла в заголовку Accept and Go to Conflict Прийняти й перейти до конфлікту Changes undone. Зміни скасовано. Choose a new shortcut for this command, or leave it without one. Виберіть нове клавіатурне скорочення для цієї команди або залиште її без нього. @@ -3907,3 +3928,32 @@ curves Smooth Згладити This document's layers: {needed} of {budget} for layers Шари цього документа: {needed} з {budget} для шарів This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Шарам цього документа потрібно {needed}, але займати вони можуть {budget}: увесь документ перемальовується на CPU GPU Memory (MB, 0 = Automatic) Пам'ять GPU (МБ, 0 = автоматично) + Replace Замінити + {name} was changed by another app after it was opened or saved here. Файл {name} змінила інша програма після того, як його тут відкрили або зберегли. + Replace it with this document, or cancel and use File › Save As to keep both. Замініть його цим документом або скасуйте й скористайтеся Файл › Зберегти як, щоб зберегти обидва. + Decrease Brush Size Зменшити розмір пензля + Increase Brush Size Збільшити розмір пензля + Decrease Brush Hardness Зменшити жорсткість пензля + Increase Brush Hardness Збільшити жорсткість пензля +# Dynamic color-picker titles and warnings about losing editable layer content. + Color Picker (Background Color) Вибір кольору (колір тла) + Color Picker (Foreground Color) Вибір кольору (основний колір) + Color Picker (Custom Canvas Color) Вибір кольору (власний колір полотна) + This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Щоб продовжити, потрібно растеризувати цей текстовий шар. Після цього його текст більше не можна буде редагувати. Растеризувати текст? + This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Щоб продовжити, потрібно растеризувати цей шар фігури. Після цього його більше не можна буде редагувати як фігуру. Растеризувати фігуру? + This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Щоб продовжити, потрібно растеризувати цей смартоб’єкт. Після цього його вміст більше не можна буде редагувати. Растеризувати смартоб’єкт? + This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Щоб продовжити, потрібно растеризувати цей шар заливки. Після цього його заливку більше не можна буде редагувати. Растеризувати шар? + Memory Usage Використання пам’яті + Per-document RAM limit (MB) Ліміт RAM на документ (МБ) + Installed RAM: {ram} MB; this limit: {percent}% Встановлено RAM: {ram} МБ; цей ліміт: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Обмежує пікселі плюс Історію кожного відкритого документа. Найстаріші стани скасування відкидаються після перевищення ліміту. + Applies immediately when saved. Memory is not reserved in advance. Застосовується одразу після збереження. Пам’ять заздалегідь не резервується. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Якщо пам’ять GPU — Авто, це також обмежує бюджет GPU. Стеля — чверть RAM і, якщо відомо, три восьмих пам’яті карти, мінімум 512 МБ. Більший ліміт бюджет GPU не збільшує. + Use Використати + In Front Спереду + Behind Ззаду + +# DDS Options (#1327) + DDS Options Параметри DDS + Compression Стиснення + Generate Mipmaps Створити MIP-карти diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e2e55ab1ba..8f8e1c3443 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3597,6 +3597,22 @@ curves Smooth Làm mượt Remove after each stroke Xóa sau mỗi nét vẽ Apply the removal ({key}) Áp dụng việc xóa ({key}) Strokes to remove: {n} (Enter applies, Esc cancels) Nét vẽ cần xóa: {n} (Enter áp dụng, Esc hủy) +# Edit › Content-Aware Fill workspace + Excluded Area Vùng loại trừ + Fill Settings Cài đặt tô + Full Toàn phần + Indicates Biểu thị + Mirror Phản chiếu + Output Settings Cài đặt đầu ra + Output To Đầu ra tới + Rectangular Chữ nhật + Rotation Adaptation Thích ứng xoay + Sampling Area Vùng lấy mẫu + Sampling Area Options Tùy chọn vùng lấy mẫu + Sampling Area Overlay Lớp phủ vùng lấy mẫu + Sampling Brush Tool Công cụ Cọ lấy mẫu + Show Sampling Area Hiện vùng lấy mẫu + Very High Rất cao Show home recent files Hiện tệp gần đây trên màn hình chính Clear Brush Controls Xóa điều khiển cọ Reset All Locked Settings Đặt lại tất cả cài đặt đã khóa @@ -3660,6 +3676,10 @@ curves Smooth Làm mượt # View › Guides › right-click a guide Edit Selected Guides Sửa đường căn đã chọn Clear Selected Guides Xóa đường căn đã chọn + Pasting from other apps is unavailable Không thể dán từ ứng dụng khác + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft không truy cập được bộ nhớ tạm của hệ thống trong phiên này. Trên Wayland, sandbox của Flatpak ẩn giao thức dùng để đọc hình ảnh từ ứng dụng khác. + To paste from other apps, start PhotoCraft under XWayland: `{command}` Để dán từ ứng dụng khác, hãy khởi động PhotoCraft dưới XWayland: `{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here Không có gì để dán: PhotoCraft không thể đọc bộ nhớ tạm của hệ thống ở đây Delete this set Xóa bộ này New Set… Bộ mới… PhotoCraft Defaults Mặc định của PhotoCraft @@ -3674,6 +3694,7 @@ curves Smooth Làm mượt There are too many sets: delete one first. Có quá nhiều bộ: hãy xóa một bộ trước. set name tên bộ {set} (modified) {set} (đã sửa đổi) + Show file name in title Hiển thị tên tệp trong tiêu đề Accept and Go to Conflict Chấp nhận và đến xung đột Changes undone. Đã hoàn tác thay đổi. Choose a new shortcut for this command, or leave it without one. Chọn phím tắt mới cho lệnh này, hoặc để lệnh không có phím tắt. @@ -3694,3 +3715,24 @@ curves Smooth Làm mượt This document's layers: {needed} of {budget} for layers Các lớp của tài liệu này: {needed} trên {budget} dành cho lớp This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Các lớp của tài liệu này cần {needed} nhưng chỉ được dùng {budget}: vẽ lại toàn bộ tài liệu dùng CPU GPU Memory (MB, 0 = Automatic) Bộ nhớ GPU (MB, 0 = Tự động) + Replace Thay thế + {name} was changed by another app after it was opened or saved here. {name} đã bị một ứng dụng khác thay đổi sau khi được mở hoặc lưu ở đây. + Replace it with this document, or cancel and use File › Save As to keep both. Thay thế bằng tài liệu này, hoặc hủy và dùng Tệp › Lưu thành để giữ cả hai. + Decrease Brush Size Giảm kích thước cọ + Increase Brush Size Tăng kích thước cọ + Decrease Brush Hardness Giảm độ cứng của cọ + Increase Brush Hardness Tăng độ cứng của cọ + Memory Usage Sử dụng bộ nhớ + Per-document RAM limit (MB) Giới hạn RAM mỗi tài liệu (MB) + Installed RAM: {ram} MB; this limit: {percent}% RAM đã cài: {ram} MB; giới hạn này: {percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. Giới hạn pixel cộng Lịch sử của mỗi tài liệu đang mở. Các trạng thái hoàn tác cũ nhất bị bỏ khi vượt giới hạn. + Applies immediately when saved. Memory is not reserved in advance. Áp dụng ngay khi lưu. Bộ nhớ không được dành trước. + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. Khi Bộ nhớ GPU là Tự động, cũng giới hạn ngân sách GPU. Trần là 1/4 RAM và, nếu biết, 3/8 bộ nhớ card, tối thiểu 512 MB. Tăng giới hạn không làm tăng ngân sách GPU. + Use Dùng + In Front Phía trước + Behind Phía sau + +# DDS Options (#1327) + DDS Options Tùy chọn DDS + Compression Nén + Generate Mipmaps Tạo mipmap diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index eebeabaa6c..5efbe28990 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -772,6 +772,7 @@ Brush Settings 画笔设置 Brushes 画笔 Channels 通道 + Channel 通道 Character 字符 Character Styles 字符样式 Clone Source 仿制源 @@ -1245,6 +1246,7 @@ Levels 色阶 Lighten 变亮 Lightness 明度 + Result 结果 Lights 亮部 Limits: 限制: Linear Gradient 线性渐变 @@ -2647,6 +2649,26 @@ cameraData Lens 镜头 Snap to Origin 贴紧原点 Search settings… 搜索设置… No matching settings 没有匹配的设置 +# Edit › Content-Aware Fill workspace + Sampling Brush Tool 取样画笔工具 + Sampling Area Overlay 取样区域叠加 + Show Sampling Area 显示取样区域 + Indicates 指示 + Sampling Area 取样区域 + Excluded Area 排除区域 + Sampling Area Options 取样区域选项 + Rectangular 矩形 + Fill Settings 填充设置 + Rotation Adaptation 旋转适应 + Very High 非常高 + High 高 + Low 低 + Full 完全 + Mirror 镜像 + Output Settings 输出设置 + Output To 输出到 + Duplicate Layer 复制图层 + Contract 收缩 Loading fonts… 正在加载字体… Response curve 响应曲线 Tool 工具 @@ -2789,6 +2811,10 @@ curves Smooth 平滑 # View › Guides › right-click a guide Edit Selected Guides 编辑所选参考线 Clear Selected Guides 清除所选参考线 + Pasting from other apps is unavailable 无法从其他应用粘贴 + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft 在此会话中无法访问系统剪贴板。在 Wayland 上,Flatpak 沙盒会隐藏读取其他应用图像所用的协议。 + To paste from other apps, start PhotoCraft under XWayland: `{command}` 要从其他应用粘贴,请在 XWayland 下启动 PhotoCraft:`{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here 没有可粘贴的内容:PhotoCraft 在此无法读取系统剪贴板 Delete this set 删除此组 New Set… 新建组… PhotoCraft Defaults PhotoCraft 默认值 @@ -2804,6 +2830,7 @@ curves Smooth 平滑 set name 组名称 {set} (modified) {set}(已修改) Random 随机 + Show file name in title 标题中显示文件名 Accept and Go to Conflict 接受并转到冲突 Changes undone. 已撤消更改。 Choose a new shortcut for this command, or leave it without one. 为此命令选择新的快捷键,或保留为无快捷键。 @@ -2824,3 +2851,25 @@ curves Smooth 平滑 This document's layers: {needed} of {budget} for layers 此文档的图层:图层可用 {budget} 中的 {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU 此文档的图层需要 {needed},但只能占用 {budget}:整个文档的重绘使用 CPU GPU Memory (MB, 0 = Automatic) GPU 内存(MB,0 = 自动) + Replace 替换 + {name} was changed by another app after it was opened or saved here. {name} 在此处打开或存储后已被其他应用更改。 + Replace it with this document, or cancel and use File › Save As to keep both. 用此文档替换它,或取消并使用“文件 › 另存为”以保留两者。 + Decrease Brush Size 减小画笔大小 + Increase Brush Size 增大画笔大小 + Decrease Brush Hardness 减小画笔硬度 + Increase Brush Hardness 增大画笔硬度 + Memory Usage 内存使用 + Per-document RAM limit (MB) 每个文档的 RAM 上限 (MB) + Installed RAM: {ram} MB; this limit: {percent}% 已安装 RAM:{ram} MB;此上限:{percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. 限制每个打开文档的像素加历史记录。超出上限时会丢弃最旧的撤销状态。 + Applies immediately when saved. Memory is not reserved in advance. 保存后立即生效。不会预先占用内存。 + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. 当 GPU 内存为自动时,这也会限制 GPU 图层预算。上限为安装 RAM 的四分之一,以及(若已知)显存的八分之三,最低 512 MB。超过这些上限不会增加 GPU 预算。 + Use 使用 + In Front 前面 + Behind 后面 + Blend 混合 + +# DDS Options (#1327) + DDS Options DDS 选项 + Compression 压缩 + Generate Mipmaps 生成 Mipmap diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b35556b6fe..ea0af79451 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -777,6 +777,7 @@ Brush Settings 筆刷設定 Brushes 筆刷 Channels 色版 + Channel 色版 Character 字元 Character Styles 字元樣式 Clone Source 仿製來源 @@ -1246,6 +1247,7 @@ Levels 色階 Lighten 變亮 Lightness 明亮 + Result 結果 Lights 燈光 Limits: 限制: Linear Gradient 線性漸層 @@ -2617,6 +2619,26 @@ cameraData Lens 鏡頭 Snap to Origin 靠齊原點 Search settings… 搜尋設定… No matching settings 沒有符合的設定 +# Edit › Content-Aware Fill workspace + Sampling Brush Tool 取樣筆刷工具 + Sampling Area Overlay 取樣區域覆蓋 + Show Sampling Area 顯示取樣區域 + Indicates 指示 + Sampling Area 取樣區域 + Excluded Area 排除區域 + Sampling Area Options 取樣區域選項 + Rectangular 矩形 + Fill Settings 填色設定 + Rotation Adaptation 旋轉調整 + Very High 非常高 + High 高 + Low 低 + Full 完全 + Mirror 鏡像 + Output Settings 輸出設定 + Output To 輸出至 + Duplicate Layer 複製圖層 + Contract 縮減 Loading fonts… 正在載入字體… Response curve 回應曲線 Tool 工具 @@ -2774,6 +2796,10 @@ curves Smooth 平滑 # View › Guides › right-click a guide Edit Selected Guides 編輯所選參考線 Clear Selected Guides 清除所選參考線 + Pasting from other apps is unavailable 無法從其他應用程式貼上 + PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft 在此工作階段中無法存取系統剪貼簿。在 Wayland 上,Flatpak 沙盒會隱藏讀取其他應用程式影像所用的協定。 + To paste from other apps, start PhotoCraft under XWayland: `{command}` 若要從其他應用程式貼上,請在 XWayland 下啟動 PhotoCraft:`{command}` + Nothing to paste: PhotoCraft can't read the system clipboard here 沒有可貼上的內容:PhotoCraft 在此無法讀取系統剪貼簿 Delete this set 刪除此組合 New Set… 新增組合… PhotoCraft Defaults PhotoCraft 預設值 @@ -2789,6 +2815,7 @@ curves Smooth 平滑 set name 組合名稱 {set} (modified) {set}(已修改) Random 隨機 + Show file name in title 標題中顯示檔案名稱 Accept and Go to Conflict 接受並前往衝突 Changes undone. 已還原變更。 Choose a new shortcut for this command, or leave it without one. 為此指令選擇新的快速鍵,或保持沒有快速鍵。 @@ -2809,3 +2836,25 @@ curves Smooth 平滑 This document's layers: {needed} of {budget} for layers 此文件的圖層:圖層可用 {budget} 中的 {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU 此文件的圖層需要 {needed},但只能佔用 {budget}:整份文件的重繪使用 CPU GPU Memory (MB, 0 = Automatic) GPU 記憶體(MB,0 = 自動) + Replace 取代 + {name} was changed by another app after it was opened or saved here. {name} 在此處開啟或儲存後已被其他 App 更改。 + Replace it with this document, or cancel and use File › Save As to keep both. 以此文件取代它,或取消並使用「檔案 › 另存新檔」以保留兩者。 + Decrease Brush Size 縮小筆刷大小 + Increase Brush Size 放大筆刷大小 + Decrease Brush Hardness 降低筆刷硬度 + Increase Brush Hardness 提高筆刷硬度 + Memory Usage 記憶體使用量 + Per-document RAM limit (MB) 每個文件的 RAM 上限 (MB) + Installed RAM: {ram} MB; this limit: {percent}% 已安裝 RAM:{ram} MB;此上限:{percent}% + Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded. 限制每個開啟文件的像素加歷史記錄。超出上限時會捨棄最舊的復原狀態。 + Applies immediately when saved. Memory is not reserved in advance. 儲存後立即套用。不會預先保留記憶體。 + With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget. 當 GPU 記憶體為自動時,這也會限制 GPU 圖層預算。上限為安裝 RAM 的四分之一,以及(若已知)顯示卡記憶體的八分之三,最低 512 MB。超過這些上限不會增加 GPU 預算。 + Use 使用 + In Front 前面 + Behind 後面 + Blend 混合 + +# DDS Options (#1327) + DDS Options DDS 選項 + Compression 壓縮 + Generate Mipmaps 產生 Mipmap diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 9301f709ce..7fdaf4f7d0 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -39,6 +39,8 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("diamond", include_bytes!("../../../assets/icons/diamond.svg")), ("direct-select", include_bytes!("../../../assets/icons/direct-select.svg")), ("droplet", include_bytes!("../../../assets/icons/droplet.svg")), + // Original: a dashed horizontal ellipse (Elliptical Marquee), on Lucide's grid and stroke. + ("ellipse-dashed", include_bytes!("../../../assets/icons/ellipse-dashed.svg")), ("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")), ("eraser", include_bytes!("../../../assets/icons/eraser.svg")), // Derived from Lucide's eraser (ISC): with a sparkle (Magic Eraser) / a transparency grid (Background Eraser). diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 131886ae6b..37d0b4aeab 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -87,7 +87,7 @@ pub fn tool_icon(t: Tool) -> &'static str { Tool::Move => "move", Tool::Artboard => "artboard", Tool::RectMarquee => "square-dashed", - Tool::EllipseMarquee => "circle-dashed", + Tool::EllipseMarquee => "ellipse-dashed", Tool::SingleRowMarquee => "marquee-row", Tool::SingleColumnMarquee => "marquee-column", Tool::Brush => "brush", @@ -272,12 +272,41 @@ mod tests { assert!(union > 0, "icons must have ink at {size}px"); let overlap = shared as f32 / union as f32; assert!(overlap < 0.5, "the two glyphs must read as distinct: {overlap:.2} of their ink overlaps at {size}px"); - // The dashed selection arc must actually rasterize: more ink than the bare brush. - let brush = ink(tool_icon(Tool::Brush), size); - assert!(quick.iter().filter(|a| **a).count() > brush.iter().filter(|a| **a).count(), "the dashed arc is missing at {size}px"); + // The dashed selection "C" must actually rasterize down the left edge, where the brush has no ink. + let s = size as usize; + assert!(quick.iter().enumerate().any(|(i, a)| *a && i % s < s / 5), "the dashed selection edge is missing at {size}px"); } } + /// Ink bounding box `(width, height)` of a rasterized mask. + fn ink_extent(mask: &[bool], size: u32) -> (usize, usize) { + let s = size as usize; + let (xs, ys): (Vec, Vec) = mask.iter().enumerate().filter(|(_, a)| **a).map(|(i, _)| (i % s, i / s)).unzip(); + let span = |v: &[usize]| v.iter().max().zip(v.iter().min()).map_or(0, |(hi, lo)| hi - lo + 1); + (span(&xs), span(&ys)) + } + + #[test] + fn ellipse_marquee_icon_is_a_wide_ellipse() { + // #6875: Photoshop's Elliptical Marquee glyph is a horizontal ellipse, not a circle. + assert_ne!(tool_icon(Tool::EllipseMarquee), "circle-dashed"); + for size in [14_u32, 28] { + let (w, h) = ink_extent(&ink(tool_icon(Tool::EllipseMarquee), size), size); + assert!(w as f32 >= h as f32 * 1.15, "ellipse marquee ink is {w}x{h} at {size}px: not wider than tall"); + } + } + + #[test] + fn quick_selection_icon_is_a_tall_selection_with_a_brush() { + // #6875: Photoshop's Quick Selection glyph is a dashed, upright rounded "C" with a brush. + let size = 28_u32; + let s = size as usize; + let quick = ink(tool_icon(Tool::QuickSelection), size); + // The left edge of the selection runs most of the icon's height. + let left_rows = (0..s).filter(|y| (0..s / 5).any(|x| quick.get(y * s + x).copied().unwrap_or(false))).count(); + assert!(left_rows * 5 > s * 2, "left selection edge covers only {left_rows} of {s} rows"); + } + #[test] fn shared_catalog_preserves_existing_icons() { // Characterize the pre-extraction loader across every real asset. The UI's tint, diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 3754e821fc..e06182870c 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -317,6 +317,56 @@ fn curves_picker_samples_document_coordinates_through_the_view_transform() { assert!((red - 32.0).abs() < 0.6, "sampled document-right blue patch through the flipped 400% view: {red}"); } +/// #7325: ⌘/Ctrl-click on the image with Curves open adds a point at the pixel's tone. The +/// modifier is the press's own, a drag onto another tone adds nothing more, and the Hand tool +/// does not take the press for a pan. +#[test] +fn command_click_under_curves_adds_one_point_per_press_not_per_frame() { + // The Hand tool too: the press is the dialog's, not the start of a pan. + for hand in [false, true] { + let mut h = harness(); + if hand { + h.state_mut().ui.tool = crate::state::Tool::Hand; + } + h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 80, "height": 300})).unwrap(); + h.state_mut().run("edit.fill", json!({"color": "#804020"})).unwrap(); + h.state_mut().run("select.rect", json!({"x": 80, "y": 0, "width": 320, "height": 300})).unwrap(); + h.state_mut().run("edit.fill", json!({"color": "#20a0e0"})).unwrap(); + h.state_mut().run("select.deselect", json!({})).unwrap(); + let view = &mut h.state_mut().ui.views[0]; + (view.zoom, view.center, view.fit_pending) = (4.0, [200.0, 150.0], false); + let dialog = crate::adjust_dialog::open(h.state_mut(), "image.adjustments.curves").unwrap(); + h.run_steps(3); + let points = |h: &Harness<'static, PhotocraftApp>| { + let d = h.state().ui.dialogs.iter().find(|d| d.id == dialog).unwrap(); + d.fields.get("points").and_then(serde_json::Value::as_array).map_or(0, Vec::len) + }; + let canvas = h.state().last_canvas_rect; + // Document x 65 (the brown strip) and 100 (the blue), both left of the centred dialog. + let (brown, blue) = (pos2(canvas.left() + 60.0, canvas.center().y), pos2(canvas.left() + 200.0, canvas.center().y)); + h.hover_at(brown); + h.run_steps(1); + press(&mut h, brown, true); + press(&mut h, brown, false); + assert_eq!(points(&h), 2, "a plain click adds no point (hand: {hand})"); + + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::COMMAND }; + // ⌘ stays held through the drag, so only the press can tell the frames apart. + h.event(egui::Event::ModifiersChanged(Modifiers::COMMAND)); + h.event(button(brown, true)); + h.run_steps(1); + assert_eq!(points(&h), 3, "the press adds the point (hand: {hand})"); + for t in [0.25, 0.5, 0.75, 1.0] { + h.event(egui::Event::PointerMoved(brown + (blue - brown) * t)); + h.run_steps(1); + } + h.event(button(blue, false)); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + assert_eq!(points(&h), 3, "dragging onto another tone adds nothing more (hand: {hand})"); + } +} + /// Type tool (#206): Alt+←/→ at a collapsed caret kerns the pair before it by 20/1000 em (100 /// with ⌘/Ctrl), one history step per press; ⌘/Ctrl+←/→ moves by word; Alt+Shift+→ extends /// the selection by a word. diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui_tests.rs index f2b7d0fbc0..70ce973be0 100644 --- a/crates/ui-egui/src/jobs_ui_tests.rs +++ b/crates/ui-egui/src/jobs_ui_tests.rs @@ -84,6 +84,21 @@ fn frames_for_at_least(h: &mut Harness<'_, PhotocraftApp>, ms: u64, min_frames: (n, worst) } +/// Step at least `min` frames and until `ready` holds; returns (frames, slowest frame in ms). +/// The test fails when `ready` still does not hold after 60 s. +fn frames_until(h: &mut Harness<'_, PhotocraftApp>, min: u64, ready: impl Fn(&Harness<'_, PhotocraftApp>) -> bool) -> (u64, f64) { + let t = Instant::now(); + let (mut n, mut worst) = (0, 0.0f64); + while n < min || !ready(h) { + assert!(t.elapsed() < Duration::from_secs(60), "not ready after {n} frames"); + let f = Instant::now(); + h.step(); + worst = worst.max(f.elapsed().as_secs_f64() * 1000.0); + n += 1; + } + (n, worst) +} + #[test] fn the_frame_loop_keeps_running_during_a_slow_job_and_esc_cancels_it() { let mut h = app_harness(); @@ -91,7 +106,9 @@ fn the_frame_loop_keeps_running_during_a_slow_job_and_esc_cancels_it() { let doc_before = h.state().session.active().unwrap().doc.clone(); let job = slow_job(h.state_mut(), &gate); let frame0 = h.state().frame; - let (n, worst) = frames_for_at_least(&mut h, 400, 10); + // The worker thread reports "Filtering tiles" when it starts, which can be after the dialog appears. + let (n, worst) = frames_until(&mut h, 10, |h| h.query_by_label("Filtering tiles").is_some()); + assert!(h.state().session.job(job).is_some(), "the job is still running"); assert!(h.state().frame - frame0 >= 10, "the UI kept rendering ({n} frames)"); eprintln!("{n} frames during the job, slowest {worst:.1} ms"); // The status bar shows the job, and after the delay the modal progress dialog. diff --git a/crates/ui-egui/src/layer_props_ui.rs b/crates/ui-egui/src/layer_props_ui.rs index c2ea848c5e..57335a897b 100644 --- a/crates/ui-egui/src/layer_props_ui.rs +++ b/crates/ui-egui/src/layer_props_ui.rs @@ -6,7 +6,7 @@ use egui::{Rect, Sense, Stroke, pos2, vec2}; use photocraft_doc::{Layer, LayerContent}; use serde_json::{Value, json}; -use crate::props_layout::{LABEL_GAP, LABEL_W, quick_actions_ui, section}; +use crate::props_layout::{LABEL_GAP, LABEL_W, quick_actions_ui, section, stacked_label}; use crate::theme::{ROW_GAP, Tokens}; use crate::{PhotocraftApp, widgets}; @@ -33,11 +33,10 @@ pub fn transform_params(layer: u64, b: [i32; 4], w: Option, h: Option, Some(json!({"layer": layer, "rect": b, "quad": quad})) } -/// A number field that reports a value once committed (drag released, Enter, focus lost). -fn field(ui: &mut egui::Ui, id: &str, label: &str, current: f32, width: f32, u: LenUnit, extent: f64) -> Option { - let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(vec2(LABEL_W, 22.0), Sense::hover()); - ui.painter().text(pos2(r.right() - 2.0, r.center().y), egui::Align2::RIGHT_CENTER, tl!(label), egui::FontId::proportional(12.0), t.text_dim); +/// A number field that reports a value once committed (drag released, Enter, focus lost). `label` is its own +/// label and the one stacked with it in the same column ("W" over "X"), which share a centre. +fn field(ui: &mut egui::Ui, id: &str, label: (&str, &str), current: f32, width: f32, u: LenUnit, extent: f64) -> Option { + stacked_label(ui, tl!(label.0), &[tl!(label.0), tl!(label.1)], LABEL_W, 2.0); let key = ui.make_persistent_id(("layer-props-field", id)); let mut v = ui.data(|d| d.get_temp::(key)).unwrap_or_else(|| u.shown(f64::from(current), extent)); let resp = widgets::value_field(ui, &mut v, -300_000.0..=300_000.0, u.unit.suffix(), width); @@ -137,24 +136,24 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) { let w = ((ui.available_width() - 2.0 * (LABEL_W + LABEL_GAP) - LINK_W - 2.0 * LABEL_GAP) / 2.0).max(36.0); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = LABEL_GAP; - if let Some(v) = field(ui, "w", "W", b.width() as f32, w, u, dw) { + if let Some(v) = field(ui, "w", ("W", "X"), b.width() as f32, w, u, dw) { run.extend(transform_params(layer.id.0, bb, Some(v), None, linked).map(|p| ("edit.transform".to_string(), p))); } if crate::icons::button(ui, if linked { "link" } else { "unlink" }, LINK_W, linked, tl!("Link width and height")).clicked() { ui.data_mut(|d| d.insert_temp(link_key, !linked)); } - if let Some(v) = field(ui, "h", "H", b.height() as f32, w, u, dh) { + if let Some(v) = field(ui, "h", ("H", "Y"), b.height() as f32, w, u, dh) { run.extend(transform_params(layer.id.0, bb, None, Some(v), linked).map(|p| ("edit.transform".to_string(), p))); } }); ui.add_space(ROW_GAP); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = LABEL_GAP; - if let Some(v) = field(ui, "x", "X", b.x0 as f32, w, u, dw) { + if let Some(v) = field(ui, "x", ("X", "W"), b.x0 as f32, w, u, dw) { run.push(("layer.translate".into(), json!({"layer": layer.id.0, "dx": (v - b.x0 as f32).round() as i32, "dy": 0}))); } ui.add_space(LINK_W + LABEL_GAP); - if let Some(v) = field(ui, "y", "Y", b.y0 as f32, w, u, dh) { + if let Some(v) = field(ui, "y", ("Y", "H"), b.y0 as f32, w, u, dh) { run.push(("layer.translate".into(), json!({"layer": layer.id.0, "dx": 0, "dy": (v - b.y0 as f32).round() as i32}))); } }); @@ -281,6 +280,40 @@ mod tests { } } + /// #7314: in the Transform section W sits over X and H over Y, and each pair shares a centre. + #[test] + fn transform_labels_are_centred_on_each_other() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(280.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().cumulative_pass_nr() == 0 { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + return; + } + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); + properties(app, ui, &layer); + }, + app, + ); + h.run_steps(3); + let centres: Vec<(String, f32)> = h + .output() + .shapes + .iter() + .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some(t) } else { None }) + .filter(|t| t.galley.text().chars().count() == 1) + .map(|t| (t.galley.text().to_string(), t.pos.x + t.galley.size().x * 0.5)) + .collect(); + let at = |l: &str| centres.iter().find(|(s, _)| s == l).map(|(_, x)| *x).unwrap_or_else(|| panic!("no {l} label in {centres:?}")); + assert!((at("W") - at("X")).abs() < 0.01, "W and X: {centres:?}"); + assert!((at("H") - at("Y")).abs() < 0.01, "H and Y: {centres:?}"); + } + #[test] fn transform_fields_show_and_take_the_ruler_unit() { use photocraft_engine::prefs::Unit; diff --git a/crates/ui-egui/src/layer_row_ui.rs b/crates/ui-egui/src/layer_row_ui.rs index 5a6e60f792..4bed6a7cc4 100644 --- a/crates/ui-egui/src/layer_row_ui.rs +++ b/crates/ui-egui/src/layer_row_ui.rs @@ -94,10 +94,23 @@ pub fn truncated(painter: &Painter, text: &str, font: FontId, color: egui::Color if max_width < 8.0 { return None; } - let mut job = egui::text::LayoutJob::default(); - job.append(text, 0.0, egui::TextFormat { font_id: font, color, italics, ..Default::default() }); - job.wrap = egui::text::TextWrapping { max_width, max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; - Some(painter.layout_job(job)) + let format = egui::text::TextFormat { font_id: font, color, italics, ..Default::default() }; + let layout = |s: &str, wrap: bool| { + let mut job = egui::text::LayoutJob::default(); + job.append(s, 0.0, format.clone()); + if wrap { + job.wrap = egui::text::TextWrapping { max_width, max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; + } + painter.layout_job(job) + }; + // A right-to-left name (Arabic, Hebrew) too long for the row is cut at its logical end and + // then put in display order, so its start stays and "…" is at the left (`bidi_text::elide`). + if let Some(shown) = crate::bidi_text::elide(text, |s| layout(s, false).size().x <= max_width) { + return Some(layout(&shown, false)); + } + // Right-to-left names in display order: egui lays words out left to right. Left-to-right + // names are cut at their right end by egui. + Some(layout(&crate::bidi_text::visual(text), true)) } /// Paint `l`'s right-hand indicators in `row` and handle the effects triangle. Returns the diff --git a/crates/ui-egui/src/layer_shortcut_tests.rs b/crates/ui-egui/src/layer_shortcut_tests.rs index a363c340bf..96ab2520dc 100644 --- a/crates/ui-egui/src/layer_shortcut_tests.rs +++ b/crates/ui-egui/src/layer_shortcut_tests.rs @@ -122,3 +122,69 @@ fn alt_click_on_a_layer_thumbnail_fits_the_layer() { assert_eq!(v.center, [310.0, 205.0], "centred on the layer's content"); assert!(v.zoom > before.zoom * 4.0, "zoomed in on 20 × 10 px: {} -> {}", before.zoom, v.zoom); } + +/// ⌘-click a layer's thumbnail loads its transparency as a selection without changing the +/// selected layer; on the Background, which has no transparency, it is a plain click, and a hidden +/// layer still loads (measured on Photoshop 25.4, 2026-10-17). +#[test] +fn command_click_on_a_thumbnail_loads_transparency_except_on_the_background() { + use egui::{Event, PointerButton, pos2, vec2}; + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let background = s.active().unwrap().active_layer.unwrap().0; + let shape = s.execute("layer.new.layer", json!({"name": "Shape"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 100, "y": 50, "width": 120, "height": 100})).unwrap(); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(s, crate::Services::default()) + }); + let ctx = h.ctx.clone(); + let (r, _) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"collapsed": ["color", "properties", "history", "navigator"]}})); + crate::control::handle(h.state_mut(), &ctx, &r); + h.run_steps(8); + let click = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, layer: u64, modifiers: Modifiers| { + let row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == layer).unwrap().row; + let at = pos2(row.left() + 46.0, row.center().y); + h.hover_at(at); + h.event(Event::ModifiersChanged(modifiers)); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers }); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers }); + h.run_steps(1); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(3); + }; + let bounds = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { + let st = h.state().session.active().unwrap(); + st.doc.selection.as_ref().map(|s| s.content_bounds()) + }; + let top = h.state().session.active().unwrap().active_layer.unwrap(); + let selected = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().selected_layers(); + click(&mut h, shape, Modifiers::COMMAND); + assert_eq!(bounds(&h), Some(photocraft_geom::Rect::new(100, 50, 220, 150)), "the layer's pixels are selected"); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(top), "the selected layer stays"); + assert_eq!(selected(&h), vec![top]); + click(&mut h, background, Modifiers::COMMAND); + assert_eq!( + bounds(&h), + Some(photocraft_geom::Rect::new(100, 50, 220, 150)), + "the Background has no transparency to load: a plain click, which leaves the selection and selects the row" + ); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(photocraft_doc::LayerId(background))); + assert_eq!(selected(&h), vec![photocraft_doc::LayerId(background)], "the Background alone, not toggled into the set"); + // Already in a multi-selection: the ⌘-click still leaves it the only selected layer. + h.state_mut().run("layer.select", json!({"layer": top.0})).unwrap(); + h.state_mut().run("layer.select", json!({"layer": background, "mode": "add"})).unwrap(); + h.run_steps(2); + assert_eq!(selected(&h).len(), 2); + click(&mut h, background, Modifiers::COMMAND); + assert_eq!(selected(&h), vec![photocraft_doc::LayerId(background)], "replaced, not removed from the set"); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(photocraft_doc::LayerId(background))); + h.state_mut().run("layer.setProps", json!({"layer": shape, "visible": false})).unwrap(); + click(&mut h, shape, Modifiers::COMMAND); + assert_eq!(bounds(&h), Some(photocraft_geom::Rect::new(100, 50, 220, 150)), "a hidden layer's transparency loads too"); +} diff --git a/crates/ui-egui/src/layer_style/color_picker.rs b/crates/ui-egui/src/layer_style/color_picker.rs index b0edb16379..341e659c9e 100644 --- a/crates/ui-egui/src/layer_style/color_picker.rs +++ b/crates/ui-egui/src/layer_style/color_picker.rs @@ -92,7 +92,7 @@ pub(crate) fn open(app: &mut PhotocraftApp, parent: u64, effect: &str, field: &s let t = Target { parent, document: st.doc.id, layer, effect: effect.into(), field: field.into(), color: color.clone(), source }; validate(app, &t)?; let rgb = color_picker_ui::parse_hex(&color).ok_or("invalid effect color")?; - let mut fields = color_picker_ui::initial_fields("dialog", "Color Picker (Layer Style Color)", rgb); + let mut fields = color_picker_ui::fields_with_web(app, "dialog", "Color Picker (Layer Style Color)", rgb); fields.insert(TARGET.into(), serde_json::to_value(t).map_err(|e| e.to_string())?); Ok(app.ui.open_dialog(DialogKind::Command, fields)) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 43d9803ab6..4ac9593017 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1,4 +1,4 @@ -//! Photocraft's first UI shell, built on egui/eframe. +//! PhotoCraft's first UI shell, built on egui/eframe. //! //! This crate is deliberately thin. Every action goes through //! [`photocraft_engine::Session::execute`], and all UI state lives in [`state::UiState`] (plain @@ -25,6 +25,7 @@ pub mod anchor_tools; pub mod artboard_tool; pub mod artboard_ui; pub(crate) mod background_redraw; +pub mod bidi_text; mod blend_keys; pub(crate) mod blend_preview; pub mod blur_pins; @@ -37,6 +38,7 @@ pub mod brush_preview; pub mod brush_resize; pub mod brush_sections; pub mod brushes_tab; +pub mod caf_ui; pub(crate) mod cam_preview; mod cam_transform; mod camera_raw_detail_ui; @@ -67,6 +69,7 @@ pub mod crop_shield; pub mod crop_size; pub mod crop_straighten; pub mod crop_ui; +pub mod dds_options_ui; pub mod delete_layer_prompt; pub mod dialog_alt_reset; pub mod dialog_blend_ui; @@ -74,6 +77,7 @@ pub mod dialogs; pub mod direct_select; pub mod direction; pub mod discard_ui; +pub mod disk_change_prompt; pub mod distort_ui; pub mod doc_props_ui; pub mod dock; @@ -269,6 +273,9 @@ pub struct ExportSettings { /// Targa: bits per pixel from Targa Options or Export As (`None`: 32 with an alpha channel or /// transparency, else 24). pub tga_bits: Option, + /// DDS: the compression and mip chain from DDS Options (uncompressed without mipmaps unless + /// chosen). + pub dds: photocraft_io::DdsOptions, /// PSD/PSB: embed a thumbnail (Preferences › File Handling › Image Previews; see /// [`PhotocraftApp::save_settings`]). pub image_previews: bool, @@ -281,6 +288,9 @@ pub struct ExportSettings { /// Embed EXIF, resolution and other non-XMP metadata when the format supports it. Export As /// turns this off for Metadata: None; Save As leaves it on. pub embed_metadata: bool, + /// The path of the document's own file, which linked smart objects that PSD/PSB embed are + /// resolved against ([`photocraft_io::ExportOptions::document_path`]). + pub document_path: Option, } impl Default for ExportSettings { @@ -292,10 +302,12 @@ impl Default for ExportSettings { tiff_layers: true, xmp_all: true, tga_bits: None, + dds: photocraft_io::DdsOptions::default(), image_previews: true, psd_maximize_compatibility: true, embed_icc: true, embed_metadata: true, + document_path: None, } } } @@ -317,12 +329,45 @@ impl ExportSettings { opts.tiff_layers = self.tiff_layers; opts.xmp = if self.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None }; opts.tga_bits = self.tga_bits; + opts.encode.dds = self.dds; opts.image_previews = self.image_previews; opts.psd_maximize_compatibility = self.psd_maximize_compatibility; + opts.document_path = self.document_path.clone(); opts } } +/// The format answers a save takes instead of asking: the Targa bits per pixel and the DDS options +/// (`"tgaBits"`, `"ddsCompression"`, `"ddsMipmaps"`). `None` asks in Save As and takes the +/// default in automation saves, which never prompt. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FormatChoices { + pub tga_bits: Option, + pub dds: Option, +} + +impl FormatChoices { + /// The answers in command `cmd`'s params; a bad value is an error. + pub fn from_params(params: &Value, cmd: &str) -> Result { + Ok(FormatChoices { tga_bits: targa_options_ui::bits_param(params, cmd)?, dds: dds_options_ui::options_param(params, cmd)? }) + } + + /// The export settings with these answers applied. + pub(crate) fn apply(self, settings: ExportSettings) -> ExportSettings { + ExportSettings { tga_bits: self.tga_bits, dds: self.dds.unwrap_or(settings.dds), ..settings } + } + + /// Adds the answers to a recorded save step. + fn record(self, step: &mut Value) { + if let Some(bits) = self.tga_bits { + step["tgaBits"] = bits.bits().into(); + } + if let Some(dds) = self.dds { + dds_options_ui::record(dds, step); + } + } +} + /// The document's lone layer when it is a plain raster a flat file keeps: visible, at full /// opacity, in Normal mode, with no masks, effects or blending restrictions (#2234). pub(crate) fn plain_raster(doc: &Document) -> Option<&photocraft_doc::Layer> { @@ -349,11 +394,27 @@ pub(crate) fn plain_raster(doc: &Document) -> Option<&photocraft_doc::Layer> { /// Encode a document: (file bytes, warnings about anything approximated or dropped). pub type ExportFn = Box Result<(Vec, Vec), String>>; pub type WriteFn = Box Result<(), String>>; +/// What a file on disk looked like when a document last read or wrote it: File › Save asks +/// before replacing a file another app changed since (#6596). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FileStamp { + pub len: u64, + pub modified: Option, +} +/// The [`FileStamp`] of the file at a path, `None` when it can't be read. +pub type FileStampFn = Box Option>; /// Encode a document and write it to a path, reporting the stage to the job; returns the export /// warnings. Runs on a worker thread (see [`Services::save_file`]). It must call /// [`jobs_ui::SaveCtl::commit`] right before replacing the file, and write nothing if that fails. pub type SaveFileFn = std::sync::Arc Result, String> + Send + Sync>; +/// The revision a document counts as saved at after `written` went to its writer: that one when +/// the writer confirms the bytes were stored, else still `previous`, so the document stays +/// unsaved. A browser download is only a request the user can cancel (#4962). +pub(crate) fn saved_revision_after_write(confirmed: bool, written: u64, previous: u64) -> u64 { + if confirmed { written } else { previous } +} + /// Who a finished save serves. #[derive(Clone, Copy)] pub(crate) enum SaveKind { @@ -379,6 +440,8 @@ pub type EncodePngFn = Box Result, String>>; pub type ClipboardSetFn = Box Result<(), String>>; /// Read an RGBA8 image from the OS clipboard. pub type ClipboardGetFn = Box Option<(u32, u32, Vec)>>; +/// Whether the last clipboard read found no way to reach the OS clipboard at all. +pub type ClipboardUnreadableFn = Box bool>; /// Shared queue of (file name, bytes) delivered asynchronously. pub type Inbox = std::sync::Arc)>>>; /// Read the saved preferences text (`None` when there is none yet). @@ -446,6 +509,13 @@ pub struct Services { pub file_dialog: Option, /// Write bytes to a path (native) or trigger a download (web). pub write: Option, + /// Size and modification time of a file (native); `None` on the web, where Save never + /// writes back to a file. + pub file_stamp: Option, + /// `write` only asks for the bytes to be kept (a browser download, which the user can + /// cancel and which reports nothing back), so a save through it names the document but + /// leaves its changes unsaved and the leave-page guard armed (#4962). + pub write_unconfirmed: bool, /// Encode and write in one step on a worker thread, so a large save doesn't freeze the /// window (#2017). With background jobs on, saves use it instead of `export` and `write`. pub save_file: Option, @@ -466,11 +536,19 @@ pub struct Services { /// Preferences ▸ General ▸ Beep When Done: the platform's default beep, played when a /// background job finishes successfully. `None` in the web build (and in tests). pub beep: Option, - /// Files delivered asynchronously (web drag-and-drop): drained every frame. + /// Files delivered asynchronously (web drag-and-drop): drained every frame and opened as + /// documents. pub inbox: Option, + /// Files delivered asynchronously for a drop onto the active document's canvas (web + /// drag-and-drop, routed by [`PhotocraftApp::dropped_on_canvas`]): placed as layers like a + /// desktop canvas drop (Place Embedded, each in Free Transform). + pub place_inbox: Option, /// OS clipboard images: copies go out, screenshots and images from other apps come in. pub clipboard_set_image: Option, pub clipboard_get_image: Option, + /// True when the last `clipboard_get_image` read had no clipboard to read, as in a Flatpak on + /// Wayland (#5031), rather than a clipboard that holds no image. `None` where that can't happen. + pub clipboard_unreadable: Option, /// Preferences persistence: the platform config directory on native, browser storage on /// the web (see `prefs_ui`). pub load_prefs: Option, @@ -494,8 +572,9 @@ pub struct Services { pub append_text: Option, /// OS requests (macOS open-documents / quit Apple events), polled every frame. pub os_events: Option, - /// The pointer position read from the OS (desktop): winit 0.30's file drops carry none, and - /// the window gets no pointer events during an OS drag (see `file_open::DropTarget`). + /// The pointer position read from the OS (desktop) or from the page's drag events (web): + /// file drops carry none, and the window gets no pointer events during an OS drag (see + /// `file_open::DropTarget`). pub cursor_pos: Option, /// Caps Lock toggled on (desktop; `None` on Wayland and the web). Read once per frame, so /// the canvas can show the precise crosshair for painting tools, whatever the preference. @@ -568,9 +647,9 @@ pub struct PhotocraftApp { /// Footprint trail of a retouching drag (see `stroke_trail`). trail: Option, /// Remove tool strokes waiting to be applied together (Remove after each stroke off), the - /// document they belong to, and their tint on the canvas (`retouch_ui`). + /// document, layer and channel they belong to, and their tint on the canvas (`retouch_ui`). pub(crate) remove_pending: Vec>, - pub(crate) remove_pending_doc: Option, + pub(crate) remove_pending_target: Option, pub(crate) remove_trail: Option, /// The open menus' items, reused between frames (`menus::ItemCache`). pub(crate) menu_cache: Option, @@ -642,6 +721,9 @@ pub struct PhotocraftApp { fonts_ready: bool, /// Screen rect of the main canvas last frame (for overlays and the navigator). pub last_canvas_rect: egui::Rect, + /// Window › Arrange: the first document of the shown run of tiles, when there are more + /// documents than tiles (`canvas::arranged_cells`). + pub(crate) arrange_start: usize, /// Physical pixels per egui point of the canvas last frame (`ctx.pixels_per_point`, which /// folds in both the display scale and Interface › UI Scale). The canvas maps document pixels /// to physical pixels, so point-space geometry divides the view zoom by this (see @@ -653,11 +735,11 @@ pub struct PhotocraftApp { /// The document tab strip last frame: a drop there opens the file at the slot under it. pub(crate) tab_strip: Option, /// Files dropped on the canvas still to place, one Free Transform at a time. - pub(crate) drop_places: std::collections::VecDeque, + pub(crate) drop_places: std::collections::VecDeque, /// The document each of `ui.views` belongs to, as of the last [`Self::sync_views`]. view_docs: Vec, pub fps: f32, - last_frame_time: f64, + pub(crate) last_frame_time: f64, thumbs: HashMap<(photocraft_doc::LayerId, u8), (u64, egui::TextureHandle)>, /// The document area each layer thumbnail in `thumbs` frames (the canvas, or the layer's /// bounds with Clip Thumbnails to Layer Bounds; #4281). @@ -684,6 +766,9 @@ pub struct PhotocraftApp { pub(crate) color_range: Option, /// Image › Adjustments dialog preview through a temporary clipped adjustment layer. pub(crate) adjust_preview: Option, + /// The Properties panel's live adjustment-layer drag: its damage region and coverage + /// (`adjust_preview::live_key`). + pub(crate) live_adjust_preview: Option, /// Synthetic input events queued by automation (`ui.click`, `ui.key`, …), injected next frame. pub(crate) synthetic: Vec, /// True only while a frame is processing synthetic automation input. It @@ -787,8 +872,13 @@ pub struct PhotocraftApp { /// Where each document was last saved or exported to through a dialog (#1826): its next Save /// As or export dialog starts there rather than beside the document. Session-only. pub(crate) save_dirs: HashMap, + /// Each document's own file as it was when the document was opened from it or saved to it + /// (see [`FileStamp`]). + pub(crate) disk_stamps: HashMap, /// A save to an RGB Targa parked behind the Targa Options prompt (see `targa_options_ui`). pub(crate) targa_options: Option, + /// A save to a DDS texture parked behind the DDS Options prompt (see `dds_options_ui`). + pub(crate) dds_options: Option, /// Files read but not opened yet: the first waits on its profile prompt, the rest behind it /// (see `open_prompt`). pub(crate) held_opens: std::collections::VecDeque, @@ -833,7 +923,7 @@ impl PhotocraftApp { committed_stroke: None, trail: None, remove_pending: Vec::new(), - remove_pending_doc: None, + remove_pending_target: None, remove_trail: None, menu_cache: None, move_preview: None, @@ -867,6 +957,7 @@ impl PhotocraftApp { last_window_title: String::new(), fonts_ready: false, last_canvas_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)), + arrange_start: 0, ppp: 1.0, drop_canvas_rect: None, tab_strip: None, @@ -888,6 +979,7 @@ impl PhotocraftApp { redraws: Default::default(), color_range: None, adjust_preview: None, + live_adjust_preview: None, synthetic: Vec::new(), automation_input: false, channel_thumbs: None, @@ -936,7 +1028,9 @@ impl PhotocraftApp { file_dialog: None, tiff_options: None, save_dirs: HashMap::new(), + disk_stamps: HashMap::new(), targa_options: None, + dds_options: None, held_opens: Default::default(), allow_close: false, stylus: Default::default(), @@ -1087,6 +1181,11 @@ impl PhotocraftApp { self.import_os_clipboard(); } if self.session.clipboard.is_none() && self.services.clipboard_get_image.is_some() { + if self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { + // The clipboard may well hold an image that can't be reached: say why. + notices::clipboard_unreadable(self); + return Ok(serde_json::json!({"pasted": false})); + } // Enabled on the strength of the OS clipboard, which held no image: a quiet no-op. let message = "Nothing to paste: the clipboard holds no image"; self.ui.status = tl!(message).into(); @@ -1383,21 +1482,22 @@ impl PhotocraftApp { /// continues on a later frame, see `file_dialog`). Returns `{"path", "warnings"}` (the export /// warnings are also shown to the user). pub fn save_as(&mut self, path: Option) -> Result { - self.save_as_with(path, None) + self.save_as_with(path, FormatChoices::default()) } - /// [`Self::save_as`], writing a Targa with `tga_bits` per pixel when given (no Targa Options - /// prompt): `file.save` and `file.saveAs` with `tgaBits`. - pub fn save_as_with(&mut self, path: Option, tga_bits: Option) -> Result { - self.save_dialog_flow(path, tga_bits, false) + /// [`Self::save_as`], writing a Targa or DDS texture with the `choices` given instead of + /// asking for them (no Targa or DDS Options prompt): `file.save` and `file.saveAs` with + /// `tgaBits`, `ddsCompression` or `ddsMipmaps`. + pub fn save_as_with(&mut self, path: Option, choices: FormatChoices) -> Result { + self.save_dialog_flow(path, choices, false) } /// [`Self::save_as_with`]. `plain_save` marks File › Save that had to ask for a file name /// (a flat file): confirming the document's own file is recorded as a `file.save` step, /// which writes whichever file the action is played on, not as a Save As to a fixed path. - pub(crate) fn save_dialog_flow(&mut self, path: Option, tga_bits: Option, plain_save: bool) -> Result { + pub(crate) fn save_dialog_flow(&mut self, path: Option, choices: FormatChoices, plain_save: bool) -> Result { if self.save_options_open() { - return Err("Answer TIFF or Targa Options before starting another save".into()); + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); } // Edit Contents documents save back into their smart object. if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") { @@ -1405,7 +1505,7 @@ impl PhotocraftApp { return Ok(serde_json::json!({"path": "smart object", "warnings": []})); } if let Some(path) = path { - return self.save_to(path, tga_bits); + return self.save_to(path, choices); } let st = self.session.active().ok_or("no document")?; // PDN imports default to our native format, which preserves Paint.NET's blend modes; @@ -1438,7 +1538,14 @@ impl PhotocraftApp { self.pick_save(&suggested, move |app, path| { app.with_document(doc, |app| { let own = app.session.active().and_then(|st| st.path.clone()); - let r = app.save_to(path.clone(), tga_bits)?; + // Confirming the document's own file: ask first if another app changed it (#6596). + if plain_save + && own.as_deref() == Some(path.as_str()) + && let Some(r) = crate::disk_change_prompt::intercept(app, doc, &path, true) + { + return r; + } + let r = app.save_to(path.clone(), choices)?; if plain_save && own.as_deref() == Some(path.as_str()) { app.journal_as_plain_save(&path); } @@ -1448,70 +1555,89 @@ impl PhotocraftApp { } /// [`Self::save_as_with`] once the path is known. - fn save_to(&mut self, path: String, tga_bits: Option) -> Result { - // An RGB Targa asks for its bits per pixel, unless the caller chose them; the save - // continues from the prompt (still a copy when it would be one without the prompt), - // which records the step once answered. - if tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) { + pub(crate) fn save_to(&mut self, path: String, choices: FormatChoices) -> Result { + // An RGB Targa asks for its bits per pixel, and a DDS texture for its compression, unless + // the caller chose them; the save continues from the prompt (still a copy when it would + // be one without the prompt), which records the step once answered. + if choices.tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) { let copy = self.saves_copy(&path, None)?; targa_options_ui::park(self, path.clone(), copy, "file.saveAs")?; return Ok(serde_json::json!({"path": path, "warnings": []})); } + if choices.dds.is_none() && dds_options_ui::wants_prompt(&path) { + let copy = self.saves_copy(&path, None)?; + dds_options_ui::park(self, path.clone(), copy, "file.saveAs")?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } // A layered TIFF asks about its layers first (Preferences › File Handling); the save // continues from the prompt, which records the step once answered. if tiff_options_ui::wants_prompt(self, &path) { tiff_options_ui::park(self, path.clone())?; return Ok(serde_json::json!({"path": path, "warnings": []})); } - self.save_as_step(path, None, tga_bits) + self.save_as_step(path, None, choices) } - /// File › Save back to the document's own layered file, recorded as a `file.save` step. - pub(crate) fn save_in_place(&mut self, path: String) -> Result { + /// File › Save back to the document's own file, recorded as a `file.save` step with the + /// Targa or DDS answer in `choices` (a replayed Save of a flat file brings its own). + pub(crate) fn save_in_place(&mut self, path: String, choices: FormatChoices) -> Result { if self.save_options_open() { - return Err("Answer TIFF or Targa Options before starting another save".into()); + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); } - let r = self.write_save(path, None, None)?; - self.session.journal.push(("file.save".into(), Value::Object(Default::default()))); + let r = self.write_save(path, None, choices)?; + let mut step = Value::Object(Default::default()); + choices.record(&mut step); + self.session.journal.push(("file.save".into(), step)); Ok(r) } - /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF or - /// Targa answer), so an action being recorded keeps it (#2032). - fn save_as_step(&mut self, path: String, tiff_layers: Option, tga_bits: Option) -> Result { - let r = self.write_save(path.clone(), tiff_layers, tga_bits)?; + /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF, + /// Targa or DDS answer), so an action being recorded keeps it (#2032). + fn save_as_step(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { + let r = self.write_save(path.clone(), tiff_layers, choices)?; let mut step = serde_json::json!({"path": path}); if let Some(layers) = tiff_layers { step["tiffLayers"] = layers.into(); } - if let Some(bits) = tga_bits { - step["tgaBits"] = bits.bits().into(); - } + choices.record(&mut step); self.session.journal.push(("file.saveAs".into(), step)); Ok(r) } - /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]). - fn journal_as_plain_save(&mut self, path: &str) { + /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]), + /// keeping its Targa or DDS answer so playback writes the file the same way. A save parked + /// behind Targa or DDS Options hasn't been journaled yet: it is recorded as File › Save once + /// answered. + pub(crate) fn journal_as_plain_save(&mut self, path: &str) { + let parked = [self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)), self.dds_options.as_mut().map(|p| (&p.path, &mut p.record))]; + if let Some((_, record)) = parked.into_iter().flatten().find(|(p, record)| p.as_str() == path && **record == "file.saveAs") { + *record = "file.save"; + return; + } if let Some(last) = self.session.journal.last_mut() && last.0 == "file.saveAs" && last.1.get("path").and_then(Value::as_str) == Some(path) - && last.1.as_object().is_some_and(|o| o.len() == 1) + && let Some(step) = last.1.as_object() + && step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps")) { - *last = ("file.save".into(), Value::Object(Default::default())); + let mut step = step.clone(); + step.remove("path"); + *last = ("file.save".into(), Value::Object(step)); } } /// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` step: no dialog or prompt, and the - /// recorded TIFF or Targa answer (if any) stands in for the TIFF or Targa Options prompt. + /// recorded TIFF, Targa or DDS answer (if any) stands in for the TIFF, Targa or DDS Options prompt. pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result { if self.save_options_open() { - return Err("Answer TIFF or Targa Options before starting another save".into()); + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); } if id == "file.save" { // The file the action is played on: one that holds the whole document, or a flat // file a recorded Save confirmed in the dialog while the document is still a plain - // raster, so it is never flattened over (#3531, #3806). + // raster, so it is never flattened over (#3531, #3806). A flat file's recorded Targa + // or DDS answer stands in for the prompt. + let choices = FormatChoices::from_params(params, id)?; let st = self.session.active().ok_or("no document")?; let flat_own = |p: &str| { !photocraft_engine::file_cmds::saves_in_place(p) @@ -1521,16 +1647,16 @@ impl PhotocraftApp { let path = st.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p) || flat_own(p)).ok_or( "Save writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file (OpenRaster only when it holds everything), or to its own flat file while the document is a single plain layer", )?; - return self.save_in_place(path); + return self.save_in_place(path, choices); } let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?; - let tga_bits = targa_options_ui::bits_param(params, id)?; + let choices = FormatChoices::from_params(params, id)?; if id == "file.saveACopy" { // A copy: the document keeps its own file and unsaved state, as when recorded (#4373). let doc = self.session.active().ok_or("no document")?.doc.clone(); - return crate::view_cmds::write_copy(self, &doc, path, tga_bits); + return crate::view_cmds::write_copy(self, &doc, path, choices); } - self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), tga_bits) + self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), choices) } /// What a save writes by default under the preferences: File Handling › Image Previews @@ -1549,6 +1675,7 @@ impl PhotocraftApp { settings.jpeg_quality = e.jpeg_quality.map(|q| q.clamp(1, 100)); settings.webp_lossless = e.webp_lossless.unwrap_or(settings.webp_lossless); settings.webp_quality = e.webp_quality.map(|q| q.min(100)); + settings.document_path = st.path.as_deref().map(std::path::PathBuf::from); } settings } @@ -1569,11 +1696,11 @@ impl PhotocraftApp { } /// Writes the active document to a known path. `tiff_layers` is the TIFF Options answer: - /// `Some(false)` discards the layers and saves a copy. `tga_bits` is the Targa bits per - /// pixel (`None`: 32 with an alpha channel or transparency, else 24). - fn write_save(&mut self, path: String, tiff_layers: Option, tga_bits: Option) -> Result { + /// `Some(false)` discards the layers and saves a copy. `choices` are the Targa bits per + /// pixel (`None`: 32 with an alpha channel or transparency, else 24) and the DDS options. + fn write_save(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { let copy = self.saves_copy(&path, tiff_layers)?; - let settings = ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), tga_bits, ..self.save_settings() }; + let settings = choices.apply(ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), ..self.save_settings() }); match self.write_document(path.clone(), &settings, copy)? { Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})), None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})), @@ -1592,11 +1719,12 @@ impl PhotocraftApp { return jobs_ui::start_save(self, path, settings.clone(), copy, save, false); } let st = self.session.active().ok_or("no document")?; - let (doc, revision) = (st.doc.id, st.revision); + let (doc, written, previous) = (st.doc.id, st.revision, st.saved_revision); let export = self.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(&st.doc, &path, settings)?; let write = self.services.write.as_mut().ok_or("no writer configured")?; write(&path, &bytes)?; + let revision = saved_revision_after_write(!self.services.write_unconfirmed, written, previous); self.saved(doc, revision, &path, &warnings, copy); Ok(Some((path, warnings))) } @@ -1633,6 +1761,7 @@ impl PhotocraftApp { st.saved_to(path.to_string()); // The job locked the document, but record the revision that was written. st.saved_revision = revision; + app.remember_stamp(doc, path); } // "Save Document" script events and File › Generate › Image Assets. if hooks @@ -1652,6 +1781,9 @@ impl PhotocraftApp { if hooks { self.push_recent(path); } + } else if self.disk_stamps.get(&doc).is_some_and(|(own, _)| own == path) { + // A copy written over the document's own file is this app's change too. + self.remember_stamp(doc, path); } self.ui.status_error = false; let what = crate::i18n::fmt(tl!("Saved {name}"), &[("name", file_open::display_name(path).as_str())]); @@ -1659,9 +1791,24 @@ impl PhotocraftApp { self.sync_views(); } - /// TIFF Options or Targa Options is waiting on an answer before a save is written. + /// Note how `doc`'s own file at `path` looks now that the document read or wrote it. + pub(crate) fn remember_stamp(&mut self, doc: photocraft_doc::DocId, path: &str) { + match self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)) { + Some(now) => self.disk_stamps.insert(doc, (path.to_string(), now)), + None => self.disk_stamps.remove(&doc), + }; + } + + /// Another app changed `doc`'s own file at `path` since the document was opened from it or + /// last saved to it. A file that is gone, or one never stamped, counts as unchanged. + pub(crate) fn changed_on_disk(&self, doc: photocraft_doc::DocId, path: &str) -> bool { + let Some((own, then)) = self.disk_stamps.get(&doc) else { return false }; + own == path && self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)).is_some_and(|now| now != *then) + } + + /// TIFF, Targa or DDS Options is waiting on an answer before a save is written. pub(crate) fn save_options_open(&self) -> bool { - self.tiff_options.is_some() || self.targa_options.is_some() + self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some() } /// A print worker may still be handing a job to the system queue. @@ -1678,12 +1825,13 @@ impl PhotocraftApp { /// picker or ambient writer is reachable from this path. Returns the path /// written and the export warnings (also shown to the user). pub fn save_automation(&mut self, path: Option) -> Result { - self.save_automation_with(path, None) + self.save_automation_with(path, FormatChoices::default()) } - /// [`Self::save_automation`] writing a Targa with `tga_bits` per pixel (`None`: 32 with an - /// alpha channel or transparency, else 24). Automation saves never prompt. - pub fn save_automation_with(&mut self, path: Option, tga_bits: Option) -> Result { + /// [`Self::save_automation`] writing a Targa or DDS texture with the `choices` given (a + /// Targa's `None`: 32 with an alpha channel or transparency, else 24; a DDS texture's: + /// uncompressed without mipmaps). Automation saves never prompt. + pub fn save_automation_with(&mut self, path: Option, choices: FormatChoices) -> Result { let target = { let state = self.session.active().ok_or("no document")?; // As File › Save: without `path` only a layered file is written back (#416). @@ -1696,7 +1844,7 @@ impl PhotocraftApp { if self.background_jobs && let Some(save) = self.services.automation_save.clone() { - return match jobs_ui::start_save(self, target.clone(), ExportSettings { tga_bits, ..self.save_settings() }, false, save, true)? { + return match jobs_ui::start_save(self, target.clone(), choices.apply(self.save_settings()), false, save, true)? { Some((path, warnings)) => Ok(reply(&path, &warnings)), None => { let job = self.jobs.last_started; @@ -1706,7 +1854,7 @@ impl PhotocraftApp { } let state = self.session.active().ok_or("no document")?; let (doc, revision) = (state.doc.id, state.revision); - let settings = ExportSettings { tga_bits, ..self.save_settings() }; + let settings = choices.apply(self.save_settings()); let export = self.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(&state.doc, &target, &settings)?; let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?; @@ -1867,6 +2015,10 @@ impl eframe::App for PhotocraftApp { self.open_failed(&name, &e); } } + // Web drops onto the canvas, read since the last frame: placed below, one at a time. + let to_place: Vec<(String, Vec)> = + self.services.place_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); + self.drop_places.extend(to_place.into_iter().map(|(name, bytes)| file_open::DropPlace::Bytes(name, bytes))); // Finder double-click / Open With / Dock drops (macOS open-documents events). self.drain_os_events(ctx); // While files are dragged over the window it gets no pointer events: keep frames coming so @@ -2002,6 +2154,7 @@ impl eframe::App for PhotocraftApp { discard_ui::show(self, &ctx); tiff_options_ui::show(self, &ctx); targa_options_ui::show(self, &ctx); + dds_options_ui::show(self, &ctx); distort_ui::show(self, &ctx); camera_raw_ui::show(self, &ctx); wide_angle_ui::show(self, &ctx); @@ -2038,6 +2191,18 @@ impl eframe::App for PhotocraftApp { ctx.set_cursor_icon(egui::CursorIcon::Wait); } let ui_ms = gpu_canvas::now_ms() - t0; + // A GPU measurement lands a frame or two after the refresh it belongs to. Refreshes + // carry them out, but the last refresh before the app settles has none following it, so + // drain the timer here too or its number is never reported. Drain it either way: a + // measurement left sitting would surface later against an unrelated refresh. Report it + // only while the canvas is still on the GPU, since a CPU refresh clears `gpu_ms` + // precisely so a GPU number is never shown as that refresh's. + if let Some(gpu) = &self.gpu + && let Some(t) = gpu.take_gpu_timing() + && self.perf.last_refresh.starts_with("gpu") + { + self.perf.record_gpu(t); + } self.perf.frame(ui_ms); if self.stroke_trace.enabled() { self.stroke_trace.canvas(self.perf.frame_refresh_ms); @@ -2744,6 +2909,9 @@ mod dropdown_press_tests; #[cfg(test)] mod marquee_tests; +#[cfg(test)] +mod guide_cursor_tests; + #[cfg(test)] mod canvas_menu_tests; diff --git a/crates/ui-egui/src/liquify_ui.rs b/crates/ui-egui/src/liquify_ui.rs index 07c1e5a7b6..9f46020b11 100644 --- a/crates/ui-egui/src/liquify_ui.rs +++ b/crates/ui-egui/src/liquify_ui.rs @@ -10,7 +10,7 @@ use egui::{Align2, Color32, FontId, Pos2, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2}; use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, LiquifyTool, ProxyImage, auto_cell}; -use photocraft_doc::LayerId; +use photocraft_doc::{Document, LayerId}; use photocraft_geom::Rect; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -40,10 +40,32 @@ pub struct LiquifyOpts { pub mesh_size: usize, pub show_mask: bool, pub show_backdrop: bool, + /// Show Backdrop › Use: the layer shown as the backdrop (its id), `None` for All Layers. + pub backdrop_layer: Option, + pub backdrop_mode: BackdropMode, pub backdrop_opacity: f32, pub reconstruct_amount: f32, } +/// Show Backdrop › Mode, as Photoshop draws them (#7609): In Front lays the backdrop over the +/// image at the Opacity, Behind lays the image over the backdrop at the Opacity, and Blend fades +/// the image to 100 − Opacity under the backdrop at the Opacity. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum BackdropMode { + #[default] + InFront, + Behind, + Blend, +} + +impl BackdropMode { + const ALL: [(BackdropMode, &'static str); 3] = [(BackdropMode::InFront, "inFront"), (BackdropMode::Behind, "behind"), (BackdropMode::Blend, "blend")]; + + fn key(self) -> &'static str { + Self::ALL.iter().find(|(m, _)| *m == self).map_or("inFront", |(_, k)| k) + } +} + impl Default for LiquifyOpts { fn default() -> Self { LiquifyOpts { @@ -56,6 +78,8 @@ impl Default for LiquifyOpts { mesh_size: 1, show_mask: true, show_backdrop: false, + backdrop_layer: None, + backdrop_mode: BackdropMode::InFront, backdrop_opacity: 50.0, reconstruct_amount: 100.0, } @@ -88,6 +112,13 @@ impl LiquifyOpts { *slot = b; } } + // `"all"` (or anything but a layer id) is All Layers. + if let Some(u) = v.get("backdropUse") { + self.backdrop_layer = u.as_u64(); + } + if let Some(m) = v.get("backdropMode").and_then(Value::as_str).and_then(|m| BackdropMode::ALL.iter().find(|(_, k)| *k == m)) { + self.backdrop_mode = m.0; + } if let Some(m) = v.get("meshSize").and_then(Value::as_str) { self.mesh_size = match m { "small" => 0, @@ -114,6 +145,8 @@ impl LiquifyOpts { "meshSize": mesh, "showMask": self.show_mask, "showBackdrop": self.show_backdrop, + "backdropUse": self.backdrop_layer.map_or(json!("all"), |id| json!(id)), + "backdropMode": self.backdrop_mode.key(), "backdropOpacity": self.backdrop_opacity, }) } @@ -143,7 +176,8 @@ pub struct LiquifyDialog { view_source_scratch: Vec<[f32; 4]>, view_tex: Option, view_dirty: Option, - backdrop: Option, + /// The backdrop and the Use it shows (see [`LiquifyOpts::backdrop_layer`]). + backdrop: Option<(Option, TextureHandle)>, mask_tex: Option, mask_dirty: bool, pub opts: LiquifyOpts, @@ -495,6 +529,8 @@ pub fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> if let Some(saved) = app.session.prefs().dialogs.get(REMEMBERED) { let _ = d.opts.apply(saved); } + // Layer ids belong to one document: a remembered backdrop Use starts at All Layers. + d.opts.backdrop_layer = None; d.upload(ctx); app.distort.liquify = Some(d); Ok(()) @@ -536,8 +572,16 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { cancel(app); return Ok(json!({"cancelled": true})); } + // A `backdropUse` that names no layer of the document is All Layers, as the Use list shows it. + let missing = |id: u64| app.session.active().is_none_or(|st| st.doc.layer(LayerId(id)).is_none()); + let unknown_use = ui.get("backdropUse").and_then(Value::as_u64).is_some_and(missing); let d = app.distort.liquify.as_mut().ok_or(tl!("Liquify is not open"))?; - d.opts.apply(ui)?; + // `apply` takes every setting it can before a bad one fails it, so normalize first. + let applied = d.opts.apply(ui); + if unknown_use { + d.opts.backdrop_layer = None; + } + applied?; let num = |k: &str| ui.get(k).and_then(Value::as_f64).map(|v| v as f32); let flag = |k: &str| ui.get(k).and_then(Value::as_bool); if flag("undo") == Some(true) { @@ -710,26 +754,85 @@ fn shortcut(t: LiquifyTool) -> &'static str { } } -fn load_backdrop(app: &PhotocraftApp, ctx: &egui::Context, layer: LayerId, canvas: Rect) -> Option { +/// The backdrop for Show Backdrop › Use `of`: the document as it is (All Layers, the liquified +/// layer's own pixels included, as in Photoshop) or that one layer alone. A layer that is gone +/// shows All Layers. +fn load_backdrop(app: &PhotocraftApp, ctx: &egui::Context, of: Option, canvas: Rect) -> Option { let st = app.session.active()?; - let doc = crate::distort_ui::without_layer(&st.doc, layer); - let buf = photocraft_compose::render(&doc, canvas); + let buf = photocraft_compose::render(&backdrop_doc(&st.doc, of), canvas); let mut s = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); let flat: Vec = buf.px.iter().flat_map(|p| *p).collect(); s.write_region(canvas, &flat); Some(ctx.load_texture("liquify-backdrop", crate::distort_ui::surface_image(&s, canvas, PROXY_SIDE), egui::TextureOptions::LINEAR)) } +/// The document [`load_backdrop`] renders for Use `of`. +fn backdrop_doc(doc: &Document, of: Option) -> std::borrow::Cow<'_, Document> { + match of.map(LayerId).filter(|id| doc.layer(*id).is_some()) { + Some(id) => { + let mut d = doc.clone(); + crate::transform_tool::solo_layer(&mut d.layers, id); + // A hidden layer, or one in a hidden group, shows too: Use lists every layer. + reveal(&mut d.layers, id); + std::borrow::Cow::Owned(d) + } + None => std::borrow::Cow::Borrowed(doc), + } +} + +/// Makes layer `id` and the groups holding it visible; whether it was found. +fn reveal(layers: &mut [photocraft_doc::Layer], id: LayerId) -> bool { + layers.iter_mut().any(|l| { + let found = l.id == id + || match &mut l.content { + photocraft_doc::LayerContent::Group(g) => reveal(&mut g.children, id), + _ => false, + }; + if found { + l.visible = true; + } + found + }) +} + +/// How the preview layers the image and the backdrop texture `T`: the image's tint, and the +/// backdrop drawn behind it or in front of it, with its tint. +#[derive(Debug, PartialEq)] +struct Layering { + image: Color32, + behind: Option<(T, Color32)>, + front: Option<(T, Color32)>, +} + +/// The [`Layering`] for the backdrop `backdrop` (when shown) in `mode` at `opacity` (0..1): +/// Photoshop's modes, measured on its Liquify (#7609). +fn backdrop_layering(backdrop: Option, mode: BackdropMode, opacity: f32) -> Layering { + let alpha = |a: f32| Color32::from_white_alpha((a.clamp(0.0, 1.0) * 255.0).round() as u8); + let (image, behind, front) = match (backdrop, mode) { + (None, _) => (Color32::WHITE, None, None), + (Some(b), BackdropMode::InFront) => (Color32::WHITE, None, Some((b, alpha(opacity)))), + (Some(b), BackdropMode::Behind) => (alpha(opacity), Some((b, Color32::WHITE)), None), + (Some(b), BackdropMode::Blend) => (alpha(1.0 - opacity), None, Some((b, alpha(opacity)))), + }; + Layering { image, behind, front } +} + /// Draws the dialog (a full-window layer over the app). pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let t = Tokens::get(ctx); let screen = ctx.content_rect(); - if app.distort.liquify.as_ref().is_some_and(|d| d.opts.show_backdrop && d.backdrop.is_none()) { - let tex = app.distort.liquify.as_ref().map(|d| (d.layer, d.canvas)).and_then(|(layer, canvas)| load_backdrop(app, ctx, layer, canvas)); + // The backdrop is built when it's first shown and again when its Use changes. + let wanted = app.distort.liquify.as_ref().filter(|d| d.opts.show_backdrop && d.backdrop.as_ref().is_none_or(|(of, _)| *of != d.opts.backdrop_layer)); + if let Some((of, canvas)) = wanted.map(|d| (d.opts.backdrop_layer, d.canvas)) { + let tex = load_backdrop(app, ctx, of, canvas); if let Some(d) = app.distort.liquify.as_mut() { - d.backdrop = tex; + d.backdrop = tex.map(|t| (of, t)); } } + // Show Backdrop › Use: All Layers or one layer, bottom to top as Photoshop lists them. + let backdrop_layers: Vec<(Option, String)> = std::iter::once((None, tl!("All Layers").to_string())) + .chain(app.session.active().into_iter().flat_map(|st| st.doc.walk().into_iter().map(|(_, _, l)| (Some(l.id.0), l.name.clone())).collect::>())) + .collect(); let mut action: Option<&str> = None; let mut events: Vec = Vec::new(); let mut mods = egui::Modifiers::NONE; @@ -818,6 +921,16 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { widgets::checkbox(ui, &mut d.opts.show_mask, tl!("Show Mask")); widgets::checkbox(ui, &mut d.opts.show_backdrop, tl!("Show Backdrop")); if d.opts.show_backdrop { + ui.horizontal(|ui| { + ui.label(tl!("Use")); + let names: Vec<(Option, &str)> = backdrop_layers.iter().map(|(id, n)| (*id, n.as_str())).collect(); + widgets::dropdown_literal(ui, "liquify-backdrop-use", &mut d.opts.backdrop_layer, &names, 150.0); + }); + ui.horizontal(|ui| { + ui.label(tl!("Mode")); + let modes = [(BackdropMode::InFront, tl!("In Front")), (BackdropMode::Behind, tl!("Behind")), (BackdropMode::Blend, tl!("Blend"))]; + widgets::dropdown(ui, "liquify-backdrop-mode", &mut d.opts.backdrop_mode, &modes, 150.0); + }); widgets::slider_row(ui, tl!("Opacity"), &mut d.opts.backdrop_opacity, 0.0..=100.0, "", None); } widgets::hairline(ui); @@ -875,10 +988,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let clip = painter.with_clip_rect(area); widgets::checker(&clip, img.intersect(area), 8.0); let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - if d.opts.show_backdrop - && let Some(b) = &d.backdrop - { - clip.image(b.id(), img, uv, Color32::from_white_alpha((d.opts.backdrop_opacity / 100.0 * 255.0) as u8)); + let backdrop = d.backdrop.as_ref().filter(|_| d.opts.show_backdrop).map(|(_, t)| t.id()); + let Layering { image: image_tint, behind, front } = backdrop_layering(backdrop, d.opts.backdrop_mode, d.opts.backdrop_opacity / 100.0); + if let Some((b, c)) = behind { + clip.image(b, img, uv, c); } if d.zoom > 1.0 && let (Some(bounds), Some(tex)) = (d.view_bounds, &d.view_tex) @@ -887,7 +1000,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { to_screen(d, area, [f64::from(bounds.x0), f64::from(bounds.y0)]), to_screen(d, area, [f64::from(bounds.x1), f64::from(bounds.y1)]), ); - clip.image(tex.id(), detail, uv, Color32::WHITE); + clip.image(tex.id(), detail, uv, image_tint); } else { // The proxy covers whole proxy pixels, a little past the canvas edge. let pr = ERect::from_min_max( @@ -895,9 +1008,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { img.min + vec2(d.proxy.w as f32 * d.proxy.scale as f32 * d.zoom, d.proxy.h as f32 * d.proxy.scale as f32 * d.zoom), ); if let Some(tex) = &d.tex { - clip.image(tex.id(), pr, uv, Color32::WHITE); + clip.image(tex.id(), pr, uv, image_tint); } } + if let Some((b, c)) = front { + clip.image(b, img, uv, c); + } if d.opts.show_mask && let Some(m) = &d.mask_tex { @@ -1111,6 +1227,55 @@ mod tests { assert!(d.preview_ms.is_finite()); } + /// #7609: Show Backdrop › Use and Mode, as in Photoshop: the settings, how each mode layers the + /// backdrop and the image, and what each Use shows. + #[test] + fn backdrop_use_and_mode() { + let mut o = LiquifyOpts::default(); + assert_eq!((o.backdrop_layer, o.backdrop_mode), (None, BackdropMode::InFront), "All Layers, In Front"); + o.apply(&json!({"backdropUse": 3, "backdropMode": "behind"})).unwrap(); + assert_eq!((o.backdrop_layer, o.backdrop_mode), (Some(3), BackdropMode::Behind)); + assert_eq!((&o.to_json()["backdropUse"], &o.to_json()["backdropMode"]), (&json!(3), &json!("behind"))); + o.apply(&json!({"backdropUse": "all", "backdropMode": "nope"})).unwrap(); + assert_eq!((o.backdrop_layer, o.backdrop_mode), (None, BackdropMode::Behind), "a bad mode is ignored"); + let (w, a) = (Color32::WHITE, |x: f32| Color32::from_white_alpha((x * 255.0).round() as u8)); + let l = |image, behind, front| Layering { image, behind, front }; + assert_eq!(backdrop_layering(Some(1), BackdropMode::InFront, 0.25), l(w, None, Some((1, a(0.25)))), "backdrop over the image"); + assert_eq!(backdrop_layering(Some(1), BackdropMode::Behind, 0.25), l(a(0.25), Some((1, w)), None), "image over the backdrop"); + assert_eq!(backdrop_layering(Some(1), BackdropMode::Blend, 0.25), l(a(0.75), None, Some((1, a(0.25)))), "faded together"); + assert_eq!(backdrop_layering::(None, BackdropMode::Blend, 0.25), l(w, None, None), "no backdrop: the image as is"); + // All Layers is the document with the liquified layer in it; one layer is that layer alone. + let app = app_with_layer(); + let st = app.session.active().unwrap(); + let (layer, background) = (st.active_layer.unwrap(), st.doc.layers[0].id); + let at = |doc: &Document| photocraft_compose::render(doc, Rect::new(10, 10, 11, 11)).px[0]; + let own = at(&st.doc); + assert_eq!(at(&backdrop_doc(&st.doc, None)), own, "All Layers"); + assert_eq!(at(&backdrop_doc(&st.doc, Some(layer.0))), own, "the liquified layer alone"); + assert_ne!(at(&backdrop_doc(&st.doc, Some(background.0))), own, "the Background alone"); + assert_eq!(at(&backdrop_doc(&st.doc, Some(9999))), own, "a layer that's gone: All Layers"); + // A hidden layer shows when it is the one used. + let mut hidden = (*st.doc).clone(); + hidden.layer_mut(layer).unwrap().visible = false; + assert_eq!(at(&backdrop_doc(&hidden, Some(layer.0))), own, "the hidden liquified layer, alone"); + // A remembered Use is a layer of another document: Liquify opens on All Layers. + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), json!({"backdropUse": 42, "backdropMode": "blend"}))); + open(&mut app, &ctx).unwrap(); + let o = &app.distort.liquify.as_ref().unwrap().opts; + assert_eq!((o.backdrop_layer, o.backdrop_mode), (None, BackdropMode::Blend), "the mode is kept, the layer is not"); + // Over the control channel, a layer of the document is kept and one that isn't is All Layers. + let layer = app.session.active().unwrap().active_layer.unwrap().0; + control(&mut app, &json!({"backdropUse": layer})).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().opts.backdrop_layer, Some(layer)); + control(&mut app, &json!({"backdropUse": 4242})).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().opts.backdrop_layer, None, "no such layer: All Layers"); + control(&mut app, &json!({"backdropUse": layer})).unwrap(); + assert!(control(&mut app, &json!({"backdropUse": 4242, "tool": "nope"})).is_err()); + assert_eq!(app.distort.liquify.as_ref().unwrap().opts.backdrop_layer, None, "also when another setting fails"); + } + /// #418: the brush settings survive Cancel, OK and Esc, and come back the next time Liquify /// opens (also after a restart: they live in the preferences). #[test] diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rs index 169d4588b9..321a31e73a 100644 --- a/crates/ui-egui/src/marquee_tests.rs +++ b/crates/ui-egui/src/marquee_tests.rs @@ -546,6 +546,29 @@ fn mouse_drag_inside_the_selection_moves_it() { assert_eq!(selection(&h), Rect::new(120, 90, 220, 170), "moved by (20, 10)"); } +/// #6290: with a fresh app's View › Snap To, a selection moved through the real canvas snaps its +/// edges to a guide and the document bounds. Layers' targets were clipped to the selection, so +/// it snapped back to its own starting edges and centre (shown as layer alignments) instead. +#[test] +fn a_moved_selection_snaps_to_guides_and_the_document_not_its_start() { + for (to, want) in [ + // Right edge 3 px left of the guide at x = 200; 3 px down stays put (not back to y = 52). + ([145.0, 103.0], Rect::new(100, 55, 200, 105)), + // 5 and 7 px from the document's top-left corner (its centre was 3 px off its start). + ([53.0, 55.0], Rect::new(0, 0, 100, 50)), + ] { + let mut h = harness(Tool::RectMarquee); + h.state_mut().run("view.newGuide", json!({"orientation": "vertical", "position": 200})).unwrap(); + h.state_mut().run("select.rect", json!({"x": 52, "y": 52, "width": 100, "height": 50})).unwrap(); + h.run_steps(2); + drag_to(&mut h, [100.0, 100.0], to); + let up = screen(&h, to[0], to[1]); + button(&mut h, up, false, Modifiers::NONE); + h.run_steps(2); + assert_eq!(selection(&h), want, "dragged to {to:?}"); + } +} + /// #5646: the Move tool keeps Photoshop's arrow pointer instead of the 4-way move cursor (the /// hover outline still marks the layer under the pointer). #[test] diff --git a/crates/ui-egui/src/mask_props_ui.rs b/crates/ui-egui/src/mask_props_ui.rs index 295310bf97..26c3791d5a 100644 --- a/crates/ui-egui/src/mask_props_ui.rs +++ b/crates/ui-egui/src/mask_props_ui.rs @@ -66,8 +66,12 @@ fn sliders(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: u64, document: u64 } g.0 }); - for (field, label, mut value, max, unit) in [("density", tl!("Density"), density * 100.0, 100.0, "%"), ("feather", tl!("Feather"), feather, 1000.0, "px")] { - let response = widgets::slider_row(ui, label, &mut value, 0.0..=max, unit, None); + // Feather's track is curved like Photoshop's, so a few px can be dragged to (#6545). + for (field, label, mut value, max, unit, curve) in + [("density", tl!("Density"), density * 100.0, 100.0, "%", None), ("feather", tl!("Feather"), feather, 1000.0, "px", Some(3.0))] + { + let gestures = widgets::RowGestures { curve, ..Default::default() }; + let response = widgets::slider_row_with(ui, label, &mut value, 0.0..=max, unit, None, gestures); response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(value), label)); if response.changed() { let mut params = json!({"document": document, "layer": layer, diff --git a/crates/ui-egui/src/mask_props_ui_tests.rs b/crates/ui-egui/src/mask_props_ui_tests.rs index 1cde904682..660b94a155 100644 --- a/crates/ui-egui/src/mask_props_ui_tests.rs +++ b/crates/ui-egui/src/mask_props_ui_tests.rs @@ -94,8 +94,32 @@ fn mask_slider_drags_preview_live_and_undo_as_separate_gestures() { h.state_mut().run("edit.redo", json!({})).unwrap(); assert!((mask(&h).density - 0.5).abs() < 0.01); h.run_steps(3); - drag(&mut h, 1, &[0.0, 0.01, 0.02]); - assert!((mask(&h).feather - 20.0).abs() < 0.1); + // #6545: Feather's track is curved like Photoshop's, so a fifth of the way is 8 px, not 200. + drag(&mut h, 1, &[0.0, 0.1, 0.2]); + assert!((mask(&h).feather - 8.0).abs() < 0.3, "feather {}", mask(&h).feather); +} + +/// #6545: the curve is only the track's. A typed Feather and the arrow keys stay exact px, and +/// drawing the knob for them never writes the value back. +#[test] +fn typed_and_stepped_feather_stays_exact() { + let mut h = harness(false, crate::theme::ThemeKind::Pro); + h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(1).unwrap().click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("5".into())); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(mask(&h).feather, 5.0); + h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(1).unwrap().click(); + h.run_steps(1); + h.key_press(egui::Key::ArrowUp); + h.run_steps(3); + assert_eq!(mask(&h).feather, 6.0); + let before = h.state().session.active().unwrap().history.past_len(); + h.run_steps(5); + assert_eq!(mask(&h).feather, 6.0); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before, "idle frames write nothing"); } #[test] diff --git a/crates/ui-egui/src/menu_keys.rs b/crates/ui-egui/src/menu_keys.rs index 5762b2a945..c1536d8ee6 100644 --- a/crates/ui-egui/src/menu_keys.rs +++ b/crates/ui-egui/src/menu_keys.rs @@ -118,6 +118,51 @@ pub fn mnemonic_text(ui: &Ui, prefix: &str, label: &str, mnemonic: Option, job.into() } +/// The checkmark menu rows draw in their gutter. +pub const CHECK_MARK: &str = "✔ "; + +/// Width of the checkmark column every menu row reserves (#5705): the width of [`CHECK_MARK`] in +/// the button font, so checked, unchecked and plain rows (and submenu headers) all start their +/// label at the same x, whatever the script of the label. +pub fn check_gutter(ui: &Ui) -> f32 { + let font = egui::TextStyle::Button.resolve(ui.style()); + ui.painter().layout_no_wrap(CHECK_MARK.to_owned(), font, Color32::PLACEHOLDER).size().x +} + +/// A menu row's text (#5705): the label behind a fixed-width checkmark column ([`check_gutter`]), +/// with ✔ in the column when `checked`, and the mnemonic underlined when given (as +/// [`mnemonic_text`]). +pub fn menu_row_text(ui: &Ui, checked: bool, label: &str, mnemonic: Option) -> egui::WidgetText { + let font = egui::TextStyle::Button.resolve(ui.style()); + let plain = egui::TextFormat { font_id: font, color: Color32::PLACEHOLDER, ..Default::default() }; + let mut job = egui::text::LayoutJob::default(); + job.wrap.max_width = f32::INFINITY; + // The label starts after the column: a checked row draws the mark in it, the others leave it + // empty (a leading space of the same width, not padding characters whose width varies). + let mut lead = check_gutter(ui); + if checked { + job.append(CHECK_MARK, 0.0, plain.clone()); + lead = 0.0; + } + let at = mnemonic.and_then(|m| label.char_indices().find(|(_, c)| c.to_ascii_uppercase() == m).map(|(i, c)| (i, c.len_utf8()))); + let parts = match at { + Some((i, len)) => [label.get(..i), label.get(i..i + len), label.get(i + len..)], + None => [Some(label), None, None], + }; + for (k, part) in parts.into_iter().enumerate() { + let Some(part) = part.filter(|p| !p.is_empty()) else { continue }; + let format = + if k == 1 && at.is_some() { egui::TextFormat { underline: Stroke::new(1.0, Color32::PLACEHOLDER), ..plain.clone() } } else { plain.clone() }; + job.append(part, lead, format); + lead = 0.0; + } + if job.sections.is_empty() { + // An empty label still keeps the row as wide as its column. + job.append("", lead, plain); + } + job.into() +} + impl Keys { /// Last frame's state. pub fn load(ctx: &egui::Context) -> Keys { @@ -173,7 +218,12 @@ impl Keys { self.alt_down = false; tap |= std::mem::take(&mut self.alt_tap); } - Event::Key { pressed: true, .. } | Event::Text(_) | Event::PointerButton { pressed: true, .. } => self.alt_tap = false, + // Alt+wheel (zoom, brush size…) or Alt going to the desktop is no tap either. + Event::Key { pressed: true, .. } + | Event::Text(_) + | Event::PointerButton { pressed: true, .. } + | Event::MouseWheel { .. } + | Event::WindowFocused(false) => self.alt_tap = false, _ => {} } } @@ -207,8 +257,10 @@ impl Keys { return; } if open { - // A letter runs the row with that mnemonic in the level the arrows are in. - let letter = events.iter().find_map(|e| match e { + // A letter runs the row with that mnemonic in the level the arrows are in, unless it is + // typed into a field in the menu: Help › Search took "S" for System Info (#5996). + let typing = ctx.text_edit_focused(); + let letter = events.iter().filter(|_| !typing).find_map(|e| match e { Event::Key { key, pressed: true, modifiers, .. } if !modifiers.command && !modifiers.ctrl && !modifiers.alt => { key_char(*key).map(|c| (*key, c)) } diff --git a/crates/ui-egui/src/menu_keys_tests.rs b/crates/ui-egui/src/menu_keys_tests.rs index 1f226054e0..0298cb470f 100644 --- a/crates/ui-egui/src/menu_keys_tests.rs +++ b/crates/ui-egui/src/menu_keys_tests.rs @@ -76,6 +76,37 @@ fn alt_focuses_the_bar_arrows_move_and_down_opens_the_lit_menu() { assert!(!is_open(&h.ctx) && Keys::current(&h.ctx).focus.is_none(), "Esc leaves the menu and the bar"); } +/// Alt+wheel zooms; letting go of Alt after it is no tap, so Space (the hand tool) can't then +/// open File and run New…. +#[test] +fn alt_with_a_wheel_scroll_or_a_lost_focus_is_no_tap() { + let mut h = bar(); + h.key_down(egui::Key::AltLeft); + h.run_steps(2); + h.event_modifiers( + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::ALT, + }, + egui::Modifiers::ALT, + ); + h.run_steps(2); + h.key_up(egui::Key::AltLeft); + h.run_steps(3); + assert_eq!(Keys::current(&h.ctx).focus, None, "Alt+scroll leaves the bar alone"); + key(&mut h, egui::Key::Space); + assert!(!is_open(&h.ctx), "Space opens no menu"); + h.key_down(egui::Key::AltLeft); + h.run_steps(2); + h.event(egui::Event::WindowFocused(false)); + h.event(egui::Event::WindowFocused(true)); + h.key_up(egui::Key::AltLeft); + h.run_steps(3); + assert_eq!(Keys::current(&h.ctx).focus, None, "Alt that went to the desktop leaves the bar alone"); +} + #[test] fn a_second_alt_or_esc_or_a_click_takes_the_keyboard_off_the_bar() { let mut h = bar(); @@ -210,3 +241,41 @@ fn the_shortcuts_wait_while_the_keyboard_is_on_the_bar() { h.run_steps(3); assert_ne!(h.state().ui.tool, tool, "off the bar, E picks the Eraser again"); } + +/// Checked, unchecked and plain rows (and submenu headers) start their label at the same x, in +/// any script: the checkmark column has a fixed width instead of padding characters (#5705). +#[test] +fn every_menu_row_starts_its_label_after_one_checkmark_column() { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(Default::default(), |ui| { + let start = |checked: bool, label: &str, mnemonic: Option| { + let galley = crate::menu_keys::menu_row_text(ui, checked, label, mnemonic).into_galley( + ui, + Some(egui::TextWrapMode::Extend), + f32::INFINITY, + egui::TextStyle::Button, + ); + let first = label.chars().next().unwrap_or(' '); + let row = galley.rows.first().expect("one row"); + let glyph = row.glyphs.iter().find(|g| g.chr == first).expect("the label's first glyph"); + assert!(galley.text().ends_with(label), "the label is shown whole: {:?}", galley.text()); + glyph.pos.x + }; + let gutter = crate::menu_keys::check_gutter(ui); + assert!(gutter > 0.0, "the column has room for the mark"); + for label in ["Lock Guides", "锁定参考线", "清除参考线"] { + let checked = start(true, label, None); + let unchecked = start(false, label, None); + assert!((checked - unchecked).abs() < 0.01, "{label}: checked {checked} vs unchecked {unchecked}"); + assert!((unchecked - gutter).abs() < 1.0, "{label}: the label starts right after the column ({unchecked} vs {gutter})"); + } + let underlined = start(false, "Clear Guides", Some('C')); + let plain = start(false, "Clear Guides", None); + assert!((underlined - plain).abs() < 0.01, "an underlined mnemonic doesn't move the label"); + let underlined_mid = start(true, "Lock Guides", Some('G')); + assert!((underlined_mid - plain).abs() < 0.01, "nor a mnemonic after the first letter"); + let t = crate::menu_keys::menu_row_text(ui, true, "Rulers", None); + assert_eq!(t.text(), "✔ Rulers", "a checked row keeps its mark (and its accessible label)"); + }); + out.textures_delta.clear(); +} diff --git a/crates/ui-egui/src/menu_nav.rs b/crates/ui-egui/src/menu_nav.rs index 822fcae2bd..c9aedd77d7 100644 --- a/crates/ui-egui/src/menu_nav.rs +++ b/crates/ui-egui/src/menu_nav.rs @@ -336,7 +336,10 @@ impl Nav { let Some(top) = self.top.filter(|_| !tops.is_empty()) else { return }; let level = self.level.min(self.rows.len().saturating_sub(1)); self.level = level; - let press = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); + // A text field in the menu (Help › Search) keeps the keys that edit it: ← / → move its + // cursor and Space types a space. + let typing = ctx.text_edit_focused(); + let press = |k: Key| !(typing && matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::Space)) && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); let current = self.highlighted(level).and_then(|i| self.rows.get(level)?.get(i)).cloned(); let switch = |by: usize| { let n = tops.len(); diff --git a/crates/ui-egui/src/menu_nav_tests.rs b/crates/ui-egui/src/menu_nav_tests.rs index 1643e2765b..fcf06ed028 100644 --- a/crates/ui-egui/src/menu_nav_tests.rs +++ b/crates/ui-egui/src/menu_nav_tests.rs @@ -265,6 +265,44 @@ fn left_and_right_switch_menus_and_shortcuts_wait_while_one_is_open() { assert!(!is_open(&h.ctx), "shortcuts work again"); } +/// In Help › Search, ← / → move the field's cursor instead of switching to Window / File, and +/// Space types a space instead of running the lit row. +#[test] +fn help_search_keeps_the_arrows_and_space_that_edit_it() { + let mut h = harness((1280.0, 720.0, 1.0)); + open(&mut h, "Help"); + let field = egui::Id::new("help-menu-search").with("field"); + assert_eq!(h.ctx.memory(|m| m.focused()), Some(field), "the search field has the keyboard"); + let text = |h: &Harness<'static, PhotocraftApp>| h.ctx.data(|d| d.get_temp::(egui::Id::new("help-menu-search"))).unwrap_or_default(); + let typing = |h: &mut Harness<'static, PhotocraftApp>, s: &str| { + h.event(egui::Event::Text(s.to_string())); + h.run_steps(3); + }; + typing(&mut h, "levls"); + key(&mut h, egui::Key::ArrowLeft); + assert!(h.query_by_label_contains("About PhotoCraft").is_some(), "← keeps Help open"); + key(&mut h, egui::Key::ArrowLeft); + typing(&mut h, "e"); + assert_eq!(text(&h), "levels", "← moved the cursor"); + // The cursor sits at `leve|ls`: two → take it to the end. + key(&mut h, egui::Key::ArrowRight); + assert!(h.query_by_label_contains("About PhotoCraft").is_some(), "→ keeps Help open"); + key(&mut h, egui::Key::ArrowRight); + // The pointer resting on a result lights it; a space typed then is text, not a click. + // "levels" finds both Image › Adjustments › Levels… and the Levels adjustment layer. + let levels = h.get_all_by_label_contains("› Levels").next().expect("a Levels result").rect().center(); + h.hover_at(levels); + h.run_steps(3); + assert!(Nav::current(&h.ctx).highlighted(0).is_some(), "a result is lit"); + h.event(egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.event(egui::Event::Text(" ".into())); + h.event(egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); + assert!(is_open(&h.ctx) && h.query_by_label_contains("About PhotoCraft").is_some(), "Space keeps Help open"); + assert!(h.state().ui.dialogs.is_empty(), "Space ran no command: {:?}", h.state().ui.dialogs); + assert_eq!(text(&h), "levels "); +} + /// A level's visible height (its view) and the full height of its rows: equal means no scrolling. fn fits(h: &Harness<'static, PhotocraftApp>, level: usize) -> (f32, f32) { let nav = Nav::current(&h.ctx); @@ -844,3 +882,62 @@ fn heading_is_the_triangle_to_the_submenus_near_edge() { assert!(!heading(egui::pos2(150.0, 110.0), egui::pos2(170.0, 160.0), left)); assert!(!heading(from, from, egui::Rect::NOTHING)); } + +/// #5896, #6225: a menu scrolled down (to reach Edit › Preferences or Window › Theme) reopens +/// scrolled, with the rows above its view lying over the menu bar. egui opens a submenu when the +/// pointer is over its row even where the row is scrolled out of sight, so a hidden submenu row +/// under the title opened on the press and the click on the title then closed the whole menu. +/// Rows out of view must not open their submenus: the menu stays open. +#[test] +fn a_scrolled_menu_reopens_and_stays_open_with_a_hidden_submenu_row_under_its_title() { + use egui::{Modifiers, PointerButton}; + for top in ["Edit", "Window"] { + let mut h = harness((1280.0, 420.0, 1.0)); + open(&mut h, top); + let title = h.get_by_label(top).rect().center(); + let view = Nav::current(&h.ctx).views[0]; + assert!(Nav::current(&h.ctx).contents[0] > view.height() + 1.0, "{top} must overflow for this test to mean anything"); + // Scroll to the end, then back up until a submenu row is out of view right under the title. + h.hover_at(egui::pos2(view.center().x, view.bottom() - 2.0)); + let wheel = |h: &mut Harness<'static, PhotocraftApp>, dy: f32| { + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, dy), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + }); + h.run_steps(1); + }; + for _ in 0..60 { + wheel(&mut h, -60.0); + } + let under = |h: &Harness<'static, PhotocraftApp>| { + rows(h, 0).iter().any(|r| r.command.is_none() && r.enabled && r.rect.x_range().contains(title.x) && r.rect.y_range().contains(title.y)) + }; + for _ in 0..400 { + if under(&h) { + break; + } + wheel(&mut h, 8.0); + } + assert!(under(&h), "{top}: a submenu row scrolled under the title"); + key(&mut h, egui::Key::Escape); + assert!(!is_open(&h.ctx), "{top}: Esc closed it"); + // Click the title again: press, release, as a mouse does. + h.hover_at(title); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: title, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: title, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + // Per frame after the click: is the menu open, and how many levels are drawn? + let frames: Vec<(bool, usize)> = (0..6) + .map(|_| { + h.run_steps(1); + let nav = Nav::current(&h.ctx); + (nav.rows.first().is_some_and(|r| !r.is_empty()), nav.rows.len()) + }) + .collect(); + assert!(frames.iter().all(|f| f.0), "{top}: the menu closed again right after the click: {frames:?}"); + assert!(frames.iter().all(|f| f.1 == 1), "{top}: a submenu scrolled out of view opened under the title: {frames:?}"); + } +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2839e51f13..79632791d5 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -155,6 +155,12 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: if let Some(r) = crate::prefs_ui::invoke(app, ctx, id, ¶ms) { return r; } + // Save for Web's dialog would export the committed document, not the open Free Transform (#6737). + if id == crate::transform_tool::SAVE_FOR_WEB + && let Some(r) = crate::transform_tool::intercept(app, id) + { + return r; + } // Save for Web, Print and the other File-menu dialogs added with slices. if let Some(r) = crate::file_ui::invoke(app, ctx, id, ¶ms) { return r; @@ -225,13 +231,18 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: "file.save" => { // Writes back only to a layered file that holds the whole document; anything else // goes through Save As, so the original is never overwritten with less (#3806). - let tga_bits = crate::targa_options_ui::bits_param(¶ms, id)?; + let choices = crate::FormatChoices::from_params(¶ms, id)?; match params.get("path").and_then(Value::as_str) { - Some(path) => app.save_as_with(Some(path.to_string()), tga_bits), + Some(path) => app.save_as_with(Some(path.to_string()), choices), None => { let own = app.session.active().and_then(|d| d.path.clone().map(|p| (photocraft_engine::file_cmds::holds_at(&d.doc, &p), p, d))); match own { - Some((true, path, _)) => app.save_in_place(path), + Some((true, path, d)) => { + // Another app changed the file since it was opened or saved: ask first (#6596). + let doc = d.doc.id; + crate::disk_change_prompt::intercept(app, doc, &path, false) + .unwrap_or_else(|| app.save_in_place(path, crate::FormatChoices::default())) + } Some((false, path, d)) if photocraft_engine::file_cmds::saves_in_place(&path) => { // Its own file is layered but can't hold what the document has now. let losses = photocraft_engine::file_cmds::losses_at(&d.doc, &path); @@ -240,11 +251,11 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: let mut lines = losses; lines.push(tl!("Choose a format that keeps it, such as Photoshop (PSD), or save a copy.").to_string()); crate::notices::post(app, title, lines, false, None); - app.save_as_with(None, tga_bits) + app.save_as_with(None, choices) } // A flat file asks for its name; confirming its own file records a // plain Save that writes the file an action is played on (#3531). - _ => app.save_dialog_flow(None, tga_bits, true), + _ => app.save_dialog_flow(None, choices, true), } } } @@ -278,8 +289,8 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: } } "file.saveAs" => { - let tga_bits = crate::targa_options_ui::bits_param(¶ms, id)?; - app.save_as_with(params.get("path").and_then(Value::as_str).map(str::to_string), tga_bits) + let choices = crate::FormatChoices::from_params(¶ms, id)?; + app.save_as_with(params.get("path").and_then(Value::as_str).map(str::to_string), choices) } "view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => app.run(id, params), "window.newWindowForDocument" => { @@ -405,6 +416,13 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: } Ok(Value::Null) } + // Only interactive creation opens the Color Picker; it creates the layer on OK, + // so Cancel leaves neither an orphan layer nor an undo/redo history entry. + // Explicit parameters continue straight to the engine. + "layer.newFillLayer.solidColor" if params.as_object().is_none_or(|o| o.is_empty()) => { + let dialog = crate::solid_fill_ui::open_new(app).ok_or("no document is open")?; + Ok(json!({"dialog": dialog})) + } // Solid Color fills and solid-colour shapes use the Color Picker, Pattern fills the Pattern // Fill dialog; other adjustment / fill / shape controls use Properties. "layer.layerContentOptions" => { @@ -1445,15 +1463,10 @@ fn render_level_rows(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, click continue; } let label = translated_menu_label(lang, it); - let prefix = match it.checked { - Some(true) => "✔ ", - Some(false) => " ", - None => "", - }; let mnemonic = mnemonics.get(next_row).copied().flatten(); next_row += 1; - let text: egui::WidgetText = - if nav.underline { crate::menu_keys::mnemonic_text(ui, prefix, &label, mnemonic, None) } else { format!("{prefix}{label}").into() }; + // Checked, unchecked and plain rows share one checkmark column (#5705). + let text = crate::menu_keys::menu_row_text(ui, it.checked == Some(true), &label, mnemonic.filter(|_| nav.underline)); let mut b = egui::Button::new(text); if let Some(tint) = it.color.as_deref().and_then(menu_tint) { b = b.fill(tint.gamma_multiply(0.55)); @@ -1486,19 +1499,15 @@ fn render_level_rows(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, click let enabled = submenu_enabled(&child); let mnemonic = mnemonics.get(next_row).copied().flatten(); next_row += 1; - let title: egui::WidgetText = if nav.underline { - crate::menu_keys::mnemonic_text(ui, "", crate::i18n::tr(lang, name), mnemonic, None) - } else { - crate::i18n::tr(lang, name).into() - }; + let title = crate::menu_keys::menu_row_text(ui, false, crate::i18n::tr(lang, name), mnemonic.filter(|_| nav.underline)); ui.add_enabled_ui(enabled, |ui| { nav.row(ui, depth - 1, enabled, None, mnemonic, |ui, nav| { - let r = ui.menu_button(title, |ui| render_level(ui, &child, depth + 1, clicked, nav)); - if r.inner.is_some() { + let (response, inner) = submenu_row(ui, title, |ui| render_level(ui, &child, depth + 1, clicked, nav)); + if inner.is_some() { // Where the submenu hangs from, to keep it below the menu bar (#319). - nav.set_anchor(depth, r.response.rect); + nav.set_anchor(depth, response.rect); } - (r.response, ()) + (response, ()) }); }); last_was_sep = false; @@ -1506,6 +1515,32 @@ fn render_level_rows(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, click } } +/// A submenu row, drawn as `ui.menu_button` draws it, except that a row scrolled out of view +/// doesn't open its submenu. egui opens a submenu whenever the pointer is over its row, clipped +/// or not: a menu reopened scrolled down (after Edit › Preferences or Window › Theme) has rows +/// hidden above its view, over the menu bar, and the hidden one under the title opened on the +/// press; the release on the title then counted as a click outside that submenu and closed the +/// whole menu (#5896, #6225). An open submenu (e.g. opened from the keyboard) is drawn as usual. +fn submenu_row(ui: &mut egui::Ui, title: egui::WidgetText, content: impl FnOnce(&mut egui::Ui) -> R) -> (egui::Response, Option) { + use egui::containers::menu::{MenuState, SubMenu, SubMenuButton}; + let sub = SubMenu::id_from_widget_id(ui.next_auto_id()); + let open = MenuState::from_ui(ui, |state, _| state.open_item == Some(sub)); + let inactive = ui.style().visuals.widgets.inactive; + if open { + ui.style_mut().visuals.widgets.inactive = ui.style().visuals.widgets.open; + } + let response = ui.add(egui::Button::new(title).right_text(SubMenuButton::RIGHT_ARROW)); + ui.style_mut().visuals.widgets.inactive = inactive; + // The rect egui tests the pointer against (`SubMenu::show`), against the part that can be seen. + let reach = response.rect.expand2(ui.spacing().item_spacing / 2.0); + let hidden = ui.ctx().pointer_hover_pos().is_some_and(|p| reach.contains(p) && !ui.clip_rect().contains(p)); + if hidden && !open { + return (response, None); + } + let inner = SubMenu::new().show(ui, &response, content); + (response, inner.map(|r| r.inner)) +} + /// A submenu header is enabled only while some item under it (at any depth) can run, so a /// submenu of greyed items is greyed too instead of opening onto them (#1976). fn submenu_enabled(children: &[&MenuItem]) -> bool { @@ -1874,6 +1909,44 @@ mod tests { } } + /// #5996: a real key press comes as a key and its text. A letter typed into Help › Search is + /// text for the field, not a mnemonic: "S" ran System Info and "A" the ArtCraft website. + #[test] + fn help_search_letters_are_not_mnemonics() { + use egui::{Event, Key, Modifiers, PointerButton}; + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ALL[0]); + PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()) + }); + h.run_steps(4); + let help = h.get_by_label("Help").rect().center(); + h.event(Event::PointerMoved(help)); + h.run_steps(1); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: help, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(3); + assert!(h.query_by_label_contains("About PhotoCraft").is_some(), "Help opened"); + for c in "DeSelect all".chars() { + let key = Key::from_name(&c.to_ascii_uppercase().to_string()); + if let Some(key) = key { + h.event(Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }); + } + h.event(Event::Text(c.to_string())); + h.run_steps(1); + if let Some(key) = key { + h.event(Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: Modifiers::NONE }); + } + } + h.run_steps(3); + assert!(h.query_by_label_contains("About PhotoCraft").is_some(), "typing keeps Help open"); + let query: String = h.ctx.data(|d| d.get_temp(egui::Id::new("help-menu-search"))).unwrap_or_default(); + assert_eq!(query, "DeSelect all", "every letter reached the field"); + assert!(h.state().ui.dialogs.is_empty(), "no menu command ran: {:?}", h.state().ui.dialogs); + } + #[test] fn dropdown_items_have_room() { use egui_kittest::{Harness, kittest::Queryable}; @@ -2079,9 +2152,11 @@ mod open_recent_tests { let ctx = egui::Context::default(); invoke(&mut app, &ctx, "file.open", json!({ "path": p })).unwrap(); assert_eq!(app.ui.recent_files.first().map(String::as_str), Some(p.as_str())); - // Re-open via the recent entry. + // Re-open via the recent entry once closed (an open file shows its tab instead, #6598). + app.session.close(0); invoke(&mut app, &ctx, "file.openRecent.0", json!({})).unwrap(); - assert_eq!(app.session.documents().len(), 2); + assert_eq!(app.session.documents().len(), 1); + assert_eq!(app.session.active().and_then(|d| d.path.as_deref()), Some(p.as_str())); let _ = std::fs::remove_file(&path); } } diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs index cd974fbbe7..76cdc7b9bb 100644 --- a/crates/ui-egui/src/notices.rs +++ b/crates/ui-egui/src/notices.rs @@ -8,6 +8,7 @@ use serde::{Deserialize, Serialize}; use crate::PhotocraftApp; const WAYLAND_FILE_DROP_DISMISSED: &str = "ui.waylandFileDropGuidanceDismissed"; +const CLIPBOARD_UNREADABLE: &str = "Pasting from other apps is unavailable"; /// At most this many notices are kept; older ones drop off. pub const MAX_NOTICES: usize = 3; /// Lines shown per notice before "…and N more". @@ -91,6 +92,30 @@ pub fn wayland_file_drop_guidance(app: &mut PhotocraftApp) { } } +/// A paste found no clipboard to read (#5031). In a Flatpak on Wayland the sandbox hides the +/// data-control protocol that other apps' images are read through, and there is no X server to +/// fall back to, so the clipboard may hold an image all the same. Say so, and give the command +/// that starts this install under XWayland, where the X11 clipboard works, when there is one. +pub fn clipboard_unreadable(app: &mut PhotocraftApp) { + app.ui.status = tl!("Nothing to paste: PhotoCraft can't read the system clipboard here").into(); + app.ui.status_error = false; + if app.ui.notices.iter().any(|notice| notice.title == CLIPBOARD_UNREADABLE) { + return; + } + // English templates, translated when drawn, as in `wayland_file_drop_guidance`. + let mut lines = + vec!["PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through.".to_owned()]; + let mut args = Vec::new(); + if let Some(command) = &app.services.xwayland_command { + lines.push("To paste from other apps, start PhotoCraft under XWayland: `{command}`".to_owned()); + args.push(("command".to_owned(), command.clone())); + } + let id = post(app, CLIPBOARD_UNREADABLE, lines, false, None); + if let Some(notice) = app.ui.notices.iter_mut().find(|notice| notice.id == id) { + notice.args = args; + } +} + /// A full refresh of document `doc` fell back to the CPU compositor (`reason`, the GPU's) and took /// `ms`. The canvas doesn't respond while it runs, so once per document say why it was slow and /// which edits will do it again (#1015). @@ -278,6 +303,37 @@ mod tests { assert_eq!(crate::i18n::tr(crate::i18n::Lang::EN, ¬ice.title), "Native file drag-and-drop is unavailable"); } + /// #5031: a paste that can't reach the clipboard (a Flatpak on Wayland) says why and how to + /// paste anyway, once while shown; a clipboard that simply holds no image stays a quiet no-op. + #[test] + fn unreadable_clipboard_paste_explains_the_sandbox() { + let command = "flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft"; + let services = |unreadable: bool| Services { + clipboard_get_image: Some(Box::new(|| None)), + clipboard_unreadable: Some(Box::new(move || unreadable)), + xwayland_command: Some(command.to_string()), + ..Default::default() + }; + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(Session::new(), services(true)); + for _ in 0..2 { + let r = crate::menus::invoke(&mut app, &ctx, "edit.paste", serde_json::json!({})).unwrap(); + assert_eq!(r["pasted"], serde_json::json!(false)); + } + assert_eq!(app.ui.status, "Nothing to paste: PhotoCraft can't read the system clipboard here"); + let shown: Vec<_> = app.ui.notices.iter().filter(|notice| notice.title == CLIPBOARD_UNREADABLE).collect(); + assert_eq!(shown.len(), 1, "a second paste doesn't stack another notice"); + let guidance = english(shown[0]); + assert!(guidance.contains(&format!("under XWayland: `{command}`")), "{guidance}"); + let es = crate::i18n::Lang::from_code("es").unwrap(); + assert!(shown[0].lines.iter().chain([&shown[0].title]).all(|line| crate::i18n::tr(es, line) != *line), "every line is a catalog template"); + + let mut empty = PhotocraftApp::new(Session::new(), services(false)); + crate::menus::invoke(&mut empty, &ctx, "edit.paste", serde_json::json!({})).unwrap(); + assert_eq!(empty.ui.status, "Nothing to paste: the clipboard holds no image"); + assert!(empty.ui.notices.iter().all(|notice| notice.title != CLIPBOARD_UNREADABLE)); + } + /// A notice's lines in English with their arguments filled in. fn english(notice: &Notice) -> String { let args: Vec<(&str, &str)> = notice.args.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); diff --git a/crates/ui-egui/src/numeric_expression.rs b/crates/ui-egui/src/numeric_expression.rs index a3232dd96f..6c7f96393c 100644 --- a/crates/ui-egui/src/numeric_expression.rs +++ b/crates/ui-egui/src/numeric_expression.rs @@ -19,6 +19,10 @@ pub struct Units<'s> { pub dpi: f64, /// Points per inch (72 PostScript, 72.27 traditional). pub ppi: f64, + /// The length in pixels that 100 % stands for, in a field that is both (Free Transform's W + /// and H, #6284): a length then converts into its percent and a percentage into its length. + /// `None` (most fields) keeps lengths and percentages apart. + pub extent: Option, } /// Unit names a number may carry, longest first so `pica` wins over `pc`. @@ -34,8 +38,9 @@ const UNIT_NAMES: [(&str, Unit); 8] = [ ]; /// [`parse`] where a number may carry a unit (`2in`, `5 mm`, `50%`), converted into the field's -/// unit. A unit that can't convert (a length in a percent field, any unit in a unitless one) makes -/// the whole text invalid; without `units`, unit names are invalid as before. +/// unit. A unit that can't convert (a length in a percent field without an [`Units::extent`], any +/// unit in a unitless one) makes the whole text invalid; without `units`, unit names are invalid +/// as before. pub(crate) fn parse_with_units(text: &str, units: Option) -> Option { if text.len() > 1024 { return None; @@ -168,7 +173,13 @@ impl Parser<'_> { Some(field) if field == typed => Some(value), // Lengths convert through pixels; a percentage has no length to convert against. Some(field) if field != Unit::Percent && typed != Unit::Percent => Some(field.from_px(typed.to_px(value, dpi, 1.0, ppi), dpi, 1.0, ppi)), - _ => None, + // A field whose 100 % is a length: convert through that length's pixels. + Some(field) => { + let extent = units.extent.map(f64::abs).filter(|e| e.is_finite() && *e > 1e-9)?; + let v = field.from_px(typed.to_px(value, dpi, extent, ppi), dpi, extent, ppi); + v.is_finite().then_some(v) + } + None => None, } } } @@ -206,10 +217,10 @@ mod tests { #[test] fn units_convert_into_the_field_unit_and_bad_input_is_rejected() { use super::{Unit, Units, parse_with_units}; - let px = Units { unit: Some(Unit::Pixels), suffix: "px", dpi: 300.0, ppi: 72.0 }; - let pt = Units { unit: Some(Unit::Points), suffix: "pt", dpi: 144.0, ppi: 72.0 }; - let pct = Units { unit: Some(Unit::Percent), suffix: "%", dpi: 72.0, ppi: 72.0 }; - let deg = Units { unit: None, suffix: "°", dpi: 72.0, ppi: 72.0 }; + let px = Units { unit: Some(Unit::Pixels), suffix: "px", dpi: 300.0, ppi: 72.0, extent: None }; + let pt = Units { unit: Some(Unit::Points), suffix: "pt", dpi: 144.0, ppi: 72.0, extent: None }; + let pct = Units { unit: Some(Unit::Percent), suffix: "%", dpi: 72.0, ppi: 72.0, extent: None }; + let deg = Units { unit: None, suffix: "°", dpi: 72.0, ppi: 72.0, extent: None }; for (text, units, want) in [ ("1in", px, 300.0), ("2.54cm", px, 300.0), @@ -255,6 +266,40 @@ mod tests { } assert_eq!(parse("1in"), None, "without a field unit, unit names stay invalid"); } + #[test] + fn a_field_with_an_extent_converts_between_lengths_and_percent() { + use super::{Unit, Units, parse_with_units}; + // Free Transform's W at 300 ppi for a 600 px side (#6284): 100 % is 600 px, 2 in. + let pct = Units { unit: Some(Unit::Percent), suffix: "%", dpi: 300.0, ppi: 72.0, extent: Some(600.0) }; + let px = Units { unit: Some(Unit::Pixels), suffix: "px", ..pct }; + let inches = Units { unit: Some(Unit::Inches), suffix: "in", ..pct }; + for (text, units, want) in [ + ("300px", pct, 50.0), + ("1in", pct, 50.0), + ("2in*2", pct, 200.0), + ("2.54cm", pct, 50.0), + ("-1in", pct, -50.0), + ("50%", pct, 50.0), + ("50", pct, 50.0), + ("50%", px, 300.0), + ("50%+10", px, 310.0), + ("150%", inches, 3.0), + ("10%3", px, 1.0), + ] { + let got = parse_with_units(text, Some(units)); + assert!(got.is_some_and(|v| (v - want).abs() < 1e-9), "{text}: {got:?}, want {want}"); + } + // A degenerate or hostile extent can't convert, and never divides by zero. + for extent in [Some(0.0), Some(f64::NAN), Some(f64::INFINITY), None] { + assert_eq!(parse_with_units("1in", Some(Units { extent, ..pct })), None, "{extent:?}"); + assert_eq!(parse_with_units("50%", Some(Units { extent, ..px })), None, "{extent:?}"); + } + assert_eq!(parse_with_units("1e308in", Some(Units { extent: Some(1e-6), ..pct })), None, "an overflow is invalid"); + // Other percent fields (opacity, fill …) still reject a length. + let opacity = Units { extent: None, ..pct }; + assert_eq!(parse_with_units("40px", Some(opacity)), None); + assert_eq!(parse_with_units("2in", Some(opacity)), None); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/object_finder.rs b/crates/ui-egui/src/object_finder.rs index e219b0ddff..01fe50e502 100644 --- a/crates/ui-egui/src/object_finder.rs +++ b/crates/ui-egui/src/object_finder.rs @@ -78,7 +78,7 @@ pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: boo return Update::default(); }; let Some(st) = app.session.active() else { return Update::default() }; - let all_layers = app.ui.tool_options.sample_all_layers; + let all_layers = app.ui.tool_options.sample_all.object_selection; let target = sampled_target(&st.doc, st.active_layer, all_layers); let (doc, revision, layer) = (st.doc.id, st.revision, st.active_layer); let px = [at[0].floor() as i32, at[1].floor() as i32]; diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index a62ecafff3..f68c3e46e7 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -547,6 +547,7 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: &str) { if group.scrolls_itself(tab) { crate::panels::dock_body(app, ui, *group, tab); } else { + crate::panels::offer_color_field_fill(ui, pro, *group, tab); egui::ScrollArea::vertical() .id_salt(("shared-panel-body", id)) .auto_shrink([false, false]) diff --git a/crates/ui-egui/src/panel_docking_tests.rs b/crates/ui-egui/src/panel_docking_tests.rs index a4ae378eda..193ff2e6b8 100644 --- a/crates/ui-egui/src/panel_docking_tests.rs +++ b/crates/ui-egui/src/panel_docking_tests.rs @@ -585,6 +585,23 @@ fn explicit_reveal_activates_existing_tab_and_expands_custom_group() { assert_eq!(app.ui.docking, before); } +// #2455 in a custom workspace: the pro Color field fills a tall floating group, not 120 pt. +#[test] +fn pro_color_field_fills_a_tall_custom_group() { + let mut app = app(); + app.run("window.panel.float", json!({"panel":"color","x":40,"y":60,"width":320,"height":560})).unwrap(); + assert!(app.ui.docking.is_some()); + let h = harness(app, vec2(1280.0, 800.0)); + // The SV field and the 14 pt hue strip beside it are draggable, equally tall and 8 pt apart. + let drags: Vec = + h.ctx.viewport(|v| v.this_pass.widgets.layers().flat_map(|(_, w)| w).filter(|w| w.sense.senses_drag()).map(|w| w.rect).collect()); + let field = drags + .iter() + .find(|f| drags.iter().any(|s| s.width() == 14.0 && s.top() == f.top() && s.height() == f.height() && (s.left() - f.right() - 8.0).abs() < 0.5)) + .expect("Color field with its hue strip"); + assert!(field.height() > 300.0, "field stays short in a 560 pt group: {field:?}"); +} + // #4028: in a custom workspace too, a new adjustment layer brings Properties to the front. #[test] fn a_new_adjustment_layer_activates_properties_in_a_custom_workspace() { diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 4793554150..04e775439e 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -128,7 +128,8 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); let footer = (if t.pro { 8.0 } else { 14.0 }) + chips_height(t.pro, t.round_chips, t.round_chips && double) - + if t.pro { 8.0 + if double { bx } else { bx * 2.0 + 3.0 } } else { 0.0 } + + 8.0 + + if double { bx } else { bx * 2.0 + 3.0 } + 6.0; // As tall as the tools, so the colour chips sit right under them (Photoshop); a column // taller than the window scrolls and keeps the chips at the bottom. @@ -287,81 +288,79 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); } } - if t.pro && icons::button(ui, "ellipsis", bx, false, tl!("Edit Toolbar…")).clicked() { + if icons::button(ui, "ellipsis", bx, false, tl!("Edit Toolbar…")).clicked() { let _ = crate::menus::invoke(app, &ctx, "edit.toolbar", json!({})); } reveal_focused_control(ui); }); ui.add_space(if t.pro { 8.0 } else { 14.0 }); color_chips(app, ui, double); - if t.pro { - ui.add_space(8.0); + ui.add_space(8.0); - let layout = if double { egui::Layout::left_to_right(egui::Align::Min) } else { egui::Layout::top_down(egui::Align::Min) }; + let layout = if double { egui::Layout::left_to_right(egui::Align::Min) } else { egui::Layout::top_down(egui::Align::Min) }; - ui.with_layout(layout, |ui| { - let quick_mask = app.session.active().is_some_and(|s| s.doc.quick_mask.is_some()); - if icons::button_with_icon_size_tip( - ui, - "square-dashed", - bx, - (bx * 0.52).round(), - quick_mask, - if quick_mask { tl!("Edit in Standard Mode (Q)") } else { tl!("Edit in Quick Mask Mode (Q)") }, - tool_tips, - ) - .clicked() - { - let _ = crate::menus::invoke(app, &ctx, "select.editInQuickMaskMode", json!({})); - } - let sm = icons::button_with_icon_size_tip(ui, "app-window", bx, (bx * 0.52).round(), false, tl!("Change Screen Mode (F)"), tool_tips); - paint_toolbar_flyout_indicator(ui, &t, &sm); + ui.with_layout(layout, |ui| { + let quick_mask = app.session.active().is_some_and(|s| s.doc.quick_mask.is_some()); + if icons::button_with_icon_size_tip( + ui, + "square-dashed", + bx, + (bx * 0.52).round(), + quick_mask, + if quick_mask { tl!("Edit in Standard Mode (Q)") } else { tl!("Edit in Quick Mask Mode (Q)") }, + tool_tips, + ) + .clicked() + { + let _ = crate::menus::invoke(app, &ctx, "select.editInQuickMaskMode", json!({})); + } + let sm = icons::button_with_icon_size_tip(ui, "app-window", bx, (bx * 0.52).round(), false, tl!("Change Screen Mode (F)"), tool_tips); + paint_toolbar_flyout_indicator(ui, &t, &sm); - // Right-click, or click and hold like the tool flyouts (#4444), lists the modes, - // like Photoshop's flyout. The release that ends a hold doesn't cycle the mode. - let held_id = sm.id.with("held"); - let was_held = ui.data(|d| d.get_temp::(held_id)).unwrap_or(false); - let held_for = sm.is_pointer_button_down_on().then(|| ui.input(|i| i.pointer.press_start_time().map(|t0| i.time - t0))).flatten(); - if let Some(seconds) = held_for - && seconds < 0.35 - { - ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds)); - } - let long_press = !was_held && held_for.is_some_and(|seconds| seconds >= 0.35); - if long_press { - ui.data_mut(|d| d.insert_temp(held_id, true)); - } else if was_held && !sm.is_pointer_button_down_on() { - ui.data_mut(|d| d.remove::(held_id)); - } - let cycle = sm.clicked() && !was_held; - if cycle { - let _ = crate::menus::invoke(app, &ctx, "view.screenMode.cycle", json!({})); - } - let open = if sm.secondary_clicked() || long_press { - Some(egui::SetOpenCommand::Bool(true)) - } else if cycle { - Some(egui::SetOpenCommand::Bool(false)) - } else { - None - }; - // The release ending the hold counts as a click; it mustn't close the list it opened. - let close = if was_held || long_press { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClick }; - egui::Popup::menu(&sm).open_memory(open).close_behavior(close).at_pointer_fixed().show(|ui| { - ui.set_min_width(220.0); - for (id, label) in [ - ("view.screenMode.standard", tl!("Standard Screen Mode")), - ("view.screenMode.fullScreenWithMenuBar", tl!("Full Screen Mode With Menu Bar")), - ("view.screenMode.fullScreen", tl!("Full Screen Mode")), - ] { - let on = crate::view_cmds::checked(app, id).unwrap_or(false); - if ui.add(egui::Button::selectable(on, label)).clicked() { - let _ = crate::menus::invoke(app, &ctx, id, json!({})); - ui.close(); - } + // Right-click, or click and hold like the tool flyouts (#4444), lists the modes, + // like Photoshop's flyout. The release that ends a hold doesn't cycle the mode. + let held_id = sm.id.with("held"); + let was_held = ui.data(|d| d.get_temp::(held_id)).unwrap_or(false); + let held_for = sm.is_pointer_button_down_on().then(|| ui.input(|i| i.pointer.press_start_time().map(|t0| i.time - t0))).flatten(); + if let Some(seconds) = held_for + && seconds < 0.35 + { + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds)); + } + let long_press = !was_held && held_for.is_some_and(|seconds| seconds >= 0.35); + if long_press { + ui.data_mut(|d| d.insert_temp(held_id, true)); + } else if was_held && !sm.is_pointer_button_down_on() { + ui.data_mut(|d| d.remove::(held_id)); + } + let cycle = sm.clicked() && !was_held; + if cycle { + let _ = crate::menus::invoke(app, &ctx, "view.screenMode.cycle", json!({})); + } + let open = if sm.secondary_clicked() || long_press { + Some(egui::SetOpenCommand::Bool(true)) + } else if cycle { + Some(egui::SetOpenCommand::Bool(false)) + } else { + None + }; + // The release ending the hold counts as a click; it mustn't close the list it opened. + let close = if was_held || long_press { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClick }; + egui::Popup::menu(&sm).open_memory(open).close_behavior(close).at_pointer_fixed().show(|ui| { + ui.set_min_width(220.0); + for (id, label) in [ + ("view.screenMode.standard", tl!("Standard Screen Mode")), + ("view.screenMode.fullScreenWithMenuBar", tl!("Full Screen Mode With Menu Bar")), + ("view.screenMode.fullScreen", tl!("Full Screen Mode")), + ] { + let on = crate::view_cmds::checked(app, id).unwrap_or(false); + if ui.add(egui::Button::selectable(on, label)).clicked() { + let _ = crate::menus::invoke(app, &ctx, id, json!({})); + ui.close(); } - }); + } }); - } + }); }); } @@ -602,7 +601,14 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let max = ui.ctx().input(|i| i.viewport().maximized.unwrap_or(false)); ui.ctx().send_viewport_cmd(egui::ViewportCommand::Maximized(!max)); } - let title = app.session.active().map(|d| format!("{}{}", d.doc.name, if d.is_dirty() { " •" } else { "" })).unwrap_or_else(|| "PhotoCraft".into()); + // Preferences › Interface › Show File Name In Title: with it off the bar keeps the + // app name and the unsaved dot, since the tabs already name the file (#5037). + let show_name = app.session.prefs().interface.show_file_name_in_title; + let title = app + .session + .active() + .map(|d| format!("{}{}", if show_name { d.doc.name.as_str() } else { "PhotoCraft" }, if d.is_dirty() { " •" } else { "" })) + .unwrap_or_else(|| "PhotoCraft".into()); // The menus and the far-end controls are laid out first; the title is centred in // whatever room is left between them (`free`, left to right: menus then controls, or // controls then menus in a right-to-left UI), shortened or dropped rather than drawn @@ -694,6 +700,9 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if system { return; } + // A right-to-left document name in display order (the OS title keeps the logical text), + // in a left-to-right line: "— PhotoCraft" stays after the name, at the right. + let title = crate::bidi_text::visual_ltr(&title).into_owned(); let font = theme::medium(13.0); let galley = ui.painter().layout_no_wrap(title.clone(), font.clone(), t.text_dim); if let Some(x) = title_x(full.center().x, free.0, free.1, galley.size().x) { @@ -725,8 +734,12 @@ pub fn system_title_bar(app: &PhotocraftApp) -> bool { /// The OS window title: the active document's name suffixed with the app name (a `*` prefix /// marks unsaved changes, like the `•` in the app-drawn title), or just the app name with no -/// document open. +/// document open. With Preferences › Interface › Show File Name In Title off, the file name +/// drops out and only the app name (and the `*`) remains (#5037). pub fn window_title(app: &PhotocraftApp) -> String { + if !app.session.prefs().interface.show_file_name_in_title { + return format!("{}PhotoCraft", if app.session.active().is_some_and(|d| d.is_dirty()) { "*" } else { "" }); + } app.session.active().map(|d| format!("{}{} \u{2014} PhotoCraft", if d.is_dirty() { "*" } else { "" }, d.doc.name)).unwrap_or_else(|| "PhotoCraft".into()) } @@ -817,6 +830,40 @@ mod title_tests { assert_eq!(window_title(&app), "*foo.psd \u{2014} PhotoCraft"); } + #[test] + fn hiding_the_file_name_keeps_the_app_name_and_the_dirty_mark() { + let mut app = app(true); + open_named(&mut app, "foo.psd"); + app.session.prefs.edit(|p| p.interface.show_file_name_in_title = false); + assert_eq!(window_title(&app), "PhotoCraft"); + if let Some(st) = app.session.active_mut() { + st.revision += 1; + } + assert_eq!(window_title(&app), "*PhotoCraft"); + } + + #[test] + fn hidden_file_name_leaves_the_app_name_in_the_drawn_title() { + let mut app = app(true); + open_named(&mut app, "foo.psd"); + let texts = |app: &mut crate::PhotocraftApp| { + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::title_bar(app, ui)); + out.textures_delta.clear(); + let mut texts = Vec::new(); + for shape in &out.shapes { + collect_text(&shape.shape, &mut texts); + } + texts + }; + assert!(texts(&mut app).iter().any(|t| t.contains("foo.psd")), "shown by default"); + app.session.prefs.edit(|p| p.interface.show_file_name_in_title = false); + let hidden = texts(&mut app); + assert!(!hidden.iter().any(|t| t.contains("foo.psd")), "file name hidden: {hidden:?}"); + assert!(hidden.iter().any(|t| t.contains("PhotoCraft")), "app name kept: {hidden:?}"); + } + #[test] fn system_mode_hides_the_mark_and_the_centred_title() { for custom in [true, false] { @@ -1193,7 +1240,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); - widgets::checkbox(ui, &mut app.ui.tool_options.sample_all_layers, tl!("Sample All Layers")); + widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.magic_wand, tl!("Sample All Layers")); widgets::vline(ui, 22.0); if widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() { let r = app.run("select.subject", json!({})); @@ -1215,7 +1262,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); - widgets::checkbox(ui, &mut app.ui.tool_options.sample_all_layers, tl!("All Layers")); + widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.paint_bucket, tl!("All Layers")); } Tool::Gradient => { // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels). @@ -1279,9 +1326,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Keep partial edits in ToolOptions so the first side survives a frame; // Original Ratio shows the document's numbers, as Photoshop does. let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size); - let cw = widgets::value_field(ui, &mut rw, 0.0..=99_999.0, "", 54.0).changed(); + let decimals = crate::crop_size::RATIO_DECIMALS; + let cw = widgets::value_field_prec(ui, &mut rw, 0.0..=99_999.0, "", 54.0, decimals).changed(); let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked(); - let ch = widgets::value_field(ui, &mut rh, 0.0..=99_999.0, "", 54.0).changed(); + let ch = widgets::value_field_prec(ui, &mut rh, 0.0..=99_999.0, "", 54.0, decimals).changed(); if swap { std::mem::swap(&mut rw, &mut rh); } @@ -1935,20 +1983,51 @@ fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.painter().image(tex, rect, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); } let s = rect.width() / size.width.max(1) as f32; - if (resp.clicked() || resp.dragged()) + // ⌘/Ctrl-drag over the preview draws a rectangle the view then zooms to, as in Photoshop + // (#6872); a plain click or drag moves the view. + let command = crate::workspace_ui::sticky_mods(app, ctx.input(|i| i.modifiers)).command; + if resp.drag_started() && command { + let start = ctx.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()); + ui.data_mut(|d| match start { + Some(p) => { + d.insert_temp(navigator_zoom_drag_id(), p); + } + None => d.remove::(navigator_zoom_drag_id()), + }); + } + let zoom_from = ui.data(|d| d.get_temp::(navigator_zoom_drag_id())); + if let Some(from) = zoom_from { + if let Some(to) = resp.interact_pointer_pos() { + let r = Rect::from_two_pos(from, to).intersect(rect); + crate::tool_feedback::draw_ants(ui.painter(), &[r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()], true); + if resp.drag_stopped() { + let doc_rect = Rect::from_min_max(((r.min - rect.min) / s).to_pos2(), ((r.max - rect.min) / s).to_pos2()); + let (canvas, ppp, aspect) = (app.last_canvas_rect, app.canvas_ppp(), app.ui.view.display_aspect()); + navigator_zoom_to(&mut app.ui.views[idx], doc_rect, [size.width, size.height], canvas.size(), ppp, aspect); + } + } + if resp.drag_stopped() || !resp.dragged() { + ui.data_mut(|d| d.remove::(navigator_zoom_drag_id())); + } + } else if (resp.clicked() || resp.dragged()) && let Some(pp) = resp.interact_pointer_pos() { let d = (pp - rect.min) / s; app.ui.views[idx].center = [d.x.clamp(0.0, size.width as f32), d.y.clamp(0.0, size.height as f32)]; app.ui.views[idx].fit_pending = false; } + if command && resp.hovered() { + ctx.set_cursor_icon(egui::CursorIcon::ZoomIn); + } // The Navigator has its own zoom target: an unmodified wheel over the preview // should zoom even when the document canvas is configured to scroll on wheel. // Use the canvas wheel classifier to honour one ×1.1 step per notch without // applying egui's smoothed wheel tail a second time. let pinch_zooms = app.session.prefs().enhanced_controls.zoom_with_trackpad_pinch; + let touch_gestures = app.session.prefs().enhanced_controls.touch_gestures; if resp.hovered() - && let Some(crate::wheel_nav::Wheel::Zoom(factor)) = crate::wheel_nav::read(&ctx, true, pinch_zooms, egui::Id::new("pc-navigator-wheel"), true) + && let Some(crate::wheel_nav::Wheel::Zoom(factor)) = + crate::wheel_nav::read_with(&ctx, true, pinch_zooms, egui::Id::new("pc-navigator-wheel"), true, true, touch_gestures) { let view = &mut app.ui.views[idx]; let next = crate::zoom_levels::clamp(view.zoom * factor, view.doc_size); @@ -2020,6 +2099,42 @@ fn navigator_fit(frame: Rect, w: u32, h: u32) -> Rect { Rect::from_center_size(frame.center(), vec2(w * s, h * s)) } +/// Where a ⌘/Ctrl-drag over the Navigator's preview started, while it lasts. +fn navigator_zoom_drag_id() -> egui::Id { + egui::Id::new("navigator-zoom-drag") +} + +/// Zoom `view` so the document rectangle `doc_rect` (pixels) fills a canvas of `canvas` points, +/// centred on it, as a Navigator ⌘/Ctrl-drag does (#6872). `doc` is the document's size in +/// pixels (the view's own copy is only set once the canvas has been drawn), `ppp` the canvas's +/// device pixels per point and `aspect` the pixel aspect ratio shown; the zoom stays within the +/// zoom range. A rectangle under 2 document pixels across zooms one step in on its centre. +fn navigator_zoom_to(view: &mut crate::state::View, doc_rect: Rect, doc: [u32; 2], canvas: egui::Vec2, ppp: f32, aspect: f32) { + // Checked before clipping: `min`/`max` would turn a NaN edge into a document edge. + if ![doc_rect.min.x, doc_rect.min.y, doc_rect.max.x, doc_rect.max.y].iter().all(|v| v.is_finite()) { + return; + } + let (w, h) = (doc[0] as f32, doc[1] as f32); + let r = doc_rect.intersect(Rect::from_min_size(Pos2::ZERO, vec2(w, h))); + if r.width() < 0.0 || r.height() < 0.0 { + return; + } + let aspect = if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; + let zoom = if r.width() < 2.0 || r.height() < 2.0 || canvas.x <= 0.0 || canvas.y <= 0.0 { + crate::zoom_levels::step(view.zoom, 1, view.doc_size) + } else { + // Document columns shown across the canvas are `canvas.x / (point_zoom * aspect)`. + let point_zoom = (canvas.x / (r.width() * aspect)).min(canvas.y / r.height()); + point_zoom * ppp + }; + if !zoom.is_finite() { + return; + } + view.zoom = crate::zoom_levels::clamp(zoom, view.doc_size); + view.center = [r.center().x, r.center().y]; + view.fit_pending = false; +} + fn navigator_preview_id() -> egui::Id { egui::Id::new("navigator-preview-rect") } @@ -2082,6 +2197,101 @@ mod navigator_wheel_tests { assert!((app.ui.views[0].zoom - 1.0).abs() < 1e-4, "wheel outside preview leaves zoom unchanged"); } + /// #6872: the zoom a Navigator ⌘/Ctrl-drag sets: the rectangle fills the canvas, centred. + #[test] + fn navigator_zoom_to_fits_the_rectangle_in_the_canvas() { + let fresh = || crate::state::View { doc_size: [200, 100], zoom: 1.0, center: [100.0, 50.0], ..Default::default() }; + let canvas = vec2(800.0, 600.0); + let r = Rect::from_min_max(pos2(50.0, 25.0), pos2(100.0, 50.0)); + // 50 × 25 px on 800 × 600 pt: the width limits it, 16 points per pixel. + let mut v = fresh(); + navigator_zoom_to(&mut v, r, [200, 100], canvas, 1.0, 1.0); + assert_eq!((v.zoom, v.center, v.fit_pending), (crate::zoom_levels::clamp(16.0, [200, 100]), [75.0, 37.5], false)); + // Device pixels per point and a 2:1 pixel aspect scale it as the canvas shows pixels. + let mut v = fresh(); + navigator_zoom_to(&mut v, r, [200, 100], canvas, 2.0, 2.0); + assert_eq!(v.zoom, crate::zoom_levels::clamp(16.0, [200, 100]), "8 points per pixel across, at 2 device pixels per point"); + // Off the document: only the part on it counts. + let mut v = fresh(); + navigator_zoom_to(&mut v, Rect::from_min_max(pos2(150.0, 50.0), pos2(400.0, 300.0)), [200, 100], canvas, 1.0, 1.0); + assert_eq!(v.center, [175.0, 75.0]); + // Under 2 px across: one step in on its centre. + let mut v = fresh(); + navigator_zoom_to(&mut v, Rect::from_min_max(pos2(10.0, 10.0), pos2(11.0, 40.0)), [200, 100], canvas, 1.0, 1.0); + assert_eq!((v.zoom, v.center), (crate::zoom_levels::step(1.0, 1, [200, 100]), [10.5, 25.0])); + // Not a number, or wholly off the document: nothing changes. + for bad in [Rect::from_min_max(pos2(f32::NAN, 0.0), pos2(10.0, 10.0)), Rect::from_min_max(pos2(300.0, 300.0), pos2(400.0, 400.0))] { + let mut v = fresh(); + navigator_zoom_to(&mut v, bad, [200, 100], canvas, 1.0, 1.0); + assert_eq!((v.zoom, v.center), (1.0, [100.0, 50.0]), "{bad:?}"); + } + } + + /// One frame of the Navigator with pointer `events` and `modifiers` held. + fn frame_with(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Modifiers, mut events: Vec) { + events.insert(0, Event::ModifiersChanged(modifiers)); + let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(430.0, 460.0))), events, ..Default::default() }; + ctx.run_ui(input, |ui| navigator(app, ui)).textures_delta.clear(); + } + + /// A drag over the Navigator's preview between document points `from` and `to`. + fn drag(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Modifiers, from: [f32; 2], to: [f32; 2]) { + let preview = last_navigator_preview(ctx).expect("the preview"); + let s = preview.width() / 200.0; + let at = |p: [f32; 2]| preview.min + vec2(p[0], p[1]) * s; + let (a, b) = (at(from), at(to)); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_with(app, ctx, modifiers, vec![Event::PointerMoved(a), button(a, true)]); + frame_with(app, ctx, modifiers, vec![Event::PointerMoved(a.lerp(b, 0.5))]); + frame_with(app, ctx, modifiers, vec![Event::PointerMoved(b)]); + frame_with(app, ctx, modifiers, vec![button(b, false)]); + frame_with(app, ctx, Modifiers::NONE, vec![]); + } + + /// #6872: ⌘/Ctrl-dragging a rectangle over the preview zooms the view to it, as in + /// Photoshop; a plain drag still only moves the view. + #[test] + fn navigator_command_drag_zooms_to_the_rectangle() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + // The preview settles once the zoom row under it has been measured. + for _ in 0..3 { + frame(&mut app, &ctx, pos2(5.0, 5.0), 0.0); + } + // A plain drag pans and keeps the zoom. + drag(&mut app, &ctx, Modifiers::NONE, [50.0, 25.0], [100.0, 50.0]); + assert_eq!(app.ui.views[0].zoom, 1.0); + let c = app.ui.views[0].center; + assert!((c[0] - 100.0).abs() < 1.0 && (c[1] - 50.0).abs() < 1.0, "the view follows the pointer: {c:?}"); + // ⌘/Ctrl-drag: the rectangle fills the canvas (`last_canvas_rect`, 800 × 600 pt). + drag(&mut app, &ctx, Modifiers::COMMAND, [50.0, 25.0], [100.0, 50.0]); + let mut expected = app.ui.views[0].clone(); + navigator_zoom_to( + &mut expected, + Rect::from_min_max(pos2(50.0, 25.0), pos2(100.0, 50.0)), + [200, 100], + vec2(800.0, 600.0), + app.canvas_ppp(), + app.ui.view.display_aspect(), + ); + let v = &app.ui.views[0]; + assert!((v.zoom - expected.zoom).abs() / expected.zoom < 0.05, "{} vs {}", v.zoom, expected.zoom); + assert!( + (v.center[0] - 75.0).abs() < 1.0 && (v.center[1] - 37.5).abs() < 1.0, + "centred on the rectangle: {:?} (zoom {}, expected {:?})", + v.center, + v.zoom, + (expected.zoom, expected.center) + ); + assert!(v.zoom > 1.0 && !v.fit_pending); + assert!(ctx.data(|d| d.get_temp::(navigator_zoom_drag_id())).is_none(), "the drag is over"); + } + /// #4840: under the preview, one row as in Photoshop: the zoom in percent, Zoom Out, the /// slider and Zoom In. The buttons step the zoom like View › Zoom In / Out. #[test] @@ -2606,10 +2816,12 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.dock.collapsed.retain(|g| *g != crate::dock::Group::Properties); continue; } - if p.is_null() { - // Context-menu items behave like their menu-bar twins (dialogs included). + if p.is_null() || id == "layer.newFillLayer.solidColor" { + // Context-menu items and the Layers footer's Solid Color… action behave like + // their menu-bar twins. In particular, a new Solid Color fill opens its picker. let ctx = ui.ctx().clone(); - if let Err(e) = crate::menus::invoke(app, &ctx, &id, json!({})) { + let params = if p.is_null() { json!({}) } else { p }; + if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) { app.ui.status = e; app.ui.status_error = true; } @@ -2931,7 +3143,9 @@ fn layer_row( if let Some(kind) = masks.hit(p) { return Some(crate::mask_thumbs_ui::load_params(l, kind, m)); } - thumb.expand(2.0).contains(p).then(|| json!({"channel": "transparency", "layer": l.id.0, "operation": crate::channels_panel::load_operation(m)})) + // The Background has no transparency to load: Photoshop treats the click as a plain one. + (!doc.is_background(l.id) && thumb.expand(2.0).contains(p)) + .then(|| json!({"channel": "transparency", "layer": l.id.0, "operation": crate::channels_panel::load_operation(m)})) }); // ⇧-click a mask thumbnail: disable / enable that mask; ⌥-click a layer mask: view it. let mask_toggle = resp.clicked().then(|| (ui.input(|i| i.modifiers), resp.interact_pointer_pos())).and_then(|(m, pos)| { @@ -2943,14 +3157,17 @@ fn layer_row( } else if let Some(cmd) = mask_toggle { actions.push(cmd); } else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked { - let mode = select_mode(ui.input(|i| i.modifiers)); + let m = ui.input(|i| i.modifiers); + let pos = resp.interact_pointer_pos(); + let on_thumb = pos.is_some_and(|p| thumb.expand(2.0).contains(p)); + // ⌘-click on the Background thumbnail stands in for the plain click (there is no + // transparency to load): it selects the Background alone, not toggled into the set. + let mode = if m.command && on_thumb && doc.is_background(l.id) { "replace" } else { select_mode(m) }; actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode}))); crate::smart_ui::deselect(ctx, doc.id); // A thumbnail explicitly selects content or a mask. Selecting an adjustment/fill row // defaults to its mask, but clicking its content thumbnail must leave the mask target. - let pos = resp.interact_pointer_pos(); let on_mask = mask_rect.zip(pos).is_some_and(|(r, p)| r.expand(2.0).contains(p)); - let on_thumb = pos.is_some_and(|p| thumb.expand(2.0).contains(p)); let on_vector = pos.and_then(|p| masks.hit(p)) == Some(crate::mask_thumbs_ui::MaskKind::Vector); // Clicking the layer thumbnail leaves mask view (#196). let viewing = app.session.active().and_then(photocraft_engine::mask_view_cmds::current).is_some_and(|v| v.layer == l.id); @@ -2973,7 +3190,6 @@ fn layer_row( actions.push(("ui.maskTarget".into(), json!(false))); } // ⌥-click the layer thumbnail: fit the layer on screen, as Photoshop does. - let m = ui.input(|i| i.modifiers); if on_thumb && m.alt && !m.shift && !m.command { actions.push(("view.fitLayersOnScreen".into(), Value::Null)); } @@ -3628,10 +3844,19 @@ fn field_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui, chips: Rect) { } /// Where the dock tells the Color field how tall its group body is. -pub(crate) fn color_field_fill_id() -> egui::Id { +fn color_field_fill_id() -> egui::Id { egui::Id::new("color-field-fill-height") } +/// The pro Color field stretches to its dock group's height instead of a fixed 120 pt: a dock +/// calls this with the group body's `ui` before drawing the tab. +pub(crate) fn offer_color_field_fill(ui: &egui::Ui, pro: bool, group: crate::dock::Group, tab: usize) { + if pro && group == crate::dock::Group::Color && tab == 0 { + let inner = ui.available_height().max(0.0); + ui.data_mut(|d| d.insert_temp(color_field_fill_id(), inner)); + } +} + /// Height of the Color field: the group body's height (when docked) less the hex/RGB readout, /// which folds onto a second line in a narrow dock. 120 pt when nothing sets a height. fn color_field_height(avail: Option, width: f32) -> f32 { @@ -5584,6 +5809,27 @@ mod toolbar_tests { } } + /// #4653: every theme draws Edit Toolbar, Quick Mask and Screen Mode, not only Pro. + #[test] + fn every_theme_has_the_toolbar_controls() { + for kind in crate::theme::ThemeKind::ALL { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = egui_kittest::Harness::builder().with_size(vec2(800.0, 1400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + toolbar(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(2); + for label in ["Edit Toolbar…", "Edit in Quick Mask Mode (Q)", "Change Screen Mode (F)"] { + assert!(h.query_by_label(label).is_some(), "{kind:?}: no {label:?} button"); + } + } + } + fn click(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, p: egui::Pos2) { h.hover_at(p); h.run_steps(1); @@ -5954,6 +6200,10 @@ mod compact_visual_regressions { phase: egui::TouchPhase::Move, }); harness.run_steps(30); + // Off the toolbar, so a tooltip of the tool scrolled under the pointer isn't a + // second "Zoom Tool" node. + harness.event(egui::Event::PointerMoved(pos2(300.0, 100.0))); + harness.run_steps(2); let node = harness.get_by_label("Zoom Tool (Z)"); let rect = node.rect(); assert!(rect.top() >= 0.0 && rect.bottom() <= 360.0, "{kind:?} at {scale}x: last tool remains outside the toolbar: {rect:?}"); @@ -5991,13 +6241,13 @@ mod compact_visual_regressions { } } - /// A window taller than the tools keeps the colour chips right under the last tool, as - /// Photoshop does, instead of at the bottom of the toolbar. + /// A window taller than the tools keeps the colour chips right under the tool column (its + /// last row is Edit Toolbar), as Photoshop does, instead of at the bottom of the toolbar. #[test] fn tall_toolbar_keeps_the_colour_chips_under_the_tools() { for kind in theme::ThemeKind::ALL { let harness = toolbar_harness_sized(kind, 1.0, 1600.0); - let last = harness.get_by_label("Zoom Tool (Z)").rect(); + let last = harness.get_by_label("Edit Toolbar…").rect(); let swap = harness.get_by_label("Swap colours (X)").rect(); assert!(swap.top() - last.bottom() < 80.0, "{kind:?}: the chips {swap:?} sit far below the last tool {last:?}"); } @@ -6217,6 +6467,40 @@ mod compact_visual_regressions { } } + #[test] + fn the_crop_ratio_fields_show_three_decimals() { + // #6487: a 1.414 : 1 ratio reads 1.414 in the bar, not 1.4. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let Some(kind) = crate::theme::ThemeKind::ALL.into_iter().find(|k| { + crate::theme::apply(&ctx, *k); + Tokens::get(&ctx).pro + }) else { + return; + }; + crate::theme::apply(&ctx, kind); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_ratio = "1.414:1".into(); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0)); + let mut out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| options_bar(&mut app, ui)); + for _ in 0..3 { + out.textures_delta.clear(); + out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| options_bar(&mut app, ui)); + } + out.textures_delta.clear(); + let texts: Vec<&str> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(t.galley.job.text.as_str()), + _ => None, + }) + .collect(); + assert!(texts.contains(&"1.414"), "{texts:?}"); + assert_eq!(app.ui.tool_options.crop_ratio, "1.414:1", "showing the ratio leaves it alone"); + } + #[test] fn the_narrow_options_bar_preference_shortens_the_bar() { assert_eq!(options_bar_height(true, false), 36.0); diff --git a/crates/ui-egui/src/pen_draw_tests.rs b/crates/ui-egui/src/pen_draw_tests.rs index 155450eac6..57be940bd6 100644 --- a/crates/ui-egui/src/pen_draw_tests.rs +++ b/crates/ui-egui/src/pen_draw_tests.rs @@ -219,3 +219,59 @@ fn delete_with_the_pen_deletes_the_finished_work_path_not_the_pixels() { h.run_steps(2); assert!(work(&h), "another tool's Delete is Edit › Clear, not Delete Path"); } + +fn space(h: &mut Harness<'static, PhotocraftApp>, down: bool) { + h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: down, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +/// Did the last frame paint the Pen's path in progress: an accent polyline starting at `at`, its +/// first anchor on screen (`vector_ui::draw_overlay`)? +fn pen_path_painted(h: &Harness<'static, PhotocraftApp>, at: Pos2) -> bool { + let accent = crate::theme::Tokens::get(&h.ctx).accent; + h.output().shapes.iter().any(|c| match &c.shape { + egui::Shape::Path(p) => { + p.stroke.width == 1.5 + && matches!(p.stroke.color, egui::epaint::ColorMode::Solid(col) if col == accent) + && p.points.len() >= 2 + && p.points[0].distance(at) < 1.0 + } + _ => false, + }) +} + +/// #6592: holding Space to pan with the Hand keeps the Pen's path in progress, and shows it, as in +/// Photoshop. +#[test] +fn space_pan_keeps_the_pen_path_in_progress_visible() { + let mut h = harness(); + click(&mut h, [20.0, 20.0]); + click(&mut h, [100.0, 20.0]); + assert_eq!(h.state().ui.pen.as_ref().map(|p| p.knots.len()), Some(2)); + let p = screen(&h, [150.0, 100.0]); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + assert!(pen_path_painted(&h, screen(&h, [20.0, 20.0])), "drawn before Space"); + space(&mut h, true); + assert!(pen_path_painted(&h, screen(&h, [20.0, 20.0])), "drawn with Space held, before the drag"); + let c0 = h.state().ui.views[0].center; + button(&mut h, p, true, Modifiers::NONE); + for i in 1..=5 { + // A pan frame paints the image and its overlays with the view it started with. + let first = screen(&h, [20.0, 20.0]); + h.event(egui::Event::PointerMoved(p + vec2(10.0 * i as f32, 0.0))); + h.run_steps(1); + let pen = h.state().ui.pen.as_ref().map(|p| p.knots.len()); + let painted = pen_path_painted(&h, first); + assert_eq!(pen, Some(2), "the path in progress is kept while panning (step {i})"); + assert!(painted, "the path in progress is drawn while panning (step {i})"); + } + button(&mut h, p + vec2(50.0, 0.0), false, Modifiers::NONE); + space(&mut h, false); + h.run_steps(1); + let c1 = h.state().ui.views[0].center; + assert!((c1[0] - (c0[0] - 50.0)).abs() < 0.5, "Space-drag panned: {c0:?} -> {c1:?}"); + assert_eq!(h.state().ui.tool, Tool::Pen); + assert_eq!(h.state().ui.pen.as_ref().map(|p| p.knots.len()), Some(2), "the path in progress survives the pan"); + assert!(pen_path_painted(&h, screen(&h, [20.0, 20.0])), "drawn after the pan"); +} diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index e9282e44c1..d808ae32f4 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -233,11 +233,15 @@ pub fn load(app: &mut PhotocraftApp) { return; } app.prefs_rt.loaded = true; - if let Some(text) = app.services.load_prefs.as_mut().and_then(|f| f()) - && let Err(e) = app.session.load_prefs_json(&text) - { - let template = "Preferences were reset: {error}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); + let mut invalid = Vec::new(); + if let Some(text) = app.services.load_prefs.as_mut().and_then(|f| f()) { + match app.session.load_prefs_json(&text) { + Ok(found) => invalid = found, + Err(e) => { + let template = "Preferences were reset: {error}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); + } + } } crate::dock::restore(app); crate::brush_picker::restore(app); @@ -248,6 +252,37 @@ pub fn load(app: &mut PhotocraftApp) { app.sync_recent(); app.prefs_rt.saved_rev = app.session.prefs.rev(); app.prefs_rt.saved_value = Some(app.session.prefs_value()); + if !invalid.is_empty() { + repair_invalid(app, &invalid); + } +} + +/// Some saved values couldn't be read and took their defaults (#6611): say which, and write +/// the defaults over them on the next save so the next launch reads a clean file. The save +/// base holds the unreadable values, so the three-way merge sees them as changed here and +/// replaces (or removes) exactly those, keeping everything else in the stored file. +fn repair_invalid(app: &mut PhotocraftApp, invalid: &[prefs::InvalidPref]) { + if let Some(base) = app.prefs_rt.saved_value.as_mut() { + for bad in invalid { + let Some((key, parent)) = bad.keys.split_last() else { + continue; + }; + if let Some(obj) = parent.iter().try_fold(&mut *base, |cur, k| cur.get_mut(k.as_str())).and_then(Value::as_object_mut) { + obj.insert(key.clone(), bad.value.clone()); + } + } + } + app.session.prefs.edit(|_| ()); + let paths = invalid.iter().map(prefs::InvalidPref::path).collect::>().join(", "); + let (title, line) = ( + "Some preferences were reset", + "The preferences file held values PhotoCraft can't read for {paths}. Those settings are back to their defaults; the rest of your preferences loaded.", + ); + // Notices keep their English source and are translated when drawn. + let id = crate::notices::post(app, title, vec![line.into()], false, None); + if let Some(notice) = app.ui.notices.iter_mut().find(|n| n.id == id) { + notice.args.push(("paths".into(), paths)); + } } /// Discover recovery entries after construction, then decode one at a time without blocking @@ -907,26 +942,16 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V } dialog(d) } - "edit.contentAwareFill" => { - if !app.session.is_enabled(id) { - return Some(Err("Content-Aware Fill needs a selection on a pixel layer".into())); - } - let d = crate::filter_dialog::open(app, id); - if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) { - dm.fields.insert("__preview".into(), json!(true)); - for k in ["margin", "seed", "channel"] { - dm.fields.remove(k); - } - } - dialog(d) - } + // Photoshop's Content-Aware Fill workspace (caf_ui); the engine command with params + // still runs directly. + "edit.contentAwareFill" => Some(crate::caf_ui::open(app).map(|_| json!({"contentAwareFill": app.distort.describe()["contentAwareFill"]}))), // Photoshop has no dialog: the menu opens the scale box (with params: the engine). crate::cas_transform::COMMAND => Some(crate::cas_transform::begin(app, ctx)), "edit.presets.presetManager" => { Some(Ok(json!({"dialog": open_kind(app, "presets", "Preset Manager", json!({"kind": "brushes", "selected": 0, "newName": ""}))}))) } "edit.presets.exportImportPresets" => Some(Ok( - json!({"dialog": open_kind(app, "presetsIO", "Export/Import Presets", json!({"action": "export", "brushes": true, "customShapes": true}))}), + json!({"dialog": open_kind(app, "presetsIO", "Export/Import Presets", json!({"action": "export", "brushes": true, "customShapes": true, "tools": true}))}), )), _ => None, } @@ -978,10 +1003,22 @@ pub fn apply(app: &mut PhotocraftApp, id: u64) -> Result { Ok(result) } -/// Max dialog width for our dialogs. +/// The size Preferences opens at: room for the widest section and about 30 settings rows. The +/// dialog's resize grip changes it, and its contents follow (#7420). +pub const PREFERENCES_SIZE: egui::Vec2 = egui::vec2(1040.0, 800.0); + +/// The height of the settings area (section list and fields) when `available` is left below the +/// search field: everything but the dialog's button row (`item_spacing` + 8 pt + the buttons) and +/// a little slack, never less than a few rows. +fn settings_height(available: f32, item_spacing: f32, button_height: f32) -> f32 { + (available - (item_spacing + 8.0 + button_height + 4.0)).max(160.0) +} + +/// Max dialog width for our dialogs. Preferences fills the width it is given (`available`, its +/// resizable area). pub fn width(fields: &Map, available: f32) -> Option { match fields.get("__prefsui").and_then(Value::as_str)? { - "prefs" => Some(available.clamp(380.0, 1040.0)), + "prefs" => Some(available.max(380.0)), "shortcuts" => Some(720.0), _ => Some(460.0), } @@ -1256,7 +1293,10 @@ fn prefs_body(ui: &mut egui::Ui, f: &mut Map, system: Option, k: &str, query: &str) let drawn_elsewhere = (section == "interface" && matches!(k, "theme" | "appearanceMode" | "darkTheme" | "lightTheme" | "favoriteThemes")) // View › Rulers (⌘R) sets it, as in Photoshop. || path == "unitsAndRulers.showRulers" - || (section == "performance" && matches!(k, "useGpu" | "gpuBackend" | "renderingMode")) + || (section == "performance" && matches!(k, "useGpu" | "gpuBackend" | "renderingMode" | "memoryUsageMb")) // The browser presents frames itself: Low-Latency Drawing does nothing there. || (cfg!(target_arch = "wasm32") && path == "performance.lowLatencyDrawing") || (section == "export" && !export_field_visible(obj, k)) @@ -1593,10 +1633,37 @@ fn section_fields( if section == "performance" && (query.is_empty() || preference_matches(section, "renderingMode", &query)) { rendering_mode_row(ui, obj); } + if section == "performance" && (query.is_empty() || preference_matches(section, "memoryUsageMb", &query)) { + memory_usage_row(ui, obj); + } keys.retain(|k| field_visible(section, obj, k, &query)); egui::Grid::new(("prefs-grid", section)).num_columns(2).spacing([14.0, 7.0]).show(ui, |ui| field_rows(ui, section, obj, keys, lang)); } +/// Explain the per-document RAM limit separately from the graphics-memory preference. +fn memory_usage_row(ui: &mut egui::Ui, obj: &mut Map) { + let t = Tokens::get(ui.ctx()); + ui.group(|ui| { + ui.label(RichText::new(tl!("Memory Usage")).strong()); + let mut mb = obj.get("memoryUsageMb").and_then(Value::as_u64).unwrap_or(8192); + ui.horizontal(|ui| { + ui.label(tl!("Per-document RAM limit (MB)")); + if ui.add(egui::DragValue::new(&mut mb).range(256..=1_048_576).suffix(" MB")).changed() { + obj.insert("memoryUsageMb".into(), json!(mb)); + } + }); + if let Some(ram) = crate::gpu_canvas::physical_memory().filter(|n| *n > 0) { + let installed = ram / (1 << 20); + let percent = mb as f64 * 100.0 / (ram as f64 / (1 << 20) as f64); + ui.label(crate::i18n::fmt(tl!("Installed RAM: {ram} MB; this limit: {percent}%"), &[("ram", &installed.to_string()), ("percent", &format!("{percent:.1}"))])); + } + ui.label(RichText::new(tl!("Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded.")).color(t.text_dim)); + ui.label(RichText::new(tl!("Applies immediately when saved. Memory is not reserved in advance.")).color(t.text_dim)); + ui.label(RichText::new(tl!("With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget.")).color(t.text_dim)); + }); + ui.add_space(8.0); +} + /// One grid row per setting in `keys` (already filtered by `field_visible`). fn field_rows(ui: &mut egui::Ui, section: &str, obj: &mut Map, keys: Vec, lang: crate::i18n::Lang) { let t = Tokens::get(ui.ctx()); @@ -2313,7 +2380,7 @@ fn presets_io_body(ui: &mut egui::Ui, f: &mut Map) { 180.0, ); }); - for (k, label) in [("brushes", tl!("Brushes")), ("customShapes", tl!("Custom Shapes"))] { + for (k, label) in [("brushes", tl!("Brushes")), ("customShapes", tl!("Custom Shapes")), ("tools", tl!("Tool Presets"))] { let mut on = f.get(k).and_then(Value::as_bool).unwrap_or(true); crate::widgets::checkbox(ui, &mut on, label); f.insert(k.into(), json!(on)); @@ -2437,7 +2504,7 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result Ok(Value::Null), "presetsIO" => { - let kinds: Vec<&str> = ["brushes", "customShapes"].into_iter().filter(|k| f.get(*k).and_then(Value::as_bool).unwrap_or(true)).collect(); + let kinds: Vec<&str> = ["brushes", "customShapes", "tools"].into_iter().filter(|k| f.get(*k).and_then(Value::as_bool).unwrap_or(true)).collect(); if f.get("action").and_then(Value::as_str) == Some("import") { app.pick_file_bytes(move |app, name, bytes| { let text = String::from_utf8(bytes).map_err(|_| format!("{name} is not a preset file"))?; @@ -2481,6 +2548,22 @@ mod shortcut_set_tests; #[cfg(test)] mod tests { + #[test] + fn memory_usage_has_a_dedicated_explanation_and_keeps_its_value() { + use egui_kittest::{Harness, kittest::Queryable}; + let values = json!({"memoryUsageMb":50000}).as_object().unwrap().clone(); + assert!(!field_visible("performance", &values, "memoryUsageMb", "")); + let mut h = Harness::builder() + .with_size(vec2(680.0, 350.0)) + .build_ui_state(|ui, values| section_fields(ui, "performance", values, &["memoryUsageMb".into()], crate::i18n::Lang::EN, None, ""), values); + h.run_steps(2); + h.get_by_label("Memory Usage"); + h.get_by_label("Per-document RAM limit (MB)"); + h.get_by_label("Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded."); + h.get_by_label("Applies immediately when saved. Memory is not reserved in advance."); + assert_eq!(h.state()["memoryUsageMb"], 50000); + } + #[test] fn colour_preferences_take_a_typed_hex_value() { // #668: the canvas colour (and every colour preference) showed its hex but couldn't take one. @@ -2568,15 +2651,30 @@ mod tests { } #[test] - fn preferences_dialog_width_follows_the_window() { + fn preferences_dialog_width_follows_its_resizable_area() { let prefs = serde_json::json!({"__prefsui": "prefs"}); let prefs = prefs.as_object().unwrap(); assert_eq!(super::width(prefs, 200.0), Some(380.0)); assert_eq!(super::width(prefs, 800.0), Some(800.0)); - assert_eq!(super::width(prefs, 3000.0), Some(1040.0)); + // A dialog resized wider than it opens is filled, not left with empty space (#7420). + assert_eq!(super::width(prefs, 3000.0), Some(3000.0)); let shortcuts = serde_json::json!({"__prefsui": "shortcuts"}); assert_eq!(super::width(shortcuts.as_object().unwrap(), 3000.0), Some(720.0)); } + + #[test] + fn preferences_settings_fill_the_dialog_down_to_the_buttons() { + // The settings area plus the button row (spacing, 8 pt gap, buttons) stays inside what the + // resizable area gives it, at any size: the area grows to fit its content, so asking for + // more would make the dialog grow every frame. The area follows the dialog's size (#7420). + for available in [300.0, 600.0, 1400.0] { + let h = super::settings_height(available, 4.0, 30.0); + assert!(h + 4.0 + 8.0 + 30.0 <= available, "{available}"); + assert!(h + 4.0 + 8.0 + 30.0 + 8.0 >= available, "{available}"); + } + assert_eq!(super::settings_height(1400.0, 4.0, 30.0) - super::settings_height(600.0, 4.0, 30.0), 800.0); + assert_eq!(super::settings_height(50.0, 4.0, 30.0), 160.0); + } use super::*; use std::sync::{Arc, Mutex}; @@ -3033,6 +3131,39 @@ mod tests { serde_json::from_str(store.lock().unwrap().as_deref().unwrap_or("null")).unwrap() } + #[test] + fn a_wrongly_typed_value_resets_only_itself_and_is_repaired_on_disk() { + // #6611: one bad value used to reset every preference, on every launch. + let saved = json!({ + "fileHandling": {"recentFileCount": "ten", "autosaveMinutes": 5}, + "performance": {"historyStates": 12}, + "shortcuts": {"edit.fill": "Cmd+Shift+F", "file.open": 7}, + "futureSection": {"kept": true}, + }); + let (mut app, store) = app_with_saved(Some(saved.to_string())); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + let p = app.session.prefs(); + assert_eq!((p.file_handling.recent_file_count, p.file_handling.autosave_minutes, p.performance.history_states), (20, 5, 12)); + assert!(!app.ui.status.contains("reset"), "{}", app.ui.status); + let notice = app.ui.notices.iter().find(|n| n.title == "Some preferences were reset").expect("a notice names the bad values"); + let text = notice.text(¬ice.lines[0]); + assert!(text.contains("fileHandling.recentFileCount, shortcuts.file.open"), "{text}"); + // The file now holds the default in its place and keeps everything else. + let v = stored(&store); + assert_eq!(v["fileHandling"]["recentFileCount"], 20); + assert_eq!(v["fileHandling"]["autosaveMinutes"], 5); + assert_eq!(v["performance"]["historyStates"], 12); + assert_eq!(v["shortcuts"]["edit.fill"], "Cmd+Shift+F"); + assert!(v["shortcuts"].get("file.open").is_none()); + assert_eq!(v["futureSection"]["kept"], true, "keys this version doesn't know survive"); + // So the next launch loads cleanly. + let (mut next, _) = app_with_saved(store.lock().unwrap().clone()); + tick(&mut next, &ctx); + assert!(next.ui.notices.iter().all(|n| n.title != "Some preferences were reset")); + assert_eq!(next.session.prefs().file_handling.autosave_minutes, 5); + } + #[test] fn merge_keeps_changes_made_elsewhere() { let base = json!({"a": {"x": 1, "y": 1}, "list": [1], "gone": 1, "kept": 1}); @@ -3486,11 +3617,13 @@ mod tests { assert!(!prefs::is_hidden("type.useEscToCommit")); assert!(!prefs::is_hidden("type.smartQuotes")); assert!(!prefs::is_hidden("type.showFontNamesInEnglish")); - // Rotate View with Trackpad and the pinch zoom are live; the other Enhanced Controls rows - // stay hidden. + // Rotate View with Trackpad, the pinch zoom and Enable Gestures are live; the other + // Enhanced Controls rows stay hidden. assert!(has_visible_fields(&values, "enhancedControls")); assert!(!prefs::is_hidden("enhancedControls.rotateViewWithTrackpad")); assert!(!prefs::is_hidden("enhancedControls.zoomWithTrackpadPinch")); + assert!(!prefs::is_hidden("enhancedControls.touchGestures")); + assert!(prefs::is_hidden("enhancedControls.scrubbySliderAcceleration")); // Camera Raw Defaults shows only "Open in Camera Raw" so far. assert!(has_visible_fields(&values, "rawDefaults")); assert!(!prefs::is_hidden("rawDefaults.openInCameraRaw")); @@ -3529,6 +3662,23 @@ mod tests { assert!(store2.lock().unwrap().as_ref().unwrap().contains("classic")); } + #[test] + fn preset_export_dialog_offers_tool_presets() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let opened = crate::menus::invoke(&mut app, &ctx, "edit.presets.exportImportPresets", json!({})).unwrap(); + let fields = app.ui.dialog_mut(opened["dialog"].as_u64().unwrap()).unwrap().fields.clone(); + assert_eq!(fields["tools"], true); + let mut h = Harness::builder().with_size(vec2(420.0, 260.0)).build_ui_state(presets_io_body, fields); + h.run_steps(2); + h.get_by_label("Tool Presets").click(); + h.run_steps(2); + assert_eq!(h.state()["tools"], false); + assert_eq!(h.state()["brushes"], true); + assert_eq!(h.state()["customShapes"], true); + } + #[test] fn brush_preset_store_attaches_when_loaded_and_persists() { use photocraft_engine::preset_store::{MemBackend, open}; @@ -3985,9 +4135,11 @@ mod tests { assert!(note.starts_with("Monitor profile in use: sRGB") && note.contains("fallback"), "{note}"); assert!(crate::menus::invoke(&mut app, &ctx, "edit.fade", json!({})).is_err()); app.run("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); - let d = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap()["dialog"].as_u64().unwrap(); - assert_eq!(app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["__preview"], true); - crate::dialogs::confirm(&mut app, d).unwrap(); + // Content-Aware Fill opens its workspace (caf_ui); OK fills. + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap(); + assert!(r["contentAwareFill"]["window"].is_array(), "{r}"); + crate::caf_ui::commit(&mut app); + assert!(app.distort.caf.is_none()); let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareScale", json!({})).unwrap(); assert_eq!(r["transform"]["rect"], json!([4.0, 4.0, 12.0, 12.0])); crate::transform_tool::cancel(&mut app); diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rs index 8411c5af63..b52f1400d7 100644 --- a/crates/ui-egui/src/preset_panels.rs +++ b/crates/ui-egui/src/preset_panels.rs @@ -1002,6 +1002,7 @@ fn tool_id(t: Tool) -> String { /// Apply a tool preset: the engine sets the brush/colour, the shell switches tool and options. pub fn select_tool_preset(app: &mut PhotocraftApp, name: &str) { + let before_ratio = crate::crop_ui::preset_ratio(app); let Some(r) = run(app, "tool.presets.select", json!({"preset": name})) else { return }; if let Some(tool) = r["tool"].as_str().and_then(Tool::from_name) { crate::tool_memory::select(app, tool); @@ -1016,13 +1017,39 @@ pub fn select_tool_preset(app: &mut PhotocraftApp, name: &str) { let mut cur = serde_json::to_value(&app.ui.tool_options).unwrap_or_default(); if let Some(c) = cur.as_object_mut() { for (k, v) in o { - c.insert(k.clone(), v.clone()); + // An object option (`sample_all`, one per tool) takes only the entries the + // preset stored, so the other tools' keep theirs (#5524). + match (c.get_mut(k), v) { + (Some(Value::Object(have)), Value::Object(set)) => have.extend(set.clone()), + _ => { + c.insert(k.clone(), v.clone()); + } + } } } if let Ok(opts) = serde_json::from_value(cur) { app.ui.tool_options = opts; } } + // As the options bar does: a crop preset's ratio (or W x H) fits the frame at once. + if crate::crop_ui::preset_ratio(app) != before_ratio { + crate::crop_ui::apply_ratio(app); + } +} + +/// The `tool.presets.new` params for the + button: `tool`'s own options only, so choosing the +/// preset later leaves the other tools' settings alone. +fn new_tool_preset_params(app: &PhotocraftApp, tool: Tool) -> Value { + let all = serde_json::to_value(&app.ui.tool_options).unwrap_or_default(); + let mut own: serde_json::Map = + crate::tool_reset::option_keys(tool).iter().filter_map(|k| Some(((*k).to_string(), all.get(*k)?.clone()))).collect(); + // Sample All Layers is each tool's own (#5524): store `tool`'s alone. + if let Some(k) = crate::tool_reset::sample_all_key(tool) + && let Some(v) = all.get("sample_all").and_then(|m| m.get(&k)) + { + own.insert("sample_all".into(), json!({ k: v })); + } + json!({"name": tool.label(), "tool": tool_id(tool), "options": {"toolOptions": own}}) } pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -1093,9 +1120,7 @@ pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { action = Some(("tool.presets.edit".into(), json!({"action": "delete", "preset": n}))); } if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new tool preset")).clicked() { - let label = cur.label().to_string(); - let opts = json!({"toolOptions": serde_json::to_value(&app.ui.tool_options).unwrap_or_default()}); - action = Some(("tool.presets.new".into(), json!({"name": label, "tool": tool_id(cur), "options": opts}))); + action = Some(("tool.presets.new".into(), new_tool_preset_params(app, cur))); } }); }); @@ -1262,6 +1287,7 @@ pub fn clone_sample_point(app: &PhotocraftApp, at: Option<[f64; 2]>) -> Option<[ mod tests { use super::*; use crate::menus::invoke; + use crate::state::ToolOptions; fn app() -> (PhotocraftApp, egui::Context) { let ctx = egui::Context::default(); @@ -1311,6 +1337,59 @@ mod tests { assert_eq!(Tool::from_name(&tool_id(Tool::CustomShape)), Some(Tool::CustomShape)); } + /// A crop preset picked in Tool Presets fits the frame to its ratio at once, as the options + /// bar's dropdown does. + #[test] + fn a_crop_tool_preset_fits_the_frame_to_its_ratio() { + let (mut app, _) = app(); + app.ui.tool = Tool::Crop; + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 64.0, 48.0])); + app.run("tool.presets.new", json!({"name": "Square", "tool": "crop", "options": {"toolOptions": {"crop_ratio": "1:1"}}})).unwrap(); + select_tool_preset(&mut app, "Square"); + assert_eq!(app.ui.tool_options.crop_ratio, "1:1"); + assert_eq!(app.ui.crop_rect, Some([8.0, 0.0, 56.0, 48.0])); + } + + /// #7356: a preset made with + keeps only its own tool's options, so choosing it doesn't + /// reset the Crop tool's Delete Cropped Pixels or the Move tool's Auto-Select. + #[test] + fn new_tool_preset_stores_only_its_tools_options() { + let (mut app, _) = app(); + app.ui.tool = Tool::RectMarquee; + app.ui.tool_options.feather = 5.0; + let p = new_tool_preset_params(&app, Tool::RectMarquee); + let r = app.run("tool.presets.new", p).unwrap(); + let name = r["name"].as_str().unwrap().to_string(); + let stored = &app.session.presets.tool_presets.iter().find(|t| t.name == name).unwrap().options["toolOptions"]; + assert_eq!(stored["feather"], json!(5.0)); + assert!(stored.as_object().unwrap().keys().all(|k| !k.starts_with("crop_") && !k.starts_with("move_")), "{stored}"); + app.ui.tool_options.feather = 0.0; + app.ui.tool_options.crop_delete = !ToolOptions::default().crop_delete; + app.ui.tool_options.move_auto_select = !ToolOptions::default().move_auto_select; + select_tool_preset(&mut app, &name); + assert_eq!(app.ui.tool_options.feather, 5.0); + assert_eq!(app.ui.tool_options.crop_delete, !ToolOptions::default().crop_delete); + assert_eq!(app.ui.tool_options.move_auto_select, !ToolOptions::default().move_auto_select); + } + + /// #5524 with #7356: a Blur preset keeps Blur's Sample All Layers and leaves the Magic Wand's + /// alone, both when it is made and when it is chosen. + #[test] + fn new_tool_preset_stores_only_its_tools_sample_all_layers() { + let (mut app, _) = app(); + app.ui.tool = Tool::Blur; + app.ui.tool_options.sample_all.blur = true; + let p = new_tool_preset_params(&app, Tool::Blur); + assert_eq!(p["options"]["toolOptions"]["sample_all"], json!({"blur": true})); + let name = app.run("tool.presets.new", p).unwrap()["name"].as_str().unwrap().to_string(); + app.ui.tool_options.sample_all.blur = false; + app.ui.tool_options.sample_all.magic_wand = true; + select_tool_preset(&mut app, &name); + assert!(app.ui.tool_options.sample_all.blur); + assert!(app.ui.tool_options.sample_all.magic_wand, "the Magic Wand's Sample All Layers is not Blur's"); + } + #[test] fn custom_shape_tool_places_the_picked_shape() { let (mut app, _) = app(); diff --git a/crates/ui-egui/src/props_layout.rs b/crates/ui-egui/src/props_layout.rs index 674ff4dba2..ea67b3714d 100644 --- a/crates/ui-egui/src/props_layout.rs +++ b/crates/ui-egui/src/props_layout.rs @@ -17,6 +17,17 @@ pub const LABEL_GAP: f32 = 4.0; /// Horizontal gap between two label+field columns. pub const COL_GAP: f32 = 8.0; +/// A one-letter field label ("W", "H", "X", "Y") in a `w`-wide column, ending `pad` before its field. The letters +/// stacked in one column share a centre (#7314): the widest of `column` stays flush right, and the narrower ones +/// are centred on it rather than pushed against its right edge. +pub fn stacked_label(ui: &mut egui::Ui, s: &str, column: &[&str], w: f32, pad: f32) { + let t = Tokens::get(ui.ctx()); + let font = egui::FontId::proportional(12.0); + let widest = column.iter().map(|c| ui.painter().layout_no_wrap((*c).to_owned(), font.clone(), t.text_dim).size().x).fold(0.0, f32::max); + let (r, _) = ui.allocate_exact_size(vec2(w, 22.0), Sense::hover()); + ui.painter().text(pos2(r.right() - pad - widest / 2.0, r.center().y), egui::Align2::CENTER_CENTER, s, font, t.text_dim); +} + /// Icon for a layer kind (the same glyphs as the Layers panel's kind filter). pub fn kind_icon(content: &LayerContent) -> &'static str { match content { diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs index 3e35407781..716b5997c4 100644 --- a/crates/ui-egui/src/retouch_ui.rs +++ b/crates/ui-egui/src/retouch_ui.rs @@ -50,9 +50,9 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { pub(crate) fn dab_params(app: &PhotocraftApp, tool: Tool) -> Option<(&'static str, Value)> { let o = &app.ui.tool_options; Some(match tool { - Tool::Blur => ("paint.blur", json!({"strength": o.strength, "sampleAllLayers": o.sample_all_layers})), - Tool::Sharpen => ("paint.sharpen", json!({"strength": o.strength, "protectDetail": o.protect_detail, "sampleAllLayers": o.sample_all_layers})), - Tool::Smudge => ("paint.smudge", json!({"strength": o.strength, "fingerPainting": o.finger_painting, "sampleAllLayers": o.sample_all_layers})), + Tool::Blur => ("paint.blur", json!({"strength": o.strength, "sampleAllLayers": o.sample_all.blur})), + Tool::Sharpen => ("paint.sharpen", json!({"strength": o.strength, "protectDetail": o.protect_detail, "sampleAllLayers": o.sample_all.sharpen})), + Tool::Smudge => ("paint.smudge", json!({"strength": o.strength, "fingerPainting": o.finger_painting, "sampleAllLayers": o.sample_all.smudge})), Tool::Dodge | Tool::Burn => ( if tool == Tool::Dodge { "paint.dodge" } else { "paint.burn" }, json!({"range": o.tone_range, "exposure": o.exposure, "protectTones": o.protect_tones}), @@ -116,7 +116,7 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], m let o = app.ui.tool_options.clone(); let pts = json!(points); let (cmd, mut p): (&str, Value) = match tool { - Tool::SpotHealing => ("paint.spotHealing", json!({"type": o.spot_type, "sampleAllLayers": o.sample_all_layers})), + Tool::SpotHealing => ("paint.spotHealing", json!({"type": o.spot_type, "sampleAllLayers": o.sample_all.spot_healing})), Tool::Remove => { if !o.remove_after_each_stroke { remove_pending_add(app, points); @@ -150,7 +150,7 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], m let size = app.session.tools.brush.size; let mode = if mods.alt { "subtract" } else { "add" }; let xy: Vec<[f64; 2]> = points.iter().map(|q| [q[0], q[1]]).collect(); - let (sample_all, enhance) = (o.sample_all_layers, o.enhance_edge); + let (sample_all, enhance) = (o.sample_all.quick_selection, o.enhance_edge); let r = app.run("select.quick", json!({"points": xy, "size": size, "mode": mode, "enhanceEdge": enhance, "sampleAllLayers": sample_all})); report_smart_result(app, r, tl!("Quick Selection found nothing there")); return true; @@ -179,21 +179,37 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], m /// `paint.remove` params from the options bar (without the strokes). fn remove_params(o: &crate::state::ToolOptions) -> Value { - json!({"sampleAllLayers": o.sample_all_layers, "newLayer": o.remove_new_layer}) + json!({"sampleAllLayers": o.sample_all.remove, "newLayer": o.remove_new_layer}) +} + +/// The selection a queued Remove stroke was drawn against. A later selection must not +/// redirect the queued strokes to a different layer or colour component. +#[derive(Clone, PartialEq)] +pub(crate) struct RemoveTarget { + doc: photocraft_doc::DocId, + layer: Option, + channel: photocraft_engine::channel_cmds::ChannelTarget, + paint: Value, +} + +fn remove_target(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + Some(RemoveTarget { doc: st.doc.id, layer: st.active_layer, channel: st.channel_view.target, paint: crate::canvas::paint_target(app) }) } /// Remove after each stroke off: a finished stroke waits with the others, tinted on the canvas, /// until ↩ or the options bar's ✓ applies them all as one removal (Esc or ⊘ drops them). pub fn remove_pending_add(app: &mut PhotocraftApp, points: &[[f64; 3]]) { + let Some(target) = remove_target(app) else { return }; let Some(st) = app.session.active() else { return }; - let (doc, size) = (st.doc.id, [st.doc.size.width, st.doc.size.height]); - if app.remove_pending_doc != Some(doc) { + let size = [st.doc.size.width, st.doc.size.height]; + if app.remove_pending_target.as_ref() != Some(&target) { app.remove_pending.clear(); app.remove_trail = None; - app.remove_pending_doc = Some(doc); + app.remove_pending_target = Some(target); } let diameter = app.session.tools.brush.size; - app.remove_trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)).feed(points, diameter); + app.remove_trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)).feed_stroke(points, diameter); app.remove_pending.push(points.to_vec()); app.ui.status = crate::i18n::fmt(tl!("Strokes to remove: {n} (Enter applies, Esc cancels)"), &[("n", &app.remove_pending.len().to_string())]); app.ui.status_error = false; @@ -201,12 +217,13 @@ pub fn remove_pending_add(app: &mut PhotocraftApp, points: &[[f64; 3]]) { /// Apply the waiting strokes as one removal (one job, one undo step). False when none wait. pub fn remove_pending_commit(app: &mut PhotocraftApp) -> bool { - if app.remove_pending.is_empty() { + // Enter can arrive before the next canvas frame checks pending-stroke lifetime. + if !remove_pending_live(app) { return false; } let strokes = std::mem::take(&mut app.remove_pending); app.remove_trail = None; - app.remove_pending_doc = None; + app.remove_pending_target = None; let mut p = remove_params(&app.ui.tool_options); p["strokes"] = json!(strokes); p["target"] = crate::canvas::paint_target(app); @@ -225,7 +242,7 @@ pub fn remove_pending_cancel(app: &mut PhotocraftApp) -> bool { } app.remove_pending.clear(); app.remove_trail = None; - app.remove_pending_doc = None; + app.remove_pending_target = None; app.ui.status.clear(); app.ui.status_error = false; true @@ -237,8 +254,7 @@ pub fn remove_pending_live(app: &mut PhotocraftApp) -> bool { if app.remove_pending.is_empty() { return false; } - let doc = app.session.active().map(|st| st.doc.id); - if app.ui.tool == Tool::Remove && doc.is_some() && app.remove_pending_doc == doc { + if app.ui.tool == Tool::Remove && remove_target(app).as_ref() == app.remove_pending_target.as_ref() { return true; } remove_pending_cancel(app); @@ -307,7 +323,7 @@ pub fn finish_patch(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { "contentAware": true, "structure": o.patch_structure.round().clamp(1.0, 7.0), "color": o.patch_color.round().clamp(0.0, 10.0), - "sampleAllLayers": o.sample_all_layers, + "sampleAllLayers": o.sample_all.patch, "target": crate::canvas::paint_target(app), }); if let Err(e) = app.run("paint.patch", p) { @@ -353,7 +369,7 @@ pub fn content_aware_move_params(app: &PhotocraftApp, offset: [i64; 2]) -> Value "mode": o.cam_mode, "structure": o.cam_structure.round().clamp(1.0, 7.0), "color": o.cam_color.round().clamp(0.0, 10.0), - "sampleAllLayers": o.sample_all_layers, + "sampleAllLayers": o.sample_all.content_aware_move, "target": crate::canvas::paint_target(app), }) } @@ -367,7 +383,7 @@ pub fn content_aware_move_params(app: &PhotocraftApp, offset: [i64; 2]) -> Value pub fn finish_object_selection(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) { let (x, y) = (start[0].min(end[0]), start[1].min(end[1])); let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs()); - let sample_all = app.ui.tool_options.sample_all_layers; + let sample_all = app.ui.tool_options.sample_all.object_selection; if (w < 2.0 || h < 2.0) && app.ui.tool_options.object_finder { // Object Finder (#4087): the object under the click, as hovering highlighted it. let mode = match (mods.shift, mods.alt) { @@ -472,12 +488,12 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } } crate::widgets::vline(ui, 22.0); - crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers")); + crate::widgets::checkbox(ui, &mut o.sample_all.spot_healing, tl!("Sample All Layers")); } Tool::Remove => { // Photoshop's options bar: Sample All Layers, Create a new layer, Remove after each // stroke; with strokes waiting, ✓ applies them and ⊘ drops them. - crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers")); + crate::widgets::checkbox(ui, &mut o.sample_all.remove, tl!("Sample All Layers")); crate::widgets::checkbox(ui, &mut o.remove_new_layer, tl!("Create a new layer")); crate::widgets::checkbox(ui, &mut o.remove_after_each_stroke, tl!("Remove after each stroke")); if !app.remove_pending.is_empty() { @@ -506,7 +522,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::value_field(ui, &mut o.patch_structure, 1.0..=7.0, "", 40.0); opt(ui, tl!("Color:")); crate::widgets::value_field(ui, &mut o.patch_color, 0.0..=10.0, "", 40.0); - crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers")); + crate::widgets::checkbox(ui, &mut o.sample_all.patch, tl!("Sample All Layers")); } else { for (k, l) in [("source", tl!("Source")), ("destination", tl!("Destination"))] { let mut on = o.patch_mode == k; @@ -526,7 +542,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::value_field(ui, &mut o.cam_structure, 1.0..=7.0, "", 40.0); opt(ui, tl!("Color:")); crate::widgets::value_field(ui, &mut o.cam_color, 0.0..=10.0, "", 40.0); - crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers")); + crate::widgets::checkbox(ui, &mut o.sample_all.content_aware_move, tl!("Sample All Layers")); crate::widgets::checkbox(ui, &mut o.cam_transform_on_drop, tl!("Transform On Drop")); crate::widgets::vline(ui, 22.0); if crate::cam_transform::active(app) { @@ -578,7 +594,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } Tool::Blur | Tool::Sharpen | Tool::Smudge => { pct(ui, tl!("Strength:"), &mut o.strength); - crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers")); + if let Some(all) = o.sample_all.slot(tool) { + crate::widgets::checkbox(ui, all, tl!("Sample All Layers")); + } if tool == Tool::Sharpen { crate::widgets::checkbox(ui, &mut o.protect_detail, tl!("Protect Detail")); } @@ -622,7 +640,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } Tool::HistoryBrush => opt(ui, "Paints from the document's opening state"), Tool::QuickSelection => { - crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers")); + crate::widgets::checkbox(ui, &mut o.sample_all.quick_selection, tl!("Sample All Layers")); crate::widgets::checkbox(ui, &mut o.enhance_edge, tl!("Enhance Edge")); opt(ui, &crate::i18n::fmt(tl!("{key} to subtract"), &[("key", &crate::shortcuts::pretty("Alt"))])); crate::widgets::vline(ui, 22.0); @@ -633,7 +651,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } Tool::ObjectSelection => { crate::widgets::checkbox(ui, &mut o.object_finder, tl!("Object Finder")); - crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers")); + crate::widgets::checkbox(ui, &mut o.sample_all.object_selection, tl!("Sample All Layers")); opt(ui, tl!("Drag a rectangle around the object")); crate::widgets::vline(ui, 22.0); if crate::widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() { @@ -820,7 +838,7 @@ mod tests { let mut app = app(); stripes(&mut app, 4, "pixels"); app.run("layer.new.layer", json!({})).unwrap(); - app.ui.tool_options.sample_all_layers = all; + *app.ui.tool_options.sample_all.slot(tool).unwrap() = all; drag(&mut app, tool); let a = active(&app).surface().unwrap().rgba(30, 30)[3]; assert_eq!(a > 0.0, all, "{tool:?} sampleAllLayers={all}: alpha {a}"); @@ -828,6 +846,42 @@ mod tests { } } + #[test] + fn sample_all_layers_is_each_tools_own() { + // #5524: Sample All Layers turned on for another tool (the Magic Wand, say) left Blur and + // Smudge copying the composite onto an annotation layer, freezing a sharp patch above the + // picture. Photoshop keeps the option per tool, so those strokes leave the empty layer empty. + for tool in [Tool::Blur, Tool::Sharpen, Tool::Smudge] { + let mut app = app(); + stripes(&mut app, 4, "pixels"); + app.run("layer.new.layer", json!({})).unwrap(); + let mut others = crate::state::SampleAllLayers::default(); + for t in [ + Tool::MagicWand, + Tool::QuickSelection, + Tool::ObjectSelection, + Tool::PaintBucket, + Tool::MagicEraser, + Tool::SpotHealing, + Tool::Patch, + Tool::ContentAwareMove, + Tool::Remove, + Tool::Blur, + Tool::Sharpen, + Tool::Smudge, + ] { + if let Some(v) = others.slot(t).filter(|_| t != tool) { + *v = true; + } + } + app.ui.tool_options.sample_all = others; + assert!(!app.ui.tool_options.sample_all.get(tool)); + drag(&mut app, tool); + let a = active(&app).surface().unwrap().rgba(30, 30)[3]; + assert_eq!(a, 0.0, "{tool:?} sampled all layers through another tool's option"); + } + } + #[test] fn object_selection_click_falls_back_to_quick_selection() { // A click cannot be a rectangle: it selects at the cursor instead of looking dead. @@ -1157,6 +1211,95 @@ mod tests { assert!(!remove_pending_commit(&mut app), "nothing left to apply"); } + #[test] + fn every_waiting_remove_stroke_is_tinted_in_full() { + // #6555: each stroke used to be stamped only past the previous stroke's point count. + let mut app = app(); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + let strokes: [&[[f64; 3]]; 3] = [ + &[[10.0, 10.0, 1.0], [40.0, 10.0, 1.0], [70.0, 10.0, 1.0]], + &[[10.0, 30.0, 1.0], [40.0, 30.0, 1.0]], + &[[10.0, 50.0, 1.0], [20.0, 50.0, 1.0], [30.0, 50.0, 1.0], [50.0, 50.0, 1.0], [90.0, 50.0, 1.0]], + ]; + for s in strokes { + remove_pending_add(&mut app, s); + } + assert_eq!(app.remove_pending.len(), 3); + let t = app.remove_trail.as_ref().expect("the waiting strokes are tinted"); + let k = f64::from(t.scale()); + for s in strokes { + for w in s.windows(2) { + for i in 0..=8 { + let f = f64::from(i) / 8.0; + let (x, y) = (w[0][0] + (w[1][0] - w[0][0]) * f, w[0][1] + (w[1][1] - w[0][1]) * f); + assert_eq!(t.coverage((x / k) as usize, (y / k) as usize), 255, "({x}, {y}) on a waiting stroke is tinted"); + } + } + } + // Enter, Esc, another tool and another document all drop the tint with the strokes. + assert!(remove_pending_commit(&mut app)); + assert!(app.remove_trail.is_none()); + remove_pending_add(&mut app, strokes[0]); + assert!(remove_pending_cancel(&mut app) && app.remove_trail.is_none()); + remove_pending_add(&mut app, strokes[1]); + app.ui.tool = Tool::SpotHealing; + assert!(!remove_pending_live(&mut app) && app.remove_trail.is_none()); + app.ui.tool = Tool::Remove; + remove_pending_add(&mut app, strokes[2]); + app.run("file.new", json!({"width": 100, "height": 60})).unwrap(); + assert!(!remove_pending_live(&mut app) && app.remove_trail.is_none()); + } + + #[test] + fn queued_remove_cannot_commit_after_layer_or_channel_target_changes() { + for change in ["layer", "color", "mask"] { + let mut app = app(); + app.run("layer.new.layer", json!({"name": "Original"})).unwrap(); + if change == "color" { + app.run("channel.target", json!({"channel": "red"})).unwrap(); + } + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + remove_pending_add(&mut app, &[[12.0, 10.0, 1.0], [16.0, 12.0, 1.0]]); + assert_eq!(app.remove_pending.len(), 1); + assert!(remove_pending_live(&mut app)); + + match change { + "layer" => { + app.run("layer.new.layer", json!({"name": "Other"})).unwrap(); + } + "color" => { + app.run("channel.target", json!({"channel": "blue"})).unwrap(); + } + _ => { + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.ui.mask_target = true; + } + } + + let journal = app.session.journal.len(); + assert!(!remove_pending_commit(&mut app), "{change}: Enter must not retarget a queued stroke"); + assert_eq!(app.session.journal.len(), journal, "{change}: no Remove command ran"); + assert!(app.remove_pending.is_empty() && app.remove_trail.is_none(), "{change}: queue cleared"); + assert!(app.remove_pending_target.is_none()); + } + } + + #[test] + fn queued_remove_starts_a_new_queue_after_target_switch() { + let mut app = app(); + app.run("layer.new.layer", json!({"name": "Original"})).unwrap(); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + remove_pending_add(&mut app, &[[12.0, 10.0, 1.0], [16.0, 12.0, 1.0]]); + app.run("layer.new.layer", json!({"name": "Other"})).unwrap(); + remove_pending_add(&mut app, &[[40.0, 10.0, 1.0], [44.0, 12.0, 1.0]]); + assert_eq!(app.remove_pending.len(), 1, "strokes from different layers must not be combined"); + assert_eq!(app.remove_pending[0][0][0], 40.0); + assert!(remove_pending_live(&mut app)); + } + #[test] fn remove_strokes_waiting_are_dropped_when_the_tool_changes() { let mut app = app(); diff --git a/crates/ui-egui/src/rgb_histogram.rs b/crates/ui-egui/src/rgb_histogram.rs index f8787ad66b..efae4cce41 100644 --- a/crates/ui-egui/src/rgb_histogram.rs +++ b/crates/ui-egui/src/rgb_histogram.rs @@ -5,7 +5,7 @@ use photocraft_algo::histogram::{BINS, RgbHistogram}; /// A five-bin binomial display kernel softens quantization combs. It cannot bridge /// a wide empty range. Clipping bins are pinned and excluded from filtering adjacent bins. -fn curves(h: &RgbHistogram) -> [[f32; BINS]; 3] { +fn curves(h: &RgbHistogram, spikes: Spikes) -> [[f32; BINS]; 3] { let mut curves = [[0.0; BINS]; 3]; for (out, bins) in curves.iter_mut().zip(&h.channels) { for (i, value) in out.iter_mut().enumerate() { @@ -22,7 +22,18 @@ fn curves(h: &RgbHistogram) -> [[f32; BINS]; 3] { // preserve them at the edges, capped at the top. A flat black/white image uses its edge peak. let interior = curves.iter().flat_map(|c| c.iter().skip(1).take(BINS - 2)).copied().fold(0.0f32, f32::max); let peak = if interior > 0.0 { interior } else { curves.iter().flatten().copied().fold(0.0f32, f32::max) }; - let scale = if peak > 0.0 { peak * 1.1 } else { 1.0 }; + let mut scale = if peak > 0.0 { peak * 1.1 } else { 1.0 }; + if spikes == Spikes::Clip { + // Camera Raw scales linearly with the 95th-percentile column at two thirds of the height + // and lets taller spikes run off the top (measured on Photoshop 25.4's Camera Raw 16.1.1: + // 49 px per 10 000 pixels in a 106 px plot, 95th percentile 14 546, full 21 600). + let mut columns: Vec = (1..BINS - 1).map(|i| curves.iter().map(|c| c[i]).fold(0.0f32, f32::max)).collect(); + columns.sort_unstable_by(f32::total_cmp); + let p95 = columns.get(columns.len() * 95 / 100).copied().unwrap_or(0.0); + if p95 > 0.0 { + scale = scale.min(p95 * 1.5); + } + } for value in curves.iter_mut().flatten() { *value = (*value / scale).min(1.0); } @@ -101,11 +112,24 @@ fn fill(rect: Rect, curves: &[[f32; BINS]; 3], t: &Tokens) -> Mesh { mesh } +/// How a histogram treats columns far above the rest. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Spikes { + /// Fit the tallest interior column (edge columns excluded). + Fit, + /// Camera Raw's: scale by the typical columns, spikes run off the top. + Clip, +} + pub(crate) fn paint(painter: &egui::Painter, rect: Rect, h: &RgbHistogram, t: &Tokens) { + paint_with(painter, rect, h, t, Spikes::Fit); +} + +pub(crate) fn paint_with(painter: &egui::Painter, rect: Rect, h: &RgbHistogram, t: &Tokens, spikes: Spikes) { if !rect.is_finite() || !rect.is_positive() || !rect.size().is_finite() { return; } - let curves = curves(h); + let curves = curves(h, spikes); painter.add(fill(rect, &curves, t)); for (channel, values) in curves.iter().enumerate() { if !values.iter().any(|&v| v > 0.0) { @@ -139,7 +163,7 @@ pub(crate) fn paint_sample(painter: &egui::Painter, rect: Rect, rgb: [f32; 3], t #[cfg(test)] fn mesh(rect: Rect, h: &RgbHistogram, t: &Tokens) -> Mesh { - fill(rect, &curves(h), t) + fill(rect, &curves(h, Spikes::Fit), t) } #[cfg(test)] @@ -161,6 +185,28 @@ mod tests { }) } + #[test] + fn camera_raw_scale_lets_a_shadow_spike_run_off_the_top() { + // A dark-sky photo: a tall spike in the first columns over a hill in the midtones. + let mut h = RgbHistogram::default(); + for c in &mut h.channels { + for (i, v) in c.iter_mut().enumerate() { + let x = i as f32 / 255.0; + *v = (14_000.0 * (-((x - 0.5) / 0.18).powi(2)).exp()) as u64 + 3_000; + } + c[1] = 88_000; + c[2] = 42_000; + } + let fit = curves(&h, Spikes::Fit); + let clip = curves(&h, Spikes::Clip); + assert!(fit[1][128] < 0.25, "fitting the spike flattens the hill: {}", fit[1][128]); + assert!((0.5..0.75).contains(&clip[1][128]), "Camera Raw keeps the hill at about two thirds: {}", clip[1][128]); + assert_eq!(clip[1][1], 1.0, "the spike is clipped at the top"); + // Without spikes both scales agree. + let flat = RgbHistogram { channels: [[3; BINS], [2; BINS], [1; BINS]], ..Default::default() }; + assert_eq!(curves(&flat, Spikes::Fit), curves(&flat, Spikes::Clip)); + } + #[test] fn shared_scale_and_overlaps_are_exact_for_every_theme() { let h = RgbHistogram { channels: [[3; BINS], [2; BINS], [1; BINS]], ..Default::default() }; @@ -217,15 +263,15 @@ mod tests { let mut h = RgbHistogram { channels: [[10; BINS]; 3], ..Default::default() }; h.channels[0][0] = 1_000_000; h.channels[1][255] = 1_000_000; - let p = curves(&h); + let p = curves(&h, Spikes::Fit); assert_eq!(p[0][0], 1.0); assert_eq!(p[1][255], 1.0); assert!((p[0][1] - 1.0 / 1.1).abs() < 0.0001); assert!((p[1][254] - 1.0 / 1.1).abs() < 0.0001); let mut h = RgbHistogram::default(); h.channels[0][255] = 100; - assert!(curves(&h)[0][255] > 0.9); - assert_eq!(curves(&h)[0][254], 0.0); + assert!(curves(&h, Spikes::Fit)[0][255] > 0.9); + assert_eq!(curves(&h, Spikes::Fit)[0][254], 0.0); } #[test] @@ -247,7 +293,7 @@ mod tests { channel[i] = 100; } } - let p = curves(&h); + let p = curves(&h, Spikes::Fit); let low = p[0][40..210].iter().copied().fold(f32::INFINITY, f32::min); let high = p[0][40..210].iter().copied().fold(0.0f32, f32::max); assert!(high - low < 0.2, "quantization comb still dominates the contour: {}", high - low); diff --git a/crates/ui-egui/src/rotate_view.rs b/crates/ui-egui/src/rotate_view.rs index 5e173da5dc..5137b9d312 100644 --- a/crates/ui-egui/src/rotate_view.rs +++ b/crates/ui-egui/src/rotate_view.rs @@ -4,7 +4,7 @@ //! decreases it in a flipped view). Shift snaps to 15°. Reset View, //! Escape, a double-click, or the on-canvas compass put the angle back to 0. History is not //! recorded. Trackpad rotate is gated by Preferences › Enhanced Controls › Rotate View with -//! Trackpad. +//! Trackpad; a two-finger twist on a touch screen also needs Enable Gestures (#204). use egui::{Align2, Pos2, Rect, Stroke, pos2, vec2}; use serde_json::{Value, json}; @@ -137,7 +137,9 @@ pub fn apply_trackpad(current: f32, enabled: bool, delta_rad: f32) -> Option Option { +/// The trackpad's own `Rotate` events always count; a touch screen's two-finger twist (egui's +/// multi-touch rotation) only while `touch_gestures` (Enhanced Controls › Enable Gestures) is on. +pub fn trackpad_delta(ctx: &egui::Context, enabled: bool, touch_gestures: bool) -> Option { if !enabled { return None; } @@ -150,7 +152,13 @@ pub fn trackpad_delta(ctx: &egui::Context, enabled: bool) -> Option { _ => None, }) .sum(); - if from_events != 0.0 { from_events } else { i.rotation_delta() } + if from_events != 0.0 { + from_events + } else if touch_gestures { + i.rotation_delta() + } else { + 0.0 + } }); apply_trackpad(0.0, true, rad).filter(|_| rad != 0.0) } @@ -324,8 +332,8 @@ mod tests { let mut disabled = None; let raw = egui::RawInput { events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)], ..Default::default() }; let mut output = ctx.run_ui(raw, |ui| { - enabled = trackpad_delta(ui.ctx(), true); - disabled = trackpad_delta(ui.ctx(), false); + enabled = trackpad_delta(ui.ctx(), true, true); + disabled = trackpad_delta(ui.ctx(), false, true); }); output.textures_delta.clear(); @@ -333,6 +341,36 @@ mod tests { assert_eq!(disabled, None); } + /// Preferences › Enhanced Controls › Enable Gestures (#204): off, a two-finger twist on a + /// touch screen doesn't turn the view; the trackpad's `Rotate` event still does. + #[test] + fn enable_gestures_switches_touch_screen_rotation() { + use egui::TouchPhase::{Move, Start}; + let touch = |id: u64, phase, pos| Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(id), phase, pos, force: None }; + let twist = |touch_gestures: bool, extra: Vec| { + let ctx = egui::Context::default(); + let frames = [ + // egui only starts a multi-touch gesture once it knows where the pointer is. + vec![Event::PointerMoved(pos2(50.0, 50.0))], + vec![touch(1, Start, pos2(40.0, 50.0)), touch(2, Start, pos2(60.0, 50.0))], + // A quarter turn about the centre between the fingers. + [vec![touch(1, Move, pos2(50.0, 40.0)), touch(2, Move, pos2(50.0, 60.0))], extra].concat(), + ]; + let mut last = None; + for (n, events) in (0u32..).zip(frames) { + let raw = egui::RawInput { time: Some(f64::from(n) / 60.0), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| last = trackpad_delta(ui.ctx(), true, touch_gestures)); + out.textures_delta.clear(); + } + last + }; + let on = twist(true, Vec::new()); + assert!(on.is_some_and(|d| (d.abs() - 90.0).abs() < 1e-3), "on: the fingers turn the view: {on:?}"); + assert_eq!(twist(false, Vec::new()), None, "off: the fingers don't"); + let trackpad = twist(false, vec![Event::Rotate(std::f32::consts::FRAC_PI_6)]); + assert!(trackpad.is_some_and(|d| (d - 30.0).abs() < 1e-3), "off: a trackpad rotate still turns: {trackpad:?}"); + } + #[test] fn trackpad_pref_gates_rotation() { assert_eq!(apply_trackpad(10.0, false, 0.5), None); diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/rulers.rs index 61ea25d96f..a5f4bb0fd1 100644 --- a/crates/ui-egui/src/rulers.rs +++ b/crates/ui-egui/src/rulers.rs @@ -329,10 +329,14 @@ fn ruler_pos(xf: &ViewXform, vertical: bool, u: f64, px_per_unit: f64, zero: [f6 /// (`y_axis` false) or the left one, from Preferences › Units & Rulers and the zoom. Minor ticks /// sit at tenths of the step. fn ruler_scale(app: &PhotocraftApp, xf: &ViewXform, y_axis: bool) -> (f64, f64) { + ruler_scale_of(app, app.session.active().map(|d| &*d.doc), xf, y_axis) +} + +/// [`ruler_scale`] for the view of `doc`. +fn ruler_scale_of(app: &PhotocraftApp, doc: Option<&photocraft_doc::Document>, xf: &ViewXform, y_axis: bool) -> (f64, f64) { let ur = &app.session.prefs().units_and_rulers; let (unit, ppi) = (ur.rulers, ur.point_size.per_inch()); - let (dpi, size) = - app.session.active().map_or((72.0, [1.0, 1.0]), |d| (d.doc.resolution_dpi.max(1.0) as f64, [d.doc.size.width as f64, d.doc.size.height as f64])); + let (dpi, size) = doc.map_or((72.0, [1.0, 1.0]), |d| (d.resolution_dpi.max(1.0) as f64, [d.size.width as f64, d.size.height as f64])); let px_per_unit = unit.to_px(1.0, dpi, if y_axis { size[1] } else { size[0] }, ppi).max(1e-9); // The top ruler runs along document x, which pixel aspect correction stretches. let zoom = if y_axis { xf.zoom } else { xf.zoom_x() }; @@ -356,9 +360,16 @@ fn ruler_label(v: f64, step: f64, whole: bool) -> String { if step >= 1.0 || whole { format!("{}", v.round() as i64) } else { crate::widgets::fmt_num2(v) } } -/// Rulers along the top and left of `full` (the canvas rect before `content_rect`), with the -/// pointer position marked; dragging out of a ruler creates a guide. -pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &ViewXform) { +/// The rulers of `doc`'s view in `full`: background, ticks and labels from its zero point. +/// Returns the top, left and corner rects, the painter, the zero point and the minor tick sizes. +#[allow(clippy::type_complexity)] +fn paint( + app: &PhotocraftApp, + ui: &egui::Ui, + full: Rect, + xf: &ViewXform, + doc: &photocraft_doc::Document, +) -> (Rect, Rect, Rect, egui::Painter, [f64; 2], [f64; 2]) { let t = Tokens::get(ui.ctx()); let top = Rect::from_min_max(pos2(full.left() + RULER, full.top()), pos2(full.right(), full.top() + RULER)); let left = Rect::from_min_max(pos2(full.left(), full.top() + RULER), pos2(full.left() + RULER, full.bottom())); @@ -376,11 +387,11 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: & let unit = app.session.prefs().units_and_rulers.rulers; let whole = unit == Unit::Pixels; // The zero point (#2955): rulers read 0 there and count the distance from it. - let origin = app.session.active().map_or([0.0, 0.0], |d| d.doc.ruler_origin); + let origin = doc.ruler_origin; let mut ticks = [1.0; 2]; for vertical in [false, true] { let p = p.with_clip_rect(if vertical { left } else { top }); - let (px_per_unit, step) = ruler_scale(app, xf, vertical); + let (px_per_unit, step) = ruler_scale_of(app, Some(doc), xf, vertical); ticks[usize::from(vertical)] = step * px_per_unit / 10.0; let (u0, u1) = if vertical { ruler_range(xf, left.left_top(), left.left_bottom(), 1, px_per_unit, origin) @@ -393,9 +404,10 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: & let c = at(v); if vertical { p.line_segment([pos2(left.right() - RULER, c), pos2(left.right(), c)], tick); - // Labels stacked, as in Photoshop. + // Labels stacked, as in Photoshop, each character centred in the ruler's width + // (a narrow "1" used to hug the left edge while a "0" filled the strip). for (i, ch) in ruler_label(v, step, whole).chars().enumerate() { - p.text(pos2(left.left() + 3.0, c + 2.0 + i as f32 * 8.5), Align2::LEFT_TOP, ch, font.clone(), t.text_dim); + p.text(pos2(left.left() + RULER * 0.5, c + 2.0 + i as f32 * 8.5), Align2::CENTER_TOP, ch, font.clone(), t.text_dim); } } else { p.line_segment([pos2(c, top.bottom() - RULER), pos2(c, top.bottom())], tick); @@ -413,6 +425,23 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: & v += step; } } + (top, left, corner, p, origin, ticks) +} + +/// Rulers for a document view that isn't the active one (another tile of Window › Arrange, a +/// floating window): shown as the active view's are, but guides and the zero point are dragged +/// in the active view (#6017). +pub fn paint_rulers(app: &PhotocraftApp, ui: &egui::Ui, full: Rect, xf: &ViewXform, doc: &photocraft_doc::Document) { + paint(app, ui, full, xf, doc); +} + +/// Rulers along the top and left of `full` (the canvas rect before `content_rect`), with the +/// pointer position marked; dragging out of a ruler creates a guide. +pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &ViewXform) { + let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; + let (top, left, corner, p, origin, ticks) = paint(app, ui, full, xf, &doc); + let t = Tokens::get(ui.ctx()); + let unit = app.session.prefs().units_and_rulers.rulers; // Pointer position markers. if let Some(h) = ui.ctx().pointer_hover_pos().filter(|h| full.contains(*h)) { let m = Stroke::new(1.0, t.text); @@ -534,6 +563,28 @@ mod tests { assert!(failures.is_empty(), "ruler drawing overlaps the origin corner: {failures:?}"); } + /// #7314: the stacked characters of the left ruler's labels are centred on the strip, so a + /// narrow "1" lines up with a wide "0". + #[test] + fn left_ruler_label_characters_are_centred() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + let (mut h, full, _) = ruler_harness(app); + h.run_steps(2); + let centres: Vec = h + .output() + .shapes + .iter() + .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some(t) } else { None }) + .filter(|t| t.pos.x < full.min.x + RULER && t.pos.y > full.min.y + RULER) + .map(|t| t.pos.x + t.galley.size().x * 0.5) + .collect(); + assert!(centres.len() > 2, "the left ruler draws labels: {centres:?}"); + for c in ¢res { + assert!((c - (full.min.x + RULER * 0.5)).abs() < 0.01, "character centre {c} in {centres:?}"); + } + } + #[test] fn shift_snaps_the_zero_point_to_ruler_ticks_from_the_current_origin() { assert_eq!(snap_px_to_tick(47.0, 0.0, 10.0), 50.0); @@ -829,7 +880,17 @@ mod tests { fn command_drag_over_a_guide_moves_the_guide_with_any_tool() { use crate::canvas::{ToolEvent, tool_event}; use crate::state::Tool; - for (tool, locked) in [(Tool::Brush, false), (Tool::RectMarquee, false), (Tool::Lasso, false), (Tool::MagicWand, false), (Tool::RectMarquee, true)] { + for (tool, locked) in [ + (Tool::Brush, false), + (Tool::Eraser, false), + (Tool::Gradient, false), + (Tool::Frame, false), + (Tool::Artboard, false), + (Tool::RectMarquee, false), + (Tool::Lasso, false), + (Tool::MagicWand, false), + (Tool::RectMarquee, true), + ] { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 80, "height": 60, "background": "transparent"})).unwrap(); app.sync_views(); diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rs index c947afc9b6..3396dfcdd5 100644 --- a/crates/ui-egui/src/save_identity_tests.rs +++ b/crates/ui-egui/src/save_identity_tests.rs @@ -254,3 +254,21 @@ fn save_settings_start_at_the_opened_files_encoding() { app.open_bytes("art.webp", &lossless).unwrap(); assert!(app.save_settings().webp_lossless); } + +/// A browser download is only requested: the document takes the name but keeps its unsaved +/// changes, so the leave-page guard stays armed (#4962). A confirmed write still saves it. +#[test] +fn unconfirmed_download_names_the_document_but_keeps_it_unsaved() { + assert_eq!(crate::saved_revision_after_write(true, 7, 3), 7); + assert_eq!(crate::saved_revision_after_write(false, 7, 3), 3); + let mut app = app(); + app.services.write_unconfirmed = true; + let (_, _, revision, saved) = identity(&app); + app.save_as(Some("download.psd".into())).unwrap(); + assert_eq!(identity(&app), ("download.psd".into(), Some("download.psd".into()), revision, saved)); + assert!(app.session.active().unwrap().is_dirty()); + assert!(app.has_unsaved_work()); + app.services.write_unconfirmed = false; + app.save_as(Some("download.psd".into())).unwrap(); + assert!(!app.has_unsaved_work()); +} diff --git a/crates/ui-egui/src/shortcut_dispatch.rs b/crates/ui-egui/src/shortcut_dispatch.rs index 4336315dba..ffc1a7f6e5 100644 --- a/crates/ui-egui/src/shortcut_dispatch.rs +++ b/crates/ui-egui/src/shortcut_dispatch.rs @@ -215,7 +215,9 @@ fn key_owner(app: &PhotocraftApp, ctx: &egui::Context) -> (bool, usize, bool, bo } /// Keys whose shortcuts follow the key's position, as in Photoshop: ⇧⌘. is ⇧⌘> on a US layout, -/// but types `:` on Nordic and German ones, so its character would never match. +/// but types `:` on Nordic and German ones, so its character would never match. Only ⌘ shortcuts +/// follow the position: a plain `,` or `;` binding (brush hardness on AZERTY, where `;` sits on the +/// US comma key) must match the character typed. const POSITIONAL: [Key; 2] = [Key::Period, Key::Comma]; /// Dispatch this frame's shortcut presses in the order they arrived (⌘Z then ⌘S undoes, then @@ -236,7 +238,7 @@ pub fn dispatch_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, focus: Foc egui::Event::Key { key, physical_key, pressed: true, modifiers, .. } => { let by_position = physical_key .filter(|p| POSITIONAL.contains(p)) - .and_then(|p| table.iter().find(|(_, sc)| sc.logical_key == p && key_matches(sc, p, *modifiers))); + .and_then(|p| table.iter().find(|(_, sc)| sc.modifiers.command && sc.logical_key == p && key_matches(sc, p, *modifiers))); by_position.or_else(|| table.iter().find(|(_, sc)| key_matches(sc, *key, *modifiers))).map(|(id, _)| (id.clone(), *key == Key::Tab)) } _ => None, diff --git a/crates/ui-egui/src/shortcut_dispatch/tests.rs b/crates/ui-egui/src/shortcut_dispatch/tests.rs index 2827671a84..00f1a120a3 100644 --- a/crates/ui-egui/src/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/shortcut_dispatch/tests.rs @@ -804,3 +804,23 @@ fn type_size_keys_follow_key_position_and_the_typed_selection() { assert_eq!(logged(&h), ["type.decreaseSize"]); assert_eq!(sizes(&h), [(2, base), (3, base + 2.0)], "only the selected \"He\" shrinks"); } + +/// AZERTY: `;` sits on the US comma key and `,` on the US M key. Plain `,` / `;` bindings (brush +/// hardness) must match the character typed, not the key's position, or `;` fires `,`'s command. +#[test] +fn plain_comma_and_semicolon_bindings_follow_the_typed_character_on_azerty() { + let mut h = harness(); + h.state_mut().session.edit_prefs(|p| { + p.shortcuts.insert("tools.decreaseBrushHardness".into(), ",".into()); + p.shortcuts.insert("tools.increaseBrushHardness".into(), ";".into()); + }); + let tap = |h: &mut Harness<'_, PhotocraftApp>, key, physical| { + h.event(egui::Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.event(egui::Event::Key { key, physical_key: Some(physical), pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + }; + tap(&mut h, egui::Key::Semicolon, egui::Key::Comma); + assert_eq!(logged(&h), ["tools.increaseBrushHardness"]); + tap(&mut h, egui::Key::Comma, egui::Key::M); + assert_eq!(logged(&h), ["tools.decreaseBrushHardness"]); +} diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index e8645a1511..1ad8d6d92a 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -233,6 +233,10 @@ fn clipboard_press(e: &egui::Event, mods: Modifiers, is_windows: bool) -> Option /// (the key-down's default action) arrives as `Event::Paste` in the same frame. A clipboard event /// right after its own ⌘ key press is that press, not a second one (#2638). /// +/// With an image on the clipboard the V release is all that reaches us, and ⌘ is often let go +/// first: a V release whose press never arrived, after ⌘ was held and before any other key, is +/// that swallowed ⌘V too (#6329). Releasing in either order then pastes. +/// /// Ctrl+Insert copies and Shift+Insert pastes: egui-winit maps them on Windows (a Shift+Insert /// release without a paste event pastes the image, like ⌘V), and we map them here on Linux. pub fn clipboard_keys(ctx: &egui::Context, typing: bool, raw: &mut egui::RawInput) { @@ -279,18 +283,31 @@ pub fn clipboard_keys(ctx: &egui::Context, typing: bool, raw: &mut egui::RawInpu return; } let seen = egui::Id::new("pc-paste-key-seen"); + // A V press without ⌘ that reached us (the Move tool's key): its release is not a paste. + let plain_v = egui::Id::new("pc-plain-v-down"); + // ⌘ was held since the last key press without it: a swallowed ⌘V can be under way. + let command_lately = egui::Id::new("pc-paste-command-lately"); // The modifiers held at each event: last frame's, updated as the events report changes. let mut mods = ctx.input(|i| i.modifiers); + if mods.command { + ctx.data_mut(|d| d.insert_temp(command_lately, true)); + } let mut out = Vec::with_capacity(raw.events.len()); // The last ⌘C/⌘X/⌘V press this frame whose clipboard event hasn't arrived (yet). let mut unpaired: Option = None; for e in raw.events.drain(..) { if let egui::Event::ModifiersChanged(m) | egui::Event::Key { modifiers: m, .. } = &e { mods = *m; + if mods.command { + ctx.data_mut(|d| d.insert_temp(command_lately, true)); + } } if let Some((key, held)) = clipboard_press(&e, mods, cfg!(target_os = "windows")) { if key == Key::V { - ctx.data_mut(|d| d.insert_temp(seen, true)); + ctx.data_mut(|d| { + d.insert_temp(seen, true); + d.remove_temp::(plain_v); + }); } if unpaired.take_if(|k| *k == key).is_none() { out.push(press(key, held)); @@ -304,15 +321,32 @@ pub fn clipboard_keys(ctx: &egui::Context, typing: bool, raw: &mut egui::RawInpu egui::Event::Key { key: key @ (Key::C | Key::X | Key::V), pressed: true, modifiers, .. } if modifiers.command => { unpaired = Some(*key); if *key == Key::V { - ctx.data_mut(|d| d.insert_temp(seen, true)); + ctx.data_mut(|d| { + d.insert_temp(seen, true); + d.remove_temp::(plain_v); + }); } } + egui::Event::Key { key, pressed: true, modifiers, .. } if !modifiers.command => { + ctx.data_mut(|d| { + d.remove_temp::(command_lately); + if *key == Key::V { + d.insert_temp(plain_v, true); + } + }); + } // A paste key's release ends that press, with or without ⌘ still held (else a stale // mark would swallow the next image paste); without a press it is the paste itself. egui::Event::Key { key: key @ (Key::V | Key::Insert), pressed: false, modifiers, .. } => { let had_press = ctx.data_mut(|d| d.remove_temp::(seen)).unwrap_or(false); + let had_plain_press = *key == Key::V && ctx.data_mut(|d| d.remove_temp::(plain_v)).unwrap_or(false); + // Taken: one swallowed ⌘V is one paste. + let lately = *key == Key::V && ctx.data_mut(|d| d.remove_temp::(command_lately)).unwrap_or(false); let held = match key { Key::V if modifiers.command => Some(*modifiers), + // ⌘ let go before V: the press egui-winit swallowed was ⌘V (#6329). The web + // always forwards the key-down, so there a lone release is no paste. + Key::V if lately && !had_plain_press && !cfg!(target_arch = "wasm32") => Some(Modifiers::COMMAND), Key::Insert if cfg!(target_os = "windows") && modifiers.shift && !modifiers.ctrl => Some(Modifiers::COMMAND), _ => None, }; @@ -382,11 +416,15 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::liquify_ui::keys(app, ctx); } } + // The Content-Aware Fill workspace likewise. + if app.distort.caf.is_some() && !ctx.text_edit_focused() { + crate::caf_ui::keys(app, ctx); + } use crate::shortcut_dispatch::{Focus, dispatch_pressed}; let focus = Focus::of(ctx); // Dialogs (and Liquify's panel while one of its controls has focus) keep canvas zoom; a // focused text field keeps its keys. - let liquify_focus = app.distort.liquify.is_some() && focus != Focus::None; + let liquify_focus = (app.distort.liquify.is_some() || app.distort.caf.is_some()) && focus != Focus::None; if liquify_focus || !app.ui.dialogs.is_empty() || app.discard.is_some() { if focus != Focus::Text { nav_keys(app, ctx); @@ -580,7 +618,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { return; } } - if !app.ui.polygon.is_empty() || app.ui.crop_rect.is_some() { + // An open options bar popup (the Crop Ratio list, the overlay and gear menus) takes the keys + // first: Esc closes it, and neither key reaches the crop beneath (#7386). Its id is kept in + // memory from the last frame; `ctx.any_popup_open` only sees this frame's, drawn later. + if (!app.ui.polygon.is_empty() || app.ui.crop_rect.is_some()) && !egui::Popup::is_any_open(ctx) { if pressed(Key::Enter) { if !app.ui.polygon.is_empty() { crate::canvas::commit_polygon(app); @@ -589,7 +630,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { } return; } - if pressed(Key::Escape) { + // In a full screen mode, the Crop tool's untouched default frame (Straighten off) has nothing to cancel: cancelling only + // makes the next one, so Esc goes on to leave full screen (#7315). + let untouched = app.ui.view.screen_mode != "standard" && app.ui.polygon.is_empty() && app.crop.default_frame && !crate::crop_straighten::mode(app); + if !untouched && pressed(Key::Escape) { app.ui.polygon.clear(); app.ui.polygon_mode.clear(); crate::crop_ui::cancel(app); @@ -1007,6 +1051,37 @@ mod tests { assert_eq!(presses(vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), key(Key::V, false, Modifiers::COMMAND)]), 1, "image paste"); } + /// #6329: with an image on the clipboard egui-winit swallows the ⌘V press and sends only the V + /// release, which carries no ⌘ when ⌘ was let go first: that release still pastes, once. A V + /// pressed and released on its own (the Move tool) never pastes. + #[test] + fn an_image_paste_released_after_command_still_pastes() { + let key = |key, pressed, modifiers| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }; + let pastes = |ctx: &egui::Context, events: Vec| { + let mut r = egui::RawInput { events, ..Default::default() }; + clipboard_keys(ctx, false, &mut r); + r.events.iter().filter(|e| matches!(e, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command)).count() + }; + let none = Modifiers::NONE; + // ⌘ down, (the swallowed V press,) ⌘ up, V up: in one frame or over several. + let ctx = egui::Context::default(); + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), egui::Event::ModifiersChanged(none), key(Key::V, false, none)]), 1); + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND)]), 0); + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(none)]), 0); + assert_eq!(pastes(&ctx, vec![key(Key::V, false, none)]), 1, "released after ⌘"); + // Once: another lone release without ⌘ held again doesn't paste again. + assert_eq!(pastes(&ctx, vec![key(Key::V, false, none)]), 0); + // A plain V tap after ⌘ was used is the Move tool, not a paste. + let ctx = egui::Context::default(); + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), egui::Event::ModifiersChanged(none)]), 0); + assert_eq!(pastes(&ctx, vec![key(Key::V, true, none), key(Key::V, false, none)]), 0); + // Without ⌘ at all, a lone V release is nothing. + let ctx = egui::Context::default(); + assert_eq!(pastes(&ctx, vec![key(Key::V, false, none)]), 0); + // Released with ⌘ still held it pastes as before. + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), key(Key::V, false, Modifiers::COMMAND)]), 1); + } + /// #2638: on the web one ⌘V brings its key press and the browser's paste event; that is one paste. #[test] fn web_paste_key_and_paste_event_are_one_press() { diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs index 3c48e041f4..d0e0cfdec4 100644 --- a/crates/ui-egui/src/sizing.rs +++ b/crates/ui-egui/src/sizing.rs @@ -70,7 +70,7 @@ pub fn reset(f: &mut Map) { pub fn open(app: &mut PhotocraftApp, command: &str) -> Option { let unit = pref_unit(app.session.prefs().units_and_rulers.rulers); - let resample = pref_resample(app.session.prefs().general.image_interpolation); + let mut resample = pref_resample(app.session.prefs().general.image_interpolation); let pt_per_in = app.session.prefs().units_and_rulers.point_size.per_inch(); let d = &app.session.active()?.doc; let (w, h, res) = (d.size.width as f64, d.size.height as f64, d.resolution_dpi as f64); @@ -88,6 +88,12 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option { f.insert("width".into(), json!(w)); f.insert("height".into(), json!(h)); if command == "image.imageSize" { + // Indexed Color resamples with Nearest Neighbor only, as the command does (#6019). + let indexed = d.mode == photocraft_color::ColorMode::Indexed; + if indexed && resample != "automatic" { + resample = "nearest"; + } + f.insert("__indexed".into(), json!(indexed)); f.insert("__constrain".into(), json!(true)); f.insert("resolution".into(), json!(res)); f.insert("resample".into(), json!(resample)); @@ -321,6 +327,10 @@ fn image_size(ui: &mut egui::Ui, f: &mut Map) { ("bilinear".to_string(), tl!("Bilinear")), ("lanczos".to_string(), tl!("Lanczos (sharp)")), ]; + // Indexed Color: every other method blends colours the colour table doesn't have, + // which the command doesn't use and a save quantises away (#6019). + let indexed = f.get("__indexed").and_then(Value::as_bool) == Some(true); + let opts: Vec<_> = opts.into_iter().filter(|(k, _)| !indexed || k == "automatic" || k == "nearest").collect(); if crate::widgets::dropdown(ui, "is-resample", &mut cur, &opts, 200.0) { f.insert("resample".into(), json!(cur)); } @@ -515,6 +525,35 @@ mod tests { assert!(app.ui.dialogs.iter().any(|x| x.id == id), "reset leaves the dialog open"); } + /// #6019: on an Indexed Color document the dialog opens on, and offers only, Automatic and Nearest Neighbor. + #[test] + fn indexed_color_resamples_with_nearest_neighbor_only() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.session.execute("image.mode.indexedColor", json!({})).unwrap(); + for (pref, method) in [("bicubic", "nearest"), ("bicubicAutomatic", "automatic"), ("nearestNeighbor", "nearest")] { + app.session.execute("prefs.set", json!({"path": "general.imageInterpolation", "value": pref})).unwrap(); + let id = open(&mut app, "image.imageSize").unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(f.get("resample"), Some(&json!(method)), "{pref}"); + assert_eq!(f.get("__indexed"), Some(&json!(true))); + app.ui.close_dialog(id); + } + // The open list offers only Automatic and Nearest Neighbor. + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), "image.imageSize").unwrap(); + h.run_steps(3); + let combo = h.query_all_by_role(egui::accesskit::Role::ComboBox).find(|n| n.value().as_deref() == Some("Nearest Neighbor (hard edges)")); + combo.expect("the Resample list shows Nearest Neighbor").click(); + h.run_steps(3); + assert!(h.query_by_label_contains("Automatic").is_some(), "Automatic is offered"); + for gone in ["Bicubic", "Bilinear", "Lanczos", "Preserve Details"] { + assert!(h.query_by_label_contains(gone).is_none(), "{gone} is not offered for Indexed Color"); + } + } + /// The dialog starts on Preferences › General › Image Interpolation: Bicubic Automatic opens /// as Automatic and the others as themselves (Bicubic Sharper used to open as Lanczos). #[test] diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rs index 7f49843c53..2acc77ceaf 100644 --- a/crates/ui-egui/src/smart_ui.rs +++ b/crates/ui-egui/src/smart_ui.rs @@ -314,8 +314,12 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm: /// filter (`layer.smartFilter.setParams`, see [`confirm_command`]) instead of adding another. fn edit_filter(app: &mut PhotocraftApp, id: u64, layer: u64, index: usize, params: &Value) { if let Some(d) = app.ui.dialog_mut(id) { - // The live preview would stack a second copy of the filter on the smart object. - d.fields.remove("__preview"); + // A filter's live preview runs `layer.smartFilter.setParams` on the proxy, as OK does + // (`canvas::ensure_filter_preview`, #6324). An adjustment's previews on the layer and + // would stack a second copy of it on the smart object. + if d.fields.contains_key("__adjust") { + d.fields.remove("__preview"); + } d.fields.insert("__smartFilter".into(), json!({"layer": layer, "index": index})); if let Value::Object(p) = params { for (k, v) in p { @@ -327,6 +331,12 @@ fn edit_filter(app: &mut PhotocraftApp, id: u64, layer: u64, index: usize, param } } +/// The command a filter dialog's live preview runs ([`confirm_command`]'s): `layer.smartFilter.setParams` +/// while it edits a smart filter (#6324), else `command`. +pub fn preview_command<'a>(fields: &serde_json::Map, command: &'a str) -> &'a str { + if fields.contains_key("__smartFilter") { "layer.smartFilter.setParams" } else { command } +} + /// The command a confirmed filter dialog runs: smart-filter edits update the recorded filter. pub fn confirm_command(fields: &serde_json::Map, command: String, params: Value) -> (String, Value) { match fields.get("__smartFilter") { @@ -452,4 +462,48 @@ mod tests { assert_eq!(sm.smart_filters[0].params.get("brightness").and_then(Value::as_f64), Some(40.0)); assert_eq!(sm.smart_filters[0].params.get("contrast").and_then(Value::as_f64), Some(-10.0)); } + + /// #6324: a smart filter opened for editing previews, and its preview replaces the filter in + /// the stack (as OK does) instead of stacking a second one. + #[test] + fn an_edited_smart_filter_previews_what_ok_gives() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.stroke", json!({"width": 4, "color": "#000000", "location": "inside"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let id = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 1.0})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.background_jobs = false; + let smart = |app: &PhotocraftApp, doc: &Document| match &doc.layer(LayerId(id)).unwrap().content { + LayerContent::Smart(sm) => sm.clone(), + other => panic!("expected a smart object, got {other:?} ({})", app.ui.status), + }; + let sm = smart(&app, &app.session.active().unwrap().doc); + open_editor(&mut app, &egui::Context::default(), id, &sm, 0); + let d = app.ui.dialogs.last_mut().expect("the filter's dialog opened"); + assert_eq!(d.fields.get("__preview"), Some(&json!(true)), "the dialog previews"); + d.fields.insert("radius".into(), json!(6.0)); + let dialog = d.id; + + crate::canvas::ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("a preview"); + let preview = app.filter_preview.as_ref().unwrap(); + assert_eq!(preview.key.command, "layer.smartFilter.setParams"); + // The dialog's own preview window matches it to the dialog by that command. + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(preview_command(fields, "filter.blur.gaussianBlur"), preview.key.command); + assert_eq!(preview_command(&serde_json::Map::new(), "filter.blur.gaussianBlur"), "filter.blur.gaussianBlur"); + let shown = preview.result.clone().expect("the preview's document"); + let filters = smart(&app, &shown).smart_filters; + assert_eq!(filters.len(), 1, "the edited filter is replaced, not stacked"); + assert_eq!(filters[0].params.get("radius").and_then(Value::as_f64), Some(6.0)); + assert_eq!(smart(&app, &app.session.active().unwrap().doc).smart_filters[0].params["radius"], json!(1.0), "the document is untouched"); + + crate::dialogs::confirm(&mut app, dialog).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!(smart(&app, doc).smart_filters.len(), 1); + assert!(photocraft_compose::flatten(&shown).px == photocraft_compose::flatten(doc).px, "OK gives what the preview showed"); + } } diff --git a/crates/ui-egui/src/solid_fill_ui.rs b/crates/ui-egui/src/solid_fill_ui.rs index 2ae44d50c8..5d9112abab 100644 --- a/crates/ui-egui/src/solid_fill_ui.rs +++ b/crates/ui-egui/src/solid_fill_ui.rs @@ -30,6 +30,36 @@ pub(crate) fn open(app: &mut PhotocraftApp) -> Option { Some(color_picker_ui::open_for_command(app, "Color Picker (Solid Color)", color.to_rgb(), cmds::SET, params)) } +/// Creating a Solid Color fill is transactional: the document is unchanged until OK. +/// The picker is seeded with the foreground colour, matching the engine's default. +pub(crate) fn open_new(app: &mut PhotocraftApp) -> Option { + let document = app.session.active()?.doc.id.0; + let foreground = app.session.tools.foreground; + Some(color_picker_ui::open_for_command( + app, + "Color Picker (Solid Color)", + [foreground[0], foreground[1], foreground[2]], + "layer.newFillLayer.solidColor", + json!({"document": document}), + )) +} + +/// A creation picker is distinct from the editor opened by a fill layer's thumbnail. +pub(crate) fn owns_new(f: &Map) -> bool { + f.get("__command").and_then(Value::as_str) == Some("layer.newFillLayer.solidColor") + && f.get("__params").and_then(|p| p.get("document")).and_then(Value::as_u64).is_some() +} + +pub(crate) fn confirm_new(app: &mut PhotocraftApp, f: &Map) -> Result { + let expected = f.get("__params").and_then(|p| p.get("document")).and_then(Value::as_u64).ok_or("missing Solid Color document")?; + let st = app.session.active().ok_or("no document open")?; + if st.doc.id.0 != expected { + return Err("the target document is no longer active".into()); + } + let color = f.get("color").and_then(Value::as_str).ok_or("missing Solid Color colour")?; + app.run("layer.newFillLayer.solidColor", json!({"color": color})) +} + pub(crate) fn owns(f: &Map) -> bool { f.get("__command").and_then(Value::as_str) == Some(cmds::SET) } diff --git a/crates/ui-egui/src/solid_fill_ui/tests.rs b/crates/ui-egui/src/solid_fill_ui/tests.rs index 9b919be934..3317875153 100644 --- a/crates/ui-egui/src/solid_fill_ui/tests.rs +++ b/crates/ui-egui/src/solid_fill_ui/tests.rs @@ -41,6 +41,82 @@ fn row(h: &Harness<'_, PhotocraftApp>, id: LayerId) -> crate::layer_row_ui::RowR crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == id.0).unwrap() } +#[test] +fn new_solid_color_from_menu_cancel_keeps_document_and_history_unchanged() { + let (mut h, _) = harness(1.0); + let ctx = h.ctx.clone(); + let app = h.state_mut(); + let before = app.session.active().unwrap().doc.clone(); + let active = app.session.active().unwrap().active_layer; + let steps = app.session.active().unwrap().history.entries().len(); + + let opened = crate::menus::invoke(app, &ctx, "layer.newFillLayer.solidColor", json!({})).unwrap(); + assert!(opened.get("layer").is_none(), "no layer exists until OK"); + let dialog = opened["dialog"].as_u64().unwrap(); + let picker = app.ui.dialogs.last().unwrap(); + assert_eq!(picker.id, dialog); + assert!(owns_new(&picker.fields), "new Solid Color fill opens the shared Color Picker"); + assert_eq!(picker.fields["__params"]["document"], before.id.0); + assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.entries().len(), steps); + + app.ui.dialog_mut(dialog).unwrap().fields.insert("color".into(), json!("#ff8800")); + crate::dialogs::cancel(app, dialog).unwrap(); + assert!(app.ui.dialogs.iter().all(|d| d.id != dialog)); + assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc), "Cancel must not create or delete a layer"); + assert_eq!(app.session.active().unwrap().active_layer, active); + assert_eq!(app.session.active().unwrap().history.entries().len(), steps, "Cancel must not record a history entry"); +} + +#[test] +fn new_solid_color_from_menu_ok_creates_one_layer_with_chosen_or_default_color() { + let (mut h, _) = harness(1.0); + let ctx = h.ctx.clone(); + let app = h.state_mut(); + let steps = app.session.active().unwrap().history.entries().len(); + + // OK with the initial foreground colour still creates the fill layer. + let first = crate::menus::invoke(app, &ctx, "layer.newFillLayer.solidColor", json!({})).unwrap(); + let created = crate::dialogs::confirm(app, first["dialog"].as_u64().unwrap()).unwrap(); + let id = LayerId(created["layer"].as_u64().unwrap()); + assert!(matches!(app.session.active().unwrap().doc.layer(id).unwrap().content, LayerContent::Fill(Fill::Solid(_)))); + assert_eq!(app.session.active().unwrap().history.entries().len(), steps + 1); + + let second = crate::menus::invoke(app, &ctx, "layer.newFillLayer.solidColor", json!({})).unwrap(); + let dialog = second["dialog"].as_u64().unwrap(); + app.ui.dialog_mut(dialog).unwrap().fields.insert("color".into(), json!("#ff8800")); + let created = crate::dialogs::confirm(app, dialog).unwrap(); + let id = LayerId(created["layer"].as_u64().unwrap()); + let LayerContent::Fill(Fill::Solid(color)) = app.session.active().unwrap().doc.layer(id).unwrap().content else { + panic!("expected the newly created Solid Color fill"); + }; + assert_eq!(color.to_rgba8()[..3], [255, 136, 0]); + assert_eq!(app.session.active().unwrap().active_layer, Some(id)); + assert_eq!(app.session.active().unwrap().history.entries().len(), steps + 2); + + let dialogs = app.ui.dialogs.len(); + let explicit = crate::menus::invoke(app, &ctx, "layer.newFillLayer.solidColor", json!({"color": "#123456"})).unwrap(); + assert!(explicit["layer"].as_u64().is_some()); + assert!(explicit.get("dialog").is_none()); + assert_eq!(app.ui.dialogs.len(), dialogs, "parameterised creation stays non-interactive"); + assert_eq!(app.session.active().unwrap().history.entries().len(), steps + 3); +} + +#[test] +fn new_solid_color_picker_rejects_a_different_active_document() { + let (mut h, _) = harness(1.0); + let ctx = h.ctx.clone(); + let app = h.state_mut(); + let dialog = crate::menus::invoke(app, &ctx, "layer.newFillLayer.solidColor", json!({})).unwrap()["dialog"].as_u64().unwrap(); + app.ui.dialog_mut(dialog).unwrap().fields.insert("color".into(), json!("#ff8800")); + app.run("file.new", json!({"width": 4, "height": 4})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.entries().len(); + assert!(crate::dialogs::confirm(app, dialog).is_err()); + assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.entries().len(), steps); +} + #[test] fn only_the_colour_thumbnail_opens_the_solid_fill_picker() { for ppp in [1.0, 2.0] { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5cbda434e7..974d3fde35 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -511,7 +511,9 @@ pub struct ToolOptions { pub tolerance: f32, pub contiguous: bool, pub anti_alias: bool, - pub sample_all_layers: bool, + /// Sample All Layers, kept per tool as in Photoshop (#5524). Stored under a new key, so the + /// single shared `sample_all_layers` of older preferences is ignored on load. + pub sample_all: SampleAllLayers, /// Object Selection › Object Finder: hovering highlights the object a click selects (#4087). pub object_finder: bool, /// Remove tool: the fill goes to a new layer above the target (Photoshop's Create a new layer). @@ -653,8 +655,8 @@ pub struct ToolOptions { /// Crop gear menu (#1919): Show Cropped Area and the crop shield. See `crop_shield`. #[serde(default)] pub crop_shield: crate::crop_shield::CropShield, - /// Magic Eraser opacity % (tolerance, anti-alias, contiguous and sample-all are shared with the - /// Magic Wand and Paint Bucket). + /// Magic Eraser opacity % (tolerance, anti-alias and contiguous are shared with the Magic Wand + /// and Paint Bucket). pub magic_eraser_opacity: f32, /// Background Eraser: sampling (continuous | once | backgroundSwatch), limits (discontiguous | /// contiguous | findEdges), tolerance % and Protect Foreground Color. @@ -761,13 +763,60 @@ fn default_eyedropper_sample() -> String { "all".into() } +/// Each tool's Sample All Layers (the Paint Bucket calls it All Layers). Photoshop keeps one per +/// tool, all off by default: turning it on for the Magic Wand must not leave Blur or Smudge +/// copying the composite onto the active layer (#5524). The Mixer Brush keeps its own with the +/// brush (`MixerSettings`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct SampleAllLayers { + pub magic_wand: bool, + pub quick_selection: bool, + pub object_selection: bool, + pub paint_bucket: bool, + pub magic_eraser: bool, + pub spot_healing: bool, + pub patch: bool, + pub content_aware_move: bool, + pub remove: bool, + pub blur: bool, + pub sharpen: bool, + pub smudge: bool, +} + +impl SampleAllLayers { + /// `tool`'s setting; false for a tool without the option. + pub fn get(mut self, tool: Tool) -> bool { + self.slot(tool).is_some_and(|v| *v) + } + + /// `tool`'s setting, or `None` for a tool without the option. + pub fn slot(&mut self, tool: Tool) -> Option<&mut bool> { + Some(match tool { + Tool::MagicWand => &mut self.magic_wand, + Tool::QuickSelection => &mut self.quick_selection, + Tool::ObjectSelection => &mut self.object_selection, + Tool::PaintBucket => &mut self.paint_bucket, + Tool::MagicEraser => &mut self.magic_eraser, + Tool::SpotHealing => &mut self.spot_healing, + Tool::Patch => &mut self.patch, + Tool::ContentAwareMove => &mut self.content_aware_move, + Tool::Remove => &mut self.remove, + Tool::Blur => &mut self.blur, + Tool::Sharpen => &mut self.sharpen, + Tool::Smudge => &mut self.smudge, + _ => return None, + }) + } +} + impl Default for ToolOptions { fn default() -> Self { Self { tolerance: 32.0, contiguous: true, anti_alias: true, - sample_all_layers: false, + sample_all: SampleAllLayers::default(), object_finder: true, remove_new_layer: false, remove_after_each_stroke: true, @@ -1054,6 +1103,9 @@ pub struct DockTabs { pub struct ColorPanelState { /// The panel edits the background colour (its chip was clicked), not the foreground. pub background: bool, + /// Color Picker › Only Web Colors, kept across opens like Photoshop (#4995). + #[serde(default)] + pub web_only: bool, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -1073,6 +1125,9 @@ pub struct UiState { /// Inline type editing session, if any. #[serde(default)] pub text_edit: Option, + /// Clock time in seconds when type cursor blink was last reset (e.g. on keypress/caret move). + #[serde(skip)] + pub caret_blink_time: f64, /// Tool to restore when an inline type edit session commits or cancels (e.g. Move tool, #1132). #[serde(skip)] pub text_edit_return_tool: Option, @@ -1307,6 +1362,7 @@ impl Default for UiState { spring: None, recent_files: Vec::new(), text_edit: None, + caret_blink_time: 0.0, text_edit_return_tool: None, type_transform: None, type_transform_pivot: None, @@ -1437,6 +1493,25 @@ impl UiState { mod tests { use super::*; + #[test] + fn sample_all_layers_is_per_tool_and_old_prefs_load() { + // The single shared flag of older preferences is dropped: every tool starts off (#5524). + let o: ToolOptions = serde_json::from_str(r#"{"sample_all_layers": true, "feather": 3.0}"#).unwrap(); + assert_eq!((o.sample_all, o.feather), (SampleAllLayers::default(), 3.0)); + let mut o = ToolOptions::default(); + o.sample_all.magic_wand = true; + let back: ToolOptions = serde_json::from_value(serde_json::to_value(&o).unwrap()).unwrap(); + assert!(back.sample_all.magic_wand && !back.sample_all.get(Tool::Blur)); + assert!(!back.sample_all.get(Tool::Brush), "a tool without the option reads false"); + let mut s = SampleAllLayers::default(); + assert!(s.slot(Tool::Brush).is_none()); + for t in [Tool::MagicWand, Tool::PaintBucket, Tool::Blur, Tool::Sharpen, Tool::Smudge, Tool::Remove] { + *s.slot(t).unwrap() = true; + assert!(s.get(t), "{t:?}"); + } + assert!(!s.get(Tool::QuickSelection)); + } + #[test] fn tool_names_parse() { assert_eq!(Tool::from_name("brush"), Some(Tool::Brush)); diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index a472a4125c..88f218c3ba 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -338,6 +338,38 @@ fn a_committed_stroke_refreshes_only_what_each_cache_had_not_shown() { assert_eq!(c.since(99), None, "not a key of this stroke"); } +/// A stroke that grows a layer with a Gradient Overlay lays the one gradient out again over the +/// whole layer (#4053): the canvas, which already showed the live stroke, still repaints where +/// the earlier strokes are, not just the new stroke's own pixels (it repainted nothing, leaving +/// one gradient per stroke). +#[test] +fn a_committed_stroke_repaints_a_gradient_overlay_over_the_whole_layer() { + let mut h = harness(); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.state_mut().run("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})).unwrap(); + h.state_mut().run("tools.setBrush", json!({"brush": {"size": 10, "hardness": 1.0}})).unwrap(); + let drag = |h: &mut Harness<'static, PhotocraftApp>, pts: &[(f32, f32)]| { + move_to(h, pts[0].0, pts[0].1); + button(h, pts[0].0, pts[0].1, true); + for (x, y) in &pts[1..] { + move_to(h, *x, *y); + } + let (x, y) = pts[pts.len() - 1]; + button(h, x, y, false); + h.run_steps(2); + }; + drag(&mut h, &[(20.0, 20.0), (30.0, 25.0), (40.0, 30.0)]); + drag(&mut h, &[(150.0, 60.0), (160.0, 70.0), (170.0, 80.0)]); + let app = h.state(); + let idx = app.session.active_index().unwrap(); + let st = app.session.active().unwrap(); + let c = app.committed_stroke.as_ref().expect("the commit took the live stroke's pixels"); + assert_eq!(c.revision, st.revision); + // A cache that showed the live stroke's last step. + let missed = crate::canvas::damage_since(app, idx, (st.revision - 1, c.last_key()), (st.revision, 0), 0, st.last_damage).unwrap(); + assert!(missed.contains(25, 25), "the gradient around the first stroke is repainted: {missed:?}"); +} + #[test] fn the_stroke_trace_times_each_frame_of_a_stroke_and_ends_on_release() { // The app's hooks around the canvas (`raw_input_hook` starts a frame, `ui` ends it); the diff --git a/crates/ui-egui/src/stroke_trail.rs b/crates/ui-egui/src/stroke_trail.rs index 6a5465ca7f..af09fca1c4 100644 --- a/crates/ui-egui/src/stroke_trail.rs +++ b/crates/ui-egui/src/stroke_trail.rs @@ -74,6 +74,13 @@ impl Trail { self.fed = points.len(); } + /// Stamp a whole new drag into the same mask (the Remove tool's waiting strokes, #6555): its + /// points are counted from its own start, not from where the previous drag ended. + pub fn feed_stroke(&mut self, points: &[[f64; 3]], diameter: f32) { + self.fed = 0; + self.feed(points, diameter); + } + /// Show the coverage the brush's own dabs leave along the drag, as the stroke commit renders /// it (`photocraft_paint::retouch::stroke_coverage`): soft edges for a soft brush, the size and /// shape each dab takes from pen pressure and dynamics. `brush` is asked for once, on the first @@ -224,6 +231,24 @@ mod tests { } } + #[test] + fn each_stroke_fed_whole_is_stamped_in_full() { + let mut t = Trail::new([300, 300]); + let strokes: [&[[f64; 3]]; 3] = [ + &[[50.0, 50.0, 1.0], [120.0, 50.0, 1.0], [200.0, 50.0, 1.0]], + &[[50.0, 120.0, 1.0], [120.0, 120.0, 1.0]], + &[[50.0, 200.0, 1.0], [80.0, 200.0, 1.0], [120.0, 200.0, 1.0], [160.0, 200.0, 1.0], [200.0, 200.0, 1.0], [260.0, 200.0, 1.0]], + ]; + for s in strokes { + t.feed_stroke(s, 10.0); + } + for (x, y) in [(50, 50), (85, 50), (199, 50), (50, 120), (85, 120), (119, 120), (50, 200), (65, 200), (100, 200), (259, 200)] { + assert_eq!(t.coverage(x, y), 255, "({x}, {y}) lies on a stroke"); + } + assert_eq!(t.coverage(50, 85), 0, "no capsule joins one stroke's end to the next one's start"); + assert_eq!(t.coverage(150, 160), 0); + } + #[test] fn hostile_points_and_huge_documents_are_safe() { let mut t = Trail::new([300_000, 2]); diff --git a/crates/ui-egui/src/tab_strip.rs b/crates/ui-egui/src/tab_strip.rs index 61650a1182..1419471f1f 100644 --- a/crates/ui-egui/src/tab_strip.rs +++ b/crates/ui-egui/src/tab_strip.rs @@ -54,8 +54,10 @@ pub struct StripOut { pub const CHEVRON_W: f32 = 18.0; /// Draw the » overflow button at `r`: hover tip `tip`, listing the tabs named by `labels` at the -/// indices in `overflow`. A picked index is left in `picked`. -pub fn overflow_button(ui: &mut Ui, id: egui::Id, r: Rect, tip: &str, labels: &[&str], overflow: &[usize], picked: &mut Option) { +/// indices in `overflow`, the `checked` one with a check mark as in the menu bar's menus. A picked +/// index is left in `picked`. +#[allow(clippy::too_many_arguments)] +pub fn overflow_button(ui: &mut Ui, id: egui::Id, r: Rect, tip: &str, labels: &[&str], overflow: &[usize], checked: Option, picked: &mut Option) { let t = Tokens::get(ui.ctx()); let resp = ui.interact(r, id, Sense::click()); let mut paint_ui = ui.new_child(egui::UiBuilder::new().max_rect(r)); @@ -69,9 +71,9 @@ pub fn overflow_button(ui: &mut Ui, id: egui::Id, r: Rect, tip: &str, labels: &[ egui::Popup::menu(&resp).show(|ui| { ui.set_min_width(140.0); for &i in overflow { - if let Some(name) = labels.get(i) - && ui.button(*name).clicked() - { + let Some(name) = labels.get(i) else { continue }; + let text = if checked.is_some() { format!("{} {name}", if checked == Some(i) { "✔" } else { " " }) } else { (*name).to_owned() }; + if ui.button(text).clicked() { *picked = Some(i); ui.close(); } @@ -161,7 +163,7 @@ fn tabs_in( if !f.overflow.is_empty() && f.overflow_width > 0.0 { let r = Rect::from_min_size(pos2(x, area.top()), vec2(f.overflow_width, area.height())); let mut picked = None; - overflow_button(ui, id.with("tab-overflow"), r, tl!("More panels"), translated_tabs, &f.overflow, &mut picked); + overflow_button(ui, id.with("tab-overflow"), r, tl!("More panels"), translated_tabs, &f.overflow, None, &mut picked); if let Some(i) = picked { out.clicked = true; *selected = i; @@ -358,7 +360,7 @@ mod tests { let mut picked = None; let input = egui::RawInput { events: vec![egui::Event::PointerMoved(rect.center())], ..Default::default() }; let mut output = ctx.run_ui(input, |ui| { - overflow_button(ui, ui.id().with("tiny-overflow"), rect, "More panels", &["Layers"], &[0], &mut picked); + overflow_button(ui, ui.id().with("tiny-overflow"), rect, "More panels", &["Layers"], &[0], None, &mut picked); }); output.textures_delta.clear(); let mut icons = 0; diff --git a/crates/ui-egui/src/targa_options_ui.rs b/crates/ui-egui/src/targa_options_ui.rs index c2161a0c9b..5a8b47d589 100644 --- a/crates/ui-egui/src/targa_options_ui.rs +++ b/crates/ui-egui/src/targa_options_ui.rs @@ -21,8 +21,9 @@ pub struct Prompt { /// Save a Copy: the document keeps its path and unsaved changes. pub copy: bool, /// The step the answered save is recorded as, so an action being recorded keeps it: - /// `file.saveAs` for Save As (#2032, even when a flat Targa is written as a copy) and - /// `file.saveACopy` for Save a Copy (#4373). + /// `file.saveAs` for Save As (#2032, even when a flat Targa is written as a copy), + /// `file.saveACopy` for Save a Copy (#4373), and `file.save` when File › Save confirmed the + /// document's own Targa (#3531), which plays back on the file the action is played on. pub record: &'static str, } @@ -46,7 +47,7 @@ pub fn bits_param(params: &serde_json::Value, cmd: &str) -> Result Result<(), String> { if app.save_options_open() { - return Err("Answer TIFF or Targa Options before starting another save".into()); + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); } let doc = app.active_doc_id()?; let bits = app.session.active().map_or(TgaBits::Bits24, |st| photocraft_io::tga_default_bits(&st.doc)); @@ -76,10 +77,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { }); cancel |= modal.should_close(); p.bits = bits; - if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels. + if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) { let Some(p) = app.targa_options.take() else { return }; let settings = ExportSettings { tga_bits: Some(p.bits), ..app.save_settings() }; - let step = serde_json::json!({"path": p.path, "tgaBits": p.bits.bits()}); + let mut step = if p.record == "file.save" { serde_json::json!({}) } else { serde_json::json!({"path": p.path}) }; + step["tgaBits"] = p.bits.bits().into(); let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy)); if written.is_ok() { // An action being recorded keeps the Save As or Save a Copy with this answer (#2032). diff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/tiff_options_ui.rs index febd5964cb..eed78830a1 100644 --- a/crates/ui-egui/src/tiff_options_ui.rs +++ b/crates/ui-egui/src/tiff_options_ui.rs @@ -65,7 +65,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { cancel |= modal.should_close(); p.discard_layers = discard; p.dont_ask_again = dont_ask; - if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels. + if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) { let Some(p) = app.tiff_options.take() else { return }; if p.dont_ask_again { app.session.edit_prefs(|prefs| prefs.file_handling.ask_before_saving_layered_tiff = false); diff --git a/crates/ui-egui/src/tone.rs b/crates/ui-egui/src/tone.rs index ba17755bd9..f02c108dbb 100644 --- a/crates/ui-egui/src/tone.rs +++ b/crates/ui-egui/src/tone.rs @@ -24,6 +24,9 @@ static EMPTY: [u32; 256] = [0; 256]; pub struct Histograms { pub tag: u64, pub ch: Vec<[u32; 256]>, + /// Photoshop's histogram cache level of a composite histogram: 1 when every document pixel + /// was counted, `n` when a proxy 2^(n-1) times smaller stood in; 0 for a gray plane's. + pub level: u32, } impl std::ops::Index for Histograms { @@ -76,6 +79,7 @@ fn isolate(layers: &mut [Layer], id: LayerId) -> bool { /// Histograms of `doc` as seen by `source`, in the channels of `space`. pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace) -> Histograms { + let mut level = 0; let mut h = vec![ [0u32; 256]; match space { @@ -100,14 +104,23 @@ pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace) } } HistSource::BelowLayer(_) | HistSource::Layer(_) => { - composite_bins(doc, source, space, &mut h); + level = composite_bins(doc, source, space, &mut h); } } - Histograms { tag: tag(source, space), ch: h } + Histograms { tag: tag(source, space), ch: h, level } } /// Bins of the composited image below (`BelowLayer`) or of one layer alone (`Layer`), in `space`. -fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, h: &mut [[u32; 256]]) { +/// Returns the cache level counted: 1 when every document pixel was counted, higher when a +/// downsampled proxy stood in (like Photoshop's histogram cache levels). +/// +/// The pixels are counted as they are, never blended: an area-averaged thumbnail invented greys +/// that aren't in the image wherever an edge fell inside one of its cells (#6538). Documents up to +/// [`photocraft_compose::PROXY_THUMBNAIL_PIXELS`] (and those a proxy can't reduce faithfully) are +/// composited in bands and counted exactly, which costs what the thumbnail did (it reduced the +/// same full composite). Larger ones count a nearest-neighbour proxy composite of about the old +/// thumbnail's work: it only holds values the layers have. +fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, h: &mut [[u32; 256]]) -> u32 { let mut d = doc.clone(); match source { HistSource::BelowLayer(hide) => { @@ -120,33 +133,87 @@ fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, h: &mut } HistSource::Channel { .. } => {} } - let img = photocraft_compose::thumbnail(&d, 384); + let longest = d.size.width.max(d.size.height); + let k = longest / 768; + let (d, level) = if k >= 2 && d.size.area() > photocraft_compose::PROXY_THUMBNAIL_PIXELS && photocraft_compose::proxy::proxy_faithful(&d) { + (photocraft_compose::proxy::proxy_document(&d, k), k.next_power_of_two().ilog2() + 1) + } else { + (d, 1) + }; + let _ = photocraft_compose::render_bands(&d, d.bounds(), 0, |band| -> Result<(), ()> { + #[cfg(not(target_arch = "wasm32"))] + let part = { + use rayon::prelude::*; + band.px + .par_chunks(64 * 1024) + .map(|px| { + let mut part = vec![[0u32; 256]; h.len()]; + count_pixels(px, space, &mut part); + part + }) + .reduce(|| vec![[0u32; 256]; h.len()], add_bins) + }; + #[cfg(target_arch = "wasm32")] + let part = { + let mut part = vec![[0u32; 256]; h.len()]; + count_pixels(&band.px, space, &mut part); + part + }; + for (dst, src) in h.iter_mut().zip(&part) { + for (a, b) in dst.iter_mut().zip(src) { + *a = a.saturating_add(*b); + } + } + Ok(()) + }); + level +} + +/// Bin-wise sum of two sets of histograms (saturating: a hostile canvas can exceed `u32`). +#[cfg(not(target_arch = "wasm32"))] +fn add_bins(mut a: Vec<[u32; 256]>, b: Vec<[u32; 256]>) -> Vec<[u32; 256]> { + for (dst, src) in a.iter_mut().zip(&b) { + for (x, y) in dst.iter_mut().zip(src) { + *x = x.saturating_add(*y); + } + } + a +} + +/// Counts straight-alpha composite pixels into `h` (one histogram per channel of `space`); +/// transparent pixels are skipped. +fn count_pixels(px: &[[f32; 4]], space: ToneSpace, h: &mut [[u32; 256]]) { let bin = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as usize; - for p in img.pixels.as_chunks::<4>().0 { - if p[3] == 0 { + let mut add = |c: usize, b: usize| { + if let Some(n) = h.get_mut(c).and_then(|ch| ch.get_mut(b)) { + *n = n.saturating_add(1); + } + }; + for p in px { + // Skips NaN alpha too. + if p[3].is_nan() || p[3] <= 0.0 { continue; } match space { ToneSpace::Rgb => { - for c in 0..3 { - h[c + 1][p[c] as usize] += 1; + let q = [p[0], p[1], p[2]].map(bin); + for (c, v) in q.iter().enumerate() { + add(c + 1, *v); } - h[0][((p[0] as u32 + p[1] as u32 + p[2] as u32) / 3) as usize] += 1; + add(0, (q[0] + q[1] + q[2]) / 3); } ToneSpace::Cmyk => { - let rgb = [p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0); - let ink = photocraft_color::convert::rgb_to_cmyk(rgb); + let ink = photocraft_color::convert::rgb_to_cmyk([p[0], p[1], p[2]].map(|v| v.clamp(0.0, 1.0))); for (c, v) in ink.iter().enumerate() { - h[c + 1][bin(1.0 - v)] += 1; + add(c + 1, bin(1.0 - v)); } - h[0][bin(1.0 - ink.iter().sum::() / 4.0)] += 1; + add(0, bin(1.0 - ink.iter().sum::() / 4.0)); } ToneSpace::Lab => { - let rgb = [p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0); - let l = photocraft_color::convert::srgb_to_lab(rgb); - h[0][bin(l[0] / 100.0)] += 1; - h[1][bin((l[1] + 128.0) / 255.0)] += 1; - h[2][bin((l[2] + 128.0) / 255.0)] += 1; + let l = photocraft_color::convert::srgb_to_lab([p[0], p[1], p[2]].map(|v| v.clamp(0.0, 1.0))); + add(0, bin(l[0] / 100.0)); + add(1, bin((l[1] + 128.0) / 255.0)); + add(2, bin((l[2] + 128.0) / 255.0)); } } } @@ -217,11 +284,17 @@ pub fn keep_after_commit(app: &mut PhotocraftApp, layer: LayerId, before: Option } } +/// Display scale for a 256-bin histogram: bar heights are `v / top` clamped to 1, linear +/// to the tallest bin like Photoshop. A percentile of the sorted bins degenerates on +/// sparse histograms (few occupied levels sort 0 into every low index), drawing tiny +/// counts as tall as the real peaks (#6574). +/// Extracted from [`draw_histogram`] so the scaling is unit-testable. +pub fn histogram_scale_top(h: &[u32; 256]) -> f32 { + h.iter().copied().max().unwrap_or(1).max(1) as f32 * 1.1 +} + pub fn draw_histogram(p: &egui::Painter, r: Rect, h: &[u32; 256], color: Color32) { - // Scale to a high percentile so a single spike (e.g. pure white) doesn't flatten the rest. - let mut sorted: Vec = h.to_vec(); - sorted.sort_unstable(); - let top = sorted.get(250).copied().unwrap_or(1).max(1) as f32 * 1.1; + let top = histogram_scale_top(h); let mut pts = vec![egui::pos2(r.left(), r.bottom())]; for (i, v) in h.iter().enumerate() { let x = r.left() + (i as f32 + 0.5) / 256.0 * r.width(); @@ -345,9 +418,8 @@ pub fn histogram_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } let Some((_, _, _, h)) = app.doc_hist.clone() else { return }; - let size = app.session.active().map_or(photocraft_doc::Size::new(0, 0), |s| s.doc.size); - // Statistics come from a downsampled cache (like Photoshop's cache levels). - let level = (size.width.max(size.height) as f32 / 384.0).max(1.0).log2().ceil() as u32 + 1; + // 1 when the statistics count every pixel; higher when a downsampled proxy stood in. + let level = h.level.max(1); let ch = channel_picker(ui, egui::Id::new("histogram-panel-ch"), "Channel:"); let w = ui.available_width(); let (r, _) = ui.allocate_exact_size(vec2(w, 100.0), Sense::hover()); @@ -377,7 +449,7 @@ pub fn histogram_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { (tl!("Mean:"), format!("{mean:.2}")), (tl!("Std Dev:"), format!("{:.2}", var.sqrt())), (tl!("Median:"), median.unwrap_or(0).to_string()), - (tl!("Pixels:"), (size.width as u64 * size.height as u64).to_string()), + (tl!("Pixels:"), n.to_string()), (tl!("Cache Level:"), level.to_string()), ] { ui.label(egui::RichText::new(k).color(t.text_dim).size(11.5)); @@ -452,6 +524,110 @@ mod tests { ); assert_ne!(tag(HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb), tag(HistSource::Layer(layer), ToneSpace::Rgb)); } + + /// #6574: bar heights scale linearly to the tallest bin. A 90/10 black/white + /// histogram draws the small bar at a ninth of the big one, not full height. + #[test] + fn histogram_scale_is_proportional_for_two_level_images() { + let mut h = [0u32; 256]; + h[0] = 100_000; + h[255] = 900_000; + let top = histogram_scale_top(&h); + let small = (h[0] as f32 / top).min(1.0); + let big = (h[255] as f32 / top).min(1.0); + assert!((small / big - 1.0 / 9.0).abs() < 0.02, "small/big = {}, top = {top}", small / big); + } + + /// #6574: a sparse histogram (few occupied levels) must not scale to a bin + /// index that is 0: the old `sorted.get(250)` degenerated to `top = 1.1`, + /// drawing a few hundred samples as tall as hundreds of thousands. + #[test] + fn histogram_scale_does_not_degenerate_on_sparse_histograms() { + let mut h = [0u32; 256]; + h[0] = 500_000; + h[128] = 300; + h[255] = 500_000; + let top = histogram_scale_top(&h); + assert!(top > h[128] as f32, "scale {top} must exceed the tiny middle bin"); + let tiny = (h[128] as f32 / top).min(1.0); + assert!(tiny < 0.05, "tiny bin draws near-flat, got {tiny}"); + } + + /// A white document with black filled over columns `0..split` (a layer above the background). + fn split_doc(w: u32, h: u32, split: u32, depth: Option) -> photocraft_engine::Session { + let mut s = photocraft_engine::Session::new(); + let mut p = json!({"width": w, "height": h}); + if let Some(bits) = depth { + p["depth"] = json!(bits); + } + s.execute("file.new", p).unwrap(); // white + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": split, "height": h})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s + } + + fn panel_histograms(s: &photocraft_engine::Session) -> Histograms { + compute_histograms(&s.active().unwrap().doc, HistSource::BelowLayer(LayerId(u64::MAX)), ToneSpace::Rgb) + } + + fn mean(h: &[u32; 256]) -> f64 { + let n: u64 = h.iter().map(|v| u64::from(*v)).sum(); + h.iter().enumerate().map(|(i, v)| i as f64 * f64::from(*v)).sum::() / n as f64 + } + + /// #6538: a black/white split counts only black and white, wherever the edge falls (the old + /// 384 px area-averaged thumbnail turned the cell holding the edge mid-grey), and counts + /// every pixel: cache level 1. + #[test] + fn split_image_histogram_counts_only_black_and_white() { + for (w, h, split) in [(1000, 1000, 334), (1000, 1000, 500), (1000, 600, 1), (777, 333, 389), (2000, 50, 1999), (64, 64, 32)] { + let s = split_doc(w, h, split, None); + let hist = panel_histograms(&s); + assert_eq!(hist.level, 1, "{w}x{h}: every pixel is counted"); + for c in 0..4 { + let stray: Vec<(usize, u32)> = hist[c].iter().copied().enumerate().filter(|&(i, v)| v > 0 && i != 0 && i != 255).collect(); + assert!(stray.is_empty(), "{w}x{h} split {split}, channel {c}: invented values {stray:?}"); + assert_eq!(u64::from(hist[c][0]), u64::from(split) * u64::from(h), "{w}x{h} split {split}: black pixels"); + assert_eq!(u64::from(hist[c][255]), u64::from(w - split) * u64::from(h), "{w}x{h} split {split}: white pixels"); + } + } + let half = panel_histograms(&split_doc(1000, 1000, 500, None)); + assert!((mean(&half[0]) - 127.5).abs() < 1e-9, "a 50/50 split has mean 127.5, got {}", mean(&half[0])); + } + + /// The same at 16 and 32 bits per channel: the count does not go through an 8-bit thumbnail. + #[test] + fn split_image_histogram_is_exact_at_high_bit_depths() { + for bits in [16, 32] { + let s = split_doc(1000, 400, 334, Some(bits)); + assert_eq!(s.active().unwrap().doc.depth.bits(), bits, "the document is {bits}-bit"); + let hist = panel_histograms(&s); + for c in 0..4 { + let stray: Vec<(usize, u32)> = hist[c].iter().copied().enumerate().filter(|&(i, v)| v > 0 && i != 0 && i != 255).collect(); + assert!(stray.is_empty(), "{bits}-bit channel {c}: invented values {stray:?}"); + assert_eq!(hist[c][0], 334 * 400); + assert_eq!(hist[c][255], 666 * 400); + } + } + } + + /// Above the exact-count size a nearest-neighbour proxy stands in (cache level > 1): it is + /// smaller, yet still only holds black and white. + #[test] + fn large_split_image_counts_a_nearest_proxy_without_inventing_greys() { + let s = split_doc(6000, 3000, 2001, None); + let hist = panel_histograms(&s); + assert!(hist.level > 1, "a proxy stood in, level {}", hist.level); + let n: u64 = hist[0].iter().map(|v| u64::from(*v)).sum(); + assert!(n > 0 && n < 6000 * 3000, "counted {n} proxy pixels"); + for c in 0..4 { + let stray: Vec<(usize, u32)> = hist[c].iter().copied().enumerate().filter(|&(i, v)| v > 0 && i != 0 && i != 255).collect(); + assert!(stray.is_empty(), "channel {c}: invented values {stray:?}"); + } + assert!((mean(&hist[0]) - 255.0 * 3999.0 / 6000.0).abs() < 1.0, "mean {}", mean(&hist[0])); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/tool_reset.rs b/crates/ui-egui/src/tool_reset.rs index 27e9622ab3..3c154d3a45 100644 --- a/crates/ui-egui/src/tool_reset.rs +++ b/crates/ui-egui/src/tool_reset.rs @@ -8,9 +8,10 @@ //! `ui.dialog.cancel` answer it); `{"confirmed": true}` skips it, for agents that already asked. //! //! What a tool's options are: [`ToolOptions`] is one struct, not one per tool, and a few fields -//! are shared by the tools that show them (Tolerance, Anti-alias, Contiguous and Sample All Layers -//! by the Magic Wand, Paint Bucket and Magic Eraser; Feather by the marquees and lassos; Strength -//! by Blur, Sharpen and Smudge). Resetting one of those tools resets the shared field too. +//! are shared by the tools that show them (Tolerance, Anti-alias and Contiguous by the Magic Wand, +//! Paint Bucket and Magic Eraser; Feather by the marquees and lassos; Strength by Blur, Sharpen and +//! Smudge). Resetting one of those tools resets the shared field too. Sample All Layers is kept per +//! tool, as in Photoshop, so resetting a tool resets only its own. //! [`reset_options`] lists the fields of each tool. The selection tools also go back to New //! Selection, and the painting tools (the ones with a brush in the options bar) get the default //! brush, keeping the colours. Tools without options (Hand, Rotate View, Ruler, Note, …) have @@ -113,9 +114,46 @@ fn is_selection_tool(tool: Tool) -> bool { /// Put `tool`'s fields of `o` back to their defaults. pub fn reset_options(o: &mut ToolOptions, tool: Tool) { + let keys = option_keys(tool); + if keys.is_empty() { + return; + } + let (Ok(Value::Object(mut cur)), Ok(Value::Object(d))) = (serde_json::to_value(&*o), serde_json::to_value(ToolOptions::default())) else { + return; + }; + for k in keys { + if let Some(v) = d.get(*k) { + cur.insert((*k).to_string(), v.clone()); + } + } + if let Ok(n) = serde_json::from_value(Value::Object(cur)) { + *o = n; + } + // Sample All Layers is each tool's own (#5524): only `tool`'s goes back. let d = ToolOptions::default(); + if let Some(all) = o.sample_all.slot(tool) { + *all = d.sample_all.get(tool); + } +} + +/// The serialized name of `tool`'s own Sample All Layers inside `sample_all`, if it has one: a +/// tool preset stores that one alone, not the other tools' (#5524, #7356). +pub fn sample_all_key(tool: Tool) -> Option { + let mut probe = crate::state::SampleAllLayers::default(); + *probe.slot(tool)? = true; + let Ok(Value::Object(m)) = serde_json::to_value(probe) else { return None }; + m.into_iter().find(|(_, v)| v.as_bool() == Some(true)).map(|(k, _)| k) +} + +/// The [`ToolOptions`] fields `tool` shows, by their serialized names: what Reset Tool resets and +/// what a tool preset made with + stores (#7356). +pub fn option_keys(tool: Tool) -> &'static [&'static str] { + // `reset!` names each field once; one that is misspelt or gone fails to compile. macro_rules! reset { - ($($f:ident),* $(,)?) => {{ $( o.$f = d.$f.clone(); )* }}; + ($($f:ident),* $(,)?) => {{ + let _ = |o: &ToolOptions| { $(let _ = &o.$f;)* }; + &[$(stringify!($f)),*] + }}; } match tool { Tool::Move => reset!(move_auto_select, move_target, move_show_transform), @@ -124,9 +162,9 @@ pub fn reset_options(o: &mut ToolOptions, tool: Tool) { Tool::SingleRowMarquee | Tool::SingleColumnMarquee => reset!(feather), Tool::Lasso | Tool::PolygonLasso => reset!(feather, anti_alias), Tool::MagneticLasso => reset!(feather, anti_alias, magnetic_width, magnetic_contrast, magnetic_frequency, magnetic_pressure), - Tool::MagicWand => reset!(tolerance, anti_alias, contiguous, sample_all_layers), - Tool::QuickSelection => reset!(sample_all_layers, enhance_edge), - Tool::ObjectSelection => reset!(sample_all_layers, enhance_edge, object_finder), + Tool::MagicWand => reset!(tolerance, anti_alias, contiguous), + Tool::QuickSelection => reset!(enhance_edge), + Tool::ObjectSelection => reset!(enhance_edge, object_finder), Tool::Crop => reset!( crop_ratio, crop_delete, @@ -144,23 +182,26 @@ pub fn reset_options(o: &mut ToolOptions, tool: Tool) { ), Tool::PerspectiveCrop => reset!(crop_width, crop_height, crop_resolution, crop_resolution_unit, perspective_crop_grid), Tool::Eyedropper => reset!(eyedropper_size, eyedropper_sample, eyedropper_ring), - Tool::Pencil => reset!(pencil_auto_erase), + Tool::Brush => reset!(brush_clear), + Tool::Pencil => reset!(pencil_auto_erase, pencil_clear), + Tool::Eraser => reset!(eraser_mode), + Tool::Remove => reset!(remove_new_layer, remove_after_each_stroke), Tool::BackgroundEraser => reset!(bg_sampling, bg_limits, bg_tolerance, bg_protect_fg), Tool::ColorReplacement => reset!(cr_mode, cr_sampling, cr_limits, cr_tolerance, cr_anti_alias), - Tool::MagicEraser => reset!(tolerance, anti_alias, contiguous, sample_all_layers, magic_eraser_opacity), + Tool::MagicEraser => reset!(tolerance, anti_alias, contiguous, magic_eraser_opacity), Tool::Gradient => reset!(gradient_style, gradient_reverse, gradient_dither, gradient_classic, gradient_blend_mode, fill_opacity), - Tool::PaintBucket => reset!(bucket_fill_pattern, fill_opacity, tolerance, anti_alias, contiguous, sample_all_layers), + Tool::PaintBucket => reset!(bucket_fill_pattern, fill_opacity, tolerance, anti_alias, contiguous), Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => reset!(type_font, type_style, type_size, type_aa, type_align), Tool::Zoom => reset!(zoom_scrubby), - Tool::SpotHealing => reset!(spot_type, sample_all_layers), + Tool::SpotHealing => reset!(spot_type), Tool::Healing => reset!(clone_aligned, clone_sample), - Tool::Patch => reset!(patch_mode, patch_content_aware, patch_structure, patch_color, sample_all_layers), - Tool::ContentAwareMove => reset!(cam_mode, cam_structure, cam_color, sample_all_layers), + Tool::Patch => reset!(patch_mode, patch_content_aware, patch_structure, patch_color), + Tool::ContentAwareMove => reset!(cam_mode, cam_structure, cam_color, cam_transform_on_drop), Tool::RedEye => reset!(red_eye_pupil_size, red_eye_darken), Tool::CloneStamp => reset!(clone_aligned, clone_sample), Tool::PatternStamp => reset!(pattern_stamp_aligned, pattern_stamp_impressionist, pattern_stamp_scale, pattern_stamp_angle), - Tool::Blur | Tool::Sharpen => reset!(strength, sample_all_layers, protect_detail), - Tool::Smudge => reset!(strength, sample_all_layers, finger_painting), + Tool::Blur | Tool::Sharpen => reset!(strength, protect_detail), + Tool::Smudge => reset!(strength, finger_painting), Tool::Dodge | Tool::Burn => reset!(tone_range, exposure, protect_tones), Tool::Sponge => reset!(sponge_mode, vibrance), Tool::Pen => reset!(vector_mode, pen_auto_add_delete), @@ -173,12 +214,9 @@ pub fn reset_options(o: &mut ToolOptions, tool: Tool) { | Tool::Ruler | Tool::Note | Tool::Count - | Tool::Brush | Tool::MixerBrush - | Tool::Eraser | Tool::Hand | Tool::RotateView - | Tool::Remove | Tool::HistoryBrush | Tool::PathSelection | Tool::DirectSelection @@ -188,7 +226,7 @@ pub fn reset_options(o: &mut ToolOptions, tool: Tool) { | Tool::DeleteAnchorPoint | Tool::ConvertPoint | Tool::Artboard - | Tool::Frame => {} + | Tool::Frame => &[], } } @@ -202,6 +240,22 @@ mod tests { PhotocraftApp::new(s, crate::Services::default()) } + /// Every option belongs to a tool, so Reset Tool and tool presets (#7356) miss none, and every + /// listed name is a real serialized field. `sample_all` holds one Sample All Layers per tool, + /// which `reset_options` and `sample_all_key` handle tool by tool (#5524). + #[test] + fn every_option_belongs_to_a_tool() { + let all = serde_json::to_value(ToolOptions::default()).unwrap(); + let all = all.as_object().unwrap(); + let listed: std::collections::BTreeSet<&str> = Tool::ALL.iter().flat_map(|t| option_keys(*t).iter().copied()).collect(); + for k in all.keys().filter(|k| *k != "sample_all") { + assert!(listed.contains(k.as_str()), "{k} is no tool's option"); + } + for k in listed { + assert!(all.contains_key(k), "{k} is not a ToolOptions field"); + } + } + /// Reset Tool resets only the current tool's options; Reset All Tools asks, then resets all. #[test] fn reset_tool_and_reset_all_tools() { @@ -226,4 +280,30 @@ mod tests { assert_eq!(app.ui.tool_options, ToolOptions::default()); assert!(app.ui.dialogs.is_empty()); } + + /// Sample All Layers is per tool (#5524): resetting Blur turns off only Blur's. + #[test] + fn reset_tool_resets_only_its_own_sample_all_layers() { + let mut o = ToolOptions::default(); + o.sample_all.blur = true; + o.sample_all.magic_wand = true; + reset_options(&mut o, Tool::Blur); + assert!(!o.sample_all.blur); + assert!(o.sample_all.magic_wand, "the Magic Wand's Sample All Layers is not Blur's"); + reset_options(&mut o, Tool::Remove); + assert!(o.sample_all.magic_wand); + reset_options(&mut o, Tool::MagicWand); + assert_eq!(o.sample_all, Default::default()); + } + + /// Every tool with a Sample All Layers names its own key, and a tool without one names none. + #[test] + fn sample_all_key_names_the_tools_own() { + assert_eq!(sample_all_key(Tool::MagicWand).as_deref(), Some("magic_wand")); + assert_eq!(sample_all_key(Tool::Blur).as_deref(), Some("blur")); + assert_eq!(sample_all_key(Tool::Brush), None); + let keys: Vec = Tool::ALL.iter().filter_map(|t| sample_all_key(*t)).collect(); + let distinct: std::collections::BTreeSet<&String> = keys.iter().collect(); + assert_eq!((keys.len(), distinct.len()), (12, 12), "one key per tool with the option"); + } } diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index d46ef189bc..7ae223029d 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -792,11 +792,12 @@ fn preview_image( (None, Some(s)) if layer.is_some_and(|l| matches!(l.content, LayerContent::Raster(_))) => Some(s), _ => { let mut solo = doc.clone(); - for l in solo.layers.iter_mut() { - if l.id != id && doc.layer(id).is_some_and(|_| !contains(l, id)) { - l.visible = false; - } else { - // Its clipping base is hidden here, which would clip it away entirely (#5239). + if layer.is_some() { + solo_layer(&mut solo.layers, id); + } else { + // Keep the previous fallback for an invalid id: render the document, with only + // top-level clipping disabled. Production callers get ids from this document. + for l in &mut solo.layers { l.clipped = false; } } @@ -988,6 +989,26 @@ fn show_only(layers: &mut [photocraft_doc::Layer], keep: &[LayerId]) { } } +/// Leave only `id`, its descendants and the groups holding it visible. Every layer on that path +/// is detached from its clipping base because the base is hidden in this isolated render (#5239). +/// Hide every layer but `id` and the groups holding it, and unclip those, so a render shows that +/// layer alone (the Free Transform preview, Liquify's one-layer backdrop). +pub(crate) fn solo_layer(layers: &mut [photocraft_doc::Layer], id: LayerId) { + for l in layers { + if l.id == id { + l.clipped = false; + continue; + } + match &mut l.content { + LayerContent::Group(g) if g.children.iter().any(|c| contains(c, id)) => { + l.clipped = false; + solo_layer(&mut g.children, id); + } + _ => l.visible = false, + } + } +} + fn contains(l: &photocraft_doc::Layer, id: LayerId) -> bool { l.id == id || matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| contains(c, id))) } @@ -1229,6 +1250,9 @@ pub(crate) fn nudge(app: &mut PhotocraftApp, dx: f64, dy: f64) { } } +/// Save for Web (Legacy): refused under an open box, as it would export without the preview (#6737). +pub(crate) const SAVE_FOR_WEB: &str = "file.export.saveForWebLegacy"; + /// While transforming, Undo and Redo apply to the box: `Some(enabled)` for those commands (and /// Toggle Last State, which would change the document under the box), `None` for the rest. pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { @@ -1245,6 +1269,8 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { "edit.redo" => Some(steps.is_some_and(|s| !s.redo.is_empty())), // No Toggle Last State or history jump under the box, and one box at a time. "edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" => Some(false), + // Save for Web exports the committed document and would ignore the pending box (#6737). + SAVE_FOR_WEB => Some(false), // Rotate and Flip turn the box (not while warping, where the mesh is the box). _ if box_preset(id).is_some() => Some(t.warp.is_none()), // Editable type can't be distorted (#2630, as #2701 rules for the menus outside a box). @@ -1284,7 +1310,7 @@ fn box_preset(id: &str) -> Option<(f64, f64, f64)> { /// `None` for other commands or when not transforming. /// The commands the open box answers itself ([`is_enabled`], [`intercept`]). fn box_command(id: &str) -> bool { - matches!(id, "edit.undo" | "edit.redo" | "edit.toggleLastState" | "edit.contentAwareScale" | "edit.puppetWarp") || box_preset(id).is_some() + matches!(id, "edit.undo" | "edit.redo" | "edit.toggleLastState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB) || box_preset(id).is_some() } pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option> { @@ -1295,7 +1321,7 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option Some(Ok(step(app, false))), "edit.redo" => Some(Ok(step(app, true))), - "edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" => { + "edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB => { Some(Err("Commit or cancel the transform first".into())) } _ => { @@ -2595,9 +2621,23 @@ fn quad_scale(t: &TransformSession) -> f32 { } /// W and H (%), the angle (°) and the horizontal skew (°) the options bar shows for the box. +/// A mirrored box reads as a negative W or H, whichever keeps the angle nearer 0 (Photoshop: +/// Flip Horizontal is W -100 % at 0°, Flip Vertical H -100 % at 0°). Both are the same box: +/// negating W and H and turning by a half turn cancel out. fn readout(t: &TransformSession) -> (f64, f64, f64, f64) { let p = Parts::of(t); - (p.sx * 100.0, p.sy.abs() * 100.0, p.angle.to_degrees(), p.skew_h.to_degrees()) + let wrap = |a: f64| { + let a = a.rem_euclid(std::f64::consts::TAU); + if a > std::f64::consts::PI { a - std::f64::consts::TAU } else { a } + }; + let turned = wrap(p.angle + std::f64::consts::PI); + let (sx, sy, angle) = if p.sy < 0.0 && turned.abs() < wrap(p.angle).abs() { (-p.sx, -p.sy, turned) } else { (p.sx, p.sy, p.angle) }; + (sx * 100.0, sy * 100.0, angle.to_degrees(), p.skew_h.to_degrees()) +} + +/// `v`, kept off zero with its sign: a divisor for a W or H scale that may be negative. +fn nonzero(v: f64) -> f64 { + if v.abs() < 1e-9 { 1e-9f64.copysign(v) } else { v } } /// The box's affine part read as Photoshop's options bar does: the frame scaled (W, H), skewed @@ -2840,14 +2880,17 @@ pub(crate) fn position_size_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t let (suffix, places) = (u.unit.suffix(), u.unit.decimals() as u32); // Lengths need more room than a percentage ("2116.67 mm"). let size_w = if u.unit == photocraft_engine::prefs::Unit::Percent { 66.0 } else { 84.0 }; + // Whatever their unit, W and H take any other typed in (`500 px` or `2 in` in percent, `50%` + // in a length), converted at the document's resolution against the box's original side (#6284). + let units = crate::widgets::FieldUnits { unit: u.unit, dpi: u.dpi, ppi: u.ppi }; lbl(ui, "W:"); - let rw = crate::widgets::value_field_prec(ui, &mut w, -wlim_u..=wlim_u, suffix, size_w, places); + let rw = crate::widgets::value_field_extent(ui, &mut w, -wlim_u..=wlim_u, suffix, size_w, places, units, side_w); let link = !app.ui.transform_unlinked; if crate::icons::button(ui, if link { "link" } else { "unlink" }, 22.0, link, tl!("Maintain aspect ratio")).clicked() { app.ui.transform_unlinked = link; } lbl(ui, "H:"); - let rh = crate::widgets::value_field_prec(ui, &mut h, -hlim_u..=hlim_u, suffix, size_w, places); + let rh = crate::widgets::value_field_extent(ui, &mut h, -hlim_u..=hlim_u, suffix, size_w, places, units, side_h); for r in [&rw, &rh] { r.context_menu(|ui| { if let Some(name) = crate::rulers::unit_menu(ui, u.unit) { @@ -2858,12 +2901,12 @@ pub(crate) fn position_size_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t let (w, h) = (size_pct(&u, w, side_w) as f32, size_pct(&u, h, side_h) as f32); if rw.changed() || rh.changed() { let (kx, ky) = if link { - let k = if rw.changed() { w as f64 / sx.max(1e-9) } else { h as f64 / sy.max(1e-9) }; + let k = if rw.changed() { w as f64 / nonzero(sx) } else { h as f64 / nonzero(sy) }; // Linked, the other side follows: keep it within its own limit too. let k = k.min(f64::from(wlim) / sx.abs().max(1e-9)).min(f64::from(hlim) / sy.abs().max(1e-9)); (k, k) } else { - (w as f64 / sx.max(1e-9), h as f64 / sy.max(1e-9)) + (w as f64 / nonzero(sx), h as f64 / nonzero(sy)) }; scale_about_pivot(app, kx, ky); } @@ -3323,6 +3366,43 @@ mod tests { assert!(eq6(skew, 20.0), "{skew}"); } + /// The test box flipped horizontally and vertically, as Edit › Transform › Flip leaves it. + const FLIPPED_H: [[f64; 2]; 4] = [[100.0, 0.0], [0.0, 0.0], [0.0, 50.0], [100.0, 50.0]]; + const FLIPPED_V: [[f64; 2]; 4] = [[0.0, 50.0], [100.0, 50.0], [100.0, 0.0], [0.0, 0.0]]; + + /// Photoshop puts a flip's minus on the flipped axis and keeps the angle at 0: Flip Horizontal + /// reads W -100 %, Flip Vertical H -100 % (it read 180° and nothing at all). + #[test] + fn a_flipped_box_reads_as_a_negative_scale_on_that_axis() { + let mut t = session(); + for (quad, want) in [(FLIPPED_H, (-100.0, 100.0)), (FLIPPED_V, (100.0, -100.0))] { + t.quad = quad; + let (w, h, angle, skew) = readout(&t); + assert!(eq6(w, want.0) && eq6(h, want.1) && eq6(angle, 0.0) && eq6(skew, 0.0), "{quad:?}: {w} {h} {angle} {skew}"); + } + // Flipped both ways is a half turn, not a mirror. + t.quad = [[100.0, 50.0], [0.0, 50.0], [0.0, 0.0], [100.0, 0.0]]; + let (w, h, angle, _) = readout(&t); + assert!(eq6(w, 100.0) && eq6(h, 100.0) && eq6(angle.abs(), 180.0), "{w} {h} {angle}"); + } + + /// The bar's fields act on a flipped box without undoing the flip: angle 0 keeps it as it is, + /// and a typed W scales it and keeps it mirrored. + #[test] + fn bar_fields_keep_a_flipped_box_flipped() { + let flip_h = |app: &mut PhotocraftApp| app.ui.transform.as_mut().unwrap().quad = FLIPPED_H; + let t = type_into_bar_field_with(flip_h, 4, "0"); + assert!(t.quad.iter().flatten().zip(FLIPPED_H.iter().flatten()).all(|(a, b)| eq6(*a, *b)), "{:?}", t.quad); + let t = type_into_bar_field_with(flip_h, 2, "-50"); + let (w, h, angle, _) = readout(&t); + assert!(eq6(w, -50.0) && eq6(h, 50.0) && eq6(angle, 0.0), "{w} {h} {angle}"); + assert!(eq6(t.quad[0][0] - t.quad[1][0], 50.0), "50 px wide, still mirrored: {:?}", t.quad); + let flip_v = |app: &mut PhotocraftApp| app.ui.transform.as_mut().unwrap().quad = FLIPPED_V; + let t = type_into_bar_field_with(flip_v, 3, "-200"); + let (w, h, _, _) = readout(&t); + assert!(eq6(w, 200.0) && eq6(h, -200.0), "{w} {h}"); + } + /// Typing H and V skews leans the box about the reference point; the angle, W and H fields keep /// their values, and V stays as typed. #[test] @@ -3437,6 +3517,93 @@ mod tests { assert_eq!(shown_size(&bar_harness(|_| {})), ["100", "100"]); } + /// Opens a document at `dpi` so the W/H fields convert typed lengths at its resolution. + fn at_dpi(app: &mut PhotocraftApp, dpi: f32) { + app.session.execute("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.session + .edit("resolution", |doc, _| { + doc.resolution_dpi = dpi; + Ok(()) + }) + .unwrap(); + } + + /// The box's width and height in px after a W/H edit. + fn box_size(t: &TransformSession) -> (f64, f64) { + (t.quad[1][0] - t.quad[0][0], t.quad[3][1] - t.quad[0][1]) + } + + #[test] + fn w_and_h_in_percent_take_a_typed_length() { + use photocraft_engine::prefs::Unit; + let near = |a: f64, b: f64| (a - b).abs() < 0.01; + // The 100 × 50 px box with W/H showing percent (#6284): a typed length is the box's new side. + for (text, px) in + [("40px", 40.0), ("40 px", 40.0), ("2in", 600.0), ("2 in", 600.0), ("5cm", 5.0 / 2.54 * 300.0), ("25.4mm", 300.0), ("72pt", 300.0), ("1pica", 50.0)] + { + // Linked: the height follows the width. + let t = type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text); + let (w, h) = box_size(&t); + assert!(near(w, px) && near(h, px / 2.0), "{text} linked: {w} × {h}"); + // Unlinked: only the width changes. + let t = type_into_bar_field_with( + |app| { + at_dpi(app, 300.0); + app.ui.transform_unlinked = true; + }, + 2, + text, + ); + let (w, h) = box_size(&t); + assert!(near(w, px) && near(h, 50.0), "{text} unlinked: {w} × {h}"); + } + // H takes a length too; linked, the width follows. + let t = type_into_bar_field_with(|app| at_dpi(app, 300.0), 3, "1in"); + let (w, h) = box_size(&t); + assert!(near(w, 600.0) && near(h, 300.0), "H 1in: {w} × {h}"); + // A plain number is still the percentage. + let (w, _) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "40")); + assert!(near(w, 40.0), "40 is 40 % of 100 px: {w}"); + // A percentage typed into a length field is that share of the box's original side. + let px = |app: &mut PhotocraftApp| { + at_dpi(app, 300.0); + set_size_unit(app, Unit::Pixels.name()); + }; + let (w, h) = box_size(&type_into_bar_field_with(px, 2, "50%")); + assert!(near(w, 50.0) && near(h, 25.0), "50% in px: {w} × {h}"); + let inches = |app: &mut PhotocraftApp| { + at_dpi(app, 300.0); + set_size_unit(app, Unit::Inches.name()); + }; + let (w, h) = box_size(&type_into_bar_field_with(inches, 3, "300%")); + assert!(near(w, 300.0) && near(h, 150.0), "300% in inches: {w} × {h}"); + } + + #[test] + fn w_and_h_reject_or_clamp_hostile_typed_lengths() { + let near = |a: f64, b: f64| (a - b).abs() < 0.01; + // Text that is no number leaves the box alone. + for text in ["px", "in", "NaN", "%"] { + let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text)); + assert!(near(w, 100.0) && near(h, 50.0), "{text}: {w} × {h}"); + } + // Invalid text after a number keeps only what applied while typing (a plain number applies + // per keystroke), never a NaN or a box past the largest document. + for text in ["1in/0", "1e400px", "2 inches", "1e308in"] { + let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text)); + assert!(w.is_finite() && h.is_finite() && w.abs() <= f64::from(POSITION_LIMIT_PX) + 0.01, "{text}: {w} × {h}"); + } + // A huge length stops at the field's limit: the box stays within the largest document. + let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "1e9in")); + assert!(w.is_finite() && w <= f64::from(POSITION_LIMIT_PX) + 0.01 && h <= f64::from(POSITION_LIMIT_PX), "{w} × {h}"); + // A negative length flips, as a negative percentage does. + let (w, _) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "-40px")); + assert!(near(w, -40.0), "{w}"); + // Zero collapses the side without dividing by zero. + let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "0px")); + assert!(w.is_finite() && h.is_finite(), "{w} × {h}"); + } + #[test] fn right_clicking_w_or_h_picks_their_unit_and_remembers_it() { use egui_kittest::kittest::Queryable; @@ -3903,6 +4070,23 @@ mod tests { assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "another tool ends it"); } + /// #6737: Save for Web exports the committed document, so it is off while a box is pending. + #[test] + fn save_for_web_is_off_under_a_pending_transform() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + assert!(crate::menus::is_enabled(&app, SAVE_FOR_WEB), "enabled with no box"); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + assert!(!crate::menus::is_enabled(&app, SAVE_FOR_WEB), "off under the box"); + assert!(crate::menus::invoke(&mut app, &ctx, SAVE_FOR_WEB, json!({})).is_err(), "the dialog doesn't open"); + let path = std::env::temp_dir().join(format!("pc-web6737-{}.png", std::process::id())).to_string_lossy().into_owned(); + let r = crate::menus::invoke(&mut app, &ctx, SAVE_FOR_WEB, json!({"path": path, "format": "png24"})); + assert!(r.is_err() && !std::path::Path::new(&path).exists(), "nor does the export run"); + assert!(app.ui.transform.is_some(), "the box stays open"); + cancel(&mut app); + assert!(crate::menus::is_enabled(&app, SAVE_FOR_WEB), "back after the box closes"); + } + /// #352: ⌥⌘T transforms a copy. OK leaves the original and a moved copy as one history step; /// Cancel leaves no copy and nothing to redo; with a selection the copy holds the selected /// pixels only. @@ -4747,6 +4931,60 @@ mod tests { assert!(pv.texture.size()[0] as f64 >= t.rect[2] - t.rect[0]); } + #[test] + fn nested_group_preview_excludes_its_siblings() { + use photocraft_color::PixelFormat; + use photocraft_doc::Layer; + + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let target_pixels = doc.layers.pop().unwrap(); + let mut sibling = Layer::raster("sibling", PixelFormat::RGBA8); + sibling.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(12, 12, 20, 20), &[0.0, 0.0, 1.0, 1.0]); + let target = Layer::group("target", vec![target_pixels]); + let target_id = target.id; + doc.layers.push(Layer::group("parent", vec![target, sibling])); + + let (image, _) = preview_image(&st.doc, target_id, None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); + assert_eq!( + image.pixels[8 * image.size[0] + 8], + Color32::from_rgb(255, 0, 0), + "a sibling in the parent group must not be baked into the moving texture" + ); + } + + #[test] + fn nested_group_preview_detaches_every_clipped_ancestor() { + use photocraft_color::PixelFormat; + use photocraft_doc::Layer; + + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let target_pixels = doc.layers.pop().unwrap(); + let target = Layer::group("target", vec![target_pixels]); + let target_id = target.id; + let mut middle = Layer::group("middle clipped ancestor", vec![target]); + middle.clipped = true; + let mut inner_base = Layer::raster("hidden inner clipping base", PixelFormat::RGBA8); + inner_base.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 64, 64), &[0.0, 0.0, 1.0, 1.0]); + let mut outer = Layer::group("outer clipped ancestor", vec![inner_base, middle]); + outer.clipped = true; + doc.layers.push(outer); + + let (image, _) = preview_image(&st.doc, target_id, None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); + assert_eq!(image.pixels[8 * image.size[0] + 8], Color32::from_rgb(255, 0, 0), "hidden clipping bases must not make a nested target disappear"); + } + + #[test] + fn unknown_preview_target_keeps_the_previous_document_fallback() { + let app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let st = app.session.active().unwrap(); + let (image, _) = preview_image(&st.doc, LayerId::fresh(), None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); + assert_eq!(image.pixels[8 * image.size[0] + 8], Color32::from_rgb(255, 0, 0)); + } + /// The textured meshes `draw_content` paints for the moving pixels (not the box or handles). fn preview_meshes(app: &PhotocraftApp, xf: &ViewXform) -> Vec { let ctx = gpu_ctx(); diff --git a/crates/ui-egui/src/transform_type_tests.rs b/crates/ui-egui/src/transform_type_tests.rs index 0ed51de669..457c03c1cb 100644 --- a/crates/ui-egui/src/transform_type_tests.rs +++ b/crates/ui-egui/src/transform_type_tests.rs @@ -52,6 +52,7 @@ fn type_layers_offer_free_transform_but_not_distort_or_perspective() { pasteboard: false, anchor: None, text: false, + type_layer: false, guide: false, spelling: None, }; diff --git a/crates/ui-egui/src/type_font_picker_tests.rs b/crates/ui-egui/src/type_font_picker_tests.rs index 176e683a9d..6f05ed61a5 100644 --- a/crates/ui-egui/src/type_font_picker_tests.rs +++ b/crates/ui-egui/src/type_font_picker_tests.rs @@ -10,6 +10,7 @@ use photocraft_engine::prefs::FontPreview; struct State { current: String, families: Vec, + button: egui::Id, popup: egui::Id, preview: FontPreview, } @@ -22,10 +23,11 @@ fn harness_with(preview: FontPreview) -> Harness<'static, State> { // Enough families that the unfiltered menu hits its maximum height and scrolls. let mut families: Vec = (0..60).map(|i| format!("Family {i:02}")).collect(); families.push("Zeta Sans".into()); - let state = State { current: "Family 00".into(), families, popup: egui::Id::NULL, preview }; + let state = State { current: "Family 00".into(), families, button: egui::Id::NULL, popup: egui::Id::NULL, preview }; let mut h = Harness::builder().with_size(vec2(600.0, 900.0)).build_ui_state( |ui, s: &mut State| { - s.popup = ui.make_persistent_id(egui::IdSalt::new("type-font")).with("popup"); + s.button = ui.make_persistent_id(egui::IdSalt::new("type-font")); + s.popup = s.button.with("popup"); let fams = s.families.clone(); font_picker_in(ui, &mut s.current, 170.0, &fams, s.preview); }, @@ -46,6 +48,16 @@ fn open(h: &mut Harness<'static, State>) { h.run(); } +/// A native click can leave the opening button held across several rendered frames. +fn hold_open(h: &mut Harness<'_, S>, button: egui::Pos2) { + h.hover_at(button); + h.run(); + h.event(egui::Event::PointerButton { pos: button, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(4); + h.event(egui::Event::PointerButton { pos: button, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run(); +} + #[test] fn hovering_a_font_row_sets_preview_and_leaving_clears_it() { let mut h = harness(); @@ -71,6 +83,35 @@ fn hovering_a_font_row_sets_preview_and_leaving_clears_it() { assert!(h.ctx.data(|d| d.get_temp::(hover_id)).is_none()); } +/// #7406: hovering a font highlights its row without moving anything: the other rows keep +/// their place, the menu its width, and every row (the selected one too) takes one height. +#[test] +fn hovering_a_font_row_moves_no_other_row() { + let mut h = harness(); + // The app's theme: its hovered and selected buttons draw a stroke (egui's default style + // would hide the jump). + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run(); + open(&mut h); + let rows = |h: &Harness<'static, State>| -> Vec { (0..8).map(|i| h.get_by_label(&format!("Family {i:02}")).rect()).collect() }; + let before = rows(&h); + let width = popup_rect(&h).expect("font menu open").width(); + let tops: Vec = before.windows(2).map(|w| w[1].top() - w[0].top()).collect(); + assert!(tops.windows(2).all(|t| (t[0] - t[1]).abs() < 0.01), "rows are evenly spaced, the selected Family 00 included: {tops:?}"); + for hovered in [2, 5] { + h.hover_at(before[hovered].center()); + h.run_steps(2); + let after = rows(&h); + for (i, (b, a)) in before.iter().zip(&after).enumerate() { + if i != hovered { + assert_eq!(b, a, "hovering Family {hovered:02} moved Family {i:02}"); + } + } + assert_eq!(after[hovered].center(), before[hovered].center(), "the hovered row stays centred where it was"); + assert_eq!(popup_rect(&h).map(|r| r.width()), Some(width), "the menu keeps its width"); + } +} + #[test] fn clearing_the_query_restores_the_menu_height() { let mut h = harness(); @@ -93,15 +134,18 @@ fn clearing_the_query_restores_the_menu_height() { #[test] fn reopening_focuses_the_search_field_and_clicking_it_keeps_the_menu_open() { let mut h = harness(); - open(&mut h); + let button = h.query_all_by_role(Role::ComboBox).next().unwrap().rect().center(); + hold_open(&mut h, button); assert!(h.get_by_role(Role::TextInput).is_focused(), "search is focused on first open"); - h.get_by_role(Role::TextInput).type_text("zeta"); - h.run(); - // Close without choosing, then reopen: the query stays and the field is focused again. - h.key_press(Key::Escape); + h.event(egui::Event::Text("zeta".into())); h.run(); + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("zeta"), "typing goes straight to the search field"); + // Close and reopen on consecutive passes: the query stays and the field is focused again. + h.input_mut().events.push(egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.step(); assert!(popup_rect(&h).is_none(), "Escape closes the menu"); - open(&mut h); + h.query_all_by_role(Role::ComboBox).next().unwrap().click_accesskit(); + h.run(); let search = h.get_by_role(Role::TextInput); assert_eq!(search.value().as_deref(), Some("zeta")); assert!(search.is_focused(), "search is focused on reopen with a query"); @@ -120,6 +164,64 @@ fn reopening_focuses_the_search_field_and_clicking_it_keeps_the_menu_open() { assert!(popup_rect(&h).is_none(), "choosing a font closes the menu"); } +#[test] +fn opening_click_release_returns_focus_to_search_before_typing() { + let mut h = harness(); + let button = h.query_all_by_role(Role::ComboBox).next().unwrap().rect().center(); + h.hover_at(button); + h.run(); + h.event(egui::Event::PointerButton { pos: button, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(4); + assert!(h.get_by_role(Role::TextInput).is_focused()); + // A native opening click can hand focus back to its button when it ends, after the + // search has already been focused for several passes. Model that platform handoff. + let id = h.state().button; + h.ctx.memory_mut(|m| m.request_focus(id)); + h.event(egui::Event::PointerButton { pos: button, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run(); + assert!(h.get_by_role(Role::TextInput).is_focused(), "the opening release leaves the search focused"); + h.event(egui::Event::Text("zeta".into())); + h.run(); + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("zeta")); + assert!(h.query_by_label("Family 01").is_none()); +} + +#[test] +fn first_options_bar_open_searches_without_changing_the_tool_or_edited_text() { + use crate::{PhotocraftApp, Services}; + use photocraft_doc::LayerContent; + use serde_json::json; + + for editing in [false, true] { + let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("type.create", json!({"text": "Sample", "font": "Inter", "size": 18})).unwrap(); + app.ui.tool = crate::state::Tool::Type; + if editing { + super::edit_active(&mut app).unwrap(); + } + app.sync_views(); + app + }); + h.run_steps(8); + let button = h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Inter")).unwrap().rect().center(); + hold_open(&mut h, button); + // Native typing carries key events as well as text; an unfocused search would let + // the first key switch tools, or replace the selected inline text instead. + h.event(egui::Event::Key { key: Key::J, physical_key: Some(Key::J), pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.event(egui::Event::Text("JetBrains".into())); + h.run(); + let search = h.query_all_by_role(Role::TextInput).find(|n| n.is_focused()).expect("font search focused on first open"); + assert_eq!(search.value().as_deref(), Some("JetBrains")); + assert_eq!(h.state().ui.tool, crate::state::Tool::Type); + let st = h.state().session.active().unwrap(); + let LayerContent::Text(text) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("type layer") }; + assert_eq!(text.text, "Sample"); + } +} + #[test] fn arrows_apply_fonts_without_closing_and_enter_accepts() { let mut h = harness(); @@ -137,6 +239,88 @@ fn arrows_apply_fonts_without_closing_and_enter_accepts() { assert!(popup_rect(&h).is_none()); } +/// #7407: as in Photoshop, the field keeps the focus once a font is picked (click or Enter), +/// and ↑ / ↓ on it step through the families with the menu closed. Escape ends it. +#[test] +fn arrows_on_the_field_step_through_the_families_after_a_pick() { + let mut h = harness(); + open(&mut h); + h.get_by_label("Family 03").click(); + h.run(); + assert_eq!(h.state().current, "Family 03"); + assert!(popup_rect(&h).is_none(), "picking closes the menu"); + let button = h.state().button; + assert!(h.ctx.memory(|m| m.has_focus(button)), "the field keeps the focus"); + let press = |h: &mut Harness<'static, State>, key: Key| { + h.key_press(key); + h.run(); + assert!(popup_rect(h).is_none(), "{key:?} leaves the menu closed"); + assert!(h.ctx.memory(|m| m.has_focus(button)), "{key:?} keeps the focus on the field"); + h.state().current.clone() + }; + assert_eq!(press(&mut h, Key::ArrowDown), "Family 04"); + assert_eq!(press(&mut h, Key::ArrowDown), "Family 05"); + assert_eq!(press(&mut h, Key::ArrowUp), "Family 04"); + // Enter in the open menu is a pick too. + open(&mut h); + h.key_press(Key::ArrowDown); + h.key_press(Key::Enter); + h.run(); + assert_eq!(h.state().current, "Family 05"); + assert_eq!(press(&mut h, Key::ArrowDown), "Family 06"); + // Escape takes the focus away; the arrows then leave the font alone. + h.key_press(Key::Escape); + h.run(); + assert!(!h.ctx.memory(|m| m.has_focus(button))); + h.key_press(Key::ArrowDown); + h.run(); + assert_eq!(h.state().current, "Family 06"); +} + +/// The first arrow right after a pick (in the very next frame) steps the font and keeps the +/// focus on the field, also between focusable widgets: the field's lock filter only holds from +/// the frame after it got the focus, and egui would read that arrow as a move to "Below". +#[test] +fn the_first_arrow_after_a_pick_keeps_the_focus_between_neighbours() { + for (enter, picked, stepped) in [(false, "Family 05", "Family 06"), (true, "Family 04", "Family 05")] { + let families: Vec = (0..20).map(|i| format!("Family {i:02}")).collect(); + let state = State { current: "Family 03".into(), families, button: egui::Id::NULL, popup: egui::Id::NULL, preview: FontPreview::Off }; + let mut h = Harness::builder().with_size(vec2(600.0, 900.0)).build_ui_state( + |ui, s: &mut State| { + let _ = ui.button("Above"); + s.button = ui.make_persistent_id(egui::IdSalt::new("type-font")); + s.popup = s.button.with("popup"); + let fams = s.families.clone(); + font_picker_in(ui, &mut s.current, 170.0, &fams, s.preview); + let _ = ui.button("Below"); + }, + state, + ); + h.run(); + open(&mut h); + if enter { + h.key_press(Key::ArrowDown); + h.key_press(Key::Enter); + } else { + h.get_by_label("Family 05").click(); + } + // Frame by frame up to the pick, then the arrow in the next frame. + for _ in 0..8 { + if h.state().current == picked && popup_rect(&h).is_none() { + break; + } + h.step(); + } + assert_eq!(h.state().current, picked, "enter: {enter}"); + h.key_press(Key::ArrowDown); + h.step(); + h.run(); + assert_eq!(h.state().current, stepped, "enter: {enter}"); + let button = h.state().button; + assert!(h.ctx.memory(|m| m.has_focus(button)), "enter: {enter}: the arrow moved the focus off the field"); + } +} + #[test] fn arrows_follow_the_filtered_list_and_handle_no_matches() { let mut h = harness(); @@ -411,6 +595,7 @@ fn localized_font_names_label_the_menu_but_pick_the_family() { let state = State { current: "Arial".into(), families: vec!["Arial".into(), "MS Gothic".into(), "Zeta Sans".into()], + button: egui::Id::NULL, popup: egui::Id::NULL, preview: FontPreview::Medium, }; @@ -519,8 +704,8 @@ fn options_bar_hover_previews_with_the_character_picker_also_shown() { }; let pickers: Vec<_> = h.query_all_by_role(Role::ComboBox).filter(|n| n.value().as_deref() == Some("Inter")).collect(); assert_eq!(pickers.len(), 2, "options bar and Character section both show the font picker"); - pickers[0].click(); - h.run(); + let button = pickers[0].rect().center(); + hold_open(&mut h, button); h.query_all_by_role(Role::TextInput).find(|n| n.is_focused()).expect("search field focused").type_text("JetBrains Mono"); h.run(); h.get_by_label("JetBrains Mono").hover(); diff --git a/crates/ui-egui/src/type_panels_ui.rs b/crates/ui-egui/src/type_panels_ui.rs index d97a649fba..86ef663209 100644 --- a/crates/ui-egui/src/type_panels_ui.rs +++ b/crates/ui-egui/src/type_panels_ui.rs @@ -443,7 +443,7 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s (tl!("Indent Right"), "end_indent_pt", "pt"), (tl!("Space Before"), "space_before_pt", "pt"), (tl!("Space After"), "space_after_pt", "pt"), - (tl!("Hyphenate"), "hyphenate", "bool"), + // Hyphenate is stored and round-trips to PSD, but layout never hyphenates (#6710). ]; for &(label, key, kind) in rows { let mut on = defined(¶_attrs, key); @@ -969,4 +969,25 @@ mod tests { assert!(h.state().ui.type_panels.spell.is_none(), "the × closed Check Spelling"); assert_eq!(h.state().session.active().unwrap().revision, revision, "and changed nothing"); } + + #[test] + fn hyphenate_is_not_shown_in_paragraph_style_options() { + // #6710: layout never hyphenates; the style editor must not advertise it. + use egui_kittest::kittest::Queryable; + let mut app = app_with_text("Hi"); + app.ui.type_panels.styles = true; + app.ui.type_panels.styles_tab = 1; + app.ui.type_panels.options = Some((true, 0)); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + windows(app, ui.ctx()); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + assert!(h.query_by_label("Hyphenate").is_none()); + } } diff --git a/crates/ui-egui/src/type_panels_ui/color_picker.rs b/crates/ui-egui/src/type_panels_ui/color_picker.rs index 3c68f72e4c..7df76c0cd5 100644 --- a/crates/ui-egui/src/type_panels_ui/color_picker.rs +++ b/crates/ui-egui/src/type_panels_ui/color_picker.rs @@ -82,7 +82,7 @@ pub(crate) fn open(app: &mut PhotocraftApp, kind: Kind, id: u32) -> Result (f32, f32) { /// Topmost shown type layer (it and every group around it visible, #4320) whose laid-out text /// contains the document point. -fn hit_layer(app: &mut PhotocraftApp, x: f64, y: f64) -> Option { +pub(crate) fn hit_layer(app: &mut PhotocraftApp, x: f64, y: f64) -> Option { let doc = app.session.active()?.doc.clone(); let slop = 6.0 / app.point_zoom().max(0.01); // A Type Mask session's text is a hidden layer; it is still the text being edited. @@ -237,6 +237,15 @@ fn resize_box(app: &mut PhotocraftApp, ed: &TextEdit, i: u8, x: f64, y: f64) { let _ = app.run("type.edit", json!({"layer": ed.layer, "box": [o.x, o.y, x1 - x0, y1 - y0], "coalesce": ed.session})); } +/// True when document point (`x`, `y`) lies inside the paragraph box of type layer `id` (false +/// for point text). +fn inside_box(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> bool { + let Some((bx, by, w, h)) = box_shape(app, id) else { return false }; + let Some((_, aff, _)) = layout(app, id) else { return false }; + let (tx, ty) = to_text(&aff, x, y); + tx >= bx && tx <= bx + w && ty >= by && ty <= by + h +} + /// Pointer down with the Type tool. Returns true when the press was consumed (no box drag). pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) -> bool { if let Some(ed) = app.ui.text_edit.clone() { @@ -247,7 +256,9 @@ pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifie } return true; } - if hit_layer(app, x, y) == Some(id) { + // Photoshop: anywhere inside the paragraph box places the caret, even off the glyphs + // (left of a line's start, below the last line); only a click outside it commits. + if hit_layer(app, x, y) == Some(id) || inside_box(app, id, x, y) { let off = hit_offset(app, id, x, y); if let Some(e) = app.ui.text_edit.as_mut() { e.caret = off; @@ -301,6 +312,7 @@ pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { if let Some(e) = app.ui.text_edit.as_mut() { e.dragging = false; e.resize = None; + app.ui.caret_blink_time = app.last_frame_time; return; } let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs()); @@ -340,6 +352,7 @@ pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { } // Like Photoshop: the placeholder is selected, so typing replaces it. let n = text.chars().count(); + app.ui.caret_blink_time = app.last_frame_time; app.ui.text_edit = Some(TextEdit { layer: id, caret: n, anchor: 0, session: key, created: true, mask, dragging: false, resize: None, preedit: None }); app.ui.text_edit_return_tool = None; } @@ -789,7 +802,11 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { e.caret = e.caret.min(n); e.anchor = e.anchor.min(n); } - ctx.request_repaint_after(std::time::Duration::from_millis(530)); // caret blink + let time = ctx.input(|i| i.time); + let elapsed = (time - app.ui.caret_blink_time).max(0.0); + let period = 0.530; + let remaining = period - (elapsed % period); + ctx.request_repaint_after(std::time::Duration::from_secs_f64(remaining.clamp(0.010, period))); let events = ctx.input(|i| i.events.clone()); let vertical_flow = is_vertical(app, id); let mut handled = vec![false; events.len()]; @@ -942,6 +959,7 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } } if handled.iter().any(|h| *h) { + app.ui.caret_blink_time = ctx.input(|i| i.time); let mut k = 0; ctx.input_mut(|i| { i.events.retain(|_| { @@ -1000,6 +1018,9 @@ pub fn commit_with(app: &mut PhotocraftApp, mods: egui::Modifiers) { /// Selection highlight, caret and text frame over the canvas. pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { let Some(ed) = app.ui.text_edit.clone() else { return }; + if ed.dragging { + app.ui.caret_blink_time = painter.ctx().input(|i| i.time); + } let id = LayerId(ed.layer); let Some((l, aff, text)) = layout(app, id) else { return }; if ed.mask { @@ -1083,18 +1104,24 @@ pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewX } } } else { - // Blinking caret (Photoshop's ~0.53 s rhythm), solid while dragging. + // Blinking caret (Photoshop's ~0.53 s rhythm), solid while dragging or immediately after interaction. let time = painter.ctx().input(|i| i.time); - if ed.dragging || (time * 1000.0 / 530.0) as i64 % 2 == 0 { + let elapsed = (time - app.ui.caret_blink_time).max(0.0); + if ed.dragging || (elapsed * 1000.0 / 530.0) as i64 % 2 == 0 { let (x, top, bot) = l.caret(a); let (x, top, bot) = if l.lines.is_empty() { (0.0, -(12.0 * l.px_per_pt.max(1.0)), 3.0) } else { (x, top, bot) }; - let c = if crate::theme::Tokens::get(painter.ctx()).pro { Color32::WHITE } else { Color32::BLACK }; - painter.line_segment([scr(x, top), scr(x, bot)], Stroke::new(1.5, c)); - painter.line_segment([scr(x, top), scr(x, bot)], Stroke::new(0.75, Color32::BLACK)); + for stroke in CARET_STROKES { + painter.line_segment([scr(x, top), scr(x, bot)], stroke); + } } } } +/// The text caret, drawn in order: a white halo, then a solid black line inside it, so it reads on +/// any background (#6085). The black line used to be a 0.75 pt hairline inside a white one, which +/// on a white background left only a faint grey line. +const CARET_STROKES: [Stroke; 2] = [Stroke { width: 3.0, color: Color32::WHITE }, Stroke { width: 1.0, color: Color32::BLACK }]; + /// The Type Mask tools while typing: Quick Mask's colour over the canvas with the glyphs clear, /// as Photoshop shows the selection-to-be. The glyphs come from the hidden working layer's pixels. fn draw_mask_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, id: LayerId) { @@ -1435,7 +1462,10 @@ pub(crate) fn family_picker_in( preview: photocraft_engine::prefs::FontPreview, ) -> bool { let mut changed = false; + // A font picked from the open menu (click or Enter): the field keeps the focus afterwards. + let mut picked = false; let search_id = ui.id().with(("font-search", salt)); + let focus_id = search_id.with("focus"); // The list opens on the press, so a press-drag-release picks a font too (#2735). let (press, close) = crate::press_menu::PressCombo::before(ui, salt); let labels: Option>> = ui.ctx().data(|d| d.get_temp(font_labels_id())); @@ -1451,26 +1481,25 @@ pub(crate) fn family_picker_in( .close_behavior(if matches!(close, egui::PopupCloseBehavior::IgnoreClicks) { close } else { egui::PopupCloseBehavior::CloseOnClickOutside }); let response = combo.show_ui(ui, |ui| { - let (pass_id, focus_id, height_id) = (search_id.with("pass"), search_id.with("focus"), search_id.with("height")); - let pass = ui.ctx().cumulative_pass_nr(); - let last_pass: Option = ui.data(|d| d.get_temp(pass_id)); - // Freshly opened (not drawn last pass): focus the search field whatever the query, and keep - // asking until it has focus (the first pass is egui's invisible sizing pass) (#1369). - let opened = last_pass.is_none_or(|p| p.saturating_add(1) < pass); - let mut focus = opened || ui.data(|d| d.get_temp(focus_id)).unwrap_or(false); + let height_id = search_id.with("height"); + // Each opening focuses the search, including a reopen on the very next pass. Keep + // asking through the invisible sizing pass, until the field receives focus. + let mut focus = ui.data(|d| d.get_temp(focus_id)).unwrap_or(true); let mut q: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default(); // Consume these before TextEdit and the canvas can interpret them as caret movement. let down = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)); let up = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)); let enter = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); - let r = ui.add(egui::TextEdit::singleline(&mut q).hint_text(tl!("Search fonts")).desired_width(200.0)); - if r.has_focus() { - focus = false; - } else if focus { - r.request_focus(); + if focus { + ui.memory_mut(|m| m.request_focus(search_id.with("input"))); + } + let r = ui.add(egui::TextEdit::singleline(&mut q).id(search_id.with("input")).hint_text(tl!("Search fonts")).desired_width(200.0)); + if focus { + // The opening click can release after several focused frames. Keep the request + // pending through that release, which can hand focus back to the combo button. + focus = !r.has_focus() || ui.input(|i| i.pointer.primary_down() || i.pointer.primary_released()); } ui.data_mut(|d| { - d.insert_temp(pass_id, pass); d.insert_temp(focus_id, focus); d.insert_temp(search_id, q.clone()); }); @@ -1492,6 +1521,7 @@ pub(crate) fn family_picker_in( } } let accept = enter && rows.iter().any(|(f, _)| *f == current); + picked |= accept; if accept { ui.data_mut(|d| d.remove::(search_id)); ui.close(); @@ -1501,7 +1531,11 @@ pub(crate) fn family_picker_in( let mut hovered: Option = None; for (f, label) in rows { - let mut button = egui::Button::selectable(f == current, label).truncate(); + // Highlighted by its fill alone, as Photoshop's font menu is. A selectable button lays + // out its frame's stroke only once hovered or selected, so with the theme's stroke the + // row under the pointer (and the selected one) grew and pushed the rows below down: + // the list jumped as the pointer moved (#7406). + let mut button = egui::Button::selectable(f == current, label).truncate().stroke(egui::Stroke::NONE); if let Some((size, [_, h])) = preview { button = button.right_text(egui::Atom::custom(ui.id().with(("font-sample", f)), egui::vec2(crate::font_preview::slot_width(ui.ctx(), f, size), h))); @@ -1523,6 +1557,7 @@ pub(crate) fn family_picker_in( // A served family not fetched yet: start now, before any text needs it. photocraft_text::served::request(f); changed = true; + picked = true; ui.data_mut(|d| d.remove::(search_id)); hovered = None; ui.close(); @@ -1540,8 +1575,43 @@ pub(crate) fn family_picker_in( if accept { None } else { hovered } }); press.after(&response.response); + if !egui::ComboBox::is_open(ui.ctx(), response.response.id) { + ui.data_mut(|d| d.remove::(focus_id)); + } let hovered_font = response.inner.unwrap_or_default(); + // As in Photoshop, the field keeps the keyboard focus once a font is picked, and ↑ / ↓ on the + // focused, closed field step to the previous / next family, applying each (#7407). The lock + // filter keeps egui from using those arrows to move the focus to another widget. + let field = response.response.id; + if picked { + ui.memory_mut(|m| m.request_focus(field)); + } + let open = egui::ComboBox::is_open(ui.ctx(), field); + if !open && ui.is_enabled() && ui.memory(|m| m.has_focus(field)) { + ui.memory_mut(|m| m.set_focus_lock_filter(field, egui::EventFilter { vertical_arrows: true, ..Default::default() })); + let down = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)); + let up = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)); + if down || up { + // The lock filter only holds from the frame after the field got the focus: an arrow + // right after a pick was already read by egui as a focus move, applied at the end of + // the frame. Cancel it, so the arrow only steps the font. + ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); + } + // The wheel's step: a negative notch is the next family. + let notches = f32::from(u8::from(up)) - f32::from(u8::from(down)); + let rows = font_menu_rows(families, labels, ""); + if let Some(i) = rows.iter().position(|(f, _)| *f == current) + && let Some(n) = wheel_family_index(i, rows.len(), notches) + && let Some((f, _)) = rows.get(n) + && **f != *current + { + current.clone_from(f); + photocraft_text::served::request(f); + changed = true; + } + } + // The wheel over the closed button steps through the families, a notch each, like Photoshop's // options-bar font menu: no need to open the list (#3350). if !egui::ComboBox::is_open(ui.ctx(), response.response.id) && ui.is_enabled() { @@ -2130,6 +2200,8 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa use crate::props_layout::{COL_GAP, LABEL_GAP, LABEL_W, field_width, section}; use crate::theme::ROW_GAP; let Some((c, para)) = styles_at(app) else { return }; + // Preferences ▸ Units & Rulers ▸ Type, as in the options bar: the model keeps points. + let (u, unit) = type_unit(app); let t = crate::theme::Tokens::get(ui.ctx()); // Row helper: `ui.horizontal` with the column gap, then the shared row gap. let row = |ui: &mut egui::Ui, add: &mut dyn FnMut(&mut egui::Ui)| { @@ -2167,13 +2239,13 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa let k = shown_scale(app); // Hover tips stay English until wired through `tl!` in a multi-locale change // (`every_tl_literal_is_translated` requires every complete catalog). - if let Some(v) = num_field(ui, "tT", "Font size", c.size_pt * k, 0.1..=1296.0, "pt", w) { - app.ui.tool_options.type_size = v; - apply(app, ui.ctx(), json!({"size": v, "metricsAsShown": true})); + if let Some(v) = num_field(ui, "tT", "Font size", c.size_pt * k * u, 0.1 * u..=1296.0 * u, unit, w) { + app.ui.tool_options.type_size = v / u; + apply(app, ui.ctx(), json!({"size": v / u, "metricsAsShown": true})); } let lead = c.leading_pt.unwrap_or(c.size_pt * para.auto_leading.max(0.01)) * k; - if let Some(v) = num_field(ui, "A↕", "Leading (set to the font size × auto-leading when Auto)", lead, 0.1..=5000.0, "pt", w) { - apply(app, ui.ctx(), json!({"leading": v, "metricsAsShown": true})); + if let Some(v) = num_field(ui, "A↕", "Leading (set to the font size × auto-leading when Auto)", lead * u, 0.1 * u..=5000.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"leading": v / u, "metricsAsShown": true})); } }); row(ui, &mut |ui| { @@ -2198,8 +2270,8 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa } }); row(ui, &mut |ui| { - if let Some(v) = num_field(ui, "Aª", "Baseline shift", c.baseline_shift_pt, -1296.0..=1296.0, "pt", w) { - apply(app, ui.ctx(), json!({"baselineShift": v})); + if let Some(v) = num_field(ui, "Aª", "Baseline shift", c.baseline_shift_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"baselineShift": v / u})); } // Colour: label + a swatch filling the rest of the second column. ui.horizontal(|ui| { @@ -2306,30 +2378,27 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa }); ui.add_space(ROW_GAP); row(ui, &mut |ui| { - if let Some(v) = num_field(ui, "→|", "Indent left margin", para.start_indent_pt, -1296.0..=1296.0, "pt", w) { - apply(app, ui.ctx(), json!({"startIndent": v})); + if let Some(v) = num_field(ui, "→|", "Indent left margin", para.start_indent_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"startIndent": v / u})); } - if let Some(v) = num_field(ui, "|←", "Indent right margin", para.end_indent_pt, -1296.0..=1296.0, "pt", w) { - apply(app, ui.ctx(), json!({"endIndent": v})); + if let Some(v) = num_field(ui, "|←", "Indent right margin", para.end_indent_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"endIndent": v / u})); } }); row(ui, &mut |ui| { - if let Some(v) = num_field(ui, "¶→", "Indent first line", para.first_line_indent_pt, -1296.0..=1296.0, "pt", w) { - apply(app, ui.ctx(), json!({"firstLineIndent": v})); + if let Some(v) = num_field(ui, "¶→", "Indent first line", para.first_line_indent_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"firstLineIndent": v / u})); } }); row(ui, &mut |ui| { - if let Some(v) = num_field(ui, "↑¶", "Add space before paragraph", para.space_before_pt, 0.0..=1296.0, "pt", w) { - apply(app, ui.ctx(), json!({"spaceBefore": v})); + if let Some(v) = num_field(ui, "↑¶", "Add space before paragraph", para.space_before_pt * u, 0.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"spaceBefore": v / u})); } - if let Some(v) = num_field(ui, "¶↓", "Add space after paragraph", para.space_after_pt, 0.0..=1296.0, "pt", w) { - apply(app, ui.ctx(), json!({"spaceAfter": v})); + if let Some(v) = num_field(ui, "¶↓", "Add space after paragraph", para.space_after_pt * u, 0.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"spaceAfter": v / u})); } }); - let mut hy = para.hyphenate; - if crate::widgets::checkbox(ui, &mut hy, "Hyphenate").changed() { - apply(app, ui.ctx(), json!({"hyphenate": hy})); - } + // Hyphenate is stored (⌥⇧⌘H / PSD AutoHyphenate) but layout never breaks words (#6710). ui.add_space(ROW_GAP); } } @@ -2700,6 +2769,51 @@ mod tests { assert_eq!(word_boundary("hello big world", 7, false), 6); assert_eq!(word_boundary("hello big world", 15, false), 10); } + #[test] + fn arrow_keys_reset_caret_blink_phase() { + let mut app = app(); + pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); + insert(&mut app, "Hello"); + app.ui.caret_blink_time = 0.0; + let ctx = egui::Context::default(); + + let has_caret = |app: &mut PhotocraftApp, ctx: &egui::Context, time: f64| -> bool { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 400.0)); + let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); + let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + draw_overlay(app, &painter, &xf); + }); + out.textures_delta.clear(); + out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::LineSegment { stroke, .. } if CARET_STROKES.contains(stroke))) + }; + + // Before resetting, the caret is in the off phase at t = 10.5 s (10500 / 530 = 19, odd phase) + assert!(!has_caret(&mut app, &ctx, 10.5), "caret should be off at t = 10.5 with phase 0.0"); + + ctx.begin_pass(egui::RawInput { + time: Some(10.5), + events: vec![egui::Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ..Default::default() + }); + handle_keys(&mut app, &ctx); + assert_eq!(app.ui.caret_blink_time, 10.5); + + // draw_overlay paints the solid caret in the new phase + assert!(has_caret(&mut app, &ctx, 10.5), "caret should be painted right after arrow key"); + } + + #[test] + fn pointer_up_click_resets_caret_blink_phase() { + let mut app = app(); + pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); + insert(&mut app, "Hello"); + app.ui.caret_blink_time = 0.0; + app.last_frame_time = 12.3; + pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); + assert_eq!(app.ui.caret_blink_time, 12.3); + } + #[test] fn double_click_from_move_tool_restores_move_tool_on_commit_and_cancel() { let (mut app, _) = variants(); diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index 7a23c9ccc3..5cbca3e2b4 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -115,6 +115,49 @@ fn new_app() -> PhotocraftApp { app } +/// #6085: the text caret is a solid black line inside a white halo, so it shows on a white +/// background (the black used to be a 0.75 pt hairline inside a white line) and on a dark one. +#[test] +fn the_caret_reads_on_white_and_on_black() { + use crate::canvas::{ToolEvent, tool_event}; + let mut app = new_app(); + app.ui.tool = crate::state::Tool::Type; + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 100.0 }, Modifiers::NONE); + // A caret, not the placeholder's selection; solid, whatever the blink (as while dragging). + let ed = app.ui.text_edit.as_mut().expect("editing"); + ed.anchor = ed.caret; + ed.dragging = true; + let xf = ViewXform { + rect: egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), + zoom: 1.0, + center: [100.0, 100.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + let mut h = + Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state(move |ui, app: &mut PhotocraftApp| super::draw_overlay(app, ui.painter(), &xf), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run(); + // Vertical line segments are the caret (the frame and underline run sideways). + let caret: Vec<(f32, egui::Color32)> = h + .output() + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::LineSegment { points: [a, b], stroke } if (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() > 1.0 => Some((stroke.width, stroke.color)), + _ => None, + }) + .collect(); + assert_eq!(caret.len(), 2, "a halo and a line: {caret:?}"); + let ((halo_w, halo), (line_w, line)) = (caret[0], caret[1]); + assert_eq!(line, egui::Color32::BLACK); + assert!(line_w >= 1.0, "a solid black line, not a hairline: {line_w}"); + assert_eq!(halo, egui::Color32::WHITE); + assert!(halo_w >= line_w + 2.0, "at least 1 pt of white on each side: {halo_w}"); +} + fn xf(app: &PhotocraftApp) -> ViewXform { let v = &app.ui.views[0]; ViewXform { @@ -921,6 +964,33 @@ fn temporary_type_transform_free_scale_center_scale_move_skew_and_rotation() { } } +/// Editing paragraph text, a click inside the box but off the glyphs moves the caret to the +/// nearest offset, as in Photoshop; a click outside the box still commits. +#[test] +fn click_inside_the_paragraph_box_off_the_glyphs_moves_the_caret() { + use crate::canvas::{ToolEvent, tool_event}; + // The box is 240 × 180; the two 32 pt lines only fill its top. + let (mut app, id) = transform_app(true, false, Affine::translate(400.0, 350.0)); + let (bx, by, _, h) = super::box_shape(&app, id).unwrap(); + let (l, aff, _) = layout(&mut app, id).unwrap(); + let click = |app: &mut PhotocraftApp, tx: f32, ty: f32| { + let p = aff.apply(Point::new(f64::from(tx), f64::from(ty))); + tool_event(app, ToolEvent::Down { x: p.x, y: p.y, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: p.x, y: p.y }, Modifiers::NONE); + }; + let layers = app.session.active().unwrap().doc.layers.len(); + // Near the bottom of the box, just right of its left edge. + assert!(!photocraft_text::text_point_inside(&l, bx + 8.0, by + h - 8.0, 6.0), "the point is off the glyphs"); + click(&mut app, bx + 8.0, by + h - 8.0); + let ed = app.ui.text_edit.clone().expect("still editing"); + // "Hello é世界\n" is 10 characters: the start of the second line. + assert_eq!((ed.layer, ed.caret, ed.anchor), (id.0, 10, 10)); + // Outside the box the edit commits, without starting new text. + click(&mut app, bx - 40.0, by + h - 8.0); + assert!(app.ui.text_edit.is_none()); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers); +} + #[test] fn temporary_type_transform_noop_cancel_and_stale_capture() { use crate::canvas::{ToolEvent, tool_event}; @@ -1508,6 +1578,14 @@ mod multi_layer_formatting { h.run(); } + #[test] + fn hyphenate_is_not_shown_while_layout_does_not_hyphenate() { + // #6710: layout never hyphenates; the control must stay hidden until it does. + let (app, _) = fixture(); + let h = controls(app, true); + assert!(h.query_by_label("Hyphenate").is_none()); + } + #[test] fn properties_edit_shown_metrics_and_paragraphs_with_a_non_type_primary() { let (mut app, ids) = fixture(); @@ -1525,8 +1603,6 @@ mod multi_layer_formatting { h.run(); h.get_by_label("Center text").click(); h.run(); - h.get_by_label("Hyphenate").click(); - h.run(); number(&mut h, "Indent left margin", "9"); for (id, scale) in [(ids[0], 2.0), (ids[1], 4.0)] { let c = style(h.state(), id, 0); @@ -1535,7 +1611,6 @@ mod multi_layer_formatting { assert!(c.faux_bold); let p = text(h.state(), id).paragraph_runs()[0].style.clone(); assert_eq!(p.align, TextAlign::Center); - assert!(p.hyphenate); assert_eq!(p.start_indent_pt, 9.0); } assert_eq!(style(h.state(), ids[2], 0), untouched); @@ -1549,6 +1624,27 @@ mod multi_layer_formatting { assert_eq!(text(h.state(), ids[1]).char_runs(), peer); } + /// #6491: with Units & Rulers ▸ Type set to pixels, the Character and Paragraph fields show + /// and take pixels, like the options bar. 144 ppi so a pixel is not a point. + #[test] + fn character_and_paragraph_fields_follow_the_type_units_preference() { + use egui_kittest::kittest::NodeT; + let (mut app, ids) = fixture(); + app.run("prefs.set", json!({"path": "unitsAndRulers.typeUnits", "value": "pixels"})).unwrap(); + app.run("image.imageSize", json!({"resolution": 144, "resample": "none"})).unwrap(); + selected(&mut app, &[ids[0]]); + let mut h = controls(app, true); + let shown = h.get_by_role_and_label(Role::SpinButton, "Font size").accesskit_node().numeric_value(); + assert_eq!(shown, Some(24.0), "12 pt at 144 ppi"); + number(&mut h, "Font size", "60"); + number(&mut h, "Leading (set to the font size × auto-leading when Auto)", "84"); + number(&mut h, "Baseline shift", "10"); + number(&mut h, "Indent left margin", "9"); + let c = style(h.state(), ids[0], 0); + assert_eq!((c.size_pt, c.leading_pt, c.baseline_shift_pt), (30.0, Some(42.0), 5.0)); + assert_eq!(text(h.state(), ids[0]).paragraph_runs()[0].style.start_indent_pt, 4.5); + } + /// #5717: a layer scaled so its shown size or leading is past a field's range (2400 pt, or /// 0.08 pt) keeps it while the Character panel and the options bar only show it. #[test] diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index 8acd676f95..ae19bfa6a3 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -459,6 +459,11 @@ pub fn handles(id: &str) -> bool { } pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { + is_enabled_with_engine(app, id, || app.session.is_enabled(id)) +} + +/// Keep picker enablement testable with the engine's native filesystem check disabled. +fn is_enabled_with_engine(app: &PhotocraftApp, id: &str, engine_enabled: impl FnOnce() -> bool) -> Option { if !handles(id) && !wraps(id) { return None; } @@ -476,7 +481,10 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { || (doc && matches!(&i["window.arrange.".len()..], "floatAllInWindows" | "cascade" | "tile" | "tileAllVertically" | "tileAllHorizontally")) } }, - i if wraps(i) => app.session.is_enabled(i), + // Embedded placement reads the picker's bytes on every platform. Linked placement keeps + // the engine's native filesystem guard because its source must remain reachable. + "file.placeEmbedded" => doc && app.services.file_dialog.is_some(), + i if wraps(i) => engine_enabled(), _ => true, }) } @@ -1434,32 +1442,32 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result { let suggested = format!("{stem} copy.psd"); // The copy is of the document as it was when asked. app.pick_save(&suggested, move |app, path| { - // An RGB Targa asks for its bits per pixel first; the copy is written from the prompt. + // An RGB Targa asks for its bits per pixel first, and a DDS texture for its compression; + // the copy is written from the prompt. let parked = app.with_document(doc.id, |app| { - let ask = crate::targa_options_ui::wants_prompt(app, &path); - if ask { + if crate::targa_options_ui::wants_prompt(app, &path) { crate::targa_options_ui::park(app, path.clone(), true, "file.saveACopy")?; + return Ok(true); } - Ok(ask) + if crate::dds_options_ui::wants_prompt(&path) { + crate::dds_options_ui::park(app, path.clone(), true, "file.saveACopy")?; + return Ok(true); + } + Ok(false) })?; if parked { return Ok(json!({"path": path, "warnings": []})); } - let r = write_copy(app, &doc, &path, None)?; + let r = write_copy(app, &doc, &path, crate::FormatChoices::default())?; app.session.journal.push(("file.saveACopy".into(), json!({"path": path}))); Ok(r) }) } /// Writes `doc` to `path` as a copy (Save a Copy, and its replayed action step): the document's -/// path and saved state are untouched. `tga_bits` is the Targa answer, when there is one. -pub(crate) fn write_copy( - app: &mut PhotocraftApp, - doc: &photocraft_doc::Document, - path: &str, - tga_bits: Option, -) -> Result { - let settings = crate::ExportSettings { tga_bits, ..app.save_settings() }; +/// path and saved state are untouched. `choices` are the Targa and DDS answers, when there are any. +pub(crate) fn write_copy(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, path: &str, choices: crate::FormatChoices) -> Result { + let settings = choices.apply(app.save_settings()); let export = app.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(doc, path, &settings)?; let write = app.services.write.as_mut().ok_or("no writer configured")?; diff --git a/crates/ui-egui/src/view_cmds/tests.rs b/crates/ui-egui/src/view_cmds/tests.rs index 2205b6e157..407d8e6824 100644 --- a/crates/ui-egui/src/view_cmds/tests.rs +++ b/crates/ui-egui/src/view_cmds/tests.rs @@ -14,6 +14,32 @@ fn checked(app: &PhotocraftApp, id: &str) -> Option { menu_items(app).into_iter().find(|i| i.id == id).and_then(|i| i.checked) } +/// #1209: the browser picker supplies bytes even when the engine cannot read native paths. +#[test] +fn place_embedded_enablement_does_not_require_native_doc() { + for has_doc in [true, false] { + for has_picker in [true, false] { + let (mut app, _) = app_with(usize::from(has_doc)); + if has_picker { + app.services.file_dialog = Some(Box::new(|_, _, _| {})); + } + for native_filesystem in [false, true] { + let native_doc = native_filesystem && has_doc; + assert_eq!( + is_enabled_with_engine(&app, "file.placeEmbedded", || native_doc), + Some(has_doc && has_picker), + "Place Embedded: doc={has_doc}, picker={has_picker}, native_doc={native_doc}" + ); + assert_eq!( + is_enabled_with_engine(&app, "file.placeLinked", || native_doc), + Some(native_doc), + "Place Linked must retain the engine's native_doc guard" + ); + } + } + } +} + #[test] fn show_snap_extras_and_screen_modes_are_state() { let (mut app, ctx) = app_with(1); @@ -474,6 +500,29 @@ fn press_esc(app: &mut PhotocraftApp, ctx: &egui::Context) { ctx.run_ui(input, |ui| crate::shortcuts::handle(app, ui.ctx())).textures_delta.clear(); } +#[test] +fn esc_leaves_full_screen_with_the_crop_tool_showing_its_default_frame() { + let (mut app, ctx) = app_with(1); + app.ui.tool = crate::Tool::Crop; + crate::crop_ui::ensure_frame(&mut app); + assert!(app.ui.crop_rect.is_some() && app.crop.default_frame); + for mode in ["fullScreen", "fullScreenWithMenuBar"] { + menu(&mut app, &ctx, &format!("view.screenMode.{mode}"), json!({})).unwrap(); + press_esc(&mut app, &ctx); + assert_eq!(app.ui.view.screen_mode, "standard", "{mode}"); + assert!(app.ui.crop_rect.is_some() && app.crop.default_frame, "{mode}: the default frame stays"); + } + // With Straighten armed, Esc drops it first and the mode stays. + menu(&mut app, &ctx, "view.screenMode.fullScreen", json!({})).unwrap(); + app.crop.straighten.armed = true; + press_esc(&mut app, &ctx); + assert!(!app.crop.straighten.armed); + assert_eq!(app.ui.view.screen_mode, "fullScreen"); + crate::crop_ui::ensure_frame(&mut app); + press_esc(&mut app, &ctx); + assert_eq!(app.ui.view.screen_mode, "standard"); +} + #[test] fn esc_leaves_full_screen_modes_unless_something_else_owns_it() { let (mut app, ctx) = app_with(1); @@ -506,3 +555,66 @@ fn esc_leaves_full_screen_modes_unless_something_else_owns_it() { assert_eq!(app.ui.view.screen_mode, "standard"); assert!(app.session.active().unwrap().doc.selection.is_some()); } + +/// #6017: a click into another tile activated that document and moved it to the first tile, so +/// the two side-by-side documents swapped places. Each document keeps its tile; with more +/// documents than tiles, the shown run slides just enough to include the active one. +#[test] +fn arranged_documents_keep_their_tiles() { + let rect = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(900.0, 600.0)); + let (mut app, _) = app_with(3); + app.ui.view.arrange = "tileAllVertically".into(); + for active in 0..3 { + app.session.set_active(active); + let shown = crate::canvas::arranged_cells(&app, rect).unwrap(); + let order: Vec = shown.iter().map(|(d, _)| *d).collect(); + assert_eq!(order, vec![0, 1, 2], "active {active}"); + assert!(shown.windows(2).all(|w| w[0].1.left() < w[1].1.left()), "document 0 on the left"); + } + app.ui.view.arrange = "twoUpVertical".into(); + // As `documents` draws them: the shown run is kept from frame to frame. + let docs = |app: &mut PhotocraftApp, active: usize| { + app.session.set_active(active); + let shown: Vec = crate::canvas::arranged_cells(app, rect).unwrap().iter().map(|(d, _)| *d).collect(); + app.arrange_start = shown[0]; + shown + }; + assert_eq!(docs(&mut app, 0), vec![0, 1]); + assert_eq!(docs(&mut app, 1), vec![0, 1], "the second tile's document stays on the right"); + assert_eq!(docs(&mut app, 2), vec![1, 2], "the third document slides in next to the second"); + assert_eq!(docs(&mut app, 1), vec![1, 2], "a click into the visible document 1 leaves the tiles as they are"); + assert_eq!(docs(&mut app, 0), vec![0, 1], "a hidden document slides in from the left"); + assert_eq!(docs(&mut app, 1), vec![0, 1]); +} + +/// #6017: rulers showed in the active tile only; the other tile had none and no room for them. +#[test] +fn every_arranged_tile_has_rulers() { + use egui_kittest::Harness; + let (mut app, _) = app_with(2); + app.ui.view.arrange = "tileAllVertically".into(); + app.ui.extras.rulers = true; + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let right = h.state().last_canvas_rect.center().x; + // Ruler labels are 9 pt text: some lie in each half of the document area. + let mut labels = [0, 0]; + for s in &h.output().shapes { + if let egui::Shape::Text(t) = &s.shape + && t.galley.job.sections.first().is_some_and(|sec| sec.format.font_id.size == 9.0) + && t.galley.text().chars().all(|c| c.is_ascii_digit()) + { + labels[usize::from(t.pos.x > right)] += 1; + } + } + assert!(labels[0] > 0 && labels[1] > 0, "ruler labels per tile: {labels:?}"); +} diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index bde5e71ae3..68a2321c44 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -8,6 +8,9 @@ //! - A trackpad pinch zooms around the pointer, unless Preferences › Enhanced Controls › //! Zoom with Trackpad Pinch is off (then a pinch does nothing, and Windows' Ctrl + wheel //! fractions scroll sideways like the wheel, because the fold below is skipped). +//! - A two-finger pinch on a touch screen zooms the same way, unless Preferences › Enhanced +//! Controls › Enable Gestures is off (#204): then the fingers leave the view alone, and a +//! trackpad pinch still zooms ([`pinch_factor`]). //! //! [`configure`] makes egui fold ⌘/Ctrl + wheel into a sideways scroll as it does ⇧ + wheel, so //! only a real pinch (egui's `Event::Zoom`, or a touch screen) reaches `zoom_delta`. macOS and @@ -23,7 +26,7 @@ //! keeps the smoothed delta. The Alt state is taken from the wheel events and kept until the next //! wheel event: releasing Alt while the tail is still settling must not turn it into a pan. -use egui::{Context, Event, Id, Modifiers, MouseWheelUnit, RawInput, Vec2}; +use egui::{Context, Event, Id, InputState, Modifiers, MouseWheelUnit, RawInput, Vec2}; /// Zoom factor of one wheel notch: every step is exactly ×1.1. pub const NOTCH: f32 = 1.1; @@ -198,13 +201,15 @@ const SNAP_IDLE_TIMEOUT: f64 = 0.5; /// accumulator per viewport. `hovered` gates accumulation: only the viewport receiving /// navigation may add raw input to the snap residual. pub fn read(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool) -> Option { - read_with(ctx, zoom_with_wheel, pinch_zooms, owner, hovered, true) + read_with(ctx, zoom_with_wheel, pinch_zooms, owner, hovered, true, true) } /// [`read`], choosing how a plain wheel scroll pans: `smooth` glides it over a few frames (egui's /// smoothed delta); off, as with Interface › Enable Animations off, the view moves the whole notch /// in the frame the wheel turns and stops there (#5721), as scroll areas already do. -pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool, smooth: bool) -> Option { +/// `touch_gestures` is Preferences › Enhanced Controls › Enable Gestures: off, a touch screen's +/// two-finger pinch doesn't zoom ([`pinch_factor`]). +pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool, smooth: bool, touch_gestures: bool) -> Option { let notch = ctx.options(|o| o.input_options.line_scroll_speed); // --- Modifier tracking (always runs for all callers) --- @@ -225,7 +230,7 @@ pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: _ => None, }) .collect(); - (i.smooth_scroll_delta, i.zoom_delta(), latest_alt, latest_shift, wheel, i.content_rect().height()) + (i.smooth_scroll_delta, pinch_factor(i, touch_gestures), latest_alt, latest_shift, wheel, i.content_rect().height()) }); let alt = match latest_alt { Some(a) => { @@ -329,6 +334,24 @@ pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: } } +/// This frame's pinch zoom factor (1 = none). While two fingers are down on a touch screen, egui's +/// `zoom_delta` reports their pinch in place of the trackpad's `Event::Zoom`. With Preferences › +/// Enhanced Controls › Enable Gestures off (`touch_gestures` false) the fingers are ignored and only +/// the trackpad's own pinch events count (Windows' Ctrl + wheel pinch included: [`fold_legacy_pinch`] +/// has already turned it into `Event::Zoom`). +pub fn pinch_factor(i: &InputState, touch_gestures: bool) -> f32 { + if touch_gestures || i.multi_touch().is_none() { + return i.zoom_delta(); + } + i.events + .iter() + .filter_map(|e| match e { + Event::Zoom(f) if f.is_finite() && *f > 0.0 => Some(*f), + _ => None, + }) + .product() +} + #[cfg(test)] mod tests { use egui::TouchPhase; @@ -393,7 +416,7 @@ mod tests { let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; let mut pan = Vec2::ZERO; let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), false, true, owner, true, smooth) { + if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), false, true, owner, true, smooth, true) { pan = d; } }); @@ -922,4 +945,62 @@ mod tests { let (_, _, snaps) = gesture(vec![vec![wheel(Vec2::new(0.0, -1.0), Modifiers::SHIFT)]], true, false); assert_eq!(snaps, -1, "Line-unit notch down produces −1 step"); } + + /// Two fingers on a touch screen: down 20 points apart, spread to 40 (a ×2 pinch), lifted. + fn touch_pinch_frames() -> Vec> { + let touch = |id: u64, phase: TouchPhase, x: f32| Event::Touch { + device_id: egui::TouchDeviceId(1), + id: egui::TouchId(id), + phase, + pos: egui::pos2(x, 50.0), + force: None, + }; + vec![ + // egui only starts a multi-touch gesture once it knows where the pointer is. + vec![Event::PointerMoved(egui::pos2(40.0, 50.0))], + vec![touch(1, TouchPhase::Start, 40.0), touch(2, TouchPhase::Start, 60.0)], + vec![touch(1, TouchPhase::Move, 30.0), touch(2, TouchPhase::Move, 70.0)], + vec![touch(1, TouchPhase::End, 30.0), touch(2, TouchPhase::End, 70.0)], + ] + } + + /// The total zoom [`read_with`] reports over `frames`, Enable Gestures set to `touch_gestures`. + fn touch_zoom(frames: Vec>, touch_gestures: bool) -> f32 { + let owner = Id::new("test-touch"); + let ctx = Context::default(); + configure(&ctx); + let mut zoom = 1.0; + for (n, events) in (0u32..).zip(frames) { + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read_with(ui.ctx(), false, true, owner, true, true, touch_gestures) { + zoom *= f; + } + }); + out.textures_delta.clear(); + } + zoom + } + + /// Preferences › Enhanced Controls › Enable Gestures (#204): on (the default) a two-finger + /// pinch on a touch screen zooms; off, it leaves the view alone. + #[test] + fn enable_gestures_switches_touch_screen_pinch_zoom() { + let on = touch_zoom(touch_pinch_frames(), true); + assert!((on - 2.0).abs() < 1e-4, "on: the fingers zoom ×2: {on}"); + let off = touch_zoom(touch_pinch_frames(), false); + assert_eq!(off, 1.0, "off: the fingers don't zoom"); + } + + /// Enable Gestures off only silences the touch screen: a trackpad pinch still zooms, also in a + /// frame where two fingers rest on the screen (egui's `zoom_delta` would report theirs instead). + #[test] + fn enable_gestures_off_keeps_the_trackpad_pinch() { + let zoom = touch_zoom(vec![vec![Event::Zoom(1.25)]], false); + assert!((zoom - 1.25).abs() < 1e-4, "no fingers down: {zoom}"); + let mut frames = touch_pinch_frames(); + frames[2] = vec![Event::Zoom(1.25)]; + let zoom = touch_zoom(frames, false); + assert!((zoom - 1.25).abs() < 1e-4, "fingers resting: {zoom}"); + } } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 2acbdf3c8b..0a91058387 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1,4 +1,4 @@ -//! Custom widgets for the Photocraft look: cards with pill tabs, thin sliders with round knobs, +//! Custom widgets for the PhotoCraft look: cards with pill tabs, thin sliders with round knobs, //! monospace value fields with dimmed units, toggle switches, primary/secondary buttons. use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; @@ -350,6 +350,25 @@ pub fn value_field_units(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInc value_field_in(ui, value, range, "", width, 0.0, FieldOpts { decimals: Some(decimals), units: Some(units), ..Default::default() }).0 } +/// A [`value_field_prec`] in `units` whose 100 % is a length of `extent` px (Free Transform's W +/// and H): a length typed while it shows percent becomes that share of `extent` (`40px`, `2in`), +/// and a percentage typed while it shows a length becomes that share of `extent` (`50%`), at +/// `units`' resolution (#6284). The field keeps its own unit. +#[allow(clippy::too_many_arguments)] +pub fn value_field_extent( + ui: &mut Ui, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + width: f32, + decimals: u32, + units: FieldUnits, + extent: f64, +) -> Response { + let opts = FieldOpts { decimals: Some(decimals), units: Some(units), extent: Some(extent), ..Default::default() }; + value_field_in(ui, value, range, suffix, width, 0.0, opts).0 +} + fn field_resolution_id() -> egui::Id { egui::Id::new("pc-field-resolution") } @@ -499,6 +518,8 @@ struct FieldOpts { decimals: Option, /// The unit typed units convert into (default: the suffix's, at [`set_field_resolution`]). units: Option, + /// The length (px) 100 % stands for, so lengths and percentages convert into each other. + extent: Option, wrap_drag: bool, } @@ -526,7 +547,7 @@ fn value_field_box( trailing: f32, opts: FieldOpts, ) -> (Response, Rect) { - let FieldOpts { decimals, units, wrap_drag } = opts; + let FieldOpts { decimals, units, extent, wrap_drag } = opts; let t = Tokens::get(ui.ctx()); let (rect, slot) = ui.allocate_exact_size(size, Sense::hover()); let scrub = take_label_scrub(ui, rect).map(|s| { @@ -544,8 +565,8 @@ fn value_field_box( // Typed text loses its spaces before parsing, so a " pt" suffix reads as "pt". let typed_suffix = suffix.trim(); let units = match units { - Some(u) => crate::numeric_expression::Units { unit: Some(u.unit), suffix: typed_suffix, dpi: u.dpi, ppi: u.ppi }, - None => crate::numeric_expression::Units { unit: unit_of_suffix(typed_suffix), suffix: typed_suffix, dpi, ppi }, + Some(u) => crate::numeric_expression::Units { unit: Some(u.unit), suffix: typed_suffix, dpi: u.dpi, ppi: u.ppi, extent }, + None => crate::numeric_expression::Units { unit: unit_of_suffix(typed_suffix), suffix: typed_suffix, dpi, ppi, extent }, }; surface(ui, rect, t.field, false); if !t.bevel { @@ -793,6 +814,8 @@ pub fn focus_first_field(ctx: &egui::Context, on: bool) { }); } +const NUMERIC_INPUT_LIMIT: usize = 128; + /// The number in a [`value_field`]. A typed number applies as it's typed; arithmetic waits for /// Enter, Tab or click-away, because per keystroke `5/2` would land first and a caller that /// rounds it would cut `5/2*2` short. `changed()` means a new value, not just a keystroke. @@ -814,6 +837,25 @@ fn number_edit( if ui.is_enabled() { crate::field_tab::register(&ctx, id); } + // Use DragValue's focus check before it builds its TextEdit: oversized events must never + // reach text layout. Registering interest also handles focus arriving by Tab this frame. + let editing = ui.is_enabled() + && ui.memory_mut(|m| { + m.interested_in_focus(id, ui.layer_id()); + m.has_focus(id) + }); + if editing { + ui.input_mut(|input| { + input.events.retain(|event| { + let text = match event { + egui::Event::Text(text) | egui::Event::Paste(text) | egui::Event::Ime(egui::ImeEvent::Commit(text)) => text, + egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => text, + _ => return true, + }; + text.chars().nth(NUMERIC_INPUT_LIMIT).is_none() + }); + }); + } let held = id.with("arithmetic"); let math = ui.memory(|m| m.has_focus(id)) && ui.data(|d| d.get_temp(held)).unwrap_or(false); ui.data_mut(|d| d.insert_temp(held, math)); @@ -837,6 +879,10 @@ fn number_edit( .update_while_editing(!math) // Focus is read when parsing, not above: Tab hands it on inside `ui.add`. .custom_parser(move |s| { + // Short events can accumulate: reject before either parser normalizes the text. + if s.chars().nth(NUMERIC_INPUT_LIMIT).is_some() { + return None; + } let v = parse_num_in(s, units); if ctx.memory(|m| m.has_focus(id)) && plain(s).is_none() { // Still typing arithmetic: hold it, and stop applying keystrokes once it parses. @@ -901,6 +947,34 @@ pub struct RowGestures { /// Each wheel notch over the slider moves the value by this step (up = higher; ×10 with /// Shift). Photoshop does this in dialogs, not in the Properties panel. pub wheel_step: Option, + /// A curved track: the knob at fraction f of the track is `lo + (hi - lo) * f^k`, so small + /// values get fine steps (Photoshop's mask Feather, #6545). Typed, scrubbed and stepped + /// values stay linear; only the track maps through the curve. + pub curve: Option, +} + +/// The value at fraction `f` of a track over `lo..=hi`, through `curve` (see [`RowGestures`]). +pub(crate) fn curve_value(f: f32, lo: f32, hi: f32, curve: Option) -> f32 { + match curve { + Some(k) if k.is_finite() && k > 0.0 => lo + f.clamp(0.0, 1.0).powf(k) * (hi - lo), + _ => lo + f * (hi - lo), + } +} + +/// Where `v` sits on a track over `lo..=hi`, as a fraction: the inverse of [`curve_value`]. +pub(crate) fn curve_fraction(v: f32, lo: f32, hi: f32, curve: Option) -> f32 { + let f = ((v - lo) / (hi - lo)).clamp(0.0, 1.0); + match curve { + // An unset (NaN) value draws the knob at the start rather than nowhere. + Some(k) if k.is_finite() && k > 0.0 => { + if f.is_finite() { + f.powf(1.0 / k) + } else { + 0.0 + } + } + _ => f, + } } /// Wheel notches this frame while the pointer is over `resp` (Shift ×10). Wheel lines add up in @@ -985,7 +1059,7 @@ fn slider_with(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive f32::EPSILON { *value = nv; resp.mark_changed(); @@ -1008,7 +1082,7 @@ fn slider_with(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive { pub label: &'a str, pub min_width: f32, pub enabled: bool, + /// Take keyboard focus this frame (see [`DialogButton::focus`]). + pub focus: bool, } impl<'a> DialogButton<'a> { pub fn new(role: ButtonRole, label: &'a str, min_width: f32) -> Self { - Self { role, label, min_width, enabled: true } + Self { role, label, min_width, enabled: true, focus: false } } pub fn enabled(self, enabled: bool) -> Self { Self { enabled, ..self } } + + /// Asks for keyboard focus for this button: from there the arrow keys move between the row's + /// buttons and Enter or Space presses the focused one. + pub fn focus(self, focus: bool) -> Self { + Self { focus, ..self } + } } /// A dialog's button row at the cursor, in the platform's order (see [`ButtonRole`]): every modal @@ -1225,6 +1307,9 @@ pub fn dialog_buttons(ui: &mut Ui, buttons: &[DialogButton]) -> Option Vec2 { button_layout(ui, label, min_width, None, Tokens::get(ui.ctx()).text).1 } +/// The height of a primary or secondary button (and so of a dialog's button row). +pub fn button_height(ctx: &egui::Context) -> f32 { + if Tokens::get(ctx).pro { 28.0 } else { 30.0 } +} + fn button_layout(ui: &Ui, label: &str, min_width: f32, height: Option, fg: Color32) -> (std::sync::Arc, Vec2) { let galley = ui.painter().layout_no_wrap(tl!(label).to_owned(), theme::medium(13.0), fg); - let h = height.unwrap_or(if Tokens::get(ui.ctx()).pro { 28.0 } else { 30.0 }); + let h = height.unwrap_or(button_height(ui.ctx())); let size = vec2((galley.size().x + 28.0).max(min_width), h); (galley, size) } @@ -2057,6 +2147,28 @@ mod tests { assert_eq!(press(&mut h, Modifiers::SHIFT, Key::ArrowUp), 1000.0); } + /// #6545: a curved track (the mask Feather) has fine steps at the left and coarse ones toward + /// the right end, and the knob drawn for a value lands where that value is picked. + #[test] + fn curved_track_maps_ends_middle_and_round_trips() { + use super::{curve_fraction, curve_value}; + for (f, want) in [(0.0, 0.0), (0.1, 1.0), (0.2, 8.0), (0.5, 125.0), (1.0, 1000.0)] { + assert!((curve_value(f, 0.0, 1000.0, Some(3.0)) - want).abs() < 1e-3, "{f}: {}", curve_value(f, 0.0, 1000.0, Some(3.0))); + } + assert_eq!(curve_value(0.25, 0.0, 1000.0, None), 250.0, "no curve is the linear track"); + assert_eq!(curve_value(0.5, 10.0, 20.0, Some(3.0)), 11.25, "the curve starts at the range's low end"); + for i in 0..=100 { + let f = i as f32 / 100.0; + let back = curve_fraction(curve_value(f, 0.0, 1000.0, Some(3.0)), 0.0, 1000.0, Some(3.0)); + assert!((back - f).abs() < 1e-4, "{f} -> {back}"); + let v = i as f32 * 10.0; + let again = curve_value(curve_fraction(v, 0.0, 1000.0, Some(3.0)), 0.0, 1000.0, Some(3.0)); + assert!((again - v).abs() < 1e-3, "{v} -> {again}"); + } + assert_eq!(curve_fraction(-5.0, 0.0, 1000.0, Some(3.0)), 0.0); + assert_eq!(curve_fraction(f32::NAN, 0.0, 1000.0, Some(3.0)), 0.0); + } + #[test] fn arrow_keys_work_out_a_typed_sum_then_step_it() { let mut h = focused(100.0, 0.0..=1000.0); @@ -2643,3 +2755,7 @@ mod screen_color_tests { } } } + +#[cfg(test)] +#[path = "widgets/numeric_input_tests.rs"] +mod numeric_input_tests; diff --git a/crates/ui-egui/src/widgets/numeric_input_tests.rs b/crates/ui-egui/src/widgets/numeric_input_tests.rs new file mode 100644 index 0000000000..41eff2ed4c --- /dev/null +++ b/crates/ui-egui/src/widgets/numeric_input_tests.rs @@ -0,0 +1,195 @@ +//! Reject oversized numeric events before layout while preserving DragValue behavior. + +use egui::{Event, ImeEvent, Key, Modifiers, accesskit::Role}; +use egui_kittest::{Harness, kittest::Queryable}; + +const LIMIT: usize = super::NUMERIC_INPUT_LIMIT; +type Fields = (f32, String); + +fn fields() -> Harness<'static, Fields> { + let mut h = Harness::builder().with_size(egui::vec2(400.0, 180.0)).build_ui_state( + |ui, (number, text): &mut Fields| { + super::value_field(ui, number, 0.01..=12800.0, "%", 90.0); + ui.add(egui::TextEdit::multiline(text).hint_text("Document text")); + }, + (100.0, String::new()), + ); + h.run(); + h +} + +fn focused() -> Harness<'static, Fields> { + let mut h = fields(); + h.get_by_role(Role::SpinButton).click(); + h.run(); + h +} + +fn numeric_text(h: &Harness<'_, Fields>) -> String { + h.query_by_role(Role::TextInput).or_else(|| h.query_by_role(Role::SpinButton)).expect("numeric editor").value().expect("numeric text") +} + +fn select_all(h: &mut Harness<'_, Fields>) { + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.run(); +} + +fn assert_bounded(h: &Harness<'_, Fields>) { + fn longest(shape: &egui::Shape) -> usize { + match shape { + egui::Shape::Text(text) => text.galley.job.text.chars().count(), + egui::Shape::Vec(shapes) => shapes.iter().map(longest).max().unwrap_or(0), + _ => 0, + } + } + let drawn = h.output().shapes.iter().map(|shape| longest(&shape.shape)).max().unwrap_or(0); + assert!(drawn <= LIMIT, "numeric input laid out {drawn} characters; expected at most {LIMIT}"); + let retained = numeric_text(h).chars().count(); + assert!(retained <= LIMIT, "numeric editor retained {retained} characters; expected at most {LIMIT}"); +} + +#[test] +fn oversized_numeric_text_paste_and_ime_are_bounded_before_layout() { + for (index, event) in [ + Event::Text("9".repeat(16 * 1024)), + Event::Paste("x".repeat(16 * 1024)), + Event::Ime(ImeEvent::Preedit { text: "é".repeat(8 * 1024), active_range_chars: None }), + Event::Ime(ImeEvent::Commit("é".repeat(8 * 1024))), + ] + .into_iter() + .enumerate() + { + let mut h = focused(); + select_all(&mut h); + if matches!(&event, Event::Ime(_)) { + // egui 0.36 assigns IME events to the focused widget; Enabled is deprecated and + // ignored. Prove both live composition and commitment reach this field first. + h.event(Event::Ime(ImeEvent::Preedit { text: "に".into(), active_range_chars: Some(0..1) })); + h.run(); + assert_eq!(numeric_text(&h), "に", "short IME composition reaches the numeric editor"); + h.event(Event::Ime(ImeEvent::Commit("é".into()))); + h.run(); + assert_eq!(numeric_text(&h), "é", "IME commit replaces its composition"); + select_all(&mut h); + } + h.event(event); + h.run(); + if let Some(dir) = std::env::var_os("CRAFT_NUMERIC_INPUT_FIXTURES") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).expect("create numeric fixture directory"); + h.render().expect("render numeric fixture").save(dir.join(format!("event-{index}.png"))).expect("save numeric fixture"); + } + assert_bounded(&h); + assert_eq!(h.state().0, 100.0, "invalid input leaves the numeric value unchanged"); + h.run(); + assert_bounded(&h); + } +} + +#[test] +fn numeric_replacement_clear_and_undo_preserve_unicode_input() { + let mut h = focused(); + select_all(&mut h); + for _ in 0..4 { + h.event(Event::Text("é".repeat(16))); + h.run(); + assert_bounded(&h); + } + let retained = numeric_text(&h); + assert!(!retained.is_empty(), "ordinary short inputs still enter the editor"); + // Let egui's text undoer store the stable text before clearing it. + h.input_mut().time = Some(h.ctx.input(|i| i.time) + 2.0); + h.run(); + select_all(&mut h); + h.key_press(Key::Backspace); + h.run(); + assert_eq!(numeric_text(&h), ""); + h.key_press_modifiers(Modifiers::COMMAND, Key::Z); + h.run(); + assert_eq!(numeric_text(&h), retained, "undo restores only the bounded input"); + assert_bounded(&h); + select_all(&mut h); + h.event(Event::Text("−4+6.5".into())); + h.run(); + assert_eq!(numeric_text(&h), "−4+6.5", "replacement accepts Unicode arithmetic"); + h.key_press(Key::Enter); + h.run(); + assert_eq!(h.state().0, 2.5); +} + +#[test] +fn numeric_input_limit_does_not_truncate_document_text() { + for switch_from_numeric in [false, true] { + let mut h = if switch_from_numeric { focused() } else { fields() }; + let text = "é".repeat(8 * 1024); + h.get_by_role(Role::MultilineTextInput).click(); + h.run(); + h.event(Event::Paste(text.clone())); + h.run(); + assert_eq!(h.state().1, text, "document paste preserved when switching from numeric: {switch_from_numeric}"); + assert_eq!(h.get_by_role(Role::MultilineTextInput).value().as_deref(), Some(text.as_str())); + assert_eq!(h.state().0, 100.0); + } +} + +#[test] +fn numeric_event_limit_counts_unicode_characters_and_rejects_without_truncating() { + let mut h = focused(); + select_all(&mut h); + let boundary = "é".repeat(LIMIT); + h.event(Event::Paste(boundary.clone())); + h.run(); + assert_eq!(numeric_text(&h), boundary); + select_all(&mut h); + h.event(Event::Text("9".repeat(LIMIT + 1))); + h.run(); + assert_eq!(numeric_text(&h), boundary, "oversized input leaves the selection intact"); + h.event(Event::Text("42".into())); + h.run(); + assert_eq!(h.state().0, 42.0); +} + +#[test] +fn numeric_parser_rejects_oversized_accumulated_text_before_normalizing() { + let mut h = focused(); + select_all(&mut h); + // Each event is under the cap, but the resulting input is too long. Normalizing first + // would hide all the spaces and apply 2. DragValue still owns its editable text. + h.event(Event::Text(" ".repeat(LIMIT / 2))); + h.run(); + h.event(Event::Text(format!("{}2", " ".repeat(LIMIT / 2)))); + h.run(); + assert_eq!(numeric_text(&h).chars().count(), LIMIT + 1); + assert_eq!(h.state().0, 100.0, "oversized plain input must not apply live"); + h.key_press(Key::Enter); + h.run(); + assert_eq!(h.state().0, 100.0, "oversized input must not apply on commit"); +} + +#[test] +fn tab_and_paste_in_one_frame_filter_only_the_receiving_numeric_field() { + let mut h = focused(); + let text = "x".repeat(16 * 1024); + h.key_press(Key::Tab); + h.event(Event::Paste(text.clone())); + h.run(); + assert_eq!(h.state().1, text, "Tab to document text preserves the paste"); + // Put the numeric field after a text field to exercise incoming forward Tab too. + // egui deliberately delays backwards traversal until the next frame. + let mut h = Harness::builder().with_size(egui::vec2(400.0, 180.0)).build_ui_state( + |ui, (number, text): &mut Fields| { + ui.add(egui::TextEdit::multiline(text).hint_text("Document text")); + super::value_field(ui, number, 0.01..=12800.0, "%", 90.0); + }, + (100.0, String::new()), + ); + h.run(); + h.get_by_role(Role::MultilineTextInput).click(); + h.run(); + h.key_press(Key::Tab); + h.event(Event::Paste("9".repeat(16 * 1024))); + h.run(); + assert_eq!(h.state().0, 100.0); + assert!(h.state().1.is_empty()); + assert_bounded(&h); +} diff --git a/crates/ui-egui/tests/crop_popup_keys.rs b/crates/ui-egui/tests/crop_popup_keys.rs new file mode 100644 index 0000000000..9c893ae7e0 --- /dev/null +++ b/crates/ui-egui/tests/crop_popup_keys.rs @@ -0,0 +1,92 @@ +//! Crop tool: Esc and Enter belong to an open options bar popup first (#7386). The shortcut pass +//! runs before the panels are drawn, so the crop branch used to take the key: Esc cancelled the +//! frame and left the Ratio list open, Enter committed the crop beneath it. +//! +//! Skips when no GPU adapter exists (like `crop_default_mode.rs`). + +use egui::Key; +use egui_kittest::kittest::Queryable; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::control::{ControlRequest, handle}; +use serde_json::{Value, json}; + +type Harness = egui_kittest::Harness<'static, PhotocraftApp>; + +fn harness() -> Option { + let built = std::panic::catch_unwind(|| { + egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_max_steps(64).wgpu().build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + // The queries below use English labels; don't follow the system locale. + app.session.prefs.edit(|p| p.interface.language = "en".into()); + if let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app + }) + }); + match built { + Ok(h) => Some(h), + Err(_) => { + eprintln!("skipping: no GPU adapter"); + None + } + } +} + +fn control(h: &mut Harness, method: &str, params: Value) { + let ctx = h.ctx.clone(); + let (req, _rx) = ControlRequest::new(method, params); + handle(h.state_mut(), &ctx, &req); + h.run_steps(3); +} + +/// A 200x100 document with the Crop tool's 1:1 frame pending and the Ratio list open again. +fn setup() -> Option { + let mut h = harness()?; + h.run_steps(4); + { + let app = h.state_mut(); + app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).expect("new"); + app.sync_views(); + } + control(&mut h, "ui.set", json!({"tool": "crop", "zoom": 1.0, "center": [100, 50]})); + h.get_by_value("Ratio").click(); + h.run_steps(3); + h.get_by_label("1 : 1 (Square)").click(); + h.run_steps(3); + assert!(photocraft_ui_egui::crop_ui::pending(h.state()), "the 1:1 frame is pending"); + assert!(!egui::Popup::is_any_open(&h.ctx), "the list closed after the pick"); + h.get_by_value("1 : 1 (Square)").click(); + h.run_steps(3); + assert!(egui::Popup::is_any_open(&h.ctx), "the Ratio list is open again"); + Some(h) +} + +#[test] +fn esc_closes_the_open_ratio_list_and_keeps_the_frame() { + // Windows WARP can access-violate when GPU harnesses initialize or tear down concurrently: + // hold the GPU lock for the whole test, harness included. + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut h) = setup() else { return }; + let frame = h.state().ui.crop_rect; + h.key_press(Key::Escape); + h.run_steps(3); + assert!(!egui::Popup::is_any_open(&h.ctx), "Esc closes the list"); + assert_eq!(h.state().ui.crop_rect, frame, "the frame stays as it was"); + assert!(photocraft_ui_egui::crop_ui::pending(h.state()), "still pending"); + // With the list closed, the keys reach the crop again: Enter commits it. + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.size, photocraft_doc::Size::new(100, 100), "the next Enter crops"); +} + +#[test] +fn enter_with_the_ratio_list_open_does_not_commit_the_crop() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut h) = setup() else { return }; + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.size, photocraft_doc::Size::new(200, 100), "nothing cropped"); + assert!(photocraft_ui_egui::crop_ui::pending(h.state()), "the frame is still pending"); +} diff --git a/crates/ui-egui/tests/drag_preview_canvas.rs b/crates/ui-egui/tests/drag_preview_canvas.rs index fc516ed307..9b7d682abb 100644 --- a/crates/ui-egui/tests/drag_preview_canvas.rs +++ b/crates/ui-egui/tests/drag_preview_canvas.rs @@ -295,3 +295,27 @@ fn a_held_marquee_drag_keeps_requesting_frames() { assert!(d.is_some_and(|d| d <= Duration::from_millis(100)), "mid-drag repaint request: {d:?}"); button(&mut h, 300.0, 220.0, false); } + +#[test] +fn the_spot_healing_trail_is_a_dark_half_opaque_tint() { + // #7342: the trail was white at a quarter opacity, invisible on white and faint elsewhere. + // Photoshop shows the area to heal in half-opaque dark grey. + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut h) = harness(1.0) else { return }; + h.run_steps(4); + for bg in ["white", "#808080"] { + setup(&mut h, bg, "spotHealing"); + let app = h.state_mut(); + app.session.tools.brush.size = 40.0; + app.session.tools.brush.hardness = 1.0; + let before = render(&mut h); + drag_to(&mut h, [80.0, 150.0], [320.0, 150.0]); + let img = render(&mut h); + let p = screen(&h, 200.0, 150.0); + let (was, now) = (before.luma(p.x as i64, p.y as i64).unwrap_or(0), img.luma(p.x as i64, p.y as i64).unwrap_or(0)); + assert!(f32::from(now) < f32::from(was) * 0.6, "spot healing trail on {bg}: luma {was} -> {now}, not dark enough"); + assert!(f32::from(now) > f32::from(was) * 0.4, "spot healing trail on {bg}: luma {was} -> {now}, should stay see-through"); + button(&mut h, 320.0, 150.0, false); + h.run_steps(2); + } +} diff --git a/crates/ui-egui/tests/full_res_preview.rs b/crates/ui-egui/tests/full_res_preview.rs index 191a071b9d..f472dd2ad3 100644 --- a/crates/ui-egui/tests/full_res_preview.rs +++ b/crates/ui-egui/tests/full_res_preview.rs @@ -145,21 +145,30 @@ fn adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off() { assert!((full - committed).abs() < 8.0, "low-res previews off: the drag matches the committed view ({full} vs {committed})"); } +/// A filter dialog's live preview is never coarser than the screen either (#6326): at 100 % every +/// column shows with low-resolution previews on; zoomed out to 50 % the default preview runs on +/// the reduced copy (only the black columns), and with them off it matches the committed view. #[test] fn filter_dialog_previews_at_full_resolution_when_low_res_is_off() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; - setup(&mut h, 1.0); + setup(&mut h, 0.5); if !on_gpu(&mut h) { return; } + let committed = mean(&row(&mut h)); + assert!(committed > 60.0, "zoomed out the columns average to grey ({committed})"); + control(&mut h, "ui.set", json!({"zoom": 1.0, "center": [W / 2, H / 2]})); // Offset 0, 0 leaves the pixels as they are: any change is the preview's resolution. photocraft_ui_egui::filter_dialog::open(h.state_mut(), "filter.other.offset").expect("Offset dialog"); - let reduced = row(&mut h); - assert!(columns(&reduced) < 0.1, "default: the reduced copy loses the columns ({})", columns(&reduced)); + let at_100 = row(&mut h); + assert!(columns(&at_100) > 0.9, "default at 100 %: the preview is never coarser than the screen ({})", columns(&at_100)); + control(&mut h, "ui.set", json!({"zoom": 0.5, "center": [W / 2, H / 2]})); + let reduced = mean(&row(&mut h)); + assert!(reduced < 30.0, "default at 50 %: the reduced copy keeps only the black columns ({reduced})"); low_res(&mut h, false); - let full = row(&mut h); - assert!(columns(&full) > 0.9, "low-res previews off: every column shows ({})", columns(&full)); + let full = mean(&row(&mut h)); + assert!((full - committed).abs() < 8.0, "low-res previews off: the preview matches the committed view ({full} vs {committed})"); } #[test] diff --git a/crates/ui-egui/tests/paint_bucket_all_layers.rs b/crates/ui-egui/tests/paint_bucket_all_layers.rs index 27e1428942..9e71d918d0 100644 --- a/crates/ui-egui/tests/paint_bucket_all_layers.rs +++ b/crates/ui-egui/tests/paint_bucket_all_layers.rs @@ -52,7 +52,7 @@ fn setup(h: &mut Harness) -> LayerId { o.tolerance = 0.0; o.anti_alias = false; o.contiguous = true; - o.sample_all_layers = false; + o.sample_all.paint_bucket = false; o.bucket_fill_pattern = false; o.fill_opacity = 100.0; background @@ -98,7 +98,7 @@ fn all_layers_checkbox_limits_bucket_fill_to_the_visible_color() { h.get_by_label("All Layers").click(); h.run_steps(3); } - assert_eq!(h.state().ui.tool_options.sample_all_layers, all_layers, "checkbox changed the option"); + assert_eq!(h.state().ui.tool_options.sample_all.paint_bucket, all_layers, "checkbox changed the option"); let pos = screen(&h, 300.0, 150.0); h.event(egui::Event::PointerMoved(pos)); diff --git a/crates/ui-egui/tests/remove_channel_target.rs b/crates/ui-egui/tests/remove_channel_target.rs new file mode 100644 index 0000000000..5d18009baa --- /dev/null +++ b/crates/ui-egui/tests/remove_channel_target.rs @@ -0,0 +1,100 @@ +//! #7366: a background Remove on a Red-only target keeps G/B/alpha intact when a Type click +//! selects another layer while the job is pending. + +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use photocraft_engine::jobs::Started; +use photocraft_ui_egui::{PhotocraftApp, Services, control, type_tool}; + +const REMOVE: &str = r#"{"points":[[12,10],[16,12]],"size":6}"#; + +fn run(s: &mut Session, id: &str, p: &str) { + s.execute(id, p.parse().unwrap()).unwrap(); +} + +fn pixels(s: &Session, doc: usize, id: LayerId) -> Vec { + let d = &s.documents()[doc].doc; + d.layer(id).unwrap().surface().unwrap().read_region(d.bounds()) +} + +#[derive(Clone, Copy)] +enum Input { + None, + TypeTool, + ControlPointer, +} + +fn probe(input: Input) { + let mut a = PhotocraftApp::new(Session::new(), Services::default()); + run(&mut a.session, "file.new", r#"{"name":"A","width":32,"height":24,"background":"transparent"}"#); + run(&mut a.session, "type.create", r#"{"text":"X","x":2,"y":18,"size":14}"#); + let text = a.session.active().unwrap().active_layer.unwrap(); + run(&mut a.session, "layer.new.layer", r#"{"name":"Target"}"#); + let target = a.session.active().unwrap().active_layer.unwrap(); + a.session + .edit("fixture", |d, l| { + let q = d.layer_mut(l.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..24 { + for x in 0..32 { + q.write_pixel(x, y, &[((x * 7 + y * 13) % 31) as f32 / 30., (x % 5) as f32 / 4., (y % 7) as f32 / 6., 1.]); + } + } + Ok(()) + }) + .unwrap(); + run(&mut a.session, "file.new", r##"{"name":"B","width":32,"height":24,"background":"#6a219c"}"##); + a.session.set_active(0); + a.sync_views(); + run(&mut a.session, "channel.target", r#"{"channel":"red"}"#); + let b = a.session.documents()[1].doc.clone(); + let text_before = a.session.documents()[0].doc.layer(text).unwrap().clone(); + + // The inline Red-only Remove is the oracle. + let mut inline = Session::new(); + inline.add_document(a.session.documents()[0].doc.as_ref().clone(), None); + inline.select_layer(target).unwrap(); + run(&mut inline, "channel.target", r#"{"channel":"red"}"#); + run(&mut inline, "paint.remove", REMOVE); + let expected = pixels(&inline, 0, target); + + let job = match a.session.start("paint.remove", REMOVE.parse().unwrap()).unwrap() { + Started::Job(id) => id, + v => panic!("must start a background job: {v:?}"), + }; + match input { + Input::None => {} + Input::TypeTool => assert!(type_tool::pointer_down(&mut a, 4., 14., Default::default()), "the click must hit the text"), + Input::ControlPointer => { + let (req, _rx) = control::ControlRequest::new("ui.pointer", r#"{"tool":"type","events":[{"kind":"down","x":4,"y":14}]}"#.parse().unwrap()); + let _ = control::handle(&mut a, &Default::default(), &req); + } + } + let selected = if matches!(input, Input::None) { target } else { text }; + assert_eq!(a.session.active().unwrap().active_layer, Some(selected), "the input selects the text layer"); + + a.session.set_active(1); + a.session.wait_job(job).unwrap(); + assert_eq!(a.session.documents()[1].doc, b, "B is unchanged"); + let st = &a.session.documents()[0]; + assert_eq!(st.doc.layer(text).unwrap(), &text_before, "the text layer is unchanged"); + assert_eq!(st.active_layer, Some(selected), "the user's selection survives the job"); + let actual = pixels(&a.session, 0, target); + let wrong = expected.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0).filter(|(e, r)| e[1..] != r[1..]).count(); + assert_eq!(wrong, 0, "pixels with G/B/alpha changed outside the Red target"); + assert_eq!(actual, expected); +} + +#[test] +fn no_input_keeps_red_restriction() { + probe(Input::None); +} + +#[test] +fn type_tool_click_keeps_red_restriction() { + probe(Input::TypeTool); +} + +#[test] +fn control_pointer_click_keeps_red_restriction() { + probe(Input::ControlPointer); +} diff --git a/docs/context-menu-parity.md b/docs/context-menu-parity.md index 76d6724b7e..53b6d99bd9 100644 --- a/docs/context-menu-parity.md +++ b/docs/context-menu-parity.md @@ -1,6 +1,6 @@ # Context-menu parity contract -> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (layer-mask thumbnail menu, #4575) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** minor (Type tool menu over committed type, #7324) · **Target:** Adobe Photoshop 2026 Status: implementation contract, updated 2026-10-09. Scope: canvas, document tabs, and panels. “Right-click” means a secondary pointer click; macOS Control-click should also open the same menu where the platform sends a context-menu gesture. Photoshop changes a context menu with the active tool, selection, and panel item. Adobe documents that principle but does not publish a complete current menu catalog. **Documented** means an Adobe source explicitly names the gesture or action. **Inferred** means a PhotoCraft design target or an item known from a main menu whose presence in a Photoshop context menu still needs a current-product capture. Do not present inferred rows as exact Photoshop menus. [Adobe: panels and menus](https://helpx.adobe.com/photoshop/using/panels-menus.html), [Adobe: shortcuts and context menus](https://helpx.adobe.com/sa_en/photoshop/using/customizing-keyboard-shortcuts.html). @@ -27,9 +27,9 @@ The “PhotoCraft at branch point” column records behavior before this PR. Pic | Ruler, Note, Count | Unit / measurement, note edit/delete, count-group operations **(inferred)** | No tool menu | P2 | | Brush, Pencil, Eraser, Background Eraser, Spot Healing, Healing, Clone Stamp, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge | Brush preset, size and hardness where applicable | Picker | P0; [Adobe Brush Settings](https://helpx.adobe.com/photoshop/desktop/apply-painting-techniques/brushes-presets/create-brush-set-painting-options.html). Alt+secondary-drag on Windows and Control+Option-drag on macOS adjust size/hardness ([Adobe cursor shortcuts](https://helpx.adobe.com/in/photoshop/desktop/get-started/settings-and-preferences/change-tool-pointers.html)) | | Gradient, Paint Bucket | Gradient preset/type/mode or fill source/tolerance **(inferred context placement)** | No tool menu | P1 | -| Type | In text: cut/copy/paste, spelling suggestions, text formatting; outside text: type-layer action **(inferred context placement)** | While editing text (canvas_tool_menu.rs `TYPE_EDIT_MENU`): Undo, Cut, Copy, Paste, Select All (on the text), Check Spelling…, Find and Replace Text…, Faux Bold/Italic (checked), Rasterize Type, Create Work Path, Convert to Shape, Horizontal/Vertical and the anti-alias modes (checked), Convert to Paragraph/Point Text, Warp Text…; Esc closes only the menu. Over a misspelled word the menu starts with up to 3 spelling suggestions (replace the word) and Add to Dictionary (#4370); Ignore / Ignore All and the non-editing type-layer menu remain open | P1; separate editing and nonediting states; [Adobe type editing](https://helpx.adobe.com/photoshop/desktop/text-typography/get-started-with-text/edit-text.html) | +| Type | In text: cut/copy/paste, spelling suggestions, text formatting; outside text: type-layer action **(inferred context placement)** | While editing text (canvas_tool_menu.rs `TYPE_EDIT_MENU`): Undo, Cut, Copy, Paste, Select All (on the text), Check Spelling…, Find and Replace Text…, Faux Bold/Italic (checked), Rasterize Type, Create Work Path, Convert to Shape, Horizontal/Vertical and the anti-alias modes (checked), Convert to Paragraph/Point Text, Warp Text…; Esc closes only the menu. Over a misspelled word the menu starts with up to 3 spelling suggestions (replace the word) and Add to Dictionary (#4370). Over committed type (no edit running, `TYPE_LAYER_MENU`, #7324): the same rows without Undo, Cut, Copy, Paste, Select All and Faux Bold/Italic; the clicked type becomes the active layer first (a layer multiselection stays). The Type Mask tools get no menu. Ignore / Ignore All remain open | P1; editing and nonediting states are separate; [Adobe type editing](https://helpx.adobe.com/photoshop/desktop/text-typography/get-started-with-text/edit-text.html) | | Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242): Zoom In, Zoom Out, Fit on Screen, Fill Screen, 100%, 200%, Print Size. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture | -| Pen, Path Selection | Path/point actions, Make Selection, Fill/Stroke Path, Free Transform Path **(inferred context placement)** | Pen canvas right-click follows the user-provided 20-row Photoshop capture below. Paths rows offer Make Selection, Fill and Stroke. Path Selection's own canvas menu remains open. | P1; distinguish node, segment, path, and blank canvas | +| Pen, Path Selection | Path/point actions, Make Selection, Fill/Stroke Path, Free Transform Path **(inferred context placement)** | Pen canvas right-click follows the user-provided 20-row Photoshop capture below. Paths rows offer Make Selection, Fill and Stroke. The Path Selection and Direct Selection tools open the same path menu for the selected path (#1056, 2026-10-15); node- and segment-specific rows remain open. | P1; distinguish node, segment, path, and blank canvas | | Rectangle, Ellipse Shape, Triangle, Polygon, Line, Custom Shape | Shape/path operations, fill/stroke settings, transform **(inferred context placement)** | No tool menu | P2 | | Slice, Slice Select | Slice properties, duplicate/delete, divide, guides **(inferred context placement)** | No tool menu | P2 | | Any tool while Free Transform is active | Scale, Rotate, Skew, Distort, Perspective, Warp, rotate/flip variants, commit/cancel **(inferred exact context placement)** | Missing per docs/scorecard.md TOOL-214-5 | P0; transform operations [documented by Adobe](https://helpx.adobe.com/photoshop/desktop/crop-resize-transform/transform-manipulate-reshape/adjust-scale-rotation-and-perspective.html); type restrictions [documented here](https://helpx.adobe.com/photoshop/using/creating-type.html) | @@ -100,6 +100,7 @@ Each slice needs pure model tests (including every item dispatching a known comm | Date | Change | Summary | |---|---|---| +| 2026-10-18 | minor | Type tool menu over committed type (#7324) | | 2026-10-13 | minor | Layer-mask thumbnail menu (#4575) | | 2026-10-10 | trivial | Status line, revision history | | 2026-10-09 | minor | Selection canvas reference and tool matrix updates | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 14d416f19b..918a9f811b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -73,8 +73,9 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing. - Edit › Transform › Warp on editable type (`ui.menu.invoke {"id":"edit.transform.warp"}`, or the warp toggle of an open transform box) opens Warp mode with no prompt, as in Photoshop: the mesh can't be dragged or split, only the options bar's warp style, Bend, H and V apply, and the commit sets the layer's Warp Text in one step, so the type stays editable. Directly: `engine.execute {"command":"edit.transform.warp","params":{"style":"flag","bend":40}}` on a type layer. Distort and Perspective stay greyed for type. - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows -- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). With the Crop tool in its default mode (Use Classic Mode off) a drag inside the box moves the image and one outside turns it, the view panning and turning with it; a drag's `move`/`up` points are read as the view showed the document at its `down`, so an `up` where the last `move` was changes nothing more. `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with Zoom or Hand it opens the view menu there (Zoom In and Zoom Out step about the pressed point; `view.fillScreen` is its Fill Screen row); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. `button` is `left` (default), `right`, `secondary` or `middle`, and an event's `kind` is `down`, `move` (default) or `up`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. +- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). With the Crop tool in its default mode (Use Classic Mode off) a drag inside the box moves the image and one outside turns it, the view panning and turning with it; a drag's `move`/`up` points are read as the view showed the document at its `down`, so an `up` where the last `move` was changes nothing more. `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen, or with a Type tool on text being edited or on committed type, it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with Zoom or Hand it opens the view menu there (Zoom In and Zoom Out step about the pressed point; `view.fillScreen` is its Fill Screen row); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. `button` is `left` (default), `right`, `secondary` or `middle`, and an event's `kind` is `down`, `move` (default) or `up`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. - Magnetic Lasso (`tool: "magneticLasso"`): a `down`/`up` pair is a click. The first sets the first fastening point (its modifiers set the selection mode); later clicks fasten a point, or close the border on the first point. `move` events trace the border with or without a button held, fastening points by themselves; with `alt: true` a click draws a straight segment and a drag a freehand one. `ui.inspect` shows the border in progress under `magnetic` (`path`, `anchors`, `live`, `mode`). `ui.key` Enter closes it along the edges, Backspace removes the last fastening point, Escape cancels. To select along edges in one call instead, use the `select.magneticLasso` command with rough points around the shape. + - Image › Adjustments › Curves on top, no eyedropper armed (#7325): a `down` with `command: true` adds a point on the curve the dialog shows (its Channel popup), at the pixel's tone (RGB: Rec. 709 luma; Gray: the mean) and at the curve's current output there, so the preview does not change; with `shift: true` as well, one point on each of Red, Green and Blue at that channel's value. It samples the merged image like the eyedroppers, never moves an existing point (a point already within 2 levels is selected instead, a 16-point curve takes no more), and the tool is not driven. Nothing is added with a pencil-drawn curve, in Lab or CMYK, or with a mask, saved channel or Quick Mask targeted. - Levels or Curves adjustment layer, Properties eyedropper armed (`layerPicker` in `ui.inspect`: `{layer, point, tool}`, set by the panel's Set Black/Neutral Gray/White Point buttons): a `down` sets that point from the image below the layer as one `layer.setAdjustment {"layer", "eyedropper": {"point", "at": [x, y], "size"}}` (send that command directly to skip the UI) and the tool is not driven; Esc, another tool or another layer disarms it. - `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points (`button`: `left` (default), `right` (or `secondary`) or `middle`). `count` (default 1, `2` for a double-click) is at most 256; a larger one is an error and queues nothing - `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`. `{"key": "AltLeft"}` is a tap on Alt, which puts the keyboard on the in-window menu bar (then `ArrowRight`, `ArrowDown`, `Enter`, `Escape` or a menu's letter drive it); `{"key": "F", "alt": true}` opens the menu with that mnemonic (#4988) @@ -87,7 +88,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i base64 PNG data; a path is relative to the automation write root. Raises the window first (default) because occluded macOS windows stop rendering - `ui.focus`: bring the main window to the front -- `app.open {path}` / `app.save {path?, tgaBits?}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. Automation saves never show TGA or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands)) +- `app.open {path}` / `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. `ddsCompression` (`none`, `bc1`, `bc2` or `bc3`) and `ddsMipmaps` (bool) set a DDS texture's compression and mip chain; without them, uncompressed without mipmaps. Automation saves never show TGA, DDS or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands)) - `app.quit` ## Engine commands @@ -246,7 +247,11 @@ log text file. GPU on/off and the GPU tile size apply at the next launch. The desktop app stores them in `preferences.json` in the platform config directory (macOS `~/Library/Application Support/Photocraft`, Windows `%APPDATA%\Photocraft`, Linux `$XDG_CONFIG_HOME/photocraft`; override with `PHOTOCRAFT_CONFIG_DIR`); autosaves go to its -`Recovery` folder, and the window size and position, the dock width and floating-panel geometry +`Recovery` folder (on Windows to `%LOCALAPPDATA%\Photocraft\Recovery`, out of the roaming +profile, and on Linux to `$XDG_STATE_HOME/photocraft/Recovery`, by default +`~/.local/state/photocraft/Recovery`, out of the config folder; autosaves left by earlier +versions move there at startup), and the window size and +position, the dock width and floating-panel geometry to `ui.ron` beside it (a file holding values that would crash startup is discarded). In portable mode (a `portable.txt` or `PhotoCraft.portable` file beside the executable, as in the Windows portable zip) that directory is `PhotoCraftData` next to the executable instead. The web build keeps them in `localStorage`. A save writes only the values @@ -316,7 +321,7 @@ How each MCP tool maps onto control methods in bridge mode: | `doc_export_layers {dir, …}` | `engine.execute {command: "file.export.layersToFiles", params}` | | `doc_export_data_sets {dir, …}` | `engine.execute {command: "file.export.dataSetsAsFiles", params}` | | `doc_import_data_sets {path, …}` | `engine.execute {command: "file.import.variableDataSets", params}` | -| `doc_save {path?, tgaBits?}` / `doc_export {path, tgaBits?}` | `app.save {path?, tgaBits?}` | +| `doc_save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}` / `doc_export {path, tgaBits?, ddsCompression?, ddsMipmaps?}` | `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}` | | `doc_render_preview {max_side?}` | `ui.screenshot`, returned directly as PNG image content | | `session_list`, `ui_inspect` | `ui.inspect` | | `ui_screenshot {max_side?}` | `ui.screenshot`, returned as PNG image content | @@ -373,7 +378,7 @@ no MCP framing, no app start-up per command. Configure its file access with the | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, count}`: one file per exported layer, named like `file.export.layersToFiles` names them. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | -| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | +| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` | diff --git a/docs/decisions.md b/docs/decisions.md index 15519ecf74..ac44d14500 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -5,3 +5,30 @@ Smart Object instances carry a document-scoped contents ID separately from their layer ID. Normal duplicates preserve it; New Smart Object via Copy creates a new one. Contents edits update the matching instances together, retaining their individual placement and filters. Copies into another document remap contents IDs as a batch, preserving sharing within the copied layers without joining existing destination objects. Native files persist this ID. Legacy embedded objects without an ID remain independent: identical file bytes do not prove that two objects were intended to share edits. Legacy nonempty linked paths and PSD source identifiers retain their explicit sharing relationship. PSD export keys embedded sources by contents identity as well as bytes, so independent equal-content objects stay independent. + +## 2026-10-17: keeping a replaced file's ACL and named streams (#7073, #7094, #7096) + +Saving replaces a file by renaming a new one over it, which drops everything the old file +carried. Carrying the security-relevant parts across needs platform calls that have no safe API +in `std`, and the workspace forbids `unsafe`, so each platform took a dependency rather than an +exception. + +**macOS ACLs: `exacl`, not `fclonefileat`.** The two routes that avoid `unsafe` are a macOS-only +`exacl` dependency (a safe wrapper over `acl_get_file`/`acl_set_file`) and `fclonefileat` with +the undocumented-in-`rustix` `CLONE_ACL` bit. The clone keeps the ACL, but only on APFS, and it +means writing every save as clone-then-truncate-then-write with a fallback for every other file +system — restructuring the one write path the whole app's durability rests on, to preserve an +ACL. `exacl` is a best-effort step beside the existing permission copy, it works wherever ACLs +do, and a failure cannot affect the bytes. + +**Windows: `ReplaceFileW` via `winsafe`, with a backup name.** Copying the `Zone.Identifier` +stream by hand with `std` would cover the Mark of the Web but not the DACL, and enumerating every +stream needs `FindFirstStreamW`. `ReplaceFileW` is the call Microsoft documents for the +save-through-a-temporary-file pattern and preserves the DACL, named streams, creation time and +object identifier in one step; `winsafe`'s `kernel` feature wraps it safely and pulls in nothing. + +The backup-file argument is a correctness requirement, not an option: `ReplaceFileW` without one +documents `ERROR_UNABLE_TO_MOVE_REPLACEMENT` as leaving the replaced file deleted and the +replacement under its temporary name — a failed save that loses the user's document. With a +backup name the same failure leaves both files alone, and the one failure that does move things +(`ERROR_UNABLE_TO_MOVE_REPLACEMENT_2`) is unwound in `atomic/meta.rs`. diff --git a/docs/development.md b/docs/development.md index 67f688b6b9..6891e88a9c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -99,7 +99,7 @@ If the device is lost while running (#243), every GPU entry point checks the dev ## Logs -The desktop app writes its `log` records to standard error and to `logs/photocraft.log` in the settings directory (Linux `~/.config/photocraft/logs/`, macOS `~/Library/Application Support/Photocraft/logs/`, Windows `%APPDATA%\Photocraft\logs\`, or under `PHOTOCRAFT_CONFIG_DIR` / the portable data folder). A start launched from a desktop menu or the Dock has no terminal, so this file is what to attach to a bug report: GPU startup fallbacks, a lost device and the crash guard's panic report all land there. Each launch moves the previous log to `photocraft.1.log` (and that one to `photocraft.2.log`), so the log of a run that crashed survives the next start. The file stops growing at 16 MiB. `--version` and command-line errors write no file. +The desktop app writes its `log` records to standard error and to `logs/photocraft.log` in the settings directory (Linux `~/.config/photocraft/logs/`, macOS `~/Library/Application Support/Photocraft/logs/`, Windows `%APPDATA%\Photocraft\logs\`, or under `PHOTOCRAFT_CONFIG_DIR` / the portable data folder). A start launched from a desktop menu or the Dock has no terminal, so this file is what to attach to a bug report: GPU startup fallbacks, a lost device and the crash guard's panic report all land there. Each launch moves the previous log to `photocraft.1.log` (and that one to `photocraft.2.log`), so the log of a run that crashed survives the next start. A launch while another PhotoCraft is still running leaves that instance's log where it is and writes its own `photocraft-.log` next to it (the newest two of those are kept once their instances have exited; the `PhotoCraft , log file ` line at startup names the file in use). The file stops growing at 16 MiB. `--version` and command-line errors write no file. By default PhotoCraft's own crates log at `info` and everything else at `warn`. `RUST_LOG` replaces that with env_logger-style directives, for example `RUST_LOG=debug`, `RUST_LOG=warn,photocraft_gpu=trace` or `RUST_LOG=info,wgpu_core=warn`; a directive ending in `*` covers every target starting with it (`photocraft*=debug`). The logger is `apps/photocraft/src/logging.rs`; the web build logs to the browser console instead. @@ -126,6 +126,7 @@ By default PhotoCraft's own crates log at `info` and everything else at `warn`. | `PHOTOCRAFT_STROKE_TRACE=1` (or `=`; also `--stroke-trace `, or `ui.set {"strokeTrace": true|false}` at runtime, without a file) | Time every frame of each brush stroke; print a summary per stroke, and with a path also append each frame to that CSV (see [Stroke latency trace](#stroke-latency-trace)) | | `PHOTOCRAFT_PRESENT_MODE=novsync` (or `--present-mode`) | Present mode for this launch: `fifo`, `autovsync`, or `novsync` (also `immediate`, `mailbox`: no vsync, the first of Immediate, Mailbox, Fifo the driver offers). Default: vsync, or no vsync when Preferences › Performance › Low-Latency Drawing is on (it ships off). For latency comparisons; shown in the stroke trace | | `PHOTOCRAFT_FRAME_LATENCY=1` (or `--frame-latency`) | Frames the swap chain may queue, 1 to 3 (wgpu's GL backend ignores it). For latency comparisons; shown in the stroke trace | +| `PHOTOCRAFT_PRINT_PORTAL=1` | Linux: File › Print always opens the system print dialog (the XDG print portal) instead of talking to CUPS; `0` never does. See [printing](printing.md). | | `PHOTOCRAFT_THEME_FILE=tokens.json` | **Debug builds only:** live design-token overrides, re-read on change | ### Live design tokens @@ -399,9 +400,9 @@ HTTPS/reverse-proxy deployment and browser limitations. How the web shell (`apps/photocraft-web/src/web.rs`) differs from desktop: -- **Open** uses `rfd::AsyncFileDialog`. The bytes arrive asynchronously in `Services::inbox`, which the app drains every frame. +- **File dialogs** use `rfd::AsyncFileDialog`. Chosen file contents arrive asynchronously through `Services::file_dialog`; this includes File › Open and single-file commands such as Place Embedded. - **Save / Save As / Export** trigger a browser download of the encoded bytes. The shell does this with a Blob, an object URL and a temporary ``, all created from Rust. There is no save dialog, so the suggested name becomes the download name. -- **Drag-and-drop:** `WebShell` takes the frame's `dropped_files` before the app sees them. It reads each file with `DroppedFile::bytes_async` and pushes the bytes into the inbox. +- **Drag-and-drop:** `WebShell` takes the frame's `dropped_files` before the app sees them. It reads each file with `DroppedFile::bytes_async` and pushes the bytes into `Services::inbox`. - **Startup failures:** `index.html` shows "Loading PhotoCraft…" until the app removes it, or replaces it with the error when the web runner fails to start. If the `.wasm` never downloads or doesn't match the page's `.js` (a stale cached `index.html` after a deploy), no Rust runs at all, so the page itself (CSS only, no script) adds a hint with a Reload link after 20 seconds. - **No control server:** browsers can't listen on TCP. To automate the web build, drive headless Chrome with `--remote-debugging-port`. `Page.setInterceptFileChooserDialog` plus `DOM.setFileInputFiles` covers Open, `Input.dispatchDragEvent` with `files` covers drops, and `Browser.setDownloadBehavior` captures downloads. - Headless Chrome on macOS (`--headless=new --enable-unsafe-webgpu`) gets a real WebGPU adapter. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ba74623709..938a723b69 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (earlier: PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); earlier: PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026 Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write @@ -26,7 +26,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) | | TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders (FILE-215-7: extra alpha channels not written) | | JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); no JPEG Options dialog (quality 0–12, baseline/progressive) (FILE-215-19) | -| PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804) | +| PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804); Save keeps a stereo PNG's `sTER` pairing (#6063) | | GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Per-frame delays and keeping the frames in `.pcraft` are not done | | BMP | R/W | yes | yes | 8-bit; palette BMPs open in Indexed Color mode | | WebP | R/W | yes | yes | Lossless and our own lossy VP8 encoder; ICC/EXIF/XMP; Save keeps an opened file lossy (at its quality) or lossless (#2399) | @@ -90,7 +90,7 @@ D5100 colour profile. Counts and the G14 estimate are unchanged. | Paint.NET `.pdn` | yes | no | [pdn.md](pdn.md) | | OpenRaster `.ora` | yes | yes | [ora.md](ora.md) | | ICO, QOI | yes | yes | | -| DirectDraw Surface `.dds` | yes | no | Top mip level of a 2D texture: uncompressed RGB, RGBA or luminance, BC1–BC3 (DXT1/3/5), legacy or DX10 header. Cubemaps, arrays, volumes and BC4–BC7 are refused (#1327). Photoshop needs a plug-in | +| DirectDraw Surface `.dds` | yes | yes | Opens the top mip level of a 2D texture: uncompressed RGB, RGBA or luminance, BC1–BC3 (DXT1/3/5), legacy or DX10 header. Saves a 2D texture uncompressed (BGRA, BGRX, luminance with or without alpha) or BC1–BC3 with the legacy header, optionally with its full mip chain (box filter); Save As and Save a Copy ask (DDS Options), scripts pass `ddsCompression` and `ddsMipmaps` (`--dds-compression`, `--dds-mipmaps` on the CLI). Cubemaps, arrays, volumes and BC4–BC7 are refused (#1327). Photoshop needs a plug-in | | Krita `.kra`, GIMP `.xcf`, Procreate | no | no | Not in Photoshop either | ### Affinity import notes (moved from `roadmap.md`) @@ -142,6 +142,9 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | DDS textures save (#1327): uncompressed or BC1/BC2/BC3 (DXT1/3/5) from a clean-room block encoder, optional box-filtered mip chain, legacy header; DDS Options in Save As and Save a Copy, `ddsCompression`/`ddsMipmaps` for scripts, the CLI and MCP | +| 2026-10-15 | minor | PNG: a stereo PNG's `sTER` pairing (PNG Extensions 1.4.0 §3.6) is read on open and written back on save, so the file still says it is a stereo pair (#6063) | +| 2026-10-15 | minor | PSD guides: image resource 1092 (guides v2) gives guides their own colours on import; 1092 and 1097 (guide GUIDs) are written back only while they still describe the document's guides, so an edit no longer leaves Photoshop a stale second guide list (#5966) | | 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 | | 2026-10-13 | minor | Lossy DNG (compression 34892) decodes: 8-bit baseline JPEG tiles and strips, CFA and LinearRaw, partial edge tiles; the stored values take the normal levels and LinearizationTable (FILE-215-11, lossy DNG part) | | 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 | diff --git a/docs/gaps.md b/docs/gaps.md index a47be61c97..a4fa075b7d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; 2026-10-11: G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; 2026-10-11: G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -200,8 +200,8 @@ what an agent can't finish alone. with saved bindings, matching toolbar hints and regression coverage (`ui-egui/src/tool_shortcuts.rs`). - **Missing:** 27 of 156 preferences do nothing (scorecard prefs audit); panel groups can't float or tear off into OS windows (UI-217-5, #1828, #1213, #2305); Color panel lacks wheel and - slider modes (UI-217-17, #2569); more themes (UI-217-11, #2661); layer clipboard - (UI-217-23, #2670); tool-specific context menus beyond brushes, selections and Pen + slider modes (UI-217-17, #2569); more themes (UI-217-11, #2661); a single pixel layer + copies without its mask and styles (UI-217-23; fill and adjustment layers copy whole, #2344); tool-specific context menus beyond brushes, selections and Pen ([context-menu-parity.md](context-menu-parity.md)); Libraries, Comments, Contextual Task Bar panels. - **Estimate:** 150–250 h. @@ -271,6 +271,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-18 | minor | G9: with no selection, Copy takes fill and adjustment layers whole and Paste recreates them (#2344); UI-217-23 stays partial (a single pixel layer copies its pixels only); estimate unchanged | | 2026-10-14 | minor | G1: a PSD smart object's filter mask shows when the file opens (Photoshop stores the filtered pixels unmasked); export stores them that way too; Photoshop-oracle floor 185 → 188 of 258 | | 2026-10-13 | minor | G14: D90 image area measured (4288 × 2848 at (10, 10)); gap remains open | | 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 | diff --git a/docs/images/SOURCES.md b/docs/images/SOURCES.md index 723d1837fc..1d68651a57 100644 --- a/docs/images/SOURCES.md +++ b/docs/images/SOURCES.md @@ -2,15 +2,15 @@ | File | Content | Source / licence | |---|---|---| -| `photocraft-demo.jpg` | Photocraft UI screenshot (rendered offscreen with `cargo run -p photocraft-ui-egui --example snapshot`) editing *The Great Wave off Kanagawa*, Katsushika Hokusai, c. 1831 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Tsunami_by_hokusai_19th_century.jpg). UI: this project. | -| `photocraft-layer-styles.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Earthrise*, William Anders, Apollo 8, 24 December 1968 (NASA photograph) | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:NASA-Apollo8-Dec24-Earthrise.jpg). UI: this project. | -| `photocraft-masks.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Girl with a Pearl Earring*, Johannes Vermeer, c. 1665 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:1665_Girl_with_a_Pearl_Earring.jpg). UI: this project. | -| `photocraft-vector.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Water Lilies*, Claude Monet, 1906 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Claude_Monet_-_Water_Lilies_-_1906,_Ryerson.jpg). UI: this project. | -| `photocraft-filters.jpg` | Photocraft UI screenshot (offscreen snapshot) with *The Starry Night*, Vincent van Gogh, 1889 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg). UI: this project. | -| `photocraft-adjustments.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Impression, Sunrise*, Claude Monet, 1872 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Monet_-_Impression,_Sunrise.jpg). UI: this project. | -| `photocraft-transform.jpg` | Photocraft UI screenshot (offscreen snapshot) with *The Tetons and the Snake River*, Ansel Adams, 1942 (U.S. National Archives) | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Adams_The_Tetons_and_the_Snake_River.jpg). UI: this project. | -| `photocraft-type.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Among the Sierra Nevada, California*, Albert Bierstadt, 1868 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Albert_Bierstadt_-_Among_the_Sierra_Nevada,_California_-_Google_Art_Project.jpg). UI: this project. | -| `photocraft-export-light.jpg` | Photocraft UI screenshot (offscreen snapshot) with *The Kiss*, Gustav Klimt, 1907–1908 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Gustav_Klimt_016.jpg). UI: this project. | +| `photocraft-demo.jpg` | PhotoCraft UI screenshot (rendered offscreen with `cargo run -p photocraft-ui-egui --example snapshot`) editing *The Great Wave off Kanagawa*, Katsushika Hokusai, c. 1831 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Tsunami_by_hokusai_19th_century.jpg). UI: this project. | +| `photocraft-layer-styles.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *Earthrise*, William Anders, Apollo 8, 24 December 1968 (NASA photograph) | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:NASA-Apollo8-Dec24-Earthrise.jpg). UI: this project. | +| `photocraft-masks.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *Girl with a Pearl Earring*, Johannes Vermeer, c. 1665 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:1665_Girl_with_a_Pearl_Earring.jpg). UI: this project. | +| `photocraft-vector.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *Water Lilies*, Claude Monet, 1906 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Claude_Monet_-_Water_Lilies_-_1906,_Ryerson.jpg). UI: this project. | +| `photocraft-filters.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *The Starry Night*, Vincent van Gogh, 1889 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg). UI: this project. | +| `photocraft-adjustments.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *Impression, Sunrise*, Claude Monet, 1872 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Monet_-_Impression,_Sunrise.jpg). UI: this project. | +| `photocraft-transform.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *The Tetons and the Snake River*, Ansel Adams, 1942 (U.S. National Archives) | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Adams_The_Tetons_and_the_Snake_River.jpg). UI: this project. | +| `photocraft-type.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *Among the Sierra Nevada, California*, Albert Bierstadt, 1868 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Albert_Bierstadt_-_Among_the_Sierra_Nevada,_California_-_Google_Art_Project.jpg). UI: this project. | +| `photocraft-export-light.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *The Kiss*, Gustav Klimt, 1907–1908 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Gustav_Klimt_016.jpg). UI: this project. | Screenshots must use famous public-domain artwork (or content made in the app), never personal photos. diff --git a/docs/mcp.md b/docs/mcp.md index 3046a669bc..9a8c573ce6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,5 +1,52 @@ # MCP conventions +## Install and register + +From the repository root, with the [source-build prerequisites](development.md#prerequisites) +installed, install the CLI independently of the build directory: + +```sh +cargo install --path apps/photocraft-cli --locked +# POSIX shells, for Cargo's default install location: +export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH" +photocraft-cli --help +photocraft-cli mcp --help +``` + +Cargo installs a binary, not a symlink into `target/`, so it survives `cargo clean`. +Re-run the install command after updating the checkout. +By default the executable goes in `$CARGO_HOME/bin` (`~/.cargo/bin` when unset), or +`%USERPROFILE%\.cargo\bin` on Windows. If you set `--root`, `CARGO_INSTALL_ROOT`, or +Cargo's `install.root`, use that installation root's `bin` directory instead. Add it +to the `PATH` inherited by the MCP client, not just an interactive shell, and restart +the client after changing its environment. + +Register the installed command explicitly (replace `/work/project` with an existing folder): + +```sh +claude mcp add photocraft -- photocraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project +``` + +Other MCP clients can use this bare-name configuration: + +```json +{"mcpServers":{"photocraft":{"command":"photocraft-cli","args":["mcp","--automation-read-root","/work/project","--automation-write-root","/work/project"]}}} +``` + +Linux `.deb` and `.rpm` packages already install `/usr/bin/photocraft-cli`; those users +can skip the source install. Other release locations are listed in the +[installed-release guide](../book/src/automation/mcp.md#from-an-installed-release). +Installing the CLI does not start or register an MCP server automatically. + +If a client reports `ENOENT` or "Executable not found in $PATH", verify the install with +`command -v photocraft-cli` (PowerShell: `Get-Command photocraft-cli`) in the client's +environment. If that environment cannot be changed, set JSON `command` to the absolute +installed binary path, not a literal `~` or `$HOME` expression. Avoid symlinks into +`target/release`: cleaning the build directory breaks them. A source build alone does +not put the CLI on `PATH`. + +## Start a session + PhotoCraft follows the same conventions as FilmCraft #28. Start a headless session: ```sh diff --git a/docs/ora.md b/docs/ora.md index 19f3c7503e..2bf4f5112d 100644 --- a/docs/ora.md +++ b/docs/ora.md @@ -12,7 +12,7 @@ entry, so an OpenRaster file with another extension still opens as one. |---|---|---| | Pixel layers (any size and position, also off-canvas) | yes | yes, cropped to their pixels | | Groups, nested | yes | yes | -| Pass-through groups | `isolation="auto"` without a blend mode | `isolation="auto"` | +| Pass-through groups | `isolation="auto"` (before 0.0.6, only without a blend mode) | `isolation="auto"` | | Names, visibility, opacity | yes | yes | | Blend modes | the `svg:*` names, `svg:plus`, and Krita's `krita:*` names | `svg:*` where the spec has the mode, else `krita:*` (read back by Krita, Normal elsewhere) | | Locks | `edit-locked`, `alpha-preserve` | the same | @@ -20,6 +20,12 @@ entry, so an OpenRaster file with another extension still opens as one. | Resolution | `xres` | `xres` and `yres` | | Merged image and thumbnail | not read (we render our own) | written (`mergedimage.png`, `Thumbnails/thumbnail.png`) | +Files declaring OpenRaster 0.0.6 or newer default to isolated groups; an explicit +`isolation="auto"` passes through regardless of the group's own composite operation. Older +files and files without a recognized version keep the legacy inference from the group's +blend mode. Pass-through group opacity still uses PhotoCraft's interpolation against the +backdrop, which can differ from 0.0.6's per-child opacity multiplication for overlapping children. + Saving reports what OpenRaster can't hold, layer by layer: pixel masks are applied to the layer's pixels, fill opacity is folded into the pixels, text, shape, fill and smart object layers are written as their rendered pixels, and adjustment layers, layer styles, vector masks, @@ -53,7 +59,9 @@ are covered by tests. Unit tests (`crates/io/src/ora/tests.rs`) round-trip layers, groups, pass-through, offsets, opacity, visibility, locks and every blend mode at 8 and 16 bit, check masks, rendered layer -kinds, the archive layout and malformed input. `crates/automation/tests/openraster.rs` saves, +kinds, the archive layout and malformed input. Synthetic 8/16-bit pixel fixtures check modern +and legacy group-isolation defaults, explicit isolation and pass-through. +`crates/automation/tests/openraster.rs` saves, reopens, edits and saves in place through the agent surface, and checks that a document with an adjustment layer never overwrites its `.ora`; the CLI test converts both ways. diff --git a/docs/printing.md b/docs/printing.md new file mode 100644 index 0000000000..68015d278e --- /dev/null +++ b/docs/printing.md @@ -0,0 +1,67 @@ +# Printing + +File › Print renders the flattened document onto one PDF page (paper size and orientation, +position and scale, crop and registration marks, labels, colour handling) and hands that page +to a printer. The rendering is `print_cmds.rs` in `photocraft-engine`, shared by the dialog, the +batch commands and automation (`file.print`, `file.printOneCopy`); this page is about the hand-off. + +## Routes to the printer + +| Route | When | What the user sees | +|---|---|---| +| **`craft-print`** (`lp` on CUPS, the Windows spooler) | Whenever `lp` is on the path (macOS, Linux outside a sandbox) or on Windows | `Sent to the printer (request id is Office-42)` | +| **CUPS over IPP** (`photocraft-ipp`) | No `lp` on the path (a Flatpak) and a print server answers: `CUPS_SERVER`, then `/run/cups/cups.sock`, `/var/run/cups/cups.sock`, `/private/var/run/cupsd`, then `localhost:631`; always for a `printServer` named in the request | `Sent to the printer (job 42 on Office)` | +| **Print portal** (`org.freedesktop.portal.Print`, desktop app on Linux) | No print server reachable or no printer set up, or always with `PHOTOCRAFT_PRINT_PORTAL=1` | The system print dialog, seeded with the copies and paper; the outcome goes to the log | +| **Print to PDF** | `output` given (the Output field of the dialog) | The file; nothing is spooled unless `send` is true | + +A route that exists but fails (an unknown printer, a job the queue refuses) is an error; only a +missing route (no `lp`, no print server, no printer) moves on to the next one. + +The IPP client is in-process, pure Rust (RFC 8010/8011: `CUPS-Get-Printers`, `CUPS-Get-Classes`, +`CUPS-Get-Default`, `Print-Job` with the PDF as the document), so no `lp` binary is needed. That +is what makes printing work in the Flatpak: the manifest grants `--socket=cups`, which mounts the +host's CUPS socket, and the sandbox has no `lp`. On a system without CUPS, or in a sandbox +without the socket, the app falls back to the print portal, whose dialog runs outside the sandbox. + +## Which printer + +The dialog's Printer field, or `"printer"` in the command, names a queue (case-insensitively; a +CUPS class counts, as with `lp -d`). +Left empty, the server's default printer is used; without a default, the only printer; with +several and no default, the error names them. With no printer at all, the portal takes over when +it is available, otherwise the error says to add one in the system settings or print to PDF. + +`file.printers` lists what the print server knows: `{"printServer": "host[:port]|socket"}` +is optional and defaults to the system's CUPS; the result is +`{server, default, printers: [{name, info, state, acceptingJobs, default, class}]}`, or an empty list +with a `note` when no server answers. `"printServer"` on `file.print` sends one job to a named +server; `"dryRun": true` renders the page and reports the equivalent `lp` command without +spooling. + +## Results + +`file.print` returns `sent`, `backend` (`lp`, `windows`, `ipp`, `portal`), `spooler` (where the +job went) and `pdf` (the page's path, only when `output` named one). + +## Environment + +| Variable | Effect | +|---|---| +| `CUPS_SERVER` | The print server, as CUPS itself reads it: `host[:port]` or a socket path | +| `PHOTOCRAFT_PRINT_PORTAL=1` | Always use the system print dialog (the portal) instead of `lp` or CUPS directly | +| `PHOTOCRAFT_PRINT_PORTAL=0` | Never use the portal; a missing print server is then an error | + +## Verification + +- `crates/ipp/src/tests.rs`: the client against a fake CUPS over TCP and a Unix socket: + printer listing with state and default, the default printer and its absence, `Print-Job` + with the document and the job id, chunked and content-length replies, HTTP and IPP error + statuses, broken replies. +- `crates/engine/src/print_cmds/tests.rs`: printer resolution (requested, default, only one, + several without a default, unknown, none); a complete `file.print` against a fake CUPS + (printer URI, copies, job name, document format, the PDF itself) and `file.printers`; + `lp` taking the job when it is on the path; the IPP route when it is not (a child process + with an empty path); the app's spooler when preferred, as the fallback without a printer, and + skipped when a server is named; print to PDF untouched. +- `apps/photocraft/src/print_portal.rs`: the request path rule and the paper/copies seeding of + the dialog (PWG names for the standard papers, millimetres for custom sizes). diff --git a/docs/psd-interleave-performance.md b/docs/psd-interleave-performance.md new file mode 100644 index 0000000000..5958442881 --- /dev/null +++ b/docs/psd-interleave-performance.md @@ -0,0 +1,46 @@ +# PSD pixel buffer allocation + +Write PSD interleaved pixels directly into the final buffer. Direct RLE output is already on main. The unrelated export-side sample-encoder inlining hint is removed locally. + +Whole-photo imports improve by about 4–7%, and the authored designs by about 20–26%. An added export-side inlining hint accompanied a separately confirmed 2.3% float PSD export slowdown (2440.168 → 2497.423 ms). Removing that one line leaves export source equal to main; follow-up float export is +0.4% and 16-bit export +0.9%, with both paired intervals crossing zero. These results supersede the much larger previous interleave-only percentages. + +Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions. + +The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used. + +The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance. + +| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes | +|---|---|---:|---:|---:|---:|---:| +| panasonic-32 | psd-export (fixed) | 2471.456 | 2481.877 | +0.4% | -0.1..+1.7% | 461,042,978 / 461,042,978 | +| panasonic-16 | psd-export (fixed) | 2649.246 | 2673.071 | +0.9% | -5.2..+1.6% | 274,409,683 / 274,409,683 | +| panasonic-8 | psd-import | 275.828 | 262.237 | -4.9% | -5.9..-4.1% | 98,823,859 / 98,823,859 | +| panasonic-8 | psd-export | 2937.854 | 2915.929 | -0.7% | -11.5..+5.6% | 98,823,859 / 98,823,859 | +| panasonic-16 | psd-import | 365.901 | 349.827 | -4.4% | -4.4..-2.6% | 274,409,683 / 274,409,683 | +| panasonic-32 | psd-import | 360.706 | 334.838 | -7.2% | -12.6..-4.4% | 461,042,978 / 461,042,978 | +| canon-8 | psd-import | 141.331 | 135.878 | -3.9% | -5.1..-3.6% | 56,209,597 / 56,209,597 | +| canon-8 | psd-export | 1052.421 | 1054.472 | +0.2% | -0.6..+1.3% | 56,209,597 / 56,209,597 | +| canon-16 | psd-import | 177.327 | 169.952 | -4.2% | -5.5..-1.7% | 140,673,004 / 140,673,004 | +| canon-16 | psd-export | 1248.449 | 1239.159 | -0.7% | -1.6..+0.6% | 140,673,004 / 140,673,004 | +| canon-32 | psd-import | 175.721 | 163.271 | -7.1% | -9.3..-4.9% | 228,234,238 / 228,234,238 | +| canon-32 | psd-export | 1008.772 | 1005.356 | -0.3% | -1.8..+0.7% | 228,234,238 / 228,234,238 | +| layout-masks | psd-import | 12.509 | 9.981 | -20.2% | -20.8..-14.5% | 493,006 / 493,006 | +| layout-masks | psd-export | 55.113 | 54.714 | -0.7% | -2.3..+1.2% | 493,006 / 493,006 | +| layout-mask-index | psd-import | 3.299 | 2.443 | -25.9% | -30.8..-23.4% | 411,435 / 411,435 | +| layout-mask-index | psd-export | 18.200 | 18.397 | +1.1% | -0.1..+1.7% | 411,435 / 411,435 | + +Real PSD exports remain byte-identical and imported layer/mask float samples match main. The committed literal previous-interleave oracle covers depths, bands, fills, truncation and inversion. + +Current local checks: affected `pixels::` unit tests (five passed, one ignored manual benchmark); strict all-target IO Clippy; affected IO wasm32 check. All passed. Follow-up exports at float and 16-bit depth remain byte-identical to main; no synthetic timing test was run. + +Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run. + +## Earlier split validation + +These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed. + +- `cargo test -p photocraft-io --locked`: passed (617 passed, 6 ignored). +- `cargo clippy -p photocraft-io --locked --all-targets -- -D warnings`: passed. +- `cargo xtask layers`: passed. +- `cargo check -p photocraft-io --locked --target wasm32-unknown-unknown`: passed. +- `cargo xtask test-corpus -p io`: passed (646 passed, 6 ignored). diff --git a/docs/scorecard.md b/docs/scorecard.md index f4077b5b5c..d9bfcccee1 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,10 +9,10 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 24 | 58 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 19 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | | [Tools](#tools) | 33 | 11 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 168 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 169 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | -| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 29 of 29 crates; panic_hunt present | +| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 4 | 2 | | | [Open bugs](#open-bugs) | 29 | 2 | 1 | | @@ -179,9 +179,9 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 168** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 25 of 169** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. -Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. +Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. | Id | Target | Status | Issue | Note | |---|---|---|---|---| @@ -192,7 +192,7 @@ Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_w | UI-217-5 | Panel groups can float (menu + drag out of the dock) and are restored at launch | missing | [#217](https://github.com/storytold/photocraft/issues/217) | No floating groups in dock.rs/panels.rs | | UI-217-6 | Document tabs: overflow list, context menu (Close/Others/All/Reveal), drag to reorder | done | [#217](https://github.com/storytold/photocraft/issues/217) | canvas.rs: Close/Others/All menu with unsaved prompt; Reveal reuses file.revealInFinder (engine layer_menu_cmds::reveal); the » chevron (tab_strip) lists overflow; dragging a tab reorders via document.move | | UI-217-7 | Command palette shows recently run commands on an empty query | done | [#217](https://github.com/storytold/photocraft/issues/217) | palette.rs: note_recent from menus::invoke keeps the last 8 commands (dedup, newest first); an empty query lists them via recent_hits; the_palette_records_and_replays_recent_commands_on_an_empty_query covers record -> empty query -> replay | -| UI-217-8 | Tool-specific canvas right-click menu; right-click spelling suggestions in text fields | partial | [#217](https://github.com/storytold/photocraft/issues/217) | paint_mouse.rs brush picker and canvas_tool_menu.rs selection actions; text_field_menu.rs gives every text field its right-click Undo/Cut/Copy/Paste/Delete/Select All menu (#2921); other tools missing; the Type tool's edit menu starts with spelling suggestions and Add to Dictionary over a misspelled word (#4370); Ignore / Ignore All, suggestions in the non-editing type menu and in generic text fields are not there yet | +| UI-217-8 | Tool-specific canvas right-click menu; right-click spelling suggestions in text fields | partial | [#217](https://github.com/storytold/photocraft/issues/217) | paint_mouse.rs brush picker and canvas_tool_menu.rs selection actions; text_field_menu.rs gives every text field its right-click Undo/Cut/Copy/Paste/Delete/Select All menu (#2921); other tools missing; the Type tool's edit menu starts with spelling suggestions and Add to Dictionary over a misspelled word (#4370); over committed type the Type tool opens the type layer menu (#7324); Ignore / Ignore All, suggestions in the non-editing type menu and in generic text fields are not there yet | | UI-217-9 | UI scale presets 100/115/125/150/200 % through zoom_factor, remembered | done | [#217](https://github.com/storytold/photocraft/issues/217) | prefs::UiScale offers Auto plus 75 to 300 percent (13 presets, more than the five this row lists); prefs_ui.rs display_scale resolves it (Auto follows the system scale, fractional and unscaled 4K included, #1072/#1278) and sync_display_scale applies it with ctx.set_zoom_factor. It is a preference, so it is remembered. The zoom_factor assert in input_tests.rs is about canvas zoom not scaling the interface, not about this setting | | UI-217-10 | Appearance: animation toggle, canvas pattern toggle per theme, start-screen recents | partial | [#217](https://github.com/storytold/photocraft/issues/217) | interface.enableAnimations (prefs_ui.rs sync_animations, #3273) zeroes egui animation_time and scroll animation in both styles; the Home screen lists recent files (canvas.rs home_recent, #2691); the canvas dot pattern toggle is interface.showCanvasDots (#2264, global rather than per theme); interface.showHomeRecentFiles hides the Home screen recents (#4382) | | UI-217-11 | Soft dark and soft light themes with picker previews; outlined knobs in light themes | partial | [#217](https://github.com/storytold/photocraft/issues/217) | theme.rs ThemeKind has fourteen themes: the twelve earlier ones plus Soft Dark and Soft Light (low-contrast Studio-layout palettes, text at 4.5:1, selectable in Preferences with the existing theme-card previews, ui.set {theme}, Window > Theme); outlined knobs in the light themes are still missing | @@ -207,7 +207,7 @@ Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_w | UI-217-20 | 'Show rulers in new documents' preference; guides stored as f64 | done | [#217](https://github.com/storytold/photocraft/issues/217) | View › Rulers is remembered in unitsAndRulers.showRulers and applied at launch and on change (#2918; rulers_open_as_last_set_after_a_restart); doc Guides are Vec through New Guide, .pcraft and PSD 1032 (guides_keep_sub_pixel_positions_through_pcraft_and_psd) | | UI-217-21 | One Preset Manager for every preset kind with folders, search, reorder, load/save sets | partial | [#217](https://github.com/storytold/photocraft/issues/217) | edit_menu_cmds.rs:714 covers brushes, custom shapes, patterns with reorder | | UI-217-22 | Stamp Visible into a new layer keeping originals; Alt+Merge keeps originals | done | [#217](https://github.com/storytold/photocraft/issues/217) | stamp_cmds.rs layer.stampVisible (Cmd+Alt+Shift+E) merges every visible layer into a new layer above the active one and keeps the originals; layer.stampDown (Cmd+Alt+E) too. As in Photoshop they have no menu item of their own: Alt + Layer > Merge Visible / Merge Down / Merge Layers run them (stamp_cmds::alt_variant, menus.rs); stamp_tests.rs alt_click_on_merge_items_stamps and cmd_alt_shift_e_stamps_visible_and_can_be_rebound | -| UI-217-23 | Layer clipboard: copy/paste whole layers (masks, styles, type) between documents | partial | [#217](https://github.com/storytold/photocraft/issues/217) | layer.copyToDocument copies layers into another open document keeping names, content, masks, styles and blending, converting to the destination's profile and depth, as one history step (layer_copy_cmds.rs, #589). It is the command a drag between documents dispatches; there is still no copy/paste layer clipboard | +| UI-217-23 | Layer clipboard: copy/paste whole layers (masks, styles, type) between documents | partial | [#217](https://github.com/storytold/photocraft/issues/217) | Edit › Copy with no pixel selection takes layers whole and Paste recreates them in this or another open document, converted to its profile and depth, as one history step (edit_cmds.rs takes_whole, paste_layers): smart objects (#2428), type, shape and group layers (#2670), fill and adjustment layers (#2344), and several selected layers with their masks and styles (#2478). layer.copyToDocument is the drag between documents (layer_copy_cmds.rs, #589). Missing: a single pixel layer copies its pixels only, leaving its mask and styles behind | ## Type @@ -243,7 +243,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T ## Reliability -Never-crash attribute on 29 of 29 crate roots. +Never-crash attribute on 30 of 30 crate roots. | Id | Target | Status | Issue | Note | |---|---|---|---|---| diff --git a/docs/sparse-raster-reads-performance.md b/docs/sparse-raster-reads-performance.md new file mode 100644 index 0000000000..1cc1a04502 --- /dev/null +++ b/docs/sparse-raster-reads-performance.md @@ -0,0 +1,45 @@ +# Sparse raster reads + +Skip absent zero-default tiles and avoid temporary default-pixel allocations and copies. ZIP CRC acceleration is already on main. + +A roughly 4% median dense 16-bit city-photo read slowdown repeated, with paired intervals crossing zero. The local fix shares the existing contiguous row loop between allocating and reusable-buffer reads, removes duplicated code, and preserves zero-filled allocation for allocating reads. Final measurements include all photo depths and authored designs; all outputs match bit for bit. + +Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions. + +The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used. + +The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance. + +| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes | +|---|---|---:|---:|---:|---:|---:| +| panasonic-16 | read (fixed) | 54.689 | 41.140 | -24.8% | -28.0..-23.8% | — | +| panasonic-16 | render (fixed) | 38.492 | 38.345 | -0.4% | -1.8..+2.0% | — | +| canon-16 | read (fixed) | 27.634 | 19.236 | -30.4% | -34.0..-23.3% | — | +| panasonic-8 | read (fixed) | 50.429 | 20.210 | -59.9% | -62.2..-56.7% | — | +| panasonic-8 | render (fixed) | 30.953 | 30.670 | -0.9% | -3.4..+1.5% | — | +| panasonic-32 | read (fixed) | 91.120 | 69.922 | -23.3% | -23.6..-20.7% | — | +| panasonic-32 | render (fixed) | 39.436 | 39.867 | +1.1% | -4.5..+3.7% | — | +| canon-8 | read (fixed) | 24.899 | 10.543 | -57.7% | -58.5..-54.9% | — | +| canon-8 | render (fixed) | 16.925 | 16.901 | -0.1% | -5.6..+5.5% | — | +| canon-16 | render (fixed) | 21.569 | 21.716 | +0.7% | -2.2..+2.4% | — | +| canon-32 | read (fixed) | 45.494 | 35.200 | -22.6% | -23.5..-21.5% | — | +| canon-32 | render (fixed) | 22.056 | 22.180 | +0.6% | -1.8..+6.9% | — | +| layout-masks | read (fixed) | 35.240 | 3.438 | -90.2% | -90.7..-89.9% | — | +| layout-masks | render (fixed) | 8.167 | 7.461 | -8.6% | -10.6..-8.3% | — | +| layout-mask-index | read (fixed) | 2.314 | 1.051 | -54.6% | -61.7..-50.0% | — | +| layout-mask-index | render (fixed) | 1.926 | 1.827 | -5.1% | -13.0..+0.6% | — | + +All real read-region and render float bits match main. The committed previous-read-region oracle also covers sparse boundaries, negative coordinates, signed zero, defaults and eight pixel formats. + +Current local checks: `cargo test -p photocraft-raster --locked --lib` (27 passed, one ignored manual benchmark); strict all-target Clippy; affected wasm32 check. All passed. The existing previous-read-path oracle covers the shared loop. + +Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run. + +## Earlier split validation + +These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed. + +- `cargo test -p photocraft-raster --locked`: passed (27 passed, 1 ignored). +- `cargo clippy -p photocraft-raster --locked --all-targets -- -D warnings`: passed. +- `cargo xtask layers`: passed. +- `cargo check -p photocraft-raster --locked --target wasm32-unknown-unknown`: passed. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c4bfd998e7..cb15e4b121 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; 2026-10-11: retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-18 · **Change:** minor (fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; 2026-10-11: retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026 The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -167,7 +167,7 @@ parity for the area and are already contained in the dimension rows above. | Area | % | Hours | Notes | |---|---:|---:|---| -| Layers, groups, masks, blend modes, smart objects, layer styles | 65% | 150–250 | Broad and GPU-accelerated. Open: layer clipboard between documents (UI-217-23: `layer.copyToDocument` exists, no copy/paste), smart-object perspective (FILE-215-6), a user contour library (FILE-215-15). Multi-layer Smart Object conversion (#2052, #2651), Stamp Visible (UI-217-22) and mask targeting by command (#2458) are done | +| Layers, groups, masks, blend modes, smart objects, layer styles | 65% | 150–250 | Broad and GPU-accelerated. Open: a single pixel layer copies its pixels without its mask and styles (UI-217-23: smart object, type, shape, group, fill and adjustment layers and multi-layer selections copy and paste whole), smart-object perspective (FILE-215-6), a user contour library (FILE-215-15). Multi-layer Smart Object conversion (#2052, #2651), Stamp Visible (UI-217-22) and mask targeting by command (#2458) are done | | Selections, Select and Mask, channels | 55% | 120–200 | All selection tools, single row/column marquee included (#2837). Select and Mask is a dialog with Photoshop's view modes, a Refine Edge Brush and six outputs, not a workspace (TOOL-214-1), no Refine Hair (#2671); Select Subject/Sky classical, 559 ms p50 on 24 MP vs a 100 ms budget | | Painting and brush engine | 55% | 150–250 | Every Brush Settings section exists; feel is the gap: lag on big brushes, pressure jumps, smoothing and edge quality reports ([brush-parity.md](brush-parity.md)) | | Retouching (healing, clone, patch, remove, content-aware) | 50% | 100–180 | Remove tool non-generative; Content-Aware Fill has no workspace (TOOL-214-15); no live stroke preview for the Mixer Brush yet (TOOL-213-7) | @@ -565,6 +565,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| +| 2026-10-18 | minor | Layers: with no selection, Copy takes fill and adjustment layers whole and Paste recreates them (#2344); UI-217-23 stays partial; percentages unchanged | | 2026-10-13 | minor | Vector shapes: on-canvas corner radius widgets on live rectangles (TOOL-214-12); estimates unchanged | | 2026-10-13 | minor | Stale "missing tool" rows corrected against main: Color Replacement (`paint.colorReplacement`), Red Eye (`paint.redEye`) and Add/Delete Anchor Point (the Pen flyout) are live toolbar tools and Frame landed, so Art History Brush is the only tool still missing; percentages unchanged | | 2026-10-12 | minor | Free Transform options bar H/V skew fields; percentages unchanged | diff --git a/docs/text-raster-performance.md b/docs/text-raster-performance.md new file mode 100644 index 0000000000..5bc446ead1 --- /dev/null +++ b/docs/text-raster-performance.md @@ -0,0 +1,63 @@ +# Text rasterization: what a type render costs + +Measured 2026-10-17 on Windows 11, `i5-10300H` (4 cores / 8 threads, 16 GB), release build, +`rustc 1.98.1`, with a probe that renders one paragraph layer through +`photocraft_text::render::rasterize_warped` and times each stage of it. + +Document: 300 dpi, a 2400 × 1600 px paragraph box holding 4000 characters at 14 pt — the worst +case a type edit has (a whole page of text at print resolution; 1851 laid-out glyphs, 2329 × 1610 px +of ink = 3.75 MP). + +| Stage | ms | What it does | +|---|---:|---| +| ink rectangle (`ink_rect_warped`) | 4.1 | its own pass over every glyph, to size the surface | +| draw (`draw_pass` into `Coverage`) | 18.6–22.9 | glyph outlines, curve flattening (0.03 px tolerance), winding scanlines | +| prefix sum (`Coverage::finish`) | 7.0–8.1 | resolves the winding accumulator to coverage 0…1, one running sum over 3.75 M pixels | +| composite | 22.6–33.4 | each colour's coverage over the premultiplied accumulator | +| unpremultiply | 11.2–14.0 | divides the accumulator back to straight colour | +| `Surface::write_region` | 23.8 | converts to the document format and fills the tiles | +| `Surface::prune` | 3.1 | drops tiles that came back the layer's default | +| **total** | **86–104** | | + +So the glyph geometry — what one would expect to dominate — is under a quarter of it. The rest is +scalar work over the pixel buffers, and every one of those passes is per pixel: a pixel's maths +reads and writes only its own slots. + +## What runs in parallel now + +`composite`, `unpremultiply` and the tile conversion run on all cores (rayon, native only; the web +build keeps the serial loops, since wasm has no threads). The rasterizer writes its tiles with +`Surface::write_region_par`; `Surface::write_region` stays serial, because mask builds call it inside +a `OnceLock` initializer, which must not enter rayon. Nothing about them +is order-dependent, so each pixel still sees the same operations on the same inputs — the pixels +are identical, not merely close. + +| | before | after | +|---|---:|---:| +| the 3.75 MP case above | 98.3–103.9 ms | 60.3–61.8 ms | + +`crates/text/src/tests.rs::parallel_raster_matches_a_single_thread` renders the shapes the pipeline +can take (plain, faux bold italic, no antialias, wide gamut, a wrapping paragraph box; 8/16/32-bit) +on a one-thread pool and on the default pool and compares the surfaces; `crates/raster`'s existing +`region_writes_match_scalar_bytes_for_every_format` compares `write_region` and `write_region_par` +against a scalar reference implementation, tile for tile. + +## What stays on one thread, and why + +- **draw** (19–23 ms): the winding accumulator carries across scanlines and rows — a pixel's value + depends on the rows above it, and one scanline can spill into the next row's first pixel. A band + split can be exact (bands keep absolute coordinates, carry the spill in band order, and are + assembled before the prefix sum), but each band re-traverses every glyph — the traversal is not + free, so the win is bounded by the band count. Worth doing when the draw matters more than it does + now. +- **prefix sum** (7–8 ms): a running f32 sum over the whole image. Splitting it per row needs the + row's starting sum, which is that same sequential chain — the only exactly-known starting sums are + the ones the chain computes. +- **ink rectangle** (4.1 ms): a second full traversal into a bounds sink. Per-glyph bounds reduce by + min/max, which is associative and exact, so this is a candidate for the same treatment as the + stages above (a glyph-range split, not a band split). + +## Related + +Byte-identical output matters here beyond taste: text pixels reach a PSD's saved cache and the +round-trip corpora. `cargo xtask test-corpus` and the Photoshop oracle tests are the gate. diff --git a/docs/ui-design.md b/docs/ui-design.md index d4ac18d297..d0ee20f7bb 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -103,8 +103,8 @@ The app's top bar (`panels::title_bar`) starts with the brand mark (the app icon ## Compact tool controls The toolbar scrolls its tool rows when two columns still exceed the available height. Foreground -and background colours stay visible below those rows, together with Pro's Quick Mask and Screen -Mode controls. Long options rows scroll horizontally. Both scrollers bring newly focused +and background colours stay visible below those rows, together with the Quick Mask and Screen +Mode controls in every theme. Long options rows scroll horizontally. Both scrollers bring newly focused controls into view and retain the existing tool actions and popups. The offscreen regression fixture uses production panels, fonts and SVG loaders across every diff --git a/docs/user/AGENTS.md b/docs/user/AGENTS.md new file mode 100644 index 0000000000..dd791ea1f5 --- /dev/null +++ b/docs/user/AGENTS.md @@ -0,0 +1,60 @@ +# User docs: rules for agents and contributors + +Everything in this folder (except this file, CLAUDE.md and README.md) is published at +https://getartcraft.com/docs/photocraft. The file path is the URL: +`troubleshooting/taskbar-turns-black.md` → `/docs/photocraft/troubleshooting/taskbar-turns-black`. +Renaming a file breaks links, so add the old path to `redirect_from` when you rename. + +## Who reads this + +Artists using PhotoCraft, Discord mods answering them, and AI assistants looking things up for +either. Write for an artist, not a developer. + +## Page rules + +- One question or problem per page. Lead with the answer or the fix in the first two lines. +- Plain words, short sentences, numbered steps for anything the reader does. +- Start the body at `##`. The page title comes from frontmatter. +- Link to other pages instead of repeating them. Use relative links to the `.md` file: + `[Install PhotoCraft](../getting-started/install.md)`. +- No marketing copy, no "simply", no claims you have not checked in the code or a release. +- Call the product "PhotoCraft", as the app, its downloads and getartcraft.com do. +- Name UI labels exactly as the app shows them, in **bold**. Menu paths read `File › Open…`. +- Troubleshooting pages: `## Symptoms`, `## Fix`, `## Why this happens` (optional), + `## Still stuck?` (link the issue tracker or Discord). + +## Frontmatter + + --- + title: Export an image as PNG or JPEG + description: One sentence for search results, link previews and AI summaries. + order: 10 # optional, sorts within the folder (lower first) + verified: 0.7.0 # optional, app version you last checked this page against + redirect_from: [old/path] # optional, old URLs (relative to /docs/photocraft) + --- + +Only `key: value` and `key: [a, b]` lines work. Quote values that start with a quote or contain ` #`. + +Set `verified` to the latest release (the newest release tag) after checking the page against that tag with `git show :`. Pages describe the latest release users download, not unreleased code on main. + +## Folders + +- `getting-started/` install and first run +- `guides/` how to do one thing +- `troubleshooting/` symptom → fix +- `faq/` short answers +- `reference/` lists and settings + +A folder's `index.md` names the folder in the sidebar. Files or folders starting with `_` are +drafts and are not published. + +## Check before you push + + node /frontend/apps/artcraft-website-next/scripts/docs/core.mjs docs/user + +The checker lives in storytold/artcraft-services. A CI check will be added once it is on that repo's main branch. + +## Support PRs + +Pages written to answer a user question come in as PRs titled `docs(support): `. +Review them like code: check every claim against the source. diff --git a/docs/user/CLAUDE.md b/docs/user/CLAUDE.md new file mode 100644 index 0000000000..e7bcfb70ed --- /dev/null +++ b/docs/user/CLAUDE.md @@ -0,0 +1 @@ +Read `AGENTS.md` in this folder: it has the rules for the user docs. diff --git a/docs/user/faq/index.md b/docs/user/faq/index.md new file mode 100644 index 0000000000..c50180a390 --- /dev/null +++ b/docs/user/faq/index.md @@ -0,0 +1,10 @@ +--- +title: FAQ +description: Short answers about PhotoCraft's price, Photoshop files and how it compares with Photoshop. +order: 40 +verified: 0.8.2 +--- + +- [Is PhotoCraft free?](is-photocraft-free.md) +- [Can PhotoCraft open my Photoshop files?](open-photoshop-files.md) +- [Can PhotoCraft replace Photoshop?](replace-photoshop.md) diff --git a/docs/user/faq/is-photocraft-free.md b/docs/user/faq/is-photocraft-free.md new file mode 100644 index 0000000000..dd9946540a --- /dev/null +++ b/docs/user/faq/is-photocraft-free.md @@ -0,0 +1,14 @@ +--- +title: Is PhotoCraft free? +description: PhotoCraft is free and open source under the MIT or Apache 2.0 license, and works offline. +order: 10 +verified: 0.8.2 +--- + +Yes. PhotoCraft is one of the Crafting Apps, which the project describes as free, open-source creative tools. The code is licensed under MIT or Apache 2.0, your choice, and is on [GitHub](https://github.com/storytold/photocraft). + +PhotoCraft works offline. Its smart selection tools run on your computer, with no cloud and no account. + +The ArtCraft logos in the repository are not open source. + +See [Install PhotoCraft](../getting-started/install.md) to download it. diff --git a/docs/user/faq/open-photoshop-files.md b/docs/user/faq/open-photoshop-files.md new file mode 100644 index 0000000000..06fbe367bc --- /dev/null +++ b/docs/user/faq/open-photoshop-files.md @@ -0,0 +1,16 @@ +--- +title: Can PhotoCraft open my Photoshop files? +description: PhotoCraft opens and saves layered PSD and PSB files and keeps what it does not understand yet. +order: 20 +verified: 0.8.2 +--- + +Yes. PhotoCraft opens, edits and saves layered PSD and PSB files, including 16-bit, 32-bit, CMYK and Lab documents. + +When it saves the file again, the picture renders the same for 307 of the 309 files in the psd-tools test set the project checks against. Parts PhotoCraft does not model yet, such as raw blocks and descriptors, are carried over instead of being dropped. A re-saved file is not byte for byte the same as the original, because PhotoCraft rewrites image resources, layer records and the composite. + +Text layers stay editable. In version 0.7.0 some of them moved when you started editing them; 0.8.2 fixes that, see [Text moves when I start editing a PSD text layer](../troubleshooting/text-moves-when-editing.md). + +Results vary from file to file. If a PSD does not open or looks wrong, search the issue tracker or report it with the file. + +PhotoCraft also opens layered TIFF, Paint.NET, OpenRaster, SVG, Krita and Affinity files (Krita and Affinity read only), and many flat formats. The full list is in [Open and save files](../guides/open-and-save-files.md). diff --git a/docs/user/faq/replace-photoshop.md b/docs/user/faq/replace-photoshop.md new file mode 100644 index 0000000000..56027f2706 --- /dev/null +++ b/docs/user/faq/replace-photoshop.md @@ -0,0 +1,12 @@ +--- +title: Can PhotoCraft replace Photoshop? +description: Not yet. PhotoCraft is in early alpha and is not ready for daily professional work, but it follows Photoshop's menus and shortcuts. +order: 30 +verified: 0.9.0 +--- + +Not yet. PhotoCraft is in early alpha. Much of Photoshop's feature surface exists in some form, but the project says plainly that it is not yet a Photoshop replacement for daily professional work. + +The biggest gaps the project lists are AI and generative features, tools Photoshop has that PhotoCraft does not yet, depth in typography and professional workflows, and plug-in compatibility. Every Photoshop menu item is connected to a command, but that only shows the menu is wired up. Having a tool or command is not the same as matching Photoshop's behaviour. + +What PhotoCraft does well already: layers, masks, adjustment layers, layer styles, type, vector shapes, brushes and live-preview filters, in a menu and shortcut layout that follows Photoshop. See [PhotoCraft](../index.md) for an overview, and the [project roadmap](https://github.com/storytold/photocraft/blob/main/ROADMAP.md) for what comes next. diff --git a/docs/user/getting-started/index.md b/docs/user/getting-started/index.md new file mode 100644 index 0000000000..2383e17f0b --- /dev/null +++ b/docs/user/getting-started/index.md @@ -0,0 +1,21 @@ +--- +title: Getting started +description: Install PhotoCraft and open your first image. +order: 10 +verified: 0.8.2 +--- + +Install PhotoCraft, then open an image with **File › Open…**. The panels you use most are **Layers**, **Properties** and **History**. + +1. [Install PhotoCraft](install.md). +2. Start PhotoCraft and choose **File › Open…**. To start from nothing, choose **File › New…** and click **Create**. +3. Pick the **Horizontal Type Tool**, a selection tool or an adjustment, and work on the image. Every step is listed in the **History** panel and can be undone. +4. Keep your layers with **File › Save As…** (PSD or PhotoCraft), or make a flat copy with **File › Export › Export As…**. + +The guides walk through each of these: + +- [Open and save files](../guides/open-and-save-files.md) +- [Adjust colors without changing your pixels](../guides/adjust-colors-with-adjustment-layers.md) +- [Select part of an image and mask it](../guides/select-and-mask.md) +- [Add and style text](../guides/add-and-style-text.md) +- [Export an image](../guides/export-an-image.md) diff --git a/docs/user/getting-started/install.md b/docs/user/getting-started/install.md new file mode 100644 index 0000000000..975f7f3b71 --- /dev/null +++ b/docs/user/getting-started/install.md @@ -0,0 +1,59 @@ +--- +title: Install PhotoCraft +description: Download PhotoCraft for Windows 10 or 11, macOS or Linux from getartcraft.com or GitHub, or install it with ArtCraft Launcher. +order: 10 +verified: 0.8.2 +--- + +The easiest way is the [PhotoCraft page on getartcraft.com](https://getartcraft.com/apps/photocraft). You can also install it with [ArtCraft Launcher](https://getartcraft.com/docs/craft-launcher/guides/install-and-update-apps), which lists PhotoCraft. For a specific build or file format, take it from the [latest release](https://github.com/storytold/photocraft/releases/latest) on GitHub. In the file names below, `` stands for the version number, for example `0.8.2`. + +## Windows + +PhotoCraft needs Windows 10 or later. On Windows 7 and 8 the installer stops with "PhotoCraft needs Windows 10 or later." + +1. Open the [latest release](https://github.com/storytold/photocraft/releases/latest). +2. Download `photocraft--windows-x64.msi`. It fits most PCs (64-bit Intel and AMD). +3. Run the file and follow the installer. + +To run without installing, download `photocraft--windows-x64-portable.zip` instead and unzip it. + +| Your PC | Installer | Portable | +|------------------------------------|------------------------------------------|---------------------------------------------------| +| 64-bit Intel or AMD | `photocraft--windows-x64.msi` | `photocraft--windows-x64-portable.zip` | +| Arm (Snapdragon and other Arm PCs) | `photocraft--windows-arm64.msi` | `photocraft--windows-arm64-portable.zip` | +| 32-bit | `photocraft--windows-x86.msi` | `photocraft--windows-x86-portable.zip` | + +The installers and executables are code-signed. + +## macOS + +1. Download `photocraft--macos-universal.dmg`. It works on Apple silicon and Intel Macs, and is signed and notarized by Apple. +2. Open it and drag PhotoCraft to Applications. + +## Linux + +Pick one file from the release. Use `x86_64` for Intel and AMD, or `aarch64` for Arm. + +| Format | File | Notes | +|---------------------|----------------------------------------------|------------------------------------------------------------------------------------| +| AppImage | `photocraft--linux-x86_64.AppImage` | Runs anywhere and needs no install. | +| Debian and Ubuntu | `photocraft--linux-x86_64.deb` | | +| Fedora and openSUSE | `photocraft--linux-x86_64.rpm` | | +| Flatpak | `photocraft--linux-x86_64.flatpak` | Run `flatpak install --user `, then `flatpak run ai.storyteller.photocraft`. | +| Tarball | `photocraft--linux-x86_64.tar.gz` | Unpack it anywhere. | + +The first time you run the AppImage, it adds its icon and menu entry under `~/.local/share`. Set `PHOTOCRAFT_NO_DESKTOP_INTEGRATION=1` to skip that. For RISC-V, take the `riscv64` file: `photocraft--linux-riscv64.tar.gz`, `.deb` or `.rpm`. The RISC-V tarball needs glibc 2.39 or newer. + +On a Wayland session, files dropped on the PhotoCraft window do not open yet. Use **File › Open…** instead, or copy the image in your file manager and paste it with Ctrl+V. To drag and drop, start PhotoCraft under XWayland with `WAYLAND_DISPLAY= photocraft`. PhotoCraft shows the right command for your install in a notice until you dismiss it. + +## FreeBSD and the web + +FreeBSD 14 (x86_64) has a tarball, `photocraft--freebsd-x86_64.tar.gz`, laid out like `/usr/local`. The web version comes as `photocraft-web-.zip`, a static site you host on any web server. It runs in a modern browser. + +## Check your download + +`SHA256SUMS.txt` on the release lists a checksum for every file. + +## Next step + +Open an image: [Open and save files](../guides/open-and-save-files.md). diff --git a/docs/user/guides/add-and-style-text.md b/docs/user/guides/add-and-style-text.md new file mode 100644 index 0000000000..71dcd7db97 --- /dev/null +++ b/docs/user/guides/add-and-style-text.md @@ -0,0 +1,36 @@ +--- +title: Add and style text +description: Add point or paragraph text with the Horizontal Type Tool in PhotoCraft, then give it a drop shadow or glow. +order: 40 +verified: 0.8.2 +--- + +Pick the **Horizontal Type Tool** (shortcut `T`), click on the canvas for a line of text or drag for a text box, and type. Text stays editable, so you can change the words and the style later. + +## Add text + +1. Choose the **Horizontal Type Tool** in the toolbox, or press `T`. +2. Click the canvas to start a line of text (point text), or drag a rectangle to start a block of text (paragraph text). +3. Type. The text is edited right on the canvas. +4. Set the font, size, leading, tracking, alignment and color with the character and paragraph controls. Each typing session is one **Edit Type** step in the **History** panel. + +To switch between the two kinds later, use **Type › Convert to Paragraph Text** or **Type › Convert to Point Text**. + +## Edit the text later + +Pick the **Horizontal Type Tool** and click the text on the canvas. Text from a PSD that was made in Photoshop stays editable too. If PSD text jumps when you start editing it, update to 0.8.2; see [Text moves when I start editing a PSD text layer](../troubleshooting/text-moves-when-editing.md). + +To start new text on top of an existing text layer instead of editing it, hold `Shift` while you click. + +## Add a layer style + +1. Click the text layer in the **Layers** panel. +2. Choose **Layer › Layer Style**, then an effect such as **Drop Shadow…**, **Outer Glow…**, **Stroke…** or **Bevel & Emboss…**. The **Layer Style** dialog opens. +3. Adjust the effect and confirm. + +The other effects in the menu are **Inner Shadow…**, **Inner Glow…**, **Satin…**, **Color Overlay…**, **Gradient Overlay…** and **Pattern Overlay…**. **Layer › Layer Style** also has **Copy Layer Style** and **Paste Layer Style** to reuse a style on another layer, and **Hide All Effects**. + +## Turn text into shapes or pixels + +- **Type › Convert to Shape** makes vector shapes from the letters. +- **Type › Rasterize Type Layer** turns the text into pixels. After that you can no longer edit the words. diff --git a/docs/user/guides/adjust-colors-with-adjustment-layers.md b/docs/user/guides/adjust-colors-with-adjustment-layers.md new file mode 100644 index 0000000000..500ff3521c --- /dev/null +++ b/docs/user/guides/adjust-colors-with-adjustment-layers.md @@ -0,0 +1,32 @@ +--- +title: Adjust colors without changing your pixels +description: Add a Curves, Levels or other adjustment layer in PhotoCraft so you can change or switch it off later. +order: 20 +verified: 0.8.2 +--- + +Use **Layer › New Adjustment Layer** and pick an adjustment. The change sits on its own layer above your image, so your original pixels stay as they were and you can edit or hide the adjustment later. + +## Add an adjustment layer + +1. Open your image and click the layer the adjustment should sit above in the **Layers** panel. +2. Choose **Layer › New Adjustment Layer**, then an adjustment such as **Curves…**, **Levels…**, **Vibrance…** or **Hue/Saturation…**. +3. Change the settings in the **Properties** panel, which shows the settings of the new layer. + +The same list is behind the button at the bottom of the **Layers** panel, labelled **Create new fill or adjustment layer** when you hover over it. + +The adjustments in the menu are **Brightness/Contrast**, **Levels**, **Curves**, **Exposure**, **Vibrance**, **Hue/Saturation**, **Color Balance**, **Black & White**, **Photo Filter**, **Channel Mixer**, **Color Lookup**, **Invert**, **Posterize**, **Threshold**, **Gradient Map** and **Selective Color**. + +## Limit it to one area + +1. Select the area first, for example with the **Elliptical Marquee Tool**. See [Select part of an image and mask it](select-and-mask.md). +2. Add the adjustment layer as above. +3. With the adjustment layer active, choose **Layer › Layer Mask › Reveal Selection**. The adjustment now shows only inside the selection. + +## Change it later + +Click the adjustment layer in the **Layers** panel and edit its settings in **Properties**. Every step you take is also listed in the **History** panel. + +## Apply an adjustment straight to the pixels + +If you do not need to change it later, use **Image › Adjustments**, for example **Image › Adjustments › Curves…**. These change the pixels of the layer directly and are not kept as a separate layer. diff --git a/docs/user/guides/export-an-image.md b/docs/user/guides/export-an-image.md new file mode 100644 index 0000000000..82d5c5a4e4 --- /dev/null +++ b/docs/user/guides/export-an-image.md @@ -0,0 +1,38 @@ +--- +title: Export an image +description: Export a PNG, JPG, WebP, TIFF or TGA from PhotoCraft with a preview, a size estimate and a scale. +order: 50 +verified: 0.8.2 +--- + +Choose **File › Export › Export As…**, set the format, and click **Export**. The dialog shows a preview and an estimate of the file size before you save. Your layered document is not changed. + +## Export with settings + +1. Choose **File › Export › Export As…**. +2. Under **File Settings**, pick a **Format**: **PNG**, **JPG**, **WebP**, **TIFF** or **TGA**. +3. Set the options for that format: + - **JPG** and lossy **WebP** have a **Quality** slider from 1 to 100. + - **WebP** also has a **Lossless** checkbox. + - **TGA** has **Resolution**: **Auto**, **24 bits/pixel** or **32 bits/pixel**. + - **Transparency** keeps transparent areas. JPG has no transparency, so this checkbox is not shown for JPG and the image is flattened. + - **Metadata** is **None** or **All**. +4. Under **Image Size**, set **Scale** in percent. The size in pixels shows below it. +5. Check the preview on the right. The line under it shows the format and the estimated file size. +6. Click **Export**, then choose a name and a place for the file. + +PhotoCraft shows "Exported" with the file path and size in the status bar when it is done. + +## Export in one step + +**File › Export › Quick Export as PNG** exports without asking about settings. It uses the format, quality, metadata and location you set in **File › Export › Export Preferences…**. + +## Export layers + +Choose **Layer › Export As…** (or **Layer › Quick Export as PNG**) to export only the active layer. + +With several layers or artboards selected in the **Layers** panel, both commands export each one as its own file. You choose a name and place once. The first file gets that name, and the others get the same name with a number and the layer name added. + +## Keep your layers + +Exporting makes a flat copy. To keep the layers, use **File › Save As…** with **PSD Document** or **PhotoCraft**; see [Open and save files](open-and-save-files.md). diff --git a/docs/user/guides/index.md b/docs/user/guides/index.md new file mode 100644 index 0000000000..a493dc2c8a --- /dev/null +++ b/docs/user/guides/index.md @@ -0,0 +1,14 @@ +--- +title: Guides +description: Step-by-step guides for the everyday tasks in PhotoCraft. +order: 20 +verified: 0.8.2 +--- + +- [Open and save files](open-and-save-files.md) +- [Adjust colors without changing your pixels](adjust-colors-with-adjustment-layers.md) +- [Select part of an image and mask it](select-and-mask.md) +- [Add and style text](add-and-style-text.md) +- [Export an image](export-an-image.md) + +Menu paths are written like **File › Open…**. Where a shortcut is shown, `Cmd` is the Ctrl key on Windows and Linux. diff --git a/docs/user/guides/open-and-save-files.md b/docs/user/guides/open-and-save-files.md new file mode 100644 index 0000000000..0c2b4306af --- /dev/null +++ b/docs/user/guides/open-and-save-files.md @@ -0,0 +1,32 @@ +--- +title: Open and save files +description: Open a PSD or other image in PhotoCraft, and save it with its layers or as a flat copy. +order: 10 +verified: 0.8.2 +--- + +Open a file with **File › Open…** and keep your layers with **File › Save As…**, choosing **PSD Document** or **PhotoCraft** as the type. Formats such as PNG and JPEG are flat: they hold one image with no layers. + +## Open a file + +1. Choose **File › Open…**. +2. Pick your file. The type menu in the dialog offers **All Formats**, **PhotoCraft**, **OpenRaster**, **Krita**, **SVG** and **Paint.NET**. +3. Confirm in the dialog. + +You can also reopen a recent file from **File › Open Recent**. On Linux under Wayland, dropping a file on the window does not work yet; see [Install PhotoCraft](../getting-started/install.md). + +PhotoCraft opens PSD and PSB (including 16-bit, 32-bit, CMYK and Lab files), layered TIFF, Paint.NET (`.pdn`), OpenRaster (`.ora`), SVG, and the flat formats PNG, JPEG, TIFF, WebP, GIF, BMP, TGA, ICO, QOI, PNM, PCX, OpenEXR, Radiance HDR and FITS. Krita files (`.kra`) open as one image layer made from the picture Krita saved, without Krita's layers. HEIC and HEIF photos from iPhone and Mac open too, read only, and so do camera raw files such as DNG, CR2, CR3, NEF and ARW. It can also open Affinity files (`.af`, `.afphoto`, `.afdesign`, `.afpub`), read only; PhotoCraft cannot save Affinity files. Anything it cannot match exactly, such as layer effects and adjustments, is approximated or left out and PhotoCraft shows a warning. + +## Save with layers + +1. Choose **File › Save As…**. +2. Pick **PSD Document** (`.psd` or `.psb`) to share the file with Photoshop, or **PhotoCraft** (`.pcraft`) for PhotoCraft's own format. +3. Name the file and save. + +After that, **File › Save** saves into the same file. **File › Save a Copy…** saves a copy under a new name. While a large file saves, the status bar and the tab title show "Saving" with a percentage. + +The **Save As…** dialog also lists OpenRaster, PNG, JPEG, WebP, TIFF, Targa, OpenEXR and FITS. **File › Save** on an opened JPEG keeps its quality, and on a WebP keeps it lossy or lossless. Check the file extension in the name box: PhotoCraft writes the format that the extension names. If you want a flat PNG or JPEG with a size and quality preview, use [Export an image](export-an-image.md) instead. + +## Good to know + +Saving a PSD again keeps the layers and the rendered result, but the file is not byte for byte the same as the one you opened. PhotoCraft rewrites image resources, layer records and the composite. It keeps parts it does not model yet instead of dropping them. diff --git a/docs/user/guides/select-and-mask.md b/docs/user/guides/select-and-mask.md new file mode 100644 index 0000000000..50f78b7685 --- /dev/null +++ b/docs/user/guides/select-and-mask.md @@ -0,0 +1,40 @@ +--- +title: Select part of an image and mask it +description: Make a selection with the marquee tools or Select Subject, soften its edge, and turn it into a layer mask in PhotoCraft. +order: 30 +verified: 0.8.2 +--- + +Pick a selection tool, drag around the area, then choose **Layer › Layer Mask › Reveal Selection** to show only that area. A mask hides part of a layer without erasing any pixels. + +## Make a selection + +Use one of these: + +- **Elliptical Marquee Tool** or **Rectangular Marquee Tool** for simple shapes. Drag on the canvas. +- **Quick Selection Tool**, **Magic Wand Tool** or **Lasso Tool** to follow the edges of an object. +- **Select › Subject** to let PhotoCraft pick the main subject. The **Quick Selection Tool** and **Object Selection Tool** also have a **Select Subject** button in the options bar. If nothing is found, PhotoCraft says "No subject found" and suggests the Object Selection or Lasso tool. + +Smart selection runs on your computer. It needs no account and no cloud. + +## Adjust the selection + +- **Select › Inverse Selection** swaps the selected and unselected areas. +- **Select › Modify** has **Border…**, **Smooth…**, **Expand…**, **Contract…** and **Feather…**. Feather softens the edge. +- **Select › Select and Mask…** refines an edge, for example around hair. +- **Select › Deselect** removes the selection. **Select › Reselect** brings back the last one. + +## Turn the selection into a mask + +1. Click the layer you want to mask in the **Layers** panel. +2. Choose **Layer › Layer Mask › Reveal Selection** to show only the selected area, or **Hide Selection** to hide it. + +To start with the whole layer visible or hidden and paint the mask yourself, use **Layer › Layer Mask › Reveal All** or **Hide All**. + +## Remove or apply a mask + +- **Layer › Layer Mask › Delete** removes the mask. +- **Layer › Layer Mask › Apply** applies the mask to the layer's pixels. +- **Layer › Layer Mask › Disable Layer Mask** (or **Enable Layer Mask**) switches the mask off and on. + +To limit a color adjustment to the selection, see [Adjust colors without changing your pixels](adjust-colors-with-adjustment-layers.md). diff --git a/docs/user/index.md b/docs/user/index.md new file mode 100644 index 0000000000..29e229c0bd --- /dev/null +++ b/docs/user/index.md @@ -0,0 +1,25 @@ +--- +title: PhotoCraft +description: PhotoCraft is a free, open-source image editor with layers, masks, type and real PSD files, built as an alternative to Adobe Photoshop. +verified: 0.8.2 +--- + +PhotoCraft is a free, open-source image editor with layers, masks, adjustment layers, layer styles, type, vector shapes and brushes. It is an alternative to Adobe Photoshop: the menus, panels, tools and shortcuts follow Photoshop's layout, so Photoshop users find things where they expect them. + +It is a native app written in Rust that draws the canvas on your graphics card, works offline, and opens and saves layered PSD files. It runs on macOS, Windows, Linux and FreeBSD, and a web version runs in the browser. PhotoCraft is in early alpha: much of Photoshop's feature surface exists, but it is not yet a Photoshop replacement for daily professional work. See [Can PhotoCraft replace Photoshop?](faq/replace-photoshop.md). + +## Start here + +- [Install PhotoCraft](getting-started/install.md) +- [Your first edit](getting-started/index.md) +- [Guides: open, adjust, select, type, export](guides/index.md) +- [Troubleshooting](troubleshooting/index.md) +- [FAQ](faq/index.md) + +## Part of the Craft App Suite + +PhotoCraft is one of the Crafting Apps from the ArtCraft team, next to VectorCraft, FilmCraft and the other Craft apps. You can install and update them from [ArtCraft Launcher](https://getartcraft.com/docs/craft-launcher). + +## Get help + +Ask in [Discord](https://discord.gg/artcraft) or open an issue in the [issue tracker](https://github.com/storytold/photocraft/issues). In PhotoCraft, **Help › Report an Issue…** opens the same issue tracker. diff --git a/docs/user/troubleshooting/get-help.md b/docs/user/troubleshooting/get-help.md new file mode 100644 index 0000000000..ee8bc860ee --- /dev/null +++ b/docs/user/troubleshooting/get-help.md @@ -0,0 +1,19 @@ +--- +title: Get help with a problem +description: How to ask for help or file a PhotoCraft bug so it can be fixed, and what to include. +order: 30 +verified: 0.8.2 +--- + +Open **Help › Report an Issue…**. It takes you to the [PhotoCraft issue tracker](https://github.com/storytold/photocraft/issues) on GitHub. You can also ask in [Discord](https://discord.gg/artcraft). + +## What to include + +1. What you did, step by step, and what you expected. +2. What happened instead. A screenshot or a short video helps. +3. Your system details. Choose **Help › System Info…**, click **Copy**, and paste the text into your message. It lists the PhotoCraft version, your operating system and processor, and your graphics adapter. +4. The file, if one file causes it. Zip a PSD or other file and attach it. Leave it out if it contains anything private. + +## Before you post + +Search the tracker for your problem first. If someone already reported it, add your details there instead of opening a new issue. For known problems, see the other pages in [Troubleshooting](index.md). diff --git a/docs/user/troubleshooting/index.md b/docs/user/troubleshooting/index.md new file mode 100644 index 0000000000..4785ae412b --- /dev/null +++ b/docs/user/troubleshooting/index.md @@ -0,0 +1,11 @@ +--- +title: Troubleshooting +description: Fixes and workarounds for known PhotoCraft problems. +order: 30 +verified: 0.8.2 +--- + +- [PhotoCraft does not start](photocraft-does-not-start.md) +- [The Windows taskbar turns black when PhotoCraft is maximized](taskbar-turns-black.md) +- [Text moves when I start editing a PSD text layer](text-moves-when-editing.md) +- [Get help with a problem](get-help.md) diff --git a/docs/user/troubleshooting/photocraft-does-not-start.md b/docs/user/troubleshooting/photocraft-does-not-start.md new file mode 100644 index 0000000000..549f6bd65d --- /dev/null +++ b/docs/user/troubleshooting/photocraft-does-not-start.md @@ -0,0 +1,58 @@ +--- +title: PhotoCraft does not start +description: PhotoCraft closes or crashes at startup on Windows PCs with Intel graphics (it uses DirectX 12 and picks a safer graphics mode after a crash) or on older Intel Macs (0.8.2 fixes one cause; no fix yet for Macs patched with OpenCore Legacy Patcher). +order: 30 +verified: 0.8.2 +--- + +On Windows, PhotoCraft starts Intel graphics on DirectX 12. If PhotoCraft closed while it was starting, start it again: it picks a safer graphics mode after a crash. On an older Intel Mac that shows a `Device(Lost)` error, update to 0.8.2, which fixes one cause; on Macs patched with OpenCore Legacy Patcher there is no fix yet. + +## Symptoms + +- Windows with Intel graphics (for example Intel UHD Graphics 630): PhotoCraft closes or crashes right after you start it. Windows Event Viewer shows an application error in `igvk64.dll` with exception `0xc0000005` ([issue 2320](https://github.com/storytold/photocraft/issues/2320), [issue 4](https://github.com/storytold/photocraft/issues/4)). +- Intel Mac: the app icon bounces in the Dock and the app disappears. Started from Terminal, it prints `Error: Wgpu(RequestDeviceError(RequestDeviceError { inner: Core(Device(Lost)) }))` ([issue 1859](https://github.com/storytold/photocraft/issues/1859)). + +## Fix + +### Windows + +1. Use PhotoCraft 0.7.0 or later. Older builds do not have the steps below. +2. Start PhotoCraft again. Double-clicking its icon or a `.pcraft` file works. PhotoCraft notes that the last start did not finish and uses the next safer graphics mode this time: + - A start on Vulkan is followed by one on DirectX 12. + - A start on DirectX 12 is followed by one on the CPU. The CPU mode does not depend on the graphics driver. +3. If it started, nothing more to do. PhotoCraft remembers the mode that worked. You can see or reset it under **Edit › Preferences › Performance…** (on macOS, **PhotoCraft › Settings › Performance…**). + +If PhotoCraft still closes on every start, force DirectX 12 from PowerShell: + +1. Open PowerShell in the folder that contains `photocraft.exe`. +2. Run these three lines: + + $env:WGPU_BACKEND = "dx12" + & .\photocraft.exe + Remove-Item Env:WGPU_BACKEND + +The last line clears the setting so later launches use the default again. You need the first two lines each time you start PhotoCraft this way. While `WGPU_BACKEND` is set, PhotoCraft uses it and does not step down to a safer mode by itself ([issue 2320](https://github.com/storytold/photocraft/issues/2320)). + +### Intel Mac + +1. Update to PhotoCraft 0.8.2 or later. On Intel Macs it skips a set of graphics checks that macOS could not compile on older Intel graphics, such as Intel Iris Pro on macOS Monterey ([issue 3107](https://github.com/storytold/photocraft/issues/3107)). +2. Start PhotoCraft again. + +If it still fails, there is no fix yet. This is the case reported on Macs patched with OpenCore Legacy Patcher, where setting `WGPU_BACKEND`, `--safe-gpu` and `PHOTOCRAFT_CPU_CANVAS=1` did not change the error ([issue 1859](https://github.com/storytold/photocraft/issues/1859)). Add your Mac model, macOS version and PhotoCraft version to that issue. + +## Why this happens + +On Windows, PhotoCraft draws with your graphics driver. Intel's Vulkan driver (`igvk64.dll`) crashed PhotoCraft on a UHD 630 PC with PhotoCraft 0.6.0, and the DirectX 12 setting above avoided the crash ([issue 2320](https://github.com/storytold/photocraft/issues/2320)). Since 0.7.0 PhotoCraft prefers DirectX 12 on Intel graphics. Before it opens the window, it writes a small file called `gpu-starting.json` in its settings folder and deletes it once the first frames are drawn. A start that crashed leaves the file behind, and the next start reads it and moves to the next safer mode. + +## Still stuck? + +See [Get help with a problem](get-help.md). Say which graphics card you have, which PhotoCraft version you use and how you started it. Add one of these: + +- If you can open PhotoCraft: the text from **Help › System Info…**. +- If PhotoCraft does not open at all: the log file `photocraft.log`, plus the faulting module and exception code from Event Viewer on Windows. PhotoCraft keeps it in a `logs` folder inside its settings folder: + - Windows: `%APPDATA%\Photocraft\logs\photocraft.log` + - macOS: `~/Library/Application Support/Photocraft/logs/photocraft.log` + - Linux: `~/.config/photocraft/logs/photocraft.log` + - Portable copy (a `portable.txt` file next to the program): the `PhotoCraftData\logs` folder next to the program. + + Every start moves the previous log to `photocraft.1.log`. If you already started PhotoCraft again after the crash, attach `photocraft.1.log` too, because it holds the run that crashed. diff --git a/docs/user/troubleshooting/taskbar-turns-black.md b/docs/user/troubleshooting/taskbar-turns-black.md new file mode 100644 index 0000000000..0c8f5b733e --- /dev/null +++ b/docs/user/troubleshooting/taskbar-turns-black.md @@ -0,0 +1,29 @@ +--- +title: The Windows taskbar turns black when PhotoCraft is maximized +description: On Windows 11, PhotoCraft 0.7.0 can turn the taskbar black or hide it when maximized. PhotoCraft 0.8.2 fixes this; update. +order: 10 +verified: 0.8.2 +--- + +Update PhotoCraft. Version 0.7.0 on Windows 11 could turn the taskbar black or hide it while the window was maximized. PhotoCraft 0.8.2 includes the fix. + +## Symptoms + +- You maximize the PhotoCraft window, or switch it to full screen, and the Windows taskbar turns completely black or is hidden. +- After you resize the window and maximize it again, a black bar the height of the taskbar stays at the bottom of the screen. + +## Fix + +1. Check your version with **Help › System Info…**, which starts with "PhotoCraft" and the version. +2. If it is older than 0.8.2, download the [latest release](https://github.com/storytold/photocraft/releases/latest) or update with [ArtCraft Launcher](https://getartcraft.com/docs/craft-launcher). See [Install PhotoCraft](../getting-started/install.md). +3. Start PhotoCraft again and maximize the window. + +A user who saw the black taskbar on 0.7.0 confirmed that it is gone in 0.8.2 ([issue 3864](https://github.com/storytold/photocraft/issues/3864)). + +## Why this happens + +PhotoCraft draws its own title bar. When such a window was maximized, Windows sized it to cover the whole screen, taskbar included, took it for a full-screen app and dropped the taskbar's background. The fix keeps a maximized PhotoCraft window clear of the taskbar ([issue 3144](https://github.com/storytold/photocraft/issues/3144), [pull request 3308](https://github.com/storytold/photocraft/pull/3308)). + +## Still stuck? + +If you still see it on 0.8.2, add your Windows version and PhotoCraft version to [issue 3864](https://github.com/storytold/photocraft/issues/3864), or ask in [Discord](https://discord.gg/artcraft). As a test, you can switch on **System title bar** under **Edit › Preferences › Interface…**, click **Apply** and restart PhotoCraft; Windows then draws the title bar. See [Get help with a problem](get-help.md) for what to include. diff --git a/docs/user/troubleshooting/text-moves-when-editing.md b/docs/user/troubleshooting/text-moves-when-editing.md new file mode 100644 index 0000000000..7130c8c7cf --- /dev/null +++ b/docs/user/troubleshooting/text-moves-when-editing.md @@ -0,0 +1,29 @@ +--- +title: Text moves when I start editing a PSD text layer +description: In PhotoCraft 0.7.0, a text layer from a Photoshop file can jump when you click it with the Type tool. PhotoCraft 0.8.2 fixes the known causes; update. +order: 20 +verified: 0.8.2 +--- + +Update PhotoCraft. In version 0.7.0, a text layer from a Photoshop file could jump or disappear when you started editing it. PhotoCraft 0.8.2 reads the text's styles and position the way Photoshop saved them, so the text stays where it was. + +## Symptoms + +- You open a PSD that was made in Photoshop and click one of its text layers with the **Horizontal Type Tool**. The text shifts, often to the left, as soon as editing starts. +- Centered text may show as left-aligned in the options bar. +- In some files, text that you click can disappear. + +## Fix + +1. Check your version with **Help › System Info…**. If it is older than 0.8.2, download the [latest release](https://github.com/storytold/photocraft/releases/latest) or update with [ArtCraft Launcher](https://getartcraft.com/docs/craft-launcher). +2. Open the PSD again and click the text layer with the **Horizontal Type Tool**. + +If you already saved the file in 0.7.0 after the text moved, the moved text is now in the file. Go back to your original PSD if you still have it. + +## Why this happens + +Clicking a PSD text layer with the Type tool starts editing it, and PhotoCraft then lays the text out itself instead of showing the pixels Photoshop saved. PhotoCraft 0.7.0 read the alignment and size of each run of text only from Photoshop's default styles, and ignored part of the text position that recent Photoshop versions store. Both are fixed in 0.8.2 ([issue 3795](https://github.com/storytold/photocraft/issues/3795), [pull request 3819](https://github.com/storytold/photocraft/pull/3819)). + +## Still stuck? + +If text still moves in 0.8.2, keep a copy of the original with **File › Save a Copy…**, then report it in the [issue tracker](https://github.com/storytold/photocraft/issues) with the PSD (zipped) and the Photoshop version that saved it. You can also ask in [Discord](https://discord.gg/artcraft). See [Get help with a problem](get-help.md). diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index 43d0eeef7d..b0c58d9d31 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -53,6 +53,16 @@ integrate() { break fi done + # AM / AppMan (#6392) install their own launcher, whose Exec runs a command on + # PATH rather than this AppImage, so the check above misses it. AM's author + # names the only two places it writes one: system-wide for AM, per user for + # AppMan and rootless installs. + for f in /usr/local/share/applications/photocraft-AM.desktop "$apps/photocraft-AM.desktop"; do + if [ -f "$f" ]; then + external=1 + break + fi + done if [ "$external" = 1 ]; then if [ -f "$apps/$DESK_ID.desktop" ]; then rm -f "$apps/$DESK_ID.desktop" 2>/dev/null || true diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index 8c9e33e6bd..18f920560b 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -129,4 +129,27 @@ out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exi [ "$out" = "stub: x" ] || fail "odd path: $out" [ ! -e "$XDG_DATA_HOME" ] || fail "integrated an AppImage path that needs escaping" +# 12. AM / AppMan (#6392): a photocraft-AM.desktop launcher in the user's applications +# dir owns the menu entry. AppRun removes its own entry left from an earlier run, +# writes no second one and still installs the icons. +rm -rf "$XDG_DATA_HOME" +"$APPDIR/AppRun" >/dev/null || fail "launch before AM install exited non-zero" +[ -f "$DESKTOP" ] || fail "no desktop entry before AM install" +am_desktop="$XDG_DATA_HOME/applications/photocraft-AM.desktop" +printf '[Desktop Entry] +Type=Application +Name=PhotoCraft +Exec=photocraft %%F +Icon=%s +' "$APP_ID" >"$am_desktop" +"$APPDIR/AppRun" >/dev/null || fail "launch with AM launcher exited non-zero" +[ ! -e "$DESKTOP" ] || fail "duplicate desktop entry kept alongside AM launcher (#6392)" +[ -f "$am_desktop" ] || fail "AM launcher was removed" +[ -f "$XDG_DATA_HOME/icons/hicolor/256x256/apps/$APP_ID.png" ] || fail "icons missing with AM launcher" + +# 13. Once AM removes its launcher, AppRun writes its own entry again. +rm -f "$am_desktop" +"$APPDIR/AppRun" >/dev/null || fail "launch after AM removal exited non-zero" +[ -f "$DESKTOP" ] || fail "no desktop entry after the AM launcher was removed" + echo "AppRun desktop integration ok" diff --git a/packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml index 0b771ae7c7..c7d30ac7d3 100644 --- a/packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml @@ -24,6 +24,9 @@ finish-args: - --share=ipc # GPU access for the wgpu compositor (Vulkan, or GL as a fallback). - --device=dri + # Printing: the host's CUPS socket, so File › Print reaches the print server directly (IPP, + # in process). Without it the app shows the system print dialog through the print portal. + - --socket=cups # Open/Save dialogs go through the file-chooser portal (rfd's xdg-portal backend) and # drag-and-drop through the document portal, so picked files work anywhere without broad # filesystem access. Pictures and Documents are granted so files passed by path (the command diff --git a/packaging/linux/flatpak/ai.storyteller.photocraft.yml b/packaging/linux/flatpak/ai.storyteller.photocraft.yml index ee6bbfac1b..e3ac74cffd 100644 --- a/packaging/linux/flatpak/ai.storyteller.photocraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.photocraft.yml @@ -25,6 +25,9 @@ finish-args: - --share=ipc # GPU access for the wgpu compositor (Vulkan, or GL as a fallback). - --device=dri + # Printing: the host's CUPS socket, so File › Print reaches the print server directly (IPP, + # in process). Without it the app shows the system print dialog through the print portal. + - --socket=cups # Open/Save dialogs go through the file-chooser portal (rfd's xdg-portal backend) and # drag-and-drop through the document portal, so picked files work anywhere without broad # filesystem access. Pictures and Documents are granted so files passed by path (the command diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index d325b2b9d6..b3cde0ea1c 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -71,7 +71,7 @@ NSHumanReadableCopyright Copyright © the PhotoCraft authors. MIT OR Apache-2.0. - + UTExportedTypeDeclarations diff --git a/packaging/macos/entitlements.plist b/packaging/macos/entitlements.plist index 05e3194d84..c32269c1d3 100644 --- a/packaging/macos/entitlements.plist +++ b/packaging/macos/entitlements.plist @@ -1,6 +1,6 @@ - diff --git a/packaging/windows/portable.txt b/packaging/windows/portable.txt index 9372e88b71..853874bc2c 100644 --- a/packaging/windows/portable.txt +++ b/packaging/windows/portable.txt @@ -2,8 +2,8 @@ PhotoCraft portable mode While this file sits next to photocraft.exe, PhotoCraft keeps its preferences, brush presets, crash-recovery autosaves and startup state in the PhotoCraftData folder beside it, and writes -nothing to %APPDATA%. Copy the whole folder to move PhotoCraft with its settings. +nothing to %APPDATA% or %LOCALAPPDATA%. Copy the whole folder to move PhotoCraft with its settings. -Delete this file to use the normal per-user settings folder (%APPDATA%\Photocraft) instead. -If PhotoCraftData can't be written (for example on a read-only drive), PhotoCraft says so and -uses %APPDATA%\Photocraft instead. +Delete this file to use the normal per-user folders instead: %APPDATA%\Photocraft for settings +and %LOCALAPPDATA%\Photocraft\Recovery for crash-recovery autosaves. If PhotoCraftData can't be +written (for example on a read-only drive), PhotoCraft says so and uses those folders instead. diff --git a/scorecard/ui.toml b/scorecard/ui.toml index 4ac0ce6386..7eff90c3ca 100644 --- a/scorecard/ui.toml +++ b/scorecard/ui.toml @@ -59,7 +59,7 @@ id = "UI-217-8" target = "Tool-specific canvas right-click menu; right-click spelling suggestions in text fields" status = "partial" issue = 217 -note = "paint_mouse.rs brush picker and canvas_tool_menu.rs selection actions; text_field_menu.rs gives every text field its right-click Undo/Cut/Copy/Paste/Delete/Select All menu (#2921); other tools missing; the Type tool's edit menu starts with spelling suggestions and Add to Dictionary over a misspelled word (#4370); Ignore / Ignore All, suggestions in the non-editing type menu and in generic text fields are not there yet" +note = "paint_mouse.rs brush picker and canvas_tool_menu.rs selection actions; text_field_menu.rs gives every text field its right-click Undo/Cut/Copy/Paste/Delete/Select All menu (#2921); other tools missing; the Type tool's edit menu starts with spelling suggestions and Add to Dictionary over a misspelled word (#4370); over committed type the Type tool opens the type layer menu (#7324); Ignore / Ignore All, suggestions in the non-editing type menu and in generic text fields are not there yet" [[item]] id = "UI-217-9" @@ -164,4 +164,4 @@ id = "UI-217-23" target = "Layer clipboard: copy/paste whole layers (masks, styles, type) between documents" status = "partial" issue = 217 -note = "layer.copyToDocument copies layers into another open document keeping names, content, masks, styles and blending, converting to the destination's profile and depth, as one history step (layer_copy_cmds.rs, #589). It is the command a drag between documents dispatches; there is still no copy/paste layer clipboard" +note = "Edit › Copy with no pixel selection takes layers whole and Paste recreates them in this or another open document, converted to its profile and depth, as one history step (edit_cmds.rs takes_whole, paste_layers): smart objects (#2428), type, shape and group layers (#2670), fill and adjustment layers (#2344), and several selected layers with their masks and styles (#2478). layer.copyToDocument is the drag between documents (layer_copy_cmds.rs, #589). Missing: a single pixel layer copies its pixels only, leaving its mask and styles behind" diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index ce34e8c25a..f2e6f53514 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -41,6 +41,8 @@ pub const TABLE: &[(&str, Class)] = &[ ("codecs", Class::Standalone), // Optional HEIF/HEIC decoder (heic-rs), used only by `codecs` behind its `heif` feature. ("heif", Class::Standalone), + // IPP client for CUPS printing (pure Rust, no dependencies), used by `engine` on Unix. + ("ipp", Class::Standalone), ("raw", Class::Standalone), ("affinity", Class::Standalone), ("adobe-assets", Class::Standalone), @@ -200,11 +202,8 @@ pub fn check(crates: &[Crate]) -> Vec { match classify(&d.name) { // Unregistered deps are reported on their own entry. None => {} - Some(Class::Testkit) => { - if d.kind != DepKind::Dev { - out.push(Violation::TestkitAsNormalDep { krate: c.name.clone() }); - } - } + Some(Class::Testkit) if d.kind != DepKind::Dev => out.push(Violation::TestkitAsNormalDep { krate: c.name.clone() }), + Some(Class::Testkit) => {} Some(dc) => { let to = dc.layer().unwrap_or(u8::MAX); if to >= layer && !(to == layer && intra_layer_allowed(&c.name, &d.name)) { diff --git a/xtask/src/perf.rs b/xtask/src/perf.rs index d2a3a75b85..3e49514c1c 100644 --- a/xtask/src/perf.rs +++ b/xtask/src/perf.rs @@ -168,6 +168,9 @@ pub fn parse_budgets(text: &str) -> Result { if !(b.settings.regression_pct.is_finite() && b.settings.regression_pct > 0.0) { return Err(format!("{BUDGETS}: settings.regression_pct must be > 0")); } + if !(b.settings.regression_min_ms.is_finite() && b.settings.regression_min_ms >= 0.0) { + return Err(format!("{BUDGETS}: settings.regression_min_ms must be finite and >= 0")); + } Ok(b) } @@ -980,6 +983,8 @@ not_measurable = "needs a frame harness" .is_err() ); assert!(parse_budgets("[settings]\nregression_pct = 0\n").is_err()); + assert!(parse_budgets("[settings]\nregression_min_ms = -1\n").is_err()); + assert!(parse_budgets("[settings]\nregression_min_ms = 0\n").is_ok()); assert!(parse_budgets("bogus = 1\n").is_err()); assert!(parse_budgets("not toml [").is_err()); }