Merge main into feat/apply-image-source-document-14480

dialogs.rs: kept the Source document rows and derive next to main's Mask group (#14489); both use main's shared apply_image_documents, layer and channel helpers.
This commit is contained in:
qvest-ssels committed 2026-11-28 10:03:32 +01:00
commit 44bc6343aa
257 files changed
+10035 -1073

No files matched your search

+20
View File
@@ -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 }}
+1
View File
@@ -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`.
Generated
+198 -112
View File
@@ -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"
+56 -56
View File
@@ -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" }
+8 -2
View File
@@ -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(());
}
+3
View File
@@ -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());
+7 -2
View File
@@ -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") {
+71
View File
@@ -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 <args>` in `dir`; its trimmed output when it succeeds.
fn git(dir: &Path, args: &[&str]) -> Option<String> {
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/<crate> → 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<PathBuf> {
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<PathBuf> {
path.ancestors().take_while(|p| p.starts_with(stop)).find(|p| p.exists()).map(Path::to_path_buf)
}
+2
View File
@@ -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();
@@ -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()));
}
+152
View File
@@ -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<PathBuf> {
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<PathBuf> {
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);
}
+1
View File
@@ -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.
+2
View File
@@ -270,3 +270,5 @@ mod satin_size_one_tests;
#[cfg(test)]
mod inner_glow_size_one_tests;
#[cfg(test)]
mod stroke_partial_alpha_tests;
+50 -20
View File
@@ -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);
+34 -25
View File
@@ -325,30 +325,6 @@ fn covered(s: &Map, test: impl Fn(f32) -> bool + Sync) -> Vec<bool> {
/// Distance from each pixel centre inside the shape to the shape's edge
/// (≤ 0 outside).
pub(super) fn dist_inside(s: &Map) -> Vec<f32> {
dist_inside_by(s, Metric::Euclidean)
}
pub(super) fn dist_inside_by(s: &Map, m: Metric) -> Vec<f32> {
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<f32> {
})
}
/// Chamfer distance for Inside and Center strokes.
pub(super) fn stroke_inside_distance(s: &Map, raster: bool) -> Vec<f32> {
// 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<f32>, 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),
@@ -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]);
}
}
+4
View File
@@ -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<A: BufferAlloc>(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();
+23
View File
@@ -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 {
+1 -1
View File
@@ -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 }
+39 -4
View File
@@ -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<String> = 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]
@@ -158,6 +158,9 @@ pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result<Value> {
{
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")
{
+66 -13
View File
@@ -369,9 +369,19 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Rect> {
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<Value> {
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<Value> {
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<Document> {
/// `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<f64>, cmd: &str) -> Result<Vec<u8>> {
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<f64>, masked: bool, cmd: &str) -> Result<(Vec<u8>, Option<Vec<u8>>)> {
/// [`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<f64>, zip: bool, masked: bool, cmd: &str) -> Result<(Vec<u8>, Option<Vec<u8>>)> {
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<f64>, masked: bool, cmd: &st
let mut surf = Surface::new(fmt);
let vals: Vec<f32> = 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<u8> = 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<u8>)]) -> Vec<u8> {
let pages: Vec<PdfPage> = 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<u8> {
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<Value> {
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<Value> {
// 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<CommandSpec> {
"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<CommandSpec> {
"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, "<dir>/<prefix><artboard name>.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, "<dir>/<prefix><artboard name>.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;
@@ -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<Value> {
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");
}
@@ -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<i64> = 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}");
}
@@ -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);
@@ -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<Vec<u8>> {
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<usize> {
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<u8> {
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<usize> = 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);
}
+5
View File
@@ -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<CommandSpec> {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod caf_action_values_tests;
#[cfg(test)]
mod layer_props_tests;
@@ -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<u8> {
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<AtnItem> {
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<Vec<[f32; 4]>> {
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<Vec<[f32; 4]>> {
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"})));
}
@@ -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<Value> {
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<Value> {
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<Descriptor> {
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<Descriptor> {
)
}
/// 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 } };
+4 -1
View File
@@ -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<CommandSpec> {
vec![
@@ -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<Value> {
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<Value> {
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" => {
@@ -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<Value> {
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<Value> {
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 }))
}
@@ -60,6 +60,23 @@ pub(super) fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
// 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())
@@ -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);
}
}
@@ -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<u64>) {
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);
}
+10 -1
View File
@@ -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<Value> {
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 };
+5 -1
View File
@@ -434,7 +434,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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;
@@ -1030,6 +1030,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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);
+19 -1
View File
@@ -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<bool>, 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
@@ -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<String>)> {
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<String>) {
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");
}
+9
View File
@@ -1254,6 +1254,11 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
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;
@@ -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);
}
}
@@ -158,8 +158,8 @@ pub fn specs() -> Vec<CommandSpec> {
&["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;
@@ -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<LayerId>, Option<LayerId>, Vec<String>) {
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<LayerId> {
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]);
}
@@ -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<Value> {
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.
@@ -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 [
+3 -3
View File
@@ -99,7 +99,8 @@ fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option<LayerMask
/// Drag a layer mask's thumbnail onto another layer or group in the Layers panel: the mask moves
/// there (⌥: a copy goes there and the original stays), as in Photoshop (#10485). A layer that
/// already has a mask keeps it unless `replace` (Photoshop asks first). One history step.
/// already has a mask keeps it unless `replace` (Photoshop asks first). One history step, named
/// `Add Layer Mask` for a move and a copy alike, as Photoshop names the drop (#16786).
pub(super) fn move_mask(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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`)"));
@@ -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<Value> {
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<Value> {
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<Value> {
})?;
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)
}
+4
View File
@@ -31,6 +31,9 @@ pub struct DocState {
pub coalesce: Option<String>,
/// 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<LayerId>,
/// 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(),
+19 -3
View File
@@ -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<Vec<u8>> {
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<Effect> {
let shadow = |inner: bool| Shadow {
@@ -598,7 +606,10 @@ fn fresh_effect(kind: &str) -> Option<Effect> {
}),
"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<Effect> {
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<Value> {
Ok(Value::Null)
}
#[cfg(test)]
mod gradient_overlay_defaults_tests;
#[cfg(test)]
mod satin_defaults_tests;
@@ -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);
}
}
@@ -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<i32> = 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))]);
}
+13 -1
View File
@@ -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<String, u64>,
}
@@ -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<R>(&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<R>(&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
@@ -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();
+11 -7
View File
@@ -249,18 +249,22 @@ fn red_eye(s: &mut Session, p: &Value) -> Result<Value> {
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<CommandSpec> {
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,
@@ -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();
@@ -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.
+1 -1
View File
@@ -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::*;
@@ -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<f32> = (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<f32> = (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:?}");
}
@@ -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<BlendMode> {
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)
};
@@ -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<ToneRange> {
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;
@@ -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<f32> = (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<f32> = (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:?}");
}
@@ -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<Value> {
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<Value> {
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<bool> = 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<bool> = 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<Value> {
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<Value> {
#[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;
@@ -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<f32> {
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<f32> {
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<f32> = 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<i32>>(), 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::<Vec<i32>>();
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<Vec<i32>> = 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<i32>> = 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<Vec<i32>> = pts.iter().map(|(x, y)| pixel(&r, *x, *y).iter().map(|&v| q(v)).collect()).collect();
assert_ne!(got, replaced, "Replace is not Normal");
}
@@ -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<f32> = (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);
}
@@ -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}");
}
}
@@ -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}");
}
}
}
+1
View File
@@ -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;
+23 -3
View File
@@ -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) => {
+5 -4
View File
@@ -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
}
+2 -1
View File
@@ -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;
+2 -2
View File
@@ -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<fx::MapProgram> =
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.
+4 -4
View File
@@ -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<fx::MapProgram> = 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)));
}
+23
View File
@@ -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
+1
View File
@@ -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
+4
View File
@@ -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<u64>,
/// 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,
}
}
}
+6 -2
View File
@@ -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() {
+33
View File
@@ -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");
}
}
+1
View File
@@ -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
+1 -1
View File
@@ -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
+63 -3
View File
@@ -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;
+2 -1
View File
@@ -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)?;
+1 -1
View File
@@ -14,7 +14,7 @@ use craft::keymap::Mods;
pub(crate) fn harness(app: Box<PhotocraftApp>) -> Harness<'static, Box<PhotocraftApp>> {
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,
);
+1 -1
View File
@@ -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,
+6 -1
View File
@@ -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
+5 -5
View File
@@ -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 {
+2
View File
@@ -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);
}
}
@@ -52,7 +52,7 @@ fn type_into(h: &mut Harness<'static, Box<PhotocraftApp>>, 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] = [
+35 -4
View File
@@ -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<Item> {
/// `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<Item> {
let with_brush = |rest: Vec<Item>| std::iter::once(Item::EditBrush).chain(std::iter::once(Item::Separator)).chain(rest).collect::<Vec<_>>();
match tool {
@@ -110,7 +114,22 @@ pub(crate) fn items(tool: Tool) -> Vec<Item> {
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<Item> {
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;
@@ -22,7 +22,7 @@ fn harness() -> Harness<'static, Box<PhotocraftApp>> {
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,
);
@@ -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"))));
@@ -15,7 +15,7 @@ fn harness() -> Harness<'static, Box<PhotocraftApp>> {
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,
);
+4 -3
View File
@@ -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<PhotocraftApp>>;
/// 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<MemoRun> {
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]
+7 -8
View File
@@ -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;
@@ -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<PhotocraftApp>, 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<PhotocraftApp>, 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");
}
+19 -3
View File
@@ -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<DocId> = 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 {
@@ -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<PhotocraftApp>>;
/// 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");
}
+81 -9
View File
@@ -153,7 +153,17 @@ pub fn transform_app_rows() -> [Entry<String>; 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.<CanvasColor name>`) 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<Entry<String>>
"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;
@@ -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<PhotocraftApp> {
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<PhotocraftApp>>, tool: Tool, doc: [f32; 2]) -> Vec<Value> {
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<Option<String>> {
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::<Vec<_>>(), lasso.iter().map(|e| &e["enabled"]).collect::<Vec<_>>());
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");
}
@@ -98,7 +98,7 @@ pub(crate) fn harness(mut app: Box<PhotocraftApp>) -> Harness<'static, Box<Photo
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,
);
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff. Show more