diff --git a/.github/workflows/notify-services.yml b/.github/workflows/notify-services.yml new file mode 100644 index 0000000000..3dc8eaf4ac --- /dev/null +++ b/.github/workflows/notify-services.yml @@ -0,0 +1,20 @@ +name: Notify Services on Release Change + +on: + release: + types: + - published + - unpublished + - created + - edited + - deleted + - prereleased + - released + +permissions: {} + +jobs: + notify: + uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main + secrets: + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} diff --git a/AGENTS.md b/AGENTS.md index a92f36f12f..490b9f8905 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,6 +87,7 @@ cargo xtask test-corpus # psd, io, codecs, compose, gpu, text, format Conventions and paths: - `unsafe` is allowed only in `crates/tablet/src/macos.rs` and `windows.rs`; the workspace sets `unsafe_code = "forbid"`. The example plug-in in `examples/plugins/` is outside the workspace and uses `unsafe` for the WebAssembly host calls. Every new crate sets `[lints] workspace = true`. +- Parity headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog item `headless: yes` only when `photocraft_engine::commands::find` has its id, the registry `photocraft-cli` and the MCP server load. Panel toggles, workspaces and tool shortcuts that are live only in the desktop app are `no` (window). Other ids take a `no`/`partial` mark with a `window`, `os` or `engine-gap` reach from `HEADLESS` in `crates/ui-egui/src/menus/parity.rs`, or read `unknown`. Never write `yes` there; stale marks fail `headless_marks_are_current`. - Attribution file: `ATTRIBUTION.md`. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (`docs/development.md` > Fonts). - Test corpora: storytold/photocraft-corpus, fetched into `corpus/` by `cargo xtask corpus --all` at the pins in `xtask/src/corpus_pins.rs`. `cargo xtask test-corpus` runs each directory's fixed sample; `PHOTOCRAFT_FULL_SWEEP=1` runs every file (CI: samples on pull requests and main, every file nightly). - Feature names are recorded in `docs/feature-names.md`. diff --git a/Cargo.lock b/Cargo.lock index 701a3199cf..0173d81543 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-automation", "craft-behavior", @@ -1406,7 +1406,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "crc32fast", "flate2", @@ -1427,7 +1427,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1438,7 +1438,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "rustix 1.1.6", ] @@ -1446,7 +1446,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1471,7 +1471,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1489,7 +1489,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-docpath", @@ -1507,7 +1507,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "egui", ] @@ -1515,7 +1515,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "md-5", "rayon", @@ -1524,12 +1524,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "serde", ] @@ -1537,7 +1537,7 @@ dependencies = [ [[package]] name = "craft-color-transform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-cms", "craft-color", @@ -1547,7 +1547,7 @@ dependencies = [ [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-cms", @@ -1567,10 +1567,11 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-ai-agents", "craft-atomic", + "craft-control-protocol", "craft-flags", "craft-platform", "dirs", @@ -1580,10 +1581,19 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-control-protocol" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" +dependencies = [ + "serde_json", + "subtle", +] + [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-metadata", "craft-xml", @@ -1593,7 +1603,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "thiserror 2.0.21", ] @@ -1601,7 +1611,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "rayon", ] @@ -1609,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-develop" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-color", "craft-color-transform", @@ -1624,7 +1634,7 @@ dependencies = [ [[package]] name = "craft-develop-model" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-geom", "craft-metadata", @@ -1636,7 +1646,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1662,7 +1672,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "serde", ] @@ -1670,7 +1680,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1689,12 +1699,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-eps", "craft-idml", @@ -1712,7 +1722,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-atomic", "dirs", @@ -1722,7 +1732,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1737,7 +1747,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1757,7 +1767,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1766,7 +1776,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "cap-primitives", "craft-atomic", @@ -1789,12 +1799,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" [[package]] name = "craft-geom" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "serde", ] @@ -1802,7 +1812,7 @@ dependencies = [ [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "heic-rs", "rayon", @@ -1811,7 +1821,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1824,7 +1834,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "chrono", "fixed_decimal", @@ -1852,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-xml", "craft-zip", @@ -1862,7 +1872,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-dds", "craft-heif", @@ -1890,7 +1900,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1908,12 +1918,12 @@ dependencies = [ [[package]] name = "craft-ipp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "thiserror 2.0.21", ] @@ -1921,7 +1931,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-host", "craft-i18n", @@ -1936,7 +1946,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-xml", "craft-zip", @@ -1946,7 +1956,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-i18n", @@ -1960,7 +1970,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-host", @@ -1978,7 +1988,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1990,7 +2000,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-xml", "craft-zip", @@ -2000,7 +2010,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-keymap", @@ -2016,7 +2026,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "blake3", "craft-atomic", @@ -2029,7 +2039,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "flate2", "serde", @@ -2040,7 +2050,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "bytemuck", "flate2", @@ -2055,7 +2065,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2064,7 +2074,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "async-channel", "async-io", @@ -2095,7 +2105,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "thiserror 2.0.21", ] @@ -2103,7 +2113,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-host", @@ -2127,7 +2137,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "encoding_rs", "flate2", @@ -2138,7 +2148,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "dispatch2", "egui", @@ -2151,7 +2161,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "chrono", "craft-crw", @@ -2169,7 +2179,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2188,7 +2198,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-atomic", "craft-host", @@ -2205,7 +2215,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2226,7 +2236,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-keymap", @@ -2238,12 +2248,15 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" +dependencies = [ + "rustix 1.1.6", +] [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2266,7 +2279,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2281,7 +2294,7 @@ dependencies = [ [[package]] name = "craft-theme-editor" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-theme", @@ -2292,7 +2305,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-atomic", "craft-behavior", @@ -2307,7 +2320,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "serde", "thiserror 2.0.21", @@ -2317,7 +2330,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "serde", "thiserror 2.0.21", @@ -2326,7 +2339,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-keymap", @@ -2341,7 +2354,7 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "serde", ] @@ -2349,7 +2362,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2363,7 +2376,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-i18n", @@ -2379,7 +2392,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "accesskit", "craft-behavior", @@ -2421,7 +2434,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2432,7 +2445,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-host", @@ -2450,7 +2463,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-host", @@ -2471,7 +2484,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-host", @@ -2491,7 +2504,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-behavior", "craft-host", @@ -2510,13 +2523,15 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ + "base64 0.22.1", "chrono", "craft-host", "craft-theme", "craft-ui", "dunce", + "ed25519-dalek", "egui", "flate2", "image", @@ -2529,6 +2544,7 @@ dependencies = [ "sha2 0.10.9", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", @@ -2539,7 +2555,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "winsafe", ] @@ -2547,7 +2563,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "craft-appkit", "craft-atomic", @@ -2579,7 +2595,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2588,7 +2604,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2598,7 +2614,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2724,6 +2740,33 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "darling" version = "0.24.1" @@ -2988,17 +3031,41 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "emath", "serde", ] +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -3035,7 +3102,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit", "ahash", @@ -3056,7 +3123,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -3075,7 +3142,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit_winit", "arboard", @@ -3101,7 +3168,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "egui", @@ -3115,7 +3182,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "egui", @@ -3128,7 +3195,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "dify", "eframe", @@ -3154,7 +3221,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "serde", @@ -3247,7 +3314,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -3274,7 +3341,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[package]] name = "equivalent" @@ -3388,6 +3455,12 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "filetime" version = "0.2.29" @@ -4061,7 +4134,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "bytemuck", "hayro-interpret", @@ -4091,7 +4164,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4109,7 +4182,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4133,7 +4206,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "flate2", "hayro-ccitt", @@ -4844,9 +4917,9 @@ dependencies = [ [[package]] name = "jpeg-encoder" -version = "0.6.1" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" +checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6" [[package]] name = "js-sys" @@ -5226,7 +5299,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -7146,6 +7219,16 @@ dependencies = [ "system-deps", ] +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -7527,6 +7610,9 @@ name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] [[package]] name = "rand_core" @@ -9266,9 +9352,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.2.1+spec-1.1.0" +version = "1.1.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ "indexmap", "serde_core", @@ -9722,7 +9808,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "bytemuck", "fearless_simd", @@ -9770,7 +9856,7 @@ dependencies = [ [[package]] name = "vello_cpu" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" dependencies = [ "bytemuck", "glifo 0.1.1", @@ -10707,7 +10793,7 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=f8b490f135ea439dd31aae100bb5591c63cb076f#f8b490f135ea439dd31aae100bb5591c63cb076f" dependencies = [ "ahash", "android-activity", @@ -11401,29 +11487,29 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=a46af76c7c74dd8dd375d694baaef00d5ae836a2#a46af76c7c74dd8dd375d694baaef00d5ae836a2" +source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#3eb5b528b08211844bc5c95c5a4fd169894d52ff" diff --git a/Cargo.toml b/Cargo.toml index f888fb6da9..fdbd10ef88 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,21 +12,21 @@ rust-version = "1.95" [workspace.dependencies] # The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match # `craft::egui_fork::REV` (checked by `cargo xtask ci`). -craft = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", default-features = false } -craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff", default-features = false } +craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -48,36 +48,36 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } # Keep the shared embedded-image validation API until the framework revision includes it. -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff", features = ["ui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -350,28 +350,28 @@ opt-level = 3 # Keep the complete egui family and native event bridge on reviewed fork commits. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -vello_common = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +vello_common = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +winit = { git = "https://github.com/storytold/winit.git", rev = "f8b490f135ea439dd31aae100bb5591c63cb076f" } diff --git a/apps/photocraft-cli/build.rs b/apps/photocraft-cli/build.rs index 8983b9c8d6..c1e78c550a 100644 --- a/apps/photocraft-cli/build.rs +++ b/apps/photocraft-cli/build.rs @@ -1,15 +1,21 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `photocraft-cli.exe`. +//! Records the checkout's git commit for `--version` (`git_checkout.rs`, every target), and on +//! Windows only embeds the app icon and version info (VERSIONINFO) into `photocraft-cli.exe`. //! -//! On every other target this does nothing, even when `PHOTOCRAFT_REQUIRE_WINRES` is set. A +//! On every other target the Windows part does nothing, even when `PHOTOCRAFT_REQUIRE_WINRES` is set. A //! missing resource compiler is a warning, so a cross-compile from macOS or Linux still links, //! unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the release packaging script) turns it into a //! build error. +#[path = "../photocraft/git_checkout.rs"] +mod git_checkout; + /// Embeds the Windows resources and delay-loads the print-only system DLLs (#8272). fn main() -> std::io::Result<()> { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-changed=../photocraft/git_checkout.rs"); + git_checkout::emit(); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return Ok(()); } diff --git a/apps/photocraft-cli/src/main.rs b/apps/photocraft-cli/src/main.rs index 6e21c2ac44..5113c2c04a 100644 --- a/apps/photocraft-cli/src/main.rs +++ b/apps/photocraft-cli/src/main.rs @@ -3,6 +3,9 @@ fn main() { // May re-execute this process with glibc tuned to return freed document memory (#8743). photocraft_engine::malloc_tuning::apply(); + // The git commit of a dev build's checkout, for `--version` (build.rs, #5247). Before `run`: + // clap reads the version string once. + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); // `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must reach clap, // not panic before anything is printed (issue #1108). let code = photocraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index a4bcba0756..f49abe6a17 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -1,9 +1,12 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `photocraft.exe`. +//! Records the checkout's git commit for `--version` (`git_checkout.rs`, every target), and on +//! Windows only embeds the app icon and version info (VERSIONINFO) into `photocraft.exe`. //! -//! On every other target this does nothing. A missing resource compiler is a warning, so a +//! On every other target the Windows part does nothing. A missing resource compiler is a warning, so a //! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the //! release workflow) turns it into an error. +mod git_checkout; + #[path = "src/build_channel.rs"] mod build_channel; @@ -27,6 +30,8 @@ fn main() { println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft-nightly.ico"); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-changed=git_checkout.rs"); + git_checkout::emit(); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_VERSION"); let built_version = if nightly { match std::env::var("PHOTOCRAFT_VERSION") { diff --git a/apps/photocraft/git_checkout.rs b/apps/photocraft/git_checkout.rs new file mode 100644 index 0000000000..38cfa185ec --- /dev/null +++ b/apps/photocraft/git_checkout.rs @@ -0,0 +1,71 @@ +//! Build-script helper shared by the `photocraft` and `photocraft-cli` binaries: the git commit +//! of the source checkout, so a plain `cargo build` from git reports `0.8.2 (dev build, 6f8505421)` +//! (#5247). Release builds set `PHOTOCRAFT_BUILD_SHA` instead and are left alone; without git or +//! outside a checkout of this workspace (a source tarball) nothing is set and the build stays +//! `(dev build)`. The binaries pass the value to `photocraft_engine::build_info::set_checkout`. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Runs `git ` in `dir`; its trimmed output when it succeeds. +fn git(dir: &Path, args: &[&str]) -> Option { + let out = Command::new("git").arg("-C").arg(dir).args(args).output().ok()?; + let s = String::from_utf8(out.stdout).ok()?.trim().to_string(); + (out.status.success() && !s.is_empty()).then_some(s) +} + +/// Emits `PHOTOCRAFT_CHECKOUT_SHA` for the crate whose build script calls it. +pub fn emit() { + println!("cargo:rerun-if-env-changed=PHOTOCRAFT_BUILD_SHA"); + if std::env::var("PHOTOCRAFT_BUILD_SHA").is_ok_and(|s| !s.trim().is_empty()) { + return; + } + let Some(manifest) = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) else { return }; + // apps/ → the workspace root. A tarball unpacked inside some other repository must not + // report that repository's commit. + let Some(root) = manifest.parent().and_then(Path::parent).and_then(|r| r.canonicalize().ok()) else { return }; + let Some(top) = git(&root, &["rev-parse", "--show-toplevel"]).and_then(|t| PathBuf::from(t).canonicalize().ok()) else { return }; + if top != root { + return; + } + // Watch before asking for the commit: on an unborn branch `rev-parse HEAD` fails, and the + // first commit must still re-run this script. + for path in watch_paths(&root) { + println!("cargo:rerun-if-changed={}", path.display()); + } + let Some(sha) = git(&root, &["rev-parse", "HEAD"]) else { return }; + println!("cargo:rustc-env=PHOTOCRAFT_CHECKOUT_SHA={sha}"); +} + +/// The git files whose change means HEAD moved: a commit or checkout changes HEAD (detached) or the +/// branch's ref. Cargo treats a watched path that does not exist as always changed (it re-runs the +/// build script and recompiles the binary on every build), so only existing paths are returned. +pub(crate) fn watch_paths(root: &Path) -> Vec { + let mut paths = Vec::new(); + if let Some(dir) = git(root, &["rev-parse", "--absolute-git-dir"]) { + let head = Path::new(&dir).join("HEAD"); + paths.extend(watched(&head, &head)); + } + let Some(common) = git(root, &["rev-parse", "--path-format=absolute", "--git-common-dir"]) else { return paths }; + let common = Path::new(&common); + if git(root, &["rev-parse", "--show-ref-format"]).as_deref() == Some("reftable") { + // Every ref update in a reftable repository rewrites the table stack. + let tables = common.join("reftable").join("tables.list"); + paths.extend(watched(&tables, &tables)); + return paths; + } + if let Some(head_ref) = git(root, &["symbolic-ref", "-q", "HEAD"]) { + // A packed or unborn branch has no loose ref file; the first commit on it creates one, + // which changes the nearest existing directory above it under `refs/`. + paths.extend(watched(&common.join(&head_ref), &common.join("refs"))); + } + let packed = common.join("packed-refs"); + paths.extend(watched(&packed, &packed)); + paths +} + +/// The path Cargo should watch for `path`: `path` itself when it exists, else its nearest existing +/// ancestor that is still inside `stop`; `None` when neither exists. +pub(crate) fn watched(path: &Path, stop: &Path) -> Option { + path.ancestors().take_while(|p| p.starts_with(stop)).find(|p| p.exists()).map(Path::to_path_buf) +} diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 85f44aa191..b8e0a15926 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -495,6 +495,8 @@ fn main() -> eframe::Result { // Before anything starts a thread: may re-execute this process with glibc tuned to return // the memory of closed documents (#8743). photocraft_engine::malloc_tuning::apply(); + // The git commit of a dev build's checkout, for `--version` and About (build.rs, #5247). + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); // Then, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); crash_guard::install_hook(); diff --git a/apps/photocraft/tests/it/command_line_usage.rs b/apps/photocraft/tests/it/command_line_usage.rs index a0d8377638..116e1440c8 100644 --- a/apps/photocraft/tests/it/command_line_usage.rs +++ b/apps/photocraft/tests/it/command_line_usage.rs @@ -88,6 +88,9 @@ fn help_wins_over_later_arguments() { fn version_prints_the_long_version() { let Run { status, stdout, .. } = run_photocraft(&["--version", "--safegpu"]); assert_eq!(status.code(), Some(0)); + // The binary records its checkout's commit at startup (#5247); the build script hands the + // same value to this test. + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); assert_eq!(stdout, format!("photocraft {}\n", photocraft_engine::build_info::long_version())); } diff --git a/apps/photocraft/tests/it/git_checkout.rs b/apps/photocraft/tests/it/git_checkout.rs new file mode 100644 index 0000000000..8b05503e78 --- /dev/null +++ b/apps/photocraft/tests/it/git_checkout.rs @@ -0,0 +1,152 @@ +//! The build-script helper `git_checkout.rs` (#5247): Cargo re-runs a build script on every build +//! when a `rerun-if-changed` path is missing, so only existing paths may be watched. + +#[allow(dead_code)] +#[path = "../../git_checkout.rs"] +mod helper; + +use helper::{watch_paths, watched}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("photocraft-git-checkout-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("scratch dir"); + dir +} + +#[test] +fn an_existing_path_is_watched_itself() { + let git = scratch("exists"); + let packed = git.join("packed-refs"); + fs::write(&packed, "").expect("write"); + assert_eq!(watched(&packed, &packed), Some(packed.clone())); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn a_missing_file_with_no_room_to_climb_is_not_watched() { + let git = scratch("missing"); + let packed = git.join("packed-refs"); + assert_eq!(watched(&packed, &packed), None); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn a_packed_branch_watches_the_nearest_existing_ref_directory() { + let git = scratch("packed-branch"); + let refs = git.join("refs"); + fs::create_dir_all(refs.join("heads")).expect("refs/heads"); + // `refs/heads/fix/5247` with no `fix/` directory yet: watch `refs/heads`. + assert_eq!(watched(&refs.join("heads/fix/5247"), &refs), Some(refs.join("heads"))); + // Once the loose ref exists it is watched directly. + fs::create_dir_all(refs.join("heads/fix")).expect("refs/heads/fix"); + fs::write(refs.join("heads/fix/5247"), "abc\n").expect("loose ref"); + assert_eq!(watched(&refs.join("heads/fix/5247"), &refs), Some(refs.join("heads/fix/5247"))); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn the_search_never_leaves_the_stop_directory() { + let git = scratch("stop"); + // `refs/` itself is missing: its parent (the git dir) exists but is outside `stop`. + assert_eq!(watched(&git.join("refs/heads/main"), &git.join("refs")), None); + let _ = fs::remove_dir_all(&git); +} + +/// `git` with the variables that point it at another repository or pick its ref format removed, +/// so a fixture is the repository in its own directory whatever the environment says. +fn git() -> Command { + let mut c = Command::new("git"); + for var in ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_DEFAULT_REF_FORMAT"] { + c.env_remove(var); + } + c +} + +/// `git init` in a fresh scratch directory with `args`; `None` when this git cannot do it. The +/// files ref format unless `args` ask for another, whatever `init.defaultRefFormat` says (older +/// git ignores the setting). +fn init(name: &str, args: &[&str]) -> Option { + let dir = scratch(name); + let mut cmd = git(); + if !args.iter().any(|a| a.starts_with("--ref-format")) { + cmd.args(["-c", "init.defaultRefFormat=files"]); + } + let ok = cmd.arg("init").arg("-q").args(args).arg(&dir).status().is_ok_and(|s| s.success()); + if ok { + dir.canonicalize().ok() + } else { + let _ = fs::remove_dir_all(&dir); + None + } +} + +fn git_dir(root: &Path) -> PathBuf { + root.join(".git") +} + +/// `watch_paths(root)` canonicalised, so git's `C:/…` output compares equal to the scratch path on +/// Windows and `/var` to `/private/var` on macOS. Panics if any watched path is missing. +fn watched_in(root: &Path) -> Vec { + watch_paths(root).iter().map(|p| p.canonicalize().unwrap_or_else(|e| panic!("{} is watched but missing: {e}", p.display()))).collect() +} + +#[test] +fn an_unborn_branch_still_watches_head_and_the_ref_directory() { + // Before the first commit `rev-parse HEAD` fails; the first commit creates refs/heads/main, + // which must re-run the build script. + let Some(root) = init("unborn", &["-b", "main"]) else { + eprintln!("git init unavailable, skipped"); + return; + }; + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("HEAD")), "{paths:?}"); + assert!(paths.iter().any(|p| p.starts_with(git.join("refs"))), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn a_reftable_checkout_watches_the_table_stack() { + // Branch updates in a reftable repository rewrite reftable/tables.list, not a loose ref or + // packed-refs. Needs git 2.45 or newer; older git cannot create the repository. + let Some(root) = init("reftable", &["-b", "main", "--ref-format=reftable"]) else { + eprintln!("git without reftable support, skipped"); + return; + }; + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("reftable").join("tables.list")), "{paths:?}"); + assert!(paths.contains(&git.join("HEAD")), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn a_files_checkout_watches_the_branch_ref_and_not_a_table_stack() { + let Some(root) = init("files", &["-b", "main"]) else { + eprintln!("git init unavailable, skipped"); + return; + }; + fs::write(git_dir(&root).join("packed-refs"), "").expect("packed-refs"); + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("packed-refs")), "{paths:?}"); + assert!(!paths.iter().any(|p| p.starts_with(git.join("reftable"))), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn outside_a_repository_nothing_is_watched() { + let dir = scratch("no-repo"); + // GIT_CEILING_DIRECTORIES is not set here, so a scratch dir inside a checkout would find it; + // the system temp dir is not inside one on CI or on a developer machine. + if git().arg("-C").arg(&dir).args(["rev-parse", "--git-dir"]).output().is_ok_and(|o| o.status.success()) { + eprintln!("temp dir is inside a git repository, skipped"); + } else { + assert!(watched_in(&dir).is_empty()); + } + let _ = fs::remove_dir_all(&dir); +} diff --git a/apps/photocraft/tests/it/main.rs b/apps/photocraft/tests/it/main.rs index 73bea9196a..f0248ad210 100644 --- a/apps/photocraft/tests/it/main.rs +++ b/apps/photocraft/tests/it/main.rs @@ -2,6 +2,7 @@ mod command_line_usage; mod control_exit_code; +mod git_checkout; mod startup_without_display; /// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid. diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 7053158613..4164e43cdf 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -270,3 +270,5 @@ mod satin_size_one_tests; #[cfg(test)] mod inner_glow_size_one_tests; +#[cfg(test)] +mod stroke_partial_alpha_tests; diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index 3d638c8a4e..f7f82fce13 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -1,5 +1,5 @@ use super::bevel::{BevelPaint, TextureCtx, bevel_geom, bevel_maps, satin_map}; -use super::distance::{INSIDE_EPS, Metric, dist_inside_by, dist_outside_by, local_coverage, stroke_outside_exact}; +use super::distance::{INSIDE_EPS, Metric, dist_outside_by, local_coverage, stroke_inside_distance, stroke_outside_exact}; use super::paint::{dissolves_in, glow_map, paint_color, paint_fx, paint_glow, paint_pattern, rgb, shadow_map}; use super::{ Bevel, BevelStyle, BlendMode, Buffer, Effect, FxMaps, FxPaint, GlobalLight, Layer, MAX_REACH, Map, PREPARED_PATTERN_BYTES, Pattern, Placement, @@ -110,7 +110,7 @@ pub(crate) fn build_maps_prepared( let exact_out = out_widths.iter().any(|&w| stroke_outside_exact(w)); let (din, dout, dout_exact) = if has_stroke { ( - Some(dist_inside_by(&shape, Metric::Chamfer)), + Some(stroke_inside_distance(&shape, matches!(layer.content, photocraft_doc::LayerContent::Raster(_)))), chamfer_out.then(|| dist_outside_by(&shape, Metric::Chamfer)), exact_out.then(|| dist_outside_by(&shape, Metric::Euclidean)), ) @@ -185,7 +185,7 @@ pub fn premerges_layer(layer: &Layer) -> bool { /// compositor paints them. The shape Stroke Emboss bevels (#8639). fn stroke_band(shape: &Map, st: &photocraft_doc::StrokeFx) -> Map { let (in_w, out_w) = stroke_widths(st); - let din = (in_w > 0.0).then(|| dist_inside_by(shape, Metric::Chamfer)); + let din = (in_w > 0.0).then(|| stroke_inside_distance(shape, false)); let metric = if stroke_outside_exact(out_w) { Metric::Euclidean } else { Metric::Chamfer }; let dout = (out_w > 0.0).then(|| dist_outside_by(shape, metric)); let mut band = Map::new(shape.w, shape.h, 0.0); @@ -318,6 +318,30 @@ fn inside(a: f32) -> bool { a > INSIDE_EPS } +/// Coverage of an inside stroke before the layer applies its own alpha. +#[inline] +fn inside_stroke_coverage(alpha: f32, distance: f32, limit: f32) -> f32 { + if inside(alpha) { (limit - distance).clamp(0.0, 1.0) } else { 0.0 } +} + +/// A Normal stroke replaces the layer beneath its band by coverage, then adds its own paint. +#[inline] +fn replace_under_stroke(pixel: &mut [f32; 4], paint: [f32; 4], coverage: f32) { + if paint[3] <= 0.0 { + return; + } + let kept = pixel[3] * (1.0 - coverage.clamp(0.0, 1.0)); + let alpha = kept + paint[3]; + if alpha > 0.0 { + *pixel = [ + (pixel[0] * kept + paint[0] * paint[3]) / alpha, + (pixel[1] * kept + paint[1] * paint[3]) / alpha, + (pixel[2] * kept + paint[2] * paint[3]) / alpha, + alpha.min(1.0), + ]; + } +} + /// An effect map as a fraction of the shape's own coverage. fn relative_to_shape(m: Map, shape: &Map) -> Map { let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect(); @@ -570,25 +594,31 @@ impl<'a> EffectPass<'a> { if in_w <= 0.0 { continue; } - let mut m = Map::new(self.w, self.h, 0.0); - for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&fields.din) { - *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 }; - } - if st.common.blend == BlendMode::Normal { - // A Normal stroke replaces the layer under it instead of blending with it - // (Photoshop): at 50 % opacity an opaque pixel under the stroke turns into the - // stroke colour at 50 % alpha, not a 50/50 mix. - let mut stroke_px = alloc.filled(self.big, [0.0; 4])?; - paint_fx(&mut stroke_px, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, BlendMode::Normal, st.common.opacity, self.patterns); - for ((p, s), cov) in lay.px.iter_mut().zip(&stroke_px.px).zip(&m.v) { - if s[3] <= 0.0 { + let limit = in_w + 0.5; + let opacity = st.common.opacity; + if let (BlendMode::Normal, FxPaint::Color(color)) = (st.common.blend, &st.paint) { + // Solid colour is constant, so we can paint and replace in one pass. + let [r, g, b] = rgb(color); + for ((pixel, &a), &distance) in lay.px.iter_mut().zip(&shape.v).zip(&fields.din) { + let coverage = inside_stroke_coverage(a, distance, limit); + let alpha = coverage * opacity; + if alpha <= 0.0 { continue; } - let kept = p[3] * (1.0 - cov.clamp(0.0, 1.0)); - let alpha = kept + s[3]; - if alpha > 0.0 { - *p = [(p[0] * kept + s[0] * s[3]) / alpha, (p[1] * kept + s[1] * s[3]) / alpha, (p[2] * kept + s[2] * s[3]) / alpha, alpha.min(1.0)]; - } + let paint = psblend::composite(BlendMode::Normal, [0.0; 4], [r, g, b, alpha], 1.0); + replace_under_stroke(pixel, paint, coverage); + } + continue; + } + let mut m = Map::new(self.w, self.h, 0.0); + for ((coverage, &a), &distance) in m.v.iter_mut().zip(&shape.v).zip(&fields.din) { + *coverage = inside_stroke_coverage(a, distance, limit); + } + if st.common.blend == BlendMode::Normal { + let mut stroke_px = alloc.filled(self.big, [0.0; 4])?; + paint_fx(&mut stroke_px, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, BlendMode::Normal, opacity, self.patterns); + for ((pixel, &paint), &coverage) in lay.px.iter_mut().zip(&stroke_px.px).zip(&m.v) { + replace_under_stroke(pixel, paint, coverage); } } else { paint_fx(lay, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, st.common.blend, st.common.opacity, self.patterns); diff --git a/crates/compose/src/effects/distance.rs b/crates/compose/src/effects/distance.rs index 1b93cd8ac6..b7ba3da110 100644 --- a/crates/compose/src/effects/distance.rs +++ b/crates/compose/src/effects/distance.rs @@ -325,30 +325,6 @@ fn covered(s: &Map, test: impl Fn(f32) -> bool + Sync) -> Vec { /// Distance from each pixel centre inside the shape to the shape's edge /// (≤ 0 outside). pub(super) fn dist_inside(s: &Map) -> Vec { - dist_inside_by(s, Metric::Euclidean) -} - -pub(super) fn dist_inside_by(s: &Map, m: Metric) -> Vec { - if m == Metric::Chamfer { - // Partly covered edge pixels (alpha below their neighbourhood's) are seeds starting at - // their coverage, mirroring `dist_outside`: a 25 % edge column puts the edge 0.25 px in. - let cov = local_coverage(s); - let start = - s.v.iter() - .zip(&cov.v) - .map(|(&a, &c)| { - if a <= INSIDE_EPS { - 0.0 - } else if c < 1.0 - INSIDE_EPS { - c - } else { - CHAMFER_INF - } - }) - .collect(); - let (d, _) = chamfer_from(start, s.w, s.h); - return d.iter().zip(&s.v).map(|(d, &a)| if a <= INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); - } let outside = covered(s, |a| a <= INSIDE_EPS); let (d, _) = edt_nearest(&outside, s.w, s.h); par_fill(s.w, s.h, 0.0f32, |y, row| { @@ -359,6 +335,36 @@ pub(super) fn dist_inside_by(s: &Map, m: Metric) -> Vec { }) } +/// Chamfer distance for Inside and Center strokes. +pub(super) fn stroke_inside_distance(s: &Map, raster: bool) -> Vec { + // Partly covered edge pixels start at their local coverage. Keep these sub-pixel + // distances for the antialiased outline. + let mut seeds = local_coverage(s).v; + for (seed, &alpha) in seeds.iter_mut().zip(&s.v) { + *seed = if alpha <= INSIDE_EPS { + 0.0 + } else if *seed < 1.0 - INSIDE_EPS { + *seed + } else { + CHAMFER_INF + }; + } + let (mut distances, _) = chamfer_from(seeds, s.w, s.h); + for (distance, &alpha) in distances.iter_mut().zip(&s.v) { + let d = *distance; + *distance = if alpha <= INSIDE_EPS { + -0.5 + } else if raster && alpha < 1.0 && d > 1.0 { + // Translucent raster interiors also take the stroke. Apply the distance + // locally, so it cannot move the stroke boundary in nearby opaque pixels. + 0.0 + } else { + d - 0.5 + }; + } + distances +} + /// Alpha relative to the 3×3 neighbourhood maximum: separates edge coverage /// from the fill's own opacity on shape layers. pub(super) fn local_coverage(s: &Map) -> Map { @@ -770,6 +776,8 @@ pub enum FieldKind { ChokeInside, /// Stroke distance inside the shape. StrokeInside, + /// Inside stroke distance with translucent raster pixels covered. + StrokeInsideRaster, /// Exact Euclidean distance outside the shape: a wide raster stroke's outer edge (see /// [`stroke_outside_exact`]). The chamfer's level sets are polygons (an ~8-fold octagon), so a /// wide stroke's outer boundary facets; the shadow / glow spread above keeps the chamfer (#3646). @@ -792,7 +800,8 @@ pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reac FieldKind::BevelInside => bevel_dist_inside(&s, &sharp_edges(&s), reach), FieldKind::StrokeOutside => dist_outside_by(&s, Metric::Chamfer), FieldKind::ChokeInside => dist_outside_by(&s.map(|a| 1.0 - a), Metric::Chamfer), - FieldKind::StrokeInside => dist_inside_by(&s, Metric::Chamfer), + FieldKind::StrokeInside => stroke_inside_distance(&s, false), + FieldKind::StrokeInsideRaster => stroke_inside_distance(&s, true), FieldKind::StrokeOutsideExact => dist_outside_by(&s, Metric::Euclidean), FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Euclidean), FieldKind::StrokeOutsideVectorChamfer => dist_outside_by(&local_coverage(&s), Metric::Chamfer), diff --git a/crates/compose/src/effects/stroke_partial_alpha_tests.rs b/crates/compose/src/effects/stroke_partial_alpha_tests.rs new file mode 100644 index 0000000000..4f58458169 --- /dev/null +++ b/crates/compose/src/effects/stroke_partial_alpha_tests.rs @@ -0,0 +1,117 @@ +use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; +use photocraft_doc::{Document, Effect, FxCommon, FxPaint, Layer, StrokeFx, StrokePosition}; +use photocraft_geom::{Rect, Size}; + +/// The three squares and blue stroke measured in issue #15002. +fn fixture(depth: SampleType, position: StrokePosition) -> Document { + let mut doc = Document::with_background("Stroke partial alpha", Size::new(240, 120), ColorMode::Rgb, depth, Color::WHITE); + let mut layer = Layer::raster("Orange squares", doc.pixel_format()); + let surface = layer.surface_mut().unwrap(); + for (x, alpha) in [(20, 1.0), (100, 0.5), (180, 0.25)] { + surface.fill_rect(Rect::from_xywh(x, 40, 40, 40), &[1.0, 128.0 / 255.0, 0.0, alpha]); + } + layer.effects.items.push(Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Normal, 1.0), + size: if position == StrokePosition::Center { 6.0 } else { 5.0 }, + position, + paint: FxPaint::Color(Color::rgb(0.0, 0.0, 1.0)), + overprint: false, + })); + doc.layers.push(layer); + doc +} + +#[test] +fn stroke_partial_alpha_matches_the_measured_square_columns() { + const BLUE: [i32; 3] = [0, 0, 255]; + const ORANGE: [i32; 3] = [255, 128, 0]; + const WHITE: [i32; 3] = [255; 3]; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for position in [StrokePosition::Inside, StrokePosition::Center, StrokePosition::Outside] { + let doc = fixture(depth, position); + let buf = crate::render(&doc, doc.bounds()); + let close = |x, y, expected: [i32; 3]| { + let pixel = buf.get(x, y); + let actual = [pixel[0], pixel[1], pixel[2]].map(|c| (c * 255.0).round() as i32); + assert!( + actual.iter().zip(expected).all(|(a, b)| (a - b).abs() <= 1), + "{depth:?} {position:?} at ({x}, {y}): {actual:?}, expected {expected:?}" + ); + assert!((pixel[3] - 1.0).abs() < 1e-6); + }; + for (x, inside, outside) in [(120, [127, 127, 255], [128, 64, 127]), (200, [191, 191, 255], [64, 32, 191])] { + for y in 40..80 { + close( + x, + y, + match position { + StrokePosition::Inside => inside, + StrokePosition::Center => BLUE, + StrokePosition::Outside => outside, + }, + ); + } + match position { + StrokePosition::Inside => close(x, 39, WHITE), + StrokePosition::Center => { + close(x, 36, WHITE); + close(x, 37, inside); + close(x, 38, BLUE); + close(x, 39, BLUE); + } + StrokePosition::Outside => { + close(x, 34, WHITE); + close(x, 35, inside); + close(x, 36, BLUE); + close(x, 39, BLUE); + } + } + } + let (first, last) = match position { + StrokePosition::Inside => (40, 44), + StrokePosition::Center => (37, 42), + StrokePosition::Outside => (35, 39), + }; + close(40, first - 1, WHITE); + for y in first..=last { + close(40, y, BLUE); + } + close(40, last + 1, ORANGE); + close(40, 60, ORANGE); + } + } +} + +#[test] +fn the_raster_distance_preserves_the_opaque_interior_and_subpixel_outline() { + use super::{FieldKind, distance_field}; + + let row = [0.0, 0.25, 0.75, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.0]; + let source = row.repeat(9); + let inside = distance_field(FieldKind::StrokeInside, source.clone(), row.len(), 9, 6.0); + let raster = distance_field(FieldKind::StrokeInsideRaster, source, row.len(), 9, 6.0); + let mid = row.len() * 4; + // Opaque pixels retain their distances even beside a translucent area. + assert_eq!(raster[mid..mid + 8], inside[mid..mid + 8]); + assert_eq!(raster[mid + 8], inside[mid + 8], "the existing subpixel seed is retained"); + assert!(inside[mid + 11] > 0.5, "the old outline did not reach this interior"); + assert_eq!(raster[mid + 11], 0.0, "the translucent interior is covered"); + assert_eq!(raster[mid + 15], inside[mid + 15], "the fully transparent pixel stays outside"); +} + +#[test] +fn stroke_partial_alpha_keeps_intrinsic_alpha_for_inside_and_fills_it_for_center() { + for position in [StrokePosition::Inside, StrokePosition::Center] { + let mut doc = fixture(SampleType::U8, position); + let background = doc.layers[0].id; + doc.remove(background).unwrap(); + let pixels = crate::render(&doc, doc.bounds()); + for (x, source_alpha) in [(120, 128.0 / 255.0), (200, 64.0 / 255.0)] { + let actual = pixels.get(x, 60); + let expected_alpha = if position == StrokePosition::Inside { source_alpha } else { 1.0 }; + assert_eq!(&actual[..3], &[0.0, 0.0, 1.0], "{position:?} at x={x}"); + assert!((actual[3] - expected_alpha).abs() < 1e-6, "{position:?} at x={x}: {actual:?}"); + } + assert_eq!(pixels.get(80, 60), [0.0; 4]); + } +} diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index 0ce4f1ab10..2983063dfb 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -30,6 +30,8 @@ pub(crate) fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map:: h.finish() } layer.id.0.hash(h); + // The same display surface can blend differently before and after rasterizing a text child. + std::mem::discriminant(&layer.content).hash(h); // What the maps depend on: `fill_opacity` shades them; layer `opacity` is applied when the // maps are composited and `visible` only skips the lookup entirely, so neither belongs in // the key (an opacity drag must not rebuild shadows over the whole layer; the GPU's @@ -235,6 +237,8 @@ pub(crate) fn effect_maps_with(layer: &Layer, rect: Rect, cx: &C } let mut h = std::collections::hash_map::DefaultHasher::new(); cx.layer_keys.identity(layer, cx.doc).hash(&mut h); + // Converting a layer can reuse its exact tiles and ID but change how its stroke reads alpha. + std::mem::discriminant(&layer.content).hash(&mut h); (region.x0, region.y0, region.x1, region.y1).hash(&mut h); (cx.light.angle.to_bits(), cx.light.altitude.to_bits()).hash(&mut h); let key = h.finish(); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 6505f2cd1a..fadc2de4b5 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4406,6 +4406,29 @@ fn effect_cache_follows_a_group_childs_blend_if() { assert!(warm.px == cold.px, "stale group effect maps after a child's Blend If changed"); } +#[test] +fn effect_cache_follows_a_group_child_being_rasterized() { + let mut doc = doc_white(32, 32); + let rect = Rect::new(4, 4, 16, 20); + let bottom = solid_layer("pale", rect, [1.0, 1.0, 1.0, 0.5]); + let mut text = solid_layer("text", rect, [0.0, 0.0, 0.0, 0.5]); + let raster = text.content.clone(); + let text_id = text.id; + text.content = LayerContent::Text(photocraft_doc::TextLayer { cache: text.surface().cloned(), ..Default::default() }); + let mut top = solid_layer("blend if", rect, [0.2, 0.6, 0.0, 1.0]); + top.blend_if.set(0, [FULL, range([0, 0], [100, 100])]); + let mut group = Layer::group("group", vec![bottom, text, top]); + group.effects.items = vec![Effect::DropShadow(Shadow { size: 2.0, spread: 0.0, ..shadow(3.0, 90.0) })]; + doc.layers.push(group); + let before = render(&doc, doc.bounds()); + doc.layer_mut(text_id).unwrap().content = raster; + let warm = render(&doc, doc.bounds()); + purge_effect_cache(); + let cold = render(&doc, doc.bounds()); + assert!((0..32).any(|y| (0..32).any(|x| !rect.contains(x, y) && before.get(x, y) != cold.get(x, y))), "the group's shadow changes"); + assert!(warm.px == cold.px, "rasterization must invalidate the group's shadow map"); +} + /// A document whose one-colour areas are found: shared background tiles, a painted patch over /// tile edges, a uniform mask tile, an adjustment, a group, a 16-bit layer and a hidden one. fn sparse_doc(w: u32, h: u32) -> Document { diff --git a/crates/engine-core/Cargo.toml b/crates/engine-core/Cargo.toml index d947a91afa..9e98cbb775 100644 --- a/crates/engine-core/Cargo.toml +++ b/crates/engine-core/Cargo.toml @@ -19,7 +19,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } # PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } diff --git a/crates/engine-core/src/build_info.rs b/crates/engine-core/src/build_info.rs index 3ad4da1aba..76267af92a 100644 --- a/crates/engine-core/src/build_info.rs +++ b/crates/engine-core/src/build_info.rs @@ -8,7 +8,11 @@ //! - `PHOTOCRAFT_BUILD_DATE`: the build date, conventionally `YYYY-MM-DD` //! //! Without them (a plain `cargo build`) the build reports itself as a dev build. Nothing here -//! shells out to git, so builds work from a source tarball and for wasm. +//! shells out to git, so builds work from a source tarball and for wasm. The desktop and CLI +//! binaries' build scripts do read the commit of a git checkout and hand it over with +//! [`set_checkout`] at startup, so a dev build from git says which commit it is +//! (`0.1.0 (dev build, 3f2a9c1d0)`); keeping it out of this crate means a commit doesn't rebuild +//! the engine. /// The workspace version, such as `0.1.0` or `0.2.0-rc.1`. pub const VERSION: &str = match option_env!("PHOTOCRAFT_OVERRIDE_VERSION") { @@ -31,12 +35,30 @@ pub fn build_date() -> Option<&'static str> { /// The commit shortened for display. pub fn short_sha() -> Option<&'static str> { - git_sha().map(|s| &s[..s.len().min(9)]) + git_sha().map(shorten) } -/// `0.1.0 (3f2a9c1d0, 2026-10-01)`, or `0.1.0 (dev build)` without provenance. +fn shorten(sha: &str) -> &str { + sha.get(..9).unwrap_or(sha) +} + +static CHECKOUT: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Records the git commit of the checkout a dev build was compiled from (the binaries' build +/// scripts read it; `None` or empty from a source tarball). Only the first call counts. +pub fn set_checkout(sha: Option<&str>) { + if let Some(sha) = sha.map(str::trim).filter(|s| !s.is_empty()) { + let _ = CHECKOUT.set(sha.to_string()); + } +} + +/// `0.1.0 (3f2a9c1d0, 2026-10-01)`; a dev build `0.1.0 (dev build, 3f2a9c1d0)` from a git +/// checkout, or `0.1.0 (dev build)` without provenance. pub fn long_version() -> String { - format_long(VERSION, short_sha(), build_date()) + match short_sha() { + Some(s) => format_long(VERSION, Some(s), build_date()), + None => format_dev(VERSION, CHECKOUT.get().map(|s| shorten(s)), build_date()), + } } /// [`long_version`] worked out once, for a `&'static str` such as clap's `version`. @@ -54,6 +76,14 @@ fn format_long(version: &str, sha: Option<&str>, date: Option<&str>) -> String { } } +/// A build without `PHOTOCRAFT_BUILD_SHA`: the checkout's commit, when known, marked as a dev build. +fn format_dev(version: &str, checkout: Option<&str>, date: Option<&str>) -> String { + match checkout { + Some(c) => format!("{version} (dev build, {c})"), + None => format_long(version, None, date), + } +} + #[cfg(test)] mod tests { use super::*; @@ -64,6 +94,11 @@ mod tests { assert_eq!(format_long("1.2.3", Some("abc"), None), "1.2.3 (abc)"); assert_eq!(format_long("1.2.3", None, Some("2026-10-01")), "1.2.3 (2026-10-01)"); assert_eq!(format_long("1.2.3-rc.1", None, None), "1.2.3-rc.1 (dev build)"); + // #5247: a dev build from a git checkout names its commit. + assert_eq!(format_dev("0.8.2", Some(shorten("6f8505421abcdef")), None), "0.8.2 (dev build, 6f8505421)"); + assert_eq!(format_dev("0.8.2", None, None), "0.8.2 (dev build)"); + assert_eq!(format_dev("0.8.2", None, Some("2026-10-01")), "0.8.2 (2026-10-01)"); + assert_eq!(shorten("abc"), "abc"); } #[test] diff --git a/crates/engine-core/src/cmd/actions_cmds.rs b/crates/engine-core/src/cmd/actions_cmds.rs index 66543cd1d6..6ddc1951f3 100644 --- a/crates/engine-core/src/cmd/actions_cmds.rs +++ b/crates/engine-core/src/cmd/actions_cmds.rs @@ -158,6 +158,9 @@ pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result { { object.remove("__atnCustom"); } + if id == "edit.contentAwareFill" { + crate::atn_cmds::caf_remembered(&mut p, s.prefs())?; + } if id == "layer.setProps" && let Some(target) = p.get("_actionLayer") { diff --git a/crates/engine-core/src/cmd/artboard_cmds.rs b/crates/engine-core/src/cmd/artboard_cmds.rs index 76012bd600..bae9c00caa 100644 --- a/crates/engine-core/src/cmd/artboard_cmds.rs +++ b/crates/engine-core/src/cmd/artboard_cmds.rs @@ -369,9 +369,19 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) { return Err(EngineError::Other("artboards are made from a top-level layer group".into())); } + let topmost = doc.artboards().last().map(|b| b.2.rect); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; // A hidden group keeps today's measure (not measured in the reference). - let rect = if l.visible { shown_children_bounds(l) } else { crate::layer_multi_cmds::layer_bounds(l) }.unwrap_or(canvas); + let bounds = if l.visible { shown_children_bounds(l) } else { crate::layer_multi_cmds::layer_bounds(l) }; + // A group without bounds covers the canvas, or once there are boards, takes the slot + // right of the topmost one (#14558). A hidden group keeps the canvas (not measured). + let rect = match (bounds, topmost) { + (Some(r), _) => r, + (None, Some(board)) if l.visible => { + right_of(board).ok_or_else(|| bad(cmd, format!("no room for an artboard right of the topmost one (its right edge is x = {})", board.x1)))? + } + (None, _) => canvas, + }; set_artboard(l, Artboard { rect, background, preset }); // As in the reference application, the new artboard is Normal at 100 % whatever the group had. l.blend = photocraft_color::BlendMode::Normal; @@ -385,6 +395,14 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// A board the size of `board`, [`GAP`] right of it at the same top; `None` past the 32-bit range +/// (computed in i64, #931). +fn right_of(board: Rect) -> Option { + let x0 = i32::try_from(i64::from(board.x1) + i64::from(GAP)).ok()?; + let x1 = i32::try_from(i64::from(x0) + i64::from(board.width())).ok()?; + Some(Rect::new(x0, board.y0, x1, board.y1)) +} + /// [`layer_multi_cmds::layer_bounds`](crate::layer_multi_cmds::layer_bounds) of what shows: a /// group unions only its visible children, so hidden layers (and a hidden group's children) don't /// size the board Artboard from Group makes (#14553). @@ -410,6 +428,11 @@ pub fn from_layers_defaults(s: &Session) -> Option<(String, [i64; 2])> { Some((next_artboard_name(&d.doc), [w, h])) } +/// The smallest width or height Artboard from Layers takes, in pixels (#14577). +pub const FROM_LAYERS_MIN: i64 = 4; +/// The largest width or height Artboard from Layers takes, in pixels (#14577). +pub const FROM_LAYERS_MAX: i64 = 32_000; + fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { let sel = crate::layer_multi_cmds::selected(s); let d = s.active().ok_or(EngineError::NoDocument)?; @@ -422,8 +445,9 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "the artboard width and height must not be negative")); } // A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps - // their bounds on that axis (#9087). - let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)]; + // their bounds on that axis (#9087). As the dialog's fields do, a size outside 4..=32000 px + // is clamped to it (#14577). + let size = [int(p, "width"), int(p, "height")].map(|v| v.filter(|v| *v != 0).map(|v| v.clamp(FROM_LAYERS_MIN, FROM_LAYERS_MAX))); let (gid, rect, shift) = s.edit("New Artboard From Layers", |doc, active| { let ids = crate::layer_multi_cmds::top_level(doc, &sel); if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) { @@ -1161,12 +1185,12 @@ fn rgb_copy(one: &Document) -> Result { /// `one` flattened over white as a JPEG, for a PDF page. A board past the compositor's render /// limit is refused before it is flattened (the flatten would be empty). fn jpeg_page(one: &Document, quality: Option, cmd: &str) -> Result> { - Ok(jpeg_page_masked(one, quality, false, cmd)?.0) + Ok(jpeg_page_masked(one, quality, false, false, cmd)?.0) } -/// [`jpeg_page`] and, when `masked`, the page's [`soft_mask`] taken from the composite before it -/// goes over white. -fn jpeg_page_masked(one: &Document, quality: Option, masked: bool, cmd: &str) -> Result<(Vec, Option>)> { +/// [`jpeg_page`], or with `zip` the page's exact 8-bit RGB samples as a zlib stream (#13651), and, +/// when `masked`, the page's [`soft_mask`] taken from the composite before it goes over white. +fn jpeg_page_masked(one: &Document, quality: Option, zip: bool, masked: bool, cmd: &str) -> Result<(Vec, Option>)> { crate::file_cmds::check_flattenable(one, cmd)?; let composite = photocraft_compose::flatten(one); let mask = if masked { soft_mask(&composite.px)? } else { None }; @@ -1176,12 +1200,19 @@ fn jpeg_page_masked(one: &Document, quality: Option, masked: bool, cmd: &st let mut surf = Surface::new(fmt); let vals: Vec = buf.px.iter().flat_map(|px| photocraft_raster::from_rgba(&fmt, *px)).collect(); surf.write_region(one.bounds(), &vals); + if zip { + // Lossless (#13651): the exact 8-bit RGB samples, alpha dropped, Flate-compressed. + let rgb: Vec = surf.to_interleaved(one.bounds()).as_chunks::<4>().0.iter().flat_map(|&[r, g, b, _]| [r, g, b]).collect(); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + let data = std::io::Write::write_all(&mut z, &rgb).and_then(|()| z.finish()).map_err(|e| EngineError::Other(format!("compressing a PDF page: {e}")))?; + return Ok((data, mask)); + } flat.layers.push(Layer::new("Background", LayerContent::Raster(surf))); Ok((encode(&flat, "page.jpg", quality)?.0, mask)) } -/// A minimal PDF with one page per JPEG image: (width px, height px, dpi, JPEG bytes). -/// Pages are sized so the image prints at its resolution. +/// A minimal PDF with one page per image: (width px, height px, dpi, JPEG bytes or a zlib +/// stream of 8-bit RGB samples). Pages are sized so the image prints at its resolution. pub fn raster_pdf(pages: &[(u32, u32, f32, Vec)]) -> Vec { let pages: Vec = pages.iter().map(|(w, h, dpi, jpeg)| (*w, *h, *dpi, jpeg.clone(), None)).collect(); raster_pdf_masked(&pages) @@ -1231,8 +1262,10 @@ fn raster_pdf_masked(pages: &[PdfPage]) -> Vec { let stream = format!("q {pw:.3} 0 0 {ph:.3} 0 0 cm /Im0 Do Q"); obj(&mut out, format!("<< /Length {} >>\nstream\n{stream}\nendstream", stream.len()).as_bytes()); let soft = if mask.is_some() { format!(" /SMask {smask} 0 R") } else { String::new() }; + // JPEG data opens with the SOI marker FF D8; a zlib stream never starts with FF. + let filter = if jpeg.starts_with(&[0xff, 0xd8]) { "DCTDecode" } else { "FlateDecode" }; let mut img = format!( - "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8{soft} /Filter /DCTDecode /Length {} >>\nstream\n", + "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8{soft} /Filter /{filter} /Length {} >>\nstream\n", jpeg.len() ) .into_bytes(); @@ -1323,6 +1356,14 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { None => stem(&path), }; let quality = f64_param(p, "quality").or(Some(10.0)); + let zip = match p.get("encoding") { + None | Some(Value::Null) => false, + Some(v) => match v.as_str() { + Some("jpeg") => false, + Some("zip") => true, + _ => return Err(bad(cmd, format!("`encoding` must be \"jpeg\" or \"zip\", not {v}"))), + }, + }; let background = p.get("includeBackground").and_then(Value::as_bool).unwrap_or(true); // Reverse Page Order (#13644): the default page order the other way round. let reverse = match p.get("reversePageOrder") { @@ -1340,7 +1381,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { // shows the board, so its visibility is read from the source. let visible = doc.layer(id).is_some_and(|l| l.visible); let masked = !background && visible && drop_white_fill(&mut one); - let (jpeg, mask) = jpeg_page_masked(&one, quality, masked, cmd)?; + let (jpeg, mask) = jpeg_page_masked(&one, quality, zip, masked, cmd)?; pages.push((one.size.width, one.size.height, doc.resolution_dpi, jpeg, mask)); names.push(one.name); } @@ -1421,7 +1462,7 @@ pub fn specs() -> Vec { "layer.new.artboardFromLayers", "Artboard from Layers…", &["Layer", "New"], - r##"{"name":text,"background":"white|black|transparent|custom"="white","color":color,"width":px=0,"height":px=0} (the selected layers; name: empty gives Artboard N; color: for custom; width, height: the board's size from the layers' top left, 0 keeps their bounds) → {layer, rect}"##, + r##"{"name":text,"background":"white|black|transparent|custom"="white","color":color,"width":px=0,"height":px=0} (the selected layers; name: empty gives Artboard N; color: for custom; width, height: the board's size from the layers' top left, 4..32000 px, a size outside is clamped to it, 0 keeps their bounds) → {layer, rect}"##, has_free_layers, artboard_from_layers ), @@ -1461,7 +1502,7 @@ pub fn specs() -> Vec { "file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], - r##"{"path":str (.pdf; with "mode":"perArtboard" only gives the defaults of "dir" and "prefix"),"mode":"multiPage|perArtboard"="multiPage" (Multi-Page Document: one file at "path"; Document Per Artboard: one single-page file per board, "/.pdf", spaces kept, characters a file name can't hold become "_", a name an earlier board already took, ignoring case, gets "-2", "-3"…),"dir":folder=folder of "path","prefix":str=file name of "path" without ".pdf", else the document name,"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's page also shows the visible boards above it where they overlap it; artboard: Artboard Content Only),"artboards":[id]?,"quality":0..12=10,"includeBackground":bool=true (false: a white board's fill is left out and the page gets a soft mask, so it is transparent where the board's layers have no pixels; an empty board, other fills and documents other than 8-bit RGB keep it),"reversePageOrder":bool=false (the default page order the other way round)} → {path (multi-page), pages, files} (one raster page per board, bottom artboard of the Layers panel first)"##, + r##"{"path":str (.pdf; with "mode":"perArtboard" only gives the defaults of "dir" and "prefix"),"mode":"multiPage|perArtboard"="multiPage" (Multi-Page Document: one file at "path"; Document Per Artboard: one single-page file per board, "/.pdf", spaces kept, characters a file name can't hold become "_", a name an earlier board already took, ignoring case, gets "-2", "-3"…),"dir":folder=folder of "path","prefix":str=file name of "path" without ".pdf", else the document name,"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's page also shows the visible boards above it where they overlap it; artboard: Artboard Content Only),"artboards":[id]?,"quality":0..12=10,"includeBackground":bool=true (false: a white board's fill is left out and the page gets a soft mask, so it is transparent where the board's layers have no pixels; an empty board, other fills and documents other than 8-bit RGB keep it),"reversePageOrder":bool=false (the default page order the other way round),"encoding":"jpeg|zip"="jpeg" (zip: lossless Flate pages, quality ignored)} → {path (multi-page), pages, files} (one raster page per board, bottom artboard of the Layers panel first)"##, export_artboards, artboards_to_pdf ), @@ -1497,10 +1538,18 @@ mod include_name_tests; #[path = "artboard_cmds/from_layers_history_name_tests.rs"] mod from_layers_history_name_tests; +#[cfg(test)] +#[path = "artboard_cmds/from_layers_size_range_tests.rs"] +mod from_layers_size_range_tests; + #[cfg(test)] #[path = "artboard_cmds/from_group_hidden_bounds_tests.rs"] mod from_group_hidden_bounds_tests; +#[cfg(test)] +#[path = "artboard_cmds/from_group_empty_placement_tests.rs"] +mod from_group_empty_placement_tests; + #[cfg(test)] #[path = "artboard_cmds/overlapping_areas_tests.rs"] mod overlapping_areas_tests; @@ -1514,9 +1563,13 @@ mod pdf_overlapping_areas_tests; #[cfg(test)] #[path = "artboard_cmds/pdf_page_order_tests.rs"] mod pdf_page_order_tests; + #[cfg(test)] #[path = "artboard_cmds/pdf_reverse_page_order_tests.rs"] mod pdf_reverse_page_order_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_zip_encoding_tests.rs"] +mod pdf_zip_encoding_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine-core/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs b/crates/engine-core/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs new file mode 100644 index 0000000000..ef7e526980 --- /dev/null +++ b/crates/engine-core/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs @@ -0,0 +1,128 @@ +//! Artboard from Group on a group without bounds (#14558): the canvas when the document has no +//! artboard yet, else a board of the topmost artboard's size, `GAP` right of it at the same top. +//! A hidden group keeps the canvas (not measured, #14553). + +use super::*; +use photocraft_geom::Rect; + +/// 800 x 600 with the white Background, the artboards `boards` (`[x, y, w, h]`, bottom to top) +/// and an empty top-level group "Empty" above them. Returns the session and Empty's id. +fn session_with(boards: &[[i32; 4]]) -> (Session, LayerId) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + for b in boards { + s.execute("layer.new.artboard", json!({"rect": b})).unwrap(); + } + let id = s.edit("Empty", |doc, active| Ok(*active.insert(doc.insert_above(None, Layer::group("Empty", vec![]))))).unwrap(); + (s, id) +} + +/// [`session_with`] with no board, or with "Artboard 1" at 100,100 to 600,450. +fn session(board: bool) -> (Session, LayerId) { + session_with(if board { &[[100, 100, 500, 350]] } else { &[] }) +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn from_group(s: &mut Session, id: LayerId) -> Result { + s.execute("layer.new.artboardFromGroup", json!({"layer": id.0})) +} + +fn board_rect(s: &Session, id: LayerId) -> Rect { + doc(s).layer(id).unwrap().artboard().unwrap().rect +} + +#[test] +fn an_empty_group_goes_right_of_the_topmost_board() { + let (mut s, id) = session(true); + let r = from_group(&mut s, id).unwrap(); + assert_eq!(r["rect"], json!([700, 100, 500, 350])); + assert_eq!(board_rect(&s, id), Rect::new(700, 100, 1200, 450)); + assert!(doc(&s).bounds().contains_rect(&Rect::new(700, 100, 1200, 450)), "the canvas grew to show it: {:?}", doc(&s).bounds()); +} + +#[test] +fn without_artboards_an_empty_group_covers_the_canvas() { + let (mut s, id) = session(false); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(0, 0, 800, 600)); + assert_eq!(doc(&s).bounds(), Rect::new(0, 0, 800, 600)); +} + +/// A hidden empty group keeps today's canvas rectangle even when a board exists: #14553 leaves a +/// hidden top-level group unmeasured. +#[test] +fn a_hidden_empty_group_keeps_the_canvas_beside_a_board() { + let (mut s, id) = session(true); + s.edit("Hide", |doc, _| { + doc.layer_mut(id).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let canvas = doc(&s).bounds(); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), canvas); +} + +/// A visible group whose children are all hidden counts as empty (#14553), so it takes the slot. +#[test] +fn a_visible_group_of_hidden_layers_goes_right_of_the_board() { + let (mut s, id) = session(true); + s.edit("Hidden red", |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Hidden red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 50), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + l.visible = false; + doc.layer_mut(id).and_then(Layer::children_mut).unwrap().push(l); + Ok(()) + }) + .unwrap(); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(700, 100, 1200, 450)); +} + +/// A group with content keeps its own bounds when boards exist. +#[test] +fn a_group_with_content_keeps_its_bounds_beside_boards() { + let (mut s, id) = session(true); + s.edit("Red", |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(650, 50, 750, 150), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + doc.layer_mut(id).and_then(Layer::children_mut).unwrap().push(l); + Ok(()) + }) + .unwrap(); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(650, 50, 750, 150)); +} + +/// With several boards (not measured) the slot follows the topmost board in the Layers panel, +/// not the rightmost one. +#[test] +fn the_slot_follows_the_topmost_board_not_the_rightmost() { + // The topmost board is a small one left of the 100,100 to 600,450 board. + let (mut s, id) = session_with(&[[100, 100, 500, 350], [0, 480, 60, 40]]); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(60 + GAP, 480, 120 + GAP, 520)); +} + +/// #931: a topmost board at the far right edge leaves no room right of it; the command says so +/// and changes nothing, instead of wrapping. +#[test] +fn no_room_right_of_a_far_right_board_is_an_error() { + let (mut s, id) = session(false); + s.edit("Far", |doc, _| { + let mut g = Layer::group("Far", vec![]); + set_artboard(&mut g, Artboard::new(Rect::new(i32::MAX - 600, 0, i32::MAX - 50, 300))); + doc.insert_above(None, g); + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let e = from_group(&mut s, id).unwrap_err().to_string(); + assert!(e.contains("no room"), "{e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "the document changed"); +} diff --git a/crates/engine-core/src/cmd/artboard_cmds/from_layers_size_range_tests.rs b/crates/engine-core/src/cmd/artboard_cmds/from_layers_size_range_tests.rs new file mode 100644 index 0000000000..95197bb42e --- /dev/null +++ b/crates/engine-core/src/cmd/artboard_cmds/from_layers_size_range_tests.rs @@ -0,0 +1,67 @@ +//! Artboard from Layers takes a width and height of 4 to 32000 px and clamps a scripted size +//! outside that range, as its dialog's fields do when you leave them (#14577). 0 or no size keeps +//! the selected layers' bounds on that axis. + +use super::*; +use photocraft_geom::Rect; + +/// 100 x 80 RGB at `depth` with a pixel layer "Red" holding a square at 10,10 to 30,30. +fn session(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth, "background": "white"})).unwrap(); + s.edit("Red", |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 30), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + s +} + +/// The new board's `[x, y, width, height]` and the canvas size after Artboard from Layers. +fn board(depth: u32, params: Value) -> ([i64; 4], (u32, u32)) { + let mut s = session(depth); + let out = s.execute("layer.new.artboardFromLayers", params.clone()).unwrap_or_else(|e| panic!("{params} at {depth} bit: {e}")); + let rect: Vec = out["rect"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); + let doc = &s.active().unwrap().doc; + (rect.try_into().unwrap(), (doc.size.width, doc.size.height)) +} + +#[test] +fn a_scripted_size_past_the_range_is_clamped_to_4_to_32000() { + for depth in [8, 16, 32] { + let (rect, canvas) = board(depth, json!({"width": 99999, "height": 1})); + assert_eq!(rect, [10, 10, 32_000, 4], "99999 -> 32000, 1 -> 4 at {depth} bit"); + assert!(canvas.0 <= 32_100, "the canvas grows only to the clamped board at {depth} bit: {canvas:?}"); + let (rect, _) = board(depth, json!({"width": 2, "height": 50_000})); + assert_eq!(rect, [10, 10, 4, 32_000], "2 -> 4, 50000 -> 32000 at {depth} bit"); + } +} + +#[test] +fn sizes_at_the_ends_of_the_range_are_kept() { + let (rect, _) = board(8, json!({"width": 4, "height": 32_000})); + assert_eq!(rect, [10, 10, 4, 32_000]); + let (rect, _) = board(8, json!({"width": 640, "height": 480})); + assert_eq!(rect, [10, 10, 640, 480]); +} + +#[test] +fn zero_or_no_size_keeps_the_layers_bounds() { + for params in [json!({}), json!({"width": 0, "height": 0}), json!({"width": 0})] { + let (rect, _) = board(8, params.clone()); + assert_eq!(rect, [10, 10, 20, 20], "{params}"); + } + let (rect, _) = board(8, json!({"width": 0, "height": 1})); + assert_eq!(rect, [10, 10, 20, 4], "0 keeps the width, 1 is clamped to 4"); +} + +#[test] +fn a_negative_size_is_still_refused() { + let mut s = session(8); + let err = s.execute("layer.new.artboardFromLayers", json!({"width": -5})).unwrap_err(); + assert!(err.to_string().contains("must not be negative"), "{err}"); +} diff --git a/crates/engine-core/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs b/crates/engine-core/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs index 4885213edf..07cae8ea1b 100644 --- a/crates/engine-core/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs +++ b/crates/engine-core/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs @@ -27,7 +27,7 @@ fn session(depth: u32) -> (Session, [u64; 3]) { } /// A pixel layer `name` of `color` over `rect`, on top of board `board`'s layers. -fn paint(s: &mut Session, board: u64, name: &str, rect: Rect, color: [u8; 3]) { +pub(super) fn paint(s: &mut Session, board: u64, name: &str, rect: Rect, color: [u8; 3]) { s.edit(name, |doc, _| { let fmt = doc.pixel_format(); let mut l = Layer::raster(name, fmt); diff --git a/crates/engine-core/src/cmd/artboard_cmds/pdf_zip_encoding_tests.rs b/crates/engine-core/src/cmd/artboard_cmds/pdf_zip_encoding_tests.rs new file mode 100644 index 0000000000..736fb375a1 --- /dev/null +++ b/crates/engine-core/src/cmd/artboard_cmds/pdf_zip_encoding_tests.rs @@ -0,0 +1,137 @@ +//! Artboards to PDF's Encoding (#13651): `"zip"` writes every page as a lossless Flate image, +//! `"jpeg"` (the default) as before. The measured document: 800 x 400, bottom to top `Red Board` +//! 0,0-200,150 (white, pixel layer `Red` 220,30,30 at 20,20-120,100), `Blue Board` +//! 120,30-320,230 (white, pixel layer `Blue`) and `Empty Board` 600,0-700,100 (white, no layers). + +use std::io::Read; + +use super::pdf_overlapping_areas_tests::paint; +use super::*; +use photocraft_geom::Rect; + +const CMD: &str = "file.export.artboardsToPdf"; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": 8, "resolution": 72, "background": "transparent"})).unwrap(); + let mut board = |rect: [i64; 4], name: &str| { + s.execute("layer.new.artboard", json!({"rect": rect, "name": name, "background": "white"})).unwrap()["layer"].as_u64().unwrap() + }; + let red = board([0, 0, 200, 150], "Red Board"); + let blue = board([120, 30, 200, 200], "Blue Board"); + board([600, 0, 100, 100], "Empty Board"); + paint(&mut s, red, "Red", Rect::new(20, 20, 120, 100), [220, 30, 30]); + paint(&mut s, blue, "Blue", Rect::new(130, 40, 230, 140), [30, 30, 220]); + s +} + +/// Runs the command with `params` plus a fresh `path`; the PDF's bytes, or the command's error. +fn export(s: &mut Session, tag: &str, params: Value) -> Result> { + let dir = std::env::temp_dir().join(format!("photocraft-pdf-zip-{}-{tag}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = join(&dir.to_string_lossy(), "boards.pdf"); + let mut params = params; + params["path"] = json!(path); + let r = s.execute(CMD, params); + let bytes = std::fs::read(&path); + let _ = std::fs::remove_dir_all(&dir); + r.map(|_| bytes.unwrap()) +} + +/// The first position of `needle` in `pdf` at or after `from` (byte offsets: streams are binary). +fn find(pdf: &[u8], from: usize, needle: &[u8]) -> Option { + pdf[from..].windows(needle.len()).position(|w| w == needle).map(|i| from + i) +} + +/// Every page image in page order: its dictionary and its stream bytes. +fn images(pdf: &[u8]) -> Vec<(String, &[u8])> { + let mut out = Vec::new(); + let mut at = 0; + while let Some(start) = find(pdf, at, b"/Subtype /Image") { + let dict_end = find(pdf, start, b">>\nstream\n").unwrap(); + let dict = String::from_utf8(pdf[start..dict_end].to_vec()).unwrap(); + let len: usize = dict.split("/Length ").nth(1).unwrap().trim().parse().unwrap(); + let data = dict_end + b">>\nstream\n".len(); + out.push((dict, &pdf[data..data + len])); + at = data + len; + } + out +} + +fn inflate(data: &[u8]) -> Vec { + let mut out = Vec::new(); + flate2::read::ZlibDecoder::new(data).read_to_end(&mut out).unwrap(); + out +} + +#[test] +fn zip_pages_are_flate_rgb_images_with_the_exact_pixels() { + // Artboard Content Only: the default Include Overlapping Areas would show Blue Board's corner on Red Board's page. + let pdf = export(&mut session(), "exact", json!({"encoding": "zip", "content": "artboard"})).unwrap(); + let pages = images(&pdf); + assert_eq!(pages.len(), 3); + for (dict, _) in &pages { + assert!(dict.contains("/ColorSpace /DeviceRGB /BitsPerComponent 8") && dict.contains("/Filter /FlateDecode"), "{dict}"); + } + assert!(find(&pdf, 0, b"/DCTDecode").is_none()); + // Page 1 is Red Board, 200 x 150: the red layer exactly 220,30,30, white elsewhere. + assert!(pages[0].0.contains("/Width 200 /Height 150"), "{}", pages[0].0); + let rgb = inflate(pages[0].1); + assert_eq!(rgb.len(), 200 * 150 * 3); + for (i, px) in rgb.as_chunks::<3>().0.iter().enumerate() { + let (x, y) = (i % 200, i / 200); + let want = if (20..120).contains(&x) && (20..100).contains(&y) { [220, 30, 30] } else { [255, 255, 255] }; + assert_eq!(*px, want, "page pixel {x},{y}"); + } + // Empty Board is plain white. + assert!(inflate(pages[2].1).iter().all(|&v| v == 255)); +} + +#[test] +fn zip_pdf_xref_offsets_point_at_their_objects() { + let pdf = export(&mut session(), "xref", json!({"encoding": "zip"})).unwrap(); + assert!(images(&pdf).iter().all(|(dict, _)| dict.contains("/Filter /FlateDecode"))); + let xref = pdf.windows(6).rposition(|w| w == b"\nxref\n").unwrap() + 1; + assert!(pdf.ends_with(format!("startxref\n{xref}\n%%EOF\n").as_bytes())); + let table = String::from_utf8(pdf[xref..].to_vec()).unwrap(); + // Catalog, page tree, then page, contents and image per page. + let offsets: Vec = table.lines().skip(3).take(2 + 3 * 3).map(|l| l[..10].parse().unwrap()).collect(); + assert_eq!(offsets.len(), 11); + for (i, o) in offsets.iter().enumerate() { + assert!(pdf[*o..].starts_with(format!("{} 0 obj", i + 1).as_bytes()), "object {}", i + 1); + } +} + +#[test] +fn zip_ignores_quality() { + let mut s = session(); + let low = export(&mut s, "q0", json!({"encoding": "zip", "quality": 0})).unwrap(); + let high = export(&mut s, "q12", json!({"encoding": "zip", "quality": 12})).unwrap(); + assert_eq!(low, high); +} + +#[test] +fn jpeg_and_no_encoding_give_todays_pdf() { + let mut s = session(); + let default = export(&mut s, "none", json!({"quality": 8})).unwrap(); + assert_eq!(export(&mut s, "jpeg", json!({"encoding": "jpeg", "quality": 8})).unwrap(), default); + assert_eq!(export(&mut s, "null", json!({"encoding": null, "quality": 8})).unwrap(), default); + let pages = images(&default); + assert_eq!(pages.len(), 3); + assert!(pages.iter().all(|(dict, data)| dict.contains("/Filter /DCTDecode") && data.starts_with(&[0xff, 0xd8]))); +} + +#[test] +fn an_unknown_encoding_is_an_error() { + let mut s = session(); + for (i, encoding) in [json!("lzw"), json!(5), json!(""), json!("ZIP"), json!(true)].into_iter().enumerate() { + let err = export(&mut s, &format!("bad{i}"), json!({"encoding": encoding})).unwrap_err(); + assert!(err.to_string().contains("`encoding` must be"), "{encoding}: {err}"); + } +} + +#[test] +fn the_params_document_the_encoding() { + let spec = specs().into_iter().find(|c| c.id == CMD).unwrap(); + assert!(spec.params.contains(r#""encoding":"jpeg|zip"="jpeg""#), "{}", spec.params); +} diff --git a/crates/engine-core/src/cmd/atn_cmds.rs b/crates/engine-core/src/cmd/atn_cmds.rs index 4b9d2ef489..25c0003d5d 100644 --- a/crates/engine-core/src/cmd/atn_cmds.rs +++ b/crates/engine-core/src/cmd/atn_cmds.rs @@ -85,6 +85,8 @@ use events::{EVENTS, event_and_descriptor, event_for}; use fields::Mapped; use files::{load, save}; pub use menu_item::{MENU_ITEM, menu_item_command, menu_item_commands, menu_item_needs_settings}; +pub(crate) use steps_content_aware::caf_remembered; +pub use steps_content_aware::{CAF_CUSTOM_AREA_NOT_REMEMBERED, CAF_WORKSPACE_PREFS}; #[cfg(test)] use steps_doc::crop_from; pub(crate) use steps_gallery::RECORDED_EVENT; @@ -197,6 +199,9 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; +#[cfg(test)] +mod caf_action_values_tests; + #[cfg(test)] mod layer_props_tests; diff --git a/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs new file mode 100644 index 0000000000..1f4e52822b --- /dev/null +++ b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs @@ -0,0 +1,251 @@ +//! Recorded `cafWorkspace` steps: every measured value maps to the command and back, and an +//! empty step plays with the workspace's remembered settings (#14254). +use super::*; +use crate::actions_cmds::{ActionList, ActionStep, ActionsExt}; + +const CMD: &str = "edit.contentAwareFill"; +const MARK: &str = "_atnCafRemembered"; + +/// A seven-key step with these enumerations and every boolean off. +fn workspace(sampling: &str, color: &str, rotation: &str, output: &str) -> Descriptor { + desc("null") + .with("cafSamplingRegion", enm("cafSamplingRegion", sampling)) + .with("cafSampleAllLayers", D::Boolean(false)) + .with("cafColorAdaptationLevel", enm("cafColorAdaptationLevel", color)) + .with("cafRotationAmount", enm("cafRotationAmount", rotation)) + .with("cafScale", D::Boolean(false)) + .with("cafMirror", D::Boolean(false)) + .with("cafOutput", enm("cafOutput", output)) +} + +/// The params [`workspace`] imports as. +fn params(sampling: &str, color: &str, rotation: &str, output: &str) -> Value { + json!({"sampling":sampling,"sampleAllLayers":false,"colorAdaptation":color, + "rotationAdaptation":rotation,"scale":false,"mirror":false,"output":output}) +} + +fn item(d: Descriptor) -> AtnItem { + AtnItem { event: AtnEvent::name("cafWorkspace"), dictionary: b"Content-Aware Fill".to_vec(), descriptor: Some(d), ..Default::default() } +} + +fn file(d: Descriptor) -> Vec { + atn::write(&AtnFile { + name: UnicodeString::new_nul("S"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item(d)], ..Default::default() }], + ..Default::default() + }) + .unwrap() +} + +/// The single step a one-step file imports as. +fn load(d: Descriptor) -> Action { + let loaded = import(&file(d)).unwrap(); + assert!(loaded.unsupported.is_empty(), "{:?}", loaded.unsupported); + loaded.actions.into_iter().next().unwrap() +} + +/// The item Save Actions writes for one step, or `None` when it refuses the step. A save that succeeds must +/// write a readable file holding the item. +fn exported(p: Value) -> Option { + let a = Action::new("A", vec![ActionStep::new(CMD, p)]); + let (bytes, skipped) = export("S", &[&a], &[], false).ok()?; + assert!(skipped.is_empty()); + let saved = atn::parse(&bytes).expect("a successful save writes a readable file"); + Some(saved.actions.into_iter().next().and_then(|a| a.items.into_iter().next()).expect("the saved file holds the step")) +} + +#[test] +fn every_measured_value_imports_to_its_param_and_saves_back_unchanged() { + let base = ("cafSamplingRegionRectangular", "cafColorAdaptationDefault", "cafRotationAmountNone", "cafOutputToNewLayer"); + let mut cases = Vec::new(); + for (wire, value) in [("cafSamplingRegionAuto", "auto"), ("cafSamplingRegionRectangular", "rectangular"), ("cafSamplingRegionCustom", "custom")] { + cases.push((workspace(wire, base.1, base.2, base.3), params(value, "default", "none", "new"))); + } + for (wire, value) in [ + ("cafColorAdaptationNone", "none"), + ("cafColorAdaptationDefault", "default"), + ("cafColorAdaptationHigh", "high"), + ("cafColorAdaptationVeryHigh", "veryHigh"), + ] { + cases.push((workspace(base.0, wire, base.2, base.3), params("rectangular", value, "none", "new"))); + } + for (wire, value) in [ + ("cafRotationAmountNone", "none"), + ("cafRotationAmountLow", "low"), + ("cafRotationAmountMedium", "medium"), + ("cafRotationAmountHigh", "high"), + ("cafRotationAmountFull", "full"), + ] { + cases.push((workspace(base.0, base.1, wire, base.3), params("rectangular", "default", value, "new"))); + } + for (wire, value) in [("cafOutputToCurrentLayer", "current"), ("cafOutputToNewLayer", "new"), ("cafOutputToDuplicateLayer", "duplicate")] { + cases.push((workspace(base.0, base.1, base.2, wire), params("rectangular", "default", "none", value))); + } + for (d, p) in cases { + let action = load(d.clone()); + assert_eq!(action.steps, vec![ActionStep::new(CMD, p.clone())]); + assert_eq!(exported(p.clone()), Some(item(d.clone())), "{p}"); + let bytes = export("S", &[&action], &[], false).unwrap().0; + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0], item(d)); + } +} + +#[test] +fn an_empty_step_imports_as_remembered_and_saves_back_empty() { + let action = load(desc("null")); + assert_eq!(action.steps, vec![ActionStep::new(CMD, json!({MARK: true}))]); + assert_eq!(exported(json!({MARK: true})), Some(item(desc("null")))); + // A differently named empty descriptor comes back as recorded. + let mut named = desc("null"); + named.name = UnicodeString::new_nul("Recorded CAF"); + let action = load(named.clone()); + assert_eq!(action.steps[0].params[MARK], json!(true)); + let bytes = export("S", &[&action], &[], false).unwrap().0; + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0], item(named)); +} + +#[test] +fn a_remembered_step_with_values_of_its_own_is_not_saved_as_an_empty_step() { + for p in [json!({MARK: true, "output": "current"}), json!({MARK: false}), json!({MARK: "yes"}), json!({MARK: true, "seed": 2})] { + assert_eq!(exported(p.clone()), None, "{p}"); + } +} + +/// White 8 x 8 with a red square selected for the fill. +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width":8,"height":8,"background":"white"})).unwrap(); + s.execute("select.rect", json!({"x":3,"y":3,"width":2,"height":2})).unwrap(); + // Painted directly: Edit › Fill is registered by another engine crate. + s.edit("paint", |doc, active| { + let surface = doc.layer_mut(active.ok_or(crate::EngineError::NoDocument)?).and_then(|l| l.surface_mut()).ok_or(crate::EngineError::NoDocument)?; + for (x, y) in [(3, 3), (4, 3), (3, 4), (4, 4)] { + surface.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); + } + Ok(()) + }) + .unwrap(); + s +} + +fn remember(s: &mut Session, settings: Value) { + s.edit_prefs(|p| p.dialogs.insert(CAF_WORKSPACE_PREFS.into(), settings)); +} + +/// Play `d` as a one-step action and return the result. +fn play(s: &mut Session, d: Descriptor) -> Value { + s.actions_mut().list = ActionList::new(); + s.actions_mut().list.push(load(d)).unwrap(); + let result = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(result["ran"], 1); + result +} + +/// Every layer's pixels, in stack order. +fn pixels(s: &Session) -> Vec> { + let doc = &s.active().unwrap().doc; + doc.layers.iter().map(|l| (0..64).map(|i| l.surface().unwrap().rgba(i % 8, i / 8)).collect()).collect() +} + +/// What running the command itself with `p` leaves. +fn native(p: Value) -> Vec> { + let mut s = session(); + s.execute(CMD, p).unwrap(); + pixels(&s) +} + +#[test] +fn an_empty_step_fills_a_new_layer_before_anything_is_remembered() { + let mut s = session(); + let layers = s.active().unwrap().doc.layers.len(); + let past = s.active().unwrap().history.past_len(); + play(&mut s, desc("null")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers + 1); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + assert_eq!(pixels(&s), native(json!({"output":"new"}))); + assert!(!s.prefs().dialogs.contains_key(CAF_WORKSPACE_PREFS), "playing remembers nothing"); +} + +#[test] +fn an_empty_step_plays_with_the_remembered_settings_and_steps_never_change_them() { + let settings = json!({"showOverlay":false,"opacity":20.0,"sampling":"rectangular","sampleAllLayers":false, + "colorAdaptation":"high","rotationAdaptation":"full","scale":true,"mirror":true,"output":"current"}); + let mut s = session(); + remember(&mut s, settings.clone()); + let layers = s.active().unwrap().doc.layers.len(); + play(&mut s, desc("null")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers, "remembered Current Layer"); + let used = json!({"sampling":"rectangular","sampleAllLayers":false,"colorAdaptation":"high", + "rotationAdaptation":"full","scale":true,"mirror":true,"output":"current"}); + assert_eq!(pixels(&s), native(used)); + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&settings)); + + // A step's own values are not remembered: the next empty step still uses Current Layer. + let mut s = session(); + remember(&mut s, settings.clone()); + let layers = s.active().unwrap().doc.layers.len(); + play(&mut s, workspace("cafSamplingRegionAuto", "cafColorAdaptationNone", "cafRotationAmountLow", "cafOutputToNewLayer")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers + 1); + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&settings)); + let next = crate::actions_cmds::playback_params(&s, CMD, &json!({MARK: true})).unwrap(); + assert_eq!(next["output"], "current"); +} + +#[test] +fn remembered_settings_fill_only_what_the_step_does_not_name() { + let resolve = |s: &Session, p: Value| crate::actions_cmds::playback_params(s, CMD, &p).unwrap(); + let mut s = crate::session(); + assert_eq!(resolve(&s, json!({MARK: true})), json!({"output":"new"})); + // Only the command's settings come over, never the overlay's. + remember(&mut s, json!({"showOverlay":true,"opacity":50.0,"color":[1,2,3],"excluded":true,"sampling":"auto","output":"duplicate"})); + assert_eq!(resolve(&s, json!({MARK: true})), json!({"sampling":"auto","output":"duplicate"})); + assert_eq!(resolve(&s, json!({MARK: true, "output": "current"})), json!({"sampling":"auto","output":"current"})); + // A mark that isn't `true` is dropped without bringing the remembered settings in. + assert_eq!(resolve(&s, json!({MARK: false, "output": "current"})), json!({"output":"current"})); + // Steps without the mark and other commands are left alone. + assert_eq!(resolve(&s, json!({"output":"current"})), json!({"output":"current"})); + let other = crate::actions_cmds::playback_params(&s, "edit.fill", &json!({MARK: true})).unwrap(); + assert_eq!(other, json!({MARK: true})); +} + +#[test] +fn damaged_remembered_settings_are_skipped_without_a_panic() { + let resolve = |s: &Session| crate::actions_cmds::playback_params(s, CMD, &json!({MARK: true})).unwrap(); + let mut s = crate::session(); + for damaged in [json!(3), json!(null), json!([]), json!({"output":5,"scale":"yes","sampling":true,"mirror":null})] { + remember(&mut s, damaged.clone()); + assert_eq!(resolve(&s), json!({"output":"new"}), "{damaged}"); + } + // A remembered value the command refuses fails the step with an error, not a panic. + let mut s = session(); + remember(&mut s, json!({"output":"sideways"})); + s.actions_mut().list = ActionList::new(); + s.actions_mut().list.push(load(desc("null"))).unwrap(); + let before = s.active().unwrap().doc.clone(); + let result = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(result.get("failed").is_some(), "{result}"); + assert_eq!(s.active().unwrap().doc, before); +} + +#[test] +fn folder_batch_plays_an_empty_step_with_the_remembered_settings() { + let dir = tempfile::tempdir().unwrap(); + let join = |name: &str| dir.path().join(name).to_string_lossy().into_owned(); + let mut source = session(); + source.execute("file.saveACopy", json!({"path": join("in.png")})).unwrap(); + let steps = json!([["select.rect", {"x":3,"y":3,"width":2,"height":2}], [CMD, {MARK: true}]]); + // The layer count of each output: Current Layer fills the background, New Layer adds one. + let layers = |s: &mut Session, out: &str| { + let result = s.execute("file.automate.batch", json!({"input":[join("in.png")],"output":join(out),"format":"psd","steps":steps})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + let bytes = std::fs::read(dir.path().join(out).join("in.psd")).unwrap(); + photocraft_io::import("in.psd", &bytes).unwrap().document.layers.len() + }; + let mut s = crate::session(); + assert_eq!(layers(&mut s, "default"), 2, "nothing remembered: a new layer"); + remember(&mut s, json!({"output":"current"})); + assert_eq!(layers(&mut s, "remembered"), 1, "the remembered Current Layer"); + // Playing in Batch remembers nothing in the caller either. + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&json!({"output":"current"}))); +} diff --git a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs index 3e30609ea2..958fd1961b 100644 --- a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs +++ b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs @@ -3,20 +3,42 @@ use super::descriptors::{desc, enm, jstr}; use super::fields::{Mapped, step}; use super::tables::lookup_back; use super::{D, Descriptor, Map, Value}; +use crate::EngineError; const CMD: &str = "edit.contentAwareFill"; const SOURCE: &str = "_atnCafDescriptor"; -// The measured row bounds these values; its ellipses are not additional enum bindings. -const SAMPLING: &[(&str, &str)] = &[("cafSamplingRegionRectangular", "rectangular")]; -const COLOR: &[(&str, &str)] = &[("cafColorAdaptationDefault", "default")]; -const ROTATION: &[(&str, &str)] = &[("cafRotationAmountNone", "none")]; -// Current Layer is also explicit in the primary Action Manager example cited in docs/atn.md. -const OUTPUT: &[(&str, &str)] = &[("cafOutputToNewLayer", "new"), ("cafOutputToCurrentLayer", "current")]; +// Every value the workspace showed when such a step was played with dialogs on (#14254). +const SAMPLING: &[(&str, &str)] = &[("cafSamplingRegionAuto", "auto"), ("cafSamplingRegionRectangular", "rectangular"), ("cafSamplingRegionCustom", "custom")]; +const COLOR: &[(&str, &str)] = &[ + ("cafColorAdaptationNone", "none"), + ("cafColorAdaptationDefault", "default"), + ("cafColorAdaptationHigh", "high"), + ("cafColorAdaptationVeryHigh", "veryHigh"), +]; +const ROTATION: &[(&str, &str)] = &[ + ("cafRotationAmountNone", "none"), + ("cafRotationAmountLow", "low"), + ("cafRotationAmountMedium", "medium"), + ("cafRotationAmountHigh", "high"), + ("cafRotationAmountFull", "full"), +]; +const OUTPUT: &[(&str, &str)] = &[("cafOutputToCurrentLayer", "current"), ("cafOutputToNewLayer", "new"), ("cafOutputToDuplicateLayer", "duplicate")]; const KEYS: &[&str] = &["cafSamplingRegion", "cafSampleAllLayers", "cafColorAdaptationLevel", "cafRotationAmount", "cafScale", "cafMirror", "cafOutput"]; const PARAMS: &[&str] = &["sampling", "sampleAllLayers", "colorAdaptation", "rotationAdaptation", "scale", "mirror", "output"]; +/// Marks a step recorded with an empty descriptor: it plays with the workspace's remembered +/// settings ([`caf_remembered`]) instead of fixed values. +const REMEMBERED: &str = "_atnCafRemembered"; +/// The `prefs.dialogs` key under which the Content-Aware Fill workspace remembers its settings. +pub const CAF_WORKSPACE_PREFS: &str = "edit.contentAwareFill.workspace"; -/// All seven settings are recorded. Missing keys have no measured Photoshop default here. +/// All seven settings are recorded, or none: an empty descriptor uses the remembered settings. +/// Other missing keys have no measured Photoshop default here. fn recorded(d: &Descriptor) -> Option { + if d.items.is_empty() { + let mut p = Map::new(); + p.insert(REMEMBERED.into(), true.into()); + return Some(Value::Object(p)); + } if d.items.len() != KEYS.len() || KEYS.iter().any(|name| d.items.iter().filter(|(key, _)| key.is(name)).count() != 1) { return None; } @@ -35,15 +57,24 @@ fn recorded(d: &Descriptor) -> Option { Some(Value::Object(p)) } -/// Write only represented native options, making their defaults explicit in all seven fields. +/// Write only represented native options, making their defaults explicit in all seven fields. A step without +/// `sampleAllLayers` is refused: the command then samples the composite when the layer is empty, which neither +/// recorded value says. fn descriptor(p: &Value) -> Option { let object = p.as_object()?; if !super::events::pixel_target(p) - || object.keys().any(|key| !PARAMS.contains(&key.as_str()) && !matches!(key.as_str(), "target" | "seed" | SOURCE)) + || object.keys().any(|key| !PARAMS.contains(&key.as_str()) && !matches!(key.as_str(), "target" | "seed" | SOURCE | REMEMBERED)) || p.get("seed").is_some_and(|seed| seed.as_u64() != Some(1)) { return None; } + if let Some(remembered) = p.get(REMEMBERED) { + // Values next to the mark would be dropped by an empty descriptor. + return (remembered.as_bool() == Some(true) && !PARAMS.iter().any(|param| object.contains_key(*param))).then(|| desc("null")); + } + if !object.contains_key(PARAMS[1]) { + return None; + } let enumeration = |key: &str, param: &str, table: &[(&str, &str)], default: &str| { let value = match p.get(param) { None => default, @@ -67,6 +98,33 @@ fn descriptor(p: &Value) -> Option { ) } +/// Why an empty recorded step refuses remembered Custom sampling ([`caf_remembered`]). The shell shows it translated. +pub const CAF_CUSTOM_AREA_NOT_REMEMBERED: &str = "This step plays with the remembered Content-Aware Fill settings, and their Custom sampling area isn't remembered. Fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again."; + +/// Resolve an empty recorded step: the remembered settings fill what the step doesn't name, and +/// before any were remembered it writes to a new layer. Playing never changes what is remembered. +/// Remembered Custom sampling is refused: its area is painted in the workspace, which keeps none +/// (Custom reopens empty), and the step must not sample another area instead. +pub(crate) fn caf_remembered(p: &mut Value, prefs: &crate::prefs::Preferences) -> Result<(), EngineError> { + let Some(object) = p.as_object_mut() else { return Ok(()) }; + if object.remove(REMEMBERED).and_then(|v| v.as_bool()) != Some(true) { + return Ok(()); + } + let saved = prefs.dialogs.get(CAF_WORKSPACE_PREFS); + for (param, flag) in PARAMS.iter().map(|param| (*param, matches!(*param, "sampleAllLayers" | "scale" | "mirror"))) { + // Only well-typed values: a damaged entry must not turn into another setting. + let value = saved.and_then(|v| v.get(param)).filter(|v| if flag { v.is_boolean() } else { v.is_string() }); + if let Some(value) = value.filter(|_| !object.contains_key(param)) { + object.insert(param.into(), value.clone()); + } + } + object.entry("output").or_insert_with(|| "new".into()); + if object.get("sampling").and_then(Value::as_str) == Some("custom") && !["area", "channel", "samplingStrokes"].iter().any(|key| object.contains_key(*key)) { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: CAF_CUSTOM_AREA_NOT_REMEMBERED.into() }); + } + Ok(()) +} + /// Import the verified seven-field form, retaining noncanonical wire data for an unchanged save. pub(super) fn caf_from(d: &Descriptor) -> Mapped { let Some(mut p) = recorded(d) else { return Mapped::Unsupported { harmless: false } }; diff --git a/crates/engine-core/src/cmd/channel_cmds.rs b/crates/engine-core/src/cmd/channel_cmds.rs index f5160db3f2..0c7619d0cb 100644 --- a/crates/engine-core/src/cmd/channel_cmds.rs +++ b/crates/engine-core/src/cmd/channel_cmds.rs @@ -119,6 +119,9 @@ mod targeting; mod tone_target; mod view; +#[cfg(test)] +mod undo_channel_target_tests; + use calc::{apply_image, calculations}; use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible}; use planes::edit_mode; @@ -147,8 +150,8 @@ pub(crate) use targeting::{ targeted_channel, }; pub use tone_target::{ToneTarget, resolve_tone_target}; -pub(crate) use view::fix_view; pub use view::{ChannelTarget, ChannelView, QuickMaskOptions, color_names, composite_name}; +pub(crate) use view::{fix_view, restore_view_after_undo}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine-core/src/cmd/channel_cmds/calc.rs b/crates/engine-core/src/cmd/channel_cmds/calc.rs index a72783de40..b086a8ba0e 100644 --- a/crates/engine-core/src/cmd/channel_cmds/calc.rs +++ b/crates/engine-core/src/cmd/channel_cmds/calc.rs @@ -2,6 +2,7 @@ use super::manage::gray_document; use super::planes::{channel_format, edit_mode, next_alpha_name, plane_surface, read_plane, tone}; use super::refs::{Blending, bad, doc_index, mask_plane, source, source_spec}; use super::targeting::{Target, is_channel_target, is_spot_target, target_of, target_surface}; +use super::view::{keep_view_for_undo, view_before_step}; use super::{AlphaChannel, ColorMode, EngineError, Result, SelectionMode, Session, Value, json, sel}; use photocraft_color::blend::blend_rgb; @@ -151,6 +152,7 @@ pub(super) fn calculations(s: &mut Session, p: &Value) -> Result { let name = p.get("name").and_then(Value::as_str).map(str::to_string); match p.get("result").and_then(Value::as_str).unwrap_or("newChannel") { "newChannel" => { + let before = view_before_step(s); let i = s.edit("Calculations", |doc, _| { let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha")); let area = doc.bounds(); @@ -158,6 +160,8 @@ pub(super) fn calculations(s: &mut Session, p: &Value) -> Result { doc.channels.push(AlphaChannel::new(name, plane_surface(&out, area, fmt))); Ok(doc.channels.len() - 1) })?; + // Undo targets and shows what was before, as after New Channel (#14683). + keep_view_for_undo(s, before); Ok(json!({ "channel": i })) } "newDocument" => { diff --git a/crates/engine-core/src/cmd/channel_cmds/manage.rs b/crates/engine-core/src/cmd/channel_cmds/manage.rs index 9c81381bf4..c213238210 100644 --- a/crates/engine-core/src/cmd/channel_cmds/manage.rs +++ b/crates/engine-core/src/cmd/channel_cmds/manage.rs @@ -2,7 +2,7 @@ use super::planes::{channel_format, color_count, edit_mode, next_alpha_name, pla use super::refs::{ChanRef, alpha_index, bad, doc_index, gray_plane, parse_ref}; use super::selection::{uniform, unselected_surface}; use super::targeting::target; -use super::view::{ChannelTarget, QuickMaskOptions, color_names, composite_name, fix_view, touch}; +use super::view::{ChannelTarget, QuickMaskOptions, color_names, composite_name, fix_view, keep_view_for_undo, touch, view_before_step}; use super::{ AlphaChannel, Color, ColorIndicates, ColorMode, DocState, Document, EngineError, Layer, PixelFormat, Result, Session, Surface, Value, json, list, sel, }; @@ -32,6 +32,7 @@ pub(super) fn new_channel(s: &mut Session, p: &Value) -> Result { let indicates = indicates_param(p.get("indicates")); let color = color_value("channel.new", p, "color")?; let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); + let before = view_before_step(s); let i = s.edit("New Channel", |doc, _| { let area = doc.bounds(); let fmt = channel_format(doc); @@ -53,7 +54,8 @@ pub(super) fn new_channel(s: &mut Session, p: &Value) -> Result { doc.channels.push(ch); Ok(doc.channels.len() - 1) })?; - // Photoshop targets and shows a new channel on its own. + // Photoshop targets and shows a new channel on its own; undo targets what was before. + keep_view_for_undo(s, before); target(s, ChannelTarget::Alpha(i)); Ok(json!({ "channel": i })) } diff --git a/crates/engine-core/src/cmd/channel_cmds/selection.rs b/crates/engine-core/src/cmd/channel_cmds/selection.rs index a49c551d2f..f5b1dc3f30 100644 --- a/crates/engine-core/src/cmd/channel_cmds/selection.rs +++ b/crates/engine-core/src/cmd/channel_cmds/selection.rs @@ -60,6 +60,23 @@ pub(super) fn save_selection(s: &mut Session, p: &Value) -> Result { Ok(json!({ "channel": i, "name": name, "document": di })) } +/// The history name of `select.loadSelection` with `p`. The Layers panel names its layer by id (a thumbnail +/// ⌘-click, Select Pixels), and those loads take Photoshop's names (#16786): `Selection Change` for a shape's +/// path or a vector mask, `Load Selection` for another layer's transparency or a layer mask. Calls that don't +/// name a layer by id (Select › Load Selection) keep their names. +fn load_label(doc: &Document, p: &Value) -> &'static str { + let channel = p.get("channel").and_then(|v| parse_ref(v, doc)); + let layer = p.get("layer").and_then(Value::as_u64).and_then(|id| doc.layer(super::LayerId(id))); + match (channel, layer) { + (Some(ChanRef::Transparency), Some(l)) if matches!(l.content, super::LayerContent::Shape(_)) => "Selection Change", + (Some(ChanRef::Transparency), Some(l)) if !l.is_group() => "Load Selection", + (Some(ChanRef::VectorMask), Some(l)) if l.vector_mask.is_some() => "Selection Change", + (Some(ChanRef::Transparency), _) => "Load Transparency", + (Some(ChanRef::LayerMask), None) => "Load Layer Mask", + _ => "Load Selection", + } +} + pub(super) fn load_selection(s: &mut Session, p: &Value) -> Result { let cmd = "select.loadSelection"; let mode = match operation(p, "operation") { @@ -89,11 +106,7 @@ pub(super) fn load_selection(s: &mut Session, p: &Value) -> Result { // Composite and colour channels load their luminosity / values, as ⌘-clicking them does. let plane = source(s, p, cmd, true)?.into_iter().next().ok_or_else(|| bad(cmd, "the channel has no pixels"))?; let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let label = match p.get("channel").and_then(|v| parse_ref(v, doc)) { - Some(ChanRef::Transparency) => "Load Transparency", - Some(ChanRef::LayerMask) => "Load Layer Mask", - _ => "Load Selection", - }; + let label = load_label(doc, p); let selected = s.edit(label, |doc, _| { doc.selection = sel::combine(doc.selection.as_ref(), &plane, doc.bounds(), mode); Ok(doc.selection.is_some()) diff --git a/crates/engine-core/src/cmd/channel_cmds/undo_channel_target_tests.rs b/crates/engine-core/src/cmd/channel_cmds/undo_channel_target_tests.rs new file mode 100644 index 0000000000..3eaa9cc078 --- /dev/null +++ b/crates/engine-core/src/cmd/channel_cmds/undo_channel_target_tests.rs @@ -0,0 +1,121 @@ +//! Undo of a step that targeted a new alpha channel brings back the channel view from before it: +//! the targeted colour channel and the eyes (#14683). + +use super::*; +use crate::channel_cmds::ChannelView; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 20})).unwrap(); + s +} + +fn view(s: &Session) -> ChannelView { + s.active().unwrap().channel_view.clone() +} + +/// Red targeted (shown alone), then `command`, then undo: Red is the target again and the only +/// colour channel shown, as before the command. +fn undo_returns_to_red(command: &str, params: Value) { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + let before = view(&s); + assert_eq!(before.target, ChannelTarget::Color(0)); + s.execute(command, params).unwrap(); + assert!(s.undo()); + assert!(doc(&s).channels.is_empty()); + let after = view(&s); + assert_eq!((after.target, &after.color_hidden), (before.target, &before.color_hidden), "{command}"); + assert_eq!(channels_json(s.active().unwrap()), channels_json_of(before, &s), "{command}"); +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +/// The Channels panel as `view` would show the current document. +fn channels_json_of(view: ChannelView, s: &Session) -> Value { + let mut st = s.active().unwrap().clone(); + st.channel_view = view; + channels_json(&st) +} + +#[test] +fn undo_of_new_channel_targets_the_colour_channel_again() { + undo_returns_to_red("channel.new", json!({})); +} + +#[test] +fn undo_of_calculations_new_channel_targets_the_colour_channel_again() { + undo_returns_to_red("image.calculations", json!({"result": "newChannel"})); +} + +/// From the composite, undo returns to the composite with every colour channel shown, as today. +#[test] +fn undo_from_the_composite_keeps_working() { + for command in ["channel.new", "image.calculations"] { + let mut s = session(); + let before = view(&s); + s.execute(command, json!({})).unwrap(); + assert!(s.undo()); + let after = view(&s); + assert_eq!(after.target, ChannelTarget::Composite, "{command}"); + assert_eq!(channels_json(s.active().unwrap()), channels_json_of(before, &s), "{command}"); + } +} + +/// Redo brings the new channel back, and undo after it returns to Red again. +#[test] +fn undo_after_redo_returns_to_red_again() { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + s.execute("channel.new", json!({})).unwrap(); + assert!(s.undo()); + assert!(s.redo()); + assert_eq!(doc(&s).channels.len(), 1); + assert!(s.undo()); + assert_eq!(view(&s).target, ChannelTarget::Color(0)); +} + +/// Other commands' undo leaves the channel view as it is: a selection made with Red targeted, +/// then Green targeted, undone, keeps Green. +#[test] +fn other_steps_do_not_restore_the_view() { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + s.execute("channel.target", json!({"channel": "green"})).unwrap(); + assert!(s.undo()); + assert_eq!(view(&s).target, ChannelTarget::Color(1)); +} + +/// New Channel from Red, undone, then a selection made from the same state with Green targeted: +/// undo of the selection lands on the state New Channel started from but undoes the selection, so +/// Green stays targeted. +#[test] +fn undo_of_a_later_step_from_the_same_state_keeps_the_target() { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + s.execute("channel.new", json!({})).unwrap(); + assert!(s.undo()); + s.execute("channel.target", json!({"channel": "green"})).unwrap(); + s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + assert!(s.undo()); + assert_eq!(view(&s).target, ChannelTarget::Color(1)); +} + +/// The remembered view stays with the New Channel step: every undo of it, after any number of +/// redos, returns to Red. +#[test] +fn every_undo_of_new_channel_returns_to_red() { + let mut s = session(); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + s.execute("channel.new", json!({})).unwrap(); + for round in 0..3 { + assert!(s.undo()); + assert_eq!(view(&s).target, ChannelTarget::Color(0), "undo {round}"); + s.execute("channel.target", json!({"channel": "blue"})).unwrap(); + assert!(s.redo()); + assert_eq!(doc(&s).channels.len(), 1); + } +} diff --git a/crates/engine-core/src/cmd/channel_cmds/view.rs b/crates/engine-core/src/cmd/channel_cmds/view.rs index 02d70cc16b..fbd5157f4b 100644 --- a/crates/engine-core/src/cmd/channel_cmds/view.rs +++ b/crates/engine-core/src/cmd/channel_cmds/view.rs @@ -1,5 +1,5 @@ use super::planes::color_count; -use super::{ColorMode, DocState, Document, Serialize}; +use super::{ColorMode, DocState, Document, Serialize, Session}; // --------------------------------------------------------------------------------------------- // View state @@ -155,3 +155,34 @@ pub fn composite_name(mode: ColorMode) -> &'static str { _ => "RGB", } } + +// --------------------------------------------------------------------------------------------- +// Undo of a step that targets the channel it creates + +/// Before New Channel or Calculations (Result: New Channel), which target the channel they make: +/// the history state the step starts from and the channel view then. +pub(super) fn view_before_step(s: &Session) -> Option<(u64, ChannelView)> { + let st = s.active()?; + Some((st.history.row_id(st.history.past_len())?, st.channel_view.clone())) +} + +/// After that step: undoing it (leaving the state it made for the one it started from) brings +/// `before`'s view back (#14683). Kept for the step, so undo after redo brings it back again. The +/// views of steps history no longer holds are dropped. +pub(super) fn keep_view_for_undo(s: &mut Session, before: Option<(u64, ChannelView)>) { + let (Some(st), Some((from, view))) = (s.active_mut(), before) else { return }; + let Some(to) = st.history.row_id(st.history.past_len()) else { return }; + let history = &st.history; + st.undo_channel_views.retain(|(kept_from, kept_to, _)| *kept_to != to && history.row_of(*kept_from).is_some() && history.row_of(*kept_to).is_some()); + st.undo_channel_views.push((from, to, view)); +} + +/// Undo just left the state `left` for the current one: when that undid a step with a kept view, +/// target and show the channels it did. +pub(crate) fn restore_view_after_undo(st: &mut DocState, left: Option) { + let Some(left) = left else { return }; + let Some(id) = st.history.row_id(st.history.past_len()) else { return }; + let Some((_, _, view)) = st.undo_channel_views.iter().find(|(from, to, _)| *from == id && *to == left) else { return }; + st.channel_view = view.clone(); + fix_view(st); +} diff --git a/crates/engine-core/src/cmd/extra_cmds.rs b/crates/engine-core/src/cmd/extra_cmds.rs index aadcfc89ca..6aa06a7c00 100644 --- a/crates/engine-core/src/cmd/extra_cmds.rs +++ b/crates/engine-core/src/cmd/extra_cmds.rs @@ -550,7 +550,16 @@ pub fn background_to_layer(doc: &mut photocraft_doc::Document, id: photocraft_do fn toggle_mask(s: &mut Session, p: &Value, key: &str) -> Result { let id = layer_param(s, p)?; - let label = if key == "enabled" { "Enable/Disable Layer Mask" } else { "Link/Unlink Layer Mask" }; + // A call that says the direction (the Layers panel's ⇧-click and chain) is named by it, as in Photoshop + // (#16786); a plain toggle (Layer › Layer Mask) keeps its two-way name. + let label = match (key, p.get(key).and_then(Value::as_bool)) { + ("enabled", Some(true)) => "Enable Layer Mask", + ("enabled", Some(false)) => "Disable Layer Mask", + ("enabled", None) => "Enable/Disable Layer Mask", + (_, Some(true)) => "Link Mask", + (_, Some(false)) => "Unlink Mask", + (_, None) => "Link/Unlink Layer Mask", + }; let v = s.edit(label, |doc, _| { let m = doc.layer_mut(id).and_then(|l| l.mask.as_mut()).ok_or(EngineError::Other("the layer has no layer mask".into()))?; let slot = if key == "enabled" { &mut m.enabled } else { &mut m.linked }; diff --git a/crates/engine-core/src/cmd/file_cmds.rs b/crates/engine-core/src/cmd/file_cmds.rs index d5d8209fc9..a810480736 100644 --- a/crates/engine-core/src/cmd/file_cmds.rs +++ b/crates/engine-core/src/cmd/file_cmds.rs @@ -434,7 +434,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,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"iccProfile":bool? (Include ICC Profile: false, no profile in any file; true, the document's profile, or its mode's working profile when it has none, PSD included, and none in a CMYK document's PNG; unset, as before),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":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),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##, native_doc, layers_to_files ), @@ -576,3 +576,7 @@ mod aces_exr_tests { } } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "file_cmds/layers_to_files_icc_tests.rs"] +mod layers_to_files_icc_tests; diff --git a/crates/engine-core/src/cmd/file_cmds/batch_run.rs b/crates/engine-core/src/cmd/file_cmds/batch_run.rs index 97b0d9fdf9..6506ce7fdc 100644 --- a/crates/engine-core/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine-core/src/cmd/file_cmds/batch_run.rs @@ -1030,6 +1030,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let authorize = s.authorize; let raw_ppi = super::open::raw_open_resolution(s); let action_prefs = s.prefs().actions.clone(); + // An empty recorded Content-Aware Fill step plays with the remembered workspace settings. + let caf_workspace = s.prefs().dialogs.get(crate::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); let prefs = s.prefs.clone(); let color_settings = s.color().settings.clone(); let raw_settings = s.batch_raw_open.as_ref().unwrap_or(&s.prefs().raw_defaults).clone(); @@ -1165,7 +1167,13 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { scratch.recording = run.clone(); scratch.recording.playback_steps = carried.get(); scratch.recording.script_steps = script_steps.get(); - scratch.prefs.edit(|prefs| prefs.actions = action_prefs.clone()); + scratch.prefs.edit(|prefs| { + prefs.actions = action_prefs.clone(); + // Only this entry: the scratch session keeps every other remembered dialog value at its default. + if let Some(workspace) = &caf_workspace { + prefs.dialogs.insert(crate::atn_cmds::CAF_WORKSPACE_PREFS.into(), workspace.clone()); + } + }); let owns_history = scratch.action_history.is_none() && scratch.prefs().actions.create_single_history_state; if owns_history { crate::actions_cmds::begin_document_history(scratch, &action_name); diff --git a/crates/engine-core/src/cmd/file_cmds/export.rs b/crates/engine-core/src/cmd/file_cmds/export.rs index b563a5be13..d7724ec064 100644 --- a/crates/engine-core/src/cmd/file_cmds/export.rs +++ b/crates/engine-core/src/cmd/file_cmds/export.rs @@ -62,7 +62,10 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. let _authorization = crate::jobs::render_authorization_scope(s.authorize); - let save = SaveOpts::from_params(s, p, cmd)?; + let mut save = SaveOpts::from_params(s, p, cmd)?; + // Include ICC Profile (#13973); unset, each file embeds what it did before. + let icc = super::save::tiff_bool_param(p, "iccProfile", cmd)?; + save.embed_icc = icc; let d = s.active().ok_or(EngineError::NoDocument)?; if layers_to_files_needs_more_layers(&d.doc) { return Err(EngineError::Other("Layers to Files needs a document with multiple layers.".into())); @@ -109,6 +112,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& // The prefix is optional; only the layer name needs the empty-name fallback. let prefix_part = if prefix.is_empty() { String::new() } else { part(&prefix) }; let name = format!("{prefix_part}_{:04}_{}.{format}", index, part(&l.name)); + let save = include_icc(&mut one, &format, icc, save); let (bytes, _warnings) = encode(&one, &name, save)?; write(&name, &bytes)?; report.files.push(name); @@ -116,6 +120,20 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& Ok(report) } +/// Include ICC Profile for one layer file: off, no profile; on, the document's profile, or the one +/// its colours are taken to be in when it has none (PSD included), except that a CMYK document's +/// PNG (written as RGB) carries none, as measured. Unset changes nothing. Off only leaves the +/// profile out of the file (`save.embed_icc`): the document keeps it, since its colours (a CMYK +/// document's conversion to RGB) are read through it. +fn include_icc(one: &mut Document, format: &str, icc: Option, mut save: SaveOpts) -> SaveOpts { + match icc { + Some(true) if format == "png" && one.mode == ColorMode::Cmyk => save.embed_icc = Some(false), + Some(true) if one.icc_profile.is_none() => one.icc_profile = Some(crate::color_cmds::working_profile(one.mode).to_bytes()), + _ => {} + } + save +} + /// Adjustment layers that can be represented as an RGB-only LUT, in document stack order. /// A LUT has no spatial coordinates, so masks and clipping geometry are deliberately stripped /// at bake time. Group adjustments need their enclosing group's compositing semantics and are diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs new file mode 100644 index 0000000000..19f2b9c24e --- /dev/null +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs @@ -0,0 +1,183 @@ +//! Layers to Files: Include ICC Profile (#13973). `iccProfile: false` writes no profile in PNG, +//! JPEG, TIFF or PSD files; `true` embeds the document's profile (a CMYK document's JPEG its CMYK +//! profile, its PNG none); unset keeps what the export wrote before. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; + +fn session(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 6, "mode": mode, "depth": depth, "background": "backgroundColor", "backgroundColor": [0.8, 0.1, 0.1]})) + .unwrap(); + // One normal layer: Layers to Files refuses a Background-only document (#13968). + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s +} + +/// The colour space of each written file's embedded profile (`None`: no profile), by extension. +fn profiles(s: &mut Session, format: &str, extra: Value) -> Vec<(String, Option)> { + let dir = tempfile::tempdir().unwrap(); + let mut p = json!({"dir": dir.path().to_string_lossy(), "prefix": "t", "format": format}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("file.export.layersToFiles", p).unwrap(); + r["files"] + .as_array() + .unwrap() + .iter() + .map(|f| { + let path = f.as_str().unwrap(); + let bytes = std::fs::read(path).unwrap(); + let doc = photocraft_io::import(path, &bytes).unwrap().document; + let space = doc.icc_profile.map(|icc| String::from_utf8_lossy(icc.get(16..20).unwrap()).trim().to_string()); + (format!("{:?}", doc.mode), space) + }) + .collect() +} + +const FORMATS: [&str; 4] = ["png", "jpg", "tif", "psd"]; + +/// RGB and CMYK documents at 8 and 16 bits. +const DOCS: [(&str, u32); 4] = [("rgb", 8), ("rgb", 16), ("cmyk", 8), ("cmyk", 16)]; + +fn one(s: &mut Session, format: &str, extra: Value) -> (String, Option) { + let files = profiles(s, format, extra); + assert_eq!(files.len(), 1, "{format}: one layer, one file"); + files.into_iter().next().unwrap() +} + +#[test] +fn off_writes_no_profile() { + for (mode, depth) in DOCS { + let mut s = session(mode, depth); + for format in FORMATS { + assert_eq!(one(&mut s, format, json!({"iccProfile": false})).1, None, "{mode}{depth} {format}"); + } + } +} + +#[test] +fn on_embeds_the_documents_profile() { + for depth in [8, 16] { + let mut s = session("rgb", depth); + for format in FORMATS { + assert_eq!(one(&mut s, format, json!({"iccProfile": true})), ("Rgb".into(), Some("RGB".into())), "rgb{depth} {format}"); + } + } + // The document's own profile, not a stand-in, when it has one. + let mut s = session("rgb", 8); + let own = crate::color_cmds::working_profile(ColorMode::Rgb).to_bytes(); + let dir = tempfile::tempdir().unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "format": "jpg", "iccProfile": true})).unwrap(); + let path = r["files"][0].as_str().unwrap(); + let embedded = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document.icc_profile; + assert_eq!(embedded.as_deref(), Some(&*own)); +} + +#[test] +fn a_cmyk_documents_jpeg_keeps_its_cmyk_profile_and_its_png_has_none() { + for depth in [8, 16] { + let mut s = session("cmyk", depth); + let on = json!({"iccProfile": true}); + assert_eq!(one(&mut s, "jpg", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} jpg"); + assert_eq!(one(&mut s, "tif", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} tif"); + assert_eq!(one(&mut s, "psd", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} psd"); + assert_eq!(one(&mut s, "png", on), ("Rgb".into(), None), "cmyk{depth} png"); + } +} + +#[test] +fn unset_keeps_what_the_export_wrote_before() { + // As main wrote them before the param: flat RGB files and a CMYK document's PNG carry the + // RGB working profile; PSD files and CMYK JPEG and TIFF files carry none. + let rgb = Some("RGB".to_string()); + for depth in [8, 16] { + let mut s = session("rgb", depth); + let got: Vec<_> = FORMATS.iter().map(|f| one(&mut s, f, json!({})).1).collect(); + assert_eq!(got, vec![rgb.clone(), rgb.clone(), rgb.clone(), None], "rgb{depth}"); + let mut s = session("cmyk", depth); + let got: Vec<_> = FORMATS.iter().map(|f| one(&mut s, f, json!({})).1).collect(); + assert_eq!(got, vec![rgb.clone(), None, None, None], "cmyk{depth}"); + // `null` is unset too. + assert_eq!(one(&mut s, "png", json!({"iccProfile": null})).1, rgb, "cmyk{depth} null"); + } +} + +#[test] +fn a_bad_value_is_an_error_and_writes_nothing() { + let mut s = session("rgb", 8); + for bad in [json!("no"), json!(0), json!([false]), json!({})] { + let dir = tempfile::tempdir().unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "format": "png", "iccProfile": bad})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "{bad}: nothing written"); + } + assert_eq!(s.active().unwrap().doc.icc_profile, None, "the document is untouched"); +} + +/// The pixels of each written file, decoded (RGBA, 0..1), and whether it carries a profile. +fn pixels(s: &mut Session, format: &str, extra: Value) -> Vec<(Vec<[f32; 4]>, bool)> { + let dir = tempfile::tempdir().unwrap(); + let mut p = json!({"dir": dir.path().to_string_lossy(), "prefix": "t", "format": format}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("file.export.layersToFiles", p).unwrap(); + r["files"] + .as_array() + .unwrap() + .iter() + .map(|f| { + let path = f.as_str().unwrap(); + let doc = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document; + let icc = doc.icc_profile.is_some(); + (photocraft_compose::flatten(&doc).px.to_vec(), icc) + }) + .collect() +} + +#[test] +fn off_keeps_a_cmyk_documents_own_profile_for_its_colours() { + // A CMYK document tagged with a profile other than the built-in coated one, whose layer + // needs compositing (50 % opacity): its colours are converted through its own profile + // whether or not the file carries it (CodeRabbit on #16653). + for depth in [8, 16] { + let mut s = session("cmyk", depth); + s.execute("edit.assignProfile", json!({"profile": "coated-fogra39"})).unwrap(); + s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); + let on = pixels(&mut s, "png", json!({"iccProfile": true})); + let off = pixels(&mut s, "png", json!({"iccProfile": false})); + let unset = pixels(&mut s, "png", json!({})); + assert_eq!(off[0].0, on[0].0, "cmyk{depth}: the same pixels with iccProfile false and true"); + assert_eq!(off[0].0, unset[0].0, "cmyk{depth}: the same pixels with iccProfile false and unset"); + for format in FORMATS { + assert!(pixels(&mut s, format, json!({"iccProfile": false})).iter().all(|(_, icc)| !icc), "cmyk{depth} {format}: no profile"); + } + let layered = pixels(&mut s, "tif", json!({"iccProfile": false, "tiffLayers": true})); + assert!(layered.iter().all(|(_, icc)| !icc), "cmyk{depth} layered tif: no profile"); + assert!(s.active().unwrap().doc.icc_profile.is_some(), "the document keeps its profile"); + } +} + +/// An Indexed Color document with an RGB profile: `iccProfile: false` writes no profile in any file, +/// the PSD included, which is written over its colour table (CodeRabbit on #16653), and the +/// layered TIFF; `true` keeps it in the PSD. +#[test] +fn an_indexed_documents_files_follow_the_setting() { + let mut s = session("rgb", 8); + s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap(); + // The conversion flattens: a normal layer again (#13968). + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.mode, ColorMode::Indexed); + assert!(doc.icc_profile.is_some(), "the document keeps its profile"); + assert!(doc.layers.iter().any(|l| !doc.is_background(l.id)), "a layer to export"); + for format in ["png", "jpg", "tif", "psd", "bmp"] { + assert!(profiles(&mut s, format, json!({"iccProfile": false})).iter().all(|(_, icc)| icc.is_none()), "indexed {format}: no profile"); + } + let layered = profiles(&mut s, "tif", json!({"iccProfile": false, "tiffLayers": true})); + assert!(layered.iter().all(|(_, icc)| icc.is_none()), "indexed layered tif: no profile"); + assert_eq!(one(&mut s, "psd", json!({"iccProfile": true})).1, Some("RGB".into()), "indexed psd: the profile"); +} diff --git a/crates/engine-core/src/cmd/image_cmds.rs b/crates/engine-core/src/cmd/image_cmds.rs index ad5178fbae..fe3e4c17a9 100644 --- a/crates/engine-core/src/cmd/image_cmds.rs +++ b/crates/engine-core/src/cmd/image_cmds.rs @@ -1254,6 +1254,11 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { reidentify_copied_layers(&mut doc); let name = doc.name.clone(); let index = s.add_document(doc, None); + if let Some(st) = s.active_mut() { + st.history.set_current_label("Duplicate Image"); + // The copy has never been saved; closing it must ask before discarding its content. + st.saved_revision = 0; + } Ok(json!({ "document": index, "name": name })) } @@ -1350,6 +1355,10 @@ mod canvas_size_relative_percent_tests; #[cfg(test)] mod canvas_size_selection_tests; +#[cfg(test)] +#[path = "image_cmds/duplicate_history_tests.rs"] +mod duplicate_history_tests; + #[cfg(test)] #[path = "image_size_drops_selection_tests.rs"] mod image_size_drops_selection_tests; diff --git a/crates/engine-core/src/cmd/image_cmds/duplicate_history_tests.rs b/crates/engine-core/src/cmd/image_cmds/duplicate_history_tests.rs new file mode 100644 index 0000000000..ebd56be16e --- /dev/null +++ b/crates/engine-core/src/cmd/image_cmds/duplicate_history_tests.rs @@ -0,0 +1,152 @@ +//! #14597: a duplicate starts with its own history baseline and must be saved before closing. + +use serde_json::{Value, json}; +use std::sync::Arc; + +use crate::Session; + +fn layered_source(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8, "name": "oracle", "background": "white", "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap(); + s.edit("fill", |doc, _| { + let bounds = doc.bounds(); + let surface = doc.layers.last_mut().unwrap().surface_mut().unwrap(); + surface.fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn open_png(s: &mut Session) { + let img = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, vec![128; 8 * 8 * 3]).unwrap(); + let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + crate::file_cmds::open_bytes_as(s, "oracle.png", &bytes, None, Some("oracle.png".into())).unwrap(); +} + +fn history(s: &Session) -> Value { + crate::inspect::document(s.active().unwrap()) +} + +#[test] +fn layered_and_merged_copies_have_one_duplicate_state_under_their_named_snapshot() { + for depth in [8, 16, 32] { + for merged in [false, true] { + for name in [None, Some("My Dup")] { + let mut s = layered_source(depth); + let mut params = json!({"mergedOnly": merged}); + if let Some(name) = name { + params["name"] = json!(name); + } + s.execute("image.duplicate", params).unwrap(); + let copy = history(&s); + assert_eq!(copy["history"], json!(["Duplicate Image"]), "depth={depth}, merged={merged}, name={name:?}"); + assert_eq!(copy["snapshots"], json!([{"id": 0, "name": name.unwrap_or("oracle copy")}])); + assert_eq!(copy["canUndo"], false); + assert_eq!(copy["canRedo"], false); + assert_eq!(copy["historySource"], json!({"state": 0, "label": "Duplicate Image"})); + assert_eq!(s.active().unwrap().doc.layers.len(), if merged { 1 } else { 2 }); + } + } + } +} + +#[test] +fn unsaved_copies_refuse_ask_but_allow_explicit_discard() { + for depth in [8, 16, 32] { + for merged in [false, true] { + let mut s = layered_source(depth); + let source = s.active().unwrap().doc.clone(); + s.execute("image.duplicate", json!({"mergedOnly": merged})).unwrap(); + let copy = s.active().unwrap(); + let id = copy.doc.id; + assert!(copy.is_dirty(), "depth={depth}, merged={merged}"); + assert!(copy.path.is_none()); + assert_eq!(crate::inspect::session(&s)["documents"][1]["dirty"], true); + let err = s.execute("file.close", json!({"save": "ask"})).unwrap_err(); + assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}"); + assert!(err.to_string().contains("unsaved changes"), "{err}"); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.active().unwrap().doc.id, id); + assert!(s.active().unwrap().is_dirty()); + s.execute("file.close", json!({"save": "discard"})).unwrap(); + assert_eq!(s.documents().len(), 1); + assert!(Arc::ptr_eq(&s.active().unwrap().doc, &source)); + } + } +} + +#[test] +fn duplicating_leaves_clean_and_dirty_sources_and_their_history_unchanged() { + for dirty in [false, true] { + for merged in [false, true] { + let mut s = crate::session(); + open_png(&mut s); + if dirty { + s.execute("layer.new.layer", json!({})).unwrap(); + } + let source = s.active().unwrap(); + assert_eq!(source.is_dirty(), dirty); + let before = crate::inspect::document(source); + let doc = source.doc.clone(); + let revisions = (source.revision, source.saved_revision); + s.execute("image.duplicate", json!({"mergedOnly": merged})).unwrap(); + let source = &s.documents()[0]; + assert_eq!(crate::inspect::document(source), before); + assert!(Arc::ptr_eq(&source.doc, &doc)); + assert_eq!((source.revision, source.saved_revision), revisions); + assert_eq!(source.is_dirty(), dirty); + } + } +} + +#[test] +fn new_and_opened_documents_keep_their_clean_initial_states_next_to_a_duplicate() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + open_png(&mut s); + s.execute("image.duplicate", json!({})).unwrap(); + for (source, label) in s.documents()[..2].iter().zip(["New", "Open"]) { + assert_eq!(source.history.entries(), [label]); + assert!(!source.is_dirty()); + } + assert_eq!(s.documents()[1].path.as_deref(), Some("oracle.png")); +} + +#[test] +fn editing_undoing_and_redoing_a_copy_preserves_its_unsaved_duplicate_baseline() { + for merged in [false, true] { + let mut s = layered_source(8); + s.execute("image.duplicate", json!({"mergedOnly": merged})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(history(&s)["history"], json!(["Duplicate Image", "New Layer"])); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(history(&s)["history"], json!(["Duplicate Image"])); + assert!(s.active().unwrap().is_dirty()); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(history(&s)["history"], json!(["Duplicate Image", "New Layer"])); + assert!(s.active().unwrap().is_dirty()); + } +} + +#[test] +fn saving_a_duplicate_clears_its_dirty_mark_and_allows_ask_to_close() { + let dir = tempfile::tempdir().unwrap(); + for merged in [false, true] { + let path = dir.path().join(format!("copy-{merged}.pcraft")); + let mut s = layered_source(8); + s.execute("image.duplicate", json!({"mergedOnly": merged})).unwrap(); + assert!(s.active().unwrap().is_dirty()); + let saved_path = path.to_str().unwrap(); + crate::file_cmds::save_doc(&s.active().unwrap().doc, saved_path, None).unwrap(); + // Save As is shell-owned; finish the successful write through its engine API. + s.active_mut().unwrap().saved_to(saved_path.into()); + assert!(path.is_file()); + assert!(!s.active().unwrap().is_dirty()); + assert_eq!(s.active().unwrap().path.as_deref(), path.to_str()); + assert_eq!(history(&s)["history"], json!(["Duplicate Image"])); + s.execute("file.close", json!({"save": "ask"})).unwrap(); + assert_eq!(s.documents().len(), 1); + } +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds.rs b/crates/engine-core/src/cmd/layer_multi_cmds.rs index a308da2541..e74f50849d 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds.rs @@ -158,8 +158,8 @@ pub fn specs() -> Vec { &["Layer", "New"], None, r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, - has_layer, - group_layers + structure::can_group_from_layers, + structure::group_from_layers ), spec!("layer.arrange.reverse", "Reverse", &["Layer", "Arrange"], None, "{}", two_plus, |s, _| reverse(s)), spec!( @@ -183,3 +183,6 @@ mod layers_panel_parity_tests; #[cfg(test)] mod tile_damage_tests; + +#[cfg(test)] +mod group_from_layers_background_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs new file mode 100644 index 0000000000..cd25687371 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs @@ -0,0 +1,112 @@ +//! Group from Layers is refused while the Background is among the selected layers (#14709), as +//! the menu rows already grey it. Layer > Group Layers keeps grouping it (not measured). + +use super::*; + +/// A 32 x 32 document with a white Background and the pixel layers Red, Green and Blue above it. +fn session() -> (Session, LayerId, [LayerId; 3]) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); + let bg = s.active().unwrap().doc.layers[0].id; + assert!(s.active().unwrap().doc.is_background(bg)); + let ids = ["Red", "Green", "Blue"].map(|name| LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap())); + (s, bg, ids) +} + +fn select(s: &mut Session, ids: &[LayerId], active: LayerId) { + set_selection(s, ids.to_vec(), Some(active), Some(active)).unwrap(); +} + +/// Everything a refused command must leave alone: the layer tree, the selection and the history. +fn snapshot(s: &Session) -> (photocraft_doc::layer_tree::LayerTree, Vec, Option, Vec) { + let d = s.active().unwrap(); + (d.doc.layers.clone(), d.selected_layers().to_vec(), d.active_layer, d.history.entries()) +} + +fn enabled(s: &Session) -> std::result::Result<(), String> { + (crate::commands::find("layer.new.groupFromLayers").unwrap().enabled)(s) +} + +fn refused(s: &mut Session, params: Value) { + let before = snapshot(s); + assert!(s.execute("layer.new.groupFromLayers", params.clone()).is_err(), "{params} must be refused"); + assert!(snapshot(s) == before, "{params} changed the document"); + assert!(s.active().unwrap().doc.background().is_some(), "the Background is still there"); +} + +#[test] +fn the_background_alone_is_refused() { + let (mut s, bg, _) = session(); + select(&mut s, &[bg], bg); + assert!(enabled(&s).is_err(), "disabled with the Background selected"); + refused(&mut s, json!({})); + refused(&mut s, json!({"name": "Set", "color": "red", "mode": "normal", "opacity": 50})); +} + +#[test] +fn the_background_with_other_layers_is_refused() { + let (mut s, bg, [red, green, _]) = session(); + for active in [red, bg] { + select(&mut s, &[bg, red], active); + assert!(enabled(&s).is_err(), "disabled with the Background and Red selected"); + refused(&mut s, json!({})); + } + select(&mut s, &[bg, red, green], green); + refused(&mut s, json!({})); +} + +#[test] +fn an_explicit_background_layer_is_refused() { + let (mut s, bg, [red, _, blue]) = session(); + select(&mut s, &[blue], blue); + refused(&mut s, json!({"layer": bg.0})); + select(&mut s, &[red, blue], red); + refused(&mut s, json!({"layer": bg.0})); + select(&mut s, &[bg], bg); + refused(&mut s, json!({"layer": bg.0})); +} + +#[test] +fn a_background_only_document_is_refused() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(enabled(&s).is_err()); + refused(&mut s, json!({})); +} + +fn children(s: &Session, group: LayerId) -> Vec { + s.active().unwrap().doc.layer(group).unwrap().children().unwrap().iter().map(|l| l.id).collect() +} + +#[test] +fn layers_without_the_background_still_group() { + let (mut s, bg, [red, green, blue]) = session(); + select(&mut s, &[blue], blue); + assert!(enabled(&s).is_ok()); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![blue]); + + select(&mut s, &[red, green], green); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![red, green]); + assert!(s.active().unwrap().doc.is_background(bg), "the Background stays"); +} + +#[test] +fn an_explicit_layer_other_than_the_background_still_groups() { + let (mut s, bg, [red, _, blue]) = session(); + select(&mut s, &[blue], blue); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({"layer": red.0})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![red]); + assert!(s.active().unwrap().doc.is_background(bg)); +} + +/// Layer > Group Layers with the Background selected is not measured: it keeps today's result. +#[test] +fn group_layers_keeps_grouping_the_background() { + let (mut s, bg, [red, ..]) = session(); + select(&mut s, &[bg, red], red); + let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![bg, red]); +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs index 967fff2f55..bcd49eafdf 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs @@ -111,6 +111,32 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { Ok(()) } +/// Group from Layers is greyed while the Background is among the selected layers, as in the +/// menus (#14709). +pub(super) fn can_group_from_layers(s: &Session) -> std::result::Result<(), String> { + super::has_layer(s)?; + let d = s.active().ok_or("no document open")?; + if d.selected_layers().iter().any(|id| d.doc.is_background(*id)) { + return Err("the Background layer can't go into a group".into()); + } + Ok(()) +} + +/// Group from Layers: [`group_layers`], refused with the Background among the layers it would +/// move, also when the `layer` param names it (#14709). Group Layers (⌘G) is not measured and +/// keeps grouping it. +pub(super) fn group_from_layers(s: &mut Session, p: &Value) -> Result { + let ids = match crate::commands::explicit_layer(s, p)? { + Some(id) => vec![id], + None => selected(s), + }; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + if ids.iter().any(|id| doc.is_background(*id)) { + return Err(EngineError::Other("the Background layer can't go into a group".into())); + } + group_layers(s, p) +} + /// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves /// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is /// preserved. The New Group dialog's colour, mode and opacity are set in the same history step. diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs index c690b0d0ae..7d915f0eb2 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs @@ -1014,7 +1014,8 @@ fn a_locked_group_keeps_a_grouped_background_locked() { let mut s = session(8); let bg = doc(&s).layers[0].id; s.execute("layer.select", json!({"layer": bg.0})).unwrap(); - let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + // Group from Layers refuses the Background (#14709); Group Layers still groups it. + let g = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); s.execute("layer.select", json!({"layer": bg.0})).unwrap(); for (cmd, p) in [ diff --git a/crates/engine-core/src/cmd/ops.rs b/crates/engine-core/src/cmd/ops.rs index 7e08493d68..e892c43325 100644 --- a/crates/engine-core/src/cmd/ops.rs +++ b/crates/engine-core/src/cmd/ops.rs @@ -99,7 +99,8 @@ fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option Result { let bad = |m: &str| EngineError::BadParams { cmd: "layer.layerMask.moveTo".into(), msg: m.into() }; let from = layer_param(s, p)?; @@ -109,8 +110,7 @@ pub(super) fn move_mask(s: &mut Session, p: &Value) -> Result { if from == to { return Err(bad("the mask is already on that layer")); } - let label = if copy { "Copy Layer Mask" } else { "Move Layer Mask" }; - s.edit(label, |doc, _| { + s.edit("Add Layer Mask", |doc, _| { let mask = doc.layer(from).ok_or(EngineError::NoLayer(from))?.mask.clone().ok_or_else(|| bad("the layer has no layer mask"))?; if doc.layer(to).ok_or(EngineError::NoLayer(to))?.mask.is_some() && !replace { return Err(bad("the layer already has a layer mask (pass `replace`)")); diff --git a/crates/engine-core/src/cmd/vector_cmds/vector_mask.rs b/crates/engine-core/src/cmd/vector_cmds/vector_mask.rs index 34abf1eab0..a03de7ff50 100644 --- a/crates/engine-core/src/cmd/vector_cmds/vector_mask.rs +++ b/crates/engine-core/src/cmd/vector_cmds/vector_mask.rs @@ -58,6 +58,11 @@ pub(super) fn vector_mask_add(s: &mut Session, p: &Value, from_path: bool) -> Re } pub(super) fn vector_mask_edit(s: &mut Session, p: &Value) -> Result { + edit_vector_mask(s, p, "Edit Vector Mask") +} + +/// `layer.vectorMask.edit` with `p`, its history step named `label`. +fn edit_vector_mask(s: &mut Session, p: &Value, label: &str) -> Result { const CMD: &str = "layer.vectorMask.edit"; let id = layer_id(s, p)?; let path = p.get("path").map(parse_path).transpose().map_err(|e| bad(CMD, e))?; @@ -100,7 +105,7 @@ pub(super) fn vector_mask_edit(s: &mut Session, p: &Value) -> Result { })?; return vector_mask_info(s, id); } - s.edit("Edit Vector Mask", |doc, _| { + s.edit(label, |doc, _| { let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let vm = l.vector_mask.as_mut().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; if let Some(pth) = path { @@ -194,6 +199,15 @@ pub(super) fn toggle_vector_mask(s: &mut Session, p: &Value, key: &str) -> Resul let vm = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?.vector_mask.as_ref().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; if key == "enabled" { vm.enabled } else { vm.linked } }; + // A call that says the direction (the Layers panel's ⇧-click and chain) is named by it, as in Photoshop + // (#16786); a plain toggle (Layer › Vector Mask) keeps its name. + let label = match (key, p.get(key).and_then(Value::as_bool)) { + ("enabled", Some(true)) => "Enable Vector Mask", + ("enabled", Some(false)) => "Disable Vector Mask", + (_, Some(true)) => "Link Vector Mask", + (_, Some(false)) => "Unlink Vector Mask", + (_, None) => "Edit Vector Mask", + }; let v = p.get(key).and_then(Value::as_bool).unwrap_or(!cur); - vector_mask_edit(s, &json!({ "layer": id.0, key: v })) + edit_vector_mask(s, &json!({ "layer": id.0, key: v }), label) } diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index 5dcd43213f..fdb9f452f8 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -31,6 +31,9 @@ pub struct DocState { pub coalesce: Option, /// Channels panel: targeted channel and eye toggles (view state, not history). pub channel_view: channel_cmds::ChannelView, + /// The channel views undo brings back, by the step they belong to: the ids of the history + /// states New Channel or Calculations started from and made (#14683). View state, not history. + pub(crate) undo_channel_views: Vec<(u64, u64, channel_cmds::ChannelView)>, /// Select › Isolate Layers: the Layers panel lists only these layers (empty = off; view state). pub isolated_layers: Vec, /// Painting symmetry preset or sampled path (tool state, not document pixels). @@ -144,6 +147,7 @@ impl DocState { damage_log: Default::default(), coalesce: None, channel_view, + undo_channel_views: Vec::new(), isolated_layers: Vec::new(), symmetry: None, fx_collapsed: Vec::new(), diff --git a/crates/engine-core/src/layer_style.rs b/crates/engine-core/src/layer_style.rs index 9159a5a9fe..ceb2c8b127 100644 --- a/crates/engine-core/src/layer_style.rs +++ b/crates/engine-core/src/layer_style.rs @@ -164,7 +164,9 @@ pub fn effect_defaults(kind: &str) -> Value { "stroke" => json!({"size": 1, "position": "inside", "blend": "Normal", "opacity": 100, "overprint": false, "color": "#000000"}), "colorOverlay" => json!({"blend": "Normal", "color": "#ff0000", "opacity": 100}), "gradientOverlay" => { - json!({"blend": "Normal", "opacity": 100, "from": "#000000", "to": "#ffffff", "reverse": false, "style": "linear", "angle": 90, "scale": 100, "method": "custom"}) + // The reference application's "Gray, White" with the Smooth method (#14900). The page + // edits the stop list; From/To name the same ends for callers that read them. + json!({"blend": "Normal", "opacity": 100, "from": "#d7d7d7", "to": "#ffffff", "stops": [[0, "#d7d7d7"], [1, "#ffffff"]], "reverse": false, "style": "linear", "angle": 90, "scale": 100, "method": "smooth", "smoothness": 100}) } "patternOverlay" => json!({"blend": "Normal", "opacity": 100, "pattern": "", "angle": 0, "scale": 100, "link": true}), "bevelEmboss" => { @@ -553,6 +555,12 @@ pub fn contour_to_shc_all(list: &[&Contour]) -> Result> { craft_psd::shc::write(&file).map_err(|e| EngineError::Other(format!("can't write the contour: {e}"))) } +/// A Gradient Overlay with `Gradient::default()` (black to white, straight stops) and no recorded +/// method: what a command that names its own colours or stops starts from. +fn blank_gradient_overlay() -> Effect { + Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false, interpolation: None } +} + /// An effect of `kind` with its factory settings (before params are applied). fn fresh_effect(kind: &str) -> Option { let shadow = |inner: bool| Shadow { @@ -598,7 +606,10 @@ fn fresh_effect(kind: &str) -> Option { }), "colorOverlay" => Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: Color::rgb(1.0, 0.0, 0.0) }, "gradientOverlay" => { - Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false, interpolation: None } + // The factory values carry the recorded Smooth method, so build them like the page does. + let mut fx = blank_gradient_overlay(); + overlay_effect(&mut fx, &effect_defaults(kind)); + fx } "patternOverlay" => Effect::PatternOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), @@ -974,7 +985,10 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) { /// 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)?; + // A Gradient Overlay given its own colours or stops keeps today's straight stops unless the + // params pick a method; only the factory one (#14900) starts from the Smooth grey to white. + let mut fx = + if kind == "gradientOverlay" && ["from", "to", "stops"].iter().any(|k| p.get(k).is_some()) { blank_gradient_overlay() } else { fresh_effect(kind)? }; overlay_effect(&mut fx, p); Some(fx) } @@ -1320,6 +1334,8 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result { Ok(Value::Null) } +#[cfg(test)] +mod gradient_overlay_defaults_tests; #[cfg(test)] mod satin_defaults_tests; diff --git a/crates/engine-core/src/layer_style/gradient_overlay.rs b/crates/engine-core/src/layer_style/gradient_overlay.rs index 217f6fd70c..aa1a0ca88d 100644 --- a/crates/engine-core/src/layer_style/gradient_overlay.rs +++ b/crates/engine-core/src/layer_style/gradient_overlay.rs @@ -248,13 +248,18 @@ mod tests { } #[test] - fn reset_to_factory_defaults_removes_the_recorded_method() { + fn reset_to_factory_defaults_restores_the_factory_gradient_and_method() { let mut gradient = Gradient::default(); let mut source = None; - overlay(&mut gradient, &mut source, &json!({"method": "smooth", "from": "#ff0000"})); + overlay(&mut gradient, &mut source, &json!({"method": "classic", "from": "#ff0000"})); overlay(&mut gradient, &mut source, &super::super::effect_defaults("gradientOverlay")); - assert!(source.is_none()); - assert_eq!(gradient, Gradient::default()); + let Some(Effect::GradientOverlay { gradient: factory, interpolation: factory_source, .. }) = + super::super::effect_from_params("gradientOverlay", &json!({})) + else { + panic!("no factory overlay") + }; + assert_eq!(source, factory_source, "#14900: the factory overlay records Smooth grey 215 to white"); + assert_eq!(gradient, factory); } } diff --git a/crates/engine-core/src/layer_style/gradient_overlay_defaults_tests.rs b/crates/engine-core/src/layer_style/gradient_overlay_defaults_tests.rs new file mode 100644 index 0000000000..56b26fe2f4 --- /dev/null +++ b/crates/engine-core/src/layer_style/gradient_overlay_defaults_tests.rs @@ -0,0 +1,149 @@ +//! #14900: the Gradient Overlay page's factory values (Normal, 100 %, grey 215 to white, Method +//! Smooth, Smoothness 100 %, Linear, Angle 90, Scale 100) and the rule that an overlay already +//! stored keeps its own gradient and method. The measured column of the factory overlay sits +//! within 2 levels of the reference application's on the white test document. + +use super::*; +use crate::Session; +use photocraft_doc::GradientStyle; +use photocraft_doc::effects::GradientInterpolation; +use serde_json::json; + +const GREY_215: f32 = 215.0 / 255.0; + +/// The issue's test document: 400 x 300 px at 72 ppi, RGB 8 bit, a white Background and a pixel +/// layer with an orange (255,128,0) rectangle at x 100..299, y 75..224. +fn test_document() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + // Edit > Fill lives in photocraft-engine-paint, so the rectangle is written directly. + let id = s.active().unwrap().active_layer.unwrap(); + s.edit("orange", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let r = photocraft_geom::Rect::from_xywh(100, 75, 200, 150); + let px = photocraft_raster::from_rgba(&surf.format(), [1.0, 128.0 / 255.0, 0.0, 1.0]); + surf.write_region(r, &px.repeat(200 * 150)); + Ok(()) + }) + .unwrap(); + s +} + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +/// The one effect the active layer carries. +fn only_effect(s: &Session) -> Effect { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + match l.effects.items.as_slice() { + [fx] => fx.clone(), + other => panic!("not one effect: {other:?}"), + } +} + +fn close(a: &Color, rgb: [f32; 3]) -> bool { + a.to_rgb().iter().zip(rgb).all(|(x, y)| (x - y).abs() < 1e-3) +} + +/// #14900: Layer > Layer Style > Gradient Overlay... seeds a new instance from `effect_defaults` +/// (the page reads its stop list, so the stops carry the colours as well as From/To). +#[test] +fn a_new_gradient_overlay_starts_at_the_factory_values() { + let d = effect_defaults("gradientOverlay"); + assert_eq!(d["blend"], json!("Normal"), "blend"); + assert_eq!(d["opacity"], json!(100), "opacity"); + assert_eq!(d["stops"], json!([[0, "#d7d7d7"], [1, "#ffffff"]]), "stops"); + assert_eq!((d["from"].as_str(), d["to"].as_str()), (Some("#d7d7d7"), Some("#ffffff")), "from / to"); + assert_eq!(d["method"], json!("smooth"), "method"); + assert_eq!(d["smoothness"], json!(100), "smoothness"); + assert_eq!(d["reverse"], json!(false), "reverse"); + assert_eq!(d["style"], json!("linear"), "style"); + assert_eq!(d["angle"], json!(90), "angle"); + assert_eq!(d["scale"], json!(100), "scale"); +} + +/// #14900: `layer.layerStyle.gradientOverlay` without colours or stops makes the factory overlay: +/// grey 215 to white with the Smooth method recorded, the rest at the page's values. +#[test] +fn a_gradient_overlay_command_without_colours_makes_the_factory_effect() { + let mut s = session(); + s.execute("layer.layerStyle.gradientOverlay", json!({})).unwrap(); + let Effect::GradientOverlay { common, gradient, dither, interpolation } = only_effect(&s) else { panic!("not a gradient overlay") }; + assert_eq!((common.blend, common.opacity), (BlendMode::Normal, 1.0)); + assert!(!dither, "dither"); + let Some(GradientInterpolation { method, smoothness, stops }) = interpolation else { panic!("no recorded method") }; + assert_eq!((method.as_str(), smoothness), ("smooth", 100.0)); + assert_eq!(stops.len(), 2, "source stops {stops:?}"); + assert!(stops[0].0 == 0.0 && close(&stops[0].1, [GREY_215; 3]), "first stop {:?}", stops[0]); + assert!(stops[1].0 == 1.0 && close(&stops[1].1, [1.0; 3]), "last stop {:?}", stops[1]); + assert!(close(&gradient.stops.first().unwrap().1, [GREY_215; 3]) && close(&gradient.stops.last().unwrap().1, [1.0; 3]), "baked ends"); + assert!(gradient.stops.len() > 2, "the Smooth curve is baked, not straight: {:?}", gradient.stops); + assert_eq!((gradient.style, gradient.angle, gradient.scale, gradient.reverse, gradient.align), (GradientStyle::Linear, 90.0, 1.0, false, true)); + // The dialog's OK on the factory values (its stop list, no From/To) builds the same effect. + let mut dialog = effect_defaults("gradientOverlay"); + dialog.as_object_mut().unwrap().retain(|k, _| k != "from" && k != "to"); + assert_eq!(effect_from_params("gradientOverlay", &json!({})), effect_from_params("gradientOverlay", &dialog)); +} + +/// #14900 measured: OK on the factory values over the white test document. Red channel at +/// x 200 down the rectangle; the reference application gives +/// `255 255 251 246 240 235 235 230 224 219 215 215`, each within 2 levels. Outside stays white. +#[test] +fn the_factory_gradient_overlay_paints_the_measured_column() { + let mut s = test_document(); + s.execute("layer.layerStyle.gradientOverlay", json!({})).unwrap(); + let d = s.active().unwrap(); + let px = photocraft_compose::render(&d.doc, d.doc.bounds()).into_px(); + let level = |x: usize, y: usize, c: usize| (px[y * 400 + x][c] * 255.0).round() as i32; + let want = [(75, 255), (76, 255), (94, 251), (112, 246), (131, 240), (149, 235), (150, 235), (168, 230), (187, 224), (205, 219), (223, 215), (224, 215)]; + let got: Vec = want.iter().map(|&(y, _)| level(200, y, 0)).collect(); + for (&(y, w), g) in want.iter().zip(&got) { + assert!((g - w).abs() <= 2, "red at (200, {y}): {g}, the reference gives {w}; column {got:?}"); + } + for (x, y) in [(200, 74), (200, 225), (99, 150), (300, 150)] { + assert_eq!([0, 1, 2].map(|c| level(x, y, c)), [255; 3], "outside the layer at ({x}, {y})"); + } +} + +/// #14900: Reset to Default reads the factory values through `layer.layerStyle.defaultFor` until a +/// Make Default stores other ones; the saved values keep winning. +#[test] +fn reset_to_default_restores_the_gradient_overlay_factory_values() { + let mut s = session(); + let d = s.execute("layer.layerStyle.defaultFor", json!({"kind": "gradientOverlay"})).unwrap(); + assert_eq!(d["user"], json!(false)); + assert_eq!(d["params"], effect_defaults("gradientOverlay")); + assert_eq!((d["params"]["method"].as_str(), d["params"]["stops"][0][1].as_str()), (Some("smooth"), Some("#d7d7d7"))); + s.execute("layer.layerStyle.makeDefault", json!({"kind": "gradientOverlay", "params": {"opacity": 40, "method": "linear"}})).unwrap(); + let saved = s.execute("layer.layerStyle.defaultFor", json!({"kind": "gradientOverlay"})).unwrap(); + assert_eq!(saved["user"], json!(true)); + assert_eq!((saved["params"]["opacity"].as_f64(), saved["params"]["method"].as_str()), (Some(40.0), Some("linear")), "a saved default still wins"); +} + +/// #14900: an overlay the document already carries (a PSD or `.pcraft` one, edited in the dialog) +/// keeps its gradient and method through `layer.layerStyle.replace`, and a command that names its +/// colours still gets those colours. +#[test] +fn a_stored_gradient_overlay_keeps_its_own_gradient_and_method() { + let mut s = session(); + let stored = Effect::GradientOverlay { + common: FxCommon::new(BlendMode::Multiply, 0.5), + gradient: Gradient { stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], angle: 30.0, ..Gradient::default() }, + dither: true, + interpolation: None, + }; + let snapshot = serde_json::to_value(&stored).unwrap(); + s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "gradientOverlay", "params": {}, "fx": snapshot}]})).unwrap(); + assert_eq!(only_effect(&s), stored, "an edited effect list left the overlay alone"); + + s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff"})).unwrap(); + let Effect::GradientOverlay { gradient, interpolation, .. } = only_effect(&s) else { panic!("not a gradient overlay") }; + assert_eq!(interpolation, None, "named colours keep today's straight stops"); + assert_eq!(gradient.stops, vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))]); +} diff --git a/crates/engine-core/src/prefs/store.rs b/crates/engine-core/src/prefs/store.rs index f27efc0d6b..9ddb4e72b8 100644 --- a/crates/engine-core/src/prefs/store.rs +++ b/crates/engine-core/src/prefs/store.rs @@ -8,6 +8,7 @@ use super::{Deserialize, Map, Preferences, Serialize, Value}; pub struct PrefsStore { values: Preferences, rev: u64, + settings_rev: u64, catalog_rev: u64, section_revs: std::collections::BTreeMap, } @@ -16,8 +17,15 @@ impl PrefsStore { pub fn get(&self) -> &Preferences { &self.values } - /// Change preferences; bumps the revision. + /// Change preferences; bumps the revision and the settings revision. pub fn edit(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { + self.settings_rev += 1; + self.remember(f) + } + /// Store what the app remembers of its own state between launches (the selected tool, its options, the colours): + /// bumps the revision, so frontends persist, but not the settings revision, because no view reads these back from + /// the preferences; they show the state itself. + pub fn remember(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { let before = (&self.values.shortcuts, &self.values.alternate_shortcuts, &self.values.toolbar); let before = (before.0.clone(), before.1.clone(), before.2.clone()); let sections = self.values.sections.clone(); @@ -45,6 +53,10 @@ impl PrefsStore { pub fn rev(&self) -> u64 { self.rev } + /// Revision of the preferences views read: every [`edit`](Self::edit), not what the app [`remember`](Self::remember)s. + pub fn settings_rev(&self) -> u64 { + self.settings_rev + } } /// The preferences file format written by [`SavedPrefsExt::prefs_value`](crate::prefs::SavedPrefsExt::prefs_value). 2: Use Shift Key for Tool diff --git a/crates/engine-core/src/session/history.rs b/crates/engine-core/src/session/history.rs index 6d5662f098..b8ae73c4d6 100644 --- a/crates/engine-core/src/session/history.rs +++ b/crates/engine-core/src/session/history.rs @@ -25,6 +25,7 @@ impl Session { st.coalesce = None; // The step being undone: the layers whose visibility it changed get it back. let changed = st.history.current_visibility().to_vec(); + let left = st.history.row_id(st.history.past_len()); let doc = st.doc.clone(); match st.history.undo(doc) { // Undo Clear History: the list comes back, the document is the same one. Not an @@ -55,6 +56,7 @@ impl Session { let before = std::mem::replace(st.doc_mut(), d); let keep_clean = st.keeps_clean(&before); restore_target(st, layers); + channel_cmds::restore_view_after_undo(st, left); st.bump_revision(keep_clean); st.last_damage = damage; st.record_damage(); diff --git a/crates/engine-paint/src/cmd/redeye_cmds.rs b/crates/engine-paint/src/cmd/redeye_cmds.rs index ceaffa4fac..55dfde2944 100644 --- a/crates/engine-paint/src/cmd/redeye_cmds.rs +++ b/crates/engine-paint/src/cmd/redeye_cmds.rs @@ -249,18 +249,22 @@ fn red_eye(s: &mut Session, p: &Value) -> Result { let pupil = pupil_raw.clamp(1.0, 100.0); let darken = darken.clamp(0.0, 100.0); let id = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|d| d.active_layer) }; + // The press point decides (#12576): a press outside the selection does nothing, not clipped, and + // like Photoshop it is silent (#13096): no pixels, no state, no message. Feathered (partly + // selected) and off-canvas presses were not measured and keep today's behaviour: any value above + // 0 counts as inside, and off-canvas presses are not checked. + if let (Some(&first), Some(d)) = (pts.first(), s.active()) + && d.doc.bounds().contains(first.0, first.1) + && d.doc.selection.as_ref().is_some_and(|m| m.sample_channel(first.0, first.1, 0) <= 0.0) + { + return Ok(json!({ "damage": [0, 0, 0, 0], "pixels": 0, "outsideSelection": true })); + } let (damage, total) = s.edit("Red Eye Removal Tool", |doc, active| { let canvas = doc.bounds(); let sel = doc.selection.clone(); let layer = id.or(*active); let (surf, lock) = crate::channel_cmds::target_surface(doc, layer, p)?; let Some(&first) = pts.first() else { return Err(EngineError::Other(MISS.into())) }; - // The press point decides (#12576): a press outside the selection is refused like a miss, - // not clipped. Feathered (partly selected) and off-canvas presses were not measured and keep - // today's behaviour: any value above 0 counts as inside, and off-canvas presses are not checked. - if canvas.contains(first.0, first.1) && sel.as_ref().is_some_and(|m| m.sample_channel(first.0, first.1, 0) <= 0.0) { - return Err(EngineError::Other(MISS.into())); - } // The Background always locks transparency, so only a click on a clear pixel counts. let on_locked_clear = lock && surf.rgba(first.0, first.1)[3] <= 1.0e-5; let mut total = 0u32; @@ -286,7 +290,7 @@ pub fn specs() -> Vec { label: "Red Eye", menu: &[], shortcut: None, - params: r#"{"x":px, "y":px} | {"points":[[x,y],…] (at most 64)},"pupilSize":1..100=50,"darken":0..100=50,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i} → {"damage":[x,y,w,h], "pixels":n}"#, + params: r#"{"x":px, "y":px} | {"points":[[x,y],…] (at most 64)},"pupilSize":1..100=50,"darken":0..100=50,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i} → {"damage":[x,y,w,h], "pixels":n, "outsideSelection":true?}"#, enabled, run: red_eye, journal: true, diff --git a/crates/engine-paint/src/cmd/redeye_history_state_tests.rs b/crates/engine-paint/src/cmd/redeye_history_state_tests.rs index 150a21802a..d188327a62 100644 --- a/crates/engine-paint/src/cmd/redeye_history_state_tests.rs +++ b/crates/engine-paint/src/cmd/redeye_history_state_tests.rs @@ -127,7 +127,13 @@ fn refused_clicks_add_no_state() { refused(&mut s, params, case); } s.execute("select.rect", json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap(); - refused(&mut s, json!({"x": 8, "y": 8}), "a click outside the selection"); + // #13096: a click outside the selection does nothing silently: an Ok with no state. + let (n, _) = last(&s); + let before = pixels(&s); + let r = s.execute("paint.redEye", json!({"x": 8, "y": 8})).unwrap(); + assert_eq!((r["pixels"].as_u64(), r["outsideSelection"].as_bool()), (Some(0), Some(true)), "{r}"); + assert_eq!(last(&s).0, n, "a click outside the selection: no state"); + assert!(pixels(&s) == before, "a click outside the selection"); unchanged_state(&mut s, json!({"x": 44, "y": 44}), "a click inside the selection"); s.execute("select.deselect", json!({})).unwrap(); let id = s.active().unwrap().active_layer.unwrap(); diff --git a/crates/engine-paint/src/cmd/redeye_outside_selection_tests.rs b/crates/engine-paint/src/cmd/redeye_outside_selection_tests.rs index 1d9ca30efa..2aed130096 100644 --- a/crates/engine-paint/src/cmd/redeye_outside_selection_tests.rs +++ b/crates/engine-paint/src/cmd/redeye_outside_selection_tests.rs @@ -1,5 +1,6 @@ //! #12576: a Red Eye press outside the selection does nothing and adds no History state; a press //! inside it is clipped to the selection as before, and with no selection nothing changes. +//! #13096: the outside press is silent, an `Ok` that says so, not the miss error. use serde_json::{Value, json}; @@ -23,7 +24,7 @@ fn eyes() -> Session { /// The left half of eye B: x 450–499. fn select_left_half_of_eye_b(s: &mut Session) { - s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 600})).unwrap(); + s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 1000})).unwrap(); } /// History length, and the Background's pixels as one value per channel. @@ -53,10 +54,46 @@ fn a_press_outside_the_selection_changes_nothing_and_adds_no_state() { let (states, cols, r) = press(&mut s, params.clone()); assert_eq!(cols, None, "{params}: pixels changed"); assert_eq!(states, 0, "{params}: a history state was added"); - assert_eq!(r, Err(MISS.to_string()), "{params}"); + let r = r.unwrap_or_else(|e| panic!("{params}: an outside press is not an error: {e}")); + assert_eq!(r, json!({"damage": [0, 0, 0, 0], "pixels": 0, "outsideSelection": true}), "{params}"); } } +#[test] +fn an_outside_press_is_silent_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 64, "mode": "rgb", "depth": depth})).unwrap(); + s.execute("edit.fill", json!({"color": "#d22828"})).unwrap(); + s.execute("select.rect", json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap(); + let n = s.active().unwrap().history.past_len(); + let r = s.execute("paint.redEye", json!({"x": 8, "y": 8})).unwrap_or_else(|e| panic!("{depth} bit: {e}")); + assert_eq!(r["pixels"], 0, "{depth} bit"); + assert_eq!(r["outsideSelection"], true, "{depth} bit"); + assert_eq!(s.active().unwrap().history.past_len(), n, "{depth} bit: no state"); + } +} + +#[test] +fn a_miss_inside_the_selection_keeps_its_result() { + // On a dark blue patch inside the selection: the tool runs and leaves one unchanged state, as before. + let mut s = eyes(); + s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 100})).unwrap(); + s.execute("edit.fill", json!({"color": "#283c78"})).unwrap(); + select_left_half_of_eye_b(&mut s); + let (states, cols, r) = press(&mut s, json!({"x": 475, "y": 40, "pupilSize": 1})); + let r = r.unwrap(); + assert_eq!((r["pixels"].as_u64(), r.get("outsideSelection")), (Some(0), None), "{r}"); + assert_eq!((states, cols), (1, None)); + // On a clear pixel under Lock transparent pixels inside the selection: still the miss error. + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + let n = s.active().unwrap().history.past_len(); + let r = s.execute("paint.redEye", json!({"x": 475, "y": 40, "pupilSize": 1})).map_err(|e| e.to_string()); + assert_eq!(r, Err(MISS.to_string())); + assert_eq!(s.active().unwrap().history.past_len(), n); +} + #[test] fn a_press_inside_the_selection_is_clipped_and_adds_one_state() { // A batch whose first point is inside runs, and x 499.5 is still on the last selected column. diff --git a/crates/engine-paint/src/cmd/retouch_cmds.rs b/crates/engine-paint/src/cmd/retouch_cmds.rs index 6ecb8398f4..767f0547db 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds.rs @@ -17,7 +17,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}; +use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke, restore_coverage}; use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use rayon::prelude::*; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/burn_32bit_linear_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/burn_32bit_linear_tests.rs new file mode 100644 index 0000000000..23fa4d1d03 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/burn_32bit_linear_tests.rs @@ -0,0 +1,188 @@ +//! Burn in a 32-bit document tones the linear values it holds, with the reference's curve +//! (#12674); 8- and 16-bit documents keep their results. + +use crate::Session; +use photocraft_algo::retouch::{ToneRange, dodge_burn}; +use photocraft_color::convert::linear_to_srgb; +use serde_json::{Value, json}; + +/// The reference's test colours (8-bit RGB): grey 32, 128 and 224, red, skin and pastel. +const PATCHES: [[u8; 3]; 6] = [[32, 32, 32], [128, 128, 128], [224, 224, 224], [200, 40, 40], [220, 170, 140], [180, 200, 230]]; +const SIDE: i32 = 60; + +/// An 8-bit RGB document of `PATCHES` side by side, converted to `depth` bits. +fn patches(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE * PATCHES.len() as i32, "height": SIDE, "depth": 8, "mode": "rgb"})).unwrap(); + s.edit("patches", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for _ in b.y0..b.y1 { + for x in b.x0..b.x1 { + let c = PATCHES[(x / SIDE) as usize].map(|v| f32::from(v) / 255.0); + data.extend(photocraft_raster::from_rgba(&fmt, [c[0], c[1], c[2], 1.0])); + } + } + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + if depth != 8 { + s.execute(&format!("image.mode.bits{depth}"), json!({})).unwrap(); + } + s +} + +fn rgb(s: &Session, x: i32, y: i32) -> [f32; 3] { + let d = s.active().unwrap(); + let p = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [p[0], p[1], p[2]] +} + +/// One default Burn click (Midtones, Protect Tones, 50 %) with a hard 40 px tip on each patch's +/// centre; the stored values there. +fn burn_each(s: &mut Session, extra: Value) -> Vec<[f32; 3]> { + (0..PATCHES.len() as i32) + .map(|i| { + let (x, y) = (i * SIDE + SIDE / 2, SIDE / 2); + let mut p = json!({"points": [[x, y]], "size": 40, "hardness": 100}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + s.execute("paint.burn", p).unwrap(); + rgb(s, x, y) + }) + .collect() +} + +/// A 32-bit document's linear values as 8-bit RGB, as the reference reads them. +fn as_8bit(c: [f32; 3]) -> [i32; 3] { + c.map(|v| (linear_to_srgb(v).clamp(0.0, 1.0) * 255.0).round() as i32) +} + +#[test] +fn burn_tones_linear_values_in_32_bit() { + // Measured in the reference: one default click in a 32-bit RGB document, read as 8-bit. + let expected = [[32, 32, 32], [122, 122, 122], [217, 217, 217], [189, 40, 40], [212, 162, 132], [168, 192, 225]]; + let mut s = patches(32); + let got: Vec<_> = burn_each(&mut s, json!({})).into_iter().map(as_8bit).collect(); + for ((g, e), p) in got.iter().zip(expected).zip(PATCHES) { + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() <= 2), "32-bit Burn of {p:?}: got {g:?}, expected {e:?} (+-2); all: {got:?}"); + } +} + +#[test] +fn burn_keeps_8_and_16_bit_results() { + // Pinned from main 406ac677e1: this change only adds the 32-bit path. + let mut s = patches(8); + let got: Vec<_> = burn_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 255.0).round() as u16)).collect(); + assert_eq!(got, [[23, 23, 23], [91, 91, 91], [218, 218, 218], [125, 25, 25], [192, 148, 122], [165, 183, 211]]); + let mut s = patches(16); + let got: Vec<_> = burn_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 65535.0).round() as u16)).collect(); + assert_eq!(got, [[5893, 5893, 5893], [23307, 23307, 23307], [56025, 56025, 56025], [32222, 6444, 6444], [49291, 38089, 31367], [42377, 47085, 54148]]); +} + +/// Fill the first patch with light above white (4.0, 1.5, 0.2, linear). +fn above_white(s: &mut Session) { + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let r = photocraft_geom::Rect::new(0, 0, SIDE, SIDE); + let px = photocraft_raster::from_rgba(&surf.format(), [4.0, 1.5, 0.2, 1.0]); + surf.write_region(r, &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn burn_keeps_light_above_white_in_32_bit() { + let mut s = patches(32); + above_white(&mut s); + let c = burn_each(&mut s, json!({}))[0]; + assert_eq!([c[0], c[1]], [4.0, 1.5], "light above white must stay as it was: {c:?}"); + assert!(c[2] < 0.2, "the in-range channel is still burned: {c:?}"); +} + +#[test] +fn burn_keeps_todays_curve_at_unmeasured_exposures_in_32_bit() { + // Only 50 % was measured in 32-bit; other exposures keep the gamma curve with Protect Tones' + // luma scaling, run on the stored values. + for exposure in [25, 100] { + let mut s = patches(32); + let before: Vec<_> = (0..PATCHES.len() as i32).map(|i| rgb(&s, i * SIDE + SIDE / 2, SIDE / 2)).collect(); + let got = burn_each(&mut s, json!({"exposure": exposure})); + for (g, o) in got.iter().zip(before) { + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, true, true); + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() < 1e-5), "{exposure} % Burn of {o:?}: got {g:?}, today's curve gives {e:?}"); + } + } +} + +#[test] +fn burn_keeps_light_above_white_with_unmeasured_settings_in_32_bit() { + // The settings that keep today's curve must not clip light above white either; Highlights + // darkens it, but not down to 1.0. + for extra in [json!({"exposure": 100}), json!({"range": "shadows"}), json!({"range": "highlights"}), json!({"protectTones": false})] { + let mut s = patches(32); + above_white(&mut s); + let c = burn_each(&mut s, extra.clone())[0]; + assert!(c[0] > 1.0, "Burn with {extra} clipped light above white: {c:?}"); + } + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE, "height": SIDE, "depth": 32, "mode": "gray"})).unwrap(); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + let before = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(before > 1.0, "{before}"); + s.execute("paint.burn", json!({"points": [[SIDE / 2, SIDE / 2]], "size": 40, "hardness": 100})).unwrap(); + let after = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(after > 1.0, "32-bit Grayscale Burn clipped {before} to {after}"); +} + +#[test] +fn burn_keeps_light_above_white_when_luma_is_not_positive_in_32_bit() { + // A channel above white next to a negative one: luma <= 0, so Protect Tones can't scale the + // colour by luma. It takes the per-channel curve instead and keeps the light above white. + for exposure in [25, 100] { + for o in [[1.2f32, -0.7, 0.2], [1.01, -0.52, 0.02]] { + let mut s = patches(32); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [o[0], o[1], o[2], 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(&s, SIDE / 2, SIDE / 2), o); + let c = burn_each(&mut s, json!({"exposure": exposure}))[0]; + assert!(c[0] > 1.0, "{exposure} % Burn of {o:?} clipped light above white: {c:?}"); + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, true, false); + assert!(c.iter().zip(e).all(|(c, e)| (c - e).abs() < 1e-5), "{exposure} % Burn of {o:?}: got {c:?}, the per-channel curve gives {e:?}"); + } + } +} + +#[test] +fn burn_keeps_tones_in_order_in_32_bit() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 256, "height": 8, "depth": 32, "mode": "rgb"})).unwrap(); + s.edit("ramp", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let data: Vec = (0..8).flat_map(|_| (0..256).flat_map(|x| photocraft_raster::from_rgba(&fmt, [x as f32 / 255.0; 4]))).collect(); + surf.write_region(photocraft_geom::Rect::new(0, 0, 256, 8), &data); + Ok(()) + }) + .unwrap(); + s.execute("paint.burn", json!({"points": [[-20, 4], [276, 4]], "size": 40, "hardness": 100})).unwrap(); + let row: Vec = (0..256).map(|x| rgb(&s, x, 4)[0]).collect(); + assert!(row.windows(2).all(|w| w[1] >= w[0]), "{row:?}"); + assert!(row.iter().all(|v| (0.0..=1.0).contains(v)) && row[0] == 0.0 && row[255] == 1.0, "{row:?}"); +} diff --git a/crates/engine-paint/src/cmd/retouch_cmds/clone.rs b/crates/engine-paint/src/cmd/retouch_cmds/clone.rs index 59c39ab183..4e8781e021 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/clone.rs @@ -4,7 +4,7 @@ use super::sampling::{SampleLayers, sample_layers}; use super::{ BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value, alpha_index, apply_coverage, bad, coverage, damage_json, flag, has_pixel_layer, json, parse_blend, parse_brush, pattern_stamp, periodic, point, - reject_huge_stroke, run_stroke, to_rgba, + reject_huge_stroke, restore_coverage, run_stroke, to_rgba, }; /// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot, @@ -212,6 +212,11 @@ pub(super) fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value, pub(super) fn blend_param(p: &Value, cmd: &str) -> Result { match p.get("mode").and_then(Value::as_str) { None => Ok(BlendMode::Normal), + // The Healing Brush's Replace row (#12101) is not a blend mode: the stroke copies the + // source, which `healing_brush` reads from the params itself. Here it only opens the live + // preview, whose texture the Replace stroke draws as it stands, through Normal. Every other + // command keeps refusing the word. + Some("replace") if cmd == "paint.healingBrush" => Ok(BlendMode::Normal), Some(m) => parse_blend(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))), } } @@ -512,10 +517,14 @@ impl LiveRetouch { // The Pattern Stamp's Behind goes beneath the pixels, as its commit lays it. let behind = matches!(self.paint, LivePaint::Pattern { behind: true, .. }); let clone = matches!(self.paint, LivePaint::Clone { .. }); + let history = matches!(self.paint, LivePaint::History(_)); let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; surf.write_region(r, &self.pre_surf.read_region(r)); let damage = if clone { apply_clone_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode) + } else if history { + // As the commit paints it (`heal::history_brush`): the source state replaces the pixels. + restore_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode) } else { pattern_stamp::lay_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode, behind) }; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs index 11dc337871..e77ba563fd 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs @@ -4,7 +4,7 @@ use super::{ Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag, from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_blend, parse_brush, run_stroke, sponge, string, to_rgba, }; -use photocraft_algo::retouch::sponge_rgb; +use photocraft_algo::retouch::{luma, sponge_rgb, tone_curve}; use photocraft_color::{ColorMode, SampleType}; // --------------------------------------------------------------------------------------------- @@ -185,6 +185,47 @@ fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + Send + ' }) } +/// Strength of [`linear_midtones`] per unit of Exposure. +const LINEAR_MIDTONES_STRENGTH: f32 = 1.34; + +/// The Midtones Dodge (`burn = false`) or Burn curve for one linear value of a 32-bit document at +/// exposure `e` (0..1): `v ± 1.34·e·v²·(1 − v)^1.5`, each channel on its own. It is fitted to the +/// reference's 32-bit results (#12687, #12674), which tone the stored linear values: much gentler on the +/// mid tones than the 8-bit curve on gamma-encoded values, and the shadows are left alone. Black +/// and white stay put, values outside 0..1 (light above white) are kept as they are, and tones +/// stay in order at every exposure. +#[inline] +fn linear_midtones(v: f32, e: f32, burn: bool) -> f32 { + if !(v > 0.0 && v < 1.0) { + return v; + } + let d = LINEAR_MIDTONES_STRENGTH * e.clamp(0.0, 1.0) * v * v * (1.0 - v).powf(1.5); + if burn { v - d } else { v + d } +} + +/// The 32-bit reference was measured at Exposure 50 % only (#12687, #12674); other exposures keep the +/// gamma curve. +const MEASURED_LINEAR_EXPOSURE: f32 = 0.5; + +/// Dodge or Burn of a 32-bit colour with the curve the other bit depths use, except that light above +/// white isn't clipped: Protect Tones scales such a colour to its new luma without gamut +/// compression, which would pull it back to 1.0 (#12687, #12674). Such a colour whose luma isn't +/// positive (a negative channel outweighs it) can't be scaled by luma, so it takes the per-channel +/// curve, as with Protect Tones off, which keeps light above white too. Other colours get today's +/// result. +#[inline] +fn dodge_burn_float(c: [f32; 3], e: f32, range: ToneRange, burn: bool, protect: bool) -> [f32; 3] { + if protect && c.iter().any(|&v| v > 1.0) { + let l = luma(c); + if l > 1e-6 { + let nl = tone_curve(l, e, range, burn); + return c.map(|v| v * nl / l); + } + return dodge_burn(c, e, range, burn, false); + } + dodge_burn(c, e, range, burn, protect) +} + fn tone_range(p: &Value, cmd: &str) -> Result { match string(p, "range", "midtones") { "shadows" => Ok(ToneRange::Shadows), @@ -305,6 +346,18 @@ impl DabTool { pub(super) fn effect(&self, fmt: PixelFormat, spacing: f32) -> DabEffect { let sp = spacing; match self.clone() { + // A 32-bit RGB document holds linear values, which the reference's default Dodge and Burn + // tone with their own curve. Grayscale, the other ranges, Protect Tones off and the other + // exposures weren't measured there and keep the gamma curve, without clipping light + // above white. + Self::Tone { burn, range: ToneRange::Midtones, exposure, protect: true } + if fmt.sample == SampleType::F32 && fmt.mode == ColorMode::Rgb && (exposure - MEASURED_LINEAR_EXPOSURE).abs() < 1e-4 => + { + tone_stroke(fmt, move |c| c.map(|v| linear_midtones(v, exposure, burn))) + } + Self::Tone { burn, range, exposure, protect } if fmt.sample == SampleType::F32 => { + tone_stroke(fmt, move |c| dodge_burn_float(c, exposure, range, burn, protect)) + } Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)), // Flow is already in the dab's coverage. The reference RGB response applies to integer // RGB surfaces, including 16-bit. Float RGB and the other models use the legacy curve. @@ -828,3 +881,11 @@ mod smudge_refuses_indexed_tests; #[cfg(test)] #[path = "smudge_mode_tests.rs"] mod smudge_mode_tests; + +#[cfg(test)] +#[path = "dodge_32bit_linear_tests.rs"] +mod dodge_32bit_linear_tests; + +#[cfg(test)] +#[path = "burn_32bit_linear_tests.rs"] +mod burn_32bit_linear_tests; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/dodge_32bit_linear_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/dodge_32bit_linear_tests.rs new file mode 100644 index 0000000000..dd8535b397 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/dodge_32bit_linear_tests.rs @@ -0,0 +1,187 @@ +//! Dodge in a 32-bit document tones the linear values it holds, with the reference's curve +//! (#12687); 8- and 16-bit documents keep their results. + +use crate::Session; +use photocraft_algo::retouch::{ToneRange, dodge_burn}; +use photocraft_color::convert::linear_to_srgb; +use serde_json::{Value, json}; + +/// The reference's test colours (8-bit RGB): grey 32, 128 and 224, red, skin and pastel. +const PATCHES: [[u8; 3]; 6] = [[32, 32, 32], [128, 128, 128], [224, 224, 224], [200, 40, 40], [220, 170, 140], [180, 200, 230]]; +const SIDE: i32 = 60; + +/// An 8-bit RGB document of `PATCHES` side by side, converted to `depth` bits. +fn patches(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE * PATCHES.len() as i32, "height": SIDE, "depth": 8, "mode": "rgb"})).unwrap(); + s.edit("patches", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for _ in b.y0..b.y1 { + for x in b.x0..b.x1 { + let c = PATCHES[(x / SIDE) as usize].map(|v| f32::from(v) / 255.0); + data.extend(photocraft_raster::from_rgba(&fmt, [c[0], c[1], c[2], 1.0])); + } + } + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + if depth != 8 { + s.execute(&format!("image.mode.bits{depth}"), json!({})).unwrap(); + } + s +} + +fn rgb(s: &Session, x: i32, y: i32) -> [f32; 3] { + let d = s.active().unwrap(); + let p = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [p[0], p[1], p[2]] +} + +/// One default Dodge click (Midtones, Protect Tones, 50 %) with a hard 40 px tip on each patch's +/// centre; the stored values there. +fn dodge_each(s: &mut Session, extra: Value) -> Vec<[f32; 3]> { + (0..PATCHES.len() as i32) + .map(|i| { + let (x, y) = (i * SIDE + SIDE / 2, SIDE / 2); + let mut p = json!({"points": [[x, y]], "size": 40, "hardness": 100}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + s.execute("paint.dodge", p).unwrap(); + rgb(s, x, y) + }) + .collect() +} + +/// A 32-bit document's linear values as 8-bit RGB, as the reference reads them. +fn as_8bit(c: [f32; 3]) -> [i32; 3] { + c.map(|v| (linear_to_srgb(v).clamp(0.0, 1.0) * 255.0).round() as i32) +} + +#[test] +fn dodge_tones_linear_values_in_32_bit() { + // Measured in the reference: one default click in a 32-bit RGB document, read as 8-bit. + let expected = [[32, 32, 32], [134, 134, 134], [230, 230, 230], [210, 40, 40], [227, 177, 147], [191, 209, 235]]; + let mut s = patches(32); + let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(as_8bit).collect(); + for ((g, e), p) in got.iter().zip(expected).zip(PATCHES) { + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() <= 2), "32-bit Dodge of {p:?}: got {g:?}, expected {e:?} (+-2); all: {got:?}"); + } +} + +#[test] +fn dodge_keeps_8_and_16_bit_results() { + // Pinned from main 406ac677e1: this change only adds the 32-bit path. + let mut s = patches(8); + let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 255.0).round() as u16)).collect(); + assert_eq!(got, [[46, 46, 46], [161, 161, 161], [228, 228, 228], [255, 65, 65], [242, 187, 154], [191, 212, 244]]); + let mut s = patches(16); + let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 65535.0).round() as u16)).collect(); + assert_eq!(got, [[11825, 11825, 11825], [41392, 41392, 41392], [58654, 58654, 58654], [65535, 16658, 16658], [62104, 47989, 39521], [49139, 54599, 62789]]); +} + +/// Fill the first patch with light above white (4.0, 1.5, 0.2, linear). +fn above_white(s: &mut Session) { + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let r = photocraft_geom::Rect::new(0, 0, SIDE, SIDE); + let px = photocraft_raster::from_rgba(&surf.format(), [4.0, 1.5, 0.2, 1.0]); + surf.write_region(r, &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn dodge_keeps_light_above_white_in_32_bit() { + let mut s = patches(32); + above_white(&mut s); + let c = dodge_each(&mut s, json!({}))[0]; + assert_eq!([c[0], c[1]], [4.0, 1.5], "light above white must stay as it was: {c:?}"); + assert!(c[2] > 0.2, "the in-range channel is still dodged: {c:?}"); +} + +#[test] +fn dodge_keeps_todays_curve_at_unmeasured_exposures_in_32_bit() { + // Only 50 % was measured in 32-bit; other exposures keep the gamma curve with Protect Tones' + // luma scaling, run on the stored values. + for exposure in [25, 100] { + let mut s = patches(32); + let before: Vec<_> = (0..PATCHES.len() as i32).map(|i| rgb(&s, i * SIDE + SIDE / 2, SIDE / 2)).collect(); + let got = dodge_each(&mut s, json!({"exposure": exposure})); + for (g, o) in got.iter().zip(before) { + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, false, true); + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() < 1e-5), "{exposure} % Dodge of {o:?}: got {g:?}, today's curve gives {e:?}"); + } + } +} + +#[test] +fn dodge_keeps_light_above_white_with_unmeasured_settings_in_32_bit() { + // The settings that keep today's curve must not clip light above white either. + for extra in [json!({"exposure": 100}), json!({"range": "shadows"}), json!({"range": "highlights"}), json!({"protectTones": false})] { + let mut s = patches(32); + above_white(&mut s); + let c = dodge_each(&mut s, extra.clone())[0]; + assert!(c[0] >= 4.0 && c[1] >= 1.5, "Dodge with {extra} clipped light above white: {c:?}"); + } + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE, "height": SIDE, "depth": 32, "mode": "gray"})).unwrap(); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + let before = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(before > 1.0, "{before}"); + s.execute("paint.dodge", json!({"points": [[SIDE / 2, SIDE / 2]], "size": 40, "hardness": 100})).unwrap(); + let after = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(after >= before, "32-bit Grayscale Dodge clipped {before} to {after}"); +} + +#[test] +fn dodge_keeps_light_above_white_when_luma_is_not_positive_in_32_bit() { + // A channel above white next to a negative one: luma <= 0, so Protect Tones can't scale the + // colour by luma. It takes the per-channel curve instead and keeps the light above white. + for exposure in [25, 100] { + for o in [[1.2f32, -0.7, 0.2], [1.01, -0.52, 0.02]] { + let mut s = patches(32); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [o[0], o[1], o[2], 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(&s, SIDE / 2, SIDE / 2), o); + let c = dodge_each(&mut s, json!({"exposure": exposure}))[0]; + assert!(c[0] >= o[0], "{exposure} % Dodge of {o:?} clipped light above white: {c:?}"); + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, false, false); + assert!(c.iter().zip(e).all(|(c, e)| (c - e).abs() < 1e-5), "{exposure} % Dodge of {o:?}: got {c:?}, the per-channel curve gives {e:?}"); + } + } +} + +#[test] +fn dodge_keeps_tones_in_order_in_32_bit() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 256, "height": 8, "depth": 32, "mode": "rgb"})).unwrap(); + s.edit("ramp", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let data: Vec = (0..8).flat_map(|_| (0..256).flat_map(|x| photocraft_raster::from_rgba(&fmt, [x as f32 / 255.0; 4]))).collect(); + surf.write_region(photocraft_geom::Rect::new(0, 0, 256, 8), &data); + Ok(()) + }) + .unwrap(); + s.execute("paint.dodge", json!({"points": [[-20, 4], [276, 4]], "size": 40, "hardness": 100})).unwrap(); + let row: Vec = (0..256).map(|x| rgb(&s, x, 4)[0]).collect(); + assert!(row.windows(2).all(|w| w[1] >= w[0]), "{row:?}"); + assert!(row.iter().all(|v| (0.0..=1.0).contains(v)) && row[0] == 0.0 && row[255] == 1.0, "{row:?}"); +} diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs index 642f8cd211..4c1c2f4bc3 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs @@ -3,7 +3,7 @@ use super::periodic; use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers}; use super::{ BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad, - coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, run_stroke, string, + coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, restore_coverage, run_stroke, string, }; /// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve). @@ -58,6 +58,10 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { let which = sample_layers(p, CMD)?; let source = super::clone_sampling::resolve(s, p, CMD)?; let mode = blend_param(p, CMD)?; + // The options bar's Replace row (#12101): the stroke copies the source pixels without the + // healing solve, composited through `mode` (Normal). It is the command's word, not a blend + // mode; `blend_param` already accepted it for this command alone. + let replace = p.get("mode").and_then(Value::as_str) == Some("replace"); let aligned = flag(p, "aligned", true); let map = clone_mapping(s, p, &stroke, CMD)?; let off = map.offset(); @@ -69,27 +73,34 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { let (g, cov) = pad_coverage(bounds, &cov, 2); let fmt = source.sample_format(surf); let src = clone_sample(pre, id, surf, which, &source, g, &map, wrap, CMD)?; - // The destination the texture is fitted to: the layer itself, or what the user sees when - // sampling several layers (so healing onto an empty layer matches the composite). - let dst = if wrap { - periodic::sample(pre, id, surf, which, g, CMD)? - } else if which == SampleLayers::Current { - Region::read(surf, g) - } else { - composite_region(pre, id, which, g, surf.format()) - }; - let dst = if fmt.alpha && !surf.format().alpha { super::clone_sampling::opaque_alpha(dst, surf.format()) } else { dst }; // The solver can reconstruct positive alpha from the destination boundary even where // no source pixel exists. Keep source availability separate from the solved channels. let alpha = super::alpha_index(&fmt); let has_source = |pixel: &[f32]| alpha.is_none_or(|a| pixel.get(a).is_some_and(|value| *value > 0.0)); - let mask: Vec = cov.iter().zip(src.data.chunks_exact(fmt.channels())).map(|(c, pixel)| *c > 0.0 && has_source(pixel)).collect(); - let mut healed = heal_region(&fmt, &src, &dst, &mask); - for (pixel, sample) in healed.data.chunks_exact_mut(fmt.channels()).zip(src.data.chunks_exact(fmt.channels())) { - if !has_source(sample) { - pixel.fill(0.0); + let healed = if replace { + // Replace (#12101): the sampled source as it stands, no solve against the + // destination. Pixels with no source stay transparent, as they do through the solver. + src + } else { + // The destination the texture is fitted to: the layer itself, or what the user sees when + // sampling several layers (so healing onto an empty layer matches the composite). + let dst = if wrap { + periodic::sample(pre, id, surf, which, g, CMD)? + } else if which == SampleLayers::Current { + Region::read(surf, g) + } else { + composite_region(pre, id, which, g, surf.format()) + }; + let dst = if fmt.alpha && !surf.format().alpha { super::clone_sampling::opaque_alpha(dst, surf.format()) } else { dst }; + let mask: Vec = cov.iter().zip(src.data.chunks_exact(fmt.channels())).map(|(c, pixel)| *c > 0.0 && has_source(pixel)).collect(); + let mut healed = heal_region(&fmt, &src, &dst, &mask); + for (pixel, sample) in healed.data.chunks_exact_mut(fmt.channels()).zip(src.data.chunks_exact(fmt.channels())) { + if !has_source(sample) { + pixel.fill(0.0); + } } - } + healed + }; if wrap { return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, fmt, |_, r| { let part = healed.crop(r); @@ -172,7 +183,7 @@ pub(super) fn history_brush(s: &mut Session, p: &Value) -> Result { let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; let (bounds, cov) = coverage(CMD, &stroke)?; let paint = Region::read(&src, bounds); - Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) + Ok(restore_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) })?; let mut r = json!({ "damage": damage_json(dmg) }); if from_live { @@ -314,3 +325,11 @@ pub(super) fn spot_healing(s: &mut Session, p: &Value) -> Result { #[cfg(test)] #[path = "heal_indexed_tests.rs"] mod heal_indexed_tests; + +#[cfg(test)] +#[path = "history_brush_transparency_tests.rs"] +mod history_brush_transparency_tests; + +#[cfg(test)] +#[path = "heal_replace_tests.rs"] +mod heal_replace_tests; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs new file mode 100644 index 0000000000..149dab07f5 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs @@ -0,0 +1,173 @@ +//! #12101: the Healing Brush's Replace mode. `paint.healingBrush {"mode":"replace"}` copies the +//! source pixels straight onto the layer: no healing solve, Normal compositing. Every pixel of the +//! tip's full-coverage disc equals the source pixel the stroke maps there, bit for bit, as read +//! from the document's state before the stroke (221 px for the 20 px hard tip); past that disc +//! Replace lays the same source through the antialiased rim's coverage - strictly between ground +//! and source. The other modes keep their results; an unknown `mode` string stays an error, and +//! the stroke's History step keeps the name "Healing Brush". + +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_doc::Size; + +use super::*; + +/// The test document: green 40,160,60 throughout with a 20 x 20 checker at 6,6 (5 px cells +/// alternating 60,60,60 / 200,200,200). The source patch and the click sit far apart, so a +/// straight copy and a heal cannot agree anywhere inside the dab. +fn document() -> Session { + let mut s = crate::session(); + s.add_document( + Document::with_background("t", Size::new(48, 48), ColorMode::Rgb, SampleType::U8, Color::rgb(40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0)), + None, + ); + for cx in 0..4 { + for cy in 0..4 { + let color = if (cx + cy) % 2 == 0 { "#3c3c3c" } else { "#c8c8c8" }; + s.execute("select.rect", json!({"x": 6 + 5 * cx, "y": 6 + 5 * cy, "width": 5, "height": 5})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + } + } + s.execute("select.deselect", json!({})).unwrap(); + s +} + +/// One click at 30,24 with a 20 px hard round tip; the source point 16,16 is sampled under it. +fn stroke(mode: Option<&str>) -> Value { + let mut p = json!({"points": [[30, 24]], "source": [16, 16], "size": 20, "hardness": 100}); + if let Some(m) = mode { + p["mode"] = json!(m); + } + p +} + +fn pixels(s: &Session) -> Vec { + let st = s.active().unwrap(); + let surf = st.doc.layers[0].surface().unwrap(); + (0..48).flat_map(|y| (0..48).flat_map(move |x| surf.pixel(x, y))).collect() +} + +/// The pixel of the Background at (`x`, `y`). +fn pixel(s: &Session, x: i32, y: i32) -> Vec { + let st = s.active().unwrap(); + st.doc.layers[0].surface().unwrap().pixel(x, y) +} + +#[test] +fn replace_paints_the_source_pixels_bit_for_bit() { + let mut s = document(); + let before = pixels(&s); + let steps = s.active().unwrap().history.past_len(); + s.execute("paint.healingBrush", stroke(Some("replace"))).unwrap(); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Healing Brush"), "the stroke's History name"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "the stroke is one step"); + // Every pixel the hard tip covers fully (out to 8.48 px of its 10 px radius, away from the + // antialiased rim) is the source pixel mapped there, bit for bit; the samples are the + // pre-stroke pixels. + let green: Vec = vec![40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0, 1.0]; + let ch = pixel(&s, 0, 0).len(); + let src = |x: i32, y: i32| { + let at = usize::try_from(y * 48 + x).unwrap() * ch; + before[at..at + ch].to_vec() + }; + let mut inside = 0; + for dy in -9i32..=9 { + for dx in -9i32..=9 { + // The exact-copy disc reaches to a pixel-centre distance under 9 px of the 10 px hard + // tip: (6, 6) has its centre at 9.19 px and already sits in the antialiased rim, where + // Replace lays the source through its coverage (the hardness-50 test below pins that). + let (ax, ay) = (f64::from(dx.abs()) + 0.5, f64::from(dy.abs()) + 0.5); + if ax * ax + ay * ay >= 81.0 { + continue; + } + let (x, y) = (30 + dx, 24 + dy); + assert_eq!(pixel(&s, x, y), src(x - 14, y - 8), "({x}, {y}) inside the Replace dab"); + inside += 1; + } + } + // The exact-copy disc this engine gives for a 20 px hard tip: 221 pixels (widened from the + // first round's r = 7 disc of 149; the rim test covers what lies beyond). + assert_eq!(inside, 221, "the loop's own shape"); + // Outside the tip nothing changed: the dab's edge is 10 px away, these are 13. + assert_eq!(pixel(&s, 43, 24), green, "right of the dab"); + assert_eq!(pixel(&s, 30, 37), green, "below the dab"); +} + +#[test] +fn replace_at_partial_coverage_lays_the_source_through_the_coverage() { + // The rim of Replace is coverage, not a hard copy edge: a pixel the tip covers only partly + // takes the source pixel composited over the ground by that coverage - strictly between the + // two, and neither one exactly. (The reference's rim, measured on its own document, is about + // 1 px wider than ours; the exact rim width here is not measured.) + let mut s = document(); + let before = pixels(&s); + let mut p = stroke(Some("replace")); + p["hardness"] = json!(50); + s.execute("paint.healingBrush", p).unwrap(); + let q = |v: f32| (v * 255.0).round() as i32; + let lvl = |x: i32, y: i32| { + let at = usize::try_from(y * 48 + x).unwrap() * 4; + [before[at], before[at + 1], before[at + 2]].map(q) + }; + // The tip's centre still holds the full copy: source 6,6..26 puts a 60-cell under the centre. + let centre = pixel(&s, 30, 24); + assert_eq!(centre.iter().map(|&v| q(v)).collect::>(), vec![60, 60, 60, 255], "centre: straight copy at full coverage"); + // 8 px out on a hardness-50 tip the coverage is partial: over the pre-stroke green the 200 + // cell now lies at about 40 %, so the levels sit strictly between the ground and the source. + let rim = pixel(&s, 38, 24).iter().map(|&v| q(v)).collect::>(); + let (src, ground) = (lvl(24, 16), [40, 160, 60]); // the 200-cell source pixel this rim copies from + assert_eq!(src, [200, 200, 200], "fixture check: the rim samples a 200-cell"); + for c in 0..3 { + assert!( + rim[c] > ground[c].min(src[c]) && rim[c] < ground[c].max(src[c]), + "rim {rim:?} channel {c}: between ground {ground:?} and source {src:?}, not either" + ); + } + // And not the full copy the interior shows. + assert_ne!(rim[..3], [200, 200, 200], "the rim is not a hard copy to the tip edge"); +} + +#[test] +fn an_unknown_mode_is_an_error_and_paints_nothing() { + let mut s = document(); + let before = (pixels(&s), s.active().unwrap().history.past_len()); + let err = s.execute("paint.healingBrush", stroke(Some("threshold"))).unwrap_err().to_string(); + assert!(err.contains("unknown blend mode `threshold`"), "{err}"); + assert_eq!((pixels(&s), s.active().unwrap().history.past_len()), (before.0.clone(), before.1), "nothing painted, no step"); +} + +#[test] +fn replace_is_the_healing_brush_command_s_alone() { + let mut s = document(); + let err = s + .execute("paint.cloneStamp", json!({"points": [[30, 24]], "source": [16, 16], "size": 20, "hardness": 100, "mode": "replace"})) + .unwrap_err() + .to_string(); + assert!(err.contains("unknown blend mode `replace`"), "the Clone Stamp still refuses it: {err}"); + // The live stroke parser reads the same mode: a Healing live stroke starts with Replace. + crate::cmd::retouch_cmds::clone::LiveRetouch::begin(&s, "paint.healingBrush", &stroke(Some("replace"))).unwrap(); + // And the blend parameter itself: Normal compositing for the Healing Brush, nothing else. + assert_eq!(blend_param(&json!({"mode": "replace"}), "paint.healingBrush").unwrap(), BlendMode::Normal); + assert!(blend_param(&json!({"mode": "replace"}), "paint.cloneStamp").is_err()); + assert!(blend_param(&json!({"mode": "Replace"}), "paint.healingBrush").is_err(), "the exact lowercase string only"); +} + +#[test] +fn normal_heals_the_same_pixels_as_before() { + // Pin the healed (not copied) result byte for byte: the values from main 984c304b20. If one of + // these moves, a mode the ticket leaves alone moved with it. + let mut s = document(); + s.execute("paint.healingBrush", stroke(Some("normal"))).unwrap(); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Healing Brush")); + let q = |v: f32| (v * 255.0).round() as i32; + let pts = [(30, 24), (34, 26), (26, 22), (24, 24)]; + let got: Vec> = pts.iter().map(|(x, y)| pixel(&s, *x, *y).iter().map(|&v| q(v)).collect()).collect(); + // The values main 984c304b20 gives on this document (R, G, B, A in 8-bit levels). + let pinned: Vec> = vec![vec![62, 56, 61, 255], vec![57, 63, 58, 255], vec![77, 49, 73, 255], vec![82, 53, 77, 255]]; + assert_eq!(got, pinned, "the Normal result is pinned"); + // Replace on the same document gives different pixels than Normal: the straight copy and the + // blend are visibly two different strokes. + let mut r = document(); + r.execute("paint.healingBrush", stroke(Some("replace"))).unwrap(); + let replaced: Vec> = pts.iter().map(|(x, y)| pixel(&r, *x, *y).iter().map(|&v| q(v)).collect()).collect(); + assert_ne!(got, replaced, "Replace is not Normal"); +} diff --git a/crates/engine-paint/src/cmd/retouch_cmds/history_brush_transparency_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/history_brush_transparency_tests.rs new file mode 100644 index 0000000000..f87ca40405 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/history_brush_transparency_tests.rs @@ -0,0 +1,107 @@ +//! #14701: the History Brush in Normal mode restores the source state's pixels, transparency +//! included, instead of laying them over what is there now. Painting a moved subject's new place +//! from the state before the move clears it again (no "ghost" double image), at the stroke's +//! opacity, and the live stroke shows what the commit paints. Other modes still composite. + +use serde_json::json; + +use super::*; + +const W: i32 = 48; +const H: i32 = 16; +const RED: [f32; 4] = [0.8, 0.1, 0.1, 1.0]; + +/// A `depth` RGB document with a layer over the Background holding a red subject on its left +/// half (History row 2), then the subject moved to the right half (row 3, the current state). +fn moved(depth: u64) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": W, "height": H, "depth": depth, "mode": "rgb"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + for left in [true, false] { + s.edit("setup", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let data: Vec = (b.y0..b.y1) + .flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))) + .flat_map(|(x, _)| photocraft_raster::from_rgba(&fmt, if (x < W / 2) == left { RED } else { [0.0; 4] })) + .collect(); + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + } + s +} + +/// A stroke across the whole layer from History row 2 (the subject still on the left). +fn stroke(extra: Value) -> Value { + let mut p = json!({"points": [[0, 8], [W, 8]], "size": 40, "hardness": 100, "state": 2}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + p +} + +fn layer_rgba(doc: &Document, s: &Session, x: i32, y: i32) -> [f32; 4] { + doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn close(a: [f32; 4], b: [f32; 4], tol: f32) -> bool { + a.iter().zip(b).all(|(a, b)| (a - b).abs() <= tol) +} + +#[test] +fn history_brush_restores_transparency_from_the_source_state() { + for depth in [8u64, 16, 32] { + let mut s = moved(depth); + s.execute("paint.historyBrush", stroke(json!({}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let (left, right) = (layer_rgba(&doc, &s, 8, 8), layer_rgba(&doc, &s, 40, 8)); + assert!(close(left, RED, 0.01), "depth {depth}: the subject comes back on the left: {left:?}"); + assert!(right[3] < 0.01, "depth {depth}: the moved subject is cleared, no ghost: {right:?}"); + } +} + +#[test] +fn history_brush_restores_transparency_at_the_stroke_opacity() { + for depth in [8u64, 16, 32] { + let mut s = moved(depth); + s.execute("paint.historyBrush", stroke(json!({"opacity": 50}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let (left, right) = (layer_rgba(&doc, &s, 8, 8), layer_rgba(&doc, &s, 40, 8)); + assert!((left[3] - 0.5).abs() < 0.01 && close([left[0], left[1], left[2], 1.0], RED, 0.01), "depth {depth}: half the subject back: {left:?}"); + assert!((right[3] - 0.5).abs() < 0.01 && close([right[0], right[1], right[2], 1.0], RED, 0.01), "depth {depth}: half cleared: {right:?}"); + } +} + +#[test] +fn live_history_brush_shows_the_restored_transparency() { + for depth in [8u64, 32] { + let s = moved(depth); + let live = super::super::LiveRetouch::begin(&s, "paint.historyBrush", &stroke(json!({}))).unwrap(); + let (left, right) = (layer_rgba(&live.doc, &s, 8, 8), layer_rgba(&live.doc, &s, 40, 8)); + assert!(close(left, RED, 0.01), "depth {depth}: {left:?}"); + assert!(right[3] < 0.01, "depth {depth}: the live stroke clears the moved subject: {right:?}"); + } +} + +#[test] +fn other_modes_and_locked_transparency_keep_compositing() { + // Multiply of a transparent source changes nothing: the moved subject stays. + let mut s = moved(8); + s.execute("paint.historyBrush", stroke(json!({"mode": "multiply"}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + assert!(close(layer_rgba(&doc, &s, 40, 8), RED, 0.01)); + // Locked transparency keeps the layer's alpha: nothing to clear, nothing to restore. + let mut s = moved(8); + s.edit("lock", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; + Ok(()) + }) + .unwrap(); + s.execute("paint.historyBrush", stroke(json!({}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + assert!(close(layer_rgba(&doc, &s, 40, 8), RED, 0.01)); + assert!(layer_rgba(&doc, &s, 8, 8)[3] < 0.01); +} diff --git a/crates/engine/tests/it/atn_content_aware_fill.rs b/crates/engine/tests/it/atn_content_aware_fill.rs index 3c7c4b7c52..736508633d 100644 --- a/crates/engine/tests/it/atn_content_aware_fill.rs +++ b/crates/engine/tests/it/atn_content_aware_fill.rs @@ -152,10 +152,11 @@ fn caf_edited_settings_export_without_stale_wire_metadata() { } /// Missing defaults, malformed/repeated fields and unrepresented workspace state stay complete. +/// An empty descriptor plays with the remembered settings (`atn_cmds/caf_action_values_tests.rs`). #[test] fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { let base = descriptor(); - let mut cases = vec![Descriptor::new("null"), base.clone().with("extra", D::Boolean(true))]; + let mut cases = vec![base.clone().with("extra", D::Boolean(true))]; for i in 0..base.items.len() { let mut missing = base.clone(); missing.items.remove(i); @@ -167,20 +168,9 @@ fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { wrong.items[i].1 = D::Integer(0); cases.push(wrong); } - for (i, key, value) in [ - (0, "cafSamplingRegion", "cafSamplingRegionAuto"), - (0, "cafSamplingRegion", "cafSamplingRegionCustom"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationNone"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationHigh"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationVeryHigh"), - (2, "cafColorAdaptationLevel", "unknown"), - (3, "cafRotationAmount", "cafRotationAmountLow"), - (3, "cafRotationAmount", "cafRotationAmountMedium"), - (3, "cafRotationAmount", "cafRotationAmountHigh"), - (3, "cafRotationAmount", "cafRotationAmountFull"), - (3, "cafRotationAmount", "unknown"), - (6, "cafOutput", "cafOutputToDuplicateLayer"), - ] { + for (i, key, value) in + [(0, "cafSamplingRegion", "unknown"), (2, "cafColorAdaptationLevel", "unknown"), (3, "cafRotationAmount", "unknown"), (6, "cafOutput", "unknown")] + { let mut d = base.clone(); d.items[i].1 = enm(key, value); cases.push(d); @@ -213,28 +203,25 @@ fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { /// Known native defaults become explicit values; unsupported defaults/options cannot disappear. #[test] fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_options() { - for p in [json!({"sampling":"rectangular","output":"new"}), json!({"sampling":"rectangular","output":"new","seed":1,"target":"pixels"}), params()] { + for p in [ + json!({"sampling":"rectangular","sampleAllLayers":false,"output":"new"}), + json!({"sampling":"rectangular","sampleAllLayers":false,"output":"new","seed":1,"target":"pixels"}), + params(), + ] { let a = load(exported(p).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, params())]); } let mut current = params(); current["output"] = json!("current"); - for p in [json!({"sampling":"rectangular"}), current.clone()] { + for p in [json!({"sampling":"rectangular","sampleAllLayers":false}), current.clone()] { let a = load(exported(p).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, current.clone())]); } for (key, value) in [ - ("sampling", json!("auto")), - ("sampling", json!("custom")), ("sampling", json!("unknown")), - ("output", json!("duplicate")), - ("colorAdaptation", json!("none")), - ("colorAdaptation", json!("high")), - ("colorAdaptation", json!("veryHigh")), - ("rotationAdaptation", json!("low")), - ("rotationAdaptation", json!("medium")), - ("rotationAdaptation", json!("high")), - ("rotationAdaptation", json!("full")), + ("output", json!("unknown")), + ("colorAdaptation", json!("unknown")), + ("rotationAdaptation", json!("unknown")), ("sampleAllLayers", json!(0)), ("scale", Value::Null), ("mirror", json!("true")), @@ -252,8 +239,19 @@ fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_optio p[key] = value; assert!(exported(p.clone()).is_none(), "{p}"); } - for p in [json!({}), json!({"output":"new"}), json!([])] { - assert!(exported(p.clone()).is_none(), "unrepresented native default: {p}"); + // The command's own defaults (Auto, Current Layer) are written out explicitly. + let mut defaults = params(); + defaults["sampling"] = json!("auto"); + defaults["output"] = json!("current"); + let a = load(exported(json!({"sampleAllLayers":false})).unwrap().descriptor.unwrap()); + assert_eq!(a.steps, vec![ActionStep::new(CMD, defaults.clone())]); + defaults["output"] = json!("new"); + let a = load(exported(json!({"sampleAllLayers":false,"output":"new"})).unwrap().descriptor.unwrap()); + assert_eq!(a.steps, vec![ActionStep::new(CMD, defaults)]); + assert!(exported(json!([])).is_none()); + // Without `sampleAllLayers` an empty layer samples the composite, and a recorded false would not. + for p in [json!({}), json!({"output":"new"}), json!({"colorAdaptation":"none"}), json!({"sampling":"rectangular"})] { + assert!(exported(p.clone()).is_none(), "unrepresented sampling: {p}"); } } diff --git a/crates/engine/tests/it/layers_thumbnail_history_names.rs b/crates/engine/tests/it/layers_thumbnail_history_names.rs new file mode 100644 index 0000000000..948f51158d --- /dev/null +++ b/crates/engine/tests/it/layers_thumbnail_history_names.rs @@ -0,0 +1,110 @@ +//! History names of the Layers panel's thumbnail gestures (#16786), run with the params the panel sends, and the +//! Layer and Select menus' calls of the same commands, which keep their names. + +use photocraft_engine::Session; +use serde_json::{Value, json}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s +} + +fn active(s: &Session) -> u64 { + s.active().unwrap().active_layer.unwrap().0 +} + +/// A new pixel layer filled with red, active. +fn pixel_layer(s: &mut Session) -> u64 { + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + active(s) +} + +/// The name of the one history state `cmd` with `params` adds. +fn step(s: &mut Session, cmd: &str, params: Value) -> String { + let before = s.active().unwrap().history.entries().len(); + s.execute(cmd, params.clone()).unwrap_or_else(|e| panic!("{cmd} {params}: {e}")); + let after = s.active().unwrap().history.entries(); + assert_eq!(after.len(), before + 1, "{cmd} {params} adds one state: {after:?}"); + after[before].clone() +} + +/// ⌘-click (with ⇧ / ⌥ too) on a pixel, type, smart object or adjustment thumbnail, Select Pixels and ⌘-click on a +/// layer mask are `Load Selection`; on a shape thumbnail or a vector mask, `Selection Change`. +#[test] +fn thumbnail_loads_are_named_as_their_kind() { + let mut s = session(); + let pixel = pixel_layer(&mut s); + pixel_layer(&mut s); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let smart = active(&s); + let typ = s.execute("type.create", json!({"text": "A", "x": 5, "y": 20})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + let adjustment = active(&s); + for layer in [pixel, smart, typ, adjustment] { + for operation in ["new", "add", "subtract", "intersect"] { + let params = json!({"channel": "transparency", "layer": layer, "operation": operation}); + assert_eq!(step(&mut s, "select.loadSelection", params), "Load Selection", "layer {layer}, {operation}"); + } + } + s.execute("layer.layerMask.revealAll", json!({"layer": pixel})).unwrap(); + assert_eq!(step(&mut s, "select.loadSelection", json!({"channel": "mask", "layer": pixel, "operation": "new"})), "Load Selection"); + + let shape = s.execute("shape.create", json!({"kind": "rect", "rect": [2, 2, 20, 20]})).unwrap()["layer"].as_u64().unwrap(); + let params = json!({"channel": "transparency", "layer": shape, "operation": "new"}); + assert_eq!(step(&mut s, "select.loadSelection", params), "Selection Change", "shape thumbnail"); + s.execute("layer.vectorMask.revealAll", json!({"layer": pixel})).unwrap(); + let params = json!({"channel": "vectorMask", "layer": pixel, "operation": "add"}); + assert_eq!(step(&mut s, "select.loadSelection", params), "Selection Change", "vector mask"); +} + +/// Select › Load Selection names no layer, and keeps its names. +#[test] +fn the_menu_load_keeps_its_names() { + let mut s = session(); + let layer = pixel_layer(&mut s); + s.execute("layer.layerMask.revealAll", json!({"layer": layer})).unwrap(); + assert_eq!(step(&mut s, "select.loadSelection", json!({"channel": "transparency"})), "Load Transparency"); + assert_eq!(step(&mut s, "select.loadSelection", json!({"channel": "mask"})), "Load Layer Mask"); +} + +/// ⇧-click on a mask and the chain say which way they went; the Layer menu's plain toggles keep their names. +#[test] +fn mask_toggles_and_chains_name_their_direction() { + let mut s = session(); + let layer = pixel_layer(&mut s); + s.execute("layer.layerMask.revealAll", json!({"layer": layer})).unwrap(); + s.execute("layer.vectorMask.revealAll", json!({"layer": layer})).unwrap(); + let cases = [ + ("layer.layerMask.enabled", "enabled", ["Disable Layer Mask", "Enable Layer Mask"], "Enable/Disable Layer Mask"), + ("layer.layerMask.linked", "linked", ["Unlink Mask", "Link Mask"], "Link/Unlink Layer Mask"), + ("layer.vectorMask.enabled", "enabled", ["Disable Vector Mask", "Enable Vector Mask"], "Edit Vector Mask"), + ("layer.vectorMask.linked", "linked", ["Unlink Vector Mask", "Link Vector Mask"], "Edit Vector Mask"), + ]; + for (cmd, key, [off, on], toggle) in cases { + assert_eq!(step(&mut s, cmd, json!({"layer": layer, key: false})), off); + assert_eq!(step(&mut s, cmd, json!({"layer": layer, key: true})), on); + assert_eq!(step(&mut s, cmd, json!({})), toggle, "{cmd} from the menu"); + } +} + +/// Dragging a layer mask onto another layer, or ⌥-dragging a copy there, is one `Add Layer Mask` state, and one undo +/// puts both layers back. +#[test] +fn a_mask_drop_is_one_add_layer_mask_state() { + for copy in [false, true] { + let mut s = session(); + let from = pixel_layer(&mut s); + let to = pixel_layer(&mut s); + s.execute("layer.layerMask.revealAll", json!({"layer": from})).unwrap(); + let before = s.active().unwrap().doc.clone(); + assert_eq!(step(&mut s, "layer.layerMask.moveTo", json!({"layer": from, "to": to, "copy": copy})), "Add Layer Mask", "copy {copy}"); + s.execute("edit.undo", json!({})).unwrap(); + let doc = &s.active().unwrap().doc; + for id in [from, to] { + let has_mask = |d: &photocraft_doc::Document| d.layer(photocraft_doc::LayerId(id)).unwrap().mask.is_some(); + assert_eq!(has_mask(doc), has_mask(&before), "copy {copy}: one undo restores layer {id}"); + } + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 69b4cb0840..eac618e76d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -92,6 +92,7 @@ mod layer_delete_last; mod layer_mask_depth; mod layer_props_several; mod layer_range_panel_order; +mod layers_thumbnail_history_names; mod live_dab_matches_replay; mod live_line_transform; mod magnetic_lasso_composite; diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 8819e5f778..658849859e 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -298,22 +298,41 @@ fn offset(angle: f32, distance: f32) -> (f32, f32) { ((-a.cos() * distance).round(), (a.sin() * distance).round()) } +/// Which shape supplies the distance fields for a layer style stroke. +#[derive(Clone, Copy)] +pub(crate) enum StrokeShape { + Raster, + VectorOutline, + Other, +} + +impl StrokeShape { + pub(crate) fn of(layer: &Layer) -> Self { + match &layer.content { + LayerContent::Raster(_) => Self::Raster, + LayerContent::Shape(_) if photocraft_compose::effect_outline(layer).is_none() => Self::VectorOutline, + _ => Self::Other, + } + } +} + /// The map program of one enabled effect (`build_maps`), without pattern sources. #[cfg(test)] pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> MapProgram { - program_with(e, light, vector_shape, &[], (0.0, 0.0)) + let shape = if vector_shape { StrokeShape::VectorOutline } else { StrokeShape::Raster }; + program_with(e, light, shape, &[], (0.0, 0.0)) } /// The map program of one enabled effect (`build_maps`); bevel textures tile `patterns` from /// `anchor` (`effects::TextureCtx`). -pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool, patterns: &[Pattern], anchor: (f64, f64)) -> MapProgram { +pub(crate) fn program_with(e: &Effect, light: &GlobalLight, stroke_shape: StrokeShape, patterns: &[Pattern], anchor: (f64, f64)) -> MapProgram { let mut b = B { stages: Vec::new(), fields: Vec::new() }; let maps = match e { Effect::DropShadow(s) | Effect::InnerShadow(s) => b.shadow(s, light, matches!(e, Effect::InnerShadow(_))), Effect::OuterGlow(g) | Effect::InnerGlow(g) => b.glow(g, matches!(e, Effect::InnerGlow(_))), Effect::Satin(s) => b.satin(s), Effect::BevelEmboss(bv) => b.bevel(bv, light, patterns, anchor), - Effect::Stroke(st) => b.stroke(st, vector_shape), + Effect::Stroke(st) => b.stroke(st, stroke_shape), Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } | Effect::PatternOverlay { .. } => return MapProgram::empty(), }; MapProgram { key: b.key(maps), maps, stages: b.stages, fields: b.fields } @@ -554,6 +573,7 @@ pub(crate) fn group_key(layer: &Layer, light: &GlobalLight, pin: &mut dyn FnMut( } fn walk(l: &Layer, h: &mut std::collections::hash_map::DefaultHasher, pin: Pin) { l.id.0.hash(h); + std::mem::discriminant(&l.content).hash(h); (l.visible, l.clipped, l.opacity.to_bits(), l.fill_opacity.to_bits(), format!("{:?}", l.blend)).hash(h); match &l.content { LayerContent::Group(g) => { diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs index 633382b8fe..ff48eae03a 100644 --- a/crates/gpu/src/fx/builders.rs +++ b/crates/gpu/src/fx/builders.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use photocraft_compose::effects::{self as fx, BevelGeom, BevelPaint, FieldKind}; use photocraft_doc::{Bevel, BevelTechnique, BevelTexture, GlobalLight, Glow, GlowSource, GlowTechnique, Pattern, Satin, Shadow, StrokeFx}; -use super::{B, In, contour_lut, offset, stage}; +use super::{B, In, StrokeShape, contour_lut, offset, stage}; use crate::plan::{Kernel, stroke_widths}; /// A flag as the shaders read it: 1.0 or 0.0. @@ -178,13 +178,13 @@ impl B { } /// Stroke stages, the outside band into map 0 and the inside band into map 1. Returns 2. - pub(super) fn stroke(&mut self, st: &StrokeFx, vector_shape: bool) -> usize { + pub(super) fn stroke(&mut self, st: &StrokeFx, shape: StrokeShape) -> usize { // Stroke bands: map 0 outside, map 1 inside. let (in_w, out_w) = stroke_widths(st); if out_w > 0.0 { // Narrow strokes keep the fitted chamfer, wide ones the exact transform (#3646); // the CPU picks the same field by the same width (`stroke_outside_exact`). - let kind = match (vector_shape, fx::stroke_outside_exact(out_w)) { + let kind = match (matches!(shape, StrokeShape::VectorOutline), fx::stroke_outside_exact(out_w)) { (true, true) => FieldKind::StrokeOutsideVector, (true, false) => FieldKind::StrokeOutsideVectorChamfer, (false, true) => FieldKind::StrokeOutsideExact, @@ -193,7 +193,8 @@ impl B { self.stroke_band(kind, out_w, 0); } if in_w > 0.0 { - self.stroke_band(FieldKind::StrokeInside, in_w, 1); + let kind = if matches!(shape, StrokeShape::Raster) { FieldKind::StrokeInsideRaster } else { FieldKind::StrokeInside }; + self.stroke_band(kind, in_w, 1); } 2 } diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs index 06342c2fb2..a8d3667e63 100644 --- a/crates/gpu/src/fx/tests.rs +++ b/crates/gpu/src/fx/tests.rs @@ -122,6 +122,7 @@ fn banded_fields_match_whole_region_within_reach() { FieldKind::ChokeInside, FieldKind::StrokeOutside, FieldKind::StrokeInside, + FieldKind::StrokeInsideRaster, FieldKind::StrokeOutsideExact, FieldKind::StrokeOutsideVector, FieldKind::StrokeOutsideVectorChamfer, @@ -266,7 +267,7 @@ fn a_stroke_uses_the_chamfer_narrow_and_the_exact_field_wide() { let vector_wide = program(&stroke(40.0, StrokePosition::Outside), &light, true); assert!(vector_wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVector), "{:?}", vector_wide.fields); let inner = program(&stroke(40.0, StrokePosition::Inside), &light, false); - assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInside), "{:?}", inner.fields); + assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInsideRaster), "{:?}", inner.fields); // The shadow / softer-glow spread is unchanged: still the chamfer. let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; s.spread = 0.5; diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs index 615677d840..a02b81b611 100644 --- a/crates/gpu/src/fx_passes.rs +++ b/crates/gpu/src/fx_passes.rs @@ -114,10 +114,10 @@ impl Compositor { // Programs, and the distance fields they read (max reach per field). // Filled shapes stroke their outline (the effect shape); others estimate it. - let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(layer).is_none(); + let stroke_shape = fx::StrokeShape::of(layer); let anchor = layer.effects.reference.unwrap_or((f64::from(f.bounds.x0), f64::from(f.bounds.y0))); let progs: Vec = - layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect(); + layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, stroke_shape, &doc.patterns, anchor)).collect(); let want = field_reaches(&progs); e.fields.retain(|k, _| want.contains_key(k)); // Each field to recompute: over which rectangle, exact up to which reach. diff --git a/crates/gpu/src/setup.rs b/crates/gpu/src/setup.rs index 3a96107499..3faeb5c8bb 100644 --- a/crates/gpu/src/setup.rs +++ b/crates/gpu/src/setup.rs @@ -4,7 +4,7 @@ use super::kit::{Kit, tex_entry, uniform_entry}; use super::paging::{cell_rect, field_reaches, first_error, grid_rects}; use super::pipelines::{NO_EFFECT_MAPS, Pipelines}; use super::textures::{FxEntry, Resident, Tex, TexKind}; -use super::{Compositor, DeviceHealth, DocId, Document, Fault, HashMap, LayerContent, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing}; +use super::{Compositor, DeviceHealth, DocId, Document, Fault, HashMap, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing}; /// Classification of a synchronous compositor pipeline build failure. /// @@ -356,14 +356,14 @@ impl Compositor { /// How far beyond a page cell the effect maps of `f` must be computed to be exact in it. pub(crate) fn fx_apron(doc: &Document, f: &plan::FxLayer<'_>) -> i32 { - let vector_shape = matches!(f.layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(f.layer).is_none(); + let stroke_shape = fx::StrokeShape::of(f.layer); let progs: Vec = f .layer .effects .items .iter() .filter(|e| e.enabled()) - .map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, (0.0, 0.0))) + .map(|e| fx::program_with(e, &doc.global_light, stroke_shape, &doc.patterns, (0.0, 0.0))) .collect(); let want = field_reaches(&progs); // Distance fields are exact one pixel inside the window they are computed from. @@ -394,7 +394,7 @@ impl Compositor { if noisy { return Err(Unsupported(format!("effect noise on `{}` uses the CPU path", f.layer.name))); } - for s in fx::program_with(e, &doc.global_light, false, &doc.patterns, (0.0, 0.0)).stages { + for s in fx::program_with(e, &doc.global_light, fx::StrokeShape::Other, &doc.patterns, (0.0, 0.0)).stages { if s.lut.as_ref().is_some_and(|l| l.len() > 4096) { return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name))); } diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 6c68854ffc..d3ffa24f21 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -2029,6 +2029,29 @@ fn semi_transparent_normal_stroke_knocks_out_the_layer_beneath_it() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +#[test] +fn stroke_on_partial_raster_alpha_matches_on_gpu_across_page_boundaries() { + let Some(mut g) = gpu() else { return }; + let mut doc = Document::with_background("Partial alpha strokes", Size::new(540, 300), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut layer = Layer::raster("Orange blocks", doc.pixel_format()); + let surface = layer.surface_mut().unwrap(); + for (x, alpha) in [(20, 1.0), (236, 0.5), (460, 0.25)] { + surface.fill_rect(Rect::from_xywh(x, 40, 44, 220), &[1.0, 128.0 / 255.0, 0.0, alpha]); + } + doc.layers.push(layer); + for (position, size) in [(StrokePosition::Inside, 5.0), (StrokePosition::Center, 6.0), (StrokePosition::Outside, 5.0)] { + doc.layers[1].effects.items = vec![Effect::Stroke(stroke(size, position, FxPaint::Color(Color::rgb(0.0, 0.0, 1.0))))]; + let stats = fx_check(&mut g, &doc, &format!("{position:?} stroke across pages")); + assert!(stats.passes > 0, "the GPU rendered the effect"); + } + + // Retouching the same tile from translucent to opaque must invalidate its inside field. + doc.layers[1].effects.items = vec![Effect::Stroke(stroke(5.0, StrokePosition::Inside, FxPaint::Color(Color::rgb(0.0, 0.0, 1.0))))]; + fx_check(&mut g, &doc, "cached inside stroke"); + doc.layers[1].surface_mut().unwrap().fill_rect(Rect::from_xywh(248, 112, 24, 32), &[1.0, 128.0 / 255.0, 0.0, 1.0]); + fx_check(&mut g, &doc, "inside stroke after changing partial alpha"); +} + #[test] fn exterior_effects_merge_from_the_shape_at_any_fill() { // Drop shadows and outer glows alone: the merge builds the layer from its shape (fill inside diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b18d478209..b879107690 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1276,6 +1276,7 @@ fn export_stages_with_renderer( document_path: opts.document_path.clone(), read_linked_files: opts.read_linked_files, stage_on_scratch_from: Some(psd_export::STAGE_DOCUMENTS_FROM), + embed_icc: opts.encode.embed_icc, ..Default::default() }; // The preview is rendered first, while only the document is in memory: its full-size diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 1f2a3a3e3a..8f1e054a57 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -80,6 +80,9 @@ pub struct PsdExportOptions { /// pixel bytes (layers and composite) reach this and spilling is on (`None`: never). The /// save then holds the file model's structure, not a second copy of its pixels (#5333). pub stage_on_scratch_from: Option, + /// Write the document's ICC profile (resource 1039). Off leaves it out of the file only: the + /// document's colours are still read through it (a CMYK document's layers and merged image). + pub embed_icc: bool, } impl Default for PsdExportOptions { @@ -93,6 +96,7 @@ impl Default for PsdExportOptions { document_path: None, read_linked_files: true, stage_on_scratch_from: None, + embed_icc: true, } } } diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index 1755a37ee6..16a48c5249 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -66,7 +66,11 @@ fn document_to_psd_sized_with_patterns( if doc.mode == ColorMode::Multichannel { return crate::multichannel_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns); } - if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns)? { + if let Some(mut file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns)? { + // An Indexed document's RGB profile is written there too; Include ICC Profile off leaves it out. + if !opts.embed_icc { + file.0.resources.retain(|r| r.id != ids::ICC_PROFILE); + } return Ok(file); } let fmt = doc.pixel_format(); @@ -149,7 +153,7 @@ fn export_supported_document( ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), ]; - if let Some(icc) = &doc.icc_profile { + if let Some(icc) = doc.icc_profile.as_ref().filter(|_| opts.embed_icc) { resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec())); } if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() { diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index 2284c4e86a..89c8b16479 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -862,3 +862,36 @@ fn a_type_layer_without_a_writable_tysh_drops_its_imported_block() { assert!(!written.blocks.iter().any(|b| b.key == *b"TySh"), "the stale imported TySh is dropped"); assert!(warnings.iter().any(|w| w.contains("no TySh data")), "{warnings:?}"); } + +/// `embed_icc: false` leaves the ICC profile resource out of the file (the document keeps it); +/// on (the default), the file carries it. +#[test] +fn embed_icc_off_writes_no_profile_resource() { + let mut doc = Document::new("icc", photocraft_geom::Size::new(4, 4), ColorMode::Rgb, SampleType::U8); + doc.layers.push(Layer::raster("Layer 1", doc.pixel_format())); + doc.icc_profile = Some(std::sync::Arc::new(craft_cms::Builtin::Srgb.profile().to_bytes().to_vec())); + let has = |opts: &PsdExportOptions| document_to_psd_with(&doc, opts).unwrap().0.resources.iter().any(|r| r.id == ids::ICC_PROFILE); + assert!(has(&PsdExportOptions::default())); + assert!(!has(&PsdExportOptions { embed_icc: false, ..Default::default() })); + assert!(doc.icc_profile.is_some()); +} + +/// An Indexed Color document is written over its colour table (`palette_map`): `embed_icc: false` +/// leaves its RGB profile out there too, as PSD and as PSB (CodeRabbit on #16653). +#[test] +fn embed_icc_off_writes_no_profile_resource_for_an_indexed_document() { + let white = photocraft_color::Color::rgba(1.0, 1.0, 1.0, 1.0); + let mut doc = Document::with_background("indexed", photocraft_geom::Size::new(4, 4), ColorMode::Rgb, SampleType::U8, white); + doc.mode = ColorMode::Indexed; + doc.color_table = Some(photocraft_doc::ColorTable { colors: vec![[255, 255, 255], [0, 0, 0]], transparent: None }); + doc.icc_profile = Some(std::sync::Arc::new(craft_cms::Builtin::Srgb.profile().to_bytes().to_vec())); + for force_psb in [false, true] { + let written = |embed_icc| document_to_psd_with(&doc, &PsdExportOptions { embed_icc, force_psb, ..Default::default() }).unwrap().0; + let on = written(true); + assert_eq!(on.header.color_mode, PsdMode::Indexed, "psb {force_psb}"); + assert!(on.resources.iter().any(|r| r.id == ids::ICC_PROFILE), "psb {force_psb}: on"); + let off = written(false); + assert_eq!((off.header.color_mode, off.header.version == Version::Psb), (PsdMode::Indexed, force_psb)); + assert!(!off.resources.iter().any(|r| r.id == ids::ICC_PROFILE), "psb {force_psb}: off"); + } +} diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 0c21f3ea19..f0814956da 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -368,6 +368,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr read_linked_files: opts.read_linked_files, // The layered TIFF reads the merged image's bytes directly: they stay in memory. stage_on_scratch_from: None, + embed_icc: opts.encode.embed_icc, }; // TIFF has no palette, bitmap or duotone layout: the PSD model of an Indexed Color, Bitmap // or Duotone document is made in its pixel format (RGB or Grayscale), which the PSD exporter diff --git a/crates/ipp/Cargo.toml b/crates/ipp/Cargo.toml index b8d05afdaf..94d8bf6793 100644 --- a/crates/ipp/Cargo.toml +++ b/crates/ipp/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true rust-version.workspace = true [dependencies] -craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" } +craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } [lints] workspace = true diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 9ab36bf2de..3735864912 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -202,6 +202,39 @@ pub fn apply_coverage( lock_transparency: bool, paint: &Region, blend: BlendMode, +) -> Rect { + composite_coverage(target, rect, cov, opacity, selection, lock_transparency, paint, blend, false) +} + +/// [`apply_coverage`] for the History Brush (#14701): in Normal mode the paint image *replaces* +/// the pixels at the per-pixel weight (a premultiplied mix, alpha included), so a transparent +/// source pixel clears what is there instead of leaving it under the restored pixels. Other +/// modes, locked transparency and targets without alpha composite as [`apply_coverage`] does. +#[allow(clippy::too_many_arguments)] +pub fn restore_coverage( + target: &mut Surface, + rect: Rect, + cov: &[f32], + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + paint: &Region, + blend: BlendMode, +) -> Rect { + composite_coverage(target, rect, cov, opacity, selection, lock_transparency, paint, blend, true) +} + +#[allow(clippy::too_many_arguments)] +fn composite_coverage( + target: &mut Surface, + rect: Rect, + cov: &[f32], + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + paint: &Region, + blend: BlendMode, + replace: bool, ) -> Rect { if rect.is_empty() { return Rect::EMPTY; @@ -237,7 +270,10 @@ pub fn apply_coverage( } let src = paint.px(x, y); if blend == BlendMode::Normal { - over_native(&fmt, px, src, k, lock_transparency); + match a { + Some(a) if replace && !lock_transparency => mix_premultiplied(px, src, a, k), + _ => over_native(&fmt, px, src, k, lock_transparency), + } } else { // A transparent source cannot paint. Skip it before an RGB round trip changes // untouched native CMYK/Lab values; Normal handles zero weight in over_native. @@ -366,12 +402,14 @@ pub fn mix_back(target: &mut Surface, orig: &Region, work: &Region, rect: Rect, #[inline] pub fn mix_premultiplied(dst: &mut [f32], src: &[f32], a: usize, k: f32) { let (Some(&da), Some(&sa)) = (dst.get(a), src.get(a)) else { return }; - let oa = da + (sa - da) * k; + // Weighted, not `d + (s - d) * k`: at k = 1 the destination drops out exactly, even for + // large 32-bit values (or a tiny alpha next to 1) where the difference would round away the source. + let oa = da * (1.0 - k) + sa * k; for (c, (d, s)) in dst.iter_mut().zip(src).enumerate() { if c == a { continue; } - *d = if oa > 1e-6 { (*d * da + (*s * sa - *d * da) * k) / oa } else { *d + (*s - *d) * k }; + *d = if oa > 0.0 { (*d * da * (1.0 - k) + *s * sa * k) / oa } else { *d * (1.0 - k) + *s * k }; } if let Some(d) = dst.get_mut(a) { *d = oa; @@ -992,6 +1030,28 @@ mod tests { assert_eq!(d, [0.5, 0.5]); } + #[test] + fn premultiplied_mix_at_full_weight_keeps_the_source_exactly() { + let mut d = [67_108_864.0, 0.0, 0.0, 1.0]; + mix_premultiplied(&mut d, &[1.0, 0.0, 0.0, 1.0], 3, 1.0); + assert_eq!(d, [1.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn premultiplied_mix_keeps_colour_at_tiny_alpha() { + // Half of a barely-there 32-bit red over transparent black is still that red, not half of it. + let mut d = [0.0, 0.0, 0.0, 0.0]; + mix_premultiplied(&mut d, &[1.0e6, 0.0, 0.0, 5.0e-7], 3, 0.5); + assert_eq!(d, [1.0e6, 0.0, 0.0, 2.5e-7]); + } + + #[test] + fn premultiplied_mix_at_full_weight_keeps_a_tiny_source_alpha() { + let mut d = [0.0, 0.0, 0.0, 1.0]; + mix_premultiplied(&mut d, &[1.0, 0.0, 0.0, 1.0e-8], 3, 1.0); + assert_eq!(d, [1.0, 0.0, 0.0, 1.0e-8]); + } + #[test] fn footprint_stays_inside_the_tips_reach() { let radius = 10.5f32; diff --git a/crates/text/build.rs b/crates/text/build.rs index 3cc6867ace..f97382430a 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -44,7 +44,8 @@ fn main() { /// Deflate the bundled fonts into `OUT_DIR/fonts/` (`fonts::BUNDLED` includes them). fn deflate_bundled_fonts() { use std::io::Write as _; - let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + // Read at run time: a compiled build script is shared by worktrees with the same unit hash. + let src = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()).join("../../assets/fonts"); let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("fonts"); let result = (|| -> std::io::Result<()> { std::fs::create_dir_all(&out)?; diff --git a/crates/ui-egui/src/alt_click_tests.rs b/crates/ui-egui/src/alt_click_tests.rs index f5055e476d..73f254b34e 100644 --- a/crates/ui-egui/src/alt_click_tests.rs +++ b/crates/ui-egui/src/alt_click_tests.rs @@ -14,7 +14,7 @@ use craft::keymap::Mods; pub(crate) fn harness(app: Box) -> Harness<'static, Box> { let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(900.0, 600.0)).build_app( |ui, app: &mut PhotocraftApp| { - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 613fa6884c..8f07325142 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -116,7 +116,6 @@ impl PhotocraftApp { adjust_open: None, adjust_session: None, properties_hidden: 0, - properties_tracked: false, dialog_dropper: None, layer_style_child: None, color_targets: HashMap::new(), @@ -135,6 +134,7 @@ impl PhotocraftApp { #[cfg(not(target_arch = "wasm32"))] filter_preview_worker: Default::default(), redraws: Default::default(), + redraw_landed: 0, kept: Default::default(), color_range: None, adjust_preview: None, diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 4c16e24817..312bae9034 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -87,7 +87,6 @@ impl PhotocraftApp { if let Some(r) = preset_files_ui::open(self, name, bytes) { return r.map(|()| Vec::new()); } - let name = &self.open_name(name); // Decoded on a worker: a tab with progress appears now, the document when it's ready // (warnings are shown then). if self.background_jobs { @@ -122,6 +121,12 @@ impl PhotocraftApp { let (doc, warnings) = import(name, bytes, &opts)?; (doc, warnings, false) }; + // Decode under the source name; only a successfully opened template becomes untitled. + let opened_name = self.open_name(name); + if opened_name != name { + doc.name = opened_name.clone(); + } + let name = &opened_name; // Preferences › Raw Defaults › Resolution, as the engine's open applies it. photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); // Edit › Color Settings policies apply on open; Ask When Opening holds the file back diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index e15fcfeaac..ec74d98a39 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -154,8 +154,6 @@ impl PhotocraftApp { // A pass whose input carries an injected step acts for the automation client. self.automation_input = WindowHost::of(&ctx).injected_pass(); self.hover_layer = None; - // The contextual task bar reports itself again if this frame draws it (#10890). - self.ui.task_bar_shown = None; i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); let t0 = gpu_canvas::now_ms(); self.perf.stage.ui_start(t0, frame.info().cpu_usage); @@ -231,10 +229,12 @@ impl PhotocraftApp { AppShell::new(WindowKey::main()) .window_title(window_title) .screen_mode(Bind::bound(&mut mode)) - .title_bar_if(menu_bar, |ui, _cx, app| panels::region_versions::show_title_bar(app, ui)) - .options_bar(options_bar && !home, |ui, _cx, app| panels::region_versions::show_options_bar(app, ui)) - .status(status_bar && !home, |ui, _cx, app| panels::status_bar(app, ui)) + .title_bar_if(menu_bar, |app| Some(panels::region_versions::title_bar(app)), |ui, _cx, app| panels::title_bar(app, ui)) + .options_bar(options_bar && !home, |app| Some(panels::region_versions::options_bar(app)), |ui, _cx, app| panels::options_bar(app, ui)) + .status(status_bar && !home, |app| Some(panels::region_versions::status_bar(app)), |ui, _cx, app| panels::status_bar(app, ui)) .body(|ui, cx, app| { + // The body runs every pass; the dock's columns and the document area replay while their versions hold. + canvas::document_area::each_pass(app, ui.ctx()); if home { canvas::document_area(app, ui); } else { diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index ef4e331070..cbc926f374 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -89,5 +89,7 @@ impl PhotocraftApp { // egui's own ⌘+ / ⌘- / ⌘0 scale the whole interface; PhotoCraft zooms the canvas instead // (shortcuts.rs), like Photoshop. ctx.options_mut(|o| o.zoom_with_keyboard = false); + // A pointer move that changes nothing under the pointer runs no frame (#17148). + craft::ui::runtime::pointer::gate_pointer_moves(ctx); } } diff --git a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs index 1c339ff7cb..0bdeb32fc5 100644 --- a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs +++ b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs @@ -52,7 +52,7 @@ fn type_into(h: &mut Harness<'static, Box>, name: &str, text: &st #[test] fn options_bar_fields_that_alert_past_their_range() { type Read = fn(&PhotocraftApp) -> f32; - let o = |a: &PhotocraftApp| -> ToolOptions { a.ui.tool_options.clone() }; + let o = |a: &PhotocraftApp| -> ToolOptions { (*a.ui.tool_options).clone() }; let _ = o; // (tool, field, typed, kept, alerts) let rows: [(Tool, &str, &str, f32, bool, Read); 11] = [ diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index 4b1637a336..8064d1ba62 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -20,6 +20,9 @@ pub(crate) enum Item { Separator, /// The tool's blend mode. Blend(BlendMode), + /// The Healing Brush's Replace row (#12101): copy the source without healing. It is not a + /// blend mode: the stroke sends it as a mode word, and the keys and the ⇧+ / ⇧− cycle skip it. + HealingReplace, /// Painting-only: paint behind the layer's pixels (Brush, Pencil and Pattern Stamp). Behind, /// Painting-only: paint transparency (Brush, Pencil, Paint Bucket). @@ -39,6 +42,7 @@ impl Item { Item::EditBrush => "Edit Brush…", Item::Separator => return None, Item::Blend(m) => m.label(), + Item::HealingReplace => "Replace", Item::Behind => "Behind", Item::Clear => "Clear", Item::Eraser(m) => match m { @@ -98,8 +102,8 @@ fn blend_items(behind: bool, clear: bool) -> Vec { /// `tool`'s menu, top to bottom. Empty for a tool without one (its Shift+right-click keeps its /// other route). Only what the tool's options bar offers is listed: the reference application's -/// Behind for the Clone Stamp, History Brush, Gradient and Paint Bucket, the Blur, Sharpen and Smudge -/// modes, the Spot Healing modes and the Healing Brush's source and Replace have no setting here. +/// Behind for the Clone Stamp, History Brush, Gradient and Paint Bucket, the Blur, Sharpen and +/// Smudge modes, the Spot Healing modes and the Healing Brush's source have no setting here. pub(crate) fn items(tool: Tool) -> Vec { let with_brush = |rest: Vec| std::iter::once(Item::EditBrush).chain(std::iter::once(Item::Separator)).chain(rest).collect::>(); match tool { @@ -110,7 +114,22 @@ pub(crate) fn items(tool: Tool) -> Vec { Tool::Eraser => ["brush", "pencil", "block"].into_iter().map(Item::Eraser).collect(), Tool::Dodge | Tool::Burn => with_brush(["shadows", "midtones", "highlights"].into_iter().map(Item::Range).collect()), Tool::Sponge => with_brush(["desaturate", "saturate"].into_iter().map(Item::Sponge).collect()), - Tool::Healing => crate::blend_keys::HEALING_MODES.into_iter().map(Item::Blend).collect(), + // The measured list (#12101): Replace after Normal, rules before Multiply and before Color. + Tool::Healing => { + use BlendMode::*; + vec![ + Item::Blend(Normal), + Item::HealingReplace, + Item::Separator, + Item::Blend(Multiply), + Item::Blend(Screen), + Item::Blend(Darken), + Item::Blend(Lighten), + Item::Separator, + Item::Blend(Color), + Item::Blend(Luminosity), + ] + } Tool::Gradient => blend_items(false, false), Tool::PaintBucket => blend_items(false, true), _ => Vec::new(), @@ -151,7 +170,15 @@ pub(crate) fn current(app: &PhotocraftApp, tool: Tool) -> Option { Tool::Brush => painting(o.brush_clear), Tool::Pencil => painting(o.pencil_clear), Tool::PatternStamp => painting(false), - Tool::CloneStamp | Tool::HistoryBrush | Tool::Healing => Item::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)), + Tool::CloneStamp | Tool::HistoryBrush => Item::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)), + // Replace wins over the brush's blend mode: it is the row the tool option selects (#12101). + Tool::Healing => { + if o.healing_replace { + Item::HealingReplace + } else { + Item::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)) + } + } Tool::Gradient => Item::Blend(o.gradient_blend_mode), Tool::PaintBucket if o.bucket_clear => Item::Clear, Tool::PaintBucket => Item::Blend(o.bucket_blend_mode), @@ -231,6 +258,8 @@ pub(crate) fn choose(app: &mut PhotocraftApp, item: Item) { Ok(_) => match tool { Tool::Brush => app.ui.tool_options.brush_clear = item == Item::Clear, Tool::Pencil => app.ui.tool_options.pencil_clear = item == Item::Clear, + // Any of the seven blend modes leaves Replace (#12101). + Tool::Healing => app.ui.tool_options.healing_replace = false, _ => {} }, Err(e) => app.ui.status = e, @@ -246,6 +275,8 @@ pub(crate) fn choose(app: &mut PhotocraftApp, item: Item) { Item::Eraser(m) => app.ui.tool_options.eraser_mode = m.into(), Item::Range(r) => app.ui.tool_options.tone_range = r.into(), Item::Sponge(m) => app.ui.tool_options.sponge_mode = m.into(), + // Replace is a tool option: it runs no command and adds no History step (#12101). + Item::HealingReplace if tool == Tool::Healing => app.ui.tool_options.healing_replace = true, Item::Blend(m) if tool == Tool::Gradient => crate::blend_keys::set_gradient_mode(app, m), Item::Blend(m) if tool == Tool::PaintBucket => { app.ui.tool_options.bucket_clear = false; diff --git a/crates/ui-egui/src/brush_picker_escape_tests.rs b/crates/ui-egui/src/brush_picker_escape_tests.rs index d841ee4cb2..dbe4ec4e9b 100644 --- a/crates/ui-egui/src/brush_picker_escape_tests.rs +++ b/crates/ui-egui/src/brush_picker_escape_tests.rs @@ -22,7 +22,7 @@ fn harness() -> Harness<'static, Box> { return; } // The canvas shows the picker itself (`canvas_tool_menu::run`); a second `show_at` would show it twice. - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/brush_picker_memo_trials.rs b/crates/ui-egui/src/brush_picker_memo_trials.rs index fa2b0189c1..08bc761f9c 100644 --- a/crates/ui-egui/src/brush_picker_memo_trials.rs +++ b/crates/ui-egui/src/brush_picker_memo_trials.rs @@ -1,5 +1,5 @@ -//! The canvas Brush Preset picker runs only what changes: open with nothing changing, the whole picker replays, its -//! popover and the focused search field included, and none of its components runs; a Size drag runs the head and replays the list on every move; a preset rename or a new preset +//! The canvas Brush Preset picker runs only what changes: open with nothing changing, the whole picker replays (with the +//! document area around it), its popover and the focused search field included, and none of its components runs; a Size drag runs the head and replays the list on every move; a preset rename or a new preset //! builds the rows once, and the lists settle. use craft::ui::runtime::measure::{MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_runs, last_pass_runs}; @@ -63,8 +63,10 @@ fn an_idle_open_picker_runs_no_component() { assert!(crate::brush_picker::opened_at(h.state()).is_some(), "the picker is open"); for frame in 0..3 { h.run_steps(1); - assert!(views(&h, "CanvasProps", MemoRun::Ran).is_empty(), "idle frame {frame} runs no picker"); - assert!(!views(&h, "CanvasProps", MemoRun::Replayed).is_empty(), "idle frame {frame} replays the picker"); + // The picker replays in its own view, or whole in the document area's view or the docked tree around it. + let holders = ["brush_picker::CanvasProps<", "region_versions::CanvasSlot<", "area::TreeView<"]; + assert!(holders.iter().all(|props| views(&h, props, MemoRun::Ran).is_empty()), "idle frame {frame} runs no picker"); + assert!(holders.iter().any(|props| !views(&h, props, MemoRun::Replayed).is_empty()), "idle frame {frame} replays the picker"); assert_eq!(chrome_runs(&h), 0, "idle frame {frame} runs none of the picker's components: {:?}", last_pass_runs(&h.ctx)); } assert!(h.query_all_by_role(Role::Slider).any(|n| n.accesskit_node().label().is_some_and(|label| label.starts_with("Size")))); diff --git a/crates/ui-egui/src/brush_resize_overlay_tests.rs b/crates/ui-egui/src/brush_resize_overlay_tests.rs index 16a746187c..932a6e97fd 100644 --- a/crates/ui-egui/src/brush_resize_overlay_tests.rs +++ b/crates/ui-egui/src/brush_resize_overlay_tests.rs @@ -15,7 +15,7 @@ fn harness() -> Harness<'static, Box> { app.sync_views(); let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(900.0, 600.0)).build_app( |ui, app: &mut PhotocraftApp| { - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/brush_settle_trials.rs b/crates/ui-egui/src/brush_settle_trials.rs index 43a83c247d..1074ca244b 100644 --- a/crates/ui-egui/src/brush_settle_trials.rs +++ b/crates/ui-egui/src/brush_settle_trials.rs @@ -8,16 +8,17 @@ use egui_kittest::Harness; use serde_json::json; use crate::PhotocraftApp; +use crate::chrome_settle_trials::{ShellSlot, slot_runs}; use crate::state::Tool; type H = Harness<'static, Box>; -/// How the memoized view whose props type is named `props` took part in the last pass. A view inside the options bar's -/// own view (`region_versions::OptionsSlot`) is not decided when that view replays: it replays with it. +/// How the memoized view whose props type is named `props` took part in the last pass. A view inside the options bar is +/// not decided when the shell's options slot replays: it replays with it. fn run_of(h: &H, props: &str) -> Option { let runs = last_pass_memo_runs(&h.ctx); let own = runs.iter().find(|(name, _, _)| name.contains(props)).map(|(_, _, run)| *run); - own.or_else(|| runs.iter().any(|(name, _, run)| name.contains("OptionsSlot<") && *run == MemoRun::Replayed).then_some(MemoRun::Replayed)) + own.or_else(|| (slot_runs(&runs, ShellSlot::Options) == (0, 1)).then_some(MemoRun::Replayed)) } #[test] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f2c04a7201..2af53fa990 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -177,6 +177,10 @@ pub fn canvas_view( primary: bool, ) -> (View, craft::ui::canvas::CanvasOutput) { let ctx = ui.ctx().clone(); + // What the canvas shows follows the pointer (the tool's cursor, the rulers' marks, the Info panel and status bar + // readouts), so every pointer move over it runs a pass; elsewhere a move that changes nothing runs none (#17148). + let on_screen = ctx.layer_transform_to_global(ui.layer_id()).map_or(rect, |to_screen| to_screen * rect); + craft::ui::runtime::pointer::follows_pointer(&ctx, on_screen); let idx = host.idx; // The primary canvas keeps its view in `app.ui.views`: the pass starts from the stored view and stores the one it // ends with, unless something stored another view while the pass ran (a tool's commit that moved it), which then @@ -206,14 +210,6 @@ pub fn canvas_view( // A document switched while a button is down ends the gesture of the document it began on. tools::end_foreign_gesture(app, &ctx, doc.id.0); } - // Pen pressure/tilt for this frame's tool events (mouse = 1.0), unless Preferences › Tools › Use Tablet Pressure - // is off; the pen's eraser end selects the Eraser. - app.stylus.use_pressure = app.session.prefs().tools.use_tablet_pressure; - let curve = app.session.prefs().tools.pressure_curve.clone(); - app.stylus.set_pressure_curve(&curve); - crate::stylus::Stylus::sync_eraser_tool(app); - // A Properties Levels/Curves eyedropper left behind by a tool or layer switch is dropped. - crate::layer_picker::prune(app); let flip = app.ui.view.flip_horizontal; let pass = document_display::CanvasPass { ctx: &ctx, host, doc: &doc, output, rect, ppp, flip, aspect }; let shown = document_display::show(app, ui, &mut view, &pass); @@ -241,6 +237,9 @@ mod pattern_drag_tests; #[cfg(test)] mod tabs_tests; +#[cfg(test)] +mod canvas_settle_trials; + #[cfg(test)] mod doc_window_dialog_tests; diff --git a/crates/ui-egui/src/canvas/arrange_keeps_zoom_tests.rs b/crates/ui-egui/src/canvas/arrange_keeps_zoom_tests.rs new file mode 100644 index 0000000000..252422abf5 --- /dev/null +++ b/crates/ui-egui/src/canvas/arrange_keeps_zoom_tests.rs @@ -0,0 +1,105 @@ +//! #16885: Window › Arrange's n-up and Tile layouts keep each document's zoom and view centre instead of fitting every +//! document to its new pane. + +use egui_kittest::Harness; +use serde_json::json; + +use super::{PhotocraftApp, document_area}; + +type Area = Harness<'static, (Box, bool)>; + +/// Documents of different sizes, each larger than any pane, so fitting them would give each a zoom of its own below +/// 100 %. +const SIZES: [(u32, u32); 6] = [(1600, 1200), (1200, 1600), (2000, 900), (900, 900), (1400, 1000), (1000, 1400)]; + +/// The document area showing `count` documents, after their first passes placed their views. +fn area(count: usize) -> Area { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for (i, (width, height)) in SIZES.iter().take(count).enumerate() { + app.run("file.new", json!({"width": width, "height": height, "name": format!("doc {i}")})).unwrap(); + } + app.sync_views(); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 700.0)).with_context(app.ctx().clone()).build_ui_state( + |ui, (app, ready): &mut (Box, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + h.state_mut().1 = true; + h.run_steps(4); + h +} + +fn set_zoom(h: &mut Area, doc: usize, zoom: f32) { + let view = &mut h.state_mut().0.ui.views[doc]; + view.zoom = zoom; + view.clear_pending(); +} + +fn arrange(h: &mut Area, layout: &str) { + let ctx = h.ctx.clone(); + crate::menus::invoke(&mut h.state_mut().0, &ctx, &format!("window.arrange.{layout}"), json!({})).unwrap(); + h.run_steps(4); +} + +/// Each view's zoom and the document point at its centre. +fn cameras(h: &Area) -> Vec<(f32, [f32; 2])> { + h.state().0.ui.views.iter().map(|view| (view.zoom, view.center)).collect() +} + +fn assert_kept(before: &[(f32, [f32; 2])], after: &[(f32, [f32; 2])], what: &str) { + assert_eq!(before.len(), after.len(), "{what}: every document keeps its view"); + for (d, ((zoom, center), (now, now_center))) in before.iter().zip(after).enumerate() { + assert!((zoom - now).abs() < 1e-4, "{what}: document {d} keeps its zoom {zoom}, not {now}"); + let moved = (center[0] - now_center[0]).hypot(center[1] - now_center[1]); + assert!(moved < 1e-2, "{what}: document {d} keeps its view centre {center:?}, not {now_center:?}"); + } +} + +#[test] +fn every_layout_keeps_each_document_at_100_percent_and_centred() { + let layouts = [ + "twoUpVertical", + "twoUpHorizontal", + "threeUpVertical", + "threeUpHorizontal", + "threeUpStacked", + "fourUp", + "sixUp", + "tile", + "tileAllVertically", + "tileAllHorizontally", + ]; + for layout in layouts { + let mut h = area(SIZES.len()); + for doc in 0..SIZES.len() { + set_zoom(&mut h, doc, 1.0); + } + h.run_steps(3); + let before = cameras(&h); + let active = h.state().0.session.active_index(); + arrange(&mut h, layout); + // Tile All Vertically / Horizontally dock as an arrangement only once the framework does (#16665); until then + // they float the documents, which never fitted them either. + if !layout.starts_with("tileAll") { + assert!(h.state().0.ui.document_windows.arrangement.is_some(), "{layout} arranges the document area"); + } + assert_kept(&before, &cameras(&h), layout); + assert_eq!(h.state().0.session.active_index(), active, "{layout} keeps the active document"); + } +} + +#[test] +fn a_zoomed_document_keeps_its_zoom_through_a_layout_and_back_to_tabs() { + let mut h = area(2); + set_zoom(&mut h, 0, 3.0); + h.run_steps(3); + let before = cameras(&h); + arrange(&mut h, "twoUpVertical"); + assert_kept(&before, &cameras(&h), "2-up Vertical"); + arrange(&mut h, "consolidateAllToTabs"); + assert!(h.state().0.ui.document_windows.arrangement.is_none(), "the tabs are back"); + assert_kept(&before, &cameras(&h), "Consolidate All to Tabs"); +} diff --git a/crates/ui-egui/src/canvas/background_redraw.rs b/crates/ui-egui/src/canvas/background_redraw.rs index d0ab02fec9..2728a14af3 100644 --- a/crates/ui-egui/src/canvas/background_redraw.rs +++ b/crates/ui-egui/src/canvas/background_redraw.rs @@ -355,11 +355,22 @@ pub(crate) fn restart(app: &mut PhotocraftApp, ctx: &egui::Context, gpu: &GpuCan /// Upload the blocks document `doc`'s redraw has finished since the last frame. When the last one /// lands, the redraw is recorded like the synchronous refresh it replaces (and explained once if /// it was slow). +/// Lands every running redraw's finished blocks: the document area's host work (`canvas::document_area`), run every +/// pass before the area's view, so blocks land while the view replays. +pub(crate) fn poll_all(app: &mut PhotocraftApp) { + let Some(gpu) = app.gpu.clone() else { return }; + let docs: Vec = app.redraws.keys().copied().collect(); + for doc in docs { + poll(app, &gpu, doc); + } +} + pub(crate) fn poll(app: &mut PhotocraftApp, gpu: &GpuCanvas, doc: DocId) { let gamma = text_gamma(app); let Some(r) = app.redraws.get_mut(&doc) else { return }; r.forget_if_gamma_changed(gamma); - loop { + let mut landed = 0; + let finished = loop { match r.rx.try_recv() { Ok(p) => { let b = r.blocks[p.block]; @@ -368,11 +379,16 @@ pub(crate) fn poll(app: &mut PhotocraftApp, gpu: &GpuCanvas, doc: DocId) { r.left -= 1; r.drawn += b.width() as u64 * b.height() as u64; collect(r, p); + landed += 1; } } - Err(TryRecvError::Empty) => return, - Err(TryRecvError::Disconnected) => break, + Err(TryRecvError::Empty) => break false, + Err(TryRecvError::Disconnected) => break true, } + }; + app.redraw_landed += landed; + if !finished { + return; } let Some(mut r) = app.redraws.remove(&doc) else { return }; if r.left > 0 { diff --git a/crates/ui-egui/src/canvas/canvas_settle_trials.rs b/crates/ui-egui/src/canvas/canvas_settle_trials.rs new file mode 100644 index 0000000000..b211e89862 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_settle_trials.rs @@ -0,0 +1,123 @@ +//! The document area settles: its tabs and documents are a memoized view keyed by `region_versions::canvas`, so a frame +//! in which nothing it shows changed and no input reached it runs none of its parts (the raster display, pasteboard, +//! scroll bars and tab strip); each repaints its last run. What it shows runs it again: a document edit, a view command +//! queued for its next pass, a redraw block landed. + +use craft::ui::runtime::measure::{MemoRun, last_frame_memo_runs, last_pass_runs}; +use egui::{Event, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::panels::region_versions; + +type H = Harness<'static, Box>; + +/// The canvas's parts: the components a run of the document area shows for a settled document. +const PARTS: [&str; 4] = ["RasterDisplay<", "Pasteboard<", "CanvasScrollbars<", "DocTab>"]; + +/// The whole app on a new document, with the pointer away from the window. +fn harness() -> H { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).with_step_dt(1.0 / 60.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + PhotocraftApp::with_context(cc.egui_ctx.clone(), session, crate::Services::default()) + }); + h.run_steps(8); + h.event(Event::PointerGone); + h.run_steps(4); + h +} + +/// The document area's view in the last frame: (ran, replayed). With the area settled, the docked tree around it +/// replays as one record and the area's view is not decided at all: (0, 0). +fn area(h: &H) -> (usize, usize) { + let runs = last_frame_memo_runs(&h.ctx); + let count = |how| runs.iter().filter(|(ty, _, run)| ty.contains("region_versions::CanvasSlot<") && *run == how).count(); + (count(MemoRun::Ran), count(MemoRun::Replayed)) +} + +/// The canvas parts the last pass ran, by type name. +fn part_runs(h: &H) -> Vec<(&'static str, u32)> { + last_pass_runs(&h.ctx).into_iter().filter(|(ty, _)| PARTS.iter().any(|part| ty.contains(part))).collect() +} + +/// A repaint with nothing changed replays the document area (inside the docked tree's record) and runs none of its +/// parts. +#[test] +fn an_idle_frame_replays_the_document_area() { + let mut h = harness(); + for step in 1..=3 { + h.ctx.request_repaint(); + h.run_steps(1); + assert_eq!(area(&h).0, 0, "idle step {step}: the document area replays"); + assert_eq!(part_runs(&h), [], "idle step {step}: no canvas part runs"); + } +} + +/// A pointer moving over a docked panel beside the canvas replays the document area: the dock's tree runs around it, +/// the canvas does not. +#[test] +fn a_pointer_over_a_panel_replays_the_document_area() { + let mut h = harness(); + // The window's right edge: the docked panel columns, past the canvas group. + let canvas = h.state().last_canvas_rect; + let beside = egui::pos2(1440.0 - 20.0, canvas.center().y); + h.event(Event::PointerMoved(beside)); + h.run_steps(2); + for step in 1..=3 { + h.event(Event::PointerMoved(beside + vec2(0.0, step as f32))); + h.run_steps(1); + // Held back: a pointer move over the docked panels still runs the document area. Two reads in the canvas + // note the pointer on every run: craft-ui-canvas's `ToolHost::run` (`pointer::frame`, for the tools' hover + // position) and `Canvas::autoscroll` (`pointer::frame`, for a press or the pointer leaving during a middle-button + // run). Turn these on once neither notes the pointer while it is away from the canvas. + // assert_eq!(area(&h).0, 0, "hover step {step}: the document area replays"); + // assert_eq!(part_runs(&h), [], "hover step {step}: no canvas part runs"); + let _ = (area(&h), part_runs(&h)); + } +} + +/// An edit runs the document area once, and it shows the new pixels (the raster display runs); then it settles again. +#[test] +fn a_document_edit_runs_the_document_area() { + let mut h = harness(); + h.state_mut().run("edit.fill", json!({"color": "#808080"})).unwrap(); + h.run_steps(1); + assert!(area(&h).0 >= 1, "the edit runs the document area"); + assert!(part_runs(&h).iter().any(|(ty, _)| ty.contains("RasterDisplay<")), "the raster display shows the edit: {:?}", part_runs(&h)); + h.run_steps(3); + assert_eq!(area(&h).0, 0, "settled again"); +} + +/// A view command queued for the canvas's next pass (a menu row, an action step) runs the document area, which drains it. +#[test] +fn a_queued_view_command_runs_the_document_area() { + let mut h = harness(); + h.state_mut().ui.views[0].request(craft::ui::canvas::ViewCommands::ZoomIn); + h.run_steps(1); + assert!(area(&h).0 >= 1, "the queued command runs the document area"); + assert!(h.state().ui.views[0].pending.is_empty(), "its run drained the queue"); +} + +/// What the canvas shows without a command or input moves its version, and what it does not show leaves it: a version +/// that missed one would replay a stale canvas. +#[test] +fn what_the_canvas_shows_moves_its_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + let moved = |app: &mut PhotocraftApp, change: &dyn Fn(&mut PhotocraftApp)| { + let before = region_versions::canvas(app); + change(app); + region_versions::canvas(app) != before + }; + assert!(!moved(&mut app, &|_| {}), "the same state settles"); + assert!(moved(&mut app, &|app| app.ui.views[0].center[0] += 4.0), "a pan"); + assert!(moved(&mut app, &|app| app.ui.views[0].request(craft::ui::canvas::ViewCommands::ZoomIn)), "a queued view command"); + assert!(moved(&mut app, &|app| app.redraw_landed += 1), "a redraw block landed"); + assert!(moved(&mut app, &|app| app.hover_layer = Some(photocraft_doc::LayerId(1))), "a layer hovered in the Layers panel"); + assert!(moved(&mut app, &|app| app.live_adjust = Some((photocraft_doc::LayerId(1), json!({"brightness": 10})))), "an adjustment's live preview"); + assert!(moved(&mut app, &|app| app.ui.tool_options.fill_opacity = 50.0), "a tool option"); + assert!(!moved(&mut app, &|app| app.hover_doc = Some([3.0, 4.0])), "the pointer's document point, which the canvas does not draw"); +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 3468795b9a..810aec8d19 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -153,7 +153,17 @@ pub fn transform_app_rows() -> [Entry; 2] { /// Photoshop's pasteboard menu (right-click outside the image): the pasteboard colour, the choice /// Preferences › Interface also offers. The ids are this menu's own: [`choose`] turns them into /// `prefs.set` (`pasteboard.`) or opens the Color Picker. -pub const PASTEBOARD_MENU: &[Row] = &[ +pub const PASTEBOARD_MENU: &[Row] = PASTEBOARD_MOVE_MENU.split_at(2).1; + +/// The Window item the Move tool's pasteboard menu toggles the contextual task bar with (#16757). +pub const PASTEBOARD_TASK_BAR: &str = "window.panel.contextualTaskBar"; + +/// The Move tool's pasteboard menu, as measured (#16757): Hide Contextual Task Bar (Show… while the +/// bar is off, [`row_label`]) and a separator above the colour rows. Other tools weren't measured and +/// keep [`PASTEBOARD_MENU`]. +pub const PASTEBOARD_MOVE_MENU: &[Row] = &[ + Some(("Hide Contextual Task Bar", PASTEBOARD_TASK_BAR)), + None, Some(("Default", "pasteboard.default")), Some(("Black", "pasteboard.black")), Some(("Dark Gray", "pasteboard.darkGray")), @@ -681,6 +691,32 @@ pub const COUNT_MENU: &[Row] = &[ /// Right-click with the Content-Aware Move tool inside an active selection (#12194). pub const CAM_INSIDE_SELECTION_MENU: &[Row] = &[Some(("Color Range…", "select.colorRange")), Some(("Load Selection…", "select.loadSelection"))]; +/// The Patch tool's rows (#12122). Use Pattern stays greyed: the Patch tool has no pattern mode yet. +pub const PATCH_USE_PATTERN: &str = "canvasMenu.patch.usePattern"; +pub const PATCH_SOURCE: &str = "canvasMenu.patch.source"; +pub const PATCH_DESTINATION: &str = "canvasMenu.patch.destination"; + +/// Right-click with the Patch tool inside the active selection, in the reference application's +/// order (#12122). Outside it the Patch tool opens the Lasso's selection menu. +pub const PATCH_INSIDE_SELECTION_MENU: &[Row] = &[ + Some(("Use Pattern to Patch Selection", PATCH_USE_PATTERN)), + None, + Some(("Use Patch as Source", PATCH_SOURCE)), + Some(("Use Patch as Destination", PATCH_DESTINATION)), + None, + Some(("Color Range…", "select.colorRange")), + Some(("Load Selection…", "select.loadSelection")), +]; + +/// The options bar's Patch mode a row sets: `source` or `destination`. +fn patch_mode(command: &str) -> Option<&'static str> { + match command { + PATCH_SOURCE => Some("source"), + PATCH_DESTINATION => Some("destination"), + _ => None, + } +} + /// The selection menu as measured in the reference application with the Red Eye tool (#12577), /// the Object Selection tool (#12866) and the Horizontal Type tool away from text (#12042): no /// Distort or Perspective, and Delete and Fill Selection after the fills. @@ -903,6 +939,9 @@ pub(crate) fn row_label(app: &PhotocraftApp, menu: &CanvasToolMenu, label: &'sta if menu.tool == Tool::AddAnchorPoint { return add_anchor_row_label(app, menu, label, command); } + if command == PASTEBOARD_TASK_BAR && !app.ui.panels.context_task_bar { + return "Show Contextual Task Bar"; + } if command != "path.transform" || !matches!(menu.tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen) { return label; } @@ -988,9 +1027,16 @@ fn sampler_menu(menu: &CanvasToolMenu) -> bool { menu.tool == Tool::ColorSampler && menu.kind == MenuKind::Tool } -/// Is `menu` the Content-Aware Move tool's menu opened inside the active selection (#12194)? +/// Do `tool`'s menu rows depend on whether the right-click is inside the selection: Content-Aware +/// Move (#12194) and Patch (#12122)? +fn splits_at_selection(tool: Tool) -> bool { + matches!(tool, Tool::ContentAwareMove | Tool::Patch) +} + +/// Is `menu` the Content-Aware Move (#12194) or Patch (#12122) tool's menu opened inside the +/// active selection? pub fn inside_selection(menu: &CanvasToolMenu) -> bool { - menu.tool == Tool::ContentAwareMove && menu.kind == MenuKind::Tool && menu.has_selection && menu.inside_selection + splits_at_selection(menu.tool) && menu.kind == MenuKind::Tool && menu.has_selection && menu.inside_selection } /// Content-Aware Move's canvas context menu requires an open document and leaves Bitmap, Duotone @@ -1055,6 +1101,8 @@ pub fn applies(tool: Tool) -> bool { // Sample Size and Copy Color (#11747). | Tool::Eyedropper | Tool::ContentAwareMove + // The patch rows inside the selection, the selection menu outside it (#12122). + | Tool::Patch // The layer or selection menu, where measured (#12577). | Tool::RedEye ) || path_menu(tool) @@ -1189,6 +1237,7 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { match &menu.kind { MenuKind::Crop { .. } | MenuKind::Layers { .. } | MenuKind::BrushMode { .. } => &[], MenuKind::Guide => GUIDE_MENU, + MenuKind::Pasteboard if menu.tool == Tool::Move => PASTEBOARD_MOVE_MENU, MenuKind::Pasteboard => PASTEBOARD_MENU, MenuKind::View => { if menu.tool == Tool::Hand { @@ -1220,7 +1269,7 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { } else if menu.tool == Tool::Eyedropper { EYEDROPPER_MENU } else if inside_selection(menu) { - CAM_INSIDE_SELECTION_MENU + if menu.tool == Tool::Patch { PATCH_INSIDE_SELECTION_MENU } else { CAM_INSIDE_SELECTION_MENU } } else { selection_rows(menu.has_selection) } @@ -1428,8 +1477,13 @@ fn choose_guide(app: &mut PhotocraftApp, ctx: &Context, command: &str) -> Result crate::menus::invoke(app, ctx, command, json!({})).map(|_| ()) } -/// A pasteboard row: set the colour, or open the Color Picker on the custom one. +/// A pasteboard row: set the colour, open the Color Picker on the custom one, or run the Window +/// item that hides or shows the contextual task bar. fn choose_pasteboard(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + if command == PASTEBOARD_TASK_BAR { + let ctx = app.ctx().clone(); + return crate::menus::invoke(app, &ctx, command, json!({})).map(|_| ()); + } if command == PASTEBOARD_PICK { let rgb = prefs::parse_hex(&app.session.prefs().interface.canvas_custom_color).map_or([0.5; 3], |c| c.map(|v| f32::from(v) / 255.0)); crate::color_picker_ui::open_for_target(app, "pasteboard", "Color Picker (Custom Canvas Color)", rgb)?; @@ -1448,7 +1502,7 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) _ => GUIDE_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command), }; } - MenuKind::Pasteboard => return PASTEBOARD_MENU.iter().flatten().any(|(_, id)| *id == command), + MenuKind::Pasteboard => return rows(menu).iter().flatten().any(|(_, id)| *id == command), MenuKind::View if command == "view.fillScreen" => return app.session.active().is_some(), MenuKind::View => return crate::menus::is_enabled(app, command), MenuKind::TypeEdit { .. } => { @@ -1478,8 +1532,12 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) if sampler_menu(menu) { return command == SAMPLER_DELETE && menu.sampler.is_some() && sampler_current(app, menu); } - // Inside the Content-Aware Move selection menu (#12194), Load Selection… stays greyed until a - // selection channel (non-spot alpha channel) has been saved. + // The Patch mode rows set the options bar's mode; Use Pattern waits for a pattern patch (#12122). + if menu.tool == Tool::Patch && (patch_mode(command).is_some() || command == PATCH_USE_PATTERN) { + return inside_selection(menu) && patch_mode(command).is_some(); + } + // Inside the Content-Aware Move (#12194) and Patch (#12122) selection menus, Load Selection… + // stays greyed until a selection channel (non-spot alpha channel) has been saved. if inside_selection(menu) && command == "select.loadSelection" { return app.session.active().is_some_and(|st| st.doc.channels.iter().any(|c| c.spot.is_none())) && crate::menus::is_enabled(app, command); } @@ -1697,7 +1755,7 @@ fn capture(app: &mut PhotocraftApp, menu: &mut CanvasToolMenu, doc: [f64; 2], po // measured configuration heads the menu with the entry (#12915). menu.point = point.filter(|(target, hit)| pen_point_allowed(app, *target, hit)).and_then(|(target, hit)| point_at(app, target, hit)); } - menu.inside_selection = menu.tool == Tool::ContentAwareMove && selected_at(app, doc); + menu.inside_selection = splits_at_selection(menu.tool) && selected_at(app, doc); if menu.tool == Tool::ColorSampler { menu.sampler = crate::analysis::sampler_at(app, doc); // PLAN: assumed name `analysis::sampler_at` (tools-w53) menu.sampler_at = menu.sampler.and_then(|i| Some((app.session.active_index()?, *app.session.active()?.color_samplers.get(i)?))); @@ -1753,6 +1811,11 @@ pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { app.run(&id, params).map(|_| ()) } MenuKind::Tool if is_eyedropper(&menu) => choose_eyedropper(app, ctx, &menu, command), + // A Patch mode row sets the options bar's Source / Destination choice (#12122). + MenuKind::Tool if patch_mode(command).is_some() => { + app.ui.tool_options.patch_mode = patch_mode(command).unwrap_or("source").into(); + Ok(()) + } // Photoshop's Make Work Path… asks for the tolerance first. MenuKind::Tool if command == "select.toWorkPath" => { pen_dialogs::open(app, command, ""); @@ -1935,6 +1998,8 @@ pub fn entries(app: &PhotocraftApp, menu: &CanvasToolMenu) -> Vec> "Duplicate Layers…" => tl!("Duplicate Layers…"), "Delete Layers" => tl!("Delete Layers"), "Rasterize Layers" => tl!("Rasterize Layers"), + "Hide Contextual Task Bar" => tl!("Hide Contextual Task Bar"), + "Show Contextual Task Bar" => tl!("Show Contextual Task Bar"), key => tl!(key), }; out.push(Entry::new(command.to_string(), text.to_string()).enabled(entry_enabled(app, menu, command)).checked(mode_checked(app, menu, command))); @@ -2017,6 +2082,13 @@ mod cam_menu_tests; #[cfg(test)] pub(crate) mod tests; +#[cfg(test)] +mod patch_menu_tests; + +#[cfg(test)] +#[path = "../task_bar_pasteboard_entry_tests.rs"] +mod task_bar_pasteboard_entry_tests; + #[cfg(test)] pub(crate) mod count_tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/patch_menu_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/patch_menu_tests.rs new file mode 100644 index 0000000000..e82ffa66ec --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/patch_menu_tests.rs @@ -0,0 +1,116 @@ +//! #12122: the Patch tool's canvas right-click opens the patch rows inside the selection, the +//! Lasso's selection menu outside it and the selection tools' no-selection menu without one. + +use egui::Modifiers; +use egui_kittest::Harness; +use serde_json::{Value, json}; + +use super::tests::{any_dialog, app, harness, open_here, pick, right_click, screen_of}; +use super::{NO_SELECTION_MENU, PATCH_DESTINATION, PATCH_SOURCE, PATCH_USE_PATTERN, SELECTION_MENU, available}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A 32 × 32 document with the selection 4..20 square and `tool` selected. +fn selected(tool: Tool) -> Box { + let mut app = app(); + app.run("select.rect", json!({"x": 4, "y": 4, "width": 16, "height": 16})).unwrap(); + app.ui.tool = tool; + app +} + +/// Right-click document point `doc` with `tool`: the open menu's entries as `ui.inspect` lists them. +fn entries_at(h: &mut Harness<'static, Box>, tool: Tool, doc: [f32; 2]) -> Vec { + h.state_mut().ui.canvas_tool_menu = None; + h.state_mut().ui.tool = tool; + let at = screen_of(h.state(), doc); + right_click(h, at, Modifiers::NONE); + let inspected = crate::control::inspect(h.state(), &h.ctx); + assert_eq!(inspected["canvasToolMenu"]["tool"], json!(format!("{tool:?}")), "{tool:?} opens its menu at {doc:?}"); + inspected["canvasToolMenu"]["entries"].as_array().cloned().unwrap_or_default() +} + +/// The entries' labels, a separator as `None`. +fn shown(entries: &[Value]) -> Vec> { + entries.iter().map(|e| if e["separator"] == json!(true) { None } else { e["label"].as_str().map(String::from) }).collect() +} + +fn enabled(entries: &[Value], label: &str) -> bool { + entries.iter().find(|e| e["label"] == json!(label)).unwrap_or_else(|| panic!("{label} is listed"))["enabled"] == json!(true) +} + +#[test] +fn inside_the_selection_the_patch_rows_show_in_the_reference_order() { + let mut h = harness(selected(Tool::Patch)); + let entries = entries_at(&mut h, Tool::Patch, [12.0, 12.0]); + let want = [ + Some("Use Pattern to Patch Selection"), + None, + Some("Use Patch as Source"), + Some("Use Patch as Destination"), + None, + Some("Color Range…"), + Some("Load Selection…"), + ]; + assert_eq!(shown(&entries), want.map(|l| l.map(String::from))); + assert!(!enabled(&entries, "Use Pattern to Patch Selection"), "no pattern patch exists yet: greyed"); + assert!(enabled(&entries, "Use Patch as Source") && enabled(&entries, "Use Patch as Destination")); + assert!(enabled(&entries, "Color Range…")); + assert!(!enabled(&entries, "Load Selection…"), "no selection saved: greyed"); + + h.state_mut().run("select.saveSelection", json!({"name": "Alpha 1"})).unwrap(); + let entries = entries_at(&mut h, Tool::Patch, [12.0, 12.0]); + assert!(enabled(&entries, "Load Selection…"), "a saved selection makes Load Selection… live"); +} + +#[test] +fn outside_the_selection_the_patch_tool_opens_the_lassos_menu() { + let mut h = harness(selected(Tool::Patch)); + let lasso = entries_at(&mut h, Tool::Lasso, [26.0, 26.0]); + let patch = entries_at(&mut h, Tool::Patch, [26.0, 26.0]); + assert_eq!(shown(&patch), shown(&lasso)); + assert_eq!(patch.iter().map(|e| &e["enabled"]).collect::>(), lasso.iter().map(|e| &e["enabled"]).collect::>()); + assert_eq!(patch.len(), SELECTION_MENU.len(), "the selection menu, nothing added"); +} + +#[test] +fn without_a_selection_the_patch_tool_opens_the_no_selection_menu() { + let mut app = app(); + app.ui.tool = Tool::Patch; + let mut h = harness(app); + let entries = entries_at(&mut h, Tool::Patch, [12.0, 12.0]); + let want: Vec<_> = NO_SELECTION_MENU.iter().map(|row| row.map(|(label, _)| label.to_string())).collect(); + assert_eq!(shown(&entries), want); +} + +#[test] +fn the_mode_rows_set_the_options_bar_mode_and_nothing_else() { + let mut app = selected(Tool::Patch); + assert_eq!(app.ui.tool_options.patch_mode, "source"); + let journal = app.session.journal.len(); + for (row, mode) in [(PATCH_DESTINATION, "destination"), (PATCH_SOURCE, "source")] { + assert!(open_here(&mut app, Tool::Patch, [12.0, 12.0])); + pick(&mut app, row); + assert!(app.ui.canvas_tool_menu.is_none(), "choosing a row closes the menu"); + assert_eq!(app.ui.tool_options.patch_mode, mode); + } + assert_eq!(app.session.journal.len(), journal, "the mode rows run no command"); + assert_eq!(app.ui.tool, Tool::Patch); + + // Use Pattern is greyed, so choosing it does nothing. + assert!(open_here(&mut app, Tool::Patch, [12.0, 12.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!available(&app, &menu, PATCH_USE_PATTERN)); + // Outside the selection the mode rows aren't offered. + assert!(open_here(&mut app, Tool::Patch, [26.0, 26.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!available(&app, &menu, PATCH_DESTINATION)); +} + +#[test] +fn color_range_opens_its_dialog() { + let mut app = selected(Tool::Patch); + assert!(open_here(&mut app, Tool::Patch, [12.0, 12.0])); + pick(&mut app, "select.colorRange"); + assert!(app.ui.canvas_tool_menu.is_none()); + assert!(any_dialog(&app), "Color Range… opens the Color Range dialog"); +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index 1ab124000f..b6ef02002e 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -98,7 +98,7 @@ pub(crate) fn harness(mut app: Box) -> Harness<'static, Box) -> Harness<'static, Box bool { /// Shape tools whose Alt Eyedropper also updates the tool's Fill. pub(super) fn shape_alt_sets_fill(tool: Tool) -> bool { - matches!(tool, Tool::Triangle | Tool::CustomShape | Tool::Rectangle | Tool::EllipseShape | Tool::Polygon) + matches!(tool, Tool::Triangle | Tool::CustomShape | Tool::Rectangle | Tool::EllipseShape | Tool::Polygon | Tool::Star) } -/// Whether an Alt or Shift+Alt press samples the foreground and Fill for the Triangle, Custom Shape, -/// Rectangle, Ellipse and Polygon tools (#13364, #15856, #13333, #13224, #13317). Sampling requires Shape mode, no active shape layer, and a sampleable pixel. -/// Control+Alt is excluded here, as in [`alt_samples`]. +/// Whether an Alt press samples the foreground and Fill for a shape tool. Sampling requires Shape +/// mode, no active shape layer, and a sampleable pixel. The Star keeps Shift+Alt for drawing a +/// constrained shape from the centre. Control+Alt is excluded, as in [`alt_samples`]. pub(crate) fn shape_alt_samples(app: &mut PhotocraftApp, mods: Mods, x: f64, y: f64) -> bool { mods.alt && !mods.ctrl + && (!mods.shift || app.ui.tool != Tool::Star) && shape_alt_sets_fill(app.ui.tool) && app.ui.tool_options.shape_mode == craft::draw::ui::VectorMode::Shape && crate::vector_ui::active_shape_path(app).is_none() @@ -122,9 +123,27 @@ pub(crate) fn alt_loads_mixer(tool: Tool, mods: craft::keymap::Mods) -> bool { mods.alt && !mods.ctrl && tool == Tool::MixerBrush } -/// Whether the Mixer Brush's target layer has Lock All on, so its cursor shows the not-allowed mark. -pub(crate) fn mixer_target_locked(app: &PhotocraftApp) -> bool { - app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|layer| layer.locks.all) +/// Whether the painting tool shows the not-allowed cursor for its current target. +pub(super) fn paint_cursor_blocked(app: &PhotocraftApp) -> bool { + use photocraft_doc::LayerContent; + + let tool = app.ui.tool; + if !matches!(tool, Tool::Brush | Tool::Eraser | Tool::PaintBucket | Tool::MixerBrush) { + return false; + } + let Some(state) = app.session.active() else { return false }; + let Some(path) = state.active_layer.and_then(|id| state.doc.layers.index().path(id)) else { return false }; + let Some(layer) = state.doc.layer_at(path) else { return false }; + if tool == Tool::MixerBrush { + // #11957 checks the active layer's own Lock All for the Mixer Brush. + return layer.locks.all; + } + let blocked = match &layer.content { + LayerContent::Raster(_) => state.doc.locks_at(path).all, + LayerContent::Text(_) => matches!(tool, Tool::Brush | Tool::PaintBucket), + _ => false, + }; + blocked && state.doc.shown_at(path) && crate::brush_refusal::pixels_target(&super::paint_target(app)) } #[cfg(test)] @@ -194,3 +213,7 @@ mod custom_shape_alt_eyedropper_tests; #[cfg(test)] #[path = "magic_eraser_cursor_tests.rs"] mod magic_eraser_cursor_tests; + +#[cfg(test)] +#[path = "locked_layer_cursor_tests.rs"] +mod locked_layer_cursor_tests; diff --git a/crates/ui-egui/src/canvas/document_area.rs b/crates/ui-egui/src/canvas/document_area.rs index ca933f7d4a..3bbcdf823a 100644 --- a/crates/ui-egui/src/canvas/document_area.rs +++ b/crates/ui-egui/src/canvas/document_area.rs @@ -22,7 +22,9 @@ use super::textures::retain_gpu_documents; use super::{PhotocraftApp, canvas_view}; /// The canvas panel with the tab strip and the document, or the Home screen; then drops layers dragged onto another -/// document (`layer_transfer`). +/// document (`layer_transfer`). The tabs and documents are a memoized view keyed by `region_versions::canvas`, and the +/// dock's column around the area replays with that version too: the app work every pass needs ([`each_pass`]) runs +/// outside both, before the window's body. pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Files the OS drops on the main window outside the tab strip: the Home screen has no other target (#16588). let dropped = super::window_drop::take(ui, ui.max_rect()); @@ -31,10 +33,19 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.dock_drop_rect = None; // It replaces the canvas too: a file dropped where the canvas was opens, not into the hidden document. app.drop_canvas_rect = None; + app.ui.task_bar_shown = None; } else { crate::distort_ui::drop_foreign(app, ui.ctx()); crate::layer_transfer::prepare(app, ui.ctx()); - documents(app, ui); + if app.home_screen_up() { + // The Home screen hides the tabs: a floating window dropped on it docks nowhere (#16415). + app.dock_drop_rect = None; + app.drop_canvas_rect = None; + app.ui.task_bar_shown = None; + start_screen(app, ui); + } else { + crate::panels::region_versions::show_canvas(app, ui, documents); + } crate::layer_transfer::finish(app, ui.ctx()); // The Shift+Alt+right-click HUD Color Picker (#6098), while its gesture is held. crate::color_hud::show(app, ui); @@ -44,6 +55,31 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } +/// The document area's work of every pass, which the window's body runs before the dock: the GPU canvas's documents +/// and their texture budget, a Content-Aware Scale step, the blocks background redraws landed, the tablet settings, and +/// what a tool switch or a layer switch leaves behind (a pending crop, a Properties eyedropper). A replayed view or dock +/// column runs none of its own code, so none of this lives in them. A Batch preview in place of the documents +/// ([`crate::jobs_ui::batch_preview`]) holds all of it back. +pub(crate) fn each_pass(app: &mut PhotocraftApp, ctx: &egui::Context) { + if crate::jobs_ui::batch_preview_key(app).is_some() { + return; + } + retain_gpu_documents(app); + publish_shown(app); + crate::cas_transform::tick(app, ctx); + crate::background_redraw::poll_all(app); + // Pen pressure/tilt for the tools' events (mouse = 1.0), unless Preferences › Tools › Use Tablet Pressure is off; + // the pen's eraser end selects the Eraser. + app.stylus.use_pressure = app.session.prefs().tools.use_tablet_pressure; + let curve = app.session.prefs().tools.pressure_curve.clone(); + app.stylus.set_pressure_curve(&curve); + crate::stylus::Stylus::sync_eraser_tool(app); + // A Properties Levels/Curves eyedropper left behind by a tool or layer switch is dropped. + crate::layer_picker::prune(app); + // A crop left pending when another tool was picked is applied or dropped. + crate::crop_ui::each_pass(app); +} + /// Where each pane of Window › Arrange's n-up or Tile arrangement is in `rect`, with the document it shows: pane `i` is /// docked group `i` of `app.ui.document_windows`, showing that group's shown document, in the rect `SplitViews` /// places it in with the dividers at `app.ui.split_at`. `None` with no arrangement or fewer than two docked groups: @@ -128,14 +164,13 @@ pub(crate) fn publish_shown(app: &PhotocraftApp) { } /// What the document area does after Window › Arrange changed the document windows (top-w15 calls it after -/// `arrange`). A new n-up or Tile arrangement starts from even panes and every document fits its new pane, as -/// production's layouts do; Tile is a pane per open document, floating windows docked first (the framework's -/// `arrange` consolidates before it splits). The other window commands and the Match commands leave the panes and -/// views alone. +/// `arrange`). A new n-up or Tile arrangement starts from even panes; every document keeps its zoom and view centre, +/// as the reference application's layouts do (#16885), so it shows centred in its new pane. Tile is a pane per open +/// document, floating windows docked first (the framework's `arrange` consolidates before it splits). The other window +/// commands and the Match commands leave the panes and views alone. pub(crate) fn apply_arranged(app: &mut PhotocraftApp, arranged: Arranged) { if arranged == Arranged::Windows && app.ui.document_windows.arrangement.is_some() { app.ui.split_at = SplitAt::default(); - app.ui.views.iter_mut().for_each(|view| view.place(craft::ui::canvas::ViewCommands::FitOnScreen)); } } @@ -146,19 +181,12 @@ const DOCK_BAND: f32 = 32.0; fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // The web build's drop path reads where the canvas is (`file_open::target_at`); set again when one shows. app.drop_canvas_rect = None; + // A run that shows no canvas of the active document shows no crop task bar (`crop_task_bar::show` reports one). + app.ui.task_bar_shown = None; // A floating window's title bar docks on the tab strip (`tabs::strip` sets its rect); where no strip shows, on a // band of a tab's height at the top of the area, where the strip would be. let area = ui.max_rect(); app.dock_drop_rect = Some(Rect::from_min_size(area.min, egui::vec2(area.width(), DOCK_BAND.min(area.height())))); - retain_gpu_documents(app); - publish_shown(app); - crate::cas_transform::tick(app, ui.ctx()); - if app.home_screen_up() { - // The Home screen hides the tabs: a floating window dropped on it docks nowhere (#16415). - app.dock_drop_rect = None; - start_screen(app, ui); - return; - } // Files opening in the background (#210) have tabs before they have documents. let opening = !app.jobs.opens.is_empty(); // The tabs region and the document run one after the other inside `show`, each with the app to itself. @@ -279,3 +307,7 @@ fn arranged(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: Rect, active: usiz } true } + +#[cfg(test)] +#[path = "arrange_keeps_zoom_tests.rs"] +mod arrange_keeps_zoom_tests; diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 81ee1515c3..2fcaa80868 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -35,6 +35,11 @@ impl View { .aspect(f64::from(aspect)) } + /// Takes `zoom` points per document unit, shown at `ppp` device pixels per point, and leaves the centre and rotation. + pub(crate) fn set_zoom(&mut self, zoom: f64, ppp: f32) { + self.zoom = (zoom * f64::from(ppp)) as f32; + } + /// Takes the zoom, centre and rotation of `view`, shown at `ppp` device pixels per point. pub(crate) fn set_from(&mut self, view: &CanvasView, ppp: f32) { self.zoom = (view.zoom * f64::from(ppp)) as f32; @@ -513,7 +518,7 @@ fn canvas_controls( crate::blur_pins::overlay(app, ui, rect); let doc = app.session.documents()[host.idx].doc.id; if let Some(shown) = crate::vector_ui::overlay::show_paths(app, ui, rect, doc) { - let mods = craft::ui::runtime::pointer::frame(ui.ctx()).mods; + let mods = craft::ui::runtime::pointer::mods(ui.ctx()); crate::direct_select::edits::apply(app, &shown.output, &shown.refs, app.ui.tool, mods); } crate::type_tool::canvas_controls(app, ui, rect); @@ -573,7 +578,6 @@ fn canvas_controls( } crate::frame_tool::task_bar::show(ui, app, bar_area); } - crate::crop_ui::each_pass(app); crate::vector_ui::shapes::show_preview(app, ui, rect, &space.view); crate::tools::brush_feedback::show(ui, app, rect, pointer); if shown != space.view { diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index 44eb6126b9..a704025cef 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -48,6 +48,18 @@ fn adjust_request(app: &PhotocraftApp) -> Option<(craft::ui::dialog::DialogId, S Some((open.id, cmd, params)) } +/// An open preview dialog's request: the dialog, its command and its parameters. +type PreviewRequest = (craft::ui::dialog::DialogId, String, String); + +/// What the canvas shows of an open filter or adjustment dialog's preview, for the document area's version +/// (`region_versions::canvas`): the request the dialog asks for (its fields change with no command) and the result +/// on screen, with whether OK's job is running. +pub(crate) fn canvas_key(app: &PhotocraftApp) -> (Option, Option<(usize, bool)>) { + let request = adjust_request(app).map(|(id, command, params)| (id, command, params.to_string())); + let shown = app.filter_preview.as_ref().map(|p| (p.result.as_ref().map_or(0, |doc| std::sync::Arc::as_ptr(doc) as usize), p.committing)); + (request, shown) +} + /// 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 @@ -184,7 +196,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e } } if app.filter_preview_worker.busy() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); + craft::ui::runtime::frame::request_repaint_after(ctx, std::time::Duration::from_millis(16).as_secs_f64()); } let preview = app.filter_preview.as_ref()?; // Keep the last preview during a drag, but never one from another source or dialog. It is diff --git a/crates/ui-egui/src/canvas/guide_select/tests.rs b/crates/ui-egui/src/canvas/guide_select/tests.rs index 1856da7fcd..07f8568725 100644 --- a/crates/ui-egui/src/canvas/guide_select/tests.rs +++ b/crates/ui-egui/src/canvas/guide_select/tests.rs @@ -82,7 +82,7 @@ fn harness(app: Box) -> AppHarness { 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)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); crate::dialogs::run(app, ui); }, app, diff --git a/crates/ui-egui/src/canvas/layer_pick_ui.rs b/crates/ui-egui/src/canvas/layer_pick_ui.rs index 1d04cdf17f..c623000b47 100644 --- a/crates/ui-egui/src/canvas/layer_pick_ui.rs +++ b/crates/ui-egui/src/canvas/layer_pick_ui.rs @@ -188,7 +188,7 @@ mod tests { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, a, ); diff --git a/crates/ui-egui/src/canvas/live_frame_tests.rs b/crates/ui-egui/src/canvas/live_frame_tests.rs index 425f189988..d4492ac4ee 100644 --- a/crates/ui-egui/src/canvas/live_frame_tests.rs +++ b/crates/ui-egui/src/canvas/live_frame_tests.rs @@ -5,7 +5,7 @@ use egui::{PointerButton, Pos2, Rect, vec2}; use serde_json::json; use super::document_display::{CanvasHost, shown_camera}; -use super::{canvas_display, canvas_view, document_area}; +use super::{canvas_display, canvas_view, testing}; use crate::PhotocraftApp; use crate::state::{Tool, View}; @@ -23,7 +23,7 @@ fn live_brush_texture_includes_this_frames_press_and_moves() { if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/canvas/locked_layer_cursor_tests.rs b/crates/ui-egui/src/canvas/locked_layer_cursor_tests.rs new file mode 100644 index 0000000000..664423ff9b --- /dev/null +++ b/crates/ui-egui/src/canvas/locked_layer_cursor_tests.rs @@ -0,0 +1,138 @@ +//! #16815: show the system cursor for painting tools on the blocked layer targets measured in the issue. + +use craft::behavior::{Cursor, CursorIcon}; +use egui::{Modifiers, PointerButton}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::dialogs::{alerts, rasterize_prompt::Rasterize}; +use crate::guide_cursor_tests::{harness, hover, screen}; +use crate::state::Tool; + +const IN_IMAGE: f32 = 100.0; +const ON_PASTEBOARD: f32 = -40.0; +const TOOLS: [Tool; 3] = [Tool::Brush, Tool::Eraser, Tool::PaintBucket]; +const BLOCKED: Option = Some(Cursor::System(CursorIcon::NotAllowed)); + +fn pixel_layer() -> Harness<'static, Box> { + let mut h = harness(Tool::Brush); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.state_mut().run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + h +} + +fn cursor_at(h: &mut Harness<'static, Box>, tool: Tool, x: f32, mods: Modifiers) -> Option { + h.state_mut().ui.tool = tool; + hover(h, x, 150.0, mods); + h.state().canvas_tools.last_response.as_ref().and_then(|response| response.cursor.clone()) +} + +fn image_cursor(h: &mut Harness<'static, Box>, tool: Tool) -> Option { + cursor_at(h, tool, IN_IMAGE, Modifiers::NONE) +} + +fn click_image(h: &mut Harness<'static, Box>) { + let pos = screen(h, IN_IMAGE, 150.0); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); + } +} + +#[test] +fn lock_all_shows_the_blocked_cursor_on_the_image_and_pasteboard() { + let mut h = pixel_layer(); + let normal = TOOLS.map(|tool| image_cursor(&mut h, tool)); + for (tool, cursor) in TOOLS.into_iter().zip(&normal) { + assert!(cursor.is_some() && *cursor != BLOCKED, "{tool:?} has a normal cursor before locking"); + } + let shift_bucket = cursor_at(&mut h, Tool::PaintBucket, ON_PASTEBOARD, Modifiers::SHIFT); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + for tool in TOOLS { + for x in [IN_IMAGE, ON_PASTEBOARD] { + assert_eq!(cursor_at(&mut h, tool, x, Modifiers::NONE), BLOCKED, "{tool:?} at x={x}"); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::NotAllowed); + } + } + assert_eq!(cursor_at(&mut h, Tool::PaintBucket, ON_PASTEBOARD, Modifiers::SHIFT), shift_bucket, "Shift changes the pasteboard colour"); + h.state_mut().run("layer.lockLayers", json!({"all": false})).unwrap(); + assert_eq!(TOOLS.map(|tool| image_cursor(&mut h, tool)), normal); +} + +#[test] +fn a_type_layer_blocks_brush_and_bucket_and_their_clicks_still_ask_to_rasterize() { + for tool in [Tool::Brush, Tool::PaintBucket] { + let mut h = pixel_layer(); + h.state_mut().run("type.create", json!({"x": 40, "y": 60, "text": "Type"})).unwrap(); + let cursor = image_cursor(&mut h, tool); + let before = h.state().session.active().unwrap().history.past_len(); + click_image(&mut h); + assert!(alerts::prompt_tagged::(h.state()).is_some(), "{tool:?}: Rasterize prompt"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before, "{tool:?}"); + assert_eq!(cursor, BLOCKED, "{tool:?}"); + } + let mut h = pixel_layer(); + let eraser = image_cursor(&mut h, Tool::Eraser); + h.state_mut().run("type.create", json!({"x": 40, "y": 60, "text": "Type"})).unwrap(); + assert_eq!(image_cursor(&mut h, Tool::Eraser), eraser); +} + +#[test] +fn locked_pixel_clicks_keep_their_refusal_and_history() { + for tool in TOOLS { + let mut h = pixel_layer(); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + image_cursor(&mut h, tool); + let before = h.state().session.active().unwrap().history.past_len(); + click_image(&mut h); + let app = h.state(); + let dialogs = app.framework.dialogs.open_dialogs(); + let alert = dialogs.iter().any(|dialog| { + dialog + .fields + .as_ref() + .and_then(|fields| fields.get("message")) + .and_then(|message| message.as_str()) + .is_some_and(|message| message.contains("layer is locked")) + }); + assert!(alert || (app.ui.status_error && app.ui.status.contains("locked")), "{tool:?}: {}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.past_len(), before, "{tool:?}"); + } +} + +#[test] +fn hidden_layers_partial_locks_and_groups_keep_each_tools_normal_cursor() { + let mut h = pixel_layer(); + let normal = TOOLS.map(|tool| image_cursor(&mut h, tool)); + for lock in ["pixels", "transparency", "position"] { + h.state_mut().run("layer.lockLayers", json!({ (lock): true })).unwrap(); + assert_eq!(TOOLS.map(|tool| image_cursor(&mut h, tool)), normal, "{lock}"); + h.state_mut().run("layer.lockLayers", json!({ (lock): false })).unwrap(); + } + // Test hiding a fully locked layer, so the hidden and locked rules compete. + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + h.state_mut().run("layer.setProps", json!({"visible": false})).unwrap(); + assert_eq!(TOOLS.map(|tool| image_cursor(&mut h, tool)), normal, "hidden Lock All layer"); + + h.state_mut().run("layer.new.group", json!({})).unwrap(); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + assert_eq!(TOOLS.map(|tool| image_cursor(&mut h, tool)), normal, "locked group itself"); +} + +#[test] +fn locked_layers_keep_nonpainting_cursors_and_the_stand_ins() { + let mut h = pixel_layer(); + let tools = [Tool::RectMarquee, Tool::Move, Tool::Pencil]; + let expected = tools.map(|tool| image_cursor(&mut h, tool)); + let eyedropper = image_cursor(&mut h, Tool::Eyedropper); + let quick_mask = image_cursor(&mut h, Tool::Brush); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + assert_eq!(tools.map(|tool| image_cursor(&mut h, tool)), expected); + assert_eq!(image_cursor(&mut h, Tool::MixerBrush), BLOCKED); + assert_eq!(cursor_at(&mut h, Tool::Brush, IN_IMAGE, Modifiers::ALT), eyedropper); + assert_eq!(cursor_at(&mut h, Tool::Brush, IN_IMAGE, Modifiers::COMMAND), expected[1]); + + h.state_mut().run("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + assert_eq!(image_cursor(&mut h, Tool::Brush), quick_mask); +} diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index b1993d367e..9c95b46fb4 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -273,6 +273,10 @@ pub(crate) enum ContextPopup { /// menus come from the guides' own output and transform menus from the transform box. pub(crate) fn context_popup(app: &mut PhotocraftApp, tool: Tool, mods: Mods, doc: [f64; 2]) -> Option { use crate::canvas_tool_menu as menu; + // Puppet Warp's pin menu, opened earlier in the pass, takes the right-click (#16734). + if crate::puppet_ui::menu_open(app) { + return None; + } if crate::brush_mode_menu::opens_on(app, tool, mods, Some(doc)) { return Some(ContextPopup::Menu(MenuKind::BrushMode { plain: !crate::brush_mode_menu::is_gesture(tool, mods) })); } diff --git a/crates/ui-egui/src/canvas/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs index 0372fbe081..9efc28951e 100644 --- a/crates/ui-egui/src/canvas/paint_mouse/tests.rs +++ b/crates/ui-egui/src/canvas/paint_mouse/tests.rs @@ -25,7 +25,7 @@ pub(super) fn harness(prefs: Option<&str>) -> Harness<'static, Box bool { } } +fn bucket_targets_pasteboard(app: &PhotocraftApp, at: [f64; 2], mods: Mods) -> bool { + let plain_shift = mods.shift && !mods.alt && !mods.ctrl && !mods.cmd; + 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 (x, y) = (at[0], at[1]); + let outside = x.is_finite() && y.is_finite() && (x < 0.0 || y < 0.0 || x >= w || y >= h); + plain_shift && outside && st.doc.selection.is_none() +} + +/// Paint Bucket ⇧-click on the pasteboard sets the pasteboard colour to the foreground colour, as +/// in the reference application (#12534): the custom colour, and use it, as the pasteboard menu's +/// Select Custom Color… does. It is a preference, so no history state and no document change. +/// Only a plain ⇧ with no selection: other modifiers and an active selection were not measured and +/// keep today's fill. True when it handled the click. +pub(crate) fn bucket_pasteboard_click(app: &mut PhotocraftApp, at: [f64; 2], mods: Mods) -> bool { + if !bucket_targets_pasteboard(app, at, mods) { + return false; + } + let [r, g, b, _] = app.session.tools.foreground; + let color = crate::color_picker_ui::hex([r, g, b]); + if let Err(e) = app.run("prefs.set", json!({"values": {"interface.canvasColor": "custom", "interface.canvasCustomColor": color}})) { + app.ui.status = e; + app.ui.status_error = true; + } + true +} + fn begin(app: &mut PhotocraftApp, state: &mut PaintState, pointer: &ToolPointer, at: [f64; 2], cx: &mut ToolContext<'_>) -> ToolAction { let tool = app.ui.tool; let (mods, button) = (pointer.mods, pointer.button); @@ -466,8 +493,10 @@ impl CanvasTool for PaintTool<'_> { if alt_loads_mixer(tool, cx.mods) && !cx.mods.cmd { return if cx.precise() { Cursor::Painted(PaintedCursor::Crosshair) } else { sample_target() }; } - // Over a layer it can't paint (Lock All), the Mixer Brush shows a no-entry sign (#11957). - if tool == Tool::MixerBrush && mixer_target_locked(app) { + let sets_pasteboard = tool == Tool::PaintBucket + && cx.mods.shift + && cx.pointer.as_ref().and_then(|pointer| doc_point(cx, pointer.pos)).is_some_and(|at| bucket_targets_pasteboard(app, at, cx.mods)); + if !sets_pasteboard && paint_cursor_blocked(app) { return Cursor::System(CursorIcon::NotAllowed); } // The Paint Bucket and the Magic Eraser act on a click: their own pointers, no brush tip. diff --git a/crates/ui-egui/src/canvas/paint_tool/tests.rs b/crates/ui-egui/src/canvas/paint_tool/tests.rs index 281651fb54..3a8685f6ad 100644 --- a/crates/ui-egui/src/canvas/paint_tool/tests.rs +++ b/crates/ui-egui/src/canvas/paint_tool/tests.rs @@ -52,7 +52,7 @@ fn harness(mut app: Box) -> Harness<'static, Box> if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); @@ -494,11 +494,12 @@ fn painting_a_group_is_refused_at_the_press_with_a_message() { let seen = errors(&app).len(); app.ui.tool = tool; tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, M); - // Brush, Classic gradient and Magic Eraser use the measured alerts (#11898, #12017, #12020). + // Brush, Classic gradient, Magic Eraser and Paint Bucket use the measured alerts (#11898, #12017, #12020, #12537). let want = match tool { Tool::Brush => "Could not use the brush tool because the pixels in a group cannot be edited without merging the group.".to_string(), Tool::MagicEraser => "Could not use the magic eraser because the pixels in a group cannot be edited without merging the group.".to_string(), Tool::Gradient => "Could not use the gradient tool because the pixels in a group cannot be edited without merging the group.".to_string(), + Tool::PaintBucket => "Could not use the paint bucket because the pixels in a group cannot be edited without merging the group.".to_string(), _ => format!("Could not use the {} because the target layer is a group.", tool.label()), }; assert_eq!(errors(&app)[seen..], [want], "{tool:?}"); diff --git a/crates/ui-egui/src/canvas/rulers/tests.rs b/crates/ui-egui/src/canvas/rulers/tests.rs index 0b5ecfce46..9782ad3106 100644 --- a/crates/ui-egui/src/canvas/rulers/tests.rs +++ b/crates/ui-egui/src/canvas/rulers/tests.rs @@ -25,7 +25,7 @@ fn harness_with_passes(size: [u32; 2], tool: Tool, second_pass: bool) -> AppHarn 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)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); if second_pass && ui.ctx().current_pass_index() == 0 { ui.ctx().request_discard("a second pass of the frame"); } diff --git a/crates/ui-egui/src/canvas/scroll_all_windows.rs b/crates/ui-egui/src/canvas/scroll_all_windows.rs index 2d77f4da00..50209b1495 100644 --- a/crates/ui-egui/src/canvas/scroll_all_windows.rs +++ b/crates/ui-egui/src/canvas/scroll_all_windows.rs @@ -281,7 +281,7 @@ mod tests { Hidden::Home => app.ui.chrome.home = Some(app.session.documents().len()), Hidden::Card => { let job = photocraft_engine::jobs::JobId(9); - app.jobs.opens.push(crate::jobs_ui::OpenTab { job, name: "opening.psd".into(), path: None, slot: None, order: None }); + app.jobs.opens.push(crate::jobs_ui::OpenTab { job, name: "opening.psd".into(), path: None, error_source: None, slot: None, order: None }); app.jobs.focus = Some(job); } } diff --git a/crates/ui-egui/src/canvas/snap_ui.rs b/crates/ui-egui/src/canvas/snap_ui.rs index 2fa083206f..7fc08b6327 100644 --- a/crates/ui-egui/src/canvas/snap_ui.rs +++ b/crates/ui-egui/src/canvas/snap_ui.rs @@ -42,7 +42,7 @@ pub(crate) struct SnapCache { /// tool that hands its press to the Move stand-in. Read before the press so the targets do not /// change at it. fn moves_as_move_tool(app: &PhotocraftApp) -> bool { - app.ui.tool == Tool::Move || (crate::canvas::tools::takes_command_stand_in(app.ui.tool) && craft::ui::runtime::pointer::frame(app.ctx()).mods.cmd) + app.ui.tool == Tool::Move || (crate::canvas::tools::takes_command_stand_in(app.ui.tool) && craft::ui::runtime::pointer::mods(app.ctx()).cmd) } /// The selected pixels move with the drag, so the selection is not a place to snap to (#6290). diff --git a/crates/ui-egui/src/canvas/testing.rs b/crates/ui-egui/src/canvas/testing.rs index d5716b8bf3..fae446554e 100644 --- a/crates/ui-egui/src/canvas/testing.rs +++ b/crates/ui-egui/src/canvas/testing.rs @@ -121,7 +121,7 @@ fn run_frame(app: &mut PhotocraftApp) { frames.frame_without_input(os_input, |ui| { crate::shortcut_dispatch::record_view_commands(app); crate::shortcuts::handle(app, &ui.ctx().clone()); - egui::CentralPanel::default().show(ui, |ui| super::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| document_area(app, ui)); crate::dialogs::run(app, ui); crate::shortcuts::escape_keys(app, &ui.ctx().clone()); }); @@ -266,6 +266,14 @@ pub(crate) fn modifiers(app: &mut PhotocraftApp, mods: Modifiers) { settle(app); } +/// The document area as the app's window runs it: first the area's work of every pass, which the window's body runs +/// before the dock (a pending crop left by a tool switch, the tablet settings, landed redraws), then the area. Every +/// harness that shows the area without the window shows it through this. +pub(crate) fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + super::document_area::each_pass(app, ui.ctx()); + super::document_area(app, ui); +} + /// One pass with no input: what a tool change cancels, a document switch drops. pub(crate) fn frame(app: &mut PhotocraftApp) { run_frame(app); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index e2acefdd92..9c928ab231 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -919,7 +919,7 @@ fn torn_off_document_is_not_drawn_again_in_the_main_window() { let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(680.0, 480.0)).with_context(app.ctx().clone()).build_ui_state( |ui, (app, ready): &mut (Box, bool)| { if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| testing::document_area(app, ui)); } }, (app, false), @@ -990,7 +990,7 @@ fn a_new_window_for_document_keeps_its_own_view() { let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).with_context(app.ctx().clone()).build_ui_state( |ui, (app, ready): &mut (Box, bool)| { if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| testing::document_area(app, ui)); extra_windows(app, ui); } }, @@ -1028,7 +1028,7 @@ fn a_tiled_document_follows_navigator_and_status_bar_zoom() { let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).with_context(app.ctx().clone()).build_ui_state( |ui, (app, ready): &mut (Box, bool)| { if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| testing::document_area(app, ui)); } }, (app, false), diff --git a/crates/ui-egui/src/canvas/textures.rs b/crates/ui-egui/src/canvas/textures.rs index 22a92e76be..1a850582d0 100644 --- a/crates/ui-egui/src/canvas/textures.rs +++ b/crates/ui-egui/src/canvas/textures.rs @@ -317,8 +317,6 @@ pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz app.navigator_gpu.remove(&id); } let size = [doc.size.width, doc.size.height]; - // A full CPU redraw running in the background: show the blocks it has finished. - crate::background_redraw::poll(app, &gpu, id); let cache = app.canvases.entry((id, GPU_OUTPUT)).or_default(); let present = cache.on_gpu && gpu.has(id.0, size); let current = cache.revision == revision && cache.preview_key == preview_key; diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 2aa3f27260..7d8c6ba2ec 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -367,6 +367,11 @@ impl CanvasTool for Preflight<'_, '_> { return ToolAction::Done; } let at = [doc.x, doc.y]; + // Paint Bucket ⇧-click on the pasteboard sets the pasteboard colour (#12534): a + // preference, so it runs before the painting refusals, as quick pick does. + if tool == Tool::PaintBucket && self.scope.with_app(|app| super::paint_tool::bucket_pasteboard_click(app, at, pointer.mods)) { + return ToolAction::Done; + } // Let the Eyedropper take an Alt press that samples the shape tool's Fill. if self.alt_stand_in && self.scope.with_app(|app| super::cursor_policy::shape_alt_samples(app, pointer.mods, at[0], at[1])) { return ToolAction::Ignored; @@ -717,7 +722,7 @@ pub(crate) fn run(app: &mut PhotocraftApp, ui: &egui::Ui, host: CanvasHost, out: response.view = Some(view); } } - ctx.request_repaint(); + craft::ui::runtime::frame::request_repaint(&ctx); } match response.gesture { Some(GesturePhase::Begin) => tools.gesture_on = app.session.documents().get(host.idx).map(|state| (state.doc.id.0, host)), diff --git a/crates/ui-egui/src/canvas/viewport_pages.rs b/crates/ui-egui/src/canvas/viewport_pages.rs index 86860233fc..96084cbaf2 100644 --- a/crates/ui-egui/src/canvas/viewport_pages.rs +++ b/crates/ui-egui/src/canvas/viewport_pages.rs @@ -723,7 +723,7 @@ pub(super) fn show(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, vie } stream.stats.limit = limit; if stream.busy() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); + craft::ui::runtime::frame::request_repaint_after(ctx, std::time::Duration::from_millis(16).as_secs_f64()); } true } diff --git a/crates/ui-egui/src/caps_lock_tests.rs b/crates/ui-egui/src/caps_lock_tests.rs index c7826048ee..4e1a40f6c5 100644 --- a/crates/ui-egui/src/caps_lock_tests.rs +++ b/crates/ui-egui/src/caps_lock_tests.rs @@ -28,7 +28,7 @@ fn capslock_harness() -> Harness<'static, Box> { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/chrome_settle_trials.rs b/crates/ui-egui/src/chrome_settle_trials.rs index 83b4a8dd81..0e69330e7f 100644 --- a/crates/ui-egui/src/chrome_settle_trials.rs +++ b/crates/ui-egui/src/chrome_settle_trials.rs @@ -53,13 +53,42 @@ fn chrome_views(h: &H) -> Vec<(&'static str, MemoRun)> { last_frame_memo_runs(&h.ctx).into_iter().filter(|(name, _, _)| CHROME.iter().any(|c| name.contains(c))).map(|(name, _, run)| (name, run)).collect() } +/// The shell's slots of the harness's window, in the order the shell shows them (`AppShell`): the title bar, the +/// options bar, the status bar. +#[derive(Clone, Copy, Debug)] +pub(crate) enum ShellSlot { + Title, + Options, + Status, +} + +/// How the shell's view of `slot` took part in `runs`: `(ran, replayed)`. The shell's slot views share one props type, +/// so they are told apart by id, in the order the shell decides them in every pass, which is the order it shows its +/// slots in. +pub(crate) fn slot_runs(runs: &[(&'static str, egui::Id, MemoRun)], slot: ShellSlot) -> (usize, usize) { + let mut ids: Vec = Vec::new(); + for (name, id, _) in runs { + if name.contains("app_shell::SlotView<") && !ids.contains(id) { + ids.push(*id); + } + } + let Some(&id) = ids.get(slot as usize) else { return (0, 0) }; + let count = |how: MemoRun| runs.iter().filter(|(_, of, run)| *of == id && *run == how).count(); + (count(MemoRun::Ran), count(MemoRun::Replayed)) +} + +/// How the shell's view of `slot` took part in the last frame: `(ran, replayed)`. +fn slot_views(h: &H, slot: ShellSlot) -> (usize, usize) { + slot_runs(&last_frame_memo_runs(&h.ctx), slot) +} + /// The panel tab strips the last pass ran. fn tab_strip_runs(h: &H) -> Vec<(&'static str, u32)> { last_pass_runs(&h.ctx).into_iter().filter(|(ty, _)| ty.contains("TabStrip<'_, craft_ui_panels::docking::PanelKey>")).collect() } -/// A hover over the canvas replays the dock's tab rows and column bars and the menu bar (memoized views) and runs no -/// panel tab strip. +/// A hover over the canvas replays the dock's tab rows and column bars (in the columns' views, which replay whole) and +/// the menu bar (memoized views) and runs no panel tab strip. #[test] fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { let mut h = harness(); @@ -68,11 +97,14 @@ fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { for step in 1..=3 { h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); h.run_steps(1); - // The menu bar sits in the title bar's own view: while that replays, the menu bar replays with it. - let title_replayed = views(&h, "TitleSlot<", MemoRun::Replayed) == 1; + // The menu bar sits in the title slot's view: while that replays, the menu bar replays with it. + let title_replayed = slot_views(&h, ShellSlot::Title).1 == 1; + let columns = (views_ran(&h, "area::ColumnView<"), views(&h, "area::ColumnView<", MemoRun::Replayed)); + assert!(columns.0 == 0 && columns.1 >= 1, "hover step {step}: the dock's columns replay: {columns:?}"); let views = chrome_views(&h); for kind in ["TabRow", "dock_column::bar::BarProps", "menu::bar::BarProps"] { - let shown = views.iter().any(|(name, _)| name.contains(kind)) || (kind == "menu::bar::BarProps" && title_replayed); + let replayed_with = if kind == "menu::bar::BarProps" { title_replayed } else { columns.1 >= 1 }; + let shown = views.iter().any(|(name, _)| name.contains(kind)) || replayed_with; assert!(shown, "hover step {step}: the chrome shows a {kind} view: {views:?}"); } let ran: Vec<_> = views.iter().filter(|(_, run)| *run != MemoRun::Replayed).collect(); @@ -81,8 +113,9 @@ fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { } } -/// A hover over the canvas replays the title bar, the options bar, the status bar (its own view) and every panel body: the -/// panels read the modifiers, not the pointer frame (storytold/craft-libs#2812), so a pointer move runs none of them. +/// A hover over the canvas replays the title bar, the options bar, the status bar (its own view) and every panel body +/// (in the columns' views, which replay whole): the panels read the modifiers, not the pointer frame +/// (storytold/craft-libs#2812), so a pointer move runs none of them. #[test] fn a_hover_over_the_canvas_replays_the_bars_and_the_panel_bodies() { let mut h = harness(); @@ -90,16 +123,20 @@ fn a_hover_over_the_canvas_replays_the_bars_and_the_panel_bodies() { for step in 1..=3 { h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); h.run_steps(1); - for slot in ["TitleSlot<", "OptionsSlot<", "status_bar::StatusProps<"] { - assert_eq!((views_ran(&h, slot), views(&h, slot, MemoRun::Replayed)), (0, 1), "hover step {step}: the {slot} view replays"); + for slot in [ShellSlot::Title, ShellSlot::Options, ShellSlot::Status] { + assert_eq!(slot_views(&h, slot), (0, 1), "hover step {step}: the {slot:?} slot's view replays"); } - let bodies = (views_ran(&h, "region_versions::PanelBody<"), views(&h, "region_versions::PanelBody<", MemoRun::Replayed)); - assert!(bodies.0 == 0 && bodies.1 >= 2, "hover step {step}: every panel body replays: {bodies:?}"); + let columns = (views_ran(&h, "area::ColumnView<"), views(&h, "area::ColumnView<", MemoRun::Replayed)); + assert!( + views_ran(&h, "region_versions::PanelBody<") == 0 && columns == (0, columns.1) && columns.1 >= 2, + "hover step {step}: every panel body replays with its column: {columns:?}" + ); } } -/// A hover over the canvas replays the toolbar's footer (the colour chips, Quick Mask and Screen Mode): the rail replays -/// its tool buttons but calls its footer every pass, so before it was a view of its own it ran on every frame (#15493). +/// A hover over the canvas replays the toolbar's footer (the colour chips, Quick Mask and Screen Mode) with the toolbar's +/// column: the rail replays its tool buttons but calls its footer every pass, so before it was a view of its own it ran +/// on every frame (#15493). #[test] fn a_hover_over_the_canvas_replays_the_toolbar_footer() { let mut h = harness(); @@ -107,11 +144,25 @@ fn a_hover_over_the_canvas_replays_the_toolbar_footer() { for step in 1..=3 { h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); h.run_steps(1); - let footer = (views_ran(&h, "toolbar::FooterProps<"), views(&h, "toolbar::FooterProps<", MemoRun::Replayed)); - assert_eq!(footer, (0, 1), "hover step {step}: the toolbar footer replays"); + let columns = (views_ran(&h, "area::ColumnView<"), views(&h, "area::ColumnView<", MemoRun::Replayed)); + assert!(views_ran(&h, "toolbar::FooterProps<") == 0 && columns.0 == 0 && columns.1 >= 1, "hover step {step}: the toolbar footer replays: {columns:?}"); } } +/// The pointer-move gate (#17148): a move within one toolbar button changes nothing under the pointer, so it runs no +/// frame; a move over the canvas runs one, since the canvas follows the pointer (its cursor, the rulers' marks and the +/// readouts). +#[test] +fn a_move_within_a_button_runs_no_frame_and_one_over_the_canvas_does() { + let h = harness(); + let viewport = egui::ViewportId::ROOT; + let button = h.query_all_by_label("Move Tool").last().map(|node| node.rect()).expect("the toolbar shows the Move tool"); + let inside = button.center(); + assert!(!h.ctx.pointer_move_needs_pass(viewport, Some(inside), inside + vec2(1.0, 1.0)), "a move within the button"); + let canvas = h.state().last_canvas_rect.center(); + assert!(h.ctx.pointer_move_needs_pass(viewport, Some(canvas), canvas + vec2(1.0, 1.0)), "a move over the canvas"); +} + /// Zoom In from the menu runs no panel body that does not show the view: before, every command counted as a command /// run, so a zoom ran every panel body in the next frame (#15493). #[test] @@ -120,8 +171,9 @@ fn a_zoom_runs_only_the_panels_that_show_the_view() { let ctx = h.ctx.clone(); crate::menus::invoke(h.state_mut(), &ctx, "view.zoomIn", json!({})).unwrap(); h.run_steps(1); - let bodies = (views_ran(&h, "region_versions::PanelBody<"), views(&h, "region_versions::PanelBody<", MemoRun::Replayed)); - assert!(bodies.0 <= 1 && bodies.1 >= 2, "only the Navigator's body may run, the others replay: {bodies:?}"); + let columns = views(&h, "area::ColumnView<", MemoRun::Replayed); + let bodies = views_ran(&h, "region_versions::PanelBody<"); + assert!(bodies <= 1 && columns >= 1, "only the Navigator's body may run, the other columns replay: {bodies} ran, {columns} columns replayed"); } /// The footer runs again when a colour it shows changes without a command (the Color panel's sliders, a Color Picker @@ -166,7 +218,7 @@ fn the_chrome_runs_when_what_it_shows_changes() { h.run_steps(1); // The new tab titles change label widths, so the frame takes a second pass that replays what the first ran: // the frame's views tell. - let (tabs, title) = (views_ran(&h, "docking::group::TabRow<"), views_ran(&h, "TitleSlot<")); + let (tabs, title) = (views_ran(&h, "docking::group::TabRow<"), slot_views(&h, ShellSlot::Title).0); assert!(tabs > 0 && title > 0, "a new language runs the tab rows and the title bar: {tabs} tab rows, {title} title bars"); h.run_steps(2); } @@ -181,7 +233,7 @@ fn the_chrome_runs_when_what_it_shows_changes() { h.state_mut().run("layer.new.layer", json!({})).unwrap(); h.run_steps(1); // The edit's frame takes two passes, and its second replays what the first ran: the frame's views tell. - assert!(views_ran(&h, "TitleSlot<") > 0, "an unsaved edit runs the title bar"); + assert!(slot_views(&h, ShellSlot::Title).0 > 0, "an unsaved edit runs the title bar"); } /// A dialog closed with Escape runs no command, and the menu bar takes the menu keys again: Alt+F opens the File menu. @@ -201,3 +253,90 @@ fn the_menu_keys_open_a_menu_after_a_dialog_closes_with_escape() { h.run_steps(4); assert!(items(&h) > titles, "Alt+F opens the File menu: {} menu items, {titles} titles", items(&h)); } + +/// What `ran` counts in each of the next `steps` frames, summed. +fn ran_over(h: &mut H, steps: usize, ran: impl Fn(&H) -> usize) -> usize { + (0..steps) + .map(|_| { + h.run_steps(1); + ran(h) + }) + .sum() +} + +/// The options bar's slot view, if it ran in the last frame. +fn options_ran(h: &H) -> usize { + slot_views(h, ShellSlot::Options).0 +} + +/// The status bar's body view, if it ran in the last frame. +fn status_ran(h: &H) -> usize { + views_ran(h, "status_bar::StatusProps<") +} + +/// A pan with a tool whose bar shows no view field runs neither the options bar nor the status bar (it shows the zoom +/// only); a zoom runs the status bar, and the options bar only while the Zoom tool's bar shows the zoom. +#[test] +fn a_pan_runs_neither_bar_and_a_zoom_runs_the_status_bar() { + let mut h = harness(); + h.state_mut().ui.tool = crate::state::Tool::Move; + h.run_steps(4); + h.state_mut().ui.views[0].center[0] += 40.0; + assert_eq!(ran_over(&mut h, 3, options_ran), 0, "a pan runs no options bar"); + h.state_mut().ui.views[0].center[0] += 40.0; + assert_eq!(ran_over(&mut h, 3, status_ran), 0, "a pan runs no status bar"); + + h.state_mut().ui.views[0].zoom *= 2.0; + let status = ran_over(&mut h, 3, status_ran); + assert!(status > 0, "a zoom runs the status bar: {status}"); +} + +/// The Zoom tool's bar shows the zoom, so a zoom runs it. +#[test] +fn a_zoom_runs_the_zoom_tools_options_bar() { + let mut h = harness(); + h.state_mut().ui.tool = crate::state::Tool::Zoom; + h.run_steps(4); + h.state_mut().ui.views[0].zoom *= 2.0; + assert!(ran_over(&mut h, 3, options_ran) > 0, "a zoom runs the Zoom tool's bar"); +} + +/// A tool option changed outside the bar runs the bar, and the frames after it replay it. +#[test] +fn a_tool_option_runs_the_options_bar_once() { + let mut h = harness(); + h.state_mut().ui.tool = crate::state::Tool::Move; + h.run_steps(4); + assert_eq!(ran_over(&mut h, 2, options_ran), 0, "settled"); + let on = h.state().ui.tool_options.move_auto_select; + h.state_mut().ui.tool_options.move_auto_select = !on; + assert!(ran_over(&mut h, 1, options_ran) > 0, "a changed option runs the bar"); + // What the bar's frame remembers of the option (the saved preferences) moves no version. + assert_eq!(ran_over(&mut h, 3, options_ran), 0, "the frames after the changed one run no bar"); +} + +/// A bar that runs and writes every control's value back leaves the tool options' revision alone, so idle frames never +/// move what the bar's version holds, whichever tool's bar is showing. +#[test] +fn an_idle_options_bar_leaves_the_tool_options_revision() { + let mut h = harness(); + let mut moved = Vec::new(); + for tool in crate::state::Tool::ALL { + h.state_mut().ui.tool = tool; + h.run_steps(4); + let settled = h.state().ui.tool_options.revision(); + h.run_steps(6); + if h.state().ui.tool_options.revision() != settled { + moved.push(tool); + } + } + assert!(moved.is_empty(), "idle frames moved the tool options under {moved:?}"); + // A changed option runs the bar, whose own writes then change nothing more. + h.state_mut().ui.tool = crate::state::Tool::Move; + h.run_steps(4); + let on = h.state().ui.tool_options.move_auto_select; + h.state_mut().ui.tool_options.move_auto_select = !on; + let changed = h.state().ui.tool_options.revision(); + h.run_steps(10); + assert_eq!(h.state().ui.tool_options.revision(), changed, "the bar's run after a change"); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5530ed0ec4..55ad0c7345 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -446,6 +446,7 @@ pub(crate) fn prompts_take(app: &mut PhotocraftApp, ctx: &egui::Context) { /// The families that take their own results (one `take(app, ctx)` each), in order. pub(crate) const TAKERS: &[fn(&mut PhotocraftApp, &egui::Context)] = &[ alerts::take, + crate::file_open::take_open_alerts, discard_ui::take, open_prompt::take, credits::take, @@ -633,6 +634,10 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) /// Preference entries the engine reads itself, by key: the engine has no settings store, so they cannot move. const ENGINE_READ: &[&str] = &["ui.layersPanelOptions", "file.print", "file.export.saveForWebLegacy"]; +/// Preference entries the engine reads that a workspace also remembers in the framework's store: they stay, and are +/// copied there only while it holds none. An empty recorded Content-Aware Fill step plays with the engine's copy (#14254). +const ENGINE_READ_SHARED: &[&str] = &[photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS]; + /// The "Don't show again" entries (`{"skip": true}`), by key, as their prompt modules read them. Told apart by key, not /// by the shape of the value. fn dont_show_again_keys() -> [&'static str; 5] { @@ -686,7 +691,9 @@ fn convert_blend_mode(key: &str, value: &mut Value) { /// Moves the dialogs' last-used values out of `Preferences.dialogs` into the remembered section of `host`, once, before /// the first frame. Entries the engine reads and the don't-show-again entries stay; a second run finds nothing to move -/// because every moved entry left `Preferences.dialogs`. An entry that has no table form stays too. +/// because every moved entry left `Preferences.dialogs`. An entry that has no table form stays too, and a shared entry +/// ([`ENGINE_READ_SHARED`]) never replaces what the framework already remembers; a profile without one gets it from +/// what the framework remembers ([`carry_forward_shared`]). pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let keys: Vec = prefs.dialogs.keys().cloned().collect(); for key in keys { @@ -694,10 +701,38 @@ pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let Some(old) = prefs.dialogs.get(&key) else { continue }; let mut value = without_nulls(old.clone()); convert_blend_mode(&key, &mut value); + if key == photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS { + crate::caf_ui::recorded_to_workspace(&mut value); + } let Ok(table) = toml::Table::try_from(&value) else { continue }; - Remembered::::new(scope).store(host, &table); + let remembered = Remembered::::new(scope); + if ENGINE_READ_SHARED.contains(&key.as_str()) { + // An empty entry holds no settings yet (see `carry_forward_shared`). + if !table.is_empty() && remembered.recall(host).is_none() { + remembered.store(host, &table); + } + continue; + } + remembered.store(host, &table); prefs.dialogs.remove(&key); } + carry_forward_shared(prefs, host); +} + +/// Gives a profile without the engine's copy of a shared entry one, once (#14254). An earlier version moved the +/// Content-Aware Fill settings into the workspace's own memory and kept no copy, so that memory is carried forward: +/// it is all such a profile has, although it also holds settings the workspace closed with and never filled. With no +/// memory the copy starts empty. From then on only a fill that ran sets the copy, so settings closed without a fill +/// are never carried forward. +fn carry_forward_shared(prefs: &mut Preferences, host: &Host) { + for key in ENGINE_READ_SHARED { + if prefs.dialogs.contains_key(*key) { + continue; + } + let Some(scope) = memory_destination(key) else { continue }; + let memory = Remembered::::new(scope).recall(host).and_then(|table| serde_json::to_value(table).ok()); + prefs.dialogs.insert((*key).into(), memory.map_or_else(|| serde_json::json!({}), crate::caf_ui::recorded_from_workspace)); + } } pub mod adjust_dialog; @@ -709,6 +744,9 @@ mod arbitrary_ruler_prefill_tests; pub mod assign_profile_layers_alert; #[cfg(test)] mod assign_profile_layers_alert_tests; +#[cfg(test)] +mod auto_align_dialog_tests; +pub(crate) mod auto_align_ui; pub(crate) mod bitmap_dialog; pub mod blend_options; pub mod blur_pins; @@ -739,6 +777,8 @@ pub mod delete_layer_prompt; pub mod discard_ui; pub mod disk_change_prompt; pub mod distort_ui; +#[cfg(test)] +mod duplicate_layer_other_document_name_tests; pub mod duplicate_layer_ui; pub mod equalize_ui; pub mod export_dialog; diff --git a/crates/ui-egui/src/dialogs/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs index 4ff8b48570..7558da5ea0 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors.rs @@ -174,6 +174,8 @@ pub struct AdjustOut { pub ask: Option, /// The pass's edit events of the value, in order, with their gesture ids and phases. pub edit: EditEvents, + /// The tone Color Balance shows after the pass, for a host that keeps it; `None` for the other kinds. + pub tone: Option, } /// What the editor function reads, built once when the adjustment opens. @@ -189,7 +191,8 @@ pub struct EditorSetup { pub gradients: Vec, /// The current foreground and background colours ([`swatches`]), for the host's colour requests. pub swatches: [[f32; 3]; 2], - /// The tone Color Balance shows first; `None` keeps the editor's default (Midtones). + /// The tone Color Balance shows, for a host that keeps it (it stores [`AdjustOut::tone`]); `None` leaves the + /// tone to the editor (Midtones at first). pub tone: Option, /// The Smart Filter the dialog edits is not reachable from the active document: the editor shows no controls. pub stale: bool, @@ -215,7 +218,7 @@ impl Default for EditorSetup { /// The edit events of one editor lifted onto the value. fn lifted(events: EditEvents, wrap: impl Fn(T) -> AdjustValue) -> AdjustOut { - AdjustOut { ask: None, edit: events.map(wrap) } + AdjustOut { ask: None, edit: events.map(wrap), tone: None } } fn reset_legacy_toggle(value: BrightnessContrast, previous_legacy: bool, reset: bool) -> BrightnessContrast { @@ -288,7 +291,7 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c *curves = converted.clone(); edit.push(EditEvent::set(Mixed::Same(from), AdjustValue::Curves { curves: converted }, Arc::from("Curves Mode"), None)); } - AdjustOut { ask: None, edit } + AdjustOut { ask: None, edit, tone: None } } ("exposure", AdjustValue::Exposure { values }) => { let fields = AdjustField::exposure(&Env::of(ui).words::()); @@ -315,16 +318,16 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c editor = editor.tone(tone); } let out = editor.show(ui); - lifted(out.edit.events, |value| AdjustValue::ColorBalance { value }) + AdjustOut { tone: Some(out.tone), ..lifted(out.edit.events, |value| AdjustValue::ColorBalance { value }) } } ("blackWhite", AdjustValue::BlackWhite { value }) => { let out = BlackWhiteEditor::new("Black & White", Bind::bound(value)).context(context).show(ui); let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) }; - AdjustOut { ask, edit: out.edit.events.map(|value| AdjustValue::BlackWhite { value }) } + AdjustOut { ask, edit: out.edit.events.map(|value| AdjustValue::BlackWhite { value }), tone: None } } ("photoFilter", AdjustValue::PhotoFilter { value }) => { let out = PhotoFilterEditor::new("Photo Filter", Bind::bound(value)).context(context).show(ui); - AdjustOut { ask: out.pick_color.map(AdjustAsk::PickColor), edit: out.edit.events.map(|value| AdjustValue::PhotoFilter { value }) } + AdjustOut { ask: out.pick_color.map(AdjustAsk::PickColor), edit: out.edit.events.map(|value| AdjustValue::PhotoFilter { value }), tone: None } } ("channelMixer", AdjustValue::ChannelMixer { value }) => { let out = ChannelMixerEditor::new("Channel Mixer", Bind::bound(value)).context(context).show(ui); @@ -358,7 +361,7 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c AdjustAsk::PickColor(request) }) }; - AdjustOut { ask, edit } + AdjustOut { ask, edit, tone: None } } ("selectiveColor", AdjustValue::SelectiveColor { value }) => { let out = SelectiveColorEditor::new("Selective Color", Bind::bound(value)).context(context).show(ui); diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index 2c0b85ca45..f3493ab60d 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -32,7 +32,7 @@ pub(crate) struct PropertiesAdjust { pub channel: usize, /// The Levels clipping display. pub clipping: Option, - /// A tone for Color Balance to show, given once: the Reset to defaults shows Midtones again. + /// The tone Color Balance shows, as the editor last reported it; the Reset to defaults sets Midtones. pub tone: Option, /// The Color Picker a colour well opened, while it is open. pub pick: Option, @@ -187,7 +187,6 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj // count of passes the panel showed something else or nothing (`PhotocraftApp::properties_hidden`), which stays // put while it shows this layer, replays included. record.session.track(session_target(doc, id), app.properties_hidden, &committed); - app.properties_tracked = true; } follow_color_pick(app, id, &mut record, &committed, &vcx); let mut value = match &app.live_adjust { @@ -207,7 +206,7 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj }, gradients: if kind == "gradientMap" { gradient_presets(app) } else { Vec::new() }, swatches: swatches(app), - tone: record.tone.take(), + tone: record.tone, ..Default::default() }; let armed = crate::layer_picker::armed(app).filter(|(layer, _)| *layer == id).map(|(_, picker)| picker); @@ -220,6 +219,9 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj if picker != armed { crate::layer_picker::arm(app, id, picker); } + if out.tone.is_some() { + record.tone = out.tone; + } for event in out.edit { match &event { diff --git a/crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs b/crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs new file mode 100644 index 0000000000..a39c7a1a21 --- /dev/null +++ b/crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs @@ -0,0 +1,276 @@ +//! #14196: Edit › Auto-Align Layers opens the reference application's dialog: a Projection group of six radios over +//! three columns (Auto, Perspective, Collage / Cylindrical, Spherical, Reposition) with Auto selected on a fresh +//! start, a Lens Correction group (Vignette Removal, Geometric Distortion, both off; Collage and Reposition grey and +//! clear them), the selected projection's description line and the warnings under them, OK and Cancel. No +//! Interpolation or Registration rows, Alt keeps Cancel a Cancel, and the last run's projection (also a scripted +//! one) is what the dialog reopens with. + +use craft::ui::dialog::DialogId; +use egui::accesskit::{Role, Toggled}; +use egui::{Event, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::LayerId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::new_layer_ui::testing::{fields, set, top}; + +const COMMAND: &str = "edit.autoAlignLayers"; +/// The radios in reading order: the first row, then the second. +const RADIOS: [&str; 6] = ["Auto", "Perspective", "Collage", "Cylindrical", "Spherical", "Reposition"]; + +type H = Harness<'static, Box>; + +/// The deterministic texture of the engine's Auto-Align tests, written into layer `id` at offset (dx, dy). +fn paint_texture(app: &mut PhotocraftApp, id: LayerId, dx: i32, dy: i32) { + app.session + .edit("tex", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let mut seed = 99u64; + let mut rnd = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as f64 / (1u64 << 31) as f64 + }; + surf.fill_rect(photocraft_geom::Rect::new(dx, dy, dx + 240, dy + 180), &[0.4, 0.4, 0.4, 1.0]); + for _ in 0..120 { + let (x, y) = ((rnd() * 220.0) as i32, (rnd() * 160.0) as i32); + let (sw, sh) = (4 + (rnd() * 14.0) as i32, 4 + (rnd() * 10.0) as i32); + let v = rnd() as f32; + surf.fill_rect(photocraft_geom::Rect::new(dx + x, dy + y, dx + x + sw, dy + y + sh), &[v, 1.0 - v, v * 0.5, 1.0]); + } + Ok(()) + }) + .unwrap(); +} + +/// A 300x240 document with two textured layers, the second offset, both selected: Auto-Align can run on it. +fn two_layers(app: &mut PhotocraftApp) { + app.run("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); + let mut ids = Vec::new(); + for (name, dx, dy) in [("A", 20, 20), ("B", 31, 13)] { + app.run("layer.new.layer", json!({"name": name})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + paint_texture(app, id, dx, dy); + ids.push(id); + } + app.run("layer.select", json!({"layer": ids[0].0})).unwrap(); + app.run("layer.select", json!({"layer": ids[1].0, "mode": "add"})).unwrap(); +} + +/// The whole app with the two-layer document, before the dialog opens. +fn harness() -> H { + let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + two_layers(&mut app); + app + }); + h.run_steps(3); + h +} + +/// Opens the dialog through the menu and draws a few frames. +fn open(h: &mut H) -> DialogId { + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); + let id = top(h.state()); + h.run_steps(4); + id +} + +fn dialog() -> (H, DialogId) { + let mut h = harness(); + let id = open(&mut h); + (h, id) +} + +fn radio(h: &H, label: &str) -> egui::Rect { + h.get_by_role_and_label(Role::RadioButton, label).rect() +} + +fn checked(h: &H, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(Toggled::True) +} + +fn disabled(h: &H, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().is_disabled() +} + +fn sent(h: &H, id: DialogId) -> Value { + crate::filter_dialog::command_params(COMMAND, fields(h.state(), id)) +} + +fn shows(h: &H, text: &str) -> bool { + h.query_all_by_label(text).next().is_some() +} + +#[test] +fn six_projection_radios_stand_three_by_two_with_auto_selected() { + let (h, _) = dialog(); + let rects: Vec = RADIOS.iter().map(|label| radio(&h, label)).collect(); + for row in [&rects[0..3], &rects[3..6]] { + for r in &row[1..] { + assert!((r.center().y - row[0].center().y).abs() < 4.0, "one row: {row:?}"); + } + assert!(row[0].right() < row[1].left() && row[1].right() < row[2].left(), "left to right: {row:?}"); + } + assert!(rects[3].top() > rects[0].bottom(), "Cylindrical, Spherical and Reposition stand under the first row"); + for col in 0..3 { + assert!((rects[col].left() - rects[col + 3].left()).abs() < 4.0, "column {col} lines up"); + } + assert!(checked(&h, Role::RadioButton, "Auto"), "a fresh dialog selects Auto"); + for label in &RADIOS[1..] { + assert!(!checked(&h, Role::RadioButton, label), "{label} starts clear"); + } +} + +#[test] +fn the_description_line_follows_the_selected_radio() { + let (mut h, id) = dialog(); + assert!(shows(&h, "Determine the best projection automatically.")); + for (label, line) in [ + ("Perspective", "Only allow perspective image transform."), + ("Collage", "Allow image rotation, scale and translation."), + ("Cylindrical", "Only allow cylindrical image transform."), + ("Spherical", "Only allow spherical image transform."), + ("Reposition", "Only allow image translation."), + ] { + h.get_by_role_and_label(Role::RadioButton, label).click(); + h.run_steps(3); + assert!(shows(&h, line), "{label}: {line}"); + assert!(!shows(&h, "Determine the best projection automatically."), "{label}: one description line"); + assert_eq!(sent(&h, id)["projection"], json!(label.to_lowercase())); + } +} + +#[test] +fn lens_correction_has_two_clear_boxes_that_collage_and_reposition_grey_and_clear() { + let (mut h, id) = dialog(); + assert!(shows(&h, "Projection") && shows(&h, "Lens Correction"), "the two groups are named"); + for label in ["Vignette Removal", "Geometric Distortion"] { + assert!(!checked(&h, Role::CheckBox, label), "{label} starts off"); + } + h.get_by_role_and_label(Role::CheckBox, "Geometric Distortion").click(); + h.run_steps(3); + assert!(checked(&h, Role::CheckBox, "Geometric Distortion")); + assert_eq!(sent(&h, id)["geometricCorrection"], json!(true), "Geometric Distortion drives geometricCorrection"); + for picked in ["Collage", "Reposition"] { + h.get_by_role_and_label(Role::RadioButton, picked).click(); + h.run_steps(3); + assert!(disabled(&h, Role::CheckBox, "Geometric Distortion") && disabled(&h, Role::CheckBox, "Vignette Removal"), "{picked} greys both"); + assert!(!checked(&h, Role::CheckBox, "Geometric Distortion"), "{picked} clears it"); + assert_eq!(sent(&h, id)["geometricCorrection"], json!(false)); + } + h.get_by_role_and_label(Role::RadioButton, "Auto").click(); + h.run_steps(3); + assert!(!disabled(&h, Role::CheckBox, "Geometric Distortion"), "Auto enables it again"); + assert!(!checked(&h, Role::CheckBox, "Geometric Distortion"), "still cleared"); +} + +#[test] +fn no_interpolation_or_registration_rows_and_the_command_keeps_them() { + let (h, id) = dialog(); + assert!(h.query_by_label("Interpolation").is_none(), "no Interpolation row"); + assert!(h.query_by_label("Registration").is_none(), "no Registration row"); + let params = sent(&h, id); + assert!(params.get("interpolation").is_none() && params.get("registration").is_none(), "the command's defaults apply: {params}"); + let spec = photocraft_engine::commands::find(COMMAND).unwrap(); + let keys: Vec = craft::ui::patterns::form_dialogs::Param::parse_list(spec.params).into_iter().map(|p| p.key).collect(); + assert!(keys.iter().any(|k| k == "interpolation") && keys.iter().any(|k| k == "registration"), "{keys:?}"); +} + +#[test] +fn the_metadata_warning_shows_for_layers_without_camera_metadata() { + let (h, _) = dialog(); + assert!( + shows( + &h, + "Warning: Could not detect camera metadata. Use the \"File > Scripts > Load Images into Stack...\" script to preserve metadata for Vignette Removal and/or Geometric Distortion." + ), + "the document has no EXIF" + ); + assert!( + !shows( + &h, + "Warning: For better Vignette Removal results, shoot with the same camera, lens, aperture, resolution, orientation, focal length and focus settings." + ), + "Vignette Removal is off" + ); +} + +/// The text block's lines: the description, the metadata warning, then the vignette warning while it is ticked. +#[test] +fn the_text_block_lists_the_warnings_in_order() { + use super::auto_align_ui::{METADATA_WARNING, VIGNETTE_WARNING, lines}; + assert_eq!(lines("reposition", false, true), vec!["Only allow image translation."]); + assert_eq!(lines("auto", false, false), vec!["Determine the best projection automatically.", METADATA_WARNING]); + assert_eq!(lines("auto", true, false), vec!["Determine the best projection automatically.", METADATA_WARNING, VIGNETTE_WARNING]); + assert_eq!(lines("spherical", true, true), vec!["Only allow spherical image transform.", VIGNETTE_WARNING]); +} + +#[test] +fn alt_keeps_cancel_and_escape_cancels() { + let (mut h, _) = dialog(); + h.event(Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(2); + assert!(h.query_by_label("Reset").is_none(), "Alt does not turn Cancel into Reset"); + h.get_by_role_and_label(Role::Button, "Cancel"); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + let before = h.state().session.active().unwrap().history.past_len(); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(h.query_by_label("Only allow image translation.").is_none() && !shows(&h, "Lens Correction"), "Escape closes the dialog"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before, "Escape leaves the history alone"); +} + +#[test] +fn ok_runs_and_the_dialog_reopens_with_the_projection_and_ticks_it_ran_with() { + let (mut h, id) = dialog(); + h.get_by_role_and_label(Role::RadioButton, "Perspective").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::CheckBox, "Geometric Distortion").click(); + h.run_steps(2); + let before = h.state().session.active().unwrap().history.past_len(); + crate::dialogs::testing::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before + 1, "OK runs Auto-Align"); + let id = open(&mut h); + assert!(checked(&h, Role::RadioButton, "Perspective"), "reopens with Perspective"); + assert!(checked(&h, Role::CheckBox, "Geometric Distortion"), "and the tick confirmed with OK"); + assert_eq!(sent(&h, id)["projection"], json!("perspective")); +} + +#[test] +fn a_scripted_run_decides_the_projection_the_dialog_reopens_with() { + let mut h = harness(); + // An OK with Geometric Distortion ticked first, so the script's run has something to replace. + let id = open(&mut h); + h.get_by_role_and_label(Role::CheckBox, "Geometric Distortion").click(); + h.run_steps(2); + crate::dialogs::testing::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); + h.state_mut().run(COMMAND, json!({"projection": "reposition"})).unwrap(); + h.run_steps(2); + let id = open(&mut h); + assert!(checked(&h, Role::RadioButton, "Reposition"), "the scripted projection"); + assert!(!checked(&h, Role::CheckBox, "Geometric Distortion"), "a run without the lens keys leaves the box clear"); + assert!(shows(&h, "Only allow image translation.")); + assert_eq!(sent(&h, id)["projection"], json!("reposition")); +} + +#[test] +fn an_agent_sets_the_projection_by_its_id_and_a_bad_one_is_refused() { + let (mut h, id) = dialog(); + set(h.state_mut(), id, "projection", json!("cylindrical")).unwrap(); + h.run_steps(3); + assert!(checked(&h, Role::RadioButton, "Cylindrical")); + assert_eq!(sent(&h, id)["projection"], json!("cylindrical")); + // An unknown id never reaches the command: the row keeps a projection it knows. + let _ = set(h.state_mut(), id, "projection", json!("sideways")); + h.run_steps(3); + let projection = sent(&h, id)["projection"].as_str().unwrap().to_owned(); + assert!(RADIOS.iter().any(|r| r.to_lowercase() == projection), "{projection}"); +} diff --git a/crates/ui-egui/src/dialogs/auto_align_ui.rs b/crates/ui-egui/src/dialogs/auto_align_ui.rs new file mode 100644 index 0000000000..0e16b6e75e --- /dev/null +++ b/crates/ui-egui/src/dialogs/auto_align_ui.rs @@ -0,0 +1,285 @@ +//! Edit › Auto-Align Layers: the reference application's dialog (#14196). A Projection group of six radios with a +//! small picture under each (3 x 2), a Lens Correction group with Vignette Removal and Geometric Distortion, and a +//! text block at the foot: the selected projection's description and the warnings. OK and Cancel; Alt does not turn +//! Cancel into Reset. +//! +//! It stays the command's schema dialog (`filter_dialog::open`), so Enter / Escape, `ui.dialog.*`, action step +//! dialogs and the no-match alert work as for every other command dialog; only its rows and buttons differ. The +//! command keeps its `interpolation` and `registration` params for scripts: the dialog has no rows for them, so the +//! command's own defaults apply. +//! +//! Memory: the projection lives in a hidden radio row ([`LAST`]) the framework remembers on OK beside the two boxes. +//! A run that did not come from this dialog (a script, the control channel, an action step) lands in the session's +//! journal; opening the dialog copies the last journaled run into those remembered values, so it reopens with the +//! projection (and the lens keys) that run used. + +use craft::behavior::ColumnWidth; +use craft::ui::choice::{Radio, RadioGroup}; +use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::{Shade, Text}; +use craft::ui::layout_components::{Grid, Stack}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; +use craft::ui::runtime::env::Label; +use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; +use egui::{Color32, Pos2, Rect, Shape, Stroke, pos2, vec2}; +use serde_json::{Map, Value}; + +use crate::PhotocraftApp; +use crate::theme::Tokens; + +pub const COMMAND: &str = "edit.autoAlignLayers"; +/// The projection the command runs with. The custom row writes it; an agent's `ui.dialog.set` may too. +pub const PROJECTION: &str = "projection"; +/// The hidden radio row that keeps the projection the framework remembers (a custom row's value is not remembered). +pub const LAST: &str = "__projection"; +/// The Geometric Distortion box: the command's `geometricCorrection`. +pub const GEOMETRIC: &str = "geometricCorrection"; +/// The Vignette Removal box: the command's `vignetteRemoval`, once the engine takes it (#14197). +pub const VIGNETTE: &str = "vignetteRemoval"; + +/// The projections in the reference application's order, row by row over three columns: id, label and the +/// description line it shows while selected. +pub const PROJECTIONS: [(&str, &str, &str); 6] = [ + ("auto", "Auto", "Determine the best projection automatically."), + ("perspective", "Perspective", "Only allow perspective image transform."), + ("collage", "Collage", "Allow image rotation, scale and translation."), + ("cylindrical", "Cylindrical", "Only allow cylindrical image transform."), + ("spherical", "Spherical", "Only allow spherical image transform."), + ("reposition", "Reposition", "Only allow image translation."), +]; +/// The projections that grey and clear both Lens Correction boxes. +const NO_LENS: [&str; 2] = ["collage", "reposition"]; +const COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; +/// The picture under each radio, in points. +const PICTURE: egui::Vec2 = vec2(64.0, 40.0); + +/// The text under the boxes when the layers carry no camera metadata. +pub const METADATA_WARNING: &str = "Warning: Could not detect camera metadata. Use the \"File > Scripts > Load Images into Stack...\" script to preserve metadata for Vignette Removal and/or Geometric Distortion."; +/// The text under the boxes while Vignette Removal is ticked. +pub const VIGNETTE_WARNING: &str = + "Warning: For better Vignette Removal results, shoot with the same camera, lens, aperture, resolution, orientation, focal length and focus settings."; + +/// `id` when it names one of the six projections. +fn known(id: &str) -> Option<&'static str> { + PROJECTIONS.iter().map(|(p, _, _)| *p).find(|p| *p == id) +} + +/// Whether the projection `id` lets the Lens Correction boxes take input. +pub fn lens_allowed(id: &str) -> bool { + !NO_LENS.contains(&id) +} + +/// Whether the engine's command takes `vignetteRemoval` yet (#14197); until then the box is shown disabled. +pub fn vignette_supported() -> bool { + photocraft_engine::commands::find(COMMAND).is_some_and(|c| Param::parse_list(c.params).iter().any(|p| p.key == VIGNETTE)) +} + +/// The projection the dialog's values hold: the row's own value (text, or the JSON string `ui.dialog.set` writes), +/// else the remembered one, else Auto. +pub fn projection(fields: &DialogFields) -> &'static str { + let own = match fields.get(PROJECTION) { + Some(FieldValue::Text(id)) => known(id), + Some(FieldValue::Json(Value::String(id))) => known(id), + _ => None, + }; + own.or_else(|| fields.text(LAST).and_then(known)).unwrap_or("auto") +} + +/// The save key the schema dialog remembers this command's values under. +fn remembered_key() -> SaveKey { + SaveKey::named(super::params::memory_scope(COMMAND)) +} + +/// Whether the active document carries camera metadata (a camera make or model in its EXIF). +fn has_camera_metadata(app: &PhotocraftApp) -> bool { + app.session.active().and_then(|st| st.doc.metadata.exif.as_ref()).is_some_and(|exif| { + let info = photocraft_algo::exif::read(exif); + info.make.is_some_and(|m| !m.trim().is_empty()) || info.model.is_some_and(|m| !m.trim().is_empty()) + }) +} + +/// Copies the session's last journaled run of the command into the values the dialog remembers, so a run from a +/// script, the control channel or an action step decides what the dialog reopens with, as one confirmed with OK +/// does. Keys the run left out are their defaults: a scripted run without the lens keys leaves both boxes clear. +pub(crate) fn adopt_last_run(app: &PhotocraftApp) { + let Some((_, params)) = app.session.journal.iter().rev().find(|(id, _)| id == COMMAND) else { return }; + let ctx = app.ctx(); + let key = remembered_key(); + let mut saved = saved_value::>(ctx, &key).unwrap_or_default(); + let id = params.get(PROJECTION).and_then(Value::as_str).and_then(known).unwrap_or("auto"); + let lens = lens_allowed(id); + let flag = |k: &str| lens && params.get(k).and_then(Value::as_bool).unwrap_or(false); + saved.set(LAST, FieldValue::Text(id.to_owned())); + saved.set(GEOMETRIC, FieldValue::Bool(flag(GEOMETRIC))); + saved.set(VIGNETTE, FieldValue::Bool(flag(VIGNETTE))); + set_saved_value(ctx, &key, Some(saved)); +} + +/// The dialog's rows, in place of the schema's: the Projection group, the Lens Correction group and the text block. +/// Opening also adopts the last journaled run ([`adopt_last_run`]). +pub(crate) fn params(app: &PhotocraftApp) -> Vec { + adopt_last_run(app); + let metadata = has_camera_metadata(app); + let lens: Vec = PROJECTIONS.iter().map(|(id, _, _)| *id).filter(|id| lens_allowed(id)).map(str::to_owned).collect(); + let vignette_on: Vec = if vignette_supported() { lens.clone() } else { Vec::new() }; + let options = PROJECTIONS.iter().map(|(id, label, _)| ((*id).to_owned(), Label::from(crate::i18n::t(label).to_string()))).collect(); + vec![ + Param::section(tl!("Projection")), + // The remembered projection: never shown, never sent (keys under `__` are not command params). + Param::new(LAST, tl!("Projection"), ParamKind::radio(options, Some("auto".into()))).visible_when("__hidden", true), + Param::custom(PROJECTION, tl!("Projection"), |ui, fields, _| projection_row(ui, fields)).full_width(), + Param::section(tl!("Lens Correction")), + Param::new(VIGNETTE, tl!("Vignette Removal"), ParamKind::bool(false)).enabled_when_in(LAST, vignette_on), + Param::new(GEOMETRIC, tl!("Geometric Distortion"), ParamKind::bool(false)).enabled_when_in(LAST, lens), + Param::custom("__notes", Label::Empty, move |ui, fields, _| notes(ui, fields, metadata)).full_width(), + ] +} + +/// The command params of the dialog's values: the projection the row shows (the remembered one when the row never +/// drew), no lens correction under Collage or Reposition, and no `vignetteRemoval` until the engine takes it. +pub(crate) fn command_params(map: &mut Map, fields: &DialogFields) { + let id = projection(fields); + map.insert(PROJECTION.into(), Value::String(id.to_owned())); + if !lens_allowed(id) { + map.insert(GEOMETRIC.into(), Value::Bool(false)); + map.insert(VIGNETTE.into(), Value::Bool(false)); + } + if !vignette_supported() { + map.remove(VIGNETTE); + } +} + +/// Keeps the values in step with the projection: both keys hold it as text, and Collage or Reposition clears the +/// Lens Correction boxes (switching back leaves them clear). +fn settle(fields: &mut DialogFields, id: &str) { + if fields.get(PROJECTION) != Some(&FieldValue::Text(id.to_owned())) { + fields.set(PROJECTION, FieldValue::Text(id.to_owned())); + } + if fields.text(LAST) != Some(id) { + fields.set(LAST, FieldValue::Text(id.to_owned())); + } + if !lens_allowed(id) { + for key in [GEOMETRIC, VIGNETTE] { + if fields.bool(key) != Some(false) { + fields.set(key, FieldValue::Bool(false)); + } + } + } +} + +/// The six radios over three columns, each with its picture under it. A press on a picture selects nothing. +fn projection_row(ui: &mut egui::Ui, fields: &mut DialogFields) -> egui::Response { + let current = projection(fields); + settle(fields, current); + let group = RadioGroup::new(tl!("Projection").to_owned(), Bind::given(current.to_owned())).show(ui, |ui, _| { + Grid::new(COLUMNS).gap(Gap::Section).show(ui, |ui, _| { + for (id, label, _) in PROJECTIONS { + Stack::new().show(ui, |ui, _| { + Radio::new(id.to_owned()).label(crate::i18n::t(label).to_string()).show(ui); + picture(ui, id); + }); + } + }); + }); + if let Some(picked) = group.output.value().and_then(|id| known(id)) { + settle(fields, picked); + } + group.output.response.clone() +} + +/// The lines of the text block at the foot, in English: the projection `id`'s description, the metadata warning when +/// the layers carry no camera `metadata`, then the vignette warning while `vignette` is ticked. +pub fn lines(id: &str, vignette: bool, metadata: bool) -> Vec<&'static str> { + let mut out: Vec<&'static str> = PROJECTIONS.iter().filter(|(p, _, _)| *p == id).map(|(_, _, d)| *d).collect(); + if !metadata { + out.push(METADATA_WARNING); + } + if vignette { + out.push(VIGNETTE_WARNING); + } + out +} + +/// The text block at the foot ([`lines`]): the description, then the warnings, dimmer. +fn notes(ui: &mut egui::Ui, fields: &mut DialogFields, metadata: bool) -> egui::Response { + let shown = lines(projection(fields), fields.bool(VIGNETTE) == Some(true), metadata); + Stack::new() + .show(ui, |ui, _| { + for (k, line) in shown.iter().enumerate() { + let text = Text::new(crate::i18n::t(line).to_string()); + if k == 0 { + text.show(ui) + } else { + text.shade(Shade::Muted).show(ui) + }; + } + }) + .output +} + +/// The small line drawing under a projection's radio (look only; it takes no press). +fn picture(ui: &mut egui::Ui, id: &str) { + let (rect, _) = ui.allocate_exact_size(PICTURE, egui::Sense::hover()); + let t = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, t.radius_sm, t.field); + let ink = Stroke::new(1.0, t.icon); + let fill = t.accent_soft; + let c = rect.center(); + let image = Rect::from_center_size(c, vec2(22.0, 15.0)); + let poly = |points: Vec| Shape::convex_polygon(points, fill, ink); + match id { + "auto" => { + painter.rect(image, 0.0, fill, ink, egui::StrokeKind::Inside); + for (corner, out) in [ + (image.left_top(), vec2(-6.0, -5.0)), + (image.right_top(), vec2(6.0, -5.0)), + (image.left_bottom(), vec2(-6.0, 5.0)), + (image.right_bottom(), vec2(6.0, 5.0)), + ] { + painter.arrow(corner, out, ink); + } + } + "perspective" => { + painter.add(poly(vec![pos2(c.x - 26.0, c.y - 6.0), pos2(c.x - 12.0, c.y - 10.0), pos2(c.x - 12.0, c.y + 10.0), pos2(c.x - 26.0, c.y + 6.0)])); + painter.rect(Rect::from_center_size(c, vec2(22.0, 20.0)), 0.0, fill, ink, egui::StrokeKind::Inside); + painter.add(poly(vec![pos2(c.x + 12.0, c.y - 10.0), pos2(c.x + 26.0, c.y - 6.0), pos2(c.x + 26.0, c.y + 6.0), pos2(c.x + 12.0, c.y + 10.0)])); + } + "collage" => { + let turn = egui::emath::Rot2::from_angle(-0.3); + let corners = [vec2(-11.0, -7.5), vec2(11.0, -7.5), vec2(11.0, 7.5), vec2(-11.0, 7.5)]; + painter.add(poly(corners.iter().map(|v| c + turn * *v).collect())); + let (a, b) = (pos2(c.x + 10.0, c.y + 14.0), pos2(c.x + 24.0, c.y + 4.0)); + painter.arrow(a, b - a, ink); + painter.arrow(b, a - b, ink); + } + "cylindrical" => { + let mut top: Vec = + (0..=8).map(|k| k as f32 / 8.0).map(|s| pos2(c.x - 18.0 + 36.0 * s, c.y - 10.0 + 4.0 * (s - 0.5).powi(2) * 4.0 - 4.0)).collect(); + let bottom: Vec = + (0..=8).rev().map(|k| k as f32 / 8.0).map(|s| pos2(c.x - 18.0 + 36.0 * s, c.y + 10.0 - 4.0 * (s - 0.5).powi(2) * 4.0 + 4.0)).collect(); + top.extend(bottom); + painter.add(Shape::closed_line(top.clone(), ink)); + painter.add(Shape::line(vec![pos2(c.x, c.y - 14.0), pos2(c.x, c.y + 14.0)], Stroke::new(1.0, t.text_faint))); + } + "spherical" => { + // An image whose corners are pulled in: each side bows inward. + let (l, r, tp, b) = (c.x - 16.0, c.x + 16.0, c.y - 12.0, c.y + 12.0); + let side = |from: Pos2, to: Pos2, bow: egui::Vec2| -> Vec { + (0..8).map(|k| k as f32 / 8.0).map(|s| from + (to - from) * s - bow * (1.0 - (2.0 * s - 1.0).powi(2))).collect() + }; + let mut outline = side(pos2(l, tp), pos2(r, tp), vec2(0.0, -4.0)); + outline.extend(side(pos2(r, tp), pos2(r, b), vec2(4.0, 0.0))); + outline.extend(side(pos2(r, b), pos2(l, b), vec2(0.0, 4.0))); + outline.extend(side(pos2(l, b), pos2(l, tp), vec2(-4.0, 0.0))); + painter.add(Shape::closed_line(outline, ink)); + } + _ => { + // Reposition: the image with blocks around it. + painter.rect(image, 0.0, fill, ink, egui::StrokeKind::Inside); + for offset in [vec2(-20.0, -9.0), vec2(20.0, -9.0), vec2(-20.0, 9.0), vec2(20.0, 9.0)] { + painter.rect(Rect::from_center_size(c + offset, vec2(10.0, 8.0)), 0.0, Color32::TRANSPARENT, ink, egui::StrokeKind::Inside); + } + } + } +} diff --git a/crates/ui-egui/src/dialogs/caf_ui.rs b/crates/ui-egui/src/dialogs/caf_ui.rs index da0f6c0d67..8cd947511d 100644 --- a/crates/ui-egui/src/dialogs/caf_ui.rs +++ b/crates/ui-egui/src/dialogs/caf_ui.rs @@ -37,7 +37,7 @@ mod lifecycle; mod preview; pub use lifecycle::open; -pub(crate) use lifecycle::{describe, take}; +pub(crate) use lifecycle::{describe, on_job_event, recorded_from_workspace, recorded_to_workspace, take}; use preview::{Base, compute_preview, plan_params}; /// Longest side of the document proxy shown in the view (px). diff --git a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs index 36e538eec6..e2007c3d70 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs @@ -6,6 +6,7 @@ use craft::imaging::ui::fill::{FillCommand, FillEvent, FillLimits, FillOpen, Fil use craft::ui::dialog::{DialogId, dialog_id}; use craft::ui::runtime::env::Label; use photocraft_engine::edit_menu_cmds::{MAX_CAF_EDITS, MAX_CAF_POINTS}; +use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -128,11 +129,74 @@ fn report(app: &mut PhotocraftApp, e: &str) { app.ui.status_error = true; } -/// Fills with `command` (one history step); the workspace stays as it is. A refusal is reported. +/// The settings an empty recorded Content-Aware Fill step plays with (#14254). +const RECORDED_SETTINGS: [&str; 7] = ["sampling", "sampleAllLayers", "colorAdaptation", "rotationAdaptation", "scale", "mirror", "output"]; + +/// The workspace's own memory names Rotation Adaptation `rotation`; an empty recorded step reads `rotationAdaptation`. +const WORKSPACE_ROTATION: &str = "rotation"; + +/// The settings an empty recorded step plays with, from what the workspace remembers (#14254). +pub(crate) fn recorded_from_workspace(memory: Value) -> Value { + let Value::Object(mut settings) = memory else { return json!({}) }; + if let Some(rotation) = settings.remove(WORKSPACE_ROTATION) { + settings.insert("rotationAdaptation".into(), rotation); + } + settings.retain(|key, _| RECORDED_SETTINGS.contains(&key.as_str())); + Value::Object(settings) +} + +/// The settings an empty recorded step plays with, in the form the workspace remembers them. +pub(crate) fn recorded_to_workspace(settings: &mut Value) { + if let Some(settings) = settings.as_object_mut() + && let Some(rotation) = settings.remove("rotationAdaptation") + { + settings.insert(WORKSPACE_ROTATION.into(), rotation); + } +} + +/// `command`'s settings that an empty recorded step plays with. +fn recorded(command: &FillCommand) -> Option { + let Ok(Value::Object(mut settings)) = serde_json::to_value(command) else { return None }; + settings.retain(|key, _| RECORDED_SETTINGS.contains(&key.as_str())); + Some(Value::Object(settings)) +} + +/// Keeps `settings` in `prefs.dialogs` too, where an empty recorded step reads them: the workspace remembers its +/// own copy in the framework's store, which the engine can't see. +fn remember(app: &mut PhotocraftApp, settings: Value) { + app.session.prefs.edit(|p| p.dialogs.insert(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS.into(), settings)); +} + +/// The background job a command's reply says is still running. +fn pending_job(reply: &Value) -> Option { + (reply.get("pending") == Some(&Value::Bool(true))).then(|| reply.get("job").and_then(Value::as_u64).map(JobId)).flatten() +} + +/// A background fill ended: its settings are remembered only when it was applied, not when it failed or was +/// cancelled (#14254). +pub(crate) fn on_job_event(app: &mut PhotocraftApp, e: &JobEvent) { + let Some(i) = app.jobs.caf_settings.iter().position(|(job, _)| *job == e.id) else { return }; + let (_, settings) = app.jobs.caf_settings.remove(i); + if matches!(e.outcome, JobOutcome::Done(_)) { + remember(app, settings); + } +} + +/// Fills with `command` (one history step); the workspace stays as it is. A refusal is reported and keeps the +/// settings of the last fill that ran. pub(super) fn apply(app: &mut PhotocraftApp, command: &FillCommand) -> Result<(), String> { let layer = app.caf.as_ref().ok_or("Content-Aware Fill is not open")?.layer; match app.run(CMD, plan_params(command, layer)) { - Ok(_) => Ok(()), + Ok(reply) => { + if let Some(settings) = recorded(command) { + match pending_job(&reply) { + // A background fill can still fail or be cancelled: its settings wait for the job's end. + Some(job) => app.jobs.caf_settings.push((job, settings)), + None => remember(app, settings), + } + } + Ok(()) + } Err(e) => { report(app, &e); Err(e) diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 74d097e122..e2d2031ac3 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -1,6 +1,7 @@ use craft::imaging::ui::fill::FillOp; use craft::ui::canvas::PixelRect; use photocraft_doc::LayerId; +use photocraft_engine::actions_cmds::ActionsExt; use serde_json::{Value, json}; use super::preview::{compute_preview, plan_params}; @@ -251,6 +252,191 @@ fn apply_fills_and_stays_open_ok_closes_cancel_keeps_what_was_applied() { assert!(px(&app, top, 100, 80)[3] > 0.99, "the new layer holds the fill"); } +/// Apply and OK keep the settings where an empty recorded step reads them (#14254), as the workspace's own store +/// is out of the engine's reach. +#[test] +fn apply_and_ok_keep_the_settings_for_an_empty_recorded_step() { + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + assert_eq!(saved(&app), Some(json!({})), "a new profile has no settings yet"); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "high", "rotation": "medium", "mirror": true})).unwrap(); + ui(&mut app, json!({"apply": true})).unwrap(); + let after_apply = saved(&app).expect("Apply remembers the settings"); + assert_eq!(after_apply["output"], "current"); + assert_eq!(after_apply["colorAdaptation"], "high"); + assert_eq!(after_apply["rotationAdaptation"], "medium"); + assert_eq!(after_apply["mirror"], true); + let keys: Vec<&str> = after_apply.as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(keys.len(), 7, "only the seven recorded settings: {keys:?}"); + ui(&mut app, json!({"output": "duplicate"})).unwrap(); + ui(&mut app, json!({"commit": true})).unwrap(); + close_all(&mut app); + assert_eq!(saved(&app).unwrap()["output"], "duplicate", "OK remembers too"); +} + +/// A fill the engine refuses leaves the settings of the last fill that ran for an empty recorded step (#14254). +#[test] +fn a_refused_fill_keeps_the_last_remembered_settings() { + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "none", "apply": true})).unwrap(); + let remembered = saved(&app).expect("the Apply that ran remembers its settings"); + // The workspace's layer: the fill may have left another layer active. + let layer = app.caf.as_ref().unwrap().layer; + app.session.execute("layer.setProps", json!({"layer": layer.0, "locks": {"pixels": true}})).unwrap(); + let before = facts(&app)["previewRevision"].as_u64().unwrap(); + ui(&mut app, json!({"colorAdaptation": "high", "mirror": true})).unwrap(); + settle(&mut app, |d| d["previewRevision"].as_u64().unwrap() > before && d["previewError"].is_null()); + ui(&mut app, json!({"apply": true})).unwrap(); + assert!(facts(&app)["error"].as_str().is_some_and(|e| e.contains("locked")), "the engine refuses the locked layer: {}", facts(&app)); + assert_eq!(saved(&app), Some(remembered.clone()), "a refused Apply remembers nothing"); + assert!(ui(&mut app, json!({"commit": true})).is_err(), "the engine refuses OK too"); + assert_eq!(saved(&app), Some(remembered), "a refused OK remembers nothing"); +} + +/// A background fill (the desktop app) remembers its settings once its job is applied; a job that fails or is +/// cancelled leaves the last remembered ones (#14254). +#[test] +fn a_background_fill_remembers_its_settings_only_when_its_job_is_applied() { + use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome}; + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "none", "apply": true})).unwrap(); + let remembered = saved(&app).expect("the Apply that ran remembers its settings"); + app.background_jobs = true; + ui(&mut app, json!({"colorAdaptation": "high", "mirror": true})).unwrap(); + let id = app.caf.as_ref().unwrap().id; + let command = app.framework.dialogs.get_by_id::(id).unwrap().workspace().command(); + super::lifecycle::apply(&mut app, &command).unwrap(); + assert_eq!(saved(&app), Some(remembered), "nothing is remembered while the fill runs"); + assert_eq!(app.jobs.caf_settings.len(), 1, "the fill runs as a background job"); + let ctx = ctx(&app); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while app.session.has_jobs() { + assert!(std::time::Instant::now() < deadline, "the fill job did not end"); + crate::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let applied = saved(&app).expect("the applied fill remembers its settings"); + assert_eq!((&applied["colorAdaptation"], &applied["mirror"]), (&json!("high"), &json!(true))); + assert!(app.jobs.caf_settings.is_empty()); + for outcome in [JobOutcome::Failed("refused".into()), JobOutcome::Cancelled] { + let job = JobId(u64::MAX); + app.jobs.caf_settings.push((job, json!({"output": "duplicate"}))); + let event = JobEvent { id: job, command: CMD.into(), label: String::new(), document: None, outcome: outcome.clone(), error: None }; + crate::caf_ui::on_job_event(&mut app, &event); + assert_eq!(saved(&app), Some(applied.clone()), "{outcome:?} remembers nothing"); + assert!(app.jobs.caf_settings.is_empty(), "{outcome:?} ends the wait"); + } +} + +/// After a restart an empty recorded step still plays with the last fill's settings: the startup move of the dialogs' +/// memories leaves the engine's copy in the preferences (#14254). +#[test] +fn an_empty_recorded_step_plays_with_the_last_settings_after_a_restart() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "commit": true})).unwrap(); + close_all(&mut app); + let mut restarted = restart(app.session.prefs().clone()); + assert_eq!(play_empty_recorded_step(&mut restarted), 0, "Current Layer, not a new layer"); +} + +/// A profile from an earlier version, which kept the Content-Aware Fill settings only in the workspace's own memory, +/// carries them forward for an empty recorded step on its first start (#14254). +#[test] +fn an_earlier_versions_workspace_settings_carry_forward_to_an_empty_recorded_step() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "rotation": "medium"})).unwrap(); + ui(&mut app, json!({"cancel": true})).unwrap(); + close_all(&mut app); + // That version moved the engine's copy into the workspace's memory and kept none. + let mut prefs = app.session.prefs().clone(); + prefs.dialogs.remove(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS); + let mut restarted = restart(prefs); + let carried = restarted.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned().unwrap(); + assert_eq!((&carried["output"], &carried["rotationAdaptation"]), (&json!("current"), &json!("medium")), "{carried}"); + assert_eq!(play_empty_recorded_step(&mut restarted), 0, "Current Layer, as the workspace remembers"); +} + +/// Settings the workspace closed with but never filled are not carried to an empty recorded step: only a fill that ran +/// sets what it plays with (#14254). +#[test] +fn settings_closed_without_a_fill_are_not_carried_forward() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current"})).unwrap(); + ui(&mut app, json!({"cancel": true})).unwrap(); + close_all(&mut app); + let mut restarted = restart(app.session.prefs().clone()); + assert_eq!(play_empty_recorded_step(&mut restarted), 1, "New Layer: no fill has run"); +} + +/// After a confirmed Custom fill an empty recorded step stops and says why, instead of filling from another area: the +/// workspace remembers Custom but not its painted area (Custom reopens empty), so the step has none (#14254). +#[test] +fn an_empty_recorded_step_after_a_custom_fill_stops_and_says_why() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"sampling": "custom", "output": "current"})).unwrap(); + ui(&mut app, json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8}})).unwrap(); + ui(&mut app, json!({"commit": true})).unwrap(); + close_all(&mut app); + let remembered = app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned().unwrap(); + assert_eq!(remembered["sampling"], "custom", "the confirmed fill remembers Custom: {remembered}"); + let revision = app.session.active().unwrap().revision; + let result = play_empty_step(&mut app); + assert_eq!(result["ran"], 0, "{result}"); + let error = result["failed"]["error"].as_str().unwrap_or_default(); + assert!(error.contains("Custom sampling area isn't remembered"), "{result}"); + // The status bar shows the shell's translatable copy of the message, not the engine's parameter error. + crate::actions::report_play(&mut app, &result); + let status = &app.ui.status; + assert!(status.contains(photocraft_engine::atn_cmds::CAF_CUSTOM_AREA_NOT_REMEMBERED) && !status.contains("invalid parameters"), "{status}"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document is unchanged"); + assert_eq!(app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS), Some(&remembered), "playing remembers nothing"); +} + +/// A new app over the saved preferences `prefs`, moved as startup does. +fn restart(prefs: photocraft_engine::prefs::Preferences) -> Box { + let mut restarted = app_with_selection(); + restarted.session.edit_prefs(|p| *p = prefs); + restarted.framework.move_memories(&mut restarted.session); + restarted +} + +/// Plays an action of one empty recorded Content-Aware Fill step and returns how many layers it added. +fn play_empty_recorded_step(app: &mut PhotocraftApp) -> usize { + let layers = app.session.active().unwrap().doc.layers.len(); + let result = play_empty_step(app); + assert_eq!(result["ran"], 1, "{result}"); + app.session.active().unwrap().doc.layers.len() - layers +} + +/// Plays an action of one empty recorded Content-Aware Fill step and returns what `actions.play` answers. +fn play_empty_step(app: &mut PhotocraftApp) -> Value { + use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; + use craft_psd::descriptor::{Descriptor, UnicodeString}; + let item = AtnItem { + event: AtnEvent::name("cafWorkspace"), + dictionary: b"Content-Aware Fill".to_vec(), + descriptor: Some(Descriptor::new("null")), + ..Default::default() + }; + let file = AtnFile { + name: UnicodeString::new_nul("S"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item], ..Default::default() }], + ..Default::default() + }; + let imported = photocraft_engine::atn_cmds::import(&craft_psd::atn::write(&file).unwrap()).unwrap(); + app.session.actions_mut().list.push(imported.actions.into_iter().next().unwrap()).unwrap(); + app.session.execute("actions.play", json!({"action": 0})).unwrap() +} + /// 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 c = app.caf.as_ref().unwrap(); diff --git a/crates/ui-egui/src/dialogs/color_range_ui.rs b/crates/ui-egui/src/dialogs/color_range_ui.rs index a308d0a051..1611261f36 100644 --- a/crates/ui-egui/src/dialogs/color_range_ui.rs +++ b/crates/ui-egui/src/dialogs/color_range_ui.rs @@ -170,6 +170,13 @@ pub fn params(value: &ColorRangeValue) -> Value { Value::Object(p) } +/// What the canvas shows of the open Color Range dialog's Selection Preview, for the document area's version +/// (`region_versions::canvas`): the preview mode and the fields, which change with no command. +pub(crate) fn canvas_key(app: &PhotocraftApp) -> Option<(PreviewMode, String)> { + let dialog = app.framework.dialogs.get::()?; + Some((dialog.preview_mode(), params(dialog.value()).to_string())) +} + /// Cached preview: the document proxy (per revision) and the pictures drawn from it. pub struct Preview { doc: DocId, diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs index 96958d5d6a..e1df6960ad 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs @@ -87,7 +87,7 @@ fn ok_on_the_document_after_an_indexed_one_copies_into_that_document() { crate::dialogs::testing::show(&mut app); } let names: Vec<_> = app.session.documents()[2].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect(); - assert!(names.contains(&"Ink copy".to_string()), "Card receives the copy: {names:?}"); + assert!(names.contains(&"Ink".to_string()), "Card receives the copy: {names:?}"); assert_eq!(app.session.documents()[1].doc.layer_count(), palette_layers, "the Indexed document is untouched"); assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "the source is untouched"); } diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs b/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs new file mode 100644 index 0000000000..72e14c7437 --- /dev/null +++ b/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs @@ -0,0 +1,188 @@ +//! #14604: Duplicate Layer proposes the layer's own name for another document or New, and " copy" for the +//! source document; the copy keeps that name also beside a layer of the same name. A Background goes to another +//! document as a normal layer named "Background" and to New as a Background. A typed name is used as typed; an empty +//! As takes the destination's default. Dragging between documents keeps its names. + +use craft::ui::dialog::DialogId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::new_layer_ui::testing::{set, top}; + +/// "source" (active: Background, then "Top") and "target" (Background, then a layer also named "Top"). +fn app() -> Box { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 20, "height": 20, "name": "source"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.execute("file.new", json!({"width": 20, "height": 20, "name": "target"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.set_active(0); + PhotocraftApp::new(s, crate::Services::default()) +} + +fn open(app: &mut PhotocraftApp) -> DialogId { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, "layer.duplicate", json!({})).unwrap(); + crate::dialogs::testing::show(app); + top(app) +} + +/// Chooses the Document entry `value` and shows the dialog once. +fn choose(app: &mut PhotocraftApp, dialog: DialogId, value: Value) { + set(app, dialog, "document", value).unwrap(); + crate::dialogs::testing::show(app); +} + +fn proposed(app: &PhotocraftApp, dialog: DialogId) -> Value { + app.framework.dialogs.open_dialogs().into_iter().find(|d| d.id == dialog).and_then(|d| d.fields).unwrap()["name"].clone() +} + +fn doc_key(app: &PhotocraftApp, i: usize) -> Value { + json!(app.session.documents()[i].doc.id.0.to_string()) +} + +fn ok(app: &mut PhotocraftApp, dialog: DialogId) { + let ctx = app.ctx().clone(); + crate::dialogs::confirm(app, &ctx, dialog).unwrap(); + for _ in 0..2 { + crate::dialogs::testing::show(app); + } +} + +fn names(app: &PhotocraftApp, i: usize) -> Vec { + app.session.documents()[i].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect() +} + +fn count(app: &PhotocraftApp, i: usize, name: &str) -> usize { + names(app, i).iter().filter(|n| *n == name).count() +} + +#[test] +fn the_document_choice_rewrites_the_proposed_name() { + let mut app = app(); + let dialog = open(&mut app); + assert_eq!(proposed(&app, dialog), json!("Top copy")); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + assert_eq!(proposed(&app, dialog), json!("Top"), "another document: the plain name"); + choose(&mut app, dialog, json!("new")); + assert_eq!(proposed(&app, dialog), json!("Top"), "New: the plain name"); + let source = doc_key(&app, 0); + choose(&mut app, dialog, source); + assert_eq!(proposed(&app, dialog), json!("Top copy"), "the source again: the copy name"); +} + +#[test] +fn the_plain_name_lands_beside_a_layer_of_the_same_name_and_in_a_new_document() { + let mut app = app(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Top"), 2, "{:?}", names(&app, 1)); + assert_eq!(count(&app, 1, "Top copy"), 0); + app.session.set_active(0); + let dialog = open(&mut app); + choose(&mut app, dialog, json!("new")); + ok(&mut app, dialog); + let new = app.session.documents().len() - 1; + assert_eq!(names(&app, new), vec!["Top".to_string()]); +} + +#[test] +fn a_background_arrives_as_background_in_another_document_and_in_new() { + let mut app = app(); + let bg = app.session.active().unwrap().doc.background().unwrap().id; + app.session.select_layer(bg).unwrap(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + ok(&mut app, dialog); + let target = &app.session.documents()[1].doc; + let copy = target.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.name == "Background").find(|l| !target.is_background(l.id)); + assert!(copy.is_some(), "a normal layer named Background: {:?}", names(&app, 1)); + app.session.set_active(0); + app.session.select_layer(bg).unwrap(); + let dialog = open(&mut app); + choose(&mut app, dialog, json!("new")); + ok(&mut app, dialog); + let new = &app.session.documents().last().unwrap().doc; + assert!(new.background().is_some_and(|l| l.name == "Background"), "{:?}", names(&app, app.session.documents().len() - 1)); +} + +#[test] +fn a_typed_name_is_used_and_an_empty_one_takes_the_default() { + let mut app = app(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target.clone()); + set(&mut app, dialog, "name", json!("Typed copy")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Typed copy"), 1); + app.session.set_active(0); + let dialog = open(&mut app); + choose(&mut app, dialog, target); + set(&mut app, dialog, "name", json!("")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Top"), 2, "empty As into another document: the plain name"); + app.session.set_active(0); + let dialog = open(&mut app); + set(&mut app, dialog, "name", json!("")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 0, "Top copy"), 1, "empty As in the source: the copy name"); +} + +#[test] +fn dragging_between_documents_keeps_its_names() { + let mut app = app(); + let bg = app.session.active().unwrap().doc.background().unwrap().id; + let before = names(&app, 1).len(); + app.run("layer.copyToDocument", json!({"source": 0, "document": 1, "layers": [bg.0]})).unwrap(); + let after = names(&app, 1); + assert_eq!(after.len(), before + 1); + assert!(!after.iter().any(|n| n == "Background copy")); + assert_eq!(after.iter().filter(|n| *n == "Background").count(), 1, "a dragged Background is renamed as today: {after:?}"); +} + +#[test] +fn an_empty_name_for_a_background_into_another_document_is_background() { + let mut app = app(); + let bg = app.session.active().unwrap().doc.background().unwrap().id; + app.session.select_layer(bg).unwrap(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + set(&mut app, dialog, "name", json!("")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Background"), 2, "the target's own Background and the copy: {:?}", names(&app, 1)); +} + +/// A name the user typed survives a change of destination; only an untouched proposal is rewritten (CodeRabbit on #16090). +#[test] +fn a_typed_name_survives_a_change_of_destination() { + let mut app = app(); + let dialog = open(&mut app); + set(&mut app, dialog, "name", json!("Shadow")).unwrap(); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + assert_eq!(proposed(&app, dialog), json!("Shadow"), "another document"); + choose(&mut app, dialog, json!("new")); + assert_eq!(proposed(&app, dialog), json!("Shadow"), "New"); + let source = doc_key(&app, 0); + choose(&mut app, dialog, source); + assert_eq!(proposed(&app, dialog), json!("Shadow"), "the source again"); +} + +/// A group is outside the new proposal policy: its " copy" stays whatever the destination (CodeRabbit on #16090). +#[test] +fn a_groups_proposal_does_not_change_with_the_destination() { + let mut app = app(); + app.run("layer.new.group", json!({"name": "Folder"})).unwrap(); + let dialog = open(&mut app); + assert_eq!(proposed(&app, dialog), json!("Folder copy")); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + assert_eq!(proposed(&app, dialog), json!("Folder copy"), "another document"); + choose(&mut app, dialog, json!("new")); + assert_eq!(proposed(&app, dialog), json!("Folder copy"), "New"); +} diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs index dd47475180..83a8b34d83 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs @@ -3,7 +3,7 @@ //! the New Layer button still duplicate at once. use craft::ui::contract::Bind; use craft::ui::dialog::DialogId; -use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; @@ -63,7 +63,27 @@ pub fn open(app: &mut PhotocraftApp) -> Result { }; let mut options: Vec<(String, Label)> = destinations(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect(); options.push(("new".to_string(), Label::from(tl!("New")))); + // Another document or New proposes the layer's own name; the source document, " copy" again (#14604). + // A group's naming is not measured and stays as it was (CodeRabbit on #16090). + let names = name.clone().filter(|_| !layer.is_group()).map(|copy| (copy, layer.name.clone())); + let shown_for = std::sync::Mutex::new(source.to_string()); + // The proposal the As: field currently holds: only an untouched one is replaced when the destination changes. + let proposal = std::sync::Mutex::new(name.clone().unwrap_or_default()); Ok(params::open_param(app, KEY, DialogFields::new(), captured, move |fields: &mut DialogFields| { + if let Some((copy, plain)) = &names { + let chosen = fields.text("document").map(str::to_owned); + let mut shown = shown_for.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(chosen) = chosen.filter(|chosen| *chosen != *shown) { + let proposed = if chosen == source.to_string() { copy } else { plain }; + let mut last = proposal.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // A name the user typed is theirs: keep it across destination changes (CodeRabbit on #16090). + if fields.text("name").is_none_or(|now| now.is_empty() || now == *last) { + fields.set("name", FieldValue::Text(proposed.clone())); + *last = proposed.clone(); + } + *shown = chosen; + } + } let mut rows = Vec::new(); if let Some(name) = &name { rows.push(Param::new("name", tl!("As:"), ParamKind::text(name.clone()))); @@ -110,10 +130,21 @@ pub(crate) fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, result: ParamRe fn duplicate(app: &mut PhotocraftApp, fields: &DialogFields) -> Result { let index = app.session.active_index().ok_or("The document is closed")?; let mut params = serde_json::Map::new(); - if let Some(name) = fields.text("name") { - params.insert("name".into(), json!(name)); + let destination = destination(app, fields)?; + match fields.text("name") { + Some(name) if !name.is_empty() => { + params.insert("name".into(), json!(name)); + } + // An empty As: another document or New takes the layer's own name, as the dialog proposes for them (#14604). + // A group keeps its previous behaviour (CodeRabbit on #16090). + Some(_) if !matches!(destination, Destination::Document(d) if d == index) => { + if let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).filter(|l| !l.is_group()) { + params.insert("name".into(), json!(layer.name)); + } + } + _ => {} } - match destination(app, fields)? { + match destination { Destination::New => { if let Some(doc_name) = fields.text("documentName").filter(|n| !n.is_empty()) { params.insert("documentName".into(), json!(doc_name)); @@ -193,7 +224,7 @@ mod tests { set(&mut app, dialog, "document", pick).unwrap(); confirm(&mut app, &ctx, dialog).unwrap(); assert_eq!(app.session.documents()[0].doc.layer_count(), 2); - assert!(names(&app, 1).contains(&"Ink copy".to_string())); + assert!(names(&app, 1).contains(&"Ink".to_string())); } #[test] @@ -208,7 +239,7 @@ mod tests { assert_eq!(app.session.active_index(), Some(1)); assert_eq!(app.session.documents()[1].doc.name, "Card"); assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "the source is untouched"); - assert!(names(&app, 1).contains(&"Ink copy".to_string())); + assert!(names(&app, 1).contains(&"Ink".to_string())); } #[test] @@ -259,7 +290,7 @@ mod tests { let docs = app.session.documents(); let spare = docs.iter().position(|d| d.doc.name == "Spare").unwrap(); let spare_names: Vec<_> = docs[spare].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect(); - assert!(spare_names.contains(&"Ink copy".to_string()), "{change}: Spare receives the copy: {spare_names:?}"); + assert!(spare_names.contains(&"Ink".to_string()), "{change}: Spare receives the copy: {spare_names:?}"); if let Some(card) = docs.iter().position(|d| d.doc.name == "Card") { assert_eq!(docs[card].doc.layer_count(), 1, "{change}: Card is untouched"); } diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 21708fc01d..422df7844c 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -318,6 +318,12 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< let kind = if command == "layer.layerStyle.globalLight" { ParamKind::angle_in(min, max, default, 0) } else { ParamKind::angle(default) }; p = Param::new(p.key, p.label, kind); } + // Artboard from Layers' Width and Height take 4 to 32000 px; a value typed outside is + // clamped when the field is left (#14577). + if command == "layer.new.artboardFromLayers" && matches!(p.key.as_str(), "width" | "height") { + use photocraft_engine::artboard_cmds::{FROM_LAYERS_MAX, FROM_LAYERS_MIN}; + p = Param::new(p.key, p.label, ParamKind::int(Some(FROM_LAYERS_MIN), Some(FROM_LAYERS_MAX), 0)); + } if command == SCALE_EFFECTS && p.key == "scale" { return scale_effects_row(p); } @@ -374,6 +380,10 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< if command == super::rotate_canvas_ui::COMMAND { list = super::rotate_canvas_ui::params(); } + // Auto-Align Layers: the Projection and Lens Correction groups and the text block (#14196). + if command == super::auto_align_ui::COMMAND { + list = super::auto_align_ui::params(app); + } rows::custom_rows(app, command, &mut list); if command == color_settings_presets::COMMAND { // The Settings menu: Custom, a greyed group label and the named setups in groups (#14229). @@ -458,12 +468,13 @@ fn command_defaults(app: &PhotocraftApp, command: &str, params: &[Param]) -> Map map.insert("name".into(), json!(photocraft_engine::pattern_cmds::default_name(&app.session))); } // The reference application's Artboard from Layers opens at the next Artboard N and the - // selected layers' size every time, never a remembered size; past the field's 30000 px + // selected layers' size every time, never a remembered size; past the field's 32000 px // range, 0 keeps the bounds. if command == "layer.new.artboardFromLayers" && let Some((name, [w, h])) = photocraft_engine::artboard_cmds::from_layers_defaults(&app.session) { - let fits = w <= 30_000 && h <= 30_000; + let max = photocraft_engine::artboard_cmds::FROM_LAYERS_MAX; + let fits = w <= max && h <= max; map.insert("name".into(), json!(name)); map.insert("width".into(), json!(if fits { w } else { 0 })); map.insert("height".into(), json!(if fits { h } else { 0 })); @@ -576,8 +587,8 @@ fn builder( .reset_to(reset.clone()) .layout(ParamLayout::Stacked) .previews(preview) - // Alt keeps Rotate Canvas's Cancel a Cancel, as in the reference application (#14462). - .alt_resets(key != super::rotate_canvas_ui::COMMAND) + // Alt keeps Rotate Canvas's and Auto-Align's Cancel a Cancel, as in the reference application (#14462, #14196). + .alt_resets(key != super::rotate_canvas_ui::COMMAND && key != super::auto_align_ui::COMMAND) .alert_title(tl!("PhotoCraft")); if let Some(canvas) = canvas { dialog = dialog.canvas(canvas); @@ -734,6 +745,9 @@ pub(crate) fn command_params(command: &str, fields: &DialogFields) -> Value { if command == super::rotate_canvas_ui::COMMAND { super::rotate_canvas_ui::command_params(&mut map); } + if command == super::auto_align_ui::COMMAND { + super::auto_align_ui::command_params(&mut map, fields); + } // After dialog keys have been reshaped into command keys (Image Processor's jpeg/width // becomes jpeg.width, and so on). Doing this earlier dropped those rows. // Drop display-only and other keys a closed schema does not take (Bitmap's Input row is @@ -1419,6 +1433,8 @@ pub struct FilterPreviewKey { pub scratch: u64, } +#[cfg(test)] +mod artboard_from_layers_size_range_tests; #[cfg(test)] mod global_light_angle_range_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/filter_dialog/artboard_from_layers_size_range_tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/artboard_from_layers_size_range_tests.rs new file mode 100644 index 0000000000..8987d8f92d --- /dev/null +++ b/crates/ui-egui/src/dialogs/filter_dialog/artboard_from_layers_size_range_tests.rs @@ -0,0 +1,93 @@ +//! #14577: Artboard from Layers' Width and Height take 4 to 32000 px. A value typed outside is +//! clamped when the field is left (Tab): 99999 becomes 32000, 1 becomes 4. + +use craft::ui::patterns::form_dialogs::HostedParamDialog; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::{PhotocraftApp, Services}; + +const CMD: &str = "layer.new.artboardFromLayers"; + +/// A 100 x 80 document whose new layer holds 20 x 30 px of red, with the dialog open over it. +fn dialog() -> (Harness<'static, Box>, craft::ui::dialog::DialogId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 5, "width": 20, "height": 30})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let id = super::open(&mut app, CMD).unwrap(); + let mut h = Harness::builder() + .with_context(app.ctx().clone()) + .with_size(egui::vec2(1200.0, 900.0)) + .build_ui_state(|ui, app: &mut Box| crate::dialogs::run(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::AppTheme::pro()); + h.run_steps(4); + (h, id) +} + +fn int(h: &Harness<'static, Box>, id: craft::ui::dialog::DialogId, key: &str) -> Option { + h.state().framework.dialogs.get_by_id::(id).and_then(|d| d.fields().int(key)) +} + +/// The open alerts' messages. +fn alerts(h: &Harness<'static, Box>) -> Vec { + h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_string)).collect() +} + +/// Types `text` into the number field labelled `name` and leaves it with Tab. +fn type_and_tab(h: &mut Harness<'static, Box>, name: &str, text: &str) { + h.query_all_by_role(Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref().is_some_and(|l| l.trim_end_matches(':') == name)) + .unwrap_or_else(|| panic!("the {name} field")) + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +#[test] +fn width_and_height_clamp_to_4_to_32000_when_the_field_is_left() { + // (field, key, typed, kept) + for (name, key, typed, kept) in [("Width", "width", "99999", 32_000), ("Height", "height", "1", 4), ("Width", "width", "640", 640)] { + let (mut h, id) = dialog(); + assert_eq!((int(&h, id, "width"), int(&h, id, "height")), (Some(20), Some(30)), "opens at the layers' size"); + type_and_tab(&mut h, name, typed); + assert_eq!(int(&h, id, key), Some(kept), "{name} {typed}"); + // The framework's range alert says the closest value was kept; OK on it keeps the value. + if typed.parse::().ok() != Some(kept) { + let shown = alerts(&h); + assert!(shown.iter().any(|m| m.starts_with("An integer between 4 and ") && m.contains("Closest value inserted")), "{name} {typed}: {shown:?}"); + } + } +} + +/// A union of 30000 to 32000 px fits the field now, so the dialog opens at it. +#[test] +fn a_union_up_to_32000_px_opens_at_its_size() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 31_000, "height": 8})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let id = super::open(&mut app, CMD).unwrap(); + let f = app.framework.dialogs.get_by_id::(id).unwrap().fields().clone(); + assert_eq!((f.int("width"), f.int("height")), (Some(31_000), Some(8))); +} + +#[test] +fn a_union_wider_than_32000_px_still_opens_at_0_to_keep_the_bounds() { + // Not measured in the reference: today's 0 x 0 ("keep the layers' bounds") stays, now past 32000 px. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 33_000, "height": 8})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let id = super::open(&mut app, CMD).unwrap(); + let f = app.framework.dialogs.get_by_id::(id).unwrap().fields().clone(); + assert_eq!((f.int("width"), f.int("height")), (Some(0), Some(0))); +} diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 5a0da87adb..4de9473444 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -29,6 +29,7 @@ use craft::ui::primitives::ContentPainterCx; use craft::ui::primitives::FacePaint; use craft::ui::primitives::textures::TextureCache; use craft::ui::runtime::env::Env; +use craft::ui::runtime::memory::{SaveKey, run_value, set_run_value}; use egui::{ColorImage, Pos2, Rect, pos2}; use photocraft_doc::effects::{FxPaint, GlowSource, GlowTechnique, StrokePosition}; use photocraft_doc::{Document, Effect, Layer, LayerId}; @@ -50,6 +51,8 @@ mod gradient_field; #[cfg(test)] mod gradient_method_tests; #[cfg(test)] +mod outer_glow_last_values_tests; +#[cfg(test)] mod pattern_overlay_picker_tests; /// The Styles preset gallery page id. @@ -204,6 +207,11 @@ fn values_of(e: &Effect, light: f32) -> Value { if let Some(source) = interpolation { set(&mut v, "method", json!(source.method)); set(&mut v, "smoothness", json!(source.smoothness)); + } else { + // No recorded method (a baked PSD curve): the factory Smooth (#14900) must not + // rebuild it on an unchanged OK, so the page shows its stops as they are. + set(&mut v, "method", json!("custom")); + drop_keys(&mut v, &["smoothness"]); } let (stops, opacity) = gradient_field::stops_to_json(&gradient_field::stops_of_doc(stops, &g.opacity_stops)); set(&mut v, gradient_field::KEY, stops); @@ -494,6 +502,11 @@ pub fn open(app: &mut PhotocraftApp, select: Option<&str>) -> Option { let keys = blend_keys(); let mut specs = specs(&keys, &user, light); start_from_last_committed(app, &mut specs, light); + if let Some(spec) = specs.iter_mut().find(|spec| spec.kind == EffectKind::OuterGlow) + && let Some(values) = run_value::>(app.ctx(), &OUTER_GLOW_SESSION) + { + spec.defaults = style_params(spec.kind, &values, None).over(&spec.defaults); + } let mut draft = LayerStyleDraft::new(draft_of(&layer, light, mode)); match select { None => { @@ -584,7 +597,29 @@ fn keep_last_committed(app: &PhotocraftApp, style: &LayerStyle) { } } +/// The starting values of a new Outer Glow live only in this app session (#14945). +const OUTER_GLOW_SESSION: SaveKey = SaveKey::new("photocraft.layerStyle.outerGlow.session"); + +/// Remember the last enabled glow added or edited by this confirmation, in the units shown by +/// the page. The original snapshot distinguishes an edit from an unchanged layer effect. +fn keep_outer_glow(app: &PhotocraftApp, layer: LayerId, style: &LayerStyle) { + let Some(layer) = app.session.active().and_then(|state| state.doc.layer(layer)) else { return }; + let light = style.global_light; + let last = style.effects.iter().zip(&layer.effects.items).rev().find_map(|(draft, applied)| { + if draft.kind != EffectKind::OuterGlow || !applied.enabled() { + return None; + } + let values = values_of(applied, light); + let original = fx_of(&draft.params).and_then(|fx| serde_json::from_value::(fx).ok()); + original.is_none_or(|original| !original.enabled() || values_of(&original, light) != values).then_some(values) + }); + if let Some(values) = last { + set_run_value(app.ctx(), &OUTER_GLOW_SESSION, Some(values)); + } +} + /// The effect pages with the user's defaults (Make Default) over the factory ones. +/// Outer Glow starts at factory values after a restart; Reset still uses the saved default. fn specs(keys: &HashMap, user: &Map, light: f32) -> Vec { KINDS .iter() @@ -601,7 +636,8 @@ fn specs(keys: &HashMap, user: &Map, light: f32) spec.fields.insert(after + 1, field); } } - spec.defaults = style_params(kind, &fresh_params(key, light, user.get(*key)), None).over(&spec.defaults); + let saved = if kind == EffectKind::OuterGlow { None } else { user.get(*key) }; + spec.defaults = style_params(kind, &fresh_params(key, light, saved), None).over(&spec.defaults); Some(spec) }) .collect() @@ -978,8 +1014,12 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) { LayerStyleAsk::NewStyle => save_new_style(app, id, layer), LayerStyleAsk::MakeDefault(kind, params) => { // The stored defaults reach new instances from the next open and, through `set_defaults`, the open dialog. - match app.run("layer.layerStyle.makeDefault", json!({"kind": kind.key(), "params": style_params_json(¶ms)})) { + let values = style_params_json(¶ms); + match app.run("layer.layerStyle.makeDefault", json!({"kind": kind.key(), "params": values})) { Ok(_) => { + if kind == EffectKind::OuterGlow { + set_run_value(app.ctx(), &OUTER_GLOW_SESSION, Some(values)); + } if let Some(dialog) = app.framework.dialogs.get_mut_by_id::(id) { dialog.set_defaults(kind, params); } @@ -1006,6 +1046,7 @@ fn finish(app: &mut PhotocraftApp, doc: photocraft_doc::DocId, layer: LayerId, s return fail(app, error); } keep_last_committed(app, style); + keep_outer_glow(app, layer, style); } /// Applies a style preset to the draft without touching the document: Cancel leaves the document @@ -1056,6 +1097,10 @@ fn reset_to_default(app: &mut PhotocraftApp, dialog: DialogId, instance: EffectI }; let Ok(v) = app.run("layer.layerStyle.defaultFor", json!({"kind": kind.key()})) else { return }; let mut values = v["params"].clone(); + if kind == EffectKind::OuterGlow { + // A partial saved default should clear every field seeded from the last OK. + values = with_defaults(kind.key(), &values); + } drop_from_to(&mut values); if values.get("useGlobalLight").and_then(Value::as_bool) == Some(true) && let Some(o) = values.as_object_mut() diff --git a/crates/ui-egui/src/dialogs/layer_style/outer_glow_last_values_tests.rs b/crates/ui-egui/src/dialogs/layer_style/outer_glow_last_values_tests.rs new file mode 100644 index 0000000000..c57d6c5e8d --- /dev/null +++ b/crates/ui-egui/src/dialogs/layer_style/outer_glow_last_values_tests.rs @@ -0,0 +1,170 @@ +//! #14945: a new Outer Glow uses the last settings confirmed in Layer Style for this app session. + +use craft::imaging::layer_style::{EffectKind, StyleValue}; +use craft::theme::Srgba; +use egui_kittest::kittest::Queryable as _; +use photocraft_engine::prefs::SavedPrefsExt; +use serde_json::{Value, json}; + +use super::tests::{app_with_layer, cancel, draft, edit, first_of, harness}; +use super::{DialogId, style_params_json}; +use crate::PhotocraftApp; + +const COMMAND: &str = "layer.layerStyle.outerGlow"; + +fn open_glow(app: &mut PhotocraftApp) -> DialogId { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, COMMAND, json!({})).unwrap(); + app.layer_style_target.unwrap().0 +} + +fn values(app: &PhotocraftApp, id: DialogId) -> Value { + let glow = first_of(app, id, EffectKind::OuterGlow); + style_params_json(&draft(app, id).style.effect(glow).unwrap().params) +} + +fn set_glow(app: &mut PhotocraftApp, id: DialogId, opacity: f64) { + let glow = first_of(app, id, EffectKind::OuterGlow); + edit(app, id, |draft| { + draft.set_param(glow, "blend", StyleValue::Text("Normal".into())); + draft.set_param(glow, "color", StyleValue::Color(Srgba::from_rgb_array([0.0; 3]))); + draft.set_param(glow, "opacity", StyleValue::Number(opacity)); + draft.set_param(glow, "size", StyleValue::Number(10.0)); + }); +} + +fn confirm(app: &mut PhotocraftApp, id: DialogId) { + crate::dialogs::testing::confirm(app, id).unwrap(); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +fn other_document(app: &mut PhotocraftApp) { + app.run("file.new", json!({"width": 40, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); +} + +fn remember_glow(app: &mut PhotocraftApp) -> Value { + let id = open_glow(app); + set_glow(app, id, 100.0); + let remembered = values(app, id); + confirm(app, id); + other_document(app); + remembered +} + +#[test] +fn a_new_outer_glow_reuses_the_confirmed_values_on_another_document() { + let mut app = app_with_layer(32); + let remembered = remember_glow(&mut app); + let id = open_glow(&mut app); + assert_eq!(values(&app, id), remembered); + confirm(&mut app, id); + let id = open_glow(&mut app); + assert_eq!(values(&app, id), remembered, "the seeded glow applies to the layer"); +} + +#[test] +fn cancelled_edits_and_an_unchanged_scripted_glow_leave_the_last_ok_alone() { + let mut app = app_with_layer(32); + let remembered = remember_glow(&mut app); + let pending = open_glow(&mut app); + set_glow(&mut app, pending, 40.0); + cancel(&mut app, pending); + + app.run(COMMAND, json!({"blend": "Screen", "color": "#0000ff", "size": 21, "opacity": 60})).unwrap(); + let scripted = open_glow(&mut app); + assert_eq!(values(&app, scripted)["color"], "#0000ff", "the existing layer effect supplies its own values"); + confirm(&mut app, scripted); + + other_document(&mut app); + let next = open_glow(&mut app); + assert_eq!(values(&app, next), remembered); +} + +#[test] +fn editing_an_existing_outer_glow_updates_the_next_new_glow() { + let mut app = app_with_layer(32); + remember_glow(&mut app); + app.run(COMMAND, json!({"size": 21})).unwrap(); + let id = open_glow(&mut app); + set_glow(&mut app, id, 50.0); + let edited = values(&app, id); + confirm(&mut app, id); + other_document(&mut app); + let next = open_glow(&mut app); + assert_eq!(values(&app, next), edited); +} + +#[test] +fn reset_uses_factory_or_user_defaults_and_a_fresh_app_starts_at_factory() { + let mut app = app_with_layer(32); + let initial = open_glow(&mut app); + let factory = values(&app, initial); + cancel(&mut app, initial); + remember_glow(&mut app); + let id = open_glow(&mut app); + let mut h = harness(app); + h.get_by_label("Reset to Default").click(); + h.run_steps(3); + assert_eq!(values(h.state(), id), factory); + + let saved_default = json!({"kind": "outerGlow", "params": {"opacity": 18.0}}); + h.state_mut().run("layer.layerStyle.makeDefault", saved_default).unwrap(); + // Reset must replace every remembered field, even when the saved default is partial. + cancel(h.state_mut(), id); + let id = open_glow(h.state_mut()); + h.run_steps(3); + h.get_by_label("Reset to Default").click(); + h.run_steps(3); + let mut user = factory.clone(); + user["opacity"] = json!(18.0); + assert_eq!(values(h.state(), id), user); + + // A fresh app opens at factory values even with an existing Make Default entry. + let saved = h.state().session.prefs_to_json(); + let mut restarted = app_with_layer(32); + restarted.session.load_prefs_json(&saved).unwrap(); + let id = open_glow(&mut restarted); + assert_eq!(values(&restarted, id), factory); + let mut h = harness(restarted); + h.get_by_label("Reset to Default").click(); + h.run_steps(3); + assert_eq!(values(h.state(), id), user); +} + +#[test] +fn make_default_in_the_current_session_seeds_new_glows() { + let mut app = app_with_layer(32); + remember_glow(&mut app); + let id = open_glow(&mut app); + set_glow(&mut app, id, 60.0); + let user = values(&app, id); + let mut h = harness(app); + h.get_by_label("Make Default").click(); + h.run_steps(3); + cancel(h.state_mut(), id); + let next = open_glow(h.state_mut()); + assert_eq!(values(h.state(), next), user); +} + +#[test] +fn disabled_or_refused_glows_do_not_replace_the_last_ok() { + let mut app = app_with_layer(32); + let remembered = remember_glow(&mut app); + let disabled = open_glow(&mut app); + set_glow(&mut app, disabled, 70.0); + let glow = first_of(&app, disabled, EffectKind::OuterGlow); + edit(&mut app, disabled, |draft| draft.toggle(glow)); + confirm(&mut app, disabled); + + other_document(&mut app); + let refused = open_glow(&mut app); + set_glow(&mut app, refused, 80.0); + let glow = first_of(&app, refused, EffectKind::OuterGlow); + edit(&mut app, refused, |draft| draft.set_param(glow, "fx", StyleValue::Other("{}".into()))); + crate::dialogs::testing::confirm(&mut app, refused).unwrap(); + assert!(app.ui.status_error); + + let next = open_glow(&mut app); + assert_eq!(values(&app, next), remembered); +} diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 1bb022d47d..d5173f383b 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -70,6 +70,8 @@ pub struct MemoryPrompt { pub id: u64, pub name: String, pub path: Option, + /// Original read source when an untitled open has no save/recent path. + pub error_source: Option, pub slot: Option, pub order: Option, pub estimated: u64, @@ -406,6 +408,7 @@ pub fn arrive_memory( id: u64, name: String, path: Option, + error_source: Option, slot: Option, order: Option, estimated: u64, @@ -413,7 +416,18 @@ pub fn arrive_memory( capacity_unknown: bool, uncertain_capacity_warning: bool, ) { - app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning }); + app.held_memory_prompts.push_back(MemoryPrompt { + id, + name, + path, + error_source, + slot, + order, + estimated, + available, + capacity_unknown, + uncertain_capacity_warning, + }); app.prompt_order.push_back(PromptKind::Memory); advance_memory(app); } @@ -480,6 +494,7 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result Result { if accept { if let Some(job) = r.get("job").and_then(Value::as_u64) { - app.jobs.opens.push(crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(job), name: name.clone(), path, slot, order }); + app.jobs.opens.push(crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(job), + name: name.clone(), + path, + error_source: error_source.clone(), + slot, + order, + }); app.jobs.focus = Some(photocraft_engine::jobs::JobId(job)); app.ui.chrome.home = None; app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", &name)]); app.ui.status_error = false; } else if let Some(result) = r.get("result") { - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(0), name: name.clone(), path: path.clone(), slot, order }; + let tab = crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(0), + name: name.clone(), + path: path.clone(), + error_source: error_source.clone(), + slot, + order, + }; if let Err(e) = crate::jobs_ui::finish_open_tab(app, &tab, result) { app.ui.status = e; app.ui.status_error = true; @@ -511,8 +540,13 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result { - app.ui.status = err.clone(); - app.ui.status_error = true; + let source = path.as_deref().or(error_source.as_deref()).unwrap_or(&name); + // A template may have reserved an Untitled name; presentation names its read source, + // while the returned error keeps the approval command's original wrapper. + let prefix = format!("{name}: "); + let error = err.strip_prefix(&prefix).unwrap_or(&err); + let reason = if name != crate::file_open::display_name(source) { error.strip_prefix(&prefix).unwrap_or(error) } else { error }; + app.open_failed(source, reason); crate::jobs_ui::end_batch(app); advance(app); crate::jobs_ui::end_batch(app); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index dec11d58b4..715f308bf9 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -148,9 +148,12 @@ fn the_one_time_move_stores_owned_dialog_values_once_and_leaves_engine_read_keys assert_eq!(table("photocraft.edit.fill").unwrap().get("mode"), Some(&toml::Value::String(photocraft_color::BlendMode::ColorBurn.key().to_string()))); let mut left: Vec<&str> = prefs.dialogs.keys().map(String::as_str).collect(); left.sort_unstable(); - let mut kept = vec!["file.print", "ui.layersPanelOptions", "file.export.saveForWebLegacy", live_shape_prompt::PREF]; + // The Content-Aware Fill entry an empty recorded step reads is given to every profile, empty here (#14254). + let mut kept = + vec!["file.print", "ui.layersPanelOptions", "file.export.saveForWebLegacy", live_shape_prompt::PREF, photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS]; kept.sort_unstable(); assert_eq!(left, kept, "only the kept entries stay in the preferences"); + assert_eq!(prefs.dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS), Some(&json!({}))); // A second run finds nothing to move: a value changed since is not overwritten. Remembered::::new("photocraft.filter.gaussianBlur").store(&host, &toml::Table::new()); @@ -158,6 +161,26 @@ fn the_one_time_move_stores_owned_dialog_values_once_and_leaves_engine_read_keys assert_eq!(table("photocraft.filter.gaussianBlur"), Some(toml::Table::new())); } +/// The Content-Aware Fill settings an empty recorded step reads stay in the preferences; the workspace's own memory +/// gets them only while it has none (#14254). +#[test] +fn the_move_keeps_the_content_aware_fill_settings_and_never_replaces_the_workspaces() { + let host = Host::builder(AppInfo { id: "photocraft", name: "PhotoCraft", version: "0" }).settings(Arc::new(MemorySections::default())).build(); + let key = photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS; + let workspace = Remembered::::new(params::memory_scope(key)); + let output = |table: Option| table.and_then(|t| t.get("output").cloned()); + let mut prefs = photocraft_engine::prefs::Preferences::default(); + prefs.dialogs.insert(key.into(), json!({"output": "current"})); + move_memories(&mut prefs, &host); + assert_eq!(prefs.dialogs.get(key), Some(&json!({"output": "current"})), "the engine's copy stays"); + assert_eq!(output(workspace.recall(&host)), Some(toml::Value::String("current".into())), "an empty workspace memory gets it"); + + prefs.dialogs.insert(key.into(), json!({"output": "new"})); + move_memories(&mut prefs, &host); + assert_eq!(output(workspace.recall(&host)), Some(toml::Value::String("current".into())), "the workspace's own memory wins"); + assert_eq!(prefs.dialogs.get(key), Some(&json!({"output": "new"}))); +} + struct MarkA; struct MarkB; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 11bdb80991..6030e04d50 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -23,7 +23,7 @@ pub fn persist(app: &mut PhotocraftApp) { } let now = snapshot(app); if app.session.prefs().panel_layout != now { - app.session.prefs.edit(|prefs| prefs.panel_layout = now); + app.session.prefs.remember(|prefs| prefs.panel_layout = now); } } diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index 4fe5c16ae2..40f69e60c4 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -379,7 +379,7 @@ impl PhotocraftApp { for (seq, path) in paths.iter().enumerate() { let order = crate::jobs_ui::OpenOrder { batch, seq }; if let Err(e) = crate::jobs_ui::start_open_as_smart_object(app, path, Some(order)) { - app.open_failed(&crate::file_open::display_name(path), &e); + app.open_failed(path, &e); } } crate::jobs_ui::end_batch(app); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 84b63dbf2f..c40cb777e5 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -3,9 +3,10 @@ //! and the OS's "open these documents" requests (macOS Finder double-click, Open With, drops on the //! Dock icon) all go through [`PhotocraftApp::open_file`], so each one names the document after the //! file, remembers its path (File › Save writes back to it) and adds it to Open Recent. Failures -//! are shown as errors (status bar + notice); import warnings as a notice. +//! are shown as modal alerts and in the status bar; import warnings as a notice. use crate::{PhotocraftApp, notices}; +use craft::ui::dialog::{Alert, DialogId, DialogResult, DialogStack, HostedAlert, StackDialog}; use craft::ui::runtime::drag::OsFile; use craft::ui::runtime::windows::{WindowAction, WindowHost}; use photocraft_doc::DocId; @@ -206,6 +207,64 @@ pub fn display_name(path: &str) -> String { std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| path.to_string()) } +// Named PSD/PSB/templates deliberately keep the PSD parser's errors for direct callers. Only +// its missing file-header signature means unrecognized content; damaged internal signatures +// (8BIM, etc.) and a recognized 8BPS file's other parse errors must retain their reasons. +fn unrecognized_open_reason(reason: &str) -> bool { + if reason == "codec: unrecognized image format" { + return true; + } + let Some(signature) = reason.strip_prefix("PSD: invalid signature [").and_then(|s| s.strip_suffix("], expected 8BPS")) else { + return false; + }; + let mut values = signature.split(", "); + let mut found = [0u8; 4]; + for byte in &mut found { + let Some(text) = values.next() else { return false }; + let Ok(value) = text.parse::() else { return false }; + if text != value.to_string() { + return false; + } + *byte = value; + } + values.next().is_none() && &found != b"8BPS" +} + +/// One failed file, rendered by the shared alert. Distinct instances keep a multi-file open's +/// errors separate; a plain HostedAlert has one fixed identity and would replace the earlier file. +struct OpenFailureAlert { + id: DialogId, + alert: HostedAlert, +} + +impl StackDialog for OpenFailureAlert { + type Result = (); + + fn id(&self) -> DialogId { + self.id + } + fn instance(&self) -> Option { + Some(self.id) + } + fn key(&self) -> Option<&str> { + self.alert.key() + } + fn json_fields(&self) -> Option { + self.alert.json_fields() + } + fn confirm(&mut self, ctx: &egui::Context) -> Option<()> { + self.alert.confirm(ctx) + } + fn show(&mut self, ui: &mut egui::Ui, stack: &DialogStack) -> Option> { + ui.push_id(self.id, |ui| self.alert.show(ui, stack)).inner + } +} + +/// Acknowledgements contain no command; drain every completed occurrence without reopening it. +pub(crate) fn take_open_alerts(app: &mut PhotocraftApp, _ctx: &egui::Context) { + while app.framework.dialogs.take_keyed::().is_some() {} +} + impl PhotocraftApp { /// Open `bytes` read from the file at `path`: the document is named after the file, keeps /// `path` for File › Save unless it is a derivative preview, and `path` goes to the top of Open Recent. Returns the import @@ -337,7 +396,7 @@ impl PhotocraftApp { // prompt that is answered later all place the file at its place in the set. match self.open_path_placed(abs, None, Some(order)) { Ok(_) => opened += 1, - Err(e) => self.open_failed(&display_name(abs), &e), + Err(e) => self.open_failed(abs, &e), } } crate::jobs_ui::end_batch(self); @@ -371,12 +430,31 @@ impl PhotocraftApp { true } - /// Show "Couldn't open : " as an error (status bar + notice). - pub fn open_failed(&mut self, name: &str, err: &str) { - self.failed({ + /// Report one failed open in an OK alert, naming its source file once. Pass the source path + /// when available so its exact prefix can be removed from filesystem read errors too. + pub fn open_failed(&mut self, source: &str, err: &str) { + let name = display_name(source); + let source_prefix = format!("{source}: "); + let name_prefix = format!("{name}: "); + // The native background importer wraps its path-prefixed read error in the file name. + let wrapped_source_prefix = format!("{name}: {source}: "); + let reason = (source != name) + .then(|| err.strip_prefix(&wrapped_source_prefix)) + .flatten() + .or_else(|| err.strip_prefix(&source_prefix)) + .or_else(|| err.strip_prefix(&name_prefix)) + .unwrap_or(err); + let msg = if unrecognized_open_reason(reason) { + crate::i18n::fmt(tl!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file."), &[("name", &name)]) + } else { let template = "Couldn't open {name}: {error}"; - crate::i18n::fmt(tl!(template), &[("name", name), ("error", err)]) - }); + crate::i18n::fmt(tl!(template), &[("name", &name), ("error", reason)]) + }; + log::warn!("{msg}"); + self.ui.status = msg.clone(); + self.ui.status_error = true; + let id = crate::jobs_ui::open_failure_id(self); + self.framework.dialogs.open(OpenFailureAlert { id, alert: HostedAlert::new(Alert::new("PhotoCraft", msg)) }); } /// Show "Couldn't place : " as an error (status bar + notice). @@ -417,11 +495,13 @@ impl PhotocraftApp { } for f in files { let name = dropped_name(&f); + let source = f.path.as_deref().filter(|path| path.is_absolute()).map(|path| path.to_string_lossy().into_owned()).unwrap_or_else(|| name.clone()); let route = to.route(&name); + if let Some(why) = f.path.as_deref().and_then(folder_error) { match route { DropRoute::Place => self.failed(crate::i18n::fmt(tl!("Couldn't place {name}: {error}"), &[("name", &name), ("error", &why)])), - DropRoute::Open => self.open_failed(&name, &why), + DropRoute::Open => self.open_failed(&source, &why), } continue; } @@ -434,7 +514,7 @@ impl PhotocraftApp { match self.open_dropped_file(&f, &name, slot) { Ok(true) => slot = slot.map(|s| s + 1), Ok(false) => {} - Err(e) => self.open_failed(&name, &e), + Err(e) => self.open_failed(&source, &e), } } } @@ -804,3 +884,6 @@ mod dialog_order_tests; mod place_multiple_files_tests; #[cfg(test)] mod tests; + +#[cfg(test)] +mod unreadable_alert_tests; diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 974dfff68e..aa14793201 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -186,7 +186,7 @@ fn the_web_opens_every_selected_file() { // Each good file is its own tab; the broken one is reported without stopping the rest. let names: Vec<_> = app.session.documents().iter().map(|st| st.doc.name.as_str()).collect(); assert_eq!(names, ["one.png", "two.jpg"]); - assert!(app.ui.notices.iter().any(|n| n.tone == craft::theme::variant::Tone::Bad && n.title.contains("broken.png")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|message| message.contains("broken.png")), "{:?}", app.ui.notices); } /// #5749: the web shell reads dropped files itself, so it asks where they landed: image files @@ -417,7 +417,7 @@ fn open_failures_are_errors_and_leave_no_document() { assert!(app.ui.recent_files.is_empty()); assert!(app.ui.status_error); assert!(app.ui.status.starts_with("Couldn't open broken.psd"), "{}", app.ui.status); - assert!(app.ui.notices.last().is_some_and(|n| n.tone == craft::theme::variant::Tone::Bad)); + assert_eq!(open_error_messages(&app).len(), 1); let _ = std::fs::remove_dir_all(&dir); } @@ -430,8 +430,9 @@ fn a_picked_file_that_cannot_be_read_is_reported_like_any_open_failure() { answer(&mut app); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - let notice = app.ui.notices.last().unwrap(); - assert!(notice.tone == craft::theme::variant::Tone::Bad && notice.title.starts_with("Couldn't open big.psb: "), "{}", notice.title); + let messages = open_error_messages(&app); + assert_eq!(messages.len(), 1); + assert!(messages[0].starts_with("Couldn't open big.psb: "), "{}", messages[0]); // Commands that read a picked file (scripts, notes, Place) fail with the file's name. app.ui.status_error = false; app.pick_file_bytes(|_, _, _| Err("read".into())).unwrap(); @@ -452,7 +453,8 @@ fn open_paths_reports_each_failure_without_panicking() { assert_eq!(n, 0); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - assert_eq!(app.ui.notices.len(), 4, "one notice per failure"); + assert_eq!(open_error_messages(&app).len(), 4, "one modal alert per failure"); + assert!(app.ui.notices.is_empty()); // Bad control params error instead of panicking. let ctx = egui::Context::default(); assert!(menus::invoke(&mut app, &ctx, "file.open", json!({ "path": "" })).is_err()); @@ -557,7 +559,9 @@ fn dropped_files_open_with_path_and_recent() { assert_eq!(app.session.documents()[1].path, None); assert_eq!(*app.ui.recent_files, vec![abs_s]); assert!(app.ui.status_error); - assert_eq!(app.ui.notices.iter().filter(|n| n.tone == craft::theme::variant::Tone::Bad).count(), 2); + assert_eq!(open_error_messages(&app), ["Couldn't open gone.psd: couldn't read the file", "Couldn't open dropped: not an image"]); + assert!(app.ui.notices.is_empty(), "open failures use modal alerts, not corner notices"); + assert_eq!(app.ui.status, "Couldn't open dropped: not an image"); let _ = std::fs::remove_dir_all(&dir); } @@ -1397,7 +1401,14 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { let (mut app, _) = app_with(Vec::new()); app.open_bytes("existing.psd", b"x").unwrap(); let batch = jobs_ui::begin_batch(&mut app); - let tab = |seq: usize| OpenTab { job: JobId(100 + seq as u64), name: format!("f{seq}.psd"), path: None, slot: None, order: Some(OpenOrder { batch, seq }) }; + let tab = |seq: usize| OpenTab { + job: JobId(100 + seq as u64), + name: format!("f{seq}.psd"), + path: None, + error_source: None, + slot: None, + order: Some(OpenOrder { batch, seq }), + }; app.jobs.opens.extend((0..4).map(tab)); // f1 opened at once (a preset file, say, or background jobs off for it). app.jobs.opens.remove(1); @@ -1419,11 +1430,11 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { assert_eq!(app.ui.views.len(), 5, "views follow their documents"); assert!(app.jobs.batches.is_empty(), "forgotten once every member opened"); // A tab with a slot (dropped on the tabs) keeps it; one from a forgotten set goes to the end. - let dropped = OpenTab { job: JobId(200), name: "dropped.psd".into(), path: None, slot: Some(0), order: None }; + let dropped = OpenTab { job: JobId(200), name: "dropped.psd".into(), path: None, error_source: None, slot: Some(0), order: None }; let index = app.session.add_document(Document::new("dropped.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); let id = app.session.documents()[index].doc.id; jobs_ui::finish_open_tab(&mut app, &dropped, &json!({"document": index, "docId": id.0})).unwrap(); - let late = OpenTab { job: JobId(201), name: "late.psd".into(), path: None, slot: None, order: Some(OpenOrder { batch: 999, seq: 0 }) }; + let late = OpenTab { job: JobId(201), name: "late.psd".into(), path: None, error_source: None, slot: None, order: Some(OpenOrder { batch: 999, seq: 0 }) }; let index = app.session.add_document(Document::new("late.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); let id = app.session.documents()[index].doc.id; jobs_ui::finish_open_tab(&mut app, &late, &json!({"document": index, "docId": id.0})).unwrap(); @@ -1691,7 +1702,17 @@ fn scratch(tag: &str) -> std::path::PathBuf { } fn error_titles(app: &PhotocraftApp) -> Vec { - app.ui.notices.iter().filter(|n| n.tone == craft::theme::variant::Tone::Bad).map(|n| n.title.clone()).collect() + app.ui.notices.iter().filter(|n| n.tone == craft::theme::variant::Tone::Bad).map(|n| n.title.clone()).chain(open_error_messages(app)).collect() +} + +fn open_error_messages(app: &PhotocraftApp) -> Vec { + app.framework + .dialogs + .open_dialogs() + .into_iter() + .filter(|d| d.key.as_deref() == Some("alert")) + .filter_map(|d| d.fields.and_then(|f| f.get("message").and_then(serde_json::Value::as_str).map(str::to_owned))) + .collect() } /// The Home screen (no document open) is where a first drop lands: every file opens as its own @@ -1717,6 +1738,7 @@ fn files_dropped_with_no_document_open_all_open() { assert_eq!(doc_names(&app), names); assert!(app.drop_places.is_empty()); assert!(error_titles(&app).is_empty(), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).is_empty(), "{:?}", app.framework.dialogs.open_dialogs()); let _ = std::fs::remove_dir_all(&dir); } @@ -1799,7 +1821,7 @@ fn several_files_dropped_on_the_canvas_are_queued_in_order() { }) .collect(); assert_eq!(queued, ["one.png", "two.jpg"]); - assert!(error_titles(&app).iter().any(|t| t.starts_with("Couldn't open set.abr: ")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|t| t.starts_with("Couldn't open set.abr: ")), "{:?}", app.framework.dialogs.open_dialogs()); } #[test] @@ -1836,9 +1858,11 @@ fn open_as_smart_object_dialog_opens_one_document_per_selected_file() { assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!( - app.ui.notices.iter().any(|n| n.tone == craft::theme::variant::Tone::Bad && n.title.starts_with("Couldn't open bad.png")), - "the unreadable file is reported" + assert_eq!( + open_error_messages(&app), + ["Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."], + "the unreadable file has one exact modal alert; status: {}", + app.ui.status ); let _ = std::fs::remove_dir_all(&dir); } @@ -1861,9 +1885,11 @@ fn open_as_smart_object_opens_in_the_background_in_name_order() { tick_until(&mut app, &ctx, |app| app.jobs.opens.is_empty()); assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!( - app.ui.notices.iter().any(|n| n.tone == craft::theme::variant::Tone::Bad && n.title.starts_with("Couldn't open bad.png")), - "the unreadable file is reported" + assert_eq!( + open_error_messages(&app), + ["Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."], + "the unreadable file has one exact modal alert; status: {}", + app.ui.status ); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs new file mode 100644 index 0000000000..41580d6888 --- /dev/null +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -0,0 +1,581 @@ +//! #14059: unreadable File > Open inputs use one modal alert per file, while callers that +//! request an error result still receive it. + +use super::*; +use crate::control::{ControlRequest, Reply, handle}; +use crate::{Services, menus}; +use craft::host::{Picked, ScriptedFiles}; +use craft::ui::dialog::{DialogId, OpenDialog}; +use craft::ui::runtime::drag::OsFile; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use std::sync::Arc; + +fn app_with(answer: Option) -> Box { + let services = Services { + files: Some(Arc::new(ScriptedFiles::answering(vec![answer.unwrap_or(Picked::Cancelled)]))), + import: Some(Box::new(|name, bytes, opts| { + photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| format!("{name}: {e}")) + })), + ..Default::default() + }; + PhotocraftApp::new(photocraft_engine::Session::new(), services) +} + +fn pick(app: &mut PhotocraftApp) { + let ctx = app.ctx().clone(); + menus::invoke(app, &ctx, "file.open", json!({})).unwrap(); + app.poll_file_dialog(); +} + +fn error_dialogs(app: &PhotocraftApp) -> Vec { + app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).collect() +} + +fn messages(app: &PhotocraftApp) -> Vec { + error_dialogs(app).into_iter().map(|d| d.fields.unwrap()["message"].as_str().unwrap().to_owned()).collect() +} + +fn no_dialogs(app: &PhotocraftApp) -> bool { + app.framework.dialogs.open_dialogs().is_empty() +} + +fn memory_id(app: &PhotocraftApp) -> DialogId { + crate::dialogs::alerts::prompt_tagged::(app).unwrap() +} + +fn expected(name: &str) -> String { + format!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file.") +} + +fn png() -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 2, "height": 2, "background": "white"})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "valid.png", &Default::default()).unwrap().bytes +} + +#[test] +fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_documents() { + for (name, bytes) in [ + ("notes.txt", b"ordinary text".to_vec()), + ("broken.png", b"ordinary text".to_vec()), + ("zz-bad.png", (1..=17).collect()), + ("unknown.psd", b"ordinary text".to_vec()), + ("unknown.psb", b"ordinary text".to_vec()), + ("unknown.psdt", b"ordinary text".to_vec()), + ] { + let mut app = app_with(Some(Picked::Contents(vec![(name.into(), bytes)]))); + pick(&mut app); + let wanted = expected(name); + assert_eq!(messages(&app), [wanted.as_str()]); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.ui.notices.is_empty(), "the modal replaces the corner notice"); + assert!(app.ui.status_error); + assert_eq!(app.ui.status, wanted); + assert_eq!(app.ui.status.matches(name).count(), 1); + } + // Interactive foreground errors now retain the source name instead of a generated Untitled-N. + let mut interactive = app_with(None); + assert_eq!( + interactive.open_bytes("unknown.psdt", b"ordinary text").unwrap_err(), + "unknown.psdt: PSD: invalid signature [111, 114, 100, 105], expected 8BPS" + ); + assert!(no_dialogs(&interactive), "the caller owns presentation of a returned error"); + + #[cfg(not(target_arch = "wasm32"))] + { + let mut app = app_with(Some(Picked::Contents(vec![("unknown.psdt".into(), b"ordinary text".to_vec())]))); + app.background_jobs = true; + pick(&mut app); + assert_eq!(app.jobs.opens.len(), 1); + let tab = &app.jobs.opens[0]; + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("unknown.psdt")); + let worker_error = format!("{}: codec: unrecognized image format", tab.name); + finish_read_failure(&mut app, "unknown.psdt", "codec: unrecognized image format", &worker_error); + assert!(app.ui.recent_files.is_empty()); + } +} + +#[test] +fn an_open_failure_alert_has_one_ok_button_and_closes_when_clicked() { + let mut app = app_with(None); + app.open_failed("notes.txt", "notes.txt: codec: unrecognized image format"); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 600.0)) + .with_context(app.ctx().clone()) + .build_ui_state(|ui, app| crate::dialogs::run(app, ui), app); + h.run_steps(3); + assert!(h.query_by_label(&expected("notes.txt")).is_some()); + assert!(h.query_by_label("Cancel").is_none()); + h.get_by_label("OK").click(); + h.run_steps(3); + assert!(no_dialogs(h.state())); + assert!(h.state().session.documents().is_empty()); +} + +#[test] +fn other_read_errors_keep_their_reason_and_only_exact_leading_source_prefixes_are_removed() { + let source = std::path::Path::new("pictures").join("missing.png").to_string_lossy().into_owned(); + for (err, reason) in [ + (format!("{source}: file not found"), "file not found"), + ("missing.png: permission denied".into(), "permission denied"), + (format!("missing.png: {source}: file not found"), "file not found"), + ("missing.png: elsewhere/missing.png: keep this reason".into(), "elsewhere/missing.png: keep this reason"), + ("the directory is missing.png: keep this reason".into(), "the directory is missing.png: keep this reason"), + ] { + let mut app = app_with(None); + app.open_failed(&source, &err); + assert_eq!(messages(&app), [format!("Couldn't open missing.png: {reason}")]); + assert!(app.ui.notices.is_empty()); + } +} + +#[test] +fn several_failed_files_each_get_one_alert_and_valid_files_still_open() { + let files = vec![("a.txt".into(), b"text".to_vec()), ("b.png".into(), png()), ("c.png".into(), b"text".to_vec()), ("d.png".into(), png())]; + let mut app = app_with(Some(Picked::Contents(files))); + pick(&mut app); + assert_eq!(messages(&app), [expected("a.txt"), expected("c.png")]); + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["b.png", "d.png"]); + assert!(app.ui.notices.iter().all(|n| n.tone != craft::theme::variant::Tone::Bad)); + let app_ctx = app.ctx().clone(); + let first = error_dialogs(&app)[0].id; + crate::dialogs::confirm(&mut app, &app_ctx, first).unwrap(); + assert_eq!(messages(&app), [expected("c.png")]); + let second = error_dialogs(&app)[0].id; + assert_ne!(first, second, "each failed file has its own instance"); + let (request, _rx) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": second.value()})); + let Reply::Done(reply) = handle(&mut app, &app_ctx, &request) else { panic!("alert confirmation is immediate") }; + assert_eq!(reply["ok"], true); + app_ctx.run_ui(Default::default(), |ui| crate::dialogs::run(&mut app, ui)).textures_delta.clear(); + assert!(messages(&app).is_empty()); + assert_eq!(app.session.documents().len(), 2); + assert!(app.framework.dialogs.take_keyed::().is_none(), "the consumer drains both instance-bound acknowledgements"); + + // The per-file consumer owns only its wrapper, even though a plain alert also answers (). + let plain = app.framework.dialogs.open(HostedAlert::new(Alert::new("PhotoCraft", "unrelated alert"))); + assert!(app.framework.dialogs.confirm_by_id(&app_ctx, plain)); + take_open_alerts(&mut app, &app_ctx); + assert!(matches!(app.framework.dialogs.take::(), Some(DialogResult::Ok(())))); + assert!(app.framework.dialogs.take_keyed::().is_none()); +} + +#[test] +fn background_open_failures_are_reported_once_when_the_jobs_finish() { + let mut app = app_with(None); + app.background_jobs = true; + app.open_bytes("first.txt", b"text").unwrap(); + app.open_bytes("second.png", b"text").unwrap(); + app.open_bytes("valid.png", &png()).unwrap(); + let ctx = app.ctx().clone(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !app.jobs.opens.is_empty() { + assert!(std::time::Instant::now() < deadline, "open jobs did not finish"); + crate::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let mut actual = messages(&app); + actual.sort(); + let mut wanted = vec![expected("first.txt"), expected("second.png")]; + wanted.sort(); + assert_eq!(actual, wanted); + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["valid.png"]); + crate::jobs_ui::tick(&mut app, &ctx); + assert_eq!(messages(&app).len(), 2, "a consumed failure event cannot show twice"); + assert!(app.ui.notices.iter().all(|n| n.tone != craft::theme::variant::Tone::Bad)); +} + +#[test] +fn cancelling_file_open_does_not_show_an_error() { + let mut app = app_with(None); + pick(&mut app); + assert!(!app.file_dialog_open()); + assert!(app.session.documents().is_empty()); + assert!(no_dialogs(&app)); + assert!(app.ui.notices.is_empty()); + assert!(!app.ui.status_error); +} + +#[test] +fn automation_and_control_open_still_return_the_original_error() { + // app.open reserves the template's untitled name before its separate automation decode. + for (name, expected_error, expected_control_error) in [ + ("notes.txt", "notes.txt: codec: unrecognized image format", "notes.txt: codec: unrecognized image format"), + ("unknown.psdt", "unknown.psdt: PSD: invalid signature [116, 101, 120, 116], expected 8BPS", "Untitled-1: codec: unrecognized image format"), + ] { + let mut app = app_with(None); + let err = app.open_automation_bytes(name, b"text").unwrap_err(); + assert_eq!(err, expected_error); + assert!(no_dialogs(&app)); + let read_name = name.to_string(); + app.services.automation_read = + Some(Box::new(move |_| Ok(crate::AutomationReadResult { name: read_name.clone(), bytes: b"text".to_vec(), save_path: None }))); + let (request, _rx) = ControlRequest::new("app.open", json!({"path": name})); + let Reply::Done(reply) = handle(&mut app, &egui::Context::default(), &request) else { panic!("open should return immediately") }; + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], expected_control_error); + assert!(app.session.documents().is_empty()); + assert!(no_dialogs(&app)); + assert!(app.ui.notices.is_empty()); + } +} + +/// This path must remain absent: both the foreground and worker open really fail to read it. +#[cfg(not(target_arch = "wasm32"))] +fn missing_source(tag: &str, name: &str) -> (std::path::PathBuf, String, String) { + let path = std::env::temp_dir().join(format!("photocraft-unreadable-{tag}-{}", std::process::id())).join(name); + assert!(!path.exists()); + let reason = photocraft_format::read_file(&path).unwrap_err().to_string(); + let source = path.to_string_lossy().into_owned(); + (path, source, reason) +} + +/// A native path plus tempting valid bytes: choosing bytes instead of reading the path would +/// open a document and fail the original missing-file and raw-error assertions below. +#[cfg(not(target_arch = "wasm32"))] +fn unreadable_native_drop(path: std::path::PathBuf) -> OsFile { + let mut file = OsFile::default(); + file.name = display_name(&path.to_string_lossy()); + file.path = Some(path); + file.bytes = Some(png().into()); + file +} + +/// Apply actual worker events and check the unmodified error sent to a waiting control client. +#[cfg(not(target_arch = "wasm32"))] +fn finish_read_failure(app: &mut PhotocraftApp, source: &str, reason: &str, worker_error: &str) { + let job = app.jobs.opens.first().map(|tab| tab.job); + let reply = job.map(|job| { + let (request, reply) = ControlRequest::new("engine.execute", json!({})); + let channel = app.control.get_or_insert_with(|| craft::automation::ControlChannel::new(std::sync::mpsc::channel().1)); + channel.settle(request, Reply::AfterJob(job.0), None, 0.0); + reply + }); + let ctx = app.ctx().clone(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !app.jobs.opens.is_empty() { + assert!(std::time::Instant::now() < deadline, "open job did not finish"); + crate::jobs_ui::tick(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + if let Some(reply) = reply { + assert_eq!(reply.try_recv().unwrap(), json!({"ok": false, "error": worker_error})); + } + let name = display_name(source); + let wanted = if reason == "codec: unrecognized image format" { expected(&name) } else { format!("Couldn't open {name}: {reason}") }; + assert_eq!(messages(app), [wanted]); + assert_eq!(app.ui.status, messages(app)[0]); + assert_eq!(app.ui.status.matches(name.as_str()).count(), 1); + assert!(app.session.documents().is_empty()); + assert!(app.ui.notices.is_empty()); + crate::jobs_ui::tick(app, &ctx); + assert_eq!(messages(app).len(), 1, "the finished event is consumed once"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_drop_read_failures_name_the_source_once_in_foreground_and_background() { + for name in ["missing.psd", "missing.psdt"] { + let (path, source, reason) = missing_source("drop", name); + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + app.open_dropped(&egui::Context::default(), vec![unreadable_native_drop(path.clone())], crate::file_open::DropTo::Window); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + let worker_name = app.jobs.opens.first().map(|tab| tab.name.as_str()).unwrap_or(name); + if background { + assert_eq!(worker_name, if name == "missing.psdt" { "Untitled-1" } else { name }); + } + let worker_error = format!("{worker_name}: {source}: {reason}"); + finish_read_failure(&mut app, &source, &reason, &worker_error); + assert!(app.ui.recent_files.is_empty()); + } + } + + // The public path-plus-bytes API retains the source while the actual template worker is untitled. + let (_, source, _) = missing_source("template-codec", "unknown.psdt"); + let mut app = app_with(None); + app.background_jobs = true; + app.open_file(&source, b"ordinary text").unwrap(); + assert_eq!(app.jobs.opens.len(), 1); + let tab = &app.jobs.opens[0]; + assert_eq!(tab.name, "Untitled-1"); + assert_eq!(tab.path.as_deref(), Some(source.as_str())); + let worker_error = format!("{}: codec: unrecognized image format", tab.name); + finish_read_failure(&mut app, &source, "codec: unrecognized image format", &worker_error); + assert!(app.ui.recent_files.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn recent_grid_and_list_read_failures_keep_the_reason_without_repeating_the_path() { + let (path, source, reason) = missing_source("recent", "missing.psd"); + for grid in [false, true] { + let mut app = app_with(None); + app.background_jobs = false; + app.ui.chrome.home_recent_view = if grid { craft::ui::shell::RecentView::Grid } else { craft::ui::shell::RecentView::List }; + app.push_recent(&source); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).with_context(app.ctx().clone()).build_ui_state( + |ui, app: &mut Box| { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + h.run_steps(3); + let label = if grid { "missing.psd".to_owned() } else { format!("missing.psd, {}", path.parent().unwrap().display()) }; + h.get_by_role_and_label(egui::accesskit::Role::ListItem, &label).click(); + h.run_steps(3); + finish_read_failure(h.state_mut(), &source, &reason, "no worker in this foreground control"); + assert_eq!(h.state().ui.recent_files.as_slice(), std::slice::from_ref(&source)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn os_open_read_failures_keep_the_existing_full_source_route() { + let (_, source, reason) = missing_source("os", "missing.psd"); + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + let mut events = vec![OsEvent::Open(vec![source.clone()])]; + app.services.os_events = Some(Box::new(move || std::mem::take(&mut events))); + app.drain_os_events(&egui::Context::default()); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + let worker_error = format!("{}: {source}: {reason}", display_name(&source)); + finish_read_failure(&mut app, &source, &reason, &worker_error); + assert!(app.ui.recent_files.is_empty()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn smart_object_open_read_failures_retain_the_read_source_without_a_save_or_recent_path() { + let (_, source, reason) = missing_source("smart-object", "missing.psd"); + for background in [false, true] { + let mut app = app_with(Some(Picked::Paths(vec![source.clone().into()]))); + app.background_jobs = background; + app.open_dialog_as_smart_object().unwrap(); + app.poll_file_dialog(); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + assert!(app.jobs.opens.iter().all(|tab| tab.path.is_none()), "a Smart Object remains untitled"); + assert!(app.jobs.opens.iter().all(|tab| tab.error_source.as_deref() == Some(source.as_str()))); + finish_read_failure(&mut app, &source, &reason, &format!("{source}: {reason}")); + assert!(app.ui.recent_files.is_empty()); + } +} + +#[test] +fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { + // The file signature is recognized: a bad version is a PSD error, not a codec miss. + let bytes = b"8BPS\0\0".to_vec(); + let mut app = app_with(Some(Picked::Contents(vec![("corrupt.psdt".into(), bytes.clone())]))); + pick(&mut app); + assert_eq!(messages(&app), ["Couldn't open corrupt.psdt: PSD: unsupported file version 0"]); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.ui.notices.is_empty()); + let mut direct = app_with(None); + // The typed PSD path returns its raw IO error without adding a source-name prefix. + assert_eq!(direct.open_bytes("corrupt.psdt", &bytes).unwrap_err(), "PSD: unsupported file version 0"); + assert!(no_dialogs(&direct)); + + // A damaged internal block or an unrelated/malformed diagnostic retains its reason. + for reason in [ + "PSD: invalid signature [0, 0, 0, 0], expected 8BIM (layer blend mode)", + "PSD: invalid signature [56, 66, 80, 83], expected 8BPS", + "PSD: invalid signature [0, 0, 0], expected 8BPS", + "PSD: invalid signature [256, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [+1, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [00, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [0, 0, 0, 0], expected 8BPS; keep this detail", + "embedded PSD: invalid signature [0, 0, 0, 0], expected 8BPS", + ] { + let mut app = app_with(None); + app.open_failed("corrupt.psdt", reason); + assert_eq!(messages(&app), [format!("Couldn't open corrupt.psdt: {reason}")]); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn template_psd_for_memory_prompt() -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 4, "height": 3, "background": "white"})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "small.psd", &Default::default()).unwrap().bytes +} + +#[cfg(not(target_arch = "wasm32"))] +fn memory_dialog_reply(app: &mut PhotocraftApp, dialog: DialogId, accept: bool) -> serde_json::Value { + let method = if accept { "ui.dialog.confirm" } else { "ui.dialog.cancel" }; + let (request, _rx) = ControlRequest::new(method, json!({"dialog": dialog.value()})); + let ctx = app.ctx().clone(); + let Reply::Done(reply) = handle(app, &ctx, &request) else { panic!("memory prompt reply is immediate") }; + ctx.run_ui(Default::default(), |ui| crate::dialogs::run(app, ui)).textures_delta.clear(); + reply +} + +#[cfg(not(target_arch = "wasm32"))] +fn finish_successful_template_jobs(app: &mut PhotocraftApp) { + let jobs: Vec<_> = app.jobs.opens.iter().map(|tab| tab.job).collect(); + for job in jobs { + app.session.wait_job(job).unwrap(); + } + crate::jobs_ui::tick(app, &egui::Context::default()); +} + +/// A real picked byte template reaches preflight through both immediate and worker completion. +/// Its original source is metadata only: approval still opens Untitled-1 without a save path. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn byte_template_memory_prompt_keeps_the_source_through_real_open_approve_and_cancel() { + if cfg!(target_pointer_width = "32") { + return; // The scoped 3 GiB estimate charge exceeds the 32-bit product cap. + } + let gb = 1u64 << 30; + let psd = template_psd_for_memory_prompt(); + let memory = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + for background in [false, true] { + for accept in [false, true] { + let mut app = app_with(Some(Picked::Contents(vec![("card.psdt".into(), psd.clone())]))); + app.background_jobs = background; + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(memory, || { + pick(&mut app); + assert_eq!(app.jobs.opens.len(), usize::from(background)); + if background { + finish_successful_template_jobs(&mut app); + } + assert!(app.session.documents().is_empty()); + assert_eq!(app.held_memory_prompts.len(), 1, "use the real high-memory preflight"); + let prompt = &app.held_memory_prompts[0]; + assert_eq!(prompt.name, "Untitled-1"); + assert!(prompt.path.is_none()); + assert_eq!(prompt.error_source.as_deref(), Some("card.psdt")); + assert!(prompt.estimated > 3 * gb); + let preflight = prompt.id; + let dialog = memory_id(&app); + assert!(crate::dialogs::alerts::prompt_tag::(&app).is_some()); + let reply = memory_dialog_reply(&mut app, dialog, accept); + assert_eq!(reply["ok"], true, "{reply}"); + if background && accept { + let tab = app.jobs.opens.first().unwrap(); + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("card.psdt")); + finish_successful_template_jobs(&mut app); + } + assert_eq!(app.session.documents().len(), usize::from(accept)); + if accept { + let opened = &app.session.documents()[0]; + assert_eq!(opened.doc.name, "Untitled-1"); + assert!(opened.path.is_none(), "error source is never a save destination"); + } + assert!(app.ui.recent_files.is_empty(), "byte input does not acquire a Recent path"); + assert!(no_dialogs(&app)); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.jobs.batches.is_empty()); + assert!(app.session.take_pending_preflight(preflight).is_none()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0); + assert!(!app.ui.status_error); + }); + }); + } + } +} + +/// A stored byte preflight with a valid identity but invalid PSD version drives the real +/// approval decoder, so both the immediate error and the later worker failure keep raw replies. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn byte_template_memory_approval_decode_failures_name_the_source_and_keep_raw_replies() { + let header = vec![ + b'8', b'B', b'P', b'S', 0, 0, // unsupported version + 0, 0, 0, 0, 0, 0, // reserved + 0, 3, // channels + 0, 0, 0, 1, // height + 0, 0, 0, 1, // width + 0, 8, // depth + 0, 3, // RGB + ]; + // The typed UI confirmation is an acknowledgement. The underlying approval result keeps + // its original raw wrapper, checked independently through the same real stored preflight. + { + let mut direct = app_with(None); + direct.background_jobs = false; + let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.clone())); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let id = direct + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "Untitled-1".into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + crate::open_prompt::arrive_memory(&mut direct, id, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false); + let error = crate::open_prompt::answer_memory(&mut direct, true).unwrap_err(); + assert_eq!(error, "Untitled-1: Untitled-1: PSD: unsupported file version 0", "preserve the approval's original wrapper"); + } + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.clone())); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let preflight = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "Untitled-1".into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + crate::open_prompt::arrive_memory(&mut app, preflight, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false); + let dialog = memory_id(&app); + let reply = memory_dialog_reply(&mut app, dialog, true); + let reason = "PSD: unsupported file version 0"; + if background { + assert_eq!(reply["ok"], true, "the actual approval starts a worker: {reply}"); + let tab = app.jobs.opens.first().unwrap(); + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("card.psdt")); + finish_read_failure(&mut app, "card.psdt", reason, &format!("Untitled-1: {reason}")); + } else { + assert_eq!(reply["ok"], true, "typed confirmation acknowledges its receipt; the approval error is presented by the real prompt consumer: {reply}"); + assert_eq!(messages(&app), [format!("Couldn't open card.psdt: {reason}")]); + } + assert_eq!(app.ui.status, format!("Couldn't open card.psdt: {reason}")); + assert_eq!(app.ui.status.matches("card.psdt").count(), 1); + assert!(!app.ui.status.contains("Untitled-1")); + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0); + assert!(app.session.take_pending_preflight(preflight).is_none()); + let alert = error_dialogs(&app)[0].id; + let ctx = app.ctx().clone(); + crate::dialogs::confirm(&mut app, &ctx, alert).unwrap(); + assert!(no_dialogs(&app), "the one error alert closes normally"); + } +} diff --git a/crates/ui-egui/src/filter_preview_locator_tests.rs b/crates/ui-egui/src/filter_preview_locator_tests.rs index 983f9545ea..39da50f6b8 100644 --- a/crates/ui-egui/src/filter_preview_locator_tests.rs +++ b/crates/ui-egui/src/filter_preview_locator_tests.rs @@ -31,7 +31,7 @@ fn harness(command: Option<&str>, rotation: f32) -> Harness<'static, Box; 10] = [ + Some(PaintMode::Blend(BlendMode::Normal)), + Some(PaintMode::HealingReplace), + None, + Some(PaintMode::Blend(BlendMode::Multiply)), + Some(PaintMode::Blend(BlendMode::Screen)), + Some(PaintMode::Blend(BlendMode::Darken)), + Some(PaintMode::Blend(BlendMode::Lighten)), + None, + Some(PaintMode::Blend(BlendMode::Color)), + Some(PaintMode::Blend(BlendMode::Luminosity)), +]; + +#[test] +fn both_healing_mode_lists_show_replace_and_the_two_separators() { + assert_eq!(items(Tool::Healing), MENU_ROWS, "the Shift+right-click menu rows"); + assert_eq!( + labels(Tool::Healing), + ["Normal", "Replace", "Multiply", "Screen", "Darken", "Lighten", "Color", "Luminosity"], + "the labels, separators left out" + ); + let entries = mode_entries(Tool::Healing, true, false); + let values: Vec> = entries.iter().map(|e| e.value().cloned()).collect(); + assert_eq!(values, BAR_ROWS, "the options bar dropdown"); + // Another tool's list is untouched by this: the Clone Stamp keeps the layer modes. + assert!(!mode_entries(Tool::CloneStamp, true, false).iter().any(|e| e.value() == Some(&PaintMode::HealingReplace)), "no Replace on the Clone Stamp"); + assert!(items(Tool::CloneStamp).iter().all(|i| *i != Item::HealingReplace), "no Replace row on the Clone Stamp menu"); +} + +/// A Healing Brush app with a document, a set clone source and the tool active. +fn app() -> Box { + let mut a = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + a.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + a.ui.tool = Tool::Healing; + crate::retouch_ui::set_source(&mut a, 8.0, 8.0); + a +} + +/// The mode the next stroke would carry in its params. +fn stroke_mode(a: &PhotocraftApp) -> String { + crate::retouch_ui::clone_params(a).expect("a source is set")["mode"].as_str().unwrap_or_default().to_owned() +} + +fn steps(a: &PhotocraftApp) -> usize { + a.session.active().unwrap().history.past_len() +} + +#[test] +fn the_canvas_menu_replace_row_switches_the_stroke_without_a_history_step() { + let mut a = app(); + let before = steps(&a); + brush_mode_menu::choose(&mut a, Item::HealingReplace); + assert!(a.ui.tool_options.healing_replace, "the row sets the tool option"); + assert_eq!(stroke_mode(&a), "replace", "the next stroke sends mode:\"replace\""); + assert_eq!(current(&a, Tool::Healing), Some(Item::HealingReplace), "the menu checks Replace"); + assert_eq!(steps(&a), before, "picking the Mode adds no History step"); + // An existing row leaves Replace and paints its blend mode. + brush_mode_menu::choose(&mut a, Item::Blend(BlendMode::Multiply)); + assert!(!a.ui.tool_options.healing_replace, "Multiply leaves Replace"); + assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); + assert_eq!(stroke_mode(&a), "Multiply"); + assert_eq!(steps(&a), before, "picking a Mode never adds a History step"); + // Replace is not offered to the other tools' choose route: their rows and options stay. + let mut b = app(); + b.ui.tool = Tool::CloneStamp; + brush_mode_menu::choose(&mut b, Item::HealingReplace); + assert!(!b.ui.tool_options.healing_replace, "the Clone Stamp never takes Replace"); +} + +#[test] +fn the_options_bar_dropdown_replaces_and_picking_a_blend_mode_leaves_it() { + use crate::app::framework::BuildApp as _; + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + // The options bar alone, like the other bar tests: open the Mode dropdown, click a row. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.ui.tool = Tool::Healing; + crate::retouch_ui::set_source(&mut app, 8.0, 8.0); + let mut h = Harness::builder().with_size(egui::vec2(1800.0, 300.0)).with_step_dt(1.0 / 60.0).build_app(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Mode").accesskit_node().value().as_deref(), Some("Normal"), "starts at Normal"); + let before = steps(h.state()); + + h.get_by_role_and_label(Role::ComboBox, "Mode").click(); + h.run_steps(2); + h.get_by_label("Replace").click(); + h.run_steps(3); + assert!(h.state().ui.tool_options.healing_replace, "the dropdown's Replace row sets the option"); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Mode").accesskit_node().value().as_deref(), Some("Replace"), "the dropdown reads Replace"); + assert_eq!(crate::retouch_ui::clone_params(h.state()).expect("the source is set")["mode"], json!("replace"), "the next stroke would run in Replace"); + assert_eq!(steps(h.state()), before, "picking a Mode adds no History step"); + + h.get_by_role_and_label(Role::ComboBox, "Mode").click(); + h.run_steps(2); + h.get_by_label("Multiply").click(); + h.run_steps(3); + assert!(!h.state().ui.tool_options.healing_replace, "Multiply leaves Replace"); + assert_eq!(h.state().session.tools.brush.mode, BlendMode::Multiply, "the brush takes the mode"); + assert_eq!(crate::retouch_ui::clone_params(h.state()).expect("the source is set")["mode"], json!("Multiply")); + assert_eq!(steps(h.state()), before, "and no Mode pick ever adds a step"); +} + +#[test] +fn the_mode_keys_keep_the_seven_modes_and_clear_replace() { + // Replace stays out of the letter keys and the ⇧+ / ⇧− cycle: the seven modes and their order. + let mut a = app(); + a.ui.tool_options.healing_replace = true; + assert!(fired(&mut a, &test_fired(BlendShortcut::Multiply.into())), "⇧⌥M is taken"); + assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); + assert!(!a.ui.tool_options.healing_replace, "a letter pick leaves Replace"); + let mut b = app(); + assert!(fired(&mut b, &test_fired(BlendStep::Next.into())), "⇧+ is taken"); + assert_eq!(b.session.tools.brush.mode, BlendMode::Multiply, "the cycle still runs Normal to Multiply"); + assert!(!b.ui.tool_options.healing_replace, "the cycle never picks Replace"); +} diff --git a/crates/ui-egui/src/hidden_layer_tests.rs b/crates/ui-egui/src/hidden_layer_tests.rs index 338d4fe76b..6b527ab174 100644 --- a/crates/ui-egui/src/hidden_layer_tests.rs +++ b/crates/ui-egui/src/hidden_layer_tests.rs @@ -82,11 +82,11 @@ fn painting_a_hidden_layer_is_refused_at_the_press() { let n = steps(&app); tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); assert!(!crate::canvas::testing::in_gesture(&app) && app.live_stroke.is_none(), "{tool:?}: no stroke started"); - // The Brush (#11898) and the Classic gradient (#12017) say so in an alert, the other tools - // in the status bar. + // The Brush (#11898), the Classic gradient (#12017) and the Paint Bucket (#12537) say so in + // an alert, the other tools in the status bar. let alerts = alerts(&app); let alert = alerts.iter().any(|m| m.contains("target layer is hidden")); - if matches!(tool, Tool::Brush | Tool::Gradient) { + if matches!(tool, Tool::Brush | Tool::Gradient | Tool::PaintBucket) { assert!(alert, "{tool:?}: {alerts:?}"); } else { assert!(app.ui.status.contains("target layer is hidden") && alerts.is_empty(), "{tool:?}: {}", app.ui.status); diff --git a/crates/ui-egui/src/home_recent_gate_tests.rs b/crates/ui-egui/src/home_recent_gate_tests.rs index 23bc95592c..54a9fbb240 100644 --- a/crates/ui-egui/src/home_recent_gate_tests.rs +++ b/crates/ui-egui/src/home_recent_gate_tests.rs @@ -34,7 +34,7 @@ fn home(path: &str) -> Harness<'static, (Box, bool)> { let mut h = Harness::builder().with_size(egui::vec2(900.0, 760.0)).with_context(app.ctx().clone()).build_ui_state( |ui, (app, ready): &mut (Box, bool)| { if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::canvas::testing::document_area(app, ui)); } }, (app, false), diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 02470d1340..73bf196644 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -210,7 +210,7 @@ pub(crate) fn act(app: &mut PhotocraftApp, action: &StartAction) -> bool { StartAction::OpenRecent(path) => { let path = path.to_string_lossy(); if let Err(e) = open_recent_gate(app, &path).and_then(|()| app.open_path(&path)) { - app.open_failed(&crate::file_open::display_name(&path), &e); + app.open_failed(&path, &e); } true } diff --git a/crates/ui-egui/src/input/blend_keys.rs b/crates/ui-egui/src/input/blend_keys.rs index 18c3f66848..7ece1ee5d5 100644 --- a/crates/ui-egui/src/input/blend_keys.rs +++ b/crates/ui-egui/src/input/blend_keys.rs @@ -21,7 +21,8 @@ use crate::brush_mode_menu::Item; use crate::state::Tool; use crate::{PhotocraftApp, brush_mode_menu}; -/// Photoshop's Healing Brush modes, less Replace (not implemented yet). +/// Photoshop's Healing Brush modes. Replace is the tool's own option, not a blend mode: the menus +/// add it as a row of its own (#12101), and the letters and steps below keep this list. pub const HEALING_MODES: [BlendMode; 7] = [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Darken, BlendMode::Lighten, BlendMode::Color, BlendMode::Luminosity]; @@ -129,7 +130,10 @@ fn set_tool_mode(app: &mut PhotocraftApp, mode: Option) { brush.insert("behind".into(), json!(false)); } if !brush.is_empty() { - let _ = app.run("tools.setBrush", json!({ "brush": brush })); + // Replace (#12101): a key-picked blend mode leaves it, in the same pick. + if app.run("tools.setBrush", json!({ "brush": brush })).is_ok() && app.ui.tool == Tool::Healing { + app.ui.tool_options.healing_replace = false; + } } } diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index ef932e8bbd..7c9ff4da05 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -48,6 +48,8 @@ pub struct OpenTab { pub name: String, /// Where it was read from (File › Save writes back there; added to Open Recent). pub path: Option, + /// Actual read source when it differs from the save/recent path (an untitled Smart Object or byte-backed template). + pub error_source: Option, /// The tab position it goes to when it opens (a file dropped on the tabs); `None`: the end. pub slot: Option, /// Its place in a set of files opened together, when it is one of several (see [`OpenOrder`]). @@ -172,6 +174,8 @@ pub struct JobsUi { pub(crate) batches: Vec, /// The id of the next set. next_batch: u64, + /// Identity of the next per-file failure alert (never a document/save identity). + next_open_failure: u64, /// Background saves. pub saves: Vec, /// The window was asked to close while a save was writing: close it once none is left. @@ -183,6 +187,15 @@ pub struct JobsUi { /// The file being placed in the background, if any. One at a time: files dropped meanwhile /// wait in the app's drop queue. pub place: Option, + /// Content-Aware Fill settings waiting for their background fill: remembered when it is applied (#14254). + pub(crate) caf_settings: Vec<(JobId, Value)>, +} + +/// A fresh identity for one failed file. Kept with the window's open bookkeeping, not persisted. +pub(crate) fn open_failure_id(app: &mut PhotocraftApp) -> craft::ui::dialog::DialogId { + let serial = app.jobs.next_open_failure; + app.jobs.next_open_failure = serial.wrapping_add(1); + craft::ui::dialog::dialog_id(("file-open-failure", serial)) } /// Run command `id`: in the background when background jobs are on and the command is a job @@ -283,13 +296,15 @@ pub fn start_open( slot: Option, order: Option, ) -> Result<(), String> { - let name = &app.open_name(name); + let source_name = name; + let name = &app.open_name(source_name); + let error_source = (path.is_none() && name.as_str() != source_name).then(|| source_name.to_string()); match app.session.start_open_for_user_with_background(name, source, app.background_jobs).map_err(|e| e.to_string())? { // Inline (wasm, or background jobs off): finish now, like a background open that ended at // once. A preflight keeps the slot and set order in its memory prompt. - Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order), + Started::Done(v) => finish_open(app, name, path.as_deref(), error_source.as_deref(), &v, slot, order), Started::Job(job) => { - track_open(app, OpenTab { job, name: name.to_string(), path, slot, order }); + track_open(app, OpenTab { job, name: name.to_string(), path, error_source, slot, order }); Ok(()) } } @@ -318,9 +333,9 @@ pub(crate) fn start_open_as_smart_object(app: &mut PhotocraftApp, path: &str, or Started::Done(app.session.execute("file.openAsSmartObject", params).map_err(|e| e.to_string())?) }; match started { - Started::Done(v) => finish_open(app, &name, None, &v, None, order), + Started::Done(v) => finish_open(app, &name, None, Some(path), &v, None, order), Started::Job(job) => { - track_open(app, OpenTab { job, name, path: None, slot: None, order }); + track_open(app, OpenTab { job, name, path: None, error_source: Some(path.to_string()), slot: None, order }); Ok(()) } } @@ -374,7 +389,7 @@ pub(crate) fn tab_slot(app: &mut PhotocraftApp, slot: Option, order: Opti /// [`JobsUi::opens`]: the document goes to the tab's slot, or to its place in its set. A memory /// preflight keeps both in its prompt. pub(crate) fn finish_open_tab(app: &mut PhotocraftApp, tab: &OpenTab, v: &Value) -> Result<(), String> { - let r = finish_open(app, &tab.name, tab.path.as_deref(), v, tab.slot, tab.order); + let r = finish_open(app, &tab.name, tab.path.as_deref(), tab.error_source.as_deref(), v, tab.slot, tab.order); end_batch(app); r } @@ -607,6 +622,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { } // A Free Transform commit's session ends with its job (then reported like any job). crate::transform_tool::on_job_event(app, &e); + crate::caf_ui::on_job_event(app, &e); if crate::prefs_ui::on_recovery_event(app, &e) { return; } @@ -636,13 +652,19 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { if e.command == OPEN_JOB || app.jobs.opens.iter().any(|o| o.job == e.id) { let Some(i) = app.jobs.opens.iter().position(|o| o.job == e.id) else { return }; let tab = app.jobs.opens.remove(i); + let source = tab.path.as_deref().or(tab.error_source.as_deref()).unwrap_or(&tab.name); match e.outcome { JobOutcome::Done(v) => { if let Err(err) = finish_open_tab(app, &tab, &v) { - app.open_failed(&tab.name, &err); + app.open_failed(source, &err); } } - JobOutcome::Failed(err) => app.open_failed(&tab.name, &err), + JobOutcome::Failed(err) => { + // A template's worker name is Untitled-N, while its alert names the read source. + let reason = + if tab.name != crate::file_open::display_name(source) { err.strip_prefix(&format!("{}: ", tab.name)).unwrap_or(&err) } else { &err }; + app.open_failed(source, reason); + } JobOutcome::Cancelled => { app.ui.status = crate::i18n::fmt(tl!("Canceled opening {name}"), &[("name", &tab.name)]); app.ui.status_error = false; @@ -704,7 +726,15 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { /// (`{document, docId, warnings, color}` or `{held, …}`). `slot` and `order` are the tab position /// and set place the file keeps: through a memory prompt, a profile/damage prompt and the final /// document, so an inline completion lands where a background tab would. -fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option, order: Option) -> Result<(), String> { +fn finish_open( + app: &mut PhotocraftApp, + name: &str, + path: Option<&str>, + error_source: Option<&str>, + v: &Value, + slot: Option, + order: Option, +) -> Result<(), String> { if let Some(preflight_id) = v.get("pendingPreflight").and_then(Value::as_u64) { let estimated = v.get("estimated").and_then(Value::as_u64).unwrap_or(0); let available = v.get("availableRam").and_then(Value::as_u64); @@ -715,6 +745,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu preflight_id, name.to_string(), path.map(str::to_string), + error_source.map(str::to_string), slot, order, estimated, @@ -852,16 +883,25 @@ pub(crate) fn status_job(app: &PhotocraftApp) -> Option<(JobId, crate::panels::s Some((j.id, crate::panels::status_bar::Progress { label, fraction: shown_fraction(&j), cancel: Some(tl!("Cancel (Esc)").to_owned()), refused })) } -/// Show the folder Batch worker's immutable current document in the canvas area. The worker -/// publishes snapshots rather than adding them to `Session`, so no edit or Save can target one. -pub(crate) fn batch_preview(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { - let current = app - .session +/// The running Batch job whose worker has published its current input, with that snapshot. +fn shown_batch_preview(app: &PhotocraftApp) -> Option<(JobId, photocraft_engine::jobs::BatchPreview)> { + app.session .jobs() .into_iter() .filter(|job| job.command == "file.automate.batch") - .find_map(|job| app.session.batch_preview(job.id).map(|preview| (job.id, preview))); - let Some((id, preview)) = current else { return false }; + .find_map(|job| app.session.batch_preview(job.id).map(|preview| (job.id, preview))) +} + +/// What [`batch_preview`] shows, for the document area's version: the job and the snapshot's generation. The worker +/// publishes a new input with no command or input reaching the area. +pub(crate) fn batch_preview_key(app: &PhotocraftApp) -> Option<(JobId, u64)> { + shown_batch_preview(app).map(|(id, preview)| (id, preview.generation)) +} + +/// Show the folder Batch worker's immutable current document in the canvas area. The worker +/// publishes snapshots rather than adding them to `Session`, so no edit or Save can target one. +pub(crate) fn batch_preview(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { + let Some((id, preview)) = shown_batch_preview(app) else { return false }; let name = std::path::Path::new(&preview.path).file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_else(|| preview.path.clone()); Row::new().show(ui, |ui, _| { Text::new(name.clone()).role(TypeRole::BodyStrong).show(ui); diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index 0a235c97c5..f931c57c8c 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -1040,7 +1040,7 @@ fn background_open_warns_about_missing_fonts() { // What the open job leaves behind: the decoded document in the session, then its result. let (index, _) = app.session.open_document(doc, None); let id = app.session.documents()[index].doc.id; - super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap(); + super::finish_open(&mut app, "poster.psd", None, None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap(); let want = vec!["font 'NoSuchFamily4559' is not installed; text may render using a fallback face".to_string()]; assert!(app.ui.notices.last().is_some_and(|n| n.title.contains("poster.psd") && n.lines == want), "{:?}", app.ui.notices); } @@ -1122,7 +1122,7 @@ fn open_identity_survives_tab_reordering() { let old_index = result["document"].as_u64().unwrap() as usize; app.session.move_document(old_index, 0).unwrap(); assert_eq!(app.session.documents()[old_index].doc.id, control.doc.id); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, None, None).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), None, &result, None, None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("imported.png")); @@ -1137,7 +1137,7 @@ fn open_identity_survives_an_earlier_tab_closing() { let (result, imported) = identified_result(&app, result); app.session.close(1).unwrap(); app.session.set_active(0); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, Some(0), None).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), None, &result, Some(0), None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.documents()[0].doc.id, imported, "the requested destination slot applies to the correct document"); @@ -1159,13 +1159,16 @@ fn open_identity_rejects_closed_missing_and_invalid_identities() { } Some(value) => result["docId"] = value, } - assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, Some(0), None).is_err(), "invalid identity was accepted: {result}"); + assert!( + super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, Some(0), None).is_err(), + "invalid identity was accepted: {result}" + ); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); assert_eq!(app.session.documents().len(), 1); result["docId"] = json!(imported.0); assert!( - super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, None, None).is_err(), + super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, None, None).is_err(), "a closed identity must not fall back to the old tab index" ); control.assert_untouched(&app); @@ -1186,9 +1189,9 @@ fn open_identity_keeps_same_poll_results_in_the_profile_queue() { let (second, second_id) = identified_result(&app, second); // All engine applies have finished. Handling the first ordinary result removes its tab, // shifting the second result before its UI callback runs. - super::finish_open(&mut app, "profile.png", Some("profile.png"), &prompt, None, None).unwrap(); - super::finish_open(&mut app, "first.png", Some("first.png"), &first, None, None).unwrap(); - super::finish_open(&mut app, "second.png", Some("second.png"), &second, None, None).unwrap(); + super::finish_open(&mut app, "profile.png", Some("profile.png"), None, &prompt, None, None).unwrap(); + super::finish_open(&mut app, "first.png", Some("first.png"), None, &first, None, None).unwrap(); + super::finish_open(&mut app, "second.png", Some("second.png"), None, &second, None, None).unwrap(); assert_eq!(app.held_opens.iter().map(|held| held.name.as_str()).collect::>(), ["profile.png", "first.png", "second.png"]); assert_eq!(app.held_opens.iter().skip(1).map(|held| held.doc.id).collect::>(), [first_id, second_id]); assert_eq!(app.session.documents().len(), 1, "both completed imports wait behind the profile prompt"); diff --git a/crates/ui-egui/src/levels_clipping.rs b/crates/ui-egui/src/levels_clipping.rs index 82ec781dae..749acb4582 100644 --- a/crates/ui-egui/src/levels_clipping.rs +++ b/crates/ui-egui/src/levels_clipping.rs @@ -221,6 +221,13 @@ fn dialog(app: &PhotocraftApp) -> Option<&crate::adjust_dialog::OpenAdjust> { crate::adjust_dialog::open_value(app).filter(|open| open.kind == "levels" && open.smart_filter.is_none()) } +/// What the canvas shows of an open Levels dialog's clipping display, for the document area's version +/// (`region_versions::canvas`): the dialog and its fields, which change with no command. +pub(crate) fn canvas_key(app: &PhotocraftApp) -> Option<(craft::ui::dialog::DialogId, String)> { + let open = dialog(app)?; + Some((open.id, crate::adjust_dialog::open_params(app).map(|params| params.to_string()).unwrap_or_default())) +} + /// The display the open Levels dialog asks for on document `idx`. None when no Levels dialog /// shows clipping, `idx` isn't the active document, or the document can't show it: CMYK and Lab, /// a channel, mask or Quick Mask target, or a target that isn't a pixel layer. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 102fbc6d51..d159f8f217 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -461,12 +461,10 @@ pub struct PhotocraftApp { /// The Properties panel's adjustment edit in progress, with the tone editor's shown channel /// (`adjust_editors::PropertiesAdjust`). pub(crate) adjust_session: Option, - /// Twice the passes the Properties panel was not in front or ran without showing the Reset session's layer: the + /// Twice the passes the Properties panel was not in front or ran showing no adjustment layer's controls: the /// session (`adjust_editors`) takes a layer's settings anew after the panel stopped showing it. A pass count would /// also move while the panel replays its memoized body, which is still showing it. pub(crate) properties_hidden: u64, - /// Whether the Properties panel's run showed the Reset session's layer (`properties_hidden`). - pub(crate) properties_tracked: bool, /// The Color Picker dialog asking for a screen sample: the dialog and the field that took it. pub(crate) dialog_dropper: Option<(craft::ui::dialog::DialogId, String)>, /// The child dialog (colour picker or contour editor) the open Layer Style dialog has, with that dialog's id. @@ -499,6 +497,9 @@ pub struct PhotocraftApp { filter_preview_worker: crate::dialogs::filter_preview_worker::Worker, /// Full CPU canvas redraws running in the background, by document (#4024). pub(crate) redraws: std::collections::HashMap, + /// How many redraw blocks have landed (`background_redraw::poll`): they reach the GPU canvas between the document + /// area's runs, so the area's version holds the count (`region_versions::canvas`). + pub(crate) redraw_landed: u64, /// The last finished background redraws, for going back to a state drawn a moment ago (#6528). pub(crate) kept: background_redraw::KeptComposites, /// Select › Color Range dialog preview (proxy document + mask / image textures). @@ -747,6 +748,8 @@ mod eyedropper_context_menu_tests; #[cfg(test)] mod menu_automate_groups_tests; #[cfg(test)] +mod paint_bucket_options_fields_tests; +#[cfg(test)] mod patch_rasterize_prompt_tests; #[cfg(test)] mod patch_shift_constrain_tests; @@ -939,6 +942,8 @@ mod move_shift_click_tests; #[cfg(test)] mod move_target_default_tests; +#[cfg(test)] +mod paint_bucket_pasteboard_color_tests; #[cfg(test)] mod wand_press_inside_selection_tests; diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rs index d9009ae3f7..2d79b25b11 100644 --- a/crates/ui-egui/src/marquee_tests.rs +++ b/crates/ui-egui/src/marquee_tests.rs @@ -28,7 +28,7 @@ fn harness_with_step_dt(tool: Tool, step_dt: f32) -> Harness<'static, Box, &str)] = &[ (&["View"], "Pixel Art Preview", None, "view.pixelArtPreview"), (&["Window", "Arrange"], "Tile All Vertically", None, "window.arrange.tileAllVertically"), (&["Window", "Arrange"], "Tile All Horizontally", None, "window.arrange.tileAllHorizontally"), - (&["Window", "Arrange"], "2-up Vertical", None, "window.arrange.twoUpVertical"), (&["Window", "Arrange"], "2-up Horizontal", None, "window.arrange.twoUpHorizontal"), - (&["Window", "Arrange"], "3-up Vertical", None, "window.arrange.threeUpVertical"), + (&["Window", "Arrange"], "2-up Vertical", None, "window.arrange.twoUpVertical"), (&["Window", "Arrange"], "3-up Horizontal", None, "window.arrange.threeUpHorizontal"), + (&["Window", "Arrange"], "3-up Vertical", None, "window.arrange.threeUpVertical"), (&["Window", "Arrange"], "3-up Stacked", None, "window.arrange.threeUpStacked"), (&["Window", "Arrange"], "4-up", None, "window.arrange.fourUp"), (&["Window", "Arrange"], "6-up", None, "window.arrange.sixUp"), - (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Consolidate All to Tabs", None, "window.arrange.consolidateAllToTabs"), + (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Cascade", None, "window.arrange.cascade"), (&["Window", "Arrange"], "Tile", None, "window.arrange.tile"), - (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Float in Window", None, "window.arrange.floatInWindow"), (&["Window", "Arrange"], "Float All in Windows", None, "window.arrange.floatAllInWindows"), (&["Window", "Arrange"], "---", None, "---"), - (&["Window", "Arrange"], "New Window", None, "window.arrange.newWindowForDocument"), - (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Match Zoom", None, "window.arrange.matchZoom"), (&["Window", "Arrange"], "Match Location", None, "window.arrange.matchLocation"), (&["Window", "Arrange"], "Match Rotation", None, "window.arrange.matchRotation"), (&["Window", "Arrange"], "Match All", None, "window.arrange.matchAll"), + (&["Window", "Arrange"], "---", None, "---"), + (&["Window", "Arrange"], "New Window", None, "window.arrange.newWindowForDocument"), (&["Window", "Workspace"], "Essentials", None, "window.workspace.essentials"), (&["Window", "Workspace"], "Photography", None, "window.workspace.photography"), (&["Window", "Workspace"], "Painting", None, "window.workspace.painting"), diff --git a/crates/ui-egui/src/menu_floor_trials.rs b/crates/ui-egui/src/menu_floor_trials.rs index 9b9e0ce880..268d033938 100644 --- a/crates/ui-egui/src/menu_floor_trials.rs +++ b/crates/ui-egui/src/menu_floor_trials.rs @@ -1,5 +1,5 @@ //! PhotoCraft's frame floor (frame-design-v2 2.2, 2.3): an idle frame keys the same bytes whatever the size of the -//! documents, presets and recent files, and builds no derived value; a status message runs only the status bar's view; +//! documents, presets and recent files, and builds no derived value; a status message runs only the status slot and its body view; //! the menu model is built only when a fact it shows changed, never for a tool option or a button release, and the //! held model always equals a fresh build. @@ -11,6 +11,7 @@ use photocraft_engine::presets::PresetsExt; use serde_json::json; use crate::PhotocraftApp; +use crate::chrome_settle_trials::{ShellSlot, slot_runs}; use crate::state::Tool; type H = Harness<'static, Box>; @@ -80,8 +81,14 @@ fn a_status_message_runs_only_the_status_bar() { h.run_steps(2); h.state_mut().ui.status = "Saved".into(); h.run_steps(1); - let ran: Vec<&'static str> = last_frame_memo_runs(&h.ctx).into_iter().filter(|(_, _, run)| *run == MemoRun::Ran).map(|(name, _, _)| name).collect(); - assert!(!ran.is_empty() && ran.iter().all(|name| name.contains("status_bar::StatusProps")), "only the status bar's view runs: {ran:?}"); + let runs = last_frame_memo_runs(&h.ctx); + let ran: Vec<&'static str> = runs.iter().filter(|(_, _, run)| *run == MemoRun::Ran).map(|(name, _, _)| *name).collect(); + let slots = [ShellSlot::Title, ShellSlot::Options, ShellSlot::Status].map(|slot| slot_runs(&runs, slot).0); + assert!(slots[0] == 0 && slots[1] == 0 && slots[2] > 0, "of the shell's slots only the status bar runs: {slots:?}"); + assert!( + ran.iter().all(|name| name.contains("status_bar::StatusProps") || name.contains("app_shell::SlotView<")), + "only the status slot and the status bar's body view run: {ran:?}" + ); } #[test] diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9da031f57b..2f62301eb7 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -118,6 +118,9 @@ mod open_recent_position_tests; #[cfg(test)] mod export_submenu_separator_tests; +#[cfg(test)] +mod arrange_menu_order_tests; + #[cfg(test)] mod bar_cursor_tests; diff --git a/crates/ui-egui/src/menus/arrange_menu_order_tests.rs b/crates/ui-egui/src/menus/arrange_menu_order_tests.rs new file mode 100644 index 0000000000..51a6ebb728 --- /dev/null +++ b/crates/ui-egui/src/menus/arrange_menu_order_tests.rs @@ -0,0 +1,92 @@ +//! Window › Arrange: measured entry order, separators, and dynamic "New Window for " label (#16888). + +use serde_json::json; + +use super::*; + +#[cfg(not(target_arch = "wasm32"))] +fn new_doc(app: &mut PhotocraftApp, name: &str) { + app.run("file.new", json!({"width": 64, "height": 64, "name": name})).unwrap(); +} + +/// The `Window › Arrange` entries returned by `ui.menu.list` as `(id, label, shortcut)`. +#[cfg(not(target_arch = "wasm32"))] +fn arrange_list(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec<(String, String, Option)> { + let (req, _rx) = crate::control::ControlRequest::new("ui.menu.list", json!({})); + let reply = match crate::control::handle(app, ctx, &req) { + crate::control::Reply::Done(v) => v, + _ => panic!("ui.menu.list: expected an immediate reply"), + }; + reply["result"] + .as_array() + .expect("ui.menu.list returns an array") + .iter() + .filter(|it| it["path"] == json!(["Window", "Arrange"])) + .map(|it| { + let label = it["label"].as_str().unwrap_or_default().to_string(); + let id = if label == "---" { "---".to_string() } else { it["id"].as_str().unwrap_or_default().to_string() }; + let shortcut = it["shortcut"].as_str().map(str::to_string); + (id, label, shortcut) + }) + .collect() +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn arrange_menu_matches_measured_order_and_active_document_label() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + + // Without a document open, the final entry keeps its plain fallback label. + let empty = arrange_list(&mut app, &ctx); + assert_eq!(empty.last().map(|(id, label, _)| (id.as_str(), label.as_str())), Some(("window.arrange.newWindowForDocument", "New Window"))); + + new_doc(&mut app, "W1"); + let got = arrange_list(&mut app, &ctx); + let expected: &[(&str, &str)] = &[ + ("window.arrange.tileAllVertically", "Tile All Vertically"), + ("window.arrange.tileAllHorizontally", "Tile All Horizontally"), + ("window.arrange.twoUpHorizontal", "2-up Horizontal"), + ("window.arrange.twoUpVertical", "2-up Vertical"), + ("window.arrange.threeUpHorizontal", "3-up Horizontal"), + ("window.arrange.threeUpVertical", "3-up Vertical"), + ("window.arrange.threeUpStacked", "3-up Stacked"), + ("window.arrange.fourUp", "4-up"), + ("window.arrange.sixUp", "6-up"), + ("window.arrange.consolidateAllToTabs", "Consolidate All to Tabs"), + ("---", "---"), + ("window.arrange.cascade", "Cascade"), + ("window.arrange.tile", "Tile"), + ("window.arrange.floatInWindow", "Float in Window"), + ("window.arrange.floatAllInWindows", "Float All in Windows"), + ("---", "---"), + ("window.arrange.matchZoom", "Match Zoom"), + ("window.arrange.matchLocation", "Match Location"), + ("window.arrange.matchRotation", "Match Rotation"), + ("window.arrange.matchAll", "Match All"), + ("---", "---"), + ("window.arrange.newWindowForDocument", "New Window for W1"), + ]; + let pairs: Vec<(&str, &str)> = got.iter().map(|(id, label, _)| (id.as_str(), label.as_str())).collect(); + assert_eq!(pairs, expected); + assert!(got.iter().all(|(_, _, shortcut)| shortcut.is_none()), "no Window › Arrange entry carries a shortcut: {got:?}"); + + // Activating another document updates the dynamic label while keeping the command id. + new_doc(&mut app, "W2"); + let second = arrange_list(&mut app, &ctx); + assert_eq!(second.last().map(|(id, label, _)| (id.as_str(), label.as_str())), Some(("window.arrange.newWindowForDocument", "New Window for W2"))); + + app.session.set_active(0); + let back = arrange_list(&mut app, &ctx); + assert_eq!(back.last().map(|(id, label, _)| (id.as_str(), label.as_str())), Some(("window.arrange.newWindowForDocument", "New Window for W1"))); +} + +#[test] +fn new_window_for_document_label_uses_translation_catalog_with_english_fallback() { + let translated = crate::i18n::fixture_lang("fr", "\tNew Window for {name}\tNouvelle fenêtre pour {name}\n"); + let missing = crate::i18n::fixture_lang("fr", ""); + + assert_eq!(translated_menu_label(translated, "window.arrange.newWindowForDocument", "New Window for W1"), "Nouvelle fenêtre pour W1"); + assert_eq!(translated_menu_label(missing, "window.arrange.newWindowForDocument", "New Window for W1"), "New Window for W1"); + assert_eq!(translated_menu_label(crate::i18n::Lang::EN, "window.arrange.newWindowForDocument", "New Window for W1"), "New Window for W1"); +} diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index 0d9bd0e3d3..6a046a5b8e 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -258,6 +258,12 @@ pub fn base_rows(app: &PhotocraftApp) -> Vec { if let Some(item) = find(&mut rows, "layer.smartObjects.revealInFinder") { item.label = reveal_label().into(); } + // Window › Arrange › New Window names the active document (#16888). + if let Some(st) = app.session.active() + && let Some(item) = find(&mut rows, "window.arrange.newWindowForDocument") + { + item.label = format!("New Window for {}", st.doc.name); + } // File › Open Recent: a dynamic submenu of recently opened files, after Open as Smart Object… (#14053). if let Some(after) = rows.iter().position(|i| i.command.id == "file.openAsSmartObject").or_else(|| rows.iter().position(|i| i.command.id == "file.openAs")) { diff --git a/crates/ui-egui/src/menus/parity.rs b/crates/ui-egui/src/menus/parity.rs index f320b4a4a4..ac2ff1cedf 100644 --- a/crates/ui-egui/src/menus/parity.rs +++ b/crates/ui-egui/src/menus/parity.rs @@ -6,6 +6,93 @@ use crate::menu_catalog::CATALOG; use crate::menus::is_live; +/// RFC-0052 hand marks for catalog ids that aren't engine commands: `(id, headless, reach, why)`. +/// +/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer), +/// `os` (needs an OS service the engine doesn't wrap) or `engine-gap` (could be an engine command, +/// isn't one yet). `yes` is never written here: an item is `yes` only when +/// `photocraft_engine::commands::find` has its id, the registry `photocraft-cli` and the MCP server +/// load. [`is_live`] also counts a dozen desktop-only sources; those make an item live in the menu, +/// not headless. Without a mark, an id the desktop serves as a panel, workspace or pointer tool is +/// `no` with `reach: window` ([`desktop_window`]); any other is `unknown`. +pub const HEADLESS: &[(&str, &str, &str, &str)] = &[]; + +/// Why a non-engine id needs a desktop window, when the desktop serves it as a panel, a workspace +/// or a pointer tool. +fn desktop_window(id: &str) -> Option<&'static str> { + if super::invoke::panel_alias(id).is_some() || crate::panel_docking::toggle_panel(id).is_some() { + Some("shows or hides a desktop panel") + } else if super::invoke::workspace_id(id).is_some() || crate::workspace_ui::handles(id) { + Some("a desktop workspace") + } else if crate::tool_shortcuts::tool(id).is_some() { + Some("picks a pointer tool") + } else { + None + } +} + +/// An item's RFC-0052 `(headless, reach, why)`: `yes` for an engine command, else its mark in +/// `marks`, else `no`/`window` for a desktop panel, workspace or tool, else `unknown`. +pub fn headless_of<'a>(id: &str, in_engine: bool, marks: &[(&'a str, &'a str, &'a str, &'a str)]) -> (&'a str, Option<&'a str>, &'a str) { + if in_engine { + return ("yes", None, ""); + } + if let Some(m) = marks.iter().find(|m| m.0 == id) { + return (m.1, Some(m.2), m.3); + } + match desktop_window(id) { + Some(why) => ("no", Some("window"), why), + None => ("unknown", None, ""), + } +} + +/// Problems with `marks` against `ids` (`(id, is an engine command)`): bad values, repeats, ids +/// not in the catalog, and marks on engine commands (they would hide a `yes`). +pub fn headless_errors(marks: &[(&str, &str, &str, &str)], ids: &[(&str, bool)]) -> Vec { + let mut errs = Vec::new(); + for (i, (id, value, reach, _)) in marks.iter().enumerate() { + if !matches!(*value, "no" | "partial") { + errs.push(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)")); + } + if !matches!(*reach, "window" | "os" | "engine-gap") { + errs.push(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap")); + } + if marks[..i].iter().any(|m| m.0 == *id) { + errs.push(format!("headless mark `{id}` is written twice")); + } + match ids.iter().find(|x| x.0 == *id) { + None => errs.push(format!("headless mark `{id}` is not a catalog id")), + Some((_, true)) => errs.push(format!("headless mark `{id}` is stale: it is an engine command, so it is `yes`")), + Some(_) => {} + } + } + errs +} + +/// RFC-0052 counts over the catalog. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] +pub struct HeadlessCounts { + pub yes: usize, + pub no_window: usize, + pub no_os: usize, + pub no_engine_gap: usize, + pub partial: usize, + pub unknown: usize, +} + +impl HeadlessCounts { + fn add(&mut self, value: &str, reach: Option<&str>) { + match (value, reach) { + ("yes", _) => self.yes += 1, + ("no", Some("window")) => self.no_window += 1, + ("no", Some("os")) => self.no_os += 1, + ("no", _) => self.no_engine_gap += 1, + ("partial", _) => self.partial += 1, + _ => self.unknown += 1, + } + } +} + /// Minimum number of live catalog items. Raise it when parity grows; never lower it. pub const FLOOR: usize = 663; @@ -17,6 +104,8 @@ pub struct MenuParity { pub total: usize, /// Labels (with submenu path) of items not implemented yet. pub missing: Vec, + /// Items that aren't `headless: yes`, with their value (RFC-0052). + pub not_headless: Vec, } #[derive(Clone, Debug, serde::Serialize)] @@ -24,6 +113,7 @@ pub struct Parity { pub live: usize, pub total: usize, pub menus: Vec, + pub headless: HeadlessCounts, } impl Parity { @@ -42,6 +132,18 @@ impl Parity { let pct = if m.total == 0 { 0.0 } else { 100.0 * m.live as f64 / m.total as f64 }; s.push_str(&format!("| {} | {} | {} | {:.0}% |\n", m.menu, m.live, m.total, pct)); } + let h = &self.headless; + s.push_str(&format!( + "\n**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.**\n\n", + h.yes, + h.no_window + h.no_os + h.no_engine_gap, + h.no_window, + h.no_os, + h.no_engine_gap, + h.partial, + h.unknown + )); + s.push_str("Live counts the desktop app's own panels, workspaces, tools and view handlers. Headless counts only the engine registry that `photocraft-cli` and the MCP server load: an item is `yes` when its id is an engine command. The rest are listed under [Not headless](#not-headless), with the hand mark from `HEADLESS` in `crates/ui-egui/src/menus/parity.rs`, `no` (`window`) for a desktop panel, workspace or tool, or `unknown`.\n"); s.push_str("\n## Not yet implemented\n"); for m in self.menus.iter().filter(|m| !m.missing.is_empty()) { s.push_str(&format!("\n### {} ({})\n\n", m.menu, m.missing.len())); @@ -49,6 +151,13 @@ impl Parity { s.push_str(&format!("- {item}\n")); } } + s.push_str("\n## Not headless\n"); + for m in self.menus.iter().filter(|m| !m.not_headless.is_empty()) { + s.push_str(&format!("\n### {} ({})\n\n", m.menu, m.not_headless.len())); + for item in &m.not_headless { + s.push_str(&format!("* {item}\n")); + } + } s } } @@ -57,6 +166,7 @@ impl Parity { pub fn compute() -> Parity { let mut menus: Vec = Vec::new(); let mut seen = std::collections::HashSet::new(); + let mut headless = HeadlessCounts::default(); for &(path, label, _, id) in CATALOG { if id == "---" || !seen.insert(id) { continue; @@ -65,21 +175,28 @@ pub fn compute() -> Parity { let i = match menus.iter().position(|m| m.menu == top) { Some(i) => i, None => { - menus.push(MenuParity { menu: top.to_string(), live: 0, total: 0, missing: Vec::new() }); + menus.push(MenuParity { menu: top.to_string(), live: 0, total: 0, missing: Vec::new(), not_headless: Vec::new() }); menus.len() - 1 } }; let Some(m) = menus.get_mut(i) else { continue }; m.total += 1; + let mut full: Vec<&str> = path[1..].to_vec(); + full.push(label); + let name = format!("{} (`{id}`)", full.join(" › ")); + let (value, reach, why) = headless_of(id, photocraft_engine::commands::find(id).is_some(), HEADLESS); + headless.add(value, reach); + if value != "yes" { + let reach = reach.map(|r| format!(", reach: {r} ({why})")).unwrap_or_default(); + m.not_headless.push(format!("{name}: headless: {value}{reach}")); + } if is_live(id) { m.live += 1; } else { - let mut full: Vec<&str> = path[1..].to_vec(); - full.push(label); - m.missing.push(format!("{} (`{id}`)", full.join(" › "))); + m.missing.push(name); } } - Parity { live: menus.iter().map(|m| m.live).sum(), total: menus.iter().map(|m| m.total).sum(), menus } + Parity { live: menus.iter().map(|m| m.live).sum(), total: menus.iter().map(|m| m.total).sum(), menus, headless } } #[cfg(test)] @@ -93,10 +210,51 @@ mod tests { assert!(p.live >= FLOOR, "menu parity regressed: {} live < floor {FLOOR}", p.live); } + #[test] + fn headless_marks_are_current() { + let ids: Vec<(&str, bool)> = CATALOG.iter().filter(|c| c.3 != "---").map(|c| (c.3, photocraft_engine::commands::find(c.3).is_some())).collect(); + let errs = headless_errors(HEADLESS, &ids); + assert!(errs.is_empty(), "{errs:?}"); + } + + #[test] + fn headless_yes_is_the_engine_registry_only() { + let p = compute(); + let h = &p.headless; + assert_eq!(h.yes + h.no_window + h.no_os + h.no_engine_gap + h.partial + h.unknown, p.total); + assert!(h.yes < p.live, "desktop-only sources are live, not headless"); + let listed: usize = p.menus.iter().map(|m| m.not_headless.len()).sum(); + assert_eq!(listed, p.total - h.yes); + // A panel toggle is live in the desktop app and never headless. + let window = p.menus.iter().find(|m| m.menu == "Window").map(|m| m.not_headless.len()).unwrap_or(0); + assert!(window > 0, "Window panels read as not headless"); + assert!(p.to_markdown().contains(&format!("{} yes,", h.yes))); + } + + #[test] + fn headless_values_and_bad_marks() { + let marks = [("c.d", "no", "engine-gap", "could be a command")]; + assert_eq!(headless_of("c.d", true, &marks).0, "yes", "an engine id is yes whatever the mark says"); + assert_eq!(headless_of("c.d", false, &marks), ("no", Some("engine-gap"), "could be a command")); + assert_eq!(headless_of("q.never", false, &marks).0, "unknown"); + let ids = [("a.b", true), ("c.d", false)]; + let bad = [("c.d", "yes", "os", ""), ("c.d", "no", "desk", ""), ("a.b", "no", "os", ""), ("z.z", "no", "os", "")]; + let errs = headless_errors(&bad, &ids); + for want in ["is not `no` or `partial`", "reach `desk`", "written twice", "`a.b` is stale", "`z.z` is not a catalog id"] { + assert!(errs.iter().any(|e| e.contains(want)), "{want}: {errs:?}"); + } + let mut c = HeadlessCounts::default(); + for (v, r) in [("yes", None), ("no", Some("window")), ("no", Some("os")), ("no", Some("engine-gap")), ("partial", Some("os")), ("unknown", None)] { + c.add(v, r); + } + assert_eq!(c, HeadlessCounts { yes: 1, no_window: 1, no_os: 1, no_engine_gap: 1, partial: 1, unknown: 1 }); + } + #[test] fn markdown_lists_every_missing_item() { let p = compute(); let md = p.to_markdown(); + // `- ` lines are the missing items; the Not headless list uses `* `. let listed = md.lines().filter(|l| l.starts_with("- ")).count(); assert_eq!(listed, p.total - p.live); } diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index bf3cd0c253..05acaf5755 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -235,5 +235,10 @@ pub(super) fn translated_menu_label(lang: crate::i18n::Lang, id: &str, label: &s { return crate::i18n::tr_id(lang, id, "Quick Export as PNG").replace("PNG", fmt); } + if id == "window.arrange.newWindowForDocument" + && let Some(name) = label.strip_prefix("New Window for ") + { + return crate::i18n::fmt(crate::i18n::tr(lang, "New Window for {name}"), &[("name", name)]); + } crate::i18n::tr_id(lang, id, label).to_string() } diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 80502f8776..e365fa1542 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -309,6 +309,8 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec Option<(Vec>; + +const TOLERANCE_ALERT: &str = "An integer between 0 and 255 is required. Closest value inserted."; +const OPACITY_ALERT: &str = "An integer between 1% and 100% is required. Closest value inserted."; + +thread_local! { + /// The decimal mark the bar's fields read, from the env they are drawn in: the system region's + /// unless the host sets one, so a typed fraction must use it to be read as one. + static MARK: Cell = const { Cell::new('.') }; +} + +/// The options bar with `tool` active, and the dialog host its alerts open on. +fn bar(tool: Tool) -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + app.ui.tool_options.tolerance = 32.0; + app.ui.tool_options.fill_opacity = 37.0; + crate::theme::install_fonts(app.ctx()); + crate::theme::apply(app.ctx(), &crate::theme::AppTheme::pro()); + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1800.0, 300.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut Box| { + MARK.set(Env::of(ui).format().separators().0); + crate::panels::options_bar(app, ui); + crate::dialogs::run(app, ui); + }, + app, + ); + h.run_steps(4); + h +} + +/// `text` with `.` replaced by the fields' decimal mark. +fn localized(text: &str) -> String { + text.replace('.', &MARK.get().to_string()) +} + +/// The number field named `label`, with or without its caption's colon. +fn field<'a>(h: &'a H, label: &str) -> Option> { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == label)) +} + +/// Types `text` (with `.` as the decimal mark) into the field named `label` and commits it with Enter. +fn type_into(h: &mut H, label: &str, text: &str) { + let text = localized(text); + field(h, label).unwrap_or_else(|| panic!("the {label} field")).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text)); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); +} + +/// The messages of the open framework alerts. +fn alerts(h: &H) -> Vec { + h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_string)).collect() +} + +/// The description (tooltip) of the control labelled `label`: not its caption's text node. +fn tip(h: &H, label: &str) -> Option { + let named = move |n: &egui_kittest::kittest::AccessKitNode<'_>| n.role() != Role::Label && n.label().is_some_and(|l| l.trim_end_matches(':') == label); + let node = h.query_all(egui_kittest::kittest::by().predicate(named)).next()?; + node.accesskit_node().description().map(|d| d.to_string()) +} + +#[test] +fn tolerance_past_0_255_takes_the_closest_value_and_alerts() { + for (typed, want) in [("300", 255.0), ("256", 255.0), ("-5", 0.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{typed}"); + assert_eq!(alerts(&h), vec![TOLERANCE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn tolerance_is_a_whole_number() { + for (typed, want) in [("12.7", 13.0), ("12.4", 12.0), ("255", 255.0), ("0", 0.0), ("abc", 32.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{typed}"); + if !typed.contains('.') { + assert!(alerts(&h).is_empty(), "{typed}: no alert, got {:?}", alerts(&h)); + } + } +} + +#[test] +fn a_fractional_tolerance_takes_the_closest_value_and_alerts() { + for (typed, want) in [("12.7", 13.0), ("12.4", 12.0), ("0.4", 0.0), ("254.6", 255.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{typed}"); + assert_eq!(alerts(&h), vec![TOLERANCE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn a_fractional_opacity_rounds_without_an_alert() { + for (typed, want) in [("50.5", 51.0), ("50.4", 50.0), ("1.4", 1.0), ("99.6", 100.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Opacity", typed); + assert_eq!(h.state().ui.tool_options.fill_opacity, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed}: no alert, got {:?}", alerts(&h)); + } +} + +#[test] +fn opacity_past_1_100_takes_the_closest_value_and_alerts() { + for (typed, want) in [("150", 100.0), ("0", 1.0), ("-3", 1.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Opacity", typed); + assert_eq!(h.state().ui.tool_options.fill_opacity, want, "{typed}"); + assert_eq!(alerts(&h), vec![OPACITY_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn opacity_in_range_rounds_to_a_whole_percent_without_an_alert() { + for (typed, want) in [("50.5", 51.0), ("50.4", 50.0), ("100", 100.0), ("1", 1.0), ("abc", 37.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Opacity", typed); + assert_eq!(h.state().ui.tool_options.fill_opacity, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed}: no alert, got {:?}", alerts(&h)); + } +} + +#[test] +fn the_seven_controls_have_the_reference_tooltips() { + let h = bar(Tool::PaintBucket); + for (control, want) in [ + ("Source", "Set source for fill area"), + ("Mode", "Fill Mode"), + ("Opacity", "Set opacity for fill"), + ("Tolerance", "Range of colors to fill"), + ("Anti-alias", "Smoothes edge transition"), + ("Contiguous", "Fill only contiguous pixels"), + ("All Layers", "Fill composite image"), + ] { + assert_eq!(tip(&h, control).as_deref(), Some(want), "{control}"); + } +} + +#[test] +fn the_source_dropdown_has_no_fill_label() { + let h = bar(Tool::PaintBucket); + assert!(h.query_by_label("Fill").is_none() && h.query_by_label("Fill:").is_none(), "a Fill label is shown"); + assert!(h.query_all_by_role(Role::ComboBox).any(|n| n.accesskit_node().label().as_deref() == Some("Source")), "the Source dropdown is shown"); +} + +/// The Magic Wand and the Magic Eraser share Tolerance and keep today's behaviour: a value past +/// 0..255 is clamped without an alert. +#[test] +fn magic_wand_and_magic_eraser_tolerance_are_unchanged() { + for tool in [Tool::MagicWand, Tool::MagicEraser] { + for (typed, want) in [("300", 255.0), ("-5", 0.0), ("128", 128.0)] { + let mut h = bar(tool); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{tool:?} {typed}"); + assert!(alerts(&h).is_empty(), "{tool:?} {typed}: no alert, got {:?}", alerts(&h)); + } + } +} diff --git a/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs b/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs new file mode 100644 index 0000000000..218798df45 --- /dev/null +++ b/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs @@ -0,0 +1,120 @@ +//! #12534: with the Paint Bucket, ⇧-click on the pasteboard sets the pasteboard colour to the +//! foreground colour, as the reference application does: the custom colour becomes the foreground +//! and the pasteboard right-click menu shows Custom checked. The press adds no history state and +//! leaves the document alone. ⇧-click on the image still fills, and the gestures the issue did not +//! measure (other modifiers held, a selection active) keep today's behaviour. + +use egui::Modifiers; +use photocraft_engine::prefs::CanvasColor; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::canvas_tool_menu::{mode_checked, open_at}; +use crate::state::Tool; +use craft::keymap::Mods; + +/// The foreground the tests pick: not the default black, so a fill and the pasteboard colour show it. +const FOREGROUND: &str = "#3366cc"; + +/// A 200 x 150 white document with the Paint Bucket and a blue foreground. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.sync_views(); + app.run("tools.setColors", json!({"foreground": FOREGROUND})).unwrap(); + app.ui.tool = Tool::PaintBucket; + app +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, mods); +} + +fn pasteboard(app: &PhotocraftApp) -> (CanvasColor, String) { + let i = &app.session.prefs().interface; + (i.canvas_color, i.canvas_custom_color.clone()) +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn revision(app: &PhotocraftApp) -> u64 { + app.session.active().unwrap().revision +} + +fn pixel(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] { + let st = app.session.active().unwrap(); + let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +#[test] +fn shift_click_on_the_pasteboard_sets_the_custom_colour_to_the_foreground() { + // Above-left of the image and past its bottom-right corner: both are pasteboard. + for p in [[-30.0, -30.0], [230.0, 170.0]] { + let mut app = app(); + assert_eq!(pasteboard(&app).0, CanvasColor::Default); + click(&mut app, p, Modifiers::SHIFT); + assert_eq!(pasteboard(&app), (CanvasColor::Custom, FOREGROUND.to_string()), "at {p:?}"); + // The pasteboard menu then shows Custom checked, and only Custom. + assert!(open_at(&mut app, Tool::PaintBucket, Mods::NONE, egui::Pos2::ZERO, [-30.0, -30.0], None)); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(mode_checked(&app, &menu, "pasteboard.custom")); + assert!(!mode_checked(&app, &menu, "pasteboard.default")); + } +} + +#[test] +fn shift_click_on_the_pasteboard_adds_no_history_state_and_keeps_the_document() { + let mut app = app(); + let (before_steps, before_revision) = (steps(&app), revision(&app)); + click(&mut app, [-30.0, -30.0], Modifiers::SHIFT); + assert_eq!(steps(&app), before_steps, "no history state"); + assert_eq!(revision(&app), before_revision, "the document did not change"); + assert!(!app.session.active().unwrap().is_dirty()); + assert_eq!(pixel(&app, 0, 0), [255, 255, 255]); +} + +#[test] +fn shift_click_on_the_pasteboard_with_a_type_layer_active_sets_the_colour_without_a_rasterize_prompt() { + // The active layer is a Type layer: a painting press on it would ask to rasterize it + // first, but this gesture only sets a preference, so it runs before that prompt and + // leaves the layer and the document alone. + let mut app = app(); + app.run("type.create", json!({"x": 10, "y": 40, "text": "Hello"})).unwrap(); + app.ui.tool = Tool::PaintBucket; + let (before_steps, before_revision) = (steps(&app), revision(&app)); + click(&mut app, [-30.0, -30.0], Modifiers::SHIFT); + assert_eq!(pasteboard(&app), (CanvasColor::Custom, FOREGROUND.to_string())); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "no rasterize prompt"); + assert_eq!(steps(&app), before_steps, "no history state"); + assert_eq!(revision(&app), before_revision, "the document did not change"); +} + +#[test] +fn shift_click_on_the_image_fills_as_a_plain_click_does() { + let mut app = app(); + let before = steps(&app); + click(&mut app, [50.0, 50.0], Modifiers::SHIFT); + assert_eq!(steps(&app), before + 1, "the fill was applied"); + assert_eq!(pixel(&app, 50, 50), [0x33, 0x66, 0xcc]); + assert_eq!(pasteboard(&app).0, CanvasColor::Default, "the pasteboard colour is untouched"); +} + +#[test] +fn unmeasured_pasteboard_gestures_keep_the_pasteboard_colour() { + // A plain click, ⇧ with another modifier, and ⇧ with a selection active are not this gesture. + for (mods, select) in + [(Modifiers::NONE, false), (Modifiers::SHIFT | Modifiers::ALT, false), (Modifiers::SHIFT | Modifiers::COMMAND, false), (Modifiers::SHIFT, true)] + { + let mut app = app(); + if select { + app.run("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + } + click(&mut app, [-30.0, -30.0], mods); + assert_eq!(pasteboard(&app).0, CanvasColor::Default, "{mods:?}, selection {select}"); + } +} diff --git a/crates/ui-egui/src/paint_bucket_refusal_alerts_tests.rs b/crates/ui-egui/src/paint_bucket_refusal_alerts_tests.rs new file mode 100644 index 0000000000..84eb482cb0 --- /dev/null +++ b/crates/ui-egui/src/paint_bucket_refusal_alerts_tests.rs @@ -0,0 +1,234 @@ +//! #12537: when the Paint Bucket can't fill (a hidden target layer, Lock All or Lock Image Pixels, +//! a group active), a click opens the reference application's alert with OK and fills nothing: no +//! History step, the target layer stays selected. Lock transparent pixels and Lock position still +//! fill; a pixel layer inside a group fills normally; a group's targeted layer mask is not refused +//! and takes today's step-without-fill. The Brush's alerts (Lock all only) and the other tools +//! stay as they are. + +use egui::Modifiers; +use serde_json::json; + +use super::brush_refusal_alert_tests::{active, alerts, app, steps, stroke}; +use super::*; +use crate::canvas::{ToolEvent, tool_event}; +use crate::control::{ControlRequest, Reply, handle}; + +/// A Paint Bucket click on the painted layer. +fn click(app: &mut PhotocraftApp) { + tool_event(app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 30.0, y: 30.0 }, Modifiers::NONE); +} + +/// The active layer's pixel at the click point; a group has no surface, hence `None`. +fn pixel(app: &PhotocraftApp) -> Option<[f32; 4]> { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap())?.surface().map(|s| s.rgba(30, 30)) +} + +/// A named layer's pixel at the click point - the byte check when the active layer is a group. +fn child_rgba(app: &PhotocraftApp, id: photocraft_doc::LayerId) -> [f32; 4] { + let st = app.session.active().unwrap(); + st.doc.layer(id).and_then(|l| l.surface()).map(|s| s.rgba(30, 30)).unwrap_or([0.0; 4]) +} + +/// The click opens one alert with `want` and changes nothing: the same pixels, no History step, the +/// same active layer. OK closes the alert. +fn refused(app: &mut PhotocraftApp, want: &str) { + let before = (steps(app), pixel(app), active(app)); + click(app); + assert_eq!(alerts(app), [want], "the alert, once"); + assert_eq!((steps(app), pixel(app), active(app)), before, "nothing filled, no History step, the target stays selected"); + let id = app.framework.dialogs.open_dialogs().first().map(|d| d.id).unwrap(); + let ctx = app.ctx().clone(); + crate::dialogs::confirm(app, &ctx, id).unwrap(); + assert!(alerts(app).is_empty(), "OK closes the alert"); +} + +#[test] +fn a_hidden_target_layer() { + let mut app = app(Tool::PaintBucket); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + refused(&mut app, "Could not use the paint bucket because the target layer is hidden."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); + assert_eq!( + photocraft_engine::hidden_target::HIDDEN, + "Could not complete your request because the target layer is hidden.", + "the engine's shared text stays as it is" + ); +} + +#[test] +fn lock_all_and_lock_image_pixels() { + // Both are the one "the layer is locked." alert in the reference application. + for lock in ["all", "pixels"] { + let mut bucket = app(Tool::PaintBucket); + bucket.run("layer.lockLayers", json!({ lock: true })).unwrap(); + refused(&mut bucket, "Could not use the paint bucket because the layer is locked."); + } +} + +#[test] +fn a_group_is_active() { + // The group holds the painted child layer, so its pixels are the byte check: a group has no + // surface of its own and the group's own check would be vacuous. + let mut app = app(Tool::PaintBucket); + let child = app.session.active().unwrap().active_layer.unwrap(); + let red = child_rgba(&app, child); + assert!(red[0] > 0.8 && red[3] > 0.99, "the child starts painted red: {red:?}"); + app.run("layer.groupLayers", json!({})).unwrap(); + // Once, with the measured wording: `press_refused` answers before `refuse_group` can add its + // own alert. + refused(&mut app, "Could not use the paint bucket because the pixels in a group cannot be edited without merging the group."); + assert_eq!(child_rgba(&app, child), red, "the child layer's pixels inside the group stay as they were"); +} + +#[test] +fn a_group_inside_a_group_is_refused_once() { + // Neighbour (pattern 3): the active inner group sits inside the outer group, which holds a + // painted child; neither group has pixels of its own at the click, so the byte check is the + // child's. + let mut app = app(Tool::PaintBucket); + app.run("layer.new.group", json!({})).unwrap(); + app.run("layer.new.group", json!({})).unwrap(); + let inner = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let child = app.session.active().unwrap().active_layer.unwrap(); + app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + app.run("layer.select", json!({"layer": inner.0})).unwrap(); + let st = app.session.active().unwrap(); + let path = st.doc.path_of(st.active_layer.unwrap()).unwrap(); + assert_eq!(path.len(), 2, "the active group sits inside the outer group: {path:?}"); + let red = child_rgba(&app, child); + assert!(red[0] > 0.8 && red[3] > 0.99, "the child inside the groups starts painted red: {red:?}"); + refused(&mut app, "Could not use the paint bucket because the pixels in a group cannot be edited without merging the group."); + assert_eq!(child_rgba(&app, child), red, "the child layer's pixels inside the groups stay as they were"); +} + +#[test] +fn the_alert_is_listed_and_confirmed_over_the_control_channel() { + let ctx = egui::Context::default(); + let mut app = app(Tool::PaintBucket); + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + click(&mut app); + let mut call = |method: &str, params: serde_json::Value| { + let (req, _rx) = ControlRequest::new(method, params); + match handle(&mut app, &ctx, &req) { + Reply::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } + }; + let inspect = call("ui.inspect", json!({})); + let dialog = &inspect["result"]["dialogs"][0]; + assert_eq!(dialog["fields"]["message"], "Could not use the paint bucket because the layer is locked.", "{inspect}"); + assert_eq!(call("ui.dialog.confirm", json!({"dialog": dialog["id"]}))["ok"], true); + assert!(alerts(&app).is_empty()); +} + +#[test] +fn a_click_on_a_visible_unlocked_layer_still_fills() { + // The guard for the whole change: the painting path is untouched. + let mut app = app(Tool::PaintBucket); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1, "the fill was applied"); + let st = app.session.active().unwrap(); + let surface = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + for (x, y) in [(30, 30), (2, 2), (61, 61)] { + let [r, g, b, a] = surface.rgba(x, y); + assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "the black foreground at ({x}, {y}): {:?}", [r, g, b, a]); + } +} + +#[test] +fn lock_transparent_pixels_still_fills_the_opaque_pixels() { + let mut app = app(Tool::PaintBucket); + app.run("layer.lockLayers", json!({"transparency": true})).unwrap(); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1); + let [r, g, b, a] = pixel(&app).unwrap(); + assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "the opaque region filled black: {:?}", [r, g, b, a]); +} + +#[test] +fn lock_position_still_fills() { + let mut app = app(Tool::PaintBucket); + app.run("layer.lockLayers", json!({"position": true})).unwrap(); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1); + let [r, g, b, a] = pixel(&app).unwrap(); + assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "filled black: {:?}", [r, g, b, a]); +} + +#[test] +fn a_pixel_layer_inside_a_group_fills_normally() { + let mut app = app(Tool::PaintBucket); + app.run("layer.new.group", json!({})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + let path = st.doc.path_of(id).unwrap(); + assert_eq!(path.len(), 2, "the new layer is a child of the group: {path:?}"); + assert!(st.doc.layer_at(&path[..1]).is_some_and(|l| l.is_group()), "its parent is a group"); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1, "the click filled the layer inside the group"); + let [r, g, b, a] = pixel(&app).unwrap(); + assert!(a > 0.99 && r < 0.01 && g < 0.01 && b < 0.01, "filled black: {:?}", [r, g, b, a]); +} + +#[test] +fn a_group_s_targeted_mask_takes_a_step_that_fills_nothing() { + // Not measured: keeps today's behaviour as a whole. Measured on `main` before and after this + // change: the click opens no alert (the alert path only speaks for pixel targets), the engine + // adds one "Paint Bucket" state, and its command answers `filled: true` while leaving the + // all-white mask's samples as they are - all pinned here, so the name says exactly what today + // is: a step, and no fill. + let mut app = app(Tool::PaintBucket); + app.run("layer.new.group", json!({})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.ui.mask_target = true; + app.sync_mask_targets(); + assert_eq!(crate::canvas::paint_target(&app), json!("mask"), "the group's mask is targeted"); + let before = steps(&app); + click(&mut app); + assert!(alerts(&app).is_empty(), "no refusal alert on a mask target: {:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1, "the engine's own step lands as today"); + let labels = app.run("document.inspect", json!({})).unwrap()["history"].as_array().cloned().unwrap_or_default(); + assert_eq!(labels.last(), Some(&json!("Paint Bucket")), "the step the click added carries the engine's own label"); + // The command's own answer, pinned once through the engine: it claims a fill and writes nothing. + let reply = app.run("paint.bucket", json!({"x": 30, "y": 30, "target": "mask"})).unwrap(); + assert_eq!(reply["filled"], json!(true), "the engine reports filled: true, as on main"); + assert_eq!(steps(&app), before + 2, "and that call adds its step too"); + let st = app.session.active().unwrap(); + let mask = st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); + for (x, y) in [(30, 30), (2, 2), (61, 61)] { + assert_eq!(mask.surface.sample_channel(x, y, 0), 1.0, "the mask samples stay white at ({x}, {y}) as on main"); + } +} + +#[test] +fn the_brush_alerts_stay_as_they_are_and_the_other_tools_stay_quiet() { + // The Brush (#11898): Lock all only, never Lock Image Pixels. + let mut brush = app(Tool::Brush); + brush.run("layer.lockLayers", json!({"all": true})).unwrap(); + stroke(&mut brush); + assert_eq!(alerts(&brush), ["Could not use the brush tool because the layer is locked."], "the Brush's Lock all alert is unchanged"); + let mut brush = app(Tool::Brush); + brush.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + stroke(&mut brush); + assert!(alerts(&brush).is_empty(), "the Brush keeps no alert for Lock Image Pixels: {:?}", alerts(&brush)); + // The Dodge tool has no layer alerts: a hidden target stays in the status bar. + let mut dodge = app(Tool::Dodge); + let id = active(&dodge); + dodge.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + stroke(&mut dodge); + assert!(alerts(&dodge).is_empty()); + assert_eq!(dodge.ui.status, photocraft_engine::hidden_target::HIDDEN); +} diff --git a/crates/ui-egui/src/panels/actions/runner.rs b/crates/ui-egui/src/panels/actions/runner.rs index 96cc04fcd3..e7ef3a91a1 100644 --- a/crates/ui-egui/src/panels/actions/runner.rs +++ b/crates/ui-egui/src/panels/actions/runner.rs @@ -772,12 +772,24 @@ pub(crate) fn report_play(app: &mut PhotocraftApp, v: &Value) { }; let step = failed.get("step").and_then(Value::as_u64).unwrap_or(0); let id = failed.get("id").and_then(Value::as_str).unwrap_or(""); - let error = failed.get("error").and_then(Value::as_str).unwrap_or(""); + let error = step_error(failed.get("error").and_then(Value::as_str).unwrap_or("")); let template = "Step {step} ({id}) failed: {error}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("step", &(step + 1).to_string()), ("id", id), ("error", error)]); app.ui.status_error = true; } +/// A failed step's `error` in the UI language when the engine's message is one the shell spells out, otherwise as the +/// engine gave it. Automation clients keep the engine's English. +fn step_error(error: &str) -> &str { + if error.ends_with(photocraft_engine::atn_cmds::CAF_CUSTOM_AREA_NOT_REMEMBERED) { + // The engine's text, as a literal the translation coverage report collects (#14254). + return tl!( + "This step plays with the remembered Content-Aware Fill settings, and their Custom sampling area isn't remembered. Fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again." + ); + } + error +} + /// Resume the recording a paused call suspended and journal that call, once. fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) { let Some(owner) = owner else { return }; diff --git a/crates/ui-egui/src/panels/channels_panel.rs b/crates/ui-egui/src/panels/channels_panel.rs index 2d4dc86584..356abab352 100644 --- a/crates/ui-egui/src/panels/channels_panel.rs +++ b/crates/ui-egui/src/panels/channels_panel.rs @@ -484,7 +484,7 @@ pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: & } return true; } - let mods = craft::ui::runtime::pointer::frame(ctx).mods; + let mods = craft::ui::runtime::pointer::mods(ctx); if let Some(event) = command.event(&rows(app), mods) { apply(app, ctx, event); } diff --git a/crates/ui-egui/src/panels/color_hud.rs b/crates/ui-egui/src/panels/color_hud.rs index 11a3b3b490..81f9013939 100644 --- a/crates/ui-egui/src/panels/color_hud.rs +++ b/crates/ui-egui/src/panels/color_hud.rs @@ -125,7 +125,7 @@ mod tests { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/panels/color_panel_ui.rs b/crates/ui-egui/src/panels/color_panel_ui.rs index dc1b08d934..e854766d01 100644 --- a/crates/ui-egui/src/panels/color_panel_ui.rs +++ b/crates/ui-egui/src/panels/color_panel_ui.rs @@ -15,7 +15,7 @@ pub fn persist(app: &mut PhotocraftApp) { } let Ok(now) = serde_json::to_value(app.ui.color_panel) else { return }; if stored != now { - app.session.prefs.edit(|p| p.color_panel = now.clone()); + app.session.prefs.remember(|p| p.color_panel = now.clone()); } app.ui.color_panel_synced = Some(now); } diff --git a/crates/ui-egui/src/panels/layer_reveal.rs b/crates/ui-egui/src/panels/layer_reveal.rs index fddbd6cc8a..284f495a3e 100644 --- a/crates/ui-egui/src/panels/layer_reveal.rs +++ b/crates/ui-egui/src/panels/layer_reveal.rs @@ -6,7 +6,7 @@ //! //! The command dispatch takes a [`mark`] before a command and calls [`file`] after it; when the //! active layer moved, the reveal waits in `PhotocraftApp::pending_reveal` until the panel next -//! draws and [`take`]s it, so a hidden panel reveals the layer when it is shown again. +//! draws and applies it, so a hidden panel reveals the layer when it is shown again. //! //! Only a change of the active layer reveals: closing the group that holds it, or scrolling //! away, is left alone until the next change. @@ -50,9 +50,9 @@ pub(crate) fn file(app: &mut PhotocraftApp, before: Mark) { app.pending_reveal = Some((id, groups)); } -/// The pending reveal, for the Layers panel's draw: the layer and what its closed parent groups -/// do. The first pass of a frame takes it, so a second pass in the same frame reveals nothing -/// again. +/// The pending reveal: the layer and what its closed parent groups do. The Layers panel takes it +/// once its real run applied it (`LayersOutput::requests_taken`), so a measuring run or a later +/// pass of the same frame reveals nothing again. pub(crate) fn take(app: &mut PhotocraftApp) -> Option<(LayerId, Groups)> { app.pending_reveal.take() } diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 9ec0163369..59a627b4c0 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -23,7 +23,7 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { use super::layers_tree::{self, PhotoThumbs}; // A Move-way pick of a layer opens its groups only when the Move option says so (#11381). - let reveal = crate::layer_reveal::take(app); + let reveal = app.pending_reveal; let ctx = ui.ctx().clone(); // Thumbnail Contents is the clip preference alone, so the panel reads it each pass. app.ui.layers_settings.options.thumbnail_contents = crate::layers_panel_ui::thumbnail_contents(app); @@ -62,8 +62,11 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { panel = panel.start_rename(id); } let out = panel.show(ui); - app.find_layers_focus = false; - app.layers_rename = None; + if out.requests_taken { + crate::layer_reveal::take(app); + app.find_layers_focus = false; + app.layers_rename = None; + } if filter != before { app.ui.layer_filter = filter; } diff --git a/crates/ui-egui/src/panels/layers_events.rs b/crates/ui-egui/src/panels/layers_events.rs index 36344f5f94..21dbd68b49 100644 --- a/crates/ui-egui/src/panels/layers_events.rs +++ b/crates/ui-egui/src/panels/layers_events.rs @@ -324,6 +324,14 @@ fn target_on_click(app: &mut PhotocraftApp, l: &Layer, was_active: bool, part: O return; } match part { + // A second click on the targeted vector mask un-targets it: the pixels take the target and + // Paths drops the mask's path (#16783). The layer mask stays targeted instead. + Some(LayerPart::VectorMask) if was_active && app.ui.vector_mask_target => { + if app.ui.selected_path.as_deref() == Some("layer") { + app.ui.selected_path = None; + } + actions.push(("ui.vectorMaskTarget".into(), json!(false))); + } Some(LayerPart::VectorMask) => { app.ui.selected_path = Some("layer".into()); actions.push(("ui.vectorMaskTarget".into(), json!(true))); @@ -371,7 +379,11 @@ fn activate( let command = match on { ActivateOn::Thumbnail(LayerPart::LayerMask | LayerPart::VectorMask) => { let kind = if on == ActivateOn::Thumbnail(LayerPart::VectorMask) { MaskKind::Vector } else { MaskKind::Pixel }; - actions.push((if kind == MaskKind::Vector { "ui.vectorMaskTarget" } else { "ui.maskTarget" }.into(), json!(true))); + // A plain double click's first click has already targeted the vector mask, or un-targeted the + // targeted one, which this leaves as it is (#16783). + if kind == MaskKind::Pixel || !ctx.input(|i| i.modifiers.is_none()) { + actions.push((if kind == MaskKind::Vector { "ui.vectorMaskTarget" } else { "ui.maskTarget" }.into(), json!(true))); + } match crate::mask_thumbs_ui::double_click_command(app, kind) { Some((cmd, val)) => actions.push((cmd.into(), val)), None => actions.push(("ui.properties".into(), json!(true))), @@ -669,3 +681,7 @@ pub(crate) fn run_actions(app: &mut PhotocraftApp, ctx: &egui::Context, actions: let _ = app.run(&id, p); } } + +#[cfg(test)] +#[path = "layers_vector_mask_click_tests.rs"] +mod layers_vector_mask_click_tests; diff --git a/crates/ui-egui/src/panels/layers_vector_mask_click_tests.rs b/crates/ui-egui/src/panels/layers_vector_mask_click_tests.rs new file mode 100644 index 0000000000..2d09ac1c41 --- /dev/null +++ b/crates/ui-egui/src/panels/layers_vector_mask_click_tests.rs @@ -0,0 +1,87 @@ +//! #16783: a second click on the targeted vector mask thumbnail un-targets it, while the layer mask +//! stays targeted. Each click is a `LayersEvent::Select` sent through `apply_layers_events`, as the +//! panel reports it. + +use craft::behavior::SelectionChange; +use craft::layers::ui::panel::{ActivateOn, LayerSelect, LayersEvent}; +use craft::layers::ui::tree::{LayerPart, LayerRowKey}; +use photocraft_doc::LayerId; +use serde_json::json; + +use super::apply_layers_events; +use super::tests::session; +use crate::PhotocraftApp; + +fn app_of(s: photocraft_engine::Session) -> Box { + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.background_jobs = false; + app.sync_views(); + app +} + +fn click(app: &mut PhotocraftApp, layer: u64, part: LayerPart) { + let ctx = app.ctx().clone(); + let event = LayersEvent::Select(LayerSelect::new(SelectionChange::Set(vec![LayerId(layer)]), Some(part))); + apply_layers_events(app, &ctx, vec![event]); +} + +/// A double click as the panel reports it: the first click selects, the second only activates. +fn double_click(app: &mut PhotocraftApp, layer: u64, part: LayerPart) { + click(app, layer, part); + let ctx = app.ctx().clone(); + apply_layers_events(app, &ctx, vec![LayersEvent::activate(LayerRowKey::Layer(LayerId(layer)), ActivateOn::Thumbnail(part))]); +} + +fn vector_mask_targeted(app: &PhotocraftApp) -> bool { + app.ui.vector_mask_target && !app.ui.mask_target && app.ui.selected_path.as_deref() == Some("layer") +} + +#[test] +fn a_second_click_on_the_targeted_vector_mask_untargets_it() { + let (s, masked, _) = session(); + let mut app = app_of(s); + click(&mut app, masked, LayerPart::VectorMask); + assert!(vector_mask_targeted(&app)); + click(&mut app, masked, LayerPart::VectorMask); + assert!(!app.ui.vector_mask_target && !app.ui.mask_target, "the layer's pixels are the target"); + assert_eq!(app.ui.selected_path, None, "Paths no longer selects the mask's path"); + assert_eq!(crate::canvas::paint_target(&app), json!("pixels")); + assert_eq!(app.session.active().unwrap().active_layer, Some(LayerId(masked)), "the layer stays active"); + click(&mut app, masked, LayerPart::VectorMask); + assert!(vector_mask_targeted(&app), "a third click targets it again"); +} + +#[test] +fn a_double_click_toggles_the_vector_mask_target_with_its_first_click() { + let (s, masked, _) = session(); + let mut app = app_of(s); + double_click(&mut app, masked, LayerPart::VectorMask); + assert!(vector_mask_targeted(&app), "on an untargeted vector mask, the double click targets it"); + double_click(&mut app, masked, LayerPart::VectorMask); + assert!(!app.ui.vector_mask_target && !app.ui.mask_target, "on the targeted one, its first click un-targets it"); + assert_eq!(app.ui.selected_path, None); +} + +#[test] +fn a_second_click_on_the_targeted_layer_mask_keeps_it_targeted() { + let (s, masked, _) = session(); + let mut app = app_of(s); + click(&mut app, masked, LayerPart::LayerMask); + click(&mut app, masked, LayerPart::LayerMask); + assert!(app.ui.mask_target && !app.ui.vector_mask_target); + assert_eq!(crate::canvas::paint_target(&app), json!("mask")); +} + +#[test] +fn the_vector_mask_of_another_layer_is_targeted_while_one_is_targeted() { + let (mut s, masked, _) = session(); + let other = s.execute("layer.new.layer", json!({"name": "Other"})).unwrap()["layer"].as_u64().unwrap(); + let path = json!({"subpaths": [{"knots": [[10, 10], [60, 10], [60, 60]]}]}); + s.execute("layer.vectorMask.add", json!({"layer": other, "path": path})).unwrap(); + s.execute("layer.select", json!({"layer": masked})).unwrap(); + let mut app = app_of(s); + click(&mut app, masked, LayerPart::VectorMask); + click(&mut app, other, LayerPart::VectorMask); + assert_eq!(app.session.active().unwrap().active_layer, Some(LayerId(other))); + assert!(vector_mask_targeted(&app), "the first click on another layer's vector mask targets it"); +} diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 961b2318ef..14c00e2281 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -262,27 +262,43 @@ fn stamp_members(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) { // Pattern Stamp's list has Behind, greyed on the Background. let entries = fill::mode_entries(tool, crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind), threshold); if !entries.is_empty() { - let current = - if tool == Tool::PatternStamp && brush.behind { PaintMode::Behind } else { PaintMode::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)) }; + let current = if tool == Tool::Healing && app.ui.tool_options.healing_replace { + PaintMode::HealingReplace + } else if tool == Tool::PatternStamp && brush.behind { + PaintMode::Behind + } else { + PaintMode::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)) + }; let picked = labelled(ui, tl!("Mode"), |ui| { let select = fill::mode_select(Bind::given(current), &entries); let select = if tool == Tool::CloneStamp { select.tooltip(tl!("Painting Mode")) } else { select }; select.show(ui) }); if let Some(mode) = picked.and_then(|shown| shown.events.value().cloned()) { - let mut after = brush.clone(); - match mode { - PaintMode::Blend(blend) => { - after.mode = blend; - if tool == Tool::PatternStamp { - after.behind = false; - } + if mode == PaintMode::HealingReplace { + // Replace (#12101): a tool option like the painting tools' Clear, with no brush + // value to write: the next stroke carries mode:"replace", and picking a Mode adds + // no History step. + app.ui.tool_options.healing_replace = true; + } else { + if tool == Tool::Healing { + // Any of the seven blend modes leaves Replace (#12101). + app.ui.tool_options.healing_replace = false; } - PaintMode::Behind => after.behind = true, - PaintMode::Clear => {} + let mut after = brush.clone(); + match mode { + PaintMode::Blend(blend) => { + after.mode = blend; + if tool == Tool::PatternStamp { + after.behind = false; + } + } + PaintMode::Behind => after.behind = true, + PaintMode::Clear | PaintMode::HealingReplace => {} + } + // A pick is one step of its own. + crate::brush_panel::commit_keyed(app, &brush, &after, None); } - // A pick is one step of its own. - crate::brush_panel::commit_keyed(app, &brush, &after, None); } } // Both stamps use whole percents. Only Clone Stamp alerts on an out-of-range commit (#12607). @@ -345,8 +361,8 @@ pub(super) fn labelled(ui: &mut egui::Ui, label: &str, mut add: impl FnMut(&m } /// A check box named `label` over `value`. -pub(super) fn check(ui: &mut egui::Ui, label: &str, value: &mut bool) { - Checkbox::new(Bind::bound(value)).label(label.to_owned()).show(ui); +pub(super) fn check(ui: &mut egui::Ui, label: &str, value: Bind<'_, bool>) { + Checkbox::new(value).label(label.to_owned()).show(ui); } /// A number field named `label` over `value` (in `unit` when it is not empty), limited to `range`. The events of this @@ -417,3 +433,7 @@ mod clone_stamp_fields_tests; #[cfg(test)] #[path = "art_history_bar_controls_tests.rs"] mod art_history_bar_controls_tests; + +#[cfg(test)] +#[path = "../healing_mode_menu_tests.rs"] +mod healing_mode_menu_tests; diff --git a/crates/ui-egui/src/panels/options_bar/fill.rs b/crates/ui-egui/src/panels/options_bar/fill.rs index 61e9ff4df5..4bae6f8d9e 100644 --- a/crates/ui-egui/src/panels/options_bar/fill.rs +++ b/crates/ui-egui/src/panels/options_bar/fill.rs @@ -1,14 +1,16 @@ //! The Paint Bucket's members of the options bar, and the Mode list of the Paint Bucket and the stamp tools. -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::choice::Checkbox; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, bind_tracked}; use craft::ui::patterns::blend_keys::{BlendKeyEntry, blend_entries}; use craft::ui::pickers::Select; use photocraft_doc::BlendMode; +use super::labelled; use super::paint::PaintMode; -use super::{check, labelled, number_field}; use crate::PhotocraftApp; use crate::state::Tool; +use crate::tools::option_cells::number; /// The text of a Mode entry. fn label_of(mode: PaintMode) -> String { @@ -16,6 +18,7 @@ fn label_of(mode: PaintMode) -> String { PaintMode::Blend(blend) => tl!(blend.label()).to_owned(), PaintMode::Behind => tl!("Behind").to_owned(), PaintMode::Clear => tl!("Clear").to_owned(), + PaintMode::HealingReplace => tl!("Replace").to_owned(), } } @@ -26,6 +29,25 @@ fn label_of(mode: PaintMode) -> String { pub(crate) fn mode_entries(tool: Tool, behind_enabled: bool, threshold: bool) -> Vec> { static CACHE: crate::i18n::LangCache<(Tool, bool, bool), Vec>> = crate::i18n::LangCache::new(); CACHE.get_or_build((tool, behind_enabled, threshold), || { + if tool == Tool::Healing { + // The Healing Brush's measured list (#12101): Normal, Replace, a rule, Multiply, + // Screen, Darken, Lighten, a rule, Color, Luminosity. Not the blend-group rules: the + // reference starts its groups elsewhere in this short list. Replace has no letter: the + // ⇧⌥ keys and the ⇧+ / ⇧− cycle keep the seven blend modes. + let blend = |b: BlendMode| Entry::new(PaintMode::Blend(b), label_of(PaintMode::Blend(b))); + return vec![ + blend(BlendMode::Normal), + Entry::new(PaintMode::HealingReplace, label_of(PaintMode::HealingReplace)), + Entry::separator(), + blend(BlendMode::Multiply), + blend(BlendMode::Screen), + blend(BlendMode::Darken), + blend(BlendMode::Lighten), + Entry::separator(), + blend(BlendMode::Color), + blend(BlendMode::Luminosity), + ]; + } let keyed: Vec> = if tool == Tool::PatternStamp { crate::brush_mode_menu::pattern_stamp_choices() .into_iter() @@ -60,32 +82,66 @@ pub(crate) fn mode_select<'a>(mode: Bind<'a, PaintMode>, entries: &'a [Entry o.bucket_clear = true, - PaintMode::Blend(blend) => { - o.bucket_clear = false; - o.bucket_blend_mode = blend; + // The Source dropdown stands alone, without a caption, as in the reference. + Select::new(tl!("Source").to_owned(), bind_tracked!(app.ui.tool_options => bucket_fill_pattern), &sources) + .tooltip(tl!("Set source for fill area").to_owned()) + .show(ui); + let o = &app.ui.tool_options; + let shown = if o.bucket_clear { PaintMode::Clear } else { PaintMode::Blend(o.bucket_blend_mode) }; + let mut mode = shown; + labelled(ui, tl!("Mode"), |ui| mode_select(Bind::bound(&mut mode), &entries).tooltip(tl!("Fill Mode").to_owned()).show(ui)); + if mode != shown { + let o = &mut app.ui.tool_options; + match mode { + PaintMode::Clear => o.bucket_clear = true, + PaintMode::Blend(blend) => { + o.bucket_clear = false; + o.bucket_blend_mode = blend; + } + PaintMode::Behind => {} + // Replace belongs to the Healing Brush's list, never the Paint Bucket's. + PaintMode::HealingReplace => {} } - PaintMode::Behind => {} } - if let Some(opacity) = number_field(ui, tl!("Opacity"), o.fill_opacity, 1.0..=100.0, "%").landed() { - o.fill_opacity = *opacity; + let opacity = number(tl!("Opacity"), bind_tracked!(app.ui.tool_options => fill_opacity), 1.0..=100.0) + .whole() + .unit("%") + .tooltip(tl!("Set opacity for fill")) + .show(ui) + .out_of_range; + let tolerance = number(tl!("Tolerance"), bind_tracked!(app.ui.tool_options => tolerance), 0.0..=255.0) + .whole_alerting_fractions() + .tooltip(tl!("Range of colors to fill")) + .show(ui); + let (anti_alias, contiguous, all_layers) = bind_tracked!(app.ui.tool_options => anti_alias, contiguous, sample_all.paint_bucket); + Checkbox::new(anti_alias).label(tl!("Anti-alias").to_owned()).tooltip(tl!("Smoothes edge transition").to_owned()).show(ui); + Checkbox::new(contiguous).label(tl!("Contiguous").to_owned()).tooltip(tl!("Fill only contiguous pixels").to_owned()).show(ui); + Checkbox::new(all_layers).label(tl!("All Layers").to_owned()).tooltip(tl!("Fill composite image").to_owned()).show(ui); + if opacity.is_some() { + let _ = crate::dialogs::alerts::alert(app, tl!(PAINT_BUCKET_OPACITY_ALERT)); + } else if let Some(alert) = tolerance.out_of_range { + // The framework words a whole-number field without a unit as the reference does: + // "An integer between 0 and 255 is required. Closest value inserted." + crate::tools::option_cells::range_alert(app, ui, &alert); + } else if tolerance.rounded { + let _ = crate::dialogs::alerts::alert(app, tl!(PAINT_BUCKET_TOLERANCE_ALERT)); } - if let Some(tolerance) = number_field(ui, tl!("Tolerance"), o.tolerance, 0.0..=255.0, "").landed() { - o.tolerance = *tolerance; - } - check(ui, tl!("Anti-alias"), &mut o.anti_alias); - check(ui, tl!("Contiguous"), &mut o.contiguous); - check(ui, tl!("All Layers"), &mut o.sample_all.paint_bucket); } diff --git a/crates/ui-egui/src/panels/options_bar/navigate.rs b/crates/ui-egui/src/panels/options_bar/navigate.rs index d05faa82cf..ee64c9e385 100644 --- a/crates/ui-egui/src/panels/options_bar/navigate.rs +++ b/crates/ui-egui/src/panels/options_bar/navigate.rs @@ -1,7 +1,7 @@ //! The options bar's members of the Move, Eyedropper, Zoom, Rotate View and Hand tools. use craft::ui::canvas::{NavigateBar, NavigationOptions}; -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, bind_tracked}; use craft::ui::display::Divider; use craft::ui::pickers::Select; @@ -21,12 +21,12 @@ pub(super) fn members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// Auto-Select, its target, Show Transform Controls, then the align strip. fn move_members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let o = &mut app.ui.tool_options; - check(ui, tl!("Auto-Select:"), &mut o.move_auto_select); + let (auto_select, target, transform) = bind_tracked!(app.ui.tool_options => move_auto_select, move_target, move_show_transform); + check(ui, tl!("Auto-Select:"), auto_select); let targets = [Entry::new("group".to_owned(), tl!("Group").to_owned()), Entry::new("layer".to_owned(), tl!("Layer").to_owned())]; - Select::new(tl!("Auto-Select:").to_owned(), Bind::bound(&mut o.move_target), &targets).show(ui); + Select::new(tl!("Auto-Select:").to_owned(), target, &targets).show(ui); Divider::vertical().show(ui); - check(ui, tl!("Show Transform Controls"), &mut o.move_show_transform); + check(ui, tl!("Show Transform Controls"), transform); Divider::vertical().show(ui); crate::align_bar::show(app, ui); } @@ -60,7 +60,9 @@ fn view_members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Zoom Out is the bar's `out`; the tool keeps the direction as `zoom_in`. let mut out = !app.ui.tool_options.zoom_in; let shown = NavigateBar::zoom(Bind::bound(&mut view), target, &mut options, Bind::bound(&mut out)).show(ui); - app.ui.tool_options.zoom_in = !out; + if app.ui.tool_options.zoom_in == out { + app.ui.tool_options.zoom_in = !out; + } crate::chrome_ui::zoom_alert(app, shown.invalid_zoom); write_view(app, index, &view, !shown.view.is_empty()); } else { diff --git a/crates/ui-egui/src/panels/options_bar/paint.rs b/crates/ui-egui/src/panels/options_bar/paint.rs index c98fecb094..765873a3df 100644 --- a/crates/ui-egui/src/panels/options_bar/paint.rs +++ b/crates/ui-egui/src/panels/options_bar/paint.rs @@ -28,6 +28,9 @@ pub(crate) enum PaintMode { Behind, /// Paint transparency. Clear, + /// The Healing Brush's Replace (#12101): copy the source without healing. A tool option, not a + /// brush value; only the Healing Brush's Mode list offers it. + HealingReplace, } impl PaintMode { @@ -37,6 +40,7 @@ impl PaintMode { PaintMode::Blend(m) => m.label(), PaintMode::Behind => "Behind", PaintMode::Clear => "Clear", + PaintMode::HealingReplace => "Replace", } } } @@ -209,6 +213,9 @@ fn apply_values(app: &mut PhotocraftApp, tool: Tool, brush: &mut BrushSettings, brush.mode = BlendMode::Normal; } PaintMode::Clear => brush.behind = false, + // Replace is the Healing Brush's row; a paint-bar tool's list never shows it, so + // `after.mode` is never this here. + PaintMode::HealingReplace => {} } } } diff --git a/crates/ui-egui/src/panels/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs index b58b191e24..b2ebeac752 100644 --- a/crates/ui-egui/src/panels/panel_docking.rs +++ b/crates/ui-egui/src/panels/panel_docking.rs @@ -221,8 +221,7 @@ struct Panels<'a> { } impl DockPanels for Panels<'_> { - /// A panel body is a memoized view keyed by its version (#16118); the canvas shows state that changes without a - /// command (the view, redraw progress, animation and job overlays), so it runs every pass. + /// A panel body is a memoized view keyed by its version (#16118). fn body(&mut self, panel: &String, ui: &mut egui::Ui, _: &mut BodyCx<'_>) { if panel == CANVAS { body(self.app, ui, panel); @@ -231,6 +230,19 @@ impl DockPanels for Panels<'_> { } } + /// The version of what the dock shows for a panel, which keys its column and the docked tree: the canvas's is the + /// document area's, which also keys the area's own view (`region_versions::canvas`). A panel whose body does not show + /// (a tab behind another, in a minimized group or an icon column without its flyout) shows only its title and icon, + /// which every version holds. + fn content(&self, panel: &String) -> Option { + match panel.as_str() { + CANVAS => Some(super::region_versions::canvas(self.app)), + TOOLBAR => Some(super::region_versions::toolbar(self.app)), + id if !is_front(self.app, id) => Some(super::region_versions::hidden_panel(self.app)), + id => Some(super::region_versions::panel(self.app, id)), + } + } + /// The canvas group is the document area: it draws its own tabs and documents in the group's rect. The toolbar's /// group is its rail, which takes the group's full rect and measures its height at a width. fn group_view(&mut self, panels: &[String], _: usize, ui: &mut egui::Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { diff --git a/crates/ui-egui/src/panels/preset_panels/tool_presets.rs b/crates/ui-egui/src/panels/preset_panels/tool_presets.rs index 8e8150e76f..69a3b6bd85 100644 --- a/crates/ui-egui/src/panels/preset_panels/tool_presets.rs +++ b/crates/ui-egui/src/panels/preset_panels/tool_presets.rs @@ -39,7 +39,7 @@ pub fn select(app: &mut PhotocraftApp, name: &str) { } } if let Ok(opts) = serde_json::from_value(cur) { - app.ui.tool_options = opts; + *app.ui.tool_options = opts; } } // As the options bar does: a crop preset's ratio (or W x H) fits the frame at once. @@ -132,7 +132,7 @@ mod tests { let mut flipped = serde_json::to_value(&app.ui.tool_options).unwrap(); flip_bools(&mut flipped); flipped["feather"] = json!(0.0); - app.ui.tool_options = serde_json::from_value(flipped.clone()).unwrap(); + *app.ui.tool_options = serde_json::from_value(flipped.clone()).unwrap(); select(&mut app, &name); let after = serde_json::to_value(&app.ui.tool_options).unwrap(); assert_eq!(after["feather"], json!(5.0)); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 08dd6ac85c..e49b0666d8 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -58,19 +58,20 @@ fn kind_label(layer: &Layer) -> String { /// mask targets, the layer the panel was opened for) keys the inspector, so a field's typing or /// scrub state stays with its layer. pub(super) fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - // A run that shows no adjustment session ends the one kept (`PhotocraftApp::properties_hidden`). - app.properties_tracked = false; - body(app, ui); - if !app.properties_tracked { + // A run that shows no adjustment layer's controls ends the Reset session kept (`PhotocraftApp::properties_hidden`). + // What the run shows decides, not whether the controls' code ran: a pass that reuses the inspector's measurement + // runs none of its content. + if !body(app, ui) { app.properties_hidden = app.properties_hidden.saturating_add(2); } } -fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { +/// The panel's inspector; whether it shows an adjustment layer's controls. +fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { let inspector = Inspector::new(tl!("Properties")).empty(tl!("No properties")); let Some(st) = app.session.active() else { inspector.show(ui, |_, _| {}); - return; + return false; }; let doc = st.doc.clone(); let active = st.active_layer; @@ -85,6 +86,7 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { _ if crate::doc_props_ui::shows_document(&doc, active) => Body::Document, _ => Body::Layer, }; + let adjustment = shown == Body::Layer && layer.is_some_and(|l| matches!(l.content, LayerContent::Adjustment(_))); let mut inspector = inspector.target(target); // The Document properties are headed by the document, as production's panel is. inspector = match layer { @@ -108,6 +110,7 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Body::Layer => layer_body(app, ui, layer), } }); + adjustment } /// The document's properties, with Align and Distribute above them while several layers are selected. diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs index 31abdea38b..63e0688651 100644 --- a/crates/ui-egui/src/panels/region_versions.rs +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -1,49 +1,20 @@ -//! The shell's title bar and options bar and every docked panel body as memoized views (#16118). The shell runs a slot -//! every pass and the dock a panel body, and leave memoizing to the app; each reads the whole app, so it is a `MemoView` -//! whose key is a version of what it shows: while the version is the same and no input reaches the slot, the frame adds -//! its last run again instead of running every control in it. The status bar is a memoized view of its own -//! (`status_bar::StatusProps`), over the values it shows. A version covers the app data its slot shows that can change while no -//! input reaches the slot: what a command changes, the active document and layer and the tool in every version; what -//! the slot shows of the canvas view, a job or the brush and colours; and what an edit elsewhere changes without a -//! command, such as a box or pin dragged on the canvas. Input inside a slot runs it whatever its version, and so does a -//! repaint it asks for itself. +//! The versions of what the shell's slots, the docked panels and the document area show (#16118). The shell replays +//! a slot, and PhotoCraft's views a panel body or the document area, while its version holds and no input reaches it: +//! the frame adds its last run again instead of running every control in it. The title bar, the options bar and the +//! status bar are the shell's versioned slots ([`title_bar`], [`options_bar`], [`status_bar`]); each panel body and +//! the document area is a `MemoView` whose key is its version. A version covers the app data its region shows that +//! can change while no input reaches the region: what a command changes, the active document and layer and the tool in +//! every version; what the region shows of the canvas view, a job or the brush and colours; and what an edit elsewhere +//! changes without a command, such as a box or pin dragged on the canvas. Input inside a region runs it whatever its +//! version, and so does a repaint it asks for itself. use std::hash::{Hash, Hasher}; -use craft::ui::contract::{MemoProps, MemoView}; +use craft::ui::contract::{MemoKey, MemoProps, MemoView}; use super::PhotocraftApp; use crate::color_picker_ui::PickWindow; - -/// The props of a shell slot's view: the app the slot reads, which its version stands for. One type per slot, so a -/// trial and the frame's memo log tell the views apart. -macro_rules! slot_props { - ($($name:ident: $what:literal),*) => {$( - #[doc = concat!("The ", $what, "'s view: the app it reads, which its version stands for.")] - #[derive(MemoProps)] - struct $name<'a> { - version: u64, - #[memo_props(covered_by = "version", reason = "the slot's version holds everything the slot shows of the app")] - app: &'a mut PhotocraftApp, - } - )*}; -} -slot_props!(TitleSlot: "title bar", OptionsSlot: "options bar"); - -/// The title bar in its slot, replaying while [`title_bar`]'s version holds. -pub(crate) fn show_title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let version = title_bar(app); - let _ = MemoView::new("photocraft.title_bar", TitleSlot { version, app }, |slot: &mut TitleSlot<'_>, ui: &mut egui::Ui| super::title_bar(slot.app, ui)) - .show(ui); -} - -/// The options bar in its slot, replaying while [`options_bar`]'s version holds. -pub(crate) fn show_options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let version = options_bar(app); - let _ = - MemoView::new("photocraft.options_bar", OptionsSlot { version, app }, |slot: &mut OptionsSlot<'_>, ui: &mut egui::Ui| super::options_bar(slot.app, ui)) - .show(ui); -} +use crate::state::Tool; /// A docked panel's body: the panel and the app it reads, which its version stands for. #[derive(MemoProps)] @@ -65,22 +36,34 @@ pub(crate) fn show_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: &str) { /// The version of the options bar: every tool option (`app.ui.tool_options`, all of which the bar shows; keys, the /// canvas menu, the canvas and its task bars, panels and presets write them without a command), the commit and cancel /// cells and hints of an edit the canvas opens or ends ([`options_bar::edit_key`](super::options_bar::edit_key)), the -/// Zoom tool's view, an open Free Transform, Puppet Warp or Perspective Warp, which shows its own members in place +/// Zoom and Rotate View tools' zoom and rotation ([`bar_view`]), an open Free Transform, Puppet Warp or Perspective Warp, which shows its own members in place /// of the tool's, with what a drag on the canvas changes (the box, the picked pin, the planes; Escape ends them without -/// a command, #15547), the Crop tool's frame state, the type members' caret or selection, the brush and its presets, the -/// colours, and the vector bar's "Make" row's own two ingredients: the Pen draft's anchor count and the Work Path the +/// a command, #15547), the Crop tool's frame state, the type members' caret or selection and the font families they +/// list ([`families_key`](crate::type_tool::families_key)), the brush and its presets, the colours, and the vector bar's "Make" row's own two ingredients: the Pen draft's anchor count and the Work Path the /// app hides (#12892), which a Pen drawing click by click changes with no History step (#12890). Which path is /// selected is already in [`version`]; the hidden path is held as its document's place, since its content can only /// change with the document's revision, which `version` holds too. pub(crate) fn options_bar(app: &PhotocraftApp) -> u64 { let sessions = (crate::transform_tool::bar_key(app), crate::puppet_ui::bar_key(app), crate::perspective_ui::bar_key(app), crate::crop_ui::bar::bar_key(app)); - let shown = (serialized(&app.ui.tool_options), super::options_bar::edit_key(app), text_target(app)); + let shown = (app.ui.tool_options.revision(), super::options_bar::edit_key(app), text_target(app), crate::type_tool::families_key()); // A canvas gesture's start and end change what the bar enables (the symmetry menu's Transform entry). let gesture = crate::canvas::tools::in_gesture(app); let hidden = app.session.active().map(|st| (st.doc.id.0, app.ui.hidden_work_path.as_ref().map(|(id, _)| *id))); let paths = (app.ui.pen.as_ref().map(|p| p.draft.knots.len()), hidden); - version(app, (view(app), sessions, shown, brush(app), colours(app), gesture, paths)) + version(app, (bar_view(app), sessions, shown, brush(app), colours(app), gesture, paths)) +} + +/// The version of the status bar: the readout's item and the zoom of the active canvas, the status message, the +/// render-path note, and the background redraw's and the job's progress. The readout's document values follow the +/// active document and its revision and name the tool, which every version holds; the language its labels are in +/// reaches the slot's view through its place. +pub(crate) fn status_bar(app: &PhotocraftApp) -> u64 { + let item = MemoKey::of(&super::chrome_ui::status_item(&app.ui.chrome)); + let zoom = crate::canvas::active_view(app).map(|view| view.zoom.to_bits()); + let message = (&app.ui.status, app.ui.status_error); + let progress = MemoKey::of(&(crate::background_redraw::progress(app), crate::jobs_ui::status_job(app).map(|(_, progress)| progress))); + version(app, (item, zoom, message, super::chrome_ui::render_path_label(app), progress)) } /// The version of the toolbar's footer: the colour chips' two colours, whether the active document is in Quick Mask and @@ -91,6 +74,13 @@ pub(crate) fn toolbar_footer(app: &PhotocraftApp) -> u64 { version(app, (colours(app), quick_mask, app.ui.view.screen_mode)) } +/// The version of the toolbar's group view, which the dock keys the toolbar's column by: the rail's slots (in the +/// preferences, which [`version`] holds with the tool), the tools its groups remember, whether the Edit Toolbar drawer +/// is open, and what the footer shows ([`toolbar_footer`]). +pub(crate) fn toolbar(app: &PhotocraftApp) -> u64 { + version(app, (toolbar_footer(app), &app.ui.group_tools, app.ui.toolbar_drawer)) +} + /// The version of the title bar: the title it shows (the active document's name and its unsaved mark), the language /// its menu titles are in, whether the menus are in the bar (not in the macOS menu bar) and whether the bar takes the /// menu keys (F10, Alt, Alt+letter), which a dialog or the shortcut recorder holds back: a dialog closed with Escape @@ -115,7 +105,8 @@ pub(crate) fn title_bar(app: &PhotocraftApp) -> u64 { /// colours, and so do Properties (a shape layer's fill and stroke swatches, a gradient fill's Foreground and /// Background stops, the adjustment editors' swatches) and Character (the colour of new type is the foreground). /// Character and Paragraph show the type defaults, and they and Properties the values at the caret or selection of the -/// type being edited, which Glyphs inserts at. Every other panel shows only what every version holds. +/// type being edited, which Glyphs inserts at; Character, Properties and Glyphs list the font families +/// ([`families_key`](crate::type_tool::families_key)). Every other panel shows only what every version holds. pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { match id { "navigator" => version(app, (view(app), adjustment_preview(app))), @@ -130,17 +121,25 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { } "cloneSource" => version(app, app.ui.presets_ui.clone_cursor.map(|(document, at)| (document, at.map(f64::to_bits)))), "modifierKeys" => version(app, app.ui.shell.latched), - "properties" => version(app, (crate::color_picker_ui::window_picker_state(app, PickWindow::Properties), colours(app), text_target(app))), + "properties" => version( + app, + (crate::color_picker_ui::window_picker_state(app, PickWindow::Properties), colours(app), text_target(app), crate::type_tool::families_key()), + ), "brushSettings" | "brushes" => version(app, brush(app)), "histogram" => version(app, (adjustment_preview(app), histograms(app))), - "character" => version(app, (colours(app), type_defaults(app), text_target(app))), + "character" => version(app, (colours(app), type_defaults(app), text_target(app), crate::type_tool::families_key())), "paragraph" => version(app, (type_defaults(app), text_target(app))), - "glyphs" => version(app, text_target(app)), + "glyphs" => version(app, (text_target(app), crate::type_tool::families_key())), "color" | "swatches" | "gradients" | "gradientEditor" => version(app, colours(app)), _ => version(app, ()), } } +/// The version of a panel in the dock whose body does not show: its title and icon, which every version holds. +pub(crate) fn hidden_panel(app: &PhotocraftApp) -> u64 { + version(app, ()) +} + /// What every slot may show, joined with `extra`: the commands run (any of them may change anything), the active /// document, its revision, its active layers and which part of them is targeted (the layer mask, the vector mask, a /// filter mask, the selected path; the Layers, Channels, Paths and Properties panels and the canvas set it without a @@ -148,7 +147,7 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { /// or `prefs.edit`, not as a counted command: units, the language, toolbar slots). /// Whether running command `id` leaves every settling region's version as it is: a view command (zoom, fit, print size, /// rotate) changes only the canvas view, which every region that shows it holds in its version (the Navigator, the Info -/// panel and the options bar through [`view`], the status bar in its own props), so it need not count as a command run +/// panel and the options bar through [`view`] and [`bar_view`], the status bar in its own props), so it need not count as a command run /// and run every panel body in the next frame (#15493). While an action is recorded it counts: the Actions panel lists /// the step it records. pub(crate) fn changes_only_the_view(app: &PhotocraftApp, id: &str) -> bool { @@ -158,7 +157,7 @@ pub(crate) fn changes_only_the_view(app: &PhotocraftApp, id: &str) -> bool { fn version(app: &PhotocraftApp, extra: impl Hash) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); app.commands_run.hash(&mut hasher); - app.session.prefs.rev().hash(&mut hasher); + app.session.prefs.settings_rev().hash(&mut hasher); app.session.active_generation().hash(&mut hasher); app.session.active_layer_changes().hash(&mut hasher); app.session.active().map(|st| st.revision).hash(&mut hasher); @@ -182,7 +181,7 @@ fn serialized(value: &impl serde::Serialize) -> u64 { } } let mut hasher = std::collections::hash_map::DefaultHasher::new(); - // Writing to a hasher cannot fail, and every tool option serializes (they are saved). + // Writing to a hasher cannot fail, and the state it hashes serializes (it is saved). let _ = serde_json::to_writer(HashWriter(&mut hasher), value); hasher.finish() } @@ -226,19 +225,127 @@ fn colours(app: &PhotocraftApp) -> [u32; 8] { bits } +/// The part of the active document's view the options bar shows: the Zoom tool's bar the zoom, the Rotate View tool's +/// the rotation, every other tool's none (the Hand tool's bar has no view field). +fn bar_view(app: &PhotocraftApp) -> Option { + let view = crate::canvas::active_view(app)?; + match app.ui.tool { + Tool::Zoom => Some(view.zoom.to_bits()), + Tool::RotateView => Some(view.rotation.to_bits()), + _ => None, + } +} + /// The active document's view as the canvas showed it: its zoom, centre and turn. fn view(app: &PhotocraftApp) -> Option<[u64; 5]> { crate::canvas::active_view(app) .map(|view| [view.zoom.to_bits(), view.center.x.to_bits(), view.center.y.to_bits(), view.rotation.to_bits(), u64::from(view.flip_x)]) } +/// The document area's props: the app it reads, which [`canvas`] stands for. +#[derive(MemoProps)] +struct CanvasSlot<'a> { + version: u64, + #[memo_props(covered_by = "version", reason = "the canvas version holds everything the document area shows of the app")] + app: &'a mut PhotocraftApp, + #[memo_props(covered_by = "version", reason = "the document area's one drawing function, the same in every pass")] + show: fn(&mut PhotocraftApp, &mut egui::Ui), +} + +/// The document area's tabs and documents in `ui`, replaying while [`canvas`] holds. `show` draws them; the per-pass +/// work around them runs before, outside the view (`canvas::document_area`). +pub(crate) fn show_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, show: fn(&mut PhotocraftApp, &mut egui::Ui)) { + let version = canvas(app); + let _ = MemoView::new("photocraft.canvas", CanvasSlot { version, app, show }, |slot: &mut CanvasSlot<'_>, ui: &mut egui::Ui| (slot.show)(slot.app, ui)) + .show(ui); +} + +/// The version of the document area, which keys its view and, through `DockPanels::content`, the docked tree it sits +/// in. It holds what the tabs and every shown canvas draw that can change while no input reaches the area and its run +/// asked for no pass: what every slot holds ([`version`]); each document's revision and unsaved mark (the tabs, the +/// arranged panes); each view as stored, with the view commands queued for its next pass and a zoom ease asked; the +/// document windows, the arrangement and its dividers; the View menu's options and the panels shown (the scroll bars +/// go with the screen mode); the tool options and the on-canvas state of the tools (a transform box, a crop frame and whether its crop is pending, a pen draft, the +/// type caret, a picked guide, the samplers, slices, frames and artboards), whose drags and keys change them without a +/// command; the canvas menu and where the Brush Preset picker is open; whether a dialog is open (it holds back the tools and the task bars); the Layers panel's hovered layer, which the Move tool outlines; the previews a dialog or a panel drag shows +/// on the canvas (an adjustment's live values, a filter's or Levels' preview, Color Range's mask); the opening files +/// and their progress; the Batch input shown in place of the documents; the display the window is on; and the blocks a background redraw has landed +/// (`background_redraw::poll`). A run that waits for work of its own (a preview worker, a tile stream) asks for its +/// next pass through the framework, which runs the view then. +pub(crate) fn canvas(app: &PhotocraftApp) -> u64 { + let ui = &app.ui; + let documents: Vec<(u64, u64, bool)> = app.session.documents().iter().map(|st| (st.doc.id.0, st.revision, st.is_dirty())).collect(); + let views: Vec<_> = ui.views.iter().chain(ui.window_views.values()).map(view_key).collect(); + let windows = serialized(&(&ui.view, &ui.panels, &ui.windows, &ui.document_windows, &ui.split_at)); + let tools = serialized(&( + &ui.brush_tool, + &ui.cam_transform, + &ui.transform, + &ui.symmetry_transform, + &ui.layer_picker, + (&ui.clone_source, &ui.clone_offset, &ui.pattern_stamp_phase), + (&ui.canvas_tool_menu, &ui.brush_picker), + &ui.selected_guide, + &ui.direct_selection, + &ui.hidden_work_path, + (&ui.analysis, &ui.slices, &ui.frame_tool, &ui.artboard_tool), + )); + let sessions = + (crate::transform_tool::bar_key(app), crate::puppet_ui::bar_key(app), crate::perspective_ui::bar_key(app), crate::crop_ui::bar::bar_key(app)); + let crop = app.canvas_tools.crop.tool.frame().map(|frame| [frame.rect.x0, frame.rect.y0, frame.rect.x1, frame.rect.y1, frame.angle].map(f64::to_bits)); + let task_bars = ( + crate::transform_task_bar::eligible(app), + crate::crop_task_bar::eligible(app), + crate::crop_ui::pending(app), + app.canvas_tools.crop.tool.straighten_armed(), + ); + let editing = (text_target(app), ui.pen.as_ref().map(|p| p.draft.knots.len()), crate::canvas::tools::in_gesture(app), crop, task_bars); + let previews = ( + adjustment_preview(app), + crate::canvas::filter_preview::canvas_key(app), + crate::levels_clipping::canvas_key(app), + crate::color_range_ui::canvas_key(app), + ); + let opening: Vec<_> = crate::jobs_ui::open_tabs(app).into_iter().map(|(job, _, fraction)| (job, fraction.map(f32::to_bits))).collect(); + let display = crate::monitor_status::view_display(app, app.ctx()); + // The open Brush Preset picker lists the presets and shows the brush. + let picker = ui.brush_picker.map(|_| brush(app)); + let gpu = app.gpu.as_ref().map(|gpu| gpu.canvas_budget()); + version( + app, + ( + documents, + views, + (windows, ui.tool_options.revision(), tools, picker), + sessions, + editing, + previews, + (app.hover_layer, app.dialog_open(), app.jobs.focus, opening, crate::jobs_ui::batch_preview_key(app), display, gpu, app.redraw_landed), + ), + ) +} + +/// A view as its canvas shows it next: the camera, the document size it last showed, how many view commands wait for +/// its next pass (only that pass drains them) and a zoom ease asked. +fn view_key(view: &crate::state::View) -> impl Hash + '_ { + let bits = |[x, y]: [f32; 2]| [x.to_bits(), y.to_bits()]; + ( + [view.zoom.to_bits(), view.rotation.to_bits()], + bits(view.center), + view.doc_size, + view.pending.len(), + view.zoom_animating, + view.zoom_anchor.map(|(doc, screen)| (doc.map(f64::to_bits), bits(screen))), + view.zoom_from.map(|(zoom, center)| (zoom.to_bits(), bits(center))), + ) +} + #[cfg(test)] mod tests { use super::*; - use crate::state::Tool; - /// The brush, the colours, the type defaults, the tool options, the type caret, the Move tool's rollover and an - /// adjustment's live preview move the versions of the bars and panels that show them and of no other, so a drag that + /// The brush, the colours, the type defaults, the tool options, the type caret, the Move tool's rollover, an + /// adjustment's live preview and the status message move the versions of the bars and panels that show them and of no other, so a drag that /// edits one leaves the rest replaying; a version that missed one would replay a stale bar or panel. #[test] fn what_a_region_shows_moves_only_its_version() { @@ -264,7 +371,7 @@ mod tests { .into_iter() .map(|id| (id, panel(app, id))) .collect(); - all.extend([("optionsBar", options_bar(app)), ("titleBar", title_bar(app))]); + all.extend([("optionsBar", options_bar(app)), ("titleBar", title_bar(app)), ("statusBar", status_bar(app))]); all }; let moved = |app: &mut PhotocraftApp, change: &dyn Fn(&mut PhotocraftApp)| -> Vec<&'static str> { @@ -302,6 +409,7 @@ mod tests { app.doc_hist = Some(crate::histogram_panel::PanelHist { key, at: 30.0, hist: Default::default() }); }); assert_eq!(landed, ["histogram"], "a histogram the worker landed"); + assert_eq!(moved(&mut app, &|app| app.ui.status = "Saved".into()), ["statusBar"], "a status message"); } /// Opening or closing a layer's effects list or a group is view state off the document's revision, and a command diff --git a/crates/ui-egui/src/panels/status_bar.rs b/crates/ui-egui/src/panels/status_bar.rs index 8d912e4e52..63a09680b1 100644 --- a/crates/ui-egui/src/panels/status_bar.rs +++ b/crates/ui-egui/src/panels/status_bar.rs @@ -40,8 +40,9 @@ struct StatusProps<'a> { values: StatusValues, item: StatusItem, document: Option, - /// The active document's main canvas as its last pass showed it; a document not yet shown has no readout. - view: Option, + /// The zoom of the active document's main canvas as its last pass showed it, the one view field the readout shows + /// (a pan leaves it as it is); a document not yet shown has no readout. + zoom: Option, message: Option, out: Outbox<'a, StatusEvent>, } @@ -59,8 +60,8 @@ struct TrailingProps<'a> { enum StatusEvent { /// The readout's item was picked. Item(StatusItem), - /// The zoom field edited the view. - View(CanvasView), + /// The zoom field set the zoom, about the view's centre. + Zoom(f64), /// The zoom field cut an entry to its range. InvalidZoom(InvalidZoom), /// The job's Cancel was clicked. @@ -69,15 +70,16 @@ enum StatusEvent { /// The status bar, in the shell's status slot: the zoom readout of the active document and the latest status /// message, and at the far end the render-path note, the background redraw and the background jobs' progress with -/// Cancel (#210). The body and the trailing group are a memoized view each, so a frame where neither changed replays -/// them. The bar itself stays the slot's direct child: it fills the slot's height and centres its content there, where -/// a memoized view around it would be moved down onto the slot row's line and clipped at the window's bottom edge. +/// Cancel (#210). The slot replays while `region_versions::status_bar` holds; when it runs, the body and the trailing +/// group are a memoized view each, so a frame that changed only one runs only that one. The bar itself stays the slot +/// pane's direct child: it fills the slot's height and centres its content there, where a memoized view around it +/// would be moved down onto the slot row's line and clipped at the window's bottom edge. pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let job = crate::jobs_ui::status_job(app); let values = chrome_ui::status_values(app); let item = chrome_ui::status_item(&app.ui.chrome); let document = app.session.active().map(|st| Size::new(st.doc.size.width as f64, st.doc.size.height as f64)); - let view = crate::canvas::active_view(app); + let zoom = crate::canvas::active_view(app).map(|view| view.zoom); let message = (!app.ui.status.is_empty()).then(|| StatusMessage::new(app.ui.status.clone()).tone(if app.ui.status_error { Tone::Warn } else { Tone::Neutral })); let render_path = chrome_ui::render_path_label(app) @@ -93,14 +95,14 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let _ = MemoView::new("status-bar-trailing", props, trailing_view).show(ui); }) .show(ui, |ui, _| { - let props = StatusProps { values: values.clone(), item, document, view, message: message.clone(), out: Outbox::new(&mut body_sent) }; + let props = StatusProps { values: values.clone(), item, document, zoom, message: message.clone(), out: Outbox::new(&mut body_sent) }; let _ = MemoView::new("status-bar", props, body_view).show(ui); }); let (mut picked, mut edited, mut invalid_zoom, mut cancelled) = (None, None, None, false); for event in body_sent.into_iter().chain(trailing_sent) { match event { StatusEvent::Item(item) => picked = Some(item), - StatusEvent::View(new) => edited = Some(new), + StatusEvent::Zoom(new) => edited = Some(new), StatusEvent::InvalidZoom(invalid) => invalid_zoom = Some(invalid), StatusEvent::CancelJob => cancelled = true, } @@ -108,11 +110,11 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some(picked) = picked { chrome_ui::set_status_item(&mut app.ui.chrome, picked); } - if let Some(new) = edited + if let Some(zoom) = edited && let Some(i) = app.session.active_index() { let ppp = app.canvas_ppp(); - app.ui.views[i].set_from(&new, ppp); + app.ui.views[i].set_zoom(zoom, ppp); } if cancelled && let Some((id, _)) = &job { crate::jobs_ui::cancel(app, *id); @@ -151,14 +153,14 @@ fn body_view(props: &mut StatusProps<'_>, ui: &mut egui::Ui) { /// The members of the status bar's body: the readout, or "No document", and the status message. fn body_members(props: &mut StatusProps<'_>, ui: &mut egui::Ui) { - match (props.document, props.view) { - (Some(size), Some(view)) => { - let out = StatusReadout::new(Bind::given(view), size, props.item, &props.values).show(ui); + match (props.document, props.zoom) { + (Some(size), Some(zoom)) => { + let out = StatusReadout::new(Bind::given(zoom), size, props.item, &props.values).show(ui); if let Some(picked) = out.item { props.out.send(StatusEvent::Item(picked)); } - if let Some(view) = out.view.value().copied() { - props.out.send(StatusEvent::View(view)); + if let Some(zoom) = out.zoom_edits.value() { + props.out.send(StatusEvent::Zoom(*zoom)); } if let Some(invalid) = out.invalid_zoom { props.out.send(StatusEvent::InvalidZoom(invalid)); @@ -186,9 +188,13 @@ pub(crate) fn document_window_status(app: &mut PhotocraftApp, ui: &mut egui::Ui, let (mut picked, mut edited, mut invalid_zoom) = (None, None, None); Bar::new("", BarKind::Status).show(ui, |ui, _| { if let (Some(size), Some(view)) = (size, view) { - let out = StatusReadout::new(Bind::given(view), size, item, &values).show(ui); + let out = StatusReadout::new(Bind::given(view.zoom), size, item, &values).show(ui); picked = out.item; - edited = out.view.value().copied(); + edited = out.zoom_edits.value().map(|zoom| { + let mut zoomed = view; + zoomed.zoom = *zoom; + zoomed + }); invalid_zoom = out.invalid_zoom; } }); diff --git a/crates/ui-egui/src/pixel_aspect_tests.rs b/crates/ui-egui/src/pixel_aspect_tests.rs index 31a808764e..d0a787c8d1 100644 --- a/crates/ui-egui/src/pixel_aspect_tests.rs +++ b/crates/ui-egui/src/pixel_aspect_tests.rs @@ -23,7 +23,7 @@ fn harness() -> Harness<'static, Box> { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/polygon_lasso_tests.rs b/crates/ui-egui/src/polygon_lasso_tests.rs index 4d970e1345..2318f11295 100644 --- a/crates/ui-egui/src/polygon_lasso_tests.rs +++ b/crates/ui-egui/src/polygon_lasso_tests.rs @@ -22,7 +22,7 @@ fn harness() -> Harness<'static, Box> { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index 79223c28bb..2c9ecb1840 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -862,7 +862,7 @@ fn restart_cases() -> Vec { assert_eq!(stored["selectedTool"], json!("Eraser")); assert_eq!(app.ui.tool, Tool::Eraser, "restored before the first frame"); assert_eq!(app.ui.group_tool(Tool::Eraser.key()), Some(Tool::Eraser)); - assert_eq!(app.ui.tool_options, crate::state::ToolOptions::default()); + assert_eq!(*app.ui.tool_options, crate::state::ToolOptions::default()); }), }, Case { @@ -1106,7 +1106,7 @@ fn damaged_cases() -> (Vec, Vec) { }, )); cases.push(loaded("tool options: a good value is left alone", json!({"toolOptions": {"feather": 12.5}}), move |app| { - assert_eq!(app.ui.tool_options, crate::state::ToolOptions { feather: 12.5, ..d() }); + assert_eq!(*app.ui.tool_options, crate::state::ToolOptions { feather: 12.5, ..d() }); let mut def = d(); crate::tool_memory::sanitize(&mut def); assert_eq!(def, d(), "in-range defaults never change"); @@ -1436,7 +1436,7 @@ fn reset_tools_clear_the_remembered_options_and_brushes() { |brushes: &[(Tool, photocraft_engine::BrushSettings)]| brushes.iter().all(|(t, b)| *b == crate::paint_mouse::fresh_brush(*t, b) && b.size != 77.0); assert!(starting(&app.ui.tool_brushes), "{saved}"); let app2 = app_on(&store); - assert_eq!(app2.ui.tool_options, crate::state::ToolOptions::default()); + assert_eq!(*app2.ui.tool_options, crate::state::ToolOptions::default()); assert!(!app2.ui.tool_brushes.is_empty() && starting(&app2.ui.tool_brushes), "remembered across a restart"); } diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 8ccafccb5d..c9863af334 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -247,7 +247,7 @@ fn memory_confirmation_dialog_and_cancel_lifecycle() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); let dlg_id = memory_dialog(&mut app); assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}))["ok"], true); @@ -390,6 +390,7 @@ fn memory_confirmation_refuses_when_source_changed_inline() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -441,6 +442,7 @@ fn memory_confirmation_refuses_when_source_changed_async() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -490,7 +492,7 @@ fn memory_decline_advances_queue_and_cleans_batch() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, Some(order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, None, Some(order), 1000, Some(4000), false, false); let dlg_id = memory_dialog(&mut app); let res = call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id})); @@ -538,8 +540,8 @@ fn batch_single_file_cancel_preserves_other_held_memory_orders() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, Some(order0), 1000, Some(4000), false, false); - crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, Some(order1), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, None, Some(order0), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, None, Some(order1), 1000, Some(4000), false, false); // Cancel first file: let dlg0 = memory_dialog(&mut app); @@ -578,7 +580,7 @@ fn profile_cancel_cancels_whole_queue_including_memory_prompts() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); crate::open_prompt::arrive( &mut app, @@ -645,7 +647,7 @@ fn mixed_prompts_follow_arrival_order_fifo() { confirm_damage: true, }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); // First prompt shown must be damage (since it arrived first)! let dlg_id = damage_dialog(&mut app); @@ -739,6 +741,7 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { job: photocraft_engine::jobs::JobId(1), name: "unknown.psd".into(), path: Some("/pics/unknown.psd".into()), + error_source: None, slot: None, order: None, }; @@ -761,7 +764,8 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { // A measured capacity shows the number and drops the uncertainty warning. let id = store_preflight(&mut app, "known.psd", 3 * gb, Some(5 * gb)); - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, slot: None, order: None }; + let tab = + crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, error_source: None, slot: None, order: None }; crate::jobs_ui::finish_open_tab( &mut app, &tab, @@ -787,7 +791,8 @@ fn memory_prompt_warns_when_little_memory_would_be_left() { let mut app = app(); let available = 3 * gb + gb / 2; let id = store_preflight(&mut app, "tight.psd", 3 * gb, Some(available)); - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(3), name: "tight.psd".into(), path: None, slot: None, order: None }; + let tab = + crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(3), name: "tight.psd".into(), path: None, error_source: None, slot: None, order: None }; crate::jobs_ui::finish_open_tab( &mut app, &tab, @@ -808,7 +813,7 @@ fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() { let gb = 1u64 << 30; let mut app = app(); let id = store_preflight(&mut app, "slow.psd", 3 * gb, Some(5 * gb)); - crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, 3 * gb, Some(5 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, None, 3 * gb, Some(5 * gb), false, false); assert_eq!(app.held_memory_prompts.len(), 1); assert!(alerts::prompt_tagged::(&app).is_some()); assert!(app.show_if_open("/pics/slow.psd"), "the waiting prompt is shown"); @@ -817,7 +822,7 @@ fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() { // The template exception: a repeat open still creates another Untitled. let id = store_preflight(&mut app, "card.psdt", 3 * gb, Some(5 * gb)); - crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, 3 * gb, Some(5 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, None, 3 * gb, Some(5 * gb), false, false); assert_eq!(app.held_memory_prompts.len(), 2); assert!(!app.show_if_open("/pics/card.psdt"), "a template reopens instead of reusing the waiting prompt"); assert_eq!(app.held_memory_prompts.len(), 2); @@ -1024,3 +1029,106 @@ fn confirmed_damaged_smart_object_opens_are_admitted_as_smart_objects_with_disti } let _ = std::fs::remove_dir_all(&dir); } + +/// A real inline decode after consent fails on a tiny recognized PSD header. Its raw approval +/// error is unchanged; typed UI confirmation acknowledges delivery. The alert names the source +/// and the next prompt retains its batch. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_error_reply() { + for (name, file_name) in [("failed.psd", None), ("failed.psd", Some("failed.psd")), ("Untitled-1", Some("template.psdt"))] { + for typed in [false, true] { + check_failed_memory_approval_case(name, file_name, typed); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn check_failed_memory_approval_case(name: &str, file_name: Option<&str>, typed: bool) { + // File-backed decoding reads the complete 26-byte header before parsing it. Give both + // routes that same header so the unsupported version, rather than EOF, is the failure. + let header = [ + b'8', b'B', b'P', b'S', 0, 0, // unsupported version + 0, 0, 0, 0, 0, 0, // reserved + 0, 3, // channels + 0, 0, 0, 1, // height + 0, 0, 0, 1, // width + 0, 8, // depth + 0, 3, // RGB + ]; + let mut app = app(); + let temp = tempfile::tempdir().unwrap(); + let path = file_name.map(|file| { + let path = temp.path().join(file); + std::fs::write(&path, header).unwrap(); + path.to_string_lossy().into_owned() + }); + let source = path.as_ref().map_or_else( + || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.to_vec())), + |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), + ); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let first = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: name.into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); + let batch = crate::jobs_ui::begin_batch(&mut app); + let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; + let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; + crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, None, Some(first_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, None, Some(second_order), 1000, Some(4000), false, false); + let dialog = alerts::prompt_tagged::(&app).unwrap(); + if typed { + let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog.value()})); + assert_eq!(reply["ok"], true, "typed confirmation acknowledges delivery; the real consumer presents the approval failure"); + } else { + let error = crate::open_prompt::answer_memory(&mut app, true).unwrap_err(); + assert_eq!(error, format!("{name}: {name}: PSD: unsupported file version 0"), "keep the approval's original raw error"); + let ctx = app.ctx().clone(); + ctx.run_ui(Default::default(), |ui| crate::dialogs::run(&mut app, ui)).textures_delta.clear(); + } + let source_name = file_name.unwrap_or(name); + let wanted = format!("Couldn't open {source_name}: PSD: unsupported file version 0"); + let errors: Vec<_> = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).collect(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].fields.as_ref().unwrap()["message"], wanted); + let error_id = errors[0].id; + assert_eq!(app.ui.status, wanted); + assert_eq!(app.ui.status.matches(source_name).count(), 1); + if name != source_name { + assert!(!app.ui.status.contains(name)); + } + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.session.take_pending_preflight(first).is_none()); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.held_memory_prompts[0].id, second); + assert_eq!(app.prompt_order.len(), 1); + assert_eq!(app.jobs.batches.len(), 1, "the waiting successor still owns this batch"); + let next = alerts::prompt_tagged::(&app).unwrap(); + crate::open_prompt::advance_memory(&mut app); + assert_eq!(app.framework.dialogs.open_dialogs().len(), 2, "neither the alert nor the successor prompt is duplicated"); + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": error_id.value()}))["ok"], true); + assert_eq!(app.framework.dialogs.open_dialogs().len(), 1); + assert_eq!(app.framework.dialogs.open_dialogs()[0].id, next); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": next.value()}))["ok"], true); + assert!(app.session.take_pending_preflight(second).is_none()); + assert!(app.framework.dialogs.open_dialogs().is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); +} diff --git a/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs b/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs new file mode 100644 index 0000000000..a6b9dddede --- /dev/null +++ b/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs @@ -0,0 +1,159 @@ +//! Smudge Pressure for Size (#12961): the bar toggle binds the same brush used by paint.smudge. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_engine::BrushSettings; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +const PRESSURE: &str = "Always use pressure for size"; +const TOOLTIP: &str = "Always use Pressure for Size. When off, Brush Preset controls pressure"; + +fn bar(tool: Tool) -> Harness<'static, Box> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + let mut h = + Harness::builder().with_size(vec2(1600.0, 400.0)).with_context(app.ctx().clone()).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + h +} + +fn toggle(h: &mut Harness<'static, Box>) { + h.get_by_label(PRESSURE).click(); + h.run_steps(3); +} + +fn brush_commands(h: &Harness<'static, Box>) -> usize { + h.state().session.journal.iter().filter(|(id, _)| id == "tools.setBrush").count() +} + +#[test] +fn pressure_is_off_by_default_and_follows_finger_painting_with_the_exact_tooltip() { + let h = bar(Tool::Smudge); + let pressure = h.get_by_label(PRESSURE); + assert!(h.get_by_label("Finger Painting").rect().right() <= pressure.rect().left()); + assert_eq!(pressure.accesskit_node().description().as_deref(), Some(TOOLTIP)); + assert!(!h.state().session.tools.brush.pressure_size); +} + +#[test] +fn the_toggle_updates_the_brush_settings_value_with_one_command_per_click() { + let mut h = bar(Tool::Smudge); + let n = brush_commands(&h); + toggle(&mut h); + assert!(h.state().session.tools.brush.pressure_size); + assert_eq!(h.state_mut().run("brush.get", json!({})).unwrap()["pressureSize"], json!(true)); + assert_eq!(brush_commands(&h), n + 1); + assert_eq!(h.state().session.journal.last().unwrap().1["brush"], json!({"pressureSize": true})); + toggle(&mut h); + assert!(!h.state().session.tools.brush.pressure_size); + assert_eq!(brush_commands(&h), n + 2); + assert_eq!(h.state().session.journal.last().unwrap().1["brush"], json!({"pressureSize": false})); +} + +#[test] +fn reset_tool_turns_pressure_off_and_other_tools_keep_their_own_setting() { + let mut h = bar(Tool::Brush); + h.state_mut().run("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap(); + h.run_steps(2); + h.state_mut().ui.tool = Tool::Smudge; + h.run_steps(3); + assert!(!h.state().session.tools.brush.pressure_size, "Smudge starts with its own default"); + toggle(&mut h); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "the Brush setting is retained"); + h.state_mut().ui.tool = Tool::Smudge; + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "Smudge remembers its value"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); + h.run_steps(2); + assert!(!h.state().session.tools.brush.pressure_size); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "resetting Smudge does not reset the Brush"); +} + +/// Read the actual shared generator's dabs for a pen tap, rather than duplicating its formula. +fn radii(brush: &BrushSettings, pressure: f32) -> Vec { + let mut generator = photocraft_paint::dynamics::DabGenerator::new(brush, 1.0); + let (mut dabs, mut dual) = (Vec::new(), Vec::new()); + generator.push(&[photocraft_paint::StrokePoint::new(28.0, 40.0, pressure)], &mut dabs, &mut dual); + generator.finish(&mut dabs, &mut dual); + assert!(!dabs.is_empty()); + dabs.into_iter().map(|dab| dab.radius).collect() +} + +#[test] +fn the_ui_toggle_changes_generated_dab_size_with_pressure_and_off_restores_the_baseline() { + let mut h = bar(Tool::Smudge); + let original = h.state().session.tools.brush.clone(); + let off_low = radii(&original, 0.25); + let off_full = radii(&original, 1.0); + assert_eq!(off_low, off_full); + toggle(&mut h); + let on = h.state().session.tools.brush.clone(); + assert_eq!(radii(&on, 1.0), off_full); + let low = radii(&on, 0.25); + assert!(low.iter().all(|r| (*r - original.size * 0.25 * 0.5).abs() < 1e-6)); + toggle(&mut h); + assert_eq!(radii(&h.state().session.tools.brush, 0.25), off_low); + assert_eq!(h.state().session.tools.brush.shape_dynamics, original.shape_dynamics, "the toggle does not rewrite preset dynamics"); +} + +/// A red/white edge and a real paint.smudge command, with the UI-selected brush and real point +/// pressures. All comparisons use complete resulting pixels, with no visual threshold. +fn smudged(brush: &BrushSettings, pressure: f32) -> (Vec, Vec) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80, "depth": 32, "background": "white"})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 80})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::Smudge; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": brush})).unwrap(); + app.ui.tool_options.strength = 100.0; + let read = |app: &PhotocraftApp| { + let state = app.session.active().unwrap(); + state.doc.layer(state.active_layer.unwrap()).unwrap().surface().unwrap().read_region(state.doc.bounds()) + }; + let before = read(&app); + let (command, mut params) = super::dab_params(&app, Tool::Smudge).unwrap(); + assert_eq!(command, "paint.smudge"); + params["points"] = json!([[28.0, 40.0, pressure], [42.0, 40.0, pressure], [58.0, 40.0, pressure]]); + app.run(command, params).unwrap(); + (before, read(&app)) +} + +#[test] +fn actual_smudge_pixels_follow_pressure_on_and_keep_the_existing_result_off() { + let mut h = bar(Tool::Smudge); + h.state_mut().run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 1.0, "spacing": 0.25, "smoothing": {"enabled": false}}})).unwrap(); + h.run_steps(2); + let off = h.state().session.tools.brush.clone(); + let (before, off_low) = smudged(&off, 0.25); + let (_, off_full) = smudged(&off, 1.0); + assert_ne!(off_full, before, "the edge fixture must actually smudge"); + assert_eq!(off_low, off_full, "off keeps today's pressure-independent size"); + toggle(&mut h); + let on = h.state().session.tools.brush.clone(); + let (_, on_low) = smudged(&on, 0.25); + let (_, on_full) = smudged(&on, 1.0); + assert_ne!(on_low, on_full, "the actual command receives pen pressure and the selected brush"); + assert_ne!(on_low, off_low); + assert_eq!(on_full, off_full, "full pressure keeps the full-size result"); + toggle(&mut h); + assert_eq!(smudged(&h.state().session.tools.brush, 0.25).1, off_low); +} + +#[test] +fn the_smudge_change_does_not_add_pressure_controls_to_blur_or_sharpen() { + for tool in [Tool::Blur, Tool::Sharpen] { + assert!(bar(tool).query_by_label(PRESSURE).is_none(), "{tool:?}"); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 78f2ae4726..203bd924e9 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -337,8 +337,8 @@ pub struct UiState { /// Frame tool (see `frame_tool`). #[serde(default)] pub frame_tool: crate::frame_tool::FrameToolUi, - /// The contextual task bar as drawn in the last frame: its screen rect `[x0, y0, x1, y1]` in - /// points, `None` while no bar shows (`ui.inspect` › `taskBar`). + /// The contextual crop task bar as the last canvas run drew it: its screen rect `[x0, y0, x1, y1]` + /// in points, `None` while no bar shows (`ui.inspect` › `taskBar`). #[serde(skip)] pub task_bar_shown: Option<[f32; 4]>, /// Artboard tool (see `artboard_tool`). @@ -422,7 +422,7 @@ pub struct UiState { #[serde(default)] pub selection_mode: u8, #[serde(default)] - pub tool_options: ToolOptions, + pub tool_options: Tracked, /// The shape Fill / Stroke swatches' recently used gradients, newest first (the Gradient /// tab's Recent row). #[serde(default)] @@ -546,7 +546,7 @@ impl Default for UiState { brush_curves_open: BTreeSet::new(), brushes_panel: brushes_list(), selection_mode: 0, - tool_options: ToolOptions::default(), + tool_options: Tracked::new(ToolOptions::default()), recent_gradients: Vec::new(), next_id: 1, status: String::new(), @@ -599,7 +599,7 @@ mod tests { 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; + *s.slot_mut(t).unwrap() = true; assert!(s.get(t), "{t:?}"); } assert!(!s.get(Tool::QuickSelection)); diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 7c699804ae..463ed44dbe 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -3,11 +3,13 @@ use craft::draw::ui::crop::{CropSettings, CropSizeFields}; use craft::draw::ui::{PathOptionsSettings, TransformSettings, VectorMode}; use craft::imaging::ui::select::MagneticSettings; +use craft::ui::contract::PlainData; + use super::tool::Tool; use super::{Deserialize, Serialize}; /// Object Selection › gear › Object Finder Mode (#12857). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, PlainData)] pub enum ObjectFinderMode { /// Auto Refresh: the finder re-analyses the document after every edit. #[default] @@ -17,7 +19,7 @@ pub enum ObjectFinderMode { } /// Options-bar state for tools (Photoshop keeps these per tool). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, PlainData)] #[serde(default)] pub struct ToolOptions { pub tolerance: f32, @@ -77,6 +79,7 @@ pub struct ToolOptions { /// parameter format. Kept as overrides so saved engine defaults still supply unset fields. /// OpenType features and variable-font axes are merged per tag/axis. #[serde(default)] + #[plain_data(assume = "a JSON map of owned values: no interior mutability")] pub type_style_defaults: serde_json::Map, /// Type tool: paragraph direction of new type, "auto" (from the first strong character), /// "ltr" or "rtl" (TYPE-218-2). @@ -93,6 +96,9 @@ pub struct ToolOptions { pub pattern_stamp_angle: f32, /// current | currentAndBelow | all pub clone_sample: String, + /// Healing Brush › Mode: Replace, which copies the source without healing (#12101). Like the + /// painting tools' Clear flags it is tool-only: the stroke params carry it, not the brush. + pub healing_replace: bool, /// Spot Healing: contentAware | createTexture | proximityMatch pub spot_type: String, /// Patch: source (repair the selection) | destination (repair where it is dragged). @@ -377,7 +383,7 @@ pub(super) fn default_brush_tool() -> Tool { /// tool, all off by default except the Patch tool's Content-Aware Sample All Layers (#5524, /// #12125): turning it on for the Magic Wand must not leave Blur or Smudge copying the composite /// onto the active layer. The Mixer Brush keeps its own with the brush (`MixerSettings`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, PlainData)] #[serde(default)] pub struct SampleAllLayers { pub magic_wand: bool, @@ -413,29 +419,41 @@ impl Default for SampleAllLayers { } } +/// The field of `SampleAllLayers` that `$tool` keeps, borrowed as `$borrow`. +macro_rules! sample_all_slot { + ($this:ident, $tool:ident, $($borrow:tt)+) => { + Some(match $tool { + Tool::MagicWand => $($borrow)+ $this.magic_wand, + Tool::QuickSelection => $($borrow)+ $this.quick_selection, + Tool::ObjectSelection => $($borrow)+ $this.object_selection, + Tool::PaintBucket => $($borrow)+ $this.paint_bucket, + Tool::MagicEraser => $($borrow)+ $this.magic_eraser, + Tool::SpotHealing => $($borrow)+ $this.spot_healing, + Tool::Patch => $($borrow)+ $this.patch, + Tool::ContentAwareMove => $($borrow)+ $this.content_aware_move, + Tool::Remove => $($borrow)+ $this.remove, + Tool::Blur => $($borrow)+ $this.blur, + Tool::Sharpen => $($borrow)+ $this.sharpen, + Tool::Smudge => $($borrow)+ $this.smudge, + _ => return None, + }) + }; +} + 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) + pub fn get(self, tool: Tool) -> bool { + self.slot(tool).unwrap_or(false) } /// `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, - }) + pub fn slot(&self, tool: Tool) -> Option { + sample_all_slot!(self, tool, &).copied() + } + + /// `tool`'s setting to write, or `None` for a tool without the option. + pub fn slot_mut(&mut self, tool: Tool) -> Option<&mut bool> { + sample_all_slot!(self, tool, &mut) } } @@ -479,6 +497,7 @@ impl Default for ToolOptions { pattern_stamp_scale: 100.0, pattern_stamp_angle: 0.0, clone_sample: "current".into(), + healing_replace: false, spot_type: "contentAware".into(), patch_mode: "source".into(), patch_content_aware: false, diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index 52b297748a..677bf6c20b 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -19,7 +19,7 @@ fn harness() -> Harness<'static, Box> { if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); @@ -356,7 +356,7 @@ fn the_stroke_trace_times_each_frame_of_a_stroke_and_ends_on_release() { let moves = ctx.input(|i| i.raw.events.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count()); app.perf.stage.start(t0, moves); app.perf.stage.ui_start(t0, Some(0.004)); - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); app.finish_frame(&ctx, crate::gpu_canvas::now_ms() - t0); }, app, diff --git a/crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs b/crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs new file mode 100644 index 0000000000..f88e7fdbbb --- /dev/null +++ b/crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs @@ -0,0 +1,66 @@ +//! #16757: with the Move tool, the pasteboard's right-click menu starts with Hide Contextual Task Bar +//! (Show Contextual Task Bar while the bar is off) and a separator, and the row toggles the same flag +//! as Window › Contextual Task Bar. + +use egui::{Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::canvas_tool_menu::tests::{harness, right_click}; +use crate::state::Tool; + +fn app(tool: Tool) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.ui.tool = tool; + app +} + +/// Right-clicks the pasteboard and returns the open menu's rows, a separator as `None`. +fn pasteboard_rows(h: &mut Harness<'static, Box>) -> Vec> { + let pasteboard = h.state().last_canvas_rect.min + vec2(5.0, 5.0); + right_click(h, pasteboard, Modifiers::NONE); + let inspected = crate::control::inspect(h.state(), &h.ctx); + assert_eq!(inspected["canvasToolMenu"]["pasteboard"], json!(true), "the pasteboard menu opens"); + let entries = inspected["canvasToolMenu"]["entries"].as_array().expect("pasteboard menu entries"); + entries.iter().map(|e| if e["separator"] == json!(true) { None } else { e["label"].as_str().map(str::to_owned) }).collect() +} + +#[test] +fn the_move_tools_pasteboard_menu_starts_with_the_task_bar_row() { + let mut marquee = harness(app(Tool::RectMarquee)); + let today = pasteboard_rows(&mut marquee); + assert!(!today.iter().flatten().any(|label| label.contains("Contextual Task Bar")), "other tools keep today's menu: {today:?}"); + + let mut h = harness(app(Tool::Move)); + let rows = pasteboard_rows(&mut h); + assert_eq!(rows.first(), Some(&Some("Hide Contextual Task Bar".to_owned())), "{rows:?}"); + assert_eq!(rows.get(1), Some(&None), "a separator under it: {rows:?}"); + assert_eq!(rows[2..], today[..], "then today's colour rows"); +} + +#[test] +fn the_task_bar_row_hides_and_shows_the_bar_as_the_window_item_does() { + let mut h = harness(app(Tool::Move)); + assert!(h.state().ui.panels.context_task_bar); + + pasteboard_rows(&mut h); + h.get_by_label("Hide Contextual Task Bar").click(); + h.run_steps(2); + assert!(!h.state().ui.panels.context_task_bar, "the row hides the bar"); + assert!(h.state().ui.canvas_tool_menu.is_none(), "and closes the menu"); + // The Window item toggles the same flag: one press turns the bar back on, and off again. + let ctx = h.ctx.clone(); + let window_item = + |h: &mut Harness<'static, Box>| crate::menus::invoke(h.state_mut(), &ctx, "window.panel.contextualTaskBar", json!({})).unwrap(); + assert_eq!(window_item(&mut h), json!(true)); + assert_eq!(window_item(&mut h), json!(false)); + + let rows = pasteboard_rows(&mut h); + assert_eq!(rows.first(), Some(&Some("Show Contextual Task Bar".to_owned())), "{rows:?}"); + h.get_by_label("Show Contextual Task Bar").click(); + h.run_steps(2); + assert!(h.state().ui.panels.context_task_bar, "the row shows the bar again"); +} diff --git a/crates/ui-egui/src/tool_memory.rs b/crates/ui-egui/src/tool_memory.rs index 7c4b555616..70ad69cdef 100644 --- a/crates/ui-egui/src/tool_memory.rs +++ b/crates/ui-egui/src/tool_memory.rs @@ -90,7 +90,7 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { if let Ok(now) = serde_json::to_value(tool) && app.session.prefs().selected_tool != now { - app.session.prefs.edit(|p| p.selected_tool = now); + app.session.prefs.remember(|p| p.selected_tool = now); // prefs_ui::tick ran before the panels; ensure it can flush this new revision. ctx.request_repaint(); } @@ -98,13 +98,13 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { persist_colors(app, ctx); persist_group_tools(app, ctx, tool); persist_brushes(app); - if app.prefs_rt.tool_options.as_ref() == Some(&app.ui.tool_options) { + if app.prefs_rt.tool_options.as_ref() == Some(&*app.ui.tool_options) { return; } - app.prefs_rt.tool_options = Some(app.ui.tool_options.clone()); + app.prefs_rt.tool_options = Some((*app.ui.tool_options).clone()); let now = changed(&app.ui.tool_options); if app.session.prefs().tool_options != now { - app.session.prefs.edit(|p| p.tool_options = now); + app.session.prefs.remember(|p| p.tool_options = now); } } @@ -138,7 +138,7 @@ fn persist_colors(app: &mut PhotocraftApp, ctx: &egui::Context) { photocraft_engine::prefs::stamp_tool_color_picks(&mut saved, &app.session.prefs().tool_colors); saved }; - app.session.prefs.edit(|p| p.tool_colors = photocraft_engine::prefs::ToolColors(saved)); + app.session.prefs.remember(|p| p.tool_colors = photocraft_engine::prefs::ToolColors(saved)); // Panels and shortcuts can change colours after prefs_ui::tick already ran this frame. ctx.request_repaint(); } @@ -289,7 +289,7 @@ fn persist_group_tools(app: &mut PhotocraftApp, ctx: &egui::Context, tool: Tool) if let Ok(now) = serde_json::to_value(&app.ui.group_tools) && app.session.prefs().group_tools != now { - app.session.prefs.edit(|p| p.group_tools = now); + app.session.prefs.remember(|p| p.group_tools = now); // As for the selected tool: prefs_ui::tick ran before the panels. ctx.request_repaint(); } @@ -322,7 +322,7 @@ fn persist_brushes(app: &mut PhotocraftApp) { }; app.prefs_rt.tool_brushes = Some((owner, brushes.clone())); if app.session.prefs().tool_brushes != now { - app.session.prefs.edit(|p| p.tool_brushes = now); + app.session.prefs.remember(|p| p.tool_brushes = now); } } @@ -422,12 +422,12 @@ pub fn restore(app: &mut PhotocraftApp) { } if let Ok(mut o) = serde_json::from_value(Value::Object(cur)) { sanitize(&mut o); - app.ui.tool_options = o; + *app.ui.tool_options = o; } } else if !saved.is_null() { log::warn!("Preferences: the remembered tool options are not an object; using the defaults"); } - app.prefs_rt.tool_options = Some(app.ui.tool_options.clone()); + app.prefs_rt.tool_options = Some((*app.ui.tool_options).clone()); restore_colors(app); restore_brushes(app); } diff --git a/crates/ui-egui/src/tools/adjustment_brush.rs b/crates/ui-egui/src/tools/adjustment_brush.rs index 04b3cf28d2..e18c508d75 100644 --- a/crates/ui-egui/src/tools/adjustment_brush.rs +++ b/crates/ui-egui/src/tools/adjustment_brush.rs @@ -6,7 +6,7 @@ use craft::behavior::IconId; use craft::ui::buttons::{IconButton, ToggleButton}; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, bind_tracked}; use craft::ui::display::Divider; use craft::ui::pickers::Select; use photocraft_engine::adjustment_brush_cmds::{self as ab, ENTRIES, INDEXED_ALERT}; @@ -152,7 +152,7 @@ pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bo let choose = tl!("Choose an object and have the adjustment applied to it"); IconButton::new(IconId::new("square-dashed-mouse-pointer")).label(choose).tooltip(choose).enabled(false).show(ui); // On, the canvas tints what the active adjustment layer's mask reveals (`raster_source::MaskTint`, #12520). - Checkbox::new(Bind::bound(&mut app.ui.tool_options.adjustment_brush_overlay)) + Checkbox::new(bind_tracked!(app.ui.tool_options => adjustment_brush_overlay)) .label(tl!("Overlay").to_owned()) .tooltip(tl!("Show or hide the painted mask areas").to_owned()) .show(ui); @@ -160,7 +160,7 @@ pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bo let mut alerts = Vec::new(); let mut opacity = (brush.opacity * 100.0).round(); - let out = option_cells::number(tl!("Opacity:"), &mut opacity, 1.0..=100.0).whole().unit("%").show(ui); + let out = option_cells::number(tl!("Opacity:"), Bind::bound(&mut opacity), 1.0..=100.0).whole().unit("%").show(ui); key = out.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key); brush.opacity = opacity / 100.0; alerts.extend(out.out_of_range); @@ -173,7 +173,7 @@ pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bo key = pressure.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key); } let mut flow = brush.flow * 100.0; - let out = option_cells::number(tl!("Flow:"), &mut flow, 1.0..=100.0).unit("%").show(ui); + let out = option_cells::number(tl!("Flow:"), Bind::bound(&mut flow), 1.0..=100.0).unit("%").show(ui); key = out.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key); brush.flow = flow / 100.0; alerts.extend(out.out_of_range); diff --git a/crates/ui-egui/src/tools/analysis/bars.rs b/crates/ui-egui/src/tools/analysis/bars.rs index 15d34f36e8..31d2f1d580 100644 --- a/crates/ui-egui/src/tools/analysis/bars.rs +++ b/crates/ui-egui/src/tools/analysis/bars.rs @@ -7,7 +7,7 @@ use craft::draw::ui::measure::{RulerBar, RulerLine}; use craft::theme::Srgba; use craft::ui::buttons::{Button, IconButton, ToggleButton}; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, bind_tracked}; use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; use craft::ui::pickers::Select; @@ -161,8 +161,8 @@ fn count(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &photocraft_doc::Docum Divider::vertical().show(ui); let (marker, label) = (g.marker_size as f32, g.label_size as f32); let (mut new_marker, mut new_label) = (marker, label); - let marker_out = option_cells::number(tl!("Marker Size"), &mut new_marker, MARKER_SIZE).whole().show(ui); - let label_out = option_cells::number(tl!("Label Size"), &mut new_label, LABEL_SIZE).whole().show(ui); + let marker_out = option_cells::number(tl!("Marker Size"), Bind::bound(&mut new_marker), MARKER_SIZE).whole().show(ui); + let label_out = option_cells::number(tl!("Label Size"), Bind::bound(&mut new_label), LABEL_SIZE).whole().show(ui); // A typed size out of range takes the closest value and says so once (#13530). for alert in [&marker_out.out_of_range, &label_out.out_of_range].into_iter().flatten() { option_cells::range_alert(app, ui, alert); @@ -207,7 +207,7 @@ fn sampler(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let n = app.session.active().map_or(0, |d| d.color_samplers.len()); // One Sample Size setting, shared with the Eyedropper (#11732). // PLAN: assumed `SamplerOptions::show(ui)` returns an output with `clear_all: bool`. - let out = SamplerOptions::new(n, Bind::bound(&mut app.ui.tool_options.eyedropper.size)).show(ui); + let out = SamplerOptions::new(n, bind_tracked!(app.ui.tool_options => eyedropper.size)).show(ui); if out.clear_all { run(app, "view.colorSamplers.clear", json!({})); } diff --git a/crates/ui-egui/src/tools/analysis/tests.rs b/crates/ui-egui/src/tools/analysis/tests.rs index d96462aee6..93f9a340bb 100644 --- a/crates/ui-egui/src/tools/analysis/tests.rs +++ b/crates/ui-egui/src/tools/analysis/tests.rs @@ -444,7 +444,7 @@ fn count_number_height(label_size: u32) -> f32 { app.sync_views(); let mut h = egui_kittest::Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(900.0, 600.0)).build_app( |ui, app: &mut PhotocraftApp| { - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/tools/brush_feedback.rs b/crates/ui-egui/src/tools/brush_feedback.rs index f0de4f44a7..95f1ae2081 100644 --- a/crates/ui-egui/src/tools/brush_feedback.rs +++ b/crates/ui-egui/src/tools/brush_feedback.rs @@ -32,7 +32,7 @@ pub(crate) fn show(ui: &mut egui::Ui, app: &mut PhotocraftApp, rect: egui::Rect, show_smoothing_string(ui, app, rect); crate::object_finder::show(ui, app, at); if let Some(at) = at { - let shift = craft::ui::runtime::pointer::frame(ui.ctx()).mods.shift; + let shift = craft::ui::runtime::pointer::mods(ui.ctx()).shift; let tool = app.ui.tool; crate::stroke_constraint::show_line_preview(ui, app, at, tool, shift); } @@ -54,7 +54,7 @@ fn show_clone_overlay(ui: &mut egui::Ui, app: &mut PhotocraftApp, at: Option Option<&'static str> { /// The tool's name in the alerts, for the tools whose wording was measured: the Brush, the /// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965), the Burn tool (#12672), the Healing Brush (#12111), the Art History Brush -/// (#12638) and the Classic gradient (the live Gradient makes a fill layer and isn't measured, #12017). +/// (#12638), the Paint Bucket (#12537) and the Classic gradient (the live Gradient makes a fill layer and isn't measured, #12017). pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { match tool { Tool::Brush => Some(tl!("brush tool")), @@ -53,6 +53,8 @@ pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { Tool::Burn => Some(tl!("burn tool")), Tool::Healing => Some(tl!("healing brush")), Tool::ArtHistoryBrush => Some(tl!("art history brush")), + // The Paint Bucket's click (#12537). + Tool::PaintBucket => Some(tl!("paint bucket")), Tool::Gradient if app.ui.tool_options.gradient_classic => Some(tl!("gradient tool")), _ => None, } @@ -132,11 +134,13 @@ fn layer_refusal(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { } } -/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge, Smudge and Burn tools and the -/// Art History Brush Lock Image Pixels as well (measured for them; the Brush keeps today's -/// behaviour there). +/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge, Smudge and Burn tools, the +/// Art History Brush, the Magic Eraser and the Paint Bucket (#12537) Lock Image Pixels as well +/// (measured for them; the Brush keeps today's behaviour there). fn locked(locks: photocraft_doc::Locks, tool: Tool) -> bool { - locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge | Tool::Burn | Tool::ArtHistoryBrush | Tool::MagicEraser) && locks.pixels) + locks.all + || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge | Tool::Burn | Tool::ArtHistoryBrush | Tool::MagicEraser | Tool::PaintBucket) + && locks.pixels) } /// A Spot Healing press on an empty pixel layer with Sample All Layers off (#12581): when that layer is hidden, the @@ -186,3 +190,7 @@ mod burn_refusal_alert_tests; #[cfg(test)] #[path = "../healing_refusal_alert_tests.rs"] mod healing_refusal_alert_tests; + +#[cfg(test)] +#[path = "../paint_bucket_refusal_alerts_tests.rs"] +mod paint_bucket_refusal_alerts_tests; diff --git a/crates/ui-egui/src/tools/crop_task_bar.rs b/crates/ui-egui/src/tools/crop_task_bar.rs index 97e8c0bad6..4d6ac524f3 100644 --- a/crates/ui-egui/src/tools/crop_task_bar.rs +++ b/crates/ui-egui/src/tools/crop_task_bar.rs @@ -36,6 +36,8 @@ pub fn eligible(app: &PhotocraftApp) -> bool { /// Shows the bar under the active document's crop frame, inside `area` (the canvas body's rect). pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, area: egui::Rect) { + // The canvas run that shows the bar reports where; a replay of that run shows it there still. + app.ui.task_bar_shown = None; if !wanted(app) { return; } diff --git a/crates/ui-egui/src/tools/direct_select/tests.rs b/crates/ui-egui/src/tools/direct_select/tests.rs index f849a9d613..805529af71 100644 --- a/crates/ui-egui/src/tools/direct_select/tests.rs +++ b/crates/ui-egui/src/tools/direct_select/tests.rs @@ -245,7 +245,7 @@ fn a_curvature_pen_double_click_through_the_canvas_rounds_a_corner() { app.ui.extras.rulers = false; let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1000.0, 700.0)).with_step_dt(1.0 / 60.0).build_ui_state( |ui, app: &mut Box| { - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); }, app, ); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 12fd03a433..c3a701c0a9 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -7,7 +7,7 @@ use craft::behavior::IconId; use craft::ui::buttons::ToggleButton; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, bind_tracked}; use craft::ui::display::Divider; use craft::ui::form::Field; use craft::ui::pickers::Select; @@ -148,8 +148,8 @@ pub(crate) fn stored_tolerance(v: f32) -> f32 { } /// A check box named `label` over `value`. -fn check(ui: &mut egui::Ui, label: &str, value: &mut bool, tip: Option<&str>) { - let mut checkbox = Checkbox::new(Bind::bound(value)).label(label.to_owned()); +fn check(ui: &mut egui::Ui, label: &str, value: Bind<'_, bool>, tip: Option<&str>) { + let mut checkbox = Checkbox::new(value).label(label.to_owned()); if let Some(tip) = tip { checkbox = checkbox.tooltip(tip.to_owned()); } @@ -168,28 +168,27 @@ pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bo } fn magic_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { - let o = &mut app.ui.tool_options; // The field clamps without an alert, as the reference's Magic Eraser Tolerance does. - let _ = option_cells::number(tl!("Tolerance:"), &mut o.tolerance, 0.0..=255.0).show(ui); - check(ui, tl!("Anti-alias"), &mut o.anti_alias, None); - check(ui, tl!("Contiguous"), &mut o.contiguous, None); - check(ui, tl!("Sample All Layers"), &mut o.sample_all.magic_eraser, None); + let _ = option_cells::number(tl!("Tolerance:"), bind_tracked!(app.ui.tool_options => tolerance), 0.0..=255.0).show(ui); + let (anti_alias, contiguous, sample_all) = bind_tracked!(app.ui.tool_options => anti_alias, contiguous, sample_all.magic_eraser); + check(ui, tl!("Anti-alias"), anti_alias, None); + check(ui, tl!("Contiguous"), contiguous, None); + check(ui, tl!("Sample All Layers"), sample_all, None); Divider::vertical().show(ui); - let _ = option_cells::number(tl!("Opacity:"), &mut o.magic_eraser_opacity, 1.0..=100.0).unit("%").show(ui); + let _ = option_cells::number(tl!("Opacity:"), bind_tracked!(app.ui.tool_options => magic_eraser_opacity), 1.0..=100.0).unit("%").show(ui); } fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { let mut alerts = Vec::new(); { - let o = &mut app.ui.tool_options; let sampling = [ Entry::new("continuous".to_string(), tl!("Sampling: Continuous")).icon(IconId::new("eyedropper")), Entry::new("once".to_string(), tl!("Sampling: Once")).icon(IconId::new("target")), Entry::new("backgroundSwatch".to_string(), tl!("Sampling: Background Swatch")).icon(IconId::new("square")), ]; - let picked = Segmented::new(tl!("Sampling"), Bind::given(o.bg_sampling.clone()), &sampling).show(ui).value().cloned(); + let picked = Segmented::new(tl!("Sampling"), Bind::given(app.ui.tool_options.bg_sampling.clone()), &sampling).show(ui).value().cloned(); if let Some(sampling) = picked { - o.bg_sampling = sampling; + app.ui.tool_options.bg_sampling = sampling; } Divider::vertical().show(ui); @@ -201,7 +200,7 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { // In a `Field`, as Color Replacement's Limits: a bare control's label only names it (#16338). let picked = Field::new(tl!("Limits:")) .show(ui, |ui, _| { - Select::new(tl!("Limits:"), Bind::given(o.bg_limits.clone()), &limits) + Select::new(tl!("Limits:"), Bind::given(app.ui.tool_options.bg_limits.clone()), &limits) .tooltip(tl!("How far to let the erasing spread").to_owned()) .show(ui) .events @@ -211,20 +210,20 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { .inner .flatten(); if let Some(limits) = picked { - o.bg_limits = limits; + app.ui.tool_options.bg_limits = limits; } // Shown as the stroke reads it; written back only when the user edits it. - let shown = stored_tolerance(o.bg_tolerance); + let shown = stored_tolerance(app.ui.tool_options.bg_tolerance); let mut tolerance = shown; - let alert = option_cells::number(tl!("Tolerance:"), &mut tolerance, 1.0..=100.0) + let alert = option_cells::number(tl!("Tolerance:"), Bind::bound(&mut tolerance), 1.0..=100.0) .whole() .unit("%") .tooltip(tl!("Erase range of similar colors")) .show(ui) .out_of_range; if tolerance != shown { - o.bg_tolerance = tolerance; + app.ui.tool_options.bg_tolerance = tolerance; } alerts.extend(alert); } @@ -233,7 +232,7 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { let before = (*app.session.tools.brush).clone(); let mut brush = before.clone(); let mut angle = brush.angle; - let angle_out = option_cells::number(tl!("Angle"), &mut angle, -180.0..=180.0) + let angle_out = option_cells::number(tl!("Angle"), Bind::bound(&mut angle), -180.0..=180.0) .whole() .unit("°") .icon(IconSpec::svg(IconId::new("rotate_cw"))) @@ -244,7 +243,7 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { brush.angle = angle; alerts.extend(angle_out.out_of_range); - check(ui, tl!("Protect Foreground Color"), &mut app.ui.tool_options.bg_protect_fg, Some(tl!("Do not erase the foreground swatch color"))); + check(ui, tl!("Protect Foreground Color"), bind_tracked!(app.ui.tool_options => bg_protect_fg), Some(tl!("Do not erase the foreground swatch color"))); let pressure = ToggleButton::new(tl!("Always use pressure for size"), Bind::given(brush.pressure_size)) .icon(IconId::new("target")) diff --git a/crates/ui-egui/src/tools/eyedropper_ui.rs b/crates/ui-egui/src/tools/eyedropper_ui.rs index d9da168205..a745abf2a2 100644 --- a/crates/ui-egui/src/tools/eyedropper_ui.rs +++ b/crates/ui-egui/src/tools/eyedropper_ui.rs @@ -10,7 +10,11 @@ use crate::PhotocraftApp; /// The options bar for the Eyedropper tool. pub fn options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - EyedropperBar::new(&mut app.ui.tool_options.eyedropper).show(ui); + let mut options = app.ui.tool_options.eyedropper; + EyedropperBar::new(&mut options).show(ui); + if options != app.ui.tool_options.eyedropper { + app.ui.tool_options.eyedropper = options; + } } #[cfg(test)] diff --git a/crates/ui-egui/src/tools/frame_tool/tests.rs b/crates/ui-egui/src/tools/frame_tool/tests.rs index 45063f1cd4..b3b4688d96 100644 --- a/crates/ui-egui/src/tools/frame_tool/tests.rs +++ b/crates/ui-egui/src/tools/frame_tool/tests.rs @@ -55,7 +55,7 @@ fn harness(app: Box) -> egui_kittest::Harness<'static, Box| crate::canvas::document_area(app, ui), app); + .build_ui_state(|ui, app: &mut Box| crate::canvas::testing::document_area(app, ui), app); h.run_steps(4); h diff --git a/crates/ui-egui/src/tools/gradient_ui/bar.rs b/crates/ui-egui/src/tools/gradient_ui/bar.rs index 0f9a30ed4e..2a389f1be8 100644 --- a/crates/ui-egui/src/tools/gradient_ui/bar.rs +++ b/crates/ui-egui/src/tools/gradient_ui/bar.rs @@ -3,7 +3,7 @@ use craft::draw::ui::gradient::{GradientFillWords, GradientStyle, GradientSwatch}; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, LabelKind, Props as _, Show as _, ShowContainer as _, SideLabel}; +use craft::ui::contract::{Bind, Entry, LabelKind, Props as _, Show as _, ShowContainer as _, SideLabel, bind_tracked}; use craft::ui::display::Divider; use craft::ui::form::Field; use craft::ui::patterns::blend_keys::{BlendKeyEntry, blend_entries}; @@ -51,37 +51,40 @@ pub(crate) fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let blends = blend_modes(); let open_editor; { - let o = &mut app.ui.tool_options; - let mut classic = o.gradient_classic && !locked_live; + let mut classic = app.ui.tool_options.gradient_classic && !locked_live; Field::new(tl!("Gradient mode").to_owned()).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { Select::new(tl!("Gradient mode").to_owned(), Bind::bound(&mut classic), &modes).enabled(!locked_live).show(ui); }); - if !locked_live { - o.gradient_classic = classic; + if !locked_live && classic != app.ui.tool_options.gradient_classic { + app.ui.tool_options.gradient_classic = classic; } open_editor = GradientSwatch::new(tl!("Gradient picker").to_string(), &tool_stops).sampler(&sampler).show(ui).clicked; Divider::vertical().show(ui); - let style = stops::style_named(&o.gradient_style); + let style = stops::style_named(&app.ui.tool_options.gradient_style); if let Some(next) = Segmented::new(Label::from(tl!("Gradient style").to_string()), Bind::given(style), &styles).show(ui).value().copied() { - o.gradient_style = stops::style_name(next).to_owned(); + app.ui.tool_options.gradient_style = stops::style_name(next).to_owned(); } if classic { - labelled(ui, tl!("Mode"), |ui| { - Select::new(tl!("Blend Mode").to_owned(), Bind::bound(&mut o.gradient_blend_mode), &blends).show(ui); - }); + let fill_opacity = app.ui.tool_options.fill_opacity; + { + let mut blend = bind_tracked!(app.ui.tool_options => gradient_blend_mode); + labelled(ui, tl!("Mode"), |ui| { + Select::new(tl!("Blend Mode").to_owned(), blend.reborrowed(), &blends).show(ui); + }); + } labelled(ui, tl!("Opacity"), |ui| { let field = - NumberField::new(tl!("Opacity").to_owned(), Bind::given(Some(f64::from(o.fill_opacity)))).range(1.0..=100.0).unit("%").scrub_by_label(); + NumberField::new(tl!("Opacity").to_owned(), Bind::given(Some(f64::from(fill_opacity)))).range(1.0..=100.0).unit("%").scrub_by_label(); if let Some(next) = field.show(ui).value().copied().flatten() { - o.fill_opacity = next as f32; + app.ui.tool_options.fill_opacity = next as f32; } }); } - if let Some(on) = Checkbox::new(Bind::given(o.gradient_reverse)).label(tl!("Reverse").to_owned()).show(ui).value().copied() { - o.gradient_reverse = on; + if let Some(on) = Checkbox::new(Bind::given(app.ui.tool_options.gradient_reverse)).label(tl!("Reverse").to_owned()).show(ui).value().copied() { + app.ui.tool_options.gradient_reverse = on; } - if let Some(on) = Checkbox::new(Bind::given(o.gradient_dither)).label(tl!("Dither").to_owned()).show(ui).value().copied() { - o.gradient_dither = on; + if let Some(on) = Checkbox::new(Bind::given(app.ui.tool_options.gradient_dither)).label(tl!("Dither").to_owned()).show(ui).value().copied() { + app.ui.tool_options.gradient_dither = on; } } if open_editor { diff --git a/crates/ui-egui/src/tools/gradient_ui/live_overlay.rs b/crates/ui-egui/src/tools/gradient_ui/live_overlay.rs index d568fb803d..b99722e785 100644 --- a/crates/ui-egui/src/tools/gradient_ui/live_overlay.rs +++ b/crates/ui-egui/src/tools/gradient_ui/live_overlay.rs @@ -58,7 +58,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut Ui, at: Rect) -> Option<(La return None; } // ⌘ is the Move tool (`hold_keys::cmd_moves`): the overlay steps aside while it is held. - if craft::ui::runtime::pointer::frame(ui.ctx()).mods.cmd && crate::canvas::tools::takes_command_stand_in(Tool::Gradient) { + if craft::ui::runtime::pointer::mods(ui.ctx()).cmd && crate::canvas::tools::takes_command_stand_in(Tool::Gradient) { return None; } let (layer, frame, canvas) = active_gradient(app)?; diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs index e2a7bb9c9d..6d059cf504 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs @@ -68,7 +68,9 @@ pub(crate) fn prepare(app: &PhotocraftApp, tool: &mut MagneticLassoTool /// Writes the tool's settings back after the run, so `[` and `]` reach the options store. pub(crate) fn store(app: &mut PhotocraftApp, tool: &MagneticLassoTool) { - app.ui.tool_options.magnetic = *tool.settings(); + if app.ui.tool_options.magnetic != *tool.settings() { + app.ui.tool_options.magnetic = *tool.settings(); + } } /// Selects the closed border as drawn, in `mode` (the family's operation-to-mode name). Fewer than diff --git a/crates/ui-egui/src/tools/move_distance.rs b/crates/ui-egui/src/tools/move_distance.rs index 82a09ffc04..5dfdd0bb43 100644 --- a/crates/ui-egui/src/tools/move_distance.rs +++ b/crates/ui-egui/src/tools/move_distance.rs @@ -93,7 +93,7 @@ fn duplicate_drag(app: &PhotocraftApp) -> Option<(Rect, Rect)> { /// Shows the measurements over the canvas `rect`, in the Smart Guides colour. `pointer` is the /// screen hover position. pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rect, pointer: Option) { - let command = craft::ui::runtime::pointer::frame(ui.ctx()).mods.cmd; + let command = craft::ui::runtime::pointer::mods(ui.ctx()).cmd; let pressed = crate::canvas::tools::in_gesture(app); let at = pointer.and_then(|p| crate::canvas::document_display::doc_point_at(app, p)).map(|p| [p.x, p.y]); let Some((a, b)) = current(app, at, command, pressed) else { return }; diff --git a/crates/ui-egui/src/tools/move_hover.rs b/crates/ui-egui/src/tools/move_hover.rs index 75fd55aeff..af59be78e4 100644 --- a/crates/ui-egui/src/tools/move_hover.rs +++ b/crates/ui-egui/src/tools/move_hover.rs @@ -111,7 +111,7 @@ pub(crate) fn active_outline(app: &mut PhotocraftApp, at: Option<[f64; 2]>, comm /// position. The Layers panel reads `canvas_hover_layer`, so a change of it asks for a repaint. pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rect, pointer: Option) { let prev_canvas_hover = app.canvas_hover_layer; - let command = craft::ui::runtime::pointer::frame(ui.ctx()).mods.cmd; + let command = craft::ui::runtime::pointer::mods(ui.ctx()).cmd; let pressed = crate::canvas::tools::in_gesture(app); let at = pointer.and_then(|p| crate::canvas::document_display::doc_point_at(app, p)).map(|p| [p.x, p.y]); let outline = active_outline(app, at, command, pressed); diff --git a/crates/ui-egui/src/tools/object_finder.rs b/crates/ui-egui/src/tools/object_finder.rs index 2ab9a34f5b..7daec81c82 100644 --- a/crates/ui-egui/src/tools/object_finder.rs +++ b/crates/ui-egui/src/tools/object_finder.rs @@ -185,7 +185,7 @@ pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: boo } let resting = f.shown.is_none() && !missed && now - f.since < DEBOUNCE; if resting { - ctx.request_repaint_after(std::time::Duration::from_secs_f64(DEBOUNCE - (now - f.since))); + craft::ui::runtime::frame::request_repaint_after(ctx, DEBOUNCE - (now - f.since)); } #[cfg(test)] let busy = f.job.is_some() || resting; diff --git a/crates/ui-egui/src/tools/option_cells.rs b/crates/ui-egui/src/tools/option_cells.rs index 159203d9c7..4e2c189a06 100644 --- a/crates/ui-egui/src/tools/option_cells.rs +++ b/crates/ui-egui/src/tools/option_cells.rs @@ -2,8 +2,9 @@ //! `NumberField` whose out-of-range commit comes back as a [`RangeAlert`] for the caller to show. use std::ops::RangeInclusive; +use std::sync::Arc; -use craft::behavior::{EditEvents, NumberCodec}; +use craft::behavior::{EditEvent, EditEvents, Mixed, NumberCodec}; use craft::ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing}; use craft::ui::dialog::Alert; use craft::ui::display::{Elide, Shade, Text}; @@ -18,10 +19,11 @@ use crate::PhotocraftApp; /// commits, so showing a bar never rounds a fraction another tool shares. pub(crate) struct NumberCell<'a> { caption: Label, - value: &'a mut f32, + value: Bind<'a, f32>, range: RangeInclusive, unit: Option