Merge upstream/main into docs/parity-refresh-2

Resolve the brush-parity header: keep main's Both Axes entry and this
PR's painting-menu entry. List Color Replacement in the Brush group and
the new Star tool (#11377) in Shapes; the Tool enum now has 69 variants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
vangel76andClaude Opus 5.5 committed 2026-11-08 13:20:11 +01:00
commit 8eecc81426
142 files changed
+6478 -487

No files matched your search

+1 -1
View File
@@ -162,7 +162,7 @@ jobs:
PHOTOCRAFT_NO_PRINT=1
LPDEST=photocraft-no-such-printer
timeout-minutes: 100
# fmt, clippy, layers, scorecard, tests, panic_hunt, doctests and the wasm32 check, with
# fmt, clippy, layers, panel-commands, scorecard, tests, panic_hunt, doctests and the wasm32 check, with
# `--locked --features heif`, then the missing-translations report (xtask/src/main.rs).
command: python3 scripts/test-ci-gpu-lavapipe.py && cargo xtask ci && python3 scripts/ci-gpu-lavapipe.py
+1
View File
@@ -148,6 +148,7 @@ When parity rises, raise `FLOOR` in `crates/ui-egui/src/parity.rs` (never lower
cargo test -p <crates you touched>
cargo clippy -p <crates> --all-targets -- -D warnings
cargo xtask layers
cargo xtask panel-commands # if you touched ui-egui: click handlers dispatch command ids (rule 1)
cargo xtask wasm # if you touched L0–L6
cargo xtask parity # if you added commands; commit the regenerated docs/parity-checklist.md
cargo test -p photocraft-engine --test panic_hunt -- --ignored # if you added/changed commands: no panic on adversarial input (Rule 9)
+13
View File
@@ -166,3 +166,16 @@ are adapted from Skyfuller1303’s MIT OR Apache-2.0 implementation in
`897f20072762fdf0eb688adcdb8d8cda7b38ce66`. Don Omondi’s embedded AI/PDF/EPS
extension and current-main integration build on that source. Clipboard and unrelated
Shape Tools changes from that branch are not included.
## Assets bundled by the PDF reader dependency (craft-pdf)
PhotoCraft imports PDF pages through `craft-pdf`, pinned to the craft-libs revision
`c5a1cbfb5f9049f9270955caffb5bee5997aebf7`. The renderer vendors Hayro and the assets below;
they ship inside the dependency rather than being copied into this repository. PDFium is no
longer used or shipped.
| Crate / file | Author | Source | Licence | Use |
| --- | --- | --- | --- | --- |
| `hayro-interpret 0.7.0 / assets/Foxit*.pfb` (13 standard-14 font files) | Foxit Software Inc. / PDFium Authors | <https://github.com/storytold/craft-libs/tree/c5a1cbfb5f9049f9270955caffb5bee5997aebf7/vendor/hayro-interpret/assets> | BSD-3-Clause | Renders non-embedded standard-14 PDF fonts |
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | <https://github.com/storytold/craft-libs/tree/c5a1cbfb5f9049f9270955caffb5bee5997aebf7/vendor/hayro-interpret/assets> | CC0-1.0 | Default CMYK colour conversion |
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | <https://github.com/storytold/craft-libs/tree/c5a1cbfb5f9049f9270955caffb5bee5997aebf7/vendor/hayro-cmap/assets> | BSD-3-Clause | Character-code mapping for CJK PDFs |
Generated
+299 -20
View File
@@ -22,7 +22,7 @@ dependencies = [
"accesskit",
"accesskit_consumer",
"atspi-common",
"phf",
"phf 0.14.0",
"serde",
"zvariant",
]
@@ -826,6 +826,17 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "brotli"
version = "8.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"brotli-decompressor",
]
[[package]]
name = "brotli-decompressor"
version = "5.0.3"
@@ -1443,6 +1454,18 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"bytemuck",
"hayro",
"hayro-interpret",
"hayro-syntax",
"thiserror 2.0.21",
]
[[package]]
name = "craft-print"
version = "0.1.0"
@@ -1472,7 +1495,7 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"serde",
"skrifa",
"skrifa 0.44.0",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
@@ -2107,7 +2130,7 @@ dependencies = [
"ecolor",
"emath",
"epaint_default_fonts",
"font-types",
"font-types 0.12.5",
"harfrust",
"log",
"nohash-hasher",
@@ -2115,13 +2138,13 @@ dependencies = [
"profiling",
"self_cell",
"serde",
"skrifa",
"skrifa 0.44.0",
"smallvec",
"unicode-bidi",
"unicode-general-category",
"unicode-properties",
"unicode-segmentation",
"vello_cpu",
"vello_cpu 0.2.0",
]
[[package]]
@@ -2377,6 +2400,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "font-types"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
dependencies = [
"bytemuck",
]
[[package]]
name = "font-types"
version = "0.12.5"
@@ -2423,7 +2455,7 @@ dependencies = [
"objc2-core-text",
"objc2-foundation 0.3.2",
"parlance",
"read-fonts",
"read-fonts 0.41.0",
"roxmltree 0.21.1",
"smallvec",
"windows",
@@ -2717,6 +2749,23 @@ dependencies = [
"xml-rs",
]
[[package]]
name = "glifo"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e"
dependencies = [
"bytemuck",
"foldhash 0.2.0",
"hashbrown 0.17.1",
"log",
"peniko",
"png 0.18.1",
"skrifa 0.42.1",
"smallvec",
"vello_common 0.0.9",
]
[[package]]
name = "glifo"
version = "0.3.0"
@@ -2728,9 +2777,9 @@ dependencies = [
"hashbrown 0.17.1",
"log",
"peniko",
"skrifa",
"skrifa 0.44.0",
"smallvec",
"vello_common",
"vello_common 0.2.0",
]
[[package]]
@@ -2879,7 +2928,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
"smallvec",
]
@@ -2912,6 +2961,94 @@ dependencies = [
"foldhash 0.2.0",
]
[[package]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"bytemuck",
"hayro-interpret",
"image",
"kurbo 0.13.1",
"log",
"pic-scale",
"vello_cpu 0.0.8",
]
[[package]]
name = "hayro-ccitt"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a14afde3344be69225fec4f6f44f6a219a3a492f9d8301eb25ef608fe4b7014c"
dependencies = [
"brotli",
"hayro-postscript",
]
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
"hayro-syntax",
"kurbo 0.13.1",
"moxcms",
"phf 0.13.1",
"rustc-hash 2.1.3",
"siphasher",
"skrifa 0.47.0",
"smallvec",
"yoke",
]
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"fearless_simd",
"hayro-ccitt",
]
[[package]]
name = "hayro-jpeg2000"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
dependencies = [
"fearless_simd",
]
[[package]]
name = "hayro-postscript"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"flate2",
"hayro-ccitt",
"hayro-jbig2",
"hayro-jpeg2000",
"memchr",
"rustc-hash 2.1.3",
"smallvec",
"stringprep",
"zune-jpeg 0.5.15",
]
[[package]]
name = "heck"
version = "0.5.0"
@@ -5001,7 +5138,7 @@ dependencies = [
"linebender_resource_handle",
"parlance",
"parley_data",
"skrifa",
"skrifa 0.44.0",
]
[[package]]
@@ -5080,17 +5217,37 @@ dependencies = [
"indexmap",
]
[[package]]
name = "phf"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros 0.13.1",
"phf_shared 0.13.1",
]
[[package]]
name = "phf"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
dependencies = [
"phf_macros",
"phf_shared",
"phf_macros 0.14.0",
"phf_shared 0.14.0",
"serde",
]
[[package]]
name = "phf_generator"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared 0.13.1",
]
[[package]]
name = "phf_generator"
version = "0.14.0"
@@ -5098,7 +5255,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100"
dependencies = [
"fastrand",
"phf_shared",
"phf_shared 0.14.0",
]
[[package]]
name = "phf_macros"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
dependencies = [
"phf_generator 0.13.1",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
@@ -5107,13 +5277,22 @@ version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"
dependencies = [
"phf_generator",
"phf_shared",
"phf_generator 0.14.0",
"phf_shared 0.14.0",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.14.0"
@@ -5242,6 +5421,7 @@ dependencies = [
"clap_complete",
"clap_mangen",
"photocraft-automation",
"photocraft-cms",
"photocraft-codecs",
"photocraft-doc",
"photocraft-engine",
@@ -5434,6 +5614,7 @@ version = "0.20.1"
dependencies = [
"blake3",
"craft-docpath",
"craft-pdf",
"crc32fast",
"flate2",
"imagesize",
@@ -5585,7 +5766,7 @@ dependencies = [
"photocraft-psd",
"photocraft-raster",
"rayon",
"skrifa",
"skrifa 0.44.0",
]
[[package]]
@@ -5681,6 +5862,16 @@ dependencies = [
"web-sys",
]
[[package]]
name = "pic-scale"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6edb0ff645d35accaec252de081d55984a0d6c952cb1e5dc2b9afa7c78f07288"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "pico-args"
version = "0.5.0"
@@ -6306,6 +6497,16 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "read-fonts"
version = "0.39.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
dependencies = [
"bytemuck",
"font-types 0.11.3",
]
[[package]]
name = "read-fonts"
version = "0.41.0"
@@ -6313,7 +6514,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [
"bytemuck",
"font-types",
"font-types 0.12.5",
"once_cell",
]
[[package]]
name = "read-fonts"
version = "0.44.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8"
dependencies = [
"bytemuck",
"font-types 0.12.5",
"once_cell",
]
@@ -7260,6 +7472,16 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
[[package]]
name = "skrifa"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
dependencies = [
"bytemuck",
"read-fonts 0.39.2",
]
[[package]]
name = "skrifa"
version = "0.44.0"
@@ -7267,7 +7489,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
]
[[package]]
name = "skrifa"
version = "0.47.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f"
dependencies = [
"bytemuck",
"read-fonts 0.44.0",
]
[[package]]
@@ -8272,6 +8504,40 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "vello_common"
version = "0.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee"
dependencies = [
"bytemuck",
"fearless_simd",
"guillotiere",
"hashbrown 0.17.1",
"log",
"peniko",
"png 0.18.1",
"smallvec",
"thiserror 2.0.21",
]
[[package]]
name = "vello_common"
version = "0.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19d672facaa2d697285a786cd9d44d614cd2ce54cdc022504bf339f8fff3b750"
dependencies = [
"bytemuck",
"fearless_simd",
"guillotiere",
"hashbrown 0.17.1",
"log",
"peniko",
"png 0.18.1",
"smallvec",
"thiserror 2.0.21",
]
[[package]]
name = "vello_common"
version = "0.2.0"
@@ -8287,6 +8553,19 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "vello_cpu"
version = "0.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0"
dependencies = [
"bytemuck",
"glifo 0.1.1",
"hashbrown 0.17.1",
"png 0.18.1",
"vello_common 0.0.8",
]
[[package]]
name = "vello_cpu"
version = "0.2.0"
@@ -8294,9 +8573,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9"
dependencies = [
"bytemuck",
"glifo",
"glifo 0.3.0",
"hashbrown 0.17.1",
"vello_common",
"vello_common 0.2.0",
]
[[package]]
+6
View File
@@ -40,6 +40,7 @@ photocraft-ipp = { path = "crates/ipp" }
# external
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["raster"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" }
@@ -203,3 +204,8 @@ eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968157
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README).
hayro = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
+48
View File
@@ -70,3 +70,51 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Optional PDF reader (craft-pdf)
PhotoCraft imports PDF pages through craft-pdf (https://github.com/storytold/craft-libs,
MIT OR Apache-2.0), pinned to revision c5a1cbfb5f9049f9270955caffb5bee5997aebf7. It vendors
Hayro 0.7.1, hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0 and
hayro-cmap 0.1.0 (https://github.com/LaurenzV/hayro, MIT OR Apache-2.0). The reader bundles
the standard-14 Foxit fonts (BSD-3-Clause), Adobe CMaps (BSD-3-Clause) and a Compact ICC
profile by Clinton Ingram (CC0-1.0); per-file sources and hashes are in craft-libs
ATTRIBUTION.md. No PDF assets are copied into this repository, and PDFium is no longer used or
shipped.
Licence texts for the optional PDF reader
Hayro (MIT):
Copyright (c) The Hayro Authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Standard-14 Foxit fonts (BSD-3-Clause):
Copyright 2014 PDFium Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Adobe CMaps (BSD-3-Clause):
Copyright 1990-2023 Adobe. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Adobe nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Compact ICC profile: CC0 1.0 Universal (public domain dedication), by Clinton Ingram (saucecontrol/Compact-ICC-Profiles).
+2 -2
View File
@@ -185,8 +185,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
<table>
<tr>
<td width="33%" valign="top">
<h4>🧰 68 tools</h4>
Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
<h4>🧰 69 tools</h4>
Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom
</td>
<td width="33%" valign="top">
<h4>🖌️ A real brush engine</h4>
+2
View File
@@ -47,6 +47,8 @@ serde = { workspace = true }
tempfile = "3"
# Reading back a saved PSD's merged-image flag (#8064).
photocraft-psd = { workspace = true }
# A real ICC profile for the --metadata test (#9466).
photocraft-cms = { workspace = true }
# Synthetic camera raws (#7789).
photocraft-raw = { workspace = true, features = ["testgen"] }
# Shell completions and man pages (examples/man-and-completions.rs, for the packages); not in
+47 -1
View File
@@ -17,7 +17,7 @@ use clap::parser::ValueSource;
use clap::{ArgAction, ArgGroup, ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use photocraft_automation::args::{AutomationArgs, ControlArgs, blank_env_is_unset, conflict, control_port, name_env_vars};
use photocraft_codecs::{JpegFormat, TiffCompression};
use photocraft_io::{DdsCompression, DpxBits, TgaBits};
use photocraft_io::{DdsCompression, DpxBits, TgaBits, XmpEmbed};
use serde_json::Value;
/// photocraft-cli: headless PhotoCraft
@@ -93,6 +93,12 @@ pub(crate) struct ExportArgs {
/// real image
#[arg(long)]
pub(crate) no_maximize_compatibility: bool,
/// The document metadata a flat export embeds: all (the default) keeps the document's XMP
/// packet and free-form text where the format holds them, as Save As does; none leaves them
/// out, as Export As's Metadata: None. Nothing else changes: the ICC profile, EXIF and
/// resolution are written as they are without it. PSD, PSB and .pcraft always keep the XMP
#[arg(long, value_name = "none|all", value_parser = metadata)]
pub(crate) metadata: Option<XmpEmbed>,
}
/// Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …)
@@ -113,6 +119,12 @@ pub(crate) struct ConvertArgs {
/// Explicitly approve high-memory PSD/PSB imports within the hard memory budget
#[arg(long)]
pub(crate) approve_high_memory: bool,
/// PDF import resolution in DPI (default 300)
#[arg(long, value_name = "DPI", value_parser = pdf_dpi)]
pub(crate) pdf_dpi: Option<f32>,
/// PDF pages to import, 1-based: "3" or "2-7" (default all)
#[arg(long)]
pub(crate) pdf_pages: Option<String>,
#[command(flatten)]
pub(crate) gpu: GpuArgs,
#[command(flatten)]
@@ -312,8 +324,12 @@ enum ValueError {
TiffCompression,
#[error("expected baseline, optimized or progressive")]
JpegFormat,
#[error("expected none or all")]
Metadata,
#[error("expected on or off")]
OnOff,
#[error("expected a positive number")]
PdfDpi,
/// Why a `--bridge` value, or a PHOTOCRAFT_CONTROL_PORT value for `mcp`, is refused.
#[error("expected a port, 0-65535 (--bridge also takes 127.0.0.1:<PORT>)")]
Bridge,
@@ -382,10 +398,24 @@ fn on_off(s: &str) -> Result<bool, ValueError> {
}
}
/// A PDF import DPI: a finite number greater than zero. The importer's fallback to 300 DPI is
/// for absent preferences, not for a mistyped flag.
fn pdf_dpi(s: &str) -> Result<f32, ValueError> {
s.parse::<f32>().ok().filter(|dpi| dpi.is_finite() && *dpi > 0.0).ok_or(ValueError::PdfDpi)
}
fn jpeg_format(s: &str) -> Result<JpegFormat, ValueError> {
JpegFormat::parse(s).ok_or(ValueError::JpegFormat)
}
fn metadata(s: &str) -> Result<XmpEmbed, ValueError> {
match s {
"none" => Ok(XmpEmbed::None),
"all" => Ok(XmpEmbed::All),
_ => Err(ValueError::Metadata),
}
}
/// Where `mcp --bridge` connects. Shown as the address: `127.0.0.1:<PORT>` for a port.
#[derive(Clone)]
pub(crate) enum Bridge {
@@ -532,3 +562,19 @@ fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, tr
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// `--pdf-dpi` only takes a positive finite number: a mistyped value is refused at parse time
/// instead of silently becoming the importer's 300 DPI fallback.
#[test]
fn pdf_dpi_rejects_non_positive_and_non_finite_values() {
assert!(pdf_dpi("300").is_ok());
assert!(pdf_dpi("0.5").is_ok());
for bad in ["0", "-1", "nan", "inf", "-inf", "abc"] {
assert!(pdf_dpi(bad).is_err(), "{bad} should be refused");
}
}
}
+18 -1
View File
@@ -26,11 +26,28 @@ fn refuse_overwriting_input(in_place: bool, input: &Path, output: &Path) -> Resu
Ok(())
}
/// `N` or `N-M`, 1-based and inclusive, into a normalized `(first, last)`.
fn parse_pdf_pages(s: &str) -> Result<(u32, u32)> {
let (a, b) = s.split_once('-').unwrap_or((s, s));
let bad = || CliError::Other(format!("invalid --pdf-pages {s:?}; use N or N-M"));
let a = a.trim().parse::<u32>().map_err(|_| bad())?;
let b = b.trim().parse::<u32>().map_err(|_| bad())?;
if a == 0 || b == 0 {
return Err(CliError::Other(format!("--pdf-pages is 1-based; {s:?} starts at 0")));
}
Ok((a.min(b), a.max(b)))
}
pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write) -> Result {
let (input, output) = (&a.input, &a.output);
let opts = ExportOptions::from(&a.export);
refuse_overwriting_input(a.in_place, input, output)?;
let import_opts = photocraft_io::ImportOptions { psd_high_memory_approved: a.approve_high_memory, ..Default::default() };
let import_opts = photocraft_io::ImportOptions {
psd_high_memory_approved: a.approve_high_memory,
pdf_dpi: a.pdf_dpi.unwrap_or(300.0),
pdf_pages: a.pdf_pages.as_deref().map(parse_pdf_pages).transpose()?,
..Default::default()
};
let mut o = files::open_with_options(input, &import_opts)?;
// Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw.
photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document);
+4
View File
@@ -34,6 +34,10 @@ impl From<&ExportArgs> for ExportOptions {
}
o.encode.dds.mipmaps = a.dds_mipmaps;
o.psd_maximize_compatibility = !a.no_maximize_compatibility;
// Conversions keep the whole packet unless asked, as Save As does (#733, #9466).
if let Some(m) = a.metadata {
o.xmp = m;
}
o
}
}
+82
View File
@@ -980,6 +980,88 @@ fn jpeg_format_chooses_the_scans() {
}
}
/// #9466: `--metadata none` leaves the document's XMP packet and free-form text out of a flat
/// export from `convert`, `run --out` and `batch`, as Export As's Metadata: None does, and changes
/// nothing else (pixels, ICC profile, resolution). The default, and `all`, keep them as before (the
/// text where the format holds it, as PNG does), and a PSD or `.pcraft` keeps the XMP either way.
/// A value it doesn't name is a usage error and nothing is written.
#[test]
fn metadata_none_leaves_out_the_document_xmp() {
const XMP: &str = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
<rdf:Description rdf:about=\"\" xmlns:photoshop=\"http://ns.adobe.com/photoshop/1.0/\">\
<photoshop:DocumentAncestors><rdf:Bag><rdf:li>xmp.did:11111111-2222-3333-4444-555555555555</rdf:li></rdf:Bag></photoshop:DocumentAncestors>\
</rdf:Description></rdf:RDF></x:xmpmeta>";
let d = tmp("metadata");
let input = d.join("in");
std::fs::create_dir_all(&input).unwrap();
let a = input.join("a.png");
let data: Vec<u8> = (0..8 * 6 * 4).map(|i| (i as u8).wrapping_mul(7).wrapping_add(3)).collect();
let mut img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgba, data).unwrap();
img.meta.xmp = Some(XMP.into());
img.meta.dpi = Some((300.0, 300.0));
img.meta.text = vec![("Comment".into(), "free-form-note".into())];
// Display P3 rather than sRGB, so no export can pass for keeping it by writing its default.
let p3 = photocraft_cms::Builtin::DisplayP3.profile().to_bytes().to_vec();
img.icc = Some(p3.clone());
std::fs::write(&a, photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap();
let ancestors = |p: &Path| String::from_utf8_lossy(&std::fs::read(p).unwrap()).contains("DocumentAncestors");
let decoded = |p: &Path| photocraft_codecs::decode(&std::fs::read(p).unwrap()).unwrap();
let note = |p: &Path| decoded(p).meta.text.iter().any(|(_, v)| v == "free-form-note");
assert!(ancestors(&a) && note(&a), "the input carries the packet and the text");
let invert = r#"[{"command":"image.adjustments.invert"}]"#;
for ext in ["png", "webp", "jpg", "tif"] {
let mut converted_files = Vec::new();
for flag in [None, Some("all"), Some("none")] {
let extra: Vec<&str> = flag.map(|f| vec!["--metadata", f]).unwrap_or_default();
let name = format!("{ext}-{}", flag.unwrap_or("default"));
let converted = d.join(format!("convert-{name}.{ext}"));
ok(bin().arg("convert").arg(&a).arg(&converted).args(&extra));
let ran = d.join(format!("run-{name}.{ext}"));
ok(bin().arg("run").arg(&a).arg("--out").arg(&ran).args(&extra));
let o = batch_with(&d, &input, &format!("batch-{name}"), invert, &[&["--format", ext][..], &extra[..]].concat());
assert!(o.status.success(), "batch {name}: {}", String::from_utf8_lossy(&o.stderr));
let batched = d.join(format!("batch-{name}")).join(format!("a.{ext}"));
for out in [&converted, &ran, &batched] {
assert_eq!(ancestors(out), flag != Some("none"), "{name}: {}", out.display());
// PNG holds free-form text; JPEG, WebP and TIFF (but for its named tags) don't.
assert_eq!(note(out), ext == "png" && flag != Some("none"), "{name} text: {}", out.display());
}
converted_files.push(converted);
}
// Only the XMP and text go: the pixels, profile and resolution are the default export's.
let (default, none) = (decoded(&converted_files[0]), decoded(&converted_files[2]));
assert_eq!(none.data(), default.data(), "{ext}: pixels");
assert_eq!(default.icc.as_deref(), Some(&p3[..]), "{ext}: the default export keeps the input's Display P3 profile");
assert_eq!(none.icc, default.icc, "{ext}: ICC profile");
assert_eq!(none.meta.dpi, default.meta.dpi, "{ext}: resolution");
assert!(none.meta.dpi.is_some_and(|(x, y)| (x - 300.0).abs() < 0.5 && (y - 300.0).abs() < 0.5), "{ext}: {:?}", none.meta.dpi);
}
// A layered save keeps the document's XMP whatever the option.
for ext in ["psd", "pcraft"] {
let out = d.join(format!("layered.{ext}"));
ok(bin().arg("convert").arg(&a).arg(&out).args(["--metadata", "none"]));
let back = d.join(format!("layered-{ext}.png"));
ok(bin().arg("convert").arg(&out).arg(&back));
assert!(ancestors(&back), "{ext} kept the packet");
}
for bad in ["None", "exif", "0", ""] {
let out = d.join("bad.png");
let (mut convert, mut run) = (bin(), bin());
convert.arg("convert").arg(&a).arg(&out).args(["--metadata", bad]);
run.arg("run").arg(&a).arg("--out").arg(&out).args(["--metadata", bad]);
for cmd in [&mut convert, &mut run] {
let o = cmd.output().unwrap();
let err = String::from_utf8_lossy(&o.stderr);
assert_eq!(o.status.code(), Some(2), "--metadata {bad}: {err}");
assert!(err.contains("--metadata") && err.contains("expected none or all"), "--metadata {bad}: {err}");
assert!(!out.exists(), "--metadata {bad} wrote a file");
}
let o = batch_with(&d, &input, "bad-batch", invert, &["--metadata", bad]);
assert_eq!(o.status.code(), Some(2), "batch --metadata {bad}");
assert!(!d.join("bad-batch").exists(), "batch --metadata {bad} wrote a folder");
}
}
/// #492: an `--out` folder that is the `--in` folder, however it is spelt, is refused before
/// anything is written, unless `--in-place` asks for it.
#[test]
+1 -1
View File
@@ -6,7 +6,7 @@
//! - **macOS**: `NSEvent.mouseLocation`, converted into the content view of our window under it.
//! - **X11**: `QueryPointer` on our window (a second, pure-Rust X connection).
//! - **Windows**: `GetCursorPos`, relative to the window's client area.
//! - **Wayland**: winit 0.30 delivers no file drops there, so there's nothing to place.
//! - **Wayland**: winit delivers file drops, and egui's last pointer position is used as fallback.
//!
//! No `unsafe`: every OS call goes through a safe binding.
//!
+21
View File
@@ -35,6 +35,27 @@ Warnings do not change the saved document's font declarations and do not stop
the operation. To list or replace the missing families intentionally, use
`type.resolveMissingFonts` on the document.
### Document metadata
`convert`, `run --out` and `batch` keep the document's XMP packet in a flat
export whose format holds one (PNG, JPEG, WebP, TIFF, …), and its free-form
text where the format holds that too (PNG text chunks, TIFF's named text tags
such as ImageDescription; JPEG and WebP have no place for it), as Save As
does. `--metadata none` leaves them out, as Export As's Metadata: None does:
a Photoshop file's XMP can list every placed document's id
(`DocumentAncestors`) and the text of every type layer, and can be far larger
than the image. `--metadata all` is the default. The option changes nothing
else: the ICC profile, EXIF and resolution are written as they are without
it, where the format holds them. An Indexed Color document saved as a palette
PNG carries no XMP, text, ICC profile or EXIF with either value, only its
resolution. PSD, PSB and `.pcraft` saves always keep the XMP. It is not a full
metadata scrub.
```sh
photocraft-cli batch --actions resize.json --in masters/ --out web/ \
--format webp --metadata none
```
### Export selected adjustment layers as a .cube LUT
The engine command `file.export.colorLookupTables` creates a 3D LUT from an
+36 -1
View File
@@ -60,7 +60,11 @@ fn over(b: Cmyka, s: Cmyka, opacity: f32) -> Cmyka {
}
let mut o = [0.0; 5];
for i in 0..4 {
o[i] = (s[i] * sa + b[i] * b[4] * (1.0 - sa)) / a;
// Over nothing, under a covering source, or where both inks agree, the result is the
// source's ink exactly: `s * sa / sa` can be one ulp off, which a later mode or
// rounding step can turn into a whole level.
let shows_through = b[4] > 0.0 && sa < 1.0;
o[i] = if !shows_through || b[i] == s[i] { s[i] } else { (s[i] * sa + b[i] * b[4] * (1.0 - sa)) / a };
}
o[4] = a;
o
@@ -762,6 +766,37 @@ fn clips_onto_pass_through(layers: &[LayerSpec]) -> bool {
}) || layers.iter().any(|l| matches!(l, LayerSpec::Group { children, .. } if clips_onto_pass_through(children)))
}
/// A proptest case from main's CI: a masked shape below 100% Fill, then Posterize in Color
/// Burn (Paint.NET) inside an isolated group. The burned brightness is exactly 73.5/255.
#[test]
fn posterize_in_paint_net_color_burn_on_a_rounding_tie_matches_the_reference() {
let shape = LayerSpec::Pixels {
kind: Kind::Shape,
blend: BlendMode::Normal,
fills: vec![(Rect::new(0, 0, 1, 1), [0.47422728, 0.0, 0.0, 0.0, 1.0])],
opacity: 1.0,
fill: 0.876696,
clipped: false,
visible: true,
mask: Some(MaskSpec { rects: vec![], default: 0.06425183, density: 1.0, enabled: true }),
};
let posterize = LayerSpec::Pixels {
kind: Kind::Adjust(AdjSpec::Posterize(4)),
blend: BlendMode::PaintNetColorBurn,
fills: vec![(Rect::new(0, 0, 1, 1), [0.0; 5])],
opacity: 1.0,
fill: 1.0,
clipped: false,
visible: true,
mask: None,
};
let group = LayerSpec::Group { children: vec![shape, posterize], pass_through: false, blend: BlendMode::Normal, opacity: 1.0, fill: 1.0, mask: None };
let s = Spec { w: 8, h: 6, layers: vec![group] };
let mut d = doc(s.w as u32, s.h as u32);
d.layers = s.layers.iter().map(build).collect();
assert_matches_reference(&d);
}
proptest! {
#![proptest_config(ProptestConfig { cases: 400, ..ProptestConfig::default() })]
+31 -1
View File
@@ -344,6 +344,9 @@ impl Tile {
/// Most taps per axis of the minification filter (the WGSL mirror uses the same cap).
const MAX_TAPS: usize = 8;
/// The smallest pattern scale a placement draws at (a fraction): keeps tile coordinates finite.
pub const MIN_PLACEMENT_SCALE: f64 = 1e-6;
/// Taps per axis for a placement whose inverse scale is `inv_scale`: one pixel covers
/// `inv_scale` tile pixels, so that many taps (capped) box-filter it. 1 at 100 % and above.
fn pixel_taps(inv_scale: f64) -> usize {
@@ -387,7 +390,9 @@ impl Placement {
let base = if link { anchor } else { (0.0, 0.0) };
let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1));
let s = f64::from(scale);
let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 };
// Any positive scale draws: a preview at a reduced work scale takes a stored 2 % pattern
// well below 0.1 %. Only 0, negatives and non-finite values fall back to 100 %.
let inv_scale = if s.is_finite() && s > 0.0 { 1.0 / s.max(MIN_PLACEMENT_SCALE) } else { 1.0 };
let a = f64::from(angle).to_radians();
Placement { origin, cs: (a.cos(), a.sin()), inv_scale }
}
@@ -608,6 +613,31 @@ mod tests {
assert_eq!((row[0][0], row[1][0]), (0.0, 1.0));
}
/// Review of #9256: a preview at 4 % work scale draws a stored 2 % pattern at 0.08 %, which
/// used to fall back to 100 % and show the stripes full size.
#[test]
fn placement_keeps_scales_below_a_tenth_of_a_percent() {
let place = Placement::new(Rect::EMPTY, false, (0.0, 0.0), 0.0008, 0.0);
let (u, v) = place.map(1.0, 2.0);
assert!((u - 1250.0).abs() < 1e-3 && (v - 2500.0).abs() < 1e-3, "{u},{v}");
// 1-px dark / light stripes: at 100 % the pixels alternate 0 / 1; at 0.08 % each pixel
// covers 1250 of them, so every pixel is their mean.
let mut s = Surface::new(PixelFormat::RGBA8);
s.fill_rect(Rect::new(0, 0, 8, 8), &[1.0, 1.0, 1.0, 1.0]);
for x in (0..8).step_by(2) {
s.fill_rect(Rect::new(x, 0, x + 1, 8), &[0.0, 0.0, 0.0, 1.0]);
}
let t = Tile::new(&Pattern::new("stripes", s, 8, 8)).unwrap();
for p in render(&t, &place, Rect::new(0, 0, 8, 1)) {
assert!((p[0] - 0.5).abs() < 0.1, "{p:?}");
}
// 0, negative and non-finite scales still draw at 100 %.
for bad in [0.0, -0.5, f32::NAN, f32::INFINITY] {
let p = Placement::new(Rect::EMPTY, false, (0.0, 0.0), bad, 0.0);
assert_eq!(p.map(3.0, 0.0).0, 3.0, "{bad}");
}
}
#[test]
fn sampling_at_hostile_phases_does_not_overflow() {
let patterns = [checker()];
+4
View File
@@ -10,6 +10,10 @@ use serde::{Deserialize, Serialize};
use crate::adjust::CurvePoint;
/// The range of a style's pattern scale as a fraction (1 = 100 %): Pattern Overlay, a pattern
/// Stroke and the Bevel & Emboss Texture all take 1..1000 % in the Layer Style dialog.
pub const PATTERN_SCALE_RANGE: (f32, f32) = (0.01, 10.0);
/// Gradient geometry (fill layers, gradient overlays, gradient strokes).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum GradientStyle {
+8 -3
View File
@@ -1105,6 +1105,8 @@ pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result<Value> {
}
b = merge_brush(&b, &patch, cmd)?;
validate_brush(&b, cmd)?;
// The painting tools' Opacity takes 1-100 %, as in Photoshop: a 0 % brush paints nothing (#11812).
b.opacity = b.opacity.max(0.01);
// Loading a stored tip can fail. Finish preparing the brush before changing its identity or
// foreground colour, so a failed pick leaves the entire current brush state intact.
s.load_brush_tips(&mut b).map_err(|e| bad(cmd, e))?;
@@ -1170,8 +1172,8 @@ pub fn remembered_settings(b: &BrushSettings) -> Option<Value> {
/// A brush remembered by [`remembered_settings`], read back at launch: `None` when the value is
/// not a brush or fails the checks `tools.setBrush` makes (a size or scatter out of range). The
/// options-bar values are clamped to the ranges their controls allow (size 1..max px; hardness,
/// opacity, flow and smoothing 0..100 %), and stored tips load when the store is attached (else
/// options-bar values are clamped to the ranges their controls allow (size 1..max px; opacity
/// 1..100 %; hardness, flow and smoothing 0..100 %), and stored tips load when the store is attached (else
/// they paint with their previews until `Session::attach_preset_store`).
pub fn restored_settings(s: &Session, v: &Value) -> Option<BrushSettings> {
if !v.is_object() {
@@ -1183,6 +1185,9 @@ pub fn restored_settings(s: &Session, v: &Value) -> Option<BrushSettings> {
for f in [&mut b.hardness, &mut b.opacity, &mut b.flow, &mut b.smoothing.amount] {
*f = if f.is_nan() { 1.0 } else { f.clamp(0.0, 1.0) };
}
// Opacity takes 1-100 %, as `tools.setBrush` floors it: a brush remembered at 0 % (saved
// before that floor) would show 1 % but paint nothing (#11812).
b.opacity = b.opacity.max(0.01);
let _ = s.load_brush_tips(&mut b);
Some(b)
}
@@ -1365,7 +1370,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"tools.setBrush",
"Set Brush",
r##"{"preset":name?,"reset":bool?,…BrushSettings fields (camelCase, deep-merged; pose.overrideTiltX/Y:bool; pose.overrideTilt:legacy combined alias)}"##,
r##"{"preset":name?,"reset":bool?,…BrushSettings fields (camelCase, deep-merged; pose.overrideTiltX/Y:bool; pose.overrideTilt:legacy combined alias; opacity floors at 0.01)}"##,
always,
set_brush,
true
+16
View File
@@ -1380,6 +1380,22 @@ fn restored_brush_settings_are_clamped_or_rejected() {
}
}
/// #11812: a brush remembered at 0 % opacity (saved before the 1 % floor) reads back at 1 %, the
/// value its options-bar field shows, so it paints instead of laying down nothing.
#[test]
fn restored_brush_opacity_floors_at_one_percent() {
let s = Session::new();
for opacity in [0.0, -1.0, 0.004] {
let b = restored_settings(&s, &json!({"opacity": opacity})).unwrap();
assert_eq!(b.opacity, 0.01, "{opacity}");
}
assert_eq!(restored_settings(&s, &json!({"opacity": 0.37})).unwrap().opacity, 0.37, "values above the floor are kept");
let mut t = Session::new();
t.prefs.edit(|p| p.last_brush = json!({"brush": {"opacity": 0.0}}));
restore_brush(&mut t);
assert_eq!(t.tools.brush.opacity, 0.01, "the remembered session brush");
}
#[test]
fn remembered_brushes_never_embed_large_bitmaps() {
use std::sync::Arc;
+18 -2
View File
@@ -899,7 +899,9 @@ fn ink_surface(s: &Surface, d: &Duotone) -> Surface {
}
/// Image › Mode › RGB/Grayscale/CMYK/Lab through the CMS. Params: `profile` (destination,
/// default the mode's working profile), `intent` (default relative), `bpc` (default true).
/// default the mode's working profile; Indexed→RGB without an explicit profile instead expands
/// the already-RGB storage without changing its encoded samples or ICC bytes), `intent`
/// (default relative), `bpc` (default true).
pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value> {
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
if doc.mode == ColorMode::Multichannel && mode != ColorMode::Multichannel {
@@ -908,8 +910,13 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value
if doc.mode == mode && p.get("profile").is_none() {
return Ok(Value::Null);
}
let preserve_indexed_rgb = p.get("profile").and_then(Value::as_str).is_none()
&& doc.mode == ColorMode::Indexed
&& mode == ColorMode::Rgb
&& doc.icc_profile.as_ref().is_none_or(|bytes| profile_from_bytes(bytes).ok().is_some_and(|p| p.color_space == ColorSpace::Rgb));
let dst = match p.get("profile").and_then(Value::as_str) {
Some(spec) => s.color.resolve(spec, Some(doc), Some(mode))?,
None if preserve_indexed_rgb => document_profile(doc),
None => s.color.working(mode),
};
if space_mode(dst.color_space)
@@ -923,7 +930,16 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value
}
let intent = intent_or(p, s.color.settings.intent())?;
let bpc = bool_param(p, "bpc", s.color.settings.bpc);
s.edit("Mode Change", |doc, _| convert_document(doc, &dst, intent, bpc))?;
if preserve_indexed_rgb {
s.edit("Mode Change", |doc, _| {
doc.mode = ColorMode::Rgb;
doc.color_table = None;
doc.duotone = None;
Ok(())
})?;
} else {
s.edit("Mode Change", |doc, _| convert_document(doc, &dst, intent, bpc))?;
}
Ok(json!({ "profile": dst.description, "intent": intent.id(), "bpc": bpc }))
}
+2 -2
View File
@@ -140,7 +140,7 @@ fn background_eraser_setup(s: &Session, p: &Value) -> Result<(Stroke, BgEraseSet
let bs = BgEraseSettings {
sampling: enum_param(p, CMD, "sampling", Sampling::Continuous, "continuous|once|backgroundSwatch")?,
limits: enum_param(p, CMD, "limits", Limits::Contiguous, "discontiguous|contiguous|findEdges")?,
tolerance: number(p, CMD, "tolerance", 50.0, 0.0..=100.0)? as f32 / 100.0,
tolerance: number(p, CMD, "tolerance", 50.0, 1.0..=100.0)? as f32 / 100.0,
protect_foreground: flag(p, "protectForegroundColor", false),
foreground: s.tools.foreground,
background: s.tools.background,
@@ -267,7 +267,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Background Eraser",
menu: &[],
shortcut: None,
params: r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"brush":{…}?,"preset":name?,"sampling":"continuous|once|backgroundSwatch"="continuous","limits":"discontiguous|contiguous|findEdges"="contiguous","tolerance":0..100=50,"protectForegroundColor":bool=false,"seed":u64?}"##,
params: r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"brush":{…}?,"preset":name?,"sampling":"continuous|once|backgroundSwatch"="continuous","limits":"discontiguous|contiguous|findEdges"="contiguous","tolerance":1..100=50,"protectForegroundColor":bool=false,"seed":u64?}"##,
enabled: has_pixel_layer,
run: background_eraser,
journal: true,
+40 -6
View File
@@ -134,9 +134,21 @@ pub(crate) fn reidentify_copied_layers(doc: &mut Document) {
}
}
/// Scale every size and distance of a style by `k` (Image Size's Scale Styles, Layer Style ›
/// Scale Effects, and previews that draw a style at a reduced resolution).
/// Scale every size and distance of a style by `k` (Image Size's Scale Styles and Layer Style ›
/// Scale Effects), with pattern scales kept within the dialog's 1..1000 %.
pub fn scale_effects(fx: &mut Effects, k: f32) {
scale_effects_with(fx, k, true);
}
/// [`scale_effects`] for a preview that draws a style at a reduced resolution: pattern scales
/// follow `k` exactly, so the preview matches the style it stands for (a 2 % pattern drawn at a
/// quarter of the size is 0.5 %, not the dialog's 1 % minimum).
pub fn scale_effects_preview(fx: &mut Effects, k: f32) {
scale_effects_with(fx, k, false);
}
fn scale_effects_with(fx: &mut Effects, k: f32, clamp: bool) {
let pattern = |scale: &mut f32| scale_pattern(scale, k, clamp);
for e in &mut fx.items {
match e {
Effect::DropShadow(s) | Effect::InnerShadow(s) => {
@@ -152,14 +164,17 @@ pub fn scale_effects(fx: &mut Effects, k: f32) {
Effect::BevelEmboss(b) => {
b.size *= k;
b.soften *= k;
if let Some(t) = &mut b.texture {
pattern(&mut t.scale);
}
}
Effect::PatternOverlay { scale, .. } => *scale *= k,
Effect::PatternOverlay { scale, .. } => pattern(scale),
Effect::GradientOverlay { .. } | Effect::ColorOverlay { .. } => {}
}
if let Effect::Stroke(s) = e
&& let FxPaint::Pattern { scale, .. } = &mut s.paint
{
*scale *= k;
pattern(scale);
}
}
// Effects changed: the preserved PSD block no longer applies.
@@ -168,6 +183,16 @@ pub fn scale_effects(fx: &mut Effects, k: f32) {
}
}
/// Scale a style's pattern scale; with `clamp`, kept within the 1..1000 % the Layer Style dialog
/// and the reference application allow (a 10 % pattern reduced to 5 % stays at 1 %).
fn scale_pattern(scale: &mut f32, k: f32, clamp: bool) {
let (min, max) = photocraft_doc::effects::PATTERN_SCALE_RANGE;
let v = *scale * k;
if !v.is_nan() {
*scale = if clamp { v.clamp(min, max) } else { v };
}
}
/// Image Size's resampling methods; `None` changes the resolution only.
#[derive(Clone, Copy)]
enum Method {
@@ -755,6 +780,7 @@ fn crop_with(s: &mut Session, p: &Value, keep_background: bool) -> Result<Value>
let unlock = !delete && !content_aware && !keep_background;
// Values beyond i32 would wrap through the narrowing casts into a rectangle unrelated to
// the numbers passed; reject them (see `commands::int_i32`).
let given = ["x", "y", "width", "height"].into_iter().any(|k| p.get(k).is_some_and(|v| !v.is_null()));
let explicit = match (
crate::commands::int_i32("image.crop", p, "x")?,
crate::commands::int_i32("image.crop", p, "y")?,
@@ -775,6 +801,14 @@ fn crop_with(s: &mut Session, p: &Value, keep_background: bool) -> Result<Value>
};
Some(Rect::new(x, y, end(x, w, "x", "width")?, end(y, h, "y", "height")?))
}
// A rectangle that is passed but incomplete or empty is refused: falling back to the
// selection would crop somewhere the caller didn't ask for (#9279).
_ if given => {
return Err(bad(
"image.crop",
"`x`, `y`, `width` and `height` go together: pass all four as numbers of pixels, with `width` and `height` rounding to at least 1",
));
}
_ => None,
};
let target = crop_target(p)?;
@@ -1206,7 +1240,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.crop",
"Crop",
["Image"],
r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true,"contentAware":bool=false,"targetWidth":px,"targetHeight":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"} → {x,y,width,height,documentWidth,documentHeight,resolution} (targetWidth/targetHeight, both or neither: the cropped area is resampled to exactly that size, as Image Size, in the same undo step; resolution: the document's new ppi; deleteCroppedPixels false: the pixels past the frame are kept and, unless contentAware, the Background becomes a normal layer, "Layer 0", so an extension is transparent on every layer (with contentAware the Background stays); contentAware: the Crop tool's Fill › Content-Aware Fill uses surrounding pixels to fill areas uncovered by a rotated or extending crop. The fill targets the Background, or the active pixel layer if there is no Background. With Delete Cropped Pixels on, it also targets a separate active pixel layer if it is visible and unlocked.)"##,
r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true,"contentAware":bool=false,"targetWidth":px,"targetHeight":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"} → {x,y,width,height,documentWidth,documentHeight,resolution} (x/y/width/height, all four or none: without them the selection's bounds are cropped to; targetWidth/targetHeight, both or neither: the cropped area is resampled to exactly that size, as Image Size, in the same undo step; resolution: the document's new ppi; deleteCroppedPixels false: the pixels past the frame are kept and, unless contentAware, the Background becomes a normal layer, "Layer 0", so an extension is transparent on every layer (with contentAware the Background stays); contentAware: the Crop tool's Fill › Content-Aware Fill uses surrounding pixels to fill areas uncovered by a rotated or extending crop. The fill targets the Background, or the active pixel layer if there is no Background. With Delete Cropped Pixels on, it also targets a separate active pixel layer if it is visible and unlocked.)"##,
has_doc,
crop
),
@@ -1222,7 +1256,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.mode.rgb",
"RGB Color",
["Image", "Mode"],
r##"{"profile":"<builtin id>|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##,
r##"{"profile":"<builtin id>|working|/path/to/profile.icc"=working (Indexed→RGB preserves the document profile unless explicit),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##,
has_doc,
|s, p| convert_mode(s, ColorMode::Rgb, p)
),
+95
View File
@@ -429,6 +429,101 @@ fn crop_to_explicit_rect_can_extend_canvas() {
assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 5), vec![1.0, 0.0, 0.0, 1.0]);
}
/// A rectangle that is passed but invalid is refused, not replaced by the selection (#9279).
#[test]
fn crop_refuses_a_bad_explicit_rect_instead_of_cropping_to_the_selection() {
let bad = [
json!({"x": 10, "y": 10, "width": 0, "height": 50}),
json!({"x": 10, "y": 10, "width": 20, "height": 0}),
json!({"x": 10, "y": 10, "width": -50, "height": 50}),
json!({"x": 10, "y": 10, "width": "100", "height": 50}),
json!({"x": 10, "y": 10, "width": true, "height": 50}),
json!({"width": 20, "height": 10}),
json!({"x": 1, "y": 1}),
json!({"x": 1, "y": null, "width": 20, "height": 10}),
json!({"height": 10}),
];
for p in bad {
for selection in [true, false] {
let mut s = session();
if selection {
s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap();
}
let (size, past) = (doc(&s).size, s.active().unwrap().history.past_len());
let err = s.execute("image.crop", p.clone()).unwrap_err();
assert!(matches!(err, EngineError::BadParams { .. }), "{p} (selection: {selection}): {err:?}");
assert_eq!(doc(&s).size, size, "{p} (selection: {selection})");
assert_eq!(doc(&s).selection.is_some(), selection, "{p}: the selection stays");
assert_eq!(s.active().unwrap().history.past_len(), past, "{p} (selection: {selection})");
}
}
// No rectangle at all (or every side null) still crops to the selection.
for p in [json!({}), json!({"x": null, "y": null, "width": null, "height": null})] {
let mut s = session();
s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap();
s.execute("image.crop", p.clone()).unwrap();
assert_eq!(doc(&s).size, Size::new(20, 10), "{p}");
}
// Whole-number floats, as the Crop tool sends them, are a valid rectangle.
let mut s = session();
s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap();
s.execute("image.crop", json!({"x": 1.0, "y": 1.0, "width": 30.0, "height": 15.0})).unwrap();
assert_eq!(doc(&s).size, Size::new(30, 15));
// Fractional pixels round, like the rectangle's `x`/`y` and every other pixel param
// (`commands::int`); a side that rounds to 0 is refused.
let mut s = session();
s.execute("image.crop", json!({"x": 0.4, "y": 0.6, "width": 20.6, "height": 9.5})).unwrap();
assert_eq!(doc(&s).size, Size::new(21, 10));
let err = s.execute("image.crop", json!({"x": 0, "y": 0, "width": 0.4, "height": 5})).unwrap_err();
assert!(matches!(err, EngineError::BadParams { .. }), "{err:?}");
assert_eq!(doc(&s).size, Size::new(21, 10));
}
/// The explicit rectangle of #9279's edge cases, each with a selection elsewhere that a fallback
/// would crop to: `0` is a given origin, numeric strings are not numbers (refused, as `x`/`y`
/// already were), and a rectangle partly past the canvas is used as passed, never clamped.
#[test]
fn crop_rect_edge_cases_never_fall_back_to_the_selection() {
let with_selection = || {
let mut s = session();
s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap();
s
};
// `x`/`y` of 0 count as given: the red square (10, 5)..(20, 15) stays where it was, where a
// crop to the selection would have moved it to (5, 3).
let mut s = with_selection();
s.execute("image.crop", json!({"x": 0, "y": 0, "width": 15, "height": 10})).unwrap();
assert_eq!(doc(&s).size, Size::new(15, 10));
assert_eq!(doc(&s).layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 15, 10));
// Numeric strings are refused on every side, with or without a selection.
for p in [
json!({"x": "0", "y": "0", "width": "15", "height": "10"}),
json!({"x": "0", "y": 0, "width": 15, "height": 10}),
json!({"x": 0, "y": 0, "width": 15, "height": "10"}),
] {
for mut s in [with_selection(), session()] {
let err = s.execute("image.crop", p.clone()).unwrap_err();
assert!(matches!(err, EngineError::BadParams { .. }), "{p}: {err:?}");
assert_eq!(doc(&s).size, Size::new(40, 20), "{p}");
}
}
// Partly outside the canvas: the canvas grows to the rectangle, not to its overlap with the
// canvas or the selection.
let mut s = with_selection();
s.execute("image.crop", json!({"x": -10, "y": -5, "width": 30, "height": 40})).unwrap();
assert_eq!(doc(&s).size, Size::new(30, 40));
assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 10), vec![1.0, 0.0, 0.0, 1.0]);
// Reveal All passes all four sides through the same check (here x = y = 0: the hidden pixels
// are past the right and bottom edges), so a selection doesn't change what it reveals.
let mut s = with_selection();
s.execute("image.canvasSize", json!({"width": 12, "height": 8, "anchor": "topLeft"})).unwrap();
s.execute("select.rect", json!({"x": 2, "y": 2, "width": 4, "height": 4})).unwrap();
assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], true);
let size = doc(&s).size;
assert!(size.width >= 20 && size.height >= 15, "{size:?}: the red square is revealed");
assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(19, 14), vec![1.0, 0.0, 0.0, 1.0]);
}
#[test]
fn crop_extension_fills_the_background_with_the_background_colour() {
let mut shrink = Session::new();
@@ -140,6 +140,119 @@ fn global_light_blending_options_scale_effects() {
}
}
#[test]
fn scale_effects_scales_the_bevel_texture_with_the_pattern_overlay() {
let mut s = session(8, "rgb");
paint(&mut s, disc);
s.execute("layer.layerStyle.patternOverlay", json!({"scale": 100})).unwrap();
s.execute("layer.layerStyle.bevelEmboss", json!({"texture": "Bubbles", "textureScale": 100})).unwrap();
s.execute("layer.layerStyle.scaleEffects", json!({"scale": 50})).unwrap();
let fx = &active(&s).effects.items;
let overlay = fx.iter().find_map(|e| match e {
Effect::PatternOverlay { scale, .. } => Some(*scale),
_ => None,
});
let texture = fx.iter().find_map(|e| match e {
Effect::BevelEmboss(b) => b.texture.as_ref().map(|t| t.scale),
_ => None,
});
// Both patterns tile at half size, so a texture aligned with the overlay stays aligned.
assert_eq!((overlay, texture), (Some(0.5), Some(0.5)));
}
/// The pattern scales of Pattern Overlay, the Bevel & Emboss Texture and a pattern Stroke, in
/// that order.
fn pattern_scales(s: &Session) -> (Option<f32>, Option<f32>, Option<f32>) {
let fx = &active(s).effects.items;
let overlay = fx.iter().find_map(|e| match e {
Effect::PatternOverlay { scale, .. } => Some(*scale),
_ => None,
});
let texture = fx.iter().find_map(|e| match e {
Effect::BevelEmboss(b) => b.texture.as_ref().map(|t| t.scale),
_ => None,
});
let stroke = fx.iter().find_map(|e| match e {
Effect::Stroke(st) => match &st.paint {
photocraft_doc::FxPaint::Pattern { scale, .. } => Some(*scale),
_ => None,
},
_ => None,
});
(overlay, texture, stroke)
}
/// A layer with a Pattern Overlay, a Bevel & Emboss Texture and a pattern Stroke, all at `pct` %.
fn pattern_styled(pct: f64) -> Session {
let mut s = session(8, "rgb");
paint(&mut s, disc);
s.execute("layer.layerStyle.patternOverlay", json!({"scale": pct})).unwrap();
s.execute("layer.layerStyle.bevelEmboss", json!({"texture": "Bubbles", "textureScale": pct})).unwrap();
s.execute("layer.layerStyle.stroke", json!({"size": 3})).unwrap();
s.edit("pattern stroke", |doc, active| {
let layer = doc.layer_mut(active.unwrap()).unwrap();
for e in &mut layer.effects.items {
if let Effect::Stroke(st) = e {
st.paint = photocraft_doc::FxPaint::Pattern { name: "Bubbles".into(), id: String::new(), scale: pct as f32 / 100.0 };
}
}
Ok(())
})
.unwrap();
s
}
#[test]
fn scale_effects_keeps_pattern_scales_within_the_dialog_range() {
// 10 % reduced to 1 % would be 0.1 %: the patterns stop at the dialog's 1 %.
let mut s = pattern_styled(10.0);
s.execute("layer.layerStyle.scaleEffects", json!({"scale": 1})).unwrap();
assert_eq!(pattern_scales(&s), (Some(0.01), Some(0.01), Some(0.01)));
// 500 % enlarged to 1000 % would be 5000 %: they stop at 1000 %.
let mut s = pattern_styled(500.0);
s.execute("layer.layerStyle.scaleEffects", json!({"scale": 1000})).unwrap();
assert_eq!(pattern_scales(&s), (Some(10.0), Some(10.0), Some(10.0)));
// Inside the range nothing is clamped: 200 % halved is 100 %.
let mut s = pattern_styled(200.0);
s.execute("layer.layerStyle.scaleEffects", json!({"scale": 50})).unwrap();
assert_eq!(pattern_scales(&s), (Some(1.0), Some(1.0), Some(1.0)));
}
/// Previews at a reduced resolution scale the patterns exactly, past the dialog's range: only
/// commands that store the style clamp them.
#[test]
fn preview_scaling_leaves_pattern_scales_unclamped() {
let s = pattern_styled(2.0);
let mut fx = active(&s).effects.clone();
crate::image_cmds::scale_effects_preview(&mut fx, 0.25);
let mut clamped = active(&s).effects.clone();
crate::image_cmds::scale_effects(&mut clamped, 0.25);
let scales = |fx: &photocraft_doc::Effects| {
fx.items
.iter()
.filter_map(|e| match e {
Effect::PatternOverlay { scale, .. } => Some(*scale),
Effect::BevelEmboss(b) => b.texture.as_ref().map(|t| t.scale),
Effect::Stroke(st) => match &st.paint {
photocraft_doc::FxPaint::Pattern { scale, .. } => Some(*scale),
_ => None,
},
_ => None,
})
.collect::<Vec<_>>()
};
assert_eq!(scales(&fx), vec![0.005; 3]);
assert_eq!(scales(&clamped), vec![0.01; 3]);
}
#[test]
fn image_size_scale_styles_keeps_pattern_scales_within_the_dialog_range() {
// 40x30 -> 400x300 with Scale Styles multiplies by 10: 500 % would become 5000 %.
let mut s = pattern_styled(500.0);
s.execute("image.imageSize", json!({"width": 400, "height": 300, "scaleStyles": true})).unwrap();
assert_eq!(pattern_scales(&s), (Some(10.0), Some(10.0), Some(10.0)));
}
#[test]
fn global_light_rejects_numbers_beyond_f32() {
let mut s = session(8, "rgb");
+68 -2
View File
@@ -9,6 +9,7 @@
use photocraft_algo::quantize::{self, BitmapMethod, Dither, Forced, HalftoneShape, PaletteKind};
use photocraft_algo::transform::{Homography, Interp};
use photocraft_cms::{ColorSpace, TransformOptions};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_doc::adjust::CurvePoint;
use photocraft_doc::{ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size};
@@ -255,6 +256,56 @@ fn parse_dither(s: &str) -> Option<Dither> {
})
}
/// Convert a tool colour from the working RGB space into the samples used by the
/// flattened document. RGB and Indexed documents keep their own document profile;
/// grayscale output is a scalar sample replicated into the flattened RGB view.
fn working_matte_color(s: &Session, doc: &Document, color: [f32; 4]) -> Result<[f32; 3]> {
let destination = match crate::color_cmds::mode_space(doc.mode) {
ColorSpace::Rgb | ColorSpace::Gray => crate::color_cmds::document_profile(doc),
// CMYK and Lab flatten through the compositor's sRGB view on the pinned main path.
_ => crate::color_cmds::composite_profile(doc),
};
let source = s.color.working(ColorMode::Rgb);
let options = TransformOptions { intent: s.color.settings.intent(), bpc: s.color.settings.bpc, ..Default::default() };
let transform = photocraft_cms::transform::cached(&source, &destination, options)
.map_err(|e| bad("image.mode.indexedColor", format!("cannot convert matte colour: {e}")))?;
let mut output = [0.0; 16];
transform.eval(&color[..3], &mut output);
let matte = if destination.color_space == ColorSpace::Gray { [output[0]; 3] } else { [output[0], output[1], output[2]] };
if matte.iter().any(|v| !v.is_finite()) {
return Err(bad("image.mode.indexedColor", "cannot convert matte colour to finite document samples"));
}
Ok(matte.map(|v| v.clamp(0.0, 1.0)))
}
fn indexed_matte(s: &Session, p: &Value) -> Result<Option<[f32; 3]>> {
const CMD: &str = "image.mode.indexedColor";
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
let matte = match p.get("matte") {
None | Some(Value::Null) => return Ok(None),
Some(Value::String(value)) => match value.as_str() {
"none" => return Ok(None),
"white" => [1.0; 3],
"black" => [0.0; 3],
"gray" => [128.0 / 255.0; 3],
"netscapeGray" => [192.0 / 255.0; 3],
"foreground" => working_matte_color(s, doc, s.tools.foreground)?,
"background" => working_matte_color(s, doc, s.tools.background)?,
value if value.len() == 7 && value.starts_with('#') => p
.get("matte")
.and_then(parse_color)
.ok_or_else(|| bad(CMD, "matte must be none, foreground, background, white, black, gray, netscapeGray or #rrggbb"))?
.map(|v| f32::from(v) / 255.0),
_ => return Err(bad(CMD, "matte must be none, foreground, background, white, black, gray, netscapeGray or #rrggbb")),
},
_ => return Err(bad(CMD, "matte must be a colour string")),
};
if matte.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v)) {
return Err(bad(CMD, "matte channels must be finite and in 0..=1"));
}
Ok(Some(matte))
}
fn indexed_color(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "image.mode.indexedColor";
let kind = PaletteKind::from_id(str_or(p, "palette", "selective"))
@@ -273,8 +324,23 @@ fn indexed_color(s: &mut Session, p: &Value) -> Result<Value> {
};
let amount = num(p, "amount", 75.0).clamp(0.0, 100.0) / 100.0;
let transparency = p.get("transparency").and_then(Value::as_bool).unwrap_or(true);
let matte = indexed_matte(s, p)?;
let (pal_len, transparent) = s.edit("Indexed Color", |doc, active| {
let mut px = composite(doc, !transparency);
let mut px = composite(doc, !transparency && matte.is_none());
if let Some(matte) = matte {
for pixel in &mut px {
let alpha = pixel[3].clamp(0.0, 1.0);
if alpha == 1.0 {
continue;
}
if !transparency || alpha > 0.0 {
for (channel, background) in pixel[..3].iter_mut().zip(matte) {
*channel = *channel * alpha + background * (1.0 - alpha);
}
pixel[3] = 1.0;
}
}
}
let has_clear = transparency && px.iter().any(|q| q[3] < 0.5);
let mut pal = quantize::build_palette(&px, kind, if has_clear { colors.saturating_sub(1).max(2) } else { colors }, forced).map_err(|e| bad(CMD, e))?;
let transparent = if has_clear && pal.len() < 256 {
@@ -689,7 +755,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.mode.indexedColor",
"Indexed Color…",
["Image", "Mode"],
r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens)"##,
r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"matte":color,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens; matte: none|foreground|background|white|black|gray|netscapeGray|#rrggbb; gray=50% Gray (#808080), netscapeGray=Netscape Gray (#c0c0c0))"##,
|s| mode_is(
s,
&[ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Indexed, ColorMode::Duotone, ColorMode::Cmyk, ColorMode::Lab],
+154
View File
@@ -247,6 +247,160 @@ fn indexed_color_palettes_and_dithers() {
}
}
#[test]
fn indexed_exact_preserves_profile_and_samples_through_default_rgb() {
for depth in [8, 16, 32] {
for profile in ["adobe-rgb-compat", "display-p3", "prophoto-compat", "none"] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 1, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
s.execute("edit.assignProfile", json!({"profile": profile})).unwrap();
paint(&mut s, |_, _| [100.0 / 255.0, 150.0 / 255.0, 200.0 / 255.0, 1.0]);
let source_profile = doc(&s).icc_profile.clone();
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap();
assert_eq!(doc(&s).icc_profile, source_profile, "{profile} at {depth}-bit: Indexed profile");
assert_eq!(doc(&s).color_table.as_ref().unwrap().colors, vec![[100, 150, 200]]);
let indexed_pixel = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
s.execute("image.mode.rgb", json!({})).unwrap();
assert_eq!(doc(&s).mode, ColorMode::Rgb);
assert_eq!(doc(&s).icc_profile, source_profile, "{profile} at {depth}-bit: RGB profile");
assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), indexed_pixel);
assert!(doc(&s).color_table.is_none());
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(doc(&s).mode, ColorMode::Indexed);
assert_eq!(doc(&s).icc_profile, source_profile);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(doc(&s).mode, ColorMode::Rgb);
assert_eq!(doc(&s).icc_profile, source_profile);
s.execute("edit.undo", json!({})).unwrap();
s.execute("image.mode.rgb", json!({"profile": "srgb"})).unwrap();
assert_eq!(doc(&s).icc_profile, Some(photocraft_cms::Builtin::Srgb.profile().to_bytes()), "an explicit target still converts");
if profile != "none" {
assert_ne!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), indexed_pixel);
}
}
}
}
#[test]
fn indexed_matte_blends_edges_without_replacing_clear_pixels() {
for depth in [8, 16, 32] {
for (matte, color) in [
("black", [0.0, 0.0, 0.0]),
("white", [1.0, 1.0, 1.0]),
("#0000ff", [0.0, 0.0, 1.0]),
("foreground", [0.0, 0.0, 1.0]),
("background", [0.0, 1.0, 0.0]),
] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 4, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
s.execute("tools.setColors", json!({"foreground": "#0000ff", "background": "#00ff00"})).unwrap();
paint(&mut s, |x, _| match x {
0 => [0.0, 1.0, 0.0, 1.0],
1 => [1.0, 0.0, 0.0, 0.75],
2 => [1.0, 0.0, 0.0, 0.25],
_ => [0.0; 4],
});
let source = [1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0));
let expected = source.map(|pixel| [0, 1, 2].map(|i| pixel[i] * pixel[3] + color[i] * (1.0 - pixel[3])));
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap();
let surface = doc(&s).layers[0].surface().unwrap();
let edges = [1, 2].map(|x| surface.rgba(x, 0));
for (edge, expected) in edges.iter().zip(expected) {
for i in 0..3 {
assert!((edge[i] - expected[i]).abs() <= 1.0 / 255.0, "{depth}-bit {matte}: {edge:?} vs {expected:?}");
}
assert_eq!(edge[3], 1.0);
}
assert_eq!(surface.rgba(3, 0)[3], 0.0, "{matte}: fully transparent pixels stay clear");
assert_eq!(surface.rgba(0, 0), [0.0, 1.0, 0.0, 1.0]);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!([1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0)), source);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!([1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0)), edges);
}
}
}
#[test]
fn indexed_matte_converts_working_rgb_to_document_profile_at_every_depth() {
use photocraft_cms::Transform;
for depth in [8, 16, 32] {
for (matte, color) in [("foreground", [0.0, 1.0, 0.0]), ("background", [1.0, 0.0, 0.0])] {
for (intent, bpc) in [("relative", false), ("absolute", true)] {
let mut s = Session::new();
s.execute("edit.colorSettings", json!({"workingRgb": "display-p3", "intent": intent, "bpc": bpc})).unwrap();
s.execute("file.new", json!({"width": 2, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
s.execute("tools.setColors", json!({"foreground": "#00ff00", "background": "#ff0000"})).unwrap();
paint(&mut s, |x, _| if x == 0 { [1.0, 0.0, 0.0, 0.5] } else { [0.0; 4] });
let pixel = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
let profile = doc(&s).icc_profile.clone();
let source = s.color.working(ColorMode::Rgb);
let destination = crate::color_cmds::document_profile(doc(&s));
let transform = Transform::new(&source, &destination, s.color.settings.intent(), bpc).unwrap();
let mut converted = [0.0; 16];
transform.eval(&color, &mut converted);
let expected = [0, 1, 2].map(|i| ((pixel[i] * pixel[3] + converted[i].clamp(0.0, 1.0) * (1.0 - pixel[3])) * 255.0).round() as u8);
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap();
let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
assert_eq!([edge[0], edge[1], edge[2]].map(|v| (v * 255.0).round() as u8), expected, "{depth}-bit {matte} {intent}, bpc={bpc}");
assert_eq!(edge[3], 1.0);
assert_eq!(doc(&s).icc_profile, profile);
assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(1, 0)[3], 0.0);
}
}
}
}
#[test]
fn indexed_matte_hex_stays_in_document_rgb_coordinates() {
for depth in [8, 16, 32] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 1, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]);
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "#3366cc"})).unwrap();
let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
let expected = [0.5 + 0.5 * 0.2, 0.5 * 0.4, 0.5 * 0.8];
for (got, want) in edge[..3].iter().zip(expected) {
assert!((got - want).abs() <= 2.0 / 255.0, "{depth}-bit: {edge:?} vs {expected:?}");
}
assert_eq!(edge[3], 1.0);
}
}
#[test]
fn indexed_matte_named_gray_choices_use_their_document_samples() {
for (matte, channel) in [("gray", 128.0 / 255.0), ("netscapeGray", 192.0 / 255.0)] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 1, "height": 1, "depth": 32, "background": "transparent"})).unwrap();
paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]);
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap();
let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
assert!((edge[0] - (0.5 + channel * 0.5)).abs() <= 1.0 / 255.0, "{matte}: {edge:?}");
for value in edge[1..3].iter() {
assert!((*value - channel * 0.5).abs() <= 2.0 / 255.0, "{matte}: {edge:?}");
}
assert_eq!(edge[3], 1.0);
}
}
#[test]
fn indexed_matte_without_transparency_fills_clear_pixels_and_rejects_bad_input_atomically() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 2, "height": 1, "background": "transparent"})).unwrap();
let before = s.active().unwrap().revision;
for matte in [json!(false), json!(12), json!("#gg0000"), json!("#000000ff"), json!("unknown")] {
assert!(s.execute("image.mode.indexedColor", json!({"matte": matte})).is_err(), "{matte}");
assert_eq!(s.active().unwrap().revision, before);
assert_eq!(doc(&s).mode, ColorMode::Rgb);
}
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false, "matte": "#0000ff"})).unwrap();
assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(doc(&s).color_table.as_ref().unwrap().transparent, None);
}
#[test]
fn indexed_exact_transparency_and_sources() {
// Two colours + transparency: exact palette with a transparent entry.
@@ -176,6 +176,9 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io
&& let Some(pr) = photocraft_paint::presets::find(&s.tools.presets, first)
{
let mut b = pr.brush.clone().picked_over(&s.tools.brush);
// Opacity takes 1-100 %, as `tools.setBrush` floors it: a preset saved at 0 % would show
// 1 % but paint nothing (#11812).
b.opacity = b.opacity.max(0.01);
s.load_brush_tips(&mut b).map_err(|e| bad("brush.presets.importAbr", e))?;
s.tools.brush = b;
s.tools.brush_changed();
@@ -477,6 +480,24 @@ mod tests {
.unwrap()
}
/// #11812: selecting an imported brush whose tool options hold 0 % opacity floors it at 1 %,
/// the value its options-bar field shows, so it paints instead of laying down nothing.
#[test]
fn selecting_an_imported_zero_opacity_brush_floors_it_at_one_percent() {
use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value as D};
let preset = |opacity: i32| {
Descriptor::new("brushPreset")
.with("Nm ", D::Text(UnicodeString::new_nul("Faint")))
.with("toolOptions", D::Descriptor(Descriptor::new("currentToolOptions").with("Opct", D::Integer(opacity))))
};
for (opacity, expected) in [(0, 0.01), (37, 0.37)] {
let abr = photocraft_psd::abr::write_v6_folders(2, &[], &[], &[preset(opacity)], &[vec![]], true).unwrap();
let mut s = Session::new();
s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&abr), "select": true})).unwrap();
assert!((s.tools.brush.opacity - expected).abs() < 1e-6, "{opacity}: {}", s.tools.brush.opacity);
}
}
#[test]
fn import_adds_a_group_and_paints() {
let mut s = Session::new();
+8
View File
@@ -957,6 +957,14 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor
photocraft_io::ImportOptions {
max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize,
demosaic: prefs.raw_defaults.demosaic.method(),
pdf_dpi: prefs.file_handling.pdf_dpi,
pdf_pages: match (prefs.file_handling.pdf_first_page, prefs.file_handling.pdf_last_page) {
(0, 0) => None,
(first, last) => {
let first = first.max(1);
Some((first, if last == 0 { u32::MAX } else { last.max(first) }))
}
},
..Default::default()
}
}
+3 -2
View File
@@ -2,6 +2,7 @@
use photocraft_color::{BlendMode, Color};
use photocraft_doc::adjust::CurvePoint;
use photocraft_doc::effects::PATTERN_SCALE_RANGE;
use photocraft_doc::{
Bevel, BevelStyle, BevelTechnique, Contour, Effect, FxCommon, FxPaint, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Satin, Shadow, StrokeFx,
StrokePosition,
@@ -804,7 +805,7 @@ fn overlay_pattern(fx: &mut Effect, p: &Value) {
*id = String::new();
}
if let Some(x) = f_of(p, "scale") {
*scale = (x / 100.0).clamp(0.01, 10.0);
*scale = (x / 100.0).clamp(PATTERN_SCALE_RANGE.0, PATTERN_SCALE_RANGE.1);
}
if let Some(x) = f_of(p, "angle") {
*angle = x;
@@ -912,7 +913,7 @@ fn overlay_bevel(bv: &mut Bevel, p: &Value) {
bv.texture = Some(photocraft_doc::BevelTexture {
name: t.to_string(),
id: t.to_string(),
scale: (f(p, "textureScale", 100.0) / 100.0).clamp(0.01, 10.0),
scale: (f(p, "textureScale", 100.0) / 100.0).clamp(PATTERN_SCALE_RANGE.0, PATTERN_SCALE_RANGE.1),
depth: (f(p, "textureDepth", 100.0) / 100.0).clamp(-10.0, 10.0),
invert: b(p, "textureInvert", false),
link: b(p, "textureLink", true),
+14
View File
@@ -570,6 +570,12 @@ pub struct FileHandling {
pub recover_on_launch: bool,
/// Open a file with no ICC profile as untagged even when its EXIF ColorSpace tag says sRGB.
pub ignore_exif_profile_tag: bool,
/// PDF import resolution in DPI; the document keeps it so the page's print size is preserved.
pub pdf_dpi: f32,
/// The first PDF page to import (1-based; 0 imports from the first page).
pub pdf_first_page: u32,
/// The last PDF page to import (1-based; 0 imports to the last page).
pub pdf_last_page: u32,
/// Most renderers write ACEScg EXRs without stating the colour space. With this on, an EXR
/// that would otherwise open as linear sRGB opens as ACEScg (AP1, linear) instead.
pub exr_aces_cg: bool,
@@ -607,6 +613,9 @@ impl Default for FileHandling {
autosave_minutes: 10,
recover_on_launch: true,
ignore_exif_profile_tag: false,
pdf_dpi: 300.0,
pdf_first_page: 0,
pdf_last_page: 0,
exr_aces_cg: false,
ask_before_saving_layered_tiff: true,
maximize_psd_compatibility: Ask::Always,
@@ -630,6 +639,10 @@ pub struct Export {
pub webp_quality: u32,
pub metadata: ExportMetadata,
pub convert_to_srgb: bool,
/// The folder the last successful export through a save dialog went to (Export As, Quick
/// Export, Save for Web, ...). The next export dialog starts there; empty until the first
/// export, and ignored while the folder no longer exists (#10192).
pub last_folder: String,
}
impl Default for Export {
@@ -642,6 +655,7 @@ impl Default for Export {
webp_quality: 85,
metadata: ExportMetadata::Copyright,
convert_to_srgb: true,
last_folder: String::new(),
}
}
}
+1
View File
@@ -169,6 +169,7 @@ pub const TOOLS: &[(&str, &str, Option<&str>)] = &[
("tools.select.ellipseShape", "Ellipse Tool", Some("U")),
("tools.select.triangle", "Triangle Tool", Some("U")),
("tools.select.polygon", "Polygon Tool", Some("U")),
("tools.select.star", "Star Tool", Some("U")),
("tools.select.line", "Line Tool", Some("U")),
("tools.select.customShape", "Custom Shape Tool", Some("U")),
("tools.select.slice", "Slice Tool", Some("C")),
+1 -1
View File
@@ -24,7 +24,7 @@ pub(super) fn placement(anchor: (f64, f64), link: bool, phase: (f32, f32), scale
let base = if link { anchor } else { (0.0, 0.0) };
let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1));
let s = f64::from(scale);
let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 };
let inv_scale = if s.is_finite() && s > 0.0 { 1.0 / s.max(photocraft_compose::pattern::MIN_PLACEMENT_SCALE) } else { 1.0 };
let a = f64::from(angle).to_radians();
Placement { origin, cs: (a.cos(), a.sin()), inv_scale }
}
+2
View File
@@ -51,6 +51,8 @@ imagesize = "0.13"
resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] }
# The SVG fallback font search keeps each font file's character map (already in the tree through usvg).
ttf-parser = { version = "0.25", default-features = false }
# PDF import (pdf_import.rs): craft-pdf rasterizes pages in pure Rust; no shared library ships.
craft-pdf = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] }
+92 -6
View File
@@ -65,6 +65,7 @@ pub use ora::losses as ora_losses;
pub mod pattern_map;
mod pcraft_cache;
pub mod pdf;
mod pdf_import;
mod pdn;
pub use pcraft_cache::PcraftExportCache;
pub mod pixels;
@@ -513,8 +514,8 @@ pub enum ImportPreflight {
/// A flat raster decoded into one image, bounded by
/// [`ImportOptions::flat_max_pixel_bytes`].
Flat,
/// Affinity, OpenRaster, Krita, XCF, PDN, SVG, camera raw and `.pcraft` files: this build has
/// no header-only estimate of their pixel memory before decoding.
/// Affinity, OpenRaster, Krita, XCF, PDN, SVG, camera raw, PDF and `.pcraft` files: this
/// build has no header-only estimate of their pixel memory before decoding.
Unbounded,
}
@@ -555,6 +556,11 @@ pub fn import_preflight(name: &str, bytes: &[u8]) -> ImportPreflight {
if is_psd_input(name, bytes) {
return ImportPreflight::Psd;
}
// PDF (craft-pdf, pure Rust). `.ai` files that start with `%PDF-` are PDFs and take this
// importer too; a recognized raster signature wins over a misleading `.pdf` suffix.
if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && photocraft_codecs::detect(bytes).is_none()) {
return ImportPreflight::Unbounded;
}
if photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) { ImportPreflight::Tiff } else { ImportPreflight::Flat }
}
@@ -601,6 +607,11 @@ pub struct ImportOptions {
/// Decoded-pixel allowance for a flat raster (the buffer a codec decodes into). May lower
/// the codec's default cap; 0 uses it. PSD/PSB and layered TIFF use `psd_max_pixel_bytes`.
pub flat_max_pixel_bytes: u64,
/// Resolution (dots per inch) PDF pages are rendered at on import; the document keeps it so
/// the page's print size is preserved. Defaults to 300.
pub pdf_dpi: f32,
/// The 1-based, inclusive page range to import; `None` imports every page (up to the cap).
pub pdf_pages: Option<(u32, u32)>,
/// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget.
pub psd_high_memory_approved: bool,
/// Optional estimate limit for high-memory approval. When set, approval only applies if
@@ -615,6 +626,8 @@ impl Default for ImportOptions {
demosaic: raw::Demosaic::default(),
psd_max_pixel_bytes: 0,
flat_max_pixel_bytes: 0,
pdf_dpi: 300.0,
pdf_pages: None,
psd_high_memory_approved: false,
psd_approved_estimate: None,
}
@@ -975,6 +988,16 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route {
/// Dispatches format-specific importers and propagates a structured PSD damage
/// flag alongside the ordinary best-effort import result.
fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result<ImportResult, IoError> {
// SVG content wins over a misleading `.pdf` suffix, matching the preflight (which checks SVG
// before PDF).
if is_svg_input(name, bytes) {
return svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth);
}
// PDF (craft-pdf, pure Rust). `.ai` files that start with `%PDF-` are PDFs and take this
// importer too; a recognized raster signature wins over a misleading `.pdf` suffix.
if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && photocraft_codecs::detect(bytes).is_none()) {
return pdf_import::import(name, bytes, opts, ctl);
}
match route(name, bytes) {
Route::Pcraft => {
let document = photocraft_format::load_from_bytes(bytes)?;
@@ -999,10 +1022,28 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o
pub fn is_svg_input(name: &str, bytes: &[u8]) -> bool {
// Keep the SVG extension as a fallback for malformed files so the SVG parser can return an
// actionable SVG error. A recognized raster signature still wins over a misleading `.svg`
// suffix (for example, a WebP downloaded as Firefox_logo.svg).
// suffix (for example, a WebP downloaded as Firefox_logo.svg), and so does every other
// format's signature: a PDF named `.svg` must reach the PDF importer.
svg::is_svg(bytes)
|| (has_extension(name, "svg") && photocraft_codecs::detect(bytes).is_none())
|| (has_extension(name, "svgz") && bytes.starts_with(&[0x1f, 0x8b]))
|| (has_extension(name, "svg") && photocraft_codecs::detect(bytes).is_none() && !has_format_signature(name, bytes))
|| (has_extension(name, "svgz") && bytes.starts_with(&[0x1f, 0x8b]) && !has_format_signature(name, bytes))
}
/// A non-raster format's signature or declared extension, checked before the `.svg` suffix
/// fallback so a misnamed file keeps its own importer.
fn has_format_signature(name: &str, bytes: &[u8]) -> bool {
is_psd(bytes)
|| pdf_import::is_pdf(bytes)
|| is_psd_input(name, bytes)
|| raw::is_raw(bytes)
|| affinity::is_affinity(bytes)
|| ora::is_ora(bytes)
|| kra::is_kra(bytes)
|| xcf::is_xcf(bytes)
|| has_extension(name, "pdn")
|| bytes.starts_with(b"PDN3")
|| photocraft_format::is_pcraft(bytes)
|| has_extension(name, photocraft_format::EXTENSION)
}
fn extension(name_or_ext: &str) -> String {
@@ -1154,7 +1195,7 @@ fn export_stages_with_renderer(
return Ok(res.into());
}
if ext == "pdf" {
let mut res = pdf::export(doc)?;
let mut res = pdf::export(doc, ctl)?;
if let Some(r) = renderer {
res.warnings.push("PDF export uses CPU compositor; GPU rendering applies to flat formats".into());
res.warnings.extend(r.drain_diagnostics());
@@ -1570,4 +1611,49 @@ mod tests {
assert_eq!(d.bounds().height(), 8, "{name}");
}
}
/// A PDF named `.svg` (a save-as mistake) must reach the PDF importer, not the SVG parser;
/// SVG content still wins over a `.pdf` suffix.
#[test]
fn a_pdf_named_svg_stays_a_pdf() {
let pdf = b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n";
assert!(!is_svg_input("drawing.svg", pdf));
assert!(!is_svg_input("drawing.svgz", pdf));
assert!(is_svg_input("drawing.svg", b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>"));
assert_eq!(crate::route("drawing.svg", pdf), crate::Route::Flat);
}
/// `.ai` files that start with `%PDF-` are PDFs: both preflight and dispatch send them to the
/// PDF importer rather than the flat decoder.
#[test]
fn an_ai_with_pdf_content_takes_the_pdf_importer() {
use lopdf::{Document as PdfDocument, Object, Stream, dictionary};
let mut pdf = PdfDocument::with_version("1.5");
let pages_id = pdf.new_object_id();
let content = b"0 0 1 rg 10 10 20 20 re f";
let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec()));
let page_id = pdf.add_object(dictionary! {
"Type" => "Page",
"Parent" => pages_id,
"MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(100.0), Object::Real(100.0)]),
"Contents" => content_id,
"Resources" => dictionary! {},
});
pdf.objects.insert(
pages_id,
Object::Dictionary(dictionary! {
"Type" => "Pages",
"Kids" => Object::Array(vec![Object::Reference(page_id)]),
"Count" => 1,
}),
);
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
pdf.trailer.set("Root", catalog);
let mut bytes = Vec::new();
pdf.save_to(&mut bytes).expect("writing the .ai fixture");
assert!(crate::pdf_import::is_pdf(&bytes));
assert_eq!(import_preflight("illustration.ai", &bytes), ImportPreflight::Unbounded);
let result = import("illustration.ai", &bytes).expect("an .ai starting with %PDF- takes the PDF importer");
assert_eq!(result.document.artboards().len(), 1);
}
}
+207 -65
View File
@@ -44,6 +44,8 @@ pub struct PrintPage {
pub marks: Marks,
pub description: Option<String>,
pub label: Option<String>,
/// The page's name in the PDF `/PageLabels` tree (Unicode-capable; not drawn on the page).
pub page_label: Option<String>,
}
pub(super) fn pdf_string(s: &str) -> String {
@@ -62,6 +64,16 @@ pub(super) fn pdf_string(s: &str) -> String {
o
}
/// A PDF text string with UTF-16BE hex (the Unicode-capable form, byte-order mark included).
fn pdf_unicode_string(s: &str) -> String {
let mut o = String::from("<FEFF");
for u in s.encode_utf16() {
o.push_str(&format!("{u:04X}"));
}
o.push('>');
o
}
fn deflate(data: &[u8]) -> Vec<u8> {
// Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static
// Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger
@@ -109,10 +121,20 @@ fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String {
/// A one-page PDF.
pub fn print_pdf(page: &PrintPage) -> Vec<u8> {
print_pdf_with_vectors(page, "", &selection::SelectionFont::default())
print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default(), &photocraft_raster::Interrupt::NONE).unwrap_or_default()
}
fn print_pdf_with_vectors(page: &PrintPage, vectors: &str, selection_font: &selection::SelectionFont) -> Vec<u8> {
/// A PDF with one page per entry; `vectors[i]` (when present) is drawn over page `i`.
fn print_pdf_pages(
pages: &[PrintPage],
vectors: &[String],
selection_font: &selection::SelectionFont,
ctl: &photocraft_raster::Interrupt,
) -> std::result::Result<Vec<u8>, IoError> {
if ctl.check().is_err() {
return Err(IoError::Cancelled);
}
let Some(first) = pages.first() else { return Ok(Vec::new()) };
let mut out: Vec<u8> = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec();
let mut offsets: Vec<usize> = Vec::new();
let mut obj = |out: &mut Vec<u8>, body: &[u8]| {
@@ -121,72 +143,112 @@ fn print_pdf_with_vectors(page: &PrintPage, vectors: &str, selection_font: &sele
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
};
let img = &page.image;
let (pw, ph) = page.paper;
let (x, y, w, h) = page.rect;
let selection_base = if img.icc.is_some() { 8 } else { 7 };
// 1 catalog, 2 pages, 3 page, 4 contents, 5 image, 6 font, 7 ICC (optional).
obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>");
obj(&mut out, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
obj(
&mut out,
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 5 0 R >> /Font << /F1 6 0 R /FSelect {selection_base} 0 R >> >> /Contents 4 0 R >>"
let n = pages.len();
// A label tree is written only for a non-empty name: an all-empty tree would be `/Nums []`,
// and filtering the first empty name away would start the tree at page index 1, not 0.
let labels_on = pages.iter().any(|p| p.page_label.as_deref().is_some_and(|label| !label.is_empty()));
// 1 catalog, 2 pages, then per page: page, contents, image; then the shared font/ICC/selection.
let font_obj = 3 + n * 3;
let icc = first.image.icc.as_ref();
let icc_obj = icc.map(|_| font_obj + 1);
let selection_base = font_obj + if icc.is_some() { 2 } else { 1 };
let selection_objects = selection_font.objects(selection_base);
let labels_obj = labels_on.then_some((selection_base + selection_objects.len()) as u32);
obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{} >>", labels_obj.map(|o| format!(" /PageLabels {o} 0 R")).unwrap_or_default()).as_bytes());
let kids = (0..n).map(|i| format!("{} 0 R", 3 + i * 3)).collect::<Vec<_>>().join(" ");
obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes());
for (i, page) in pages.iter().enumerate() {
let page_obj = 3 + i * 3;
let content_obj = page_obj + 1;
let image_obj = page_obj + 2;
let (pw, ph) = page.paper;
let (x, y, w, h) = page.rect;
obj(
&mut out,
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 {image_obj} 0 R >> /Font << /F1 {font_obj} 0 R /FSelect {selection_base} 0 R >> >> /Contents {content_obj} 0 R >>"
)
.as_bytes(),
);
// An explicit white page, so every viewer (and rasteriser) shows paper, not transparency.
let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\nq {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n");
if let Some(v) = vectors.get(i) {
content.push_str(v);
}
content.push_str(&marks_ops(page.marks, page.rect));
let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration;
let pad = if any_marks { 30.0 } else { 6.0 };
if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) {
content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l)));
}
if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) {
content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d)));
}
let c = deflate(content.as_bytes());
let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes();
body.extend_from_slice(&c);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
let img = &page.image;
let device = match img.channels {
1 => "/DeviceGray",
4 => "/DeviceCMYK",
_ => "/DeviceRGB",
};
let cs = match icc_obj {
Some(obj) => format!("[/ICCBased {obj} 0 R]"),
None => device.to_string(),
};
let z = deflate(&img.data);
let mut body = format!(
"<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n",
img.width,
img.height,
z.len()
)
.as_bytes(),
);
// An explicit white page, so every viewer (and rasteriser) shows paper, not transparency.
let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\nq {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n");
content.push_str(vectors);
content.push_str(&marks_ops(page.marks, page.rect));
let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration;
let pad = if any_marks { 30.0 } else { 6.0 };
if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) {
content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l)));
}
if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) {
content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d)));
}
let c = deflate(content.as_bytes());
let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes();
body.extend_from_slice(&c);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
let device = match img.channels {
1 => "/DeviceGray",
4 => "/DeviceCMYK",
_ => "/DeviceRGB",
};
let cs = if img.icc.is_some() { "[/ICCBased 7 0 R]".to_string() } else { device.to_string() };
let z = deflate(&img.data);
let mut body = format!(
"<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n",
img.width,
img.height,
z.len()
)
.into_bytes();
body.extend_from_slice(&z);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>");
if let Some(icc) = &img.icc {
let z = deflate(icc);
let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", img.channels, z.len()).into_bytes();
.into_bytes();
body.extend_from_slice(&z);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
}
for body in selection_font.objects(selection_base) {
obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>");
if let Some(icc) = icc {
let device = match first.image.channels {
1 => "/DeviceGray",
4 => "/DeviceCMYK",
_ => "/DeviceRGB",
};
let z = deflate(icc);
let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", first.image.channels, z.len()).into_bytes();
body.extend_from_slice(&z);
body.extend_from_slice(b"\nendstream");
obj(&mut out, &body);
}
for body in &selection_objects {
obj(&mut out, body);
}
if labels_obj.is_some() {
// Every page gets an entry: a number-tree range runs until the next key, so omitting an
// empty name would make that page inherit the previous page's label. An empty
// dictionary gives the page the default (decimal) label instead.
let nums = pages
.iter()
.enumerate()
.map(|(i, p)| match p.page_label.as_deref().filter(|label| !label.is_empty()) {
Some(label) => format!("{i} << /P {} >>", pdf_unicode_string(label)),
None => format!("{i} << >>"),
})
.collect::<Vec<_>>()
.join(" ");
obj(&mut out, format!("<< /Nums [{nums}] >>").as_bytes());
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
for o in &offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
out
Ok(out)
}
/// The vector operators for the contiguous visible top prefix of `doc`, top to bottom, with the
@@ -261,10 +323,17 @@ fn collect_vectors(doc: &Document) -> (Vec<(usize, String)>, selection::Selectio
(layers, selection_font)
}
/// File › Save As / Save a Copy › PDF (#3401): the flattened document, at its print size
/// (pixels ÷ resolution × 72 pt), as a one-page PDF. Layers and transparency are dropped — the
/// warning says so — and the embedded profile travels with the image.
pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
/// Pixels in `rect`, saturating on overflow.
fn rect_pixels(rect: photocraft_geom::Rect) -> u64 {
u64::from(rect.width()).saturating_mul(u64::from(rect.height()))
}
/// File › Save As / Save a Copy › PDF (#3401): the flattened document at its print size
/// (pixels ÷ resolution × 72 pt). One page per artboard when the document has artboards, else one
/// page for the whole document. Layers and transparency are dropped — the warning says so — and
/// the embedded profile travels with the images.
pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result::Result<ExportResult, IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
let (w, h) = (usize::try_from(doc.size.width).unwrap_or(0), usize::try_from(doc.size.height).unwrap_or(0));
if w == 0 || h == 0 {
return Err(IoError::Unsupported("PDF needs a document with non-zero width and height; nothing was written".into()));
@@ -277,6 +346,82 @@ pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
};
let fmt = doc.pixel_format();
let n = fmt.channels().max(1);
let dpi = f64::from(doc.resolution_dpi.max(1.0));
let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 };
let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
let icc = doc.icc_profile.as_ref().map(|p| p.to_vec());
let artboards = doc.artboards();
if !artboards.is_empty() {
// Every page's encoded pixels are kept until the PDF is assembled; bound that peak.
const MAX_PDF_EXPORT_BYTES: u64 = 1 << 30;
let page_pixels: u64 = artboards.iter().fold(0u64, |bytes, (_, _, a)| bytes.saturating_add(rect_pixels(a.rect)));
let retained = page_pixels.saturating_mul(device as u64);
// One page renders at a time: its f32 composite surface plus the region read back from
// it, both `n` channels at 4 bytes per pixel. The whole-document canvas is never held.
let largest = artboards.iter().map(|(_, _, a)| rect_pixels(a.rect)).max().unwrap_or(0);
let temporary = largest.saturating_mul(n as u64).saturating_mul(4).saturating_mul(2);
let estimate = retained.saturating_add(temporary);
if estimate > MAX_PDF_EXPORT_BYTES {
return Err(IoError::Unsupported(format!(
"PDF export would need about {} MB for {} artboards; export them in smaller batches",
estimate >> 20,
artboards.len()
)));
}
// One document shell is reused for every page. Each page renders a document holding only
// its artboard group (the same isolation as `artboard_document`), so an overlapping board
// cannot paint on another board's page. Layer pixels are shared with `doc`; this one
// clone and the per-page group clone hold no new pixel buffers, but they are outside the
// 1 GiB estimate because they are not retained page data.
let mut one = doc.clone();
let mut pages = Vec::with_capacity(artboards.len());
for (id, name, artboard) in &artboards {
ctl.check().map_err(|_| IoError::Cancelled)?;
let rect = artboard.rect;
let (aw, ah) = (rect.width(), rect.height());
if aw == 0 || ah == 0 {
continue;
}
// A hidden artboard still gets its page, rendered from its own content rather than
// left blank by the group's visibility.
let Some(layer) = doc.layer(*id) else { continue };
let mut group = layer.clone();
group.visible = true;
one.layers.clear();
one.layers.push(group);
// Render only this artboard's rect; the surface never holds the whole document.
let surface = photocraft_compose::composite_to_surface(&one, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None);
let values = surface.read_region(rect);
let mut data = Vec::with_capacity((aw as usize * ah as usize).saturating_mul(device));
for px in values.chunks(n) {
let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0);
for v in px.iter().take(device) {
data.push(to8(v * a + paper * (1.0 - a)));
}
}
let image = PrintImage { width: aw, height: ah, channels: device, data, icc: icc.clone() };
let (pw, ph) = (f64::from(aw) * 72.0 / dpi, f64::from(ah) * 72.0 / dpi);
pages.push(PrintPage {
paper: (pw, ph),
image,
rect: (0.0, 0.0, pw, ph),
marks: Marks::default(),
description: None,
label: None,
page_label: Some((*name).to_string()),
});
}
if pages.is_empty() {
return Err(IoError::Unsupported("PDF: the document's artboards have no area".into()));
}
let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()];
warnings.push(format!("PDF exported {} artboards as {} pages; vector/text layers on artboards are rasterised", artboards.len(), pages.len()));
if !doc.metadata.text.is_empty() {
warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into());
}
let vectors = vec![String::new(); pages.len()];
return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default(), ctl)?, warnings });
}
let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32);
// Simple topmost shapes and text layers can be drawn over the flattened backdrop without changing
// compositing. Stop at the first unsupported visible layer, since it may depend on the
@@ -290,10 +435,8 @@ pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
}
let surface = photocraft_compose::flatten_to_surface(&backdrop, PixelFormat::new(fmt.mode, fmt.sample, true), None);
let values = surface.read_region(canvas);
let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
// Straight alpha, composited here over paper: white in RGB/Gray (1 = full light), zero ink
// in CMYK (0 = paper).
let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 };
let mut data = Vec::with_capacity((w * h).saturating_mul(device));
for px in values.chunks(n) {
let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0);
@@ -301,10 +444,9 @@ pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
data.push(to8(v * a + paper * (1.0 - a)));
}
}
let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: doc.icc_profile.as_ref().map(|p| p.to_vec()) };
let dpi = f64::from(doc.resolution_dpi.max(1.0));
let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: icc.clone() };
let (pw, ph) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi);
let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None };
let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None, page_label: None };
let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()];
if !doc.metadata.text.is_empty() {
warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into());
@@ -315,7 +457,7 @@ pub fn export(doc: &Document) -> std::result::Result<ExportResult, IoError> {
vectors.push_str(ops);
}
vectors.push_str("Q\n");
Ok(ExportResult { bytes: print_pdf_with_vectors(&page, &vectors, &selection_font), warnings })
Ok(ExportResult { bytes: print_pdf_pages(&[page], &[vectors], &selection_font, ctl)?, warnings })
}
#[cfg(test)]
+170 -18
View File
@@ -1,10 +1,11 @@
//! PDF export: structure, pixel oracle, colour modes and refusal paths.
use super::*;
use lopdf::{Object, StringFormat};
use photocraft_color::{PixelFormat, SampleType};
use photocraft_doc::{Layer, LayerContent, Size};
use photocraft_doc::{Artboard, Group, Layer, LayerContent, Size};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use photocraft_raster::{Interrupt, Surface};
fn solid(fmt: PixelFormat, x0: i32, y0: i32, x1: i32, y1: i32, px: &[f32]) -> Surface {
let mut s = Surface::new(fmt);
@@ -68,7 +69,7 @@ fn check_structure(pdf: &[u8]) {
#[test]
fn a_flat_rgb_document_saves_as_one_page_pdf() {
let d = doc(ColorMode::Rgb);
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
let pdf = &out.bytes;
check_structure(pdf);
assert!(has(pdf, "/MediaBox [0 0 4.00 2.00]"), "page = image size at 72 pt/in");
@@ -85,7 +86,7 @@ fn layers_composite_over_white_before_the_page() {
let mut d = doc(ColorMode::Rgb);
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
d.layers.push(Layer::new("Half red", LayerContent::Raster(solid(fmt, 1, 0, 3, 2, &[1.0, 0.0, 0.0, 0.5]))));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
let img = stream_after(&out.bytes, "/Subtype /Image");
// Pixels 1-2 of row 0: 0.5 red over white = (1.0, 0.5, 0.5); elsewhere plain white.
assert_eq!(&img[3..6], &[255, 128, 128], "the blend lands: {:?}", &img[3..6]);
@@ -102,7 +103,7 @@ fn topmost_solid_shape_is_exported_as_a_vector_path() {
..Default::default()
};
d.layers.push(Layer::new("Shape", LayerContent::Shape(shape)));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let content = stream_after(&out.bytes, "/Contents 4 0 R");
let content = String::from_utf8(content).unwrap();
@@ -128,7 +129,7 @@ fn topmost_text_layer_is_exported_with_selectable_text_and_vector_outlines() {
let baseline = layout.lines.get(cluster.line).expect("a line").baseline;
let origin = text.transform.apply(photocraft_geom::Point::new(f64::from(cluster.x), f64::from(baseline)));
d.layers.push(Layer::new("Text", LayerContent::Text(text)));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let content = stream_after(&out.bytes, "/Contents 4 0 R");
let content = String::from_utf8(content).unwrap();
@@ -159,7 +160,7 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() {
d.layers.push(Layer::new("Shape", LayerContent::Shape(shape)));
let text = TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() };
d.layers.push(Layer::new("Text", LayerContent::Text(text)));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let content = stream_after(&out.bytes, "/Contents 4 0 R");
let content = String::from_utf8(content).unwrap();
@@ -173,10 +174,10 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() {
#[test]
fn greyscale_and_cmyk_pages_keep_their_channels() {
let g = export(&doc(ColorMode::Grayscale)).unwrap();
let g = export(&doc(ColorMode::Grayscale), &Interrupt::NONE).unwrap();
assert!(has(&g.bytes, "/ColorSpace /DeviceGray"), "gray is DeviceGray");
assert_eq!(stream_after(&g.bytes, "/Subtype /Image"), vec![255; 4 * 2], "one sample per pixel");
let c = export(&doc(ColorMode::Cmyk)).unwrap();
let c = export(&doc(ColorMode::Cmyk), &Interrupt::NONE).unwrap();
assert!(has(&c.bytes, "/ColorSpace /DeviceCMYK"), "cmyk is DeviceCMYK");
assert_eq!(stream_after(&c.bytes, "/Subtype /Image"), vec![0; 4 * 2 * 4], "zero ink over the whole page");
}
@@ -188,7 +189,7 @@ fn the_page_measures_at_the_document_resolution() {
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 300, 150, &[1.0, 1.0, 1.0, 1.0])))];
d.resolution_dpi = 300.0;
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
assert!(has(&out.bytes, "/MediaBox [0 0 72.00 36.00]"), "300 px at 300 dpi is one inch");
}
@@ -196,7 +197,7 @@ fn the_page_measures_at_the_document_resolution() {
fn an_embedded_profile_travels_as_iccbased() {
let mut d = doc(ColorMode::Rgb);
d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8]));
let out = export(&d).unwrap();
let out = export(&d, &Interrupt::NONE).unwrap();
assert!(has(&out.bytes, "[/ICCBased 7 0 R]"), "the image refers to the profile");
assert_eq!(stream_after(&out.bytes, "/N 3 /Alternate"), vec![1, 2, 3, 4, 5, 6, 7, 8], "the profile bytes survive");
}
@@ -204,7 +205,7 @@ fn an_embedded_profile_travels_as_iccbased() {
#[test]
fn other_modes_are_refused_with_an_actionable_error() {
let d = doc(ColorMode::Lab);
let e = export(&d).unwrap_err().to_string();
let e = export(&d, &Interrupt::NONE).unwrap_err().to_string();
assert!(e.contains("RGB") && e.contains("Mode"), "{e}");
assert!(crate::export(&d, "x.pdf", &crate::ExportOptions::default()).is_err());
}
@@ -226,7 +227,7 @@ fn unicode_text_over_a_photo_extracts_through_a_pdf_reader() {
..Default::default()
}),
));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), text);
assert!(has(&pdf, "/Subtype /Image"));
@@ -266,7 +267,7 @@ fn text_with_compositing_or_a_profile_stays_in_the_raster_backdrop() {
_ => d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4])),
}
d.layers.push(layer);
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
assert!(!content.contains("/ActualText"), "case {case} must retain the raster composite");
assert!(stream_after(&pdf, "/Subtype /Image").iter().any(|v| *v != 255), "case {case} must retain visible text");
@@ -304,7 +305,7 @@ fn text_outside_the_vector_prefix_does_not_consume_the_selection_font() {
"Top text",
LayerContent::Text(TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() }),
));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), "Hi", "case {case}: only the top text is selectable");
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
@@ -355,7 +356,7 @@ fn a_text_layer_refused_at_emission_keeps_the_upper_vectors_and_stays_raster() {
..Default::default()
}),
));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
check_structure(&pdf);
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
assert!(content.contains("/ActualText <FEFF0048"), "the upper text stays vector:\n{content}");
@@ -377,7 +378,7 @@ fn multiline_text_keeps_its_paragraph_breaks_in_the_selection() {
use photocraft_doc::TextLayer;
let mut d = doc(ColorMode::Rgb);
d.layers.push(Layer::new("Text", LayerContent::Text(TextLayer { text: "A\nB".into(), size_pt: 12.0, ..Default::default() })));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), "A\nB", "the paragraph break survives selection");
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
@@ -389,7 +390,158 @@ fn leading_newline_stays_in_the_first_selection_span() {
use photocraft_doc::TextLayer;
let mut d = doc(ColorMode::Rgb);
d.layers.push(Layer::new("Text", LayerContent::Text(TextLayer { text: "\nA".into(), size_pt: 12.0, ..Default::default() })));
let pdf = export(&d).unwrap().bytes;
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap();
assert!(content.contains("/ActualText <FEFF000A0041>"), "the first span retains the leading newline:\n{content}");
}
#[test]
/// Each artboard becomes one labelled page, in document order.
fn artboards_export_as_one_page_each() {
use photocraft_doc::{Artboard, Group};
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
let mut d = Document::new("pages.pdf", Size { width: 40, height: 30 }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 72.0;
for (rect, px) in [(Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]), (Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 1.0])] {
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, rect.y0, rect.x1, rect.y1, &px)));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new("Page", LayerContent::Group(group)));
}
let out = export(&d, &Interrupt::NONE).unwrap();
check_structure(&out.bytes);
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
let pages = parsed.get_pages();
assert_eq!(pages.len(), 2);
for id in pages.values() {
let page = parsed.get_dictionary(*id).unwrap();
let media = page.get(b"MediaBox").unwrap().as_array().unwrap();
let w = media[2].as_float().or_else(|_| media[2].as_i64().map(|v| v as f32)).unwrap();
let h = media[3].as_float().or_else(|_| media[3].as_i64().map(|v| v as f32)).unwrap();
assert!((w - 20.0).abs() < 0.01 && (h - 30.0).abs() < 0.01, "page {w}x{h}");
}
assert_eq!(out.bytes.windows(15).filter(|w| *w == b"/Subtype /Image").count(), 2);
}
/// Side-by-side 2x2 artboards at 72 dpi, named by `names` (empty names are kept).
fn artboard_doc(names: &[&str]) -> Document {
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
let width = (names.len() as u32).saturating_mul(2).max(2);
let mut d = Document::new("labels.pdf", Size { width, height: 2 }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 72.0;
for (index, name) in names.iter().enumerate() {
let x0 = (index as i32) * 2;
let rect = Rect::new(x0, 0, x0 + 2, 2);
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, rect.y0, rect.x1, rect.y1, &[0.5, 0.5, 0.5, 1.0])));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new(*name, LayerContent::Group(group)));
}
d
}
/// The decompressed samples of page `id`'s first image XObject (`/Im0`).
fn page_image(pdf: &lopdf::Document, id: lopdf::ObjectId) -> Vec<u8> {
let page = pdf.get_dictionary(id).expect("page dictionary");
let resources = page.get(b"Resources").expect("page resources").as_dict().expect("resources dictionary");
let xobjects = resources.get(b"XObject").expect("xobjects").as_dict().expect("xobject dictionary");
let image = xobjects.get(b"Im0").expect("Im0").as_reference().expect("image reference");
pdf.get_object(image).expect("image object").as_stream().expect("image stream").decompressed_content().expect("image samples")
}
/// A named artboard gives every page a `/PageLabels` entry, and an empty name gets an empty
/// label dictionary rather than inheriting the previous name.
#[test]
fn page_labels_name_every_page_and_an_empty_name_does_not_inherit() {
let d = artboard_doc(&["A", "", "C"]);
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
check_structure(&pdf);
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
let labels = parsed
.catalog()
.unwrap()
.get(b"PageLabels")
.expect("a named artboard gives the PDF page labels")
.as_reference()
.expect("the label tree is an indirect object");
let nums = parsed.get_dictionary(labels).unwrap().get(b"Nums").unwrap().as_array().unwrap();
assert_eq!(nums.len(), 6, "one key and one label dictionary per page");
for page in 0..3 {
assert_eq!(nums[page * 2].as_i64().unwrap(), page as i64, "the tree starts at page index 0 and covers every page");
}
let label = |page: usize| nums[page * 2 + 1].as_dict().unwrap();
assert_eq!(label(0).get(b"P").unwrap(), &Object::String(vec![0xFE, 0xFF, 0x00, 0x41], StringFormat::Hexadecimal), "page 1 is A");
assert!(label(1).get(b"P").is_err(), "the empty name gets an empty dictionary, not A");
assert_eq!(label(2).get(b"P").unwrap(), &Object::String(vec![0xFE, 0xFF, 0x00, 0x43], StringFormat::Hexadecimal), "page 3 is C");
assert_eq!(parsed.get_pages().len(), 3);
}
/// With no non-empty name there is no label tree at all: an empty `/Nums` would be invalid.
#[test]
fn an_all_empty_artboard_names_document_has_no_page_labels_tree() {
let d = artboard_doc(&["", "", ""]);
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
check_structure(&pdf);
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
assert!(parsed.catalog().unwrap().get(b"PageLabels").is_err(), "no names means no /PageLabels");
assert!(!has(&pdf, "/PageLabels"));
assert_eq!(parsed.get_pages().len(), 3, "the pages themselves are still written");
}
/// Two artboards at the same rectangle: each page must hold only its own board's pixels, not
/// the other board composited over it.
#[test]
fn overlapping_artboards_export_only_their_own_pixels() {
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
let mut d = Document::new("overlap.pdf", Size { width: 2, height: 2 }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 72.0;
for (name, color) in [("Red", [1.0, 0.0, 0.0, 1.0]), ("Blue", [0.0, 0.0, 1.0, 1.0])] {
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, 0, 0, 2, 2, &color)));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(Rect::new(0, 0, 2, 2))), frame_stroke: None };
d.layers.push(Layer::new(name, LayerContent::Group(group)));
}
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
let pages = parsed.get_pages();
let images = pages.values().map(|id| page_image(&parsed, *id)).collect::<Vec<_>>();
assert_eq!(images.len(), 2);
assert_eq!(images[0], [255u8, 0, 0].repeat(4), "the bottom board's page is red, not blue over red");
assert_eq!(images[1], [0u8, 0, 255].repeat(4), "the top board's page is blue");
}
/// A large, mostly empty canvas must not be charged as if its whole area were rendered.
#[test]
fn sparse_canvas_artboards_export_without_a_false_memory_limit() {
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
let mut d = Document::new("sparse.pdf", Size { width: 9000, height: 9000 }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 72.0;
for index in 0..2 {
let x0 = index * 10;
let rect = Rect::new(x0, 0, x0 + 2, 2);
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, 0, rect.x1, 2, &[1.0, 0.0, 0.0, 1.0])));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new("Page", LayerContent::Group(group)));
}
let out = export(&d, &Interrupt::NONE).expect("two 2x2 boards on a 9000x9000 canvas must fit the export budget");
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
assert_eq!(parsed.get_pages().len(), 2);
}
/// Seven US Letter boards at 300 dpi with the importer's gaps: the pages are retained as encoded
/// data, but no whole-canvas buffer exists, so the old whole-canvas charge rejected this.
#[test]
fn seven_us_letter_artboards_export_without_a_false_memory_limit() {
const PAGE_W: u32 = 2550;
const PAGE_H: u32 = 3300;
const GAP: u32 = 80;
const PAGES: u32 = 7;
let mut d = Document::new("letters.pdf", Size { width: PAGES * PAGE_W + (PAGES - 1) * GAP, height: PAGE_H }, ColorMode::Rgb, SampleType::F32);
d.resolution_dpi = 300.0;
for index in 0..PAGES {
let x0 = (index * (PAGE_W + GAP)) as i32;
let rect = Rect::new(x0, 0, x0 + PAGE_W as i32, PAGE_H as i32);
let group = Group { children: Vec::new(), expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
d.layers.push(Layer::new(format!("Letter {}", index + 1), LayerContent::Group(group)));
}
let out = export(&d, &Interrupt::NONE).expect("seven US Letter pages at 300 dpi fit the export budget");
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
assert_eq!(parsed.get_pages().len(), 7);
}
+374
View File
@@ -0,0 +1,374 @@
//! PDF import: craft-pdf (a Rust PDF reader and renderer built on Hayro) rasterizes the
//! selected pages, and each page becomes one artboard.
//!
//! Raster pages only: editable text and vector import would need craft-pdf's `interpret`
//! device and is not part of this importer. The renderer's hard output bounds (8192 px per
//! side and 64M px per page) and a document-wide strip budget are respected by lowering the
//! effective DPI, so each page keeps its physical size: pixels / resolution * 72 pt.
//!
//! The renderer is pure Rust and runs on every desktop platform: no shared library is loaded
//! or shipped, and a malformed file is reported as an error rather than taking the process down.
//!
//! Pages are drawn with the interpreter's default annotation settings, so annotations and
//! filled-in form fields are rendered; comments are not hidden.
use crate::{ImportOptions, ImportResult, IoError};
#[cfg(not(target_arch = "wasm32"))]
use craft_pdf::interpret::InterpreterSettings;
#[cfg(not(target_arch = "wasm32"))]
use craft_pdf::raster::{self, RenderCache};
#[cfg(not(target_arch = "wasm32"))]
use photocraft_color::{ColorMode, PixelFormat, SampleType};
#[cfg(not(target_arch = "wasm32"))]
use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent};
#[cfg(not(target_arch = "wasm32"))]
use photocraft_geom::{Rect, Size};
use photocraft_raster::Interrupt;
#[cfg(not(target_arch = "wasm32"))]
use photocraft_raster::Surface;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(not(target_arch = "wasm32"))]
use std::time::Duration;
/// `%PDF-` magic. `.ai` files that start with it are PDFs and render through this importer.
pub fn is_pdf(bytes: &[u8]) -> bool {
bytes.starts_with(b"%PDF-")
}
/// PDF import is not available in the web build.
#[cfg(target_arch = "wasm32")]
pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrupt) -> Result<ImportResult, IoError> {
Err(IoError::Unsupported("PDF import needs the desktop build".into()))
}
/// Renders the selected PDF pages and opens each as one artboard.
#[cfg(not(target_arch = "wasm32"))]
pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -> Result<ImportResult, IoError> {
/// The most pages one import renders.
const MAX_PAGES: usize = 16;
/// Gap between the artboards, in document pixels.
const GAP: u32 = 80;
/// The document-wide raster budget across every imported page, in pixels.
const MAX_UNION_PIXELS: u64 = 200_000_000;
/// The default pixel-memory budget when the caller sets none: a zero
/// [`ImportOptions::flat_max_pixel_bytes`] still bounds the import.
const DEFAULT_MAX_PIXEL_BYTES: u64 = 2 << 30;
ctl.check().map_err(|_| IoError::Cancelled)?;
let requested = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { f64::from(opts.pdf_dpi) } else { 300.0 };
let pdf = craft_pdf::open_slice_with_options(bytes, None, &craft_pdf::OpenOptions::default()).map_err(open_error)?;
let total = pdf.pages().len();
if total == 0 {
return Err(IoError::Unsupported("PDF has no pages".into()));
}
let (first, last) = match opts.pdf_pages {
Some((a, b)) => {
let a = a.max(1);
let b = if b == 0 { u32::MAX } else { b.max(a) };
if u64::from(a) > total as u64 {
return Err(IoError::Unsupported(format!("PDF page range starts at {a}, but the PDF has {total} pages")));
}
((a as usize).min(total), (b as usize).min(total))
}
None => (1, total),
};
let page_count = last - first + 1;
let count = page_count.min(MAX_PAGES);
// Page sizes in points first: the effective DPI must fit the renderer's bounds without
// changing any page's physical size.
let mut sizes = Vec::with_capacity(count);
for index in 0..count {
let page = &pdf.pages()[first - 1 + index];
let (width, height) = page.render_dimensions();
if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 {
return Err(IoError::Unsupported(format!("PDF page {} has no area", first + index)));
}
sizes.push((f64::from(width), f64::from(height)));
ctl.check().map_err(|_| IoError::Cancelled)?;
}
let dpi = effective_dpi(requested, &sizes, u64::from(raster::MAX_SIDE), raster::MAX_PIXELS, MAX_UNION_PIXELS);
let mut doc_width: u64 = 0;
let mut doc_height: u64 = 0;
let mut retained: u64 = 0;
for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() {
let width = page_pixels(width_pt, dpi);
let height = page_pixels(height_pt, dpi);
doc_width = doc_width.saturating_add(u64::from(width)).saturating_add(if index + 1 < count { u64::from(GAP) } else { 0 });
doc_height = doc_height.max(u64::from(height));
let tiles_x = (u64::from(width)).div_ceil(256);
let tiles_y = (u64::from(height)).div_ceil(256);
retained = retained.saturating_add(tiles_x.saturating_mul(tiles_y).saturating_mul(256 * 256 * 4));
}
if doc_width == 0 || doc_height == 0 {
return Err(IoError::Unsupported("PDF pages have no area".into()));
}
if doc_width > u64::from(u32::MAX) || doc_height > u64::from(u32::MAX) {
return Err(IoError::Unsupported("PDF import is too large at this DPI; lower the import DPI".into()));
}
// Retained tiles plus the converting page's raster (4 B/px); the f32 conversion runs in
// 256-row bands, so it adds only a constant-sized buffer rather than a second full page.
let max_page = sizes.iter().map(|&(w, h)| u64::from(page_pixels(w, dpi)) * u64::from(page_pixels(h, dpi))).max().unwrap_or(0);
let estimate = retained.saturating_add(max_page.saturating_mul(4));
let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES };
if estimate > budget {
return Err(IoError::Unsupported(format!(
"PDF import needs about {} MB of pixel memory; the limit is {} MB (lower the import DPI)",
estimate >> 20,
budget >> 20
)));
}
let mut warnings = Vec::new();
if first > 1 || last < total || count < page_count {
let shown_last = first + count - 1;
let reason = if count < page_count { " (the page limit is 16)" } else { "" };
warnings.push(format!("PDF has {total} pages; imported pages {first}-{shown_last}{reason}"));
}
if dpi + 0.5 < requested {
warnings.push(format!("PDF was rendered at {:.0} dpi to fit the import limits", dpi.max(1.0)));
}
let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8);
doc.resolution_dpi = dpi as f32;
let mut x: u32 = 0;
for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() {
ctl.check().map_err(|_| IoError::Cancelled)?;
let page_number = first + index;
let page = &pdf.pages()[page_number - 1];
let width = page_pixels(width_pt, dpi);
let height = page_pixels(height_pt, dpi);
// The DPI solve keeps these inside the renderer's bounds; re-check rather than panic if
// rounding on an edge moves one pixel past them.
if width > raster::MAX_SIDE || height > raster::MAX_SIDE || u64::from(width) * u64::from(height) > raster::MAX_PIXELS {
return Err(IoError::Unsupported(format!("PDF page {page_number} is too large at {dpi:.0} dpi; lower the import DPI")));
}
// A cache per page, deliberately: a shared one would keep decoded images and fonts alive
// across up to 16 pages outside the pixel budget, and would hide an image-decode warning
// on a later page after the page that first hit it.
let cache = RenderCache::new();
let options = raster::Options {
scale: [(dpi / 72.0) as f32; 2],
size: Some([width, height]),
offset: [0.0, 0.0],
// PDF pages composite onto white, as every PDF viewer and the previous importer did.
// craft-pdf returns premultiplied RGBA8; an opaque background makes alpha 1, so the
// bytes below can be written as straight alpha. A transparent background would need
// un-premultiplying (dividing each colour by alpha) first.
background: [255, 255, 255, 255],
color_replacement: None,
};
let rendered = render_page(page, &cache, &options, ctl).map_err(|error| render_error(page_number, dpi, error))?;
if rendered.diagnostics.image_decode_failed {
warnings.push(format!("PDF page {page_number}: an image could not be decoded and is missing"));
}
// craft-pdf's hayro backend does not emit this flag yet (its README says so); keep the
// warning ready so a backend that starts reporting font substitution needs no change here.
if rendered.diagnostics.unsupported_font {
warnings.push(format!("PDF page {page_number}: a font could not be used and was substituted, so text may look different"));
}
if rendered.diagnostics.content_truncated {
warnings.push(format!("PDF page {page_number}: some content was omitted (a decode or memory limit)"));
}
ctl.check().map_err(|_| IoError::Cancelled)?;
let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
let bytes = rendered.bytes();
// Convert and write in row bands: the f32 buffer stays bounded instead of a second
// 16-bytes-per-pixel copy of the whole page, and cancellation is polled per band.
const BAND_ROWS: usize = 256;
let row_bytes = width as usize * 4;
let band_bytes = row_bytes.saturating_mul(BAND_ROWS);
let mut data: Vec<f32> = Vec::new();
if data.try_reserve_exact(band_bytes).is_err() {
return Err(IoError::Unsupported(format!("PDF page {page_number} needs more memory than is available")));
}
for (band, rows) in bytes.chunks(band_bytes).enumerate() {
ctl.check().map_err(|_| IoError::Cancelled)?;
data.clear();
data.extend(rows.iter().map(|&value| f32::from(value) / 255.0));
let top = (band * BAND_ROWS) as i32;
let band_height = (rows.len() / row_bytes) as u32;
surface.write_region(Rect::from_xywh(x as i32, top, width, band_height), &data);
}
let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32);
let layer = Layer::new(format!("Page {page_number}"), LayerContent::Raster(surface));
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
doc.layers.push(Layer::new(format!("Page {page_number}"), LayerContent::Group(group)));
x = x.saturating_add(width).saturating_add(GAP);
ctl.progress((index + 1) as f32 / count as f32);
}
Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false })
}
/// Renders one page, forwarding `ctl`'s cancellation to craft-pdf while it interprets content.
///
/// craft-pdf checks `InterpreterSettings::cancelled` between content operators, so a dense
/// vector page (CAD, maps) can be stopped part-way through. `Interrupt` is a borrowed callback
/// while the setting needs an owned flag, so a scoped watcher thread copies one into the other
/// every few milliseconds until the render returns.
#[cfg(not(target_arch = "wasm32"))]
fn render_page<'a>(
page: &'a craft_pdf::syntax::page::Page<'a>,
cache: &RenderCache<'a>,
options: &raster::Options,
ctl: &Interrupt,
) -> Result<raster::Raster, raster::Error> {
if ctl.cancelled() {
return Err(raster::Error::Cancelled);
}
let cancelled = Arc::new(AtomicBool::new(false));
let finished = Arc::new(AtomicBool::new(false));
let settings = InterpreterSettings { cancelled: Some(Arc::clone(&cancelled)), ..InterpreterSettings::default() };
std::thread::scope(|scope| {
let flag = Arc::clone(&cancelled);
let done = Arc::clone(&finished);
let ctl = *ctl;
scope.spawn(move || {
while !done.load(Ordering::Relaxed) {
if ctl.cancelled() {
flag.store(true, Ordering::Relaxed);
}
std::thread::sleep(Duration::from_millis(5));
}
});
let rendered = raster::render(page, cache, &settings, options);
finished.store(true, Ordering::Relaxed);
rendered
})
}
/// One page's raster width or height in pixels at `dpi`, at least one.
#[cfg(not(target_arch = "wasm32"))]
fn page_pixels(points: f64, dpi: f64) -> u32 {
(points * dpi / 72.0).round().max(1.0) as u32
}
/// The highest DPI not above `requested` that keeps every page inside the renderer's side and
/// pixel bounds and the whole strip inside `max_union_pixels`. Rendering at that DPI keeps each
/// page's physical size unchanged; unreachable bounds report 1 DPI and the render call then fails
/// with a clear message.
#[cfg(not(target_arch = "wasm32"))]
fn effective_dpi(requested: f64, sizes: &[(f64, f64)], max_side: u64, max_page_pixels: u64, max_union_pixels: u64) -> f64 {
let mut dpi = requested.clamp(1.0, 2400.0);
loop {
let mut union = 0u64;
let mut fits = true;
for &(width_pt, height_pt) in sizes {
let width = u64::from(page_pixels(width_pt, dpi));
let height = u64::from(page_pixels(height_pt, dpi));
if width > max_side || height > max_side || width.saturating_mul(height) > max_page_pixels {
fits = false;
break;
}
union = union.saturating_add(width.saturating_mul(height));
}
if fits && union <= max_union_pixels {
return dpi;
}
if dpi <= 1.0 {
return 1.0;
}
// The strip's gaps contribute a constant width, so a geometric step converges without
// needing a closed form per page.
dpi = (dpi * 0.9).max(1.0);
}
}
/// Maps a craft-pdf open failure to the importer's error.
#[cfg(not(target_arch = "wasm32"))]
fn open_error(error: craft_pdf::OpenError) -> IoError {
use craft_pdf::OpenError;
match error {
OpenError::InputLimit { limit } => IoError::Unsupported(format!("PDF is larger than the {limit}-byte input limit")),
OpenError::Allocation => IoError::Unsupported("PDF needs more memory than is available".into()),
OpenError::BackendPanic => IoError::Unsupported("PDF reader failed on this file; it may be damaged".into()),
OpenError::Load(error) => IoError::Unsupported(format!("PDF: {error:?}")),
}
}
/// Maps a craft-pdf render failure to the importer's error.
#[cfg(not(target_arch = "wasm32"))]
fn render_error(page: usize, dpi: f64, error: raster::Error) -> IoError {
use raster::Error;
match error {
Error::Cancelled => IoError::Cancelled,
Error::OutputLimit => IoError::Unsupported(format!("PDF page {page} is too large at {dpi:.0} dpi; lower the import DPI")),
Error::InvalidPage => IoError::Unsupported(format!("PDF page {page} has an empty or invalid page box")),
Error::Allocation => IoError::Unsupported(format!("PDF page {page} needs more memory than is available")),
Error::BackendPanic => IoError::Unsupported(format!("PDF renderer failed on page {page}; it may be damaged")),
Error::InvalidOptions | Error::BufferLength => IoError::Unsupported(format!("PDF page {page} could not be rendered")),
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use std::sync::atomic::AtomicUsize;
use lopdf::{Document as PdfDocument, Object, Stream, dictionary};
use super::*;
/// A one-page PDF whose content stream is `operators` short strokes: rendering costs time
/// per operator, not per pixel.
fn dense_operator_pdf(operators: usize) -> Result<Vec<u8>, lopdf::Error> {
let mut pdf = PdfDocument::with_version("1.5");
let pages_id = pdf.new_object_id();
let mut content = String::with_capacity(operators.saturating_mul(24));
content.push_str("0 0 1 RG 0.5 w\n");
for i in 0..operators {
let x = (i % 200) as f32 * 0.5;
let y = ((i / 200) % 100) as f32 * 0.5;
content.push_str(&format!("{x:.1} {y:.1} m {:.1} {y:.1} l S\n", x + 0.4));
}
let content_id = pdf.add_object(Stream::new(dictionary! {}, content.into_bytes()));
let page_id = pdf.add_object(dictionary! {
"Type" => "Page",
"Parent" => pages_id,
"MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(200.0), Object::Real(100.0)]),
"Contents" => content_id,
"Resources" => dictionary! {},
});
pdf.objects.insert(
pages_id,
Object::Dictionary(dictionary! {
"Type" => "Pages",
"Kids" => Object::Array(vec![Object::Reference(page_id)]),
"Count" => 1,
}),
);
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
pdf.trailer.set("Root", catalog);
let mut bytes = Vec::new();
pdf.save_to(&mut bytes)?;
Ok(bytes)
}
/// Hundreds of thousands of path operators take far longer than the watcher's polling
/// interval, so the interrupt lands mid-render and the page reports Cancelled. A million
/// strokes leaves a wide margin even on a fast, optimised test build.
#[test]
fn a_dense_page_stops_when_the_interrupt_fires_mid_render() {
let pdf = dense_operator_pdf(1_000_000).expect("writing the dense PDF");
let document = craft_pdf::open_slice_with_options(&pdf, None, &craft_pdf::OpenOptions::default()).expect("the dense PDF opens");
let cache = RenderCache::new();
let options =
raster::Options { scale: [1.0, 1.0], size: Some([200, 100]), offset: [0.0, 0.0], background: [255, 255, 255, 255], color_replacement: None };
let polls = AtomicUsize::new(0);
// `render_page` checks once before spawning; the watcher then polls every 5 ms. Ten
// polls put the cancellation about 45 ms into a render that takes much longer.
let cancel = || polls.fetch_add(1, Ordering::SeqCst) >= 9;
let ctl = Interrupt::cancel_only(&cancel);
let error = match render_page(&document.pages()[0], &cache, &options, &ctl) {
Err(error) => error,
Ok(_) => panic!("the dense page rendered to completion before the interrupt fired"),
};
assert!(matches!(render_error(1, 72.0, error), IoError::Cancelled), "the render error maps to Cancelled");
assert!(polls.load(Ordering::SeqCst) >= 10, "the watcher must keep polling the interrupt");
}
}
+1
View File
@@ -44,6 +44,7 @@ mod orientation;
mod pattern_fill_psd;
mod pcraft_full_composite;
mod pcraft_manifest_name;
mod pdf_import;
mod pdn_corpus;
mod png_steps;
mod png_text_metadata;
+196
View File
@@ -0,0 +1,196 @@
//! PDF import end-to-end through craft-pdf (pure Rust, no shared library).
//!
//! A six-page synthetic PDF (plain, CropBox offset, rotations 90/180/270 and an oversized
//! CropBox) imports at 72 and 300 DPI as one artboard per page, with the page's print size kept,
//! a blue rectangle sampled from the raster, and the renderer's side/pixel limits respected by
//! lowering the effective DPI on a huge page.
use std::sync::atomic::{AtomicBool, Ordering};
use lopdf::{Document as PdfDocument, Object, Stream, dictionary};
use photocraft_doc::LayerContent;
use photocraft_geom::Rect;
use photocraft_io::{ImportOptions, IoError, import_with_options_and_interrupt};
use photocraft_raster::Interrupt;
const PAGE_W: f64 = 200.0;
const PAGE_H: f64 = 100.0;
/// Six one-page variants: plain, CropBox offset to (10, 20, 210, 120), rotations of 90/180/270
/// degrees and an oversized CropBox (-50, -50, 250, 150) around the 200 x 100 MediaBox. Each page
/// draws a 40 x 40 blue rectangle at (20, 30) in PDF space.
fn variant_pdf() -> Vec<u8> {
let pages: [(Option<i64>, Option<[f32; 4]>); 6] = [
(None, None),
(None, Some([10.0, 20.0, 210.0, 120.0])),
(Some(90), None),
(Some(180), None),
(Some(270), None),
(None, Some([-50.0, -50.0, 250.0, 150.0])),
];
let mut pdf = PdfDocument::with_version("1.5");
let pages_id = pdf.new_object_id();
let mut kids = Vec::new();
for (rotate, crop) in pages {
let content = b"0 0 1 rg 20 30 40 40 re f";
let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec()));
let mut page = dictionary! {
"Type" => "Page",
"Parent" => pages_id,
"MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(PAGE_W as f32), Object::Real(PAGE_H as f32)]),
"Contents" => content_id,
"Resources" => dictionary! {},
};
if let Some(rotate) = rotate {
page.set("Rotate", rotate);
}
if let Some([left, bottom, right, top]) = crop {
page.set("CropBox", Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)]));
}
kids.push(Object::Reference(pdf.add_object(page)));
}
let count = kids.len() as i64;
pdf.objects.insert(
pages_id,
Object::Dictionary(dictionary! {
"Type" => "Pages",
"Kids" => Object::Array(kids),
"Count" => count,
}),
);
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
pdf.trailer.set("Root", catalog);
let mut bytes = Vec::new();
pdf.save_to(&mut bytes).expect("writing the variant PDF");
bytes
}
/// One page of `width` x `height` points with the same blue rectangle.
fn one_page_pdf(width: f32, height: f32) -> Vec<u8> {
let mut pdf = PdfDocument::with_version("1.5");
let pages_id = pdf.new_object_id();
let content_id = pdf.add_object(Stream::new(dictionary! {}, b"0 0 1 rg 20 30 40 40 re f".to_vec()));
let page_id = pdf.add_object(dictionary! {
"Type" => "Page",
"Parent" => pages_id,
"MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(width), Object::Real(height)]),
"Contents" => content_id,
"Resources" => dictionary! {},
});
pdf.objects.insert(
pages_id,
Object::Dictionary(dictionary! {
"Type" => "Pages",
"Kids" => Object::Array(vec![Object::Reference(page_id)]),
"Count" => 1,
}),
);
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
pdf.trailer.set("Root", catalog);
let mut bytes = Vec::new();
pdf.save_to(&mut bytes).expect("writing the page PDF");
bytes
}
/// The first artboard rectangle of `document`.
fn first_artboard(document: &photocraft_doc::Document) -> Rect {
let layer = document.layers.first().expect("an imported page group");
let group = match &layer.content {
LayerContent::Group(group) => group,
_ => panic!("{} is not a group", layer.name),
};
group.artboard.as_ref().expect("page artboard").rect
}
/// Each page becomes its own artboard at 72 and 300 DPI, with the print size preserved.
#[test]
fn imports_every_page_as_an_artboard_with_its_print_size() {
let pdf = variant_pdf();
for dpi in [72.0f32, 300.0] {
let options = ImportOptions { pdf_dpi: dpi, ..Default::default() };
let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &Interrupt::NONE).expect("PDF import");
assert_eq!(result.document.layers.len(), 6, "one artboard per page at {dpi} dpi");
let mut top_left = 0i32;
for (index, layer) in result.document.layers.iter().enumerate() {
let group = match &layer.content {
LayerContent::Group(group) => group,
_ => panic!("{} is not a page group", layer.name),
};
let artboard = group.artboard.as_ref().expect("page artboard").rect;
let expected = match index {
// CropBox [10, 20, 210, 120] intersected with the MediaBox is 190 x 80 points.
1 => (190.0, 80.0),
// Rotations 90 and 270 swap the axes.
2 | 4 => (100.0, 200.0),
_ => (200.0, 100.0),
};
let print_width = f64::from(artboard.width()) * 72.0 / f64::from(dpi);
let print_height = f64::from(artboard.height()) * 72.0 / f64::from(dpi);
assert!((print_width - expected.0).abs() < 1.0, "page {} width is {print_width:.1} pt, expected {} at {dpi} dpi", index + 1, expected.0);
assert!((print_height - expected.1).abs() < 1.0, "page {} height is {print_height:.1} pt, expected {} at {dpi} dpi", index + 1, expected.1);
assert_eq!(artboard.x0, top_left, "pages lay out side by side from x=0");
top_left = artboard.x1 + 80;
let surface = group.children.first().and_then(|layer| layer.surface()).expect("page raster layer");
if index == 0 {
// The rectangle's centre in PDF space is (40, 50); at the document's top-left
// origin that is y = PAGE_H - 50.
let scale = f64::from(dpi) / 72.0;
let x = artboard.x0 + (40.0 * scale).round() as i32;
let y = ((PAGE_H - 50.0) * scale).round() as i32;
let mut pixel = [[0u8; 4]; 1];
surface.read_rgba8_into(Rect::from_xywh(x, y, 1, 1), &mut pixel);
assert!(pixel[0][2] > 120 && pixel[0][0] < 120, "page 1 should be blue inside the rectangle, got {:?}", pixel[0]);
let mut background = [[0u8; 4]; 1];
surface.read_rgba8_into(Rect::from_xywh(artboard.x0 + 2, 2, 1, 1), &mut background);
assert!(background[0][0] > 240 && background[0][1] > 240 && background[0][2] > 240, "page background should be white, got {:?}", background[0]);
}
}
}
}
/// A page over the renderer's side limit lowers the effective DPI instead of failing.
#[test]
fn huge_pages_lower_the_effective_dpi_within_the_renderer_bounds() {
// 3000 pt at 300 dpi would be 12500 px wide, over craft-pdf's 8192 px side limit.
let pdf = one_page_pdf(3000.0, 100.0);
let options = ImportOptions { pdf_dpi: 300.0, ..Default::default() };
let result = import_with_options_and_interrupt("wide.pdf", &pdf, &options, &Interrupt::NONE).expect("PDF import");
assert!(result.warnings.iter().any(|warning| warning.contains("rendered at")), "warnings: {:?}", result.warnings);
let artboard = first_artboard(&result.document);
assert!(artboard.width() <= 8192, "width {} is over the renderer's side limit", artboard.width());
assert!(result.document.resolution_dpi < 300.0, "the effective DPI should be lowered");
let print_width = f64::from(artboard.width()) * 72.0 / f64::from(result.document.resolution_dpi);
assert!((print_width - 3000.0).abs() < 1.0, "print width {print_width:.1} pt should stay 3000 pt");
}
/// Cancelling at the public boundary or between pages returns Cancelled, never a document.
///
/// The renderer's watcher polls the interrupt while a page is being interpreted, so the number
/// of checks is not fixed any more; these triggers do not depend on counting them.
#[test]
fn cancelling_before_and_between_pages_is_reported() {
let pdf = variant_pdf();
let options = ImportOptions { pdf_dpi: 72.0, ..Default::default() };
// The boundary check before dispatch: already cancelled.
let always = || true;
let ctl = Interrupt::cancel_only(&always);
match import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl) {
Err(IoError::Cancelled) => {}
other => panic!("an already-cancelled import returned {:?}", other.map(|_| ())),
}
// The per-page loop's check: the first page's progress cancels the next iteration.
let cancelled = AtomicBool::new(false);
let cancel = || cancelled.load(Ordering::SeqCst);
let progress = |fraction: f32| {
if fraction > 0.0 {
cancelled.store(true, Ordering::SeqCst);
}
};
let ctl = Interrupt::new(&cancel, &progress);
match import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl) {
Err(IoError::Cancelled) => {}
other => panic!("cancelling after the first page returned {:?}", other.map(|_| ())),
}
}
-1
View File
@@ -227,7 +227,6 @@ impl PhotocraftApp {
histogram_panel::restore_options(&mut app);
// After the saved preferences, which say whether the set was already offered.
kys_import::offer_import(&mut app);
notices::wayland_file_drop_guidance(&mut app);
// File › Scripts › Script Events Manager: "Start Application".
photocraft_engine::automate_cmds::fire_event(&mut app.session, "startApplication");
app
+1 -1
View File
@@ -121,7 +121,7 @@ impl PhotocraftApp {
}
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
if !dropped.is_empty() {
let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx));
let at = self.cursor_pos(ctx);
self.open_dropped(ctx, dropped, at);
// Files dragged in from another app's window: PhotoCraft comes to the front and takes
// the keyboard, as Photoshop does, instead of staying behind the source (#5687).
@@ -0,0 +1,125 @@
//! #11907: with the Background Eraser active, the number keys set its Tolerance as they set Opacity
//! for the painting tools (3 = 30%, 0 = 100%, 5 then 5 typed quickly = 55%), as in the reference
//! application. Other tools' digits are unchanged.
use egui::{Event, Key, Modifiers};
use serde_json::json;
use crate::PhotocraftApp;
use crate::opacity_keys::press;
use crate::state::Tool;
fn app(tool: Tool) -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 32, "height": 32})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
app.ui.tool = tool;
app
}
fn tolerance(app: &PhotocraftApp) -> f32 {
app.ui.tool_options.bg_tolerance
}
fn layer(app: &PhotocraftApp) -> (f32, f32) {
let st = app.session.active().unwrap();
let l = st.doc.layer(st.active_layer.unwrap()).unwrap();
(l.opacity, l.fill_opacity)
}
#[test]
fn single_digits_set_the_tolerance() {
let mut a = app(Tool::BackgroundEraser);
assert_eq!(tolerance(&a), 50.0, "default");
press(&mut a, 3, false, 0.0);
assert_eq!(tolerance(&a), 30.0);
press(&mut a, 0, false, 5000.0);
assert_eq!(tolerance(&a), 100.0, "0 = 100%");
press(&mut a, 1, false, 10000.0);
assert_eq!(tolerance(&a), 10.0);
}
#[test]
fn two_quick_digits_set_an_exact_tolerance() {
let mut a = app(Tool::BackgroundEraser);
press(&mut a, 5, false, 0.0);
press(&mut a, 5, false, 300.0);
assert_eq!(tolerance(&a), 55.0);
// A slow second digit starts over.
press(&mut a, 4, false, 5000.0);
press(&mut a, 2, false, 9000.0);
assert_eq!(tolerance(&a), 20.0);
}
#[test]
fn the_tolerance_is_shown_in_ui_inspect() {
let mut a = app(Tool::BackgroundEraser);
press(&mut a, 3, false, 0.0);
let options = serde_json::to_value(&a.ui.tool_options).unwrap();
assert_eq!(options["bg_tolerance"], json!(30.0));
}
#[test]
fn background_eraser_digits_leave_the_brush_and_the_layer_alone() {
let mut a = app(Tool::BackgroundEraser);
let brush = a.session.tools.brush.clone();
press(&mut a, 7, false, 0.0);
assert_eq!(a.session.tools.brush, brush);
assert_eq!(layer(&a), (1.0, 1.0));
assert_eq!(a.ui.tool_options.fill_opacity, 100.0);
}
#[test]
fn unmeasured_shift_digits_and_double_zero_keep_the_tolerance() {
let mut a = app(Tool::BackgroundEraser);
press(&mut a, 3, true, 0.0);
assert_eq!(tolerance(&a), 50.0, "⇧3 changes nothing");
press(&mut a, 0, false, 5000.0);
press(&mut a, 0, false, 5100.0);
assert_eq!(tolerance(&a), 100.0, "00 keeps the 100% of the first 0");
}
#[test]
fn other_tools_digits_are_unchanged() {
for tool in [Tool::Brush, Tool::Pencil, Tool::Eraser] {
let mut a = app(tool);
press(&mut a, 3, false, 0.0);
assert!((a.session.tools.brush.opacity - 0.3).abs() < 1e-6, "{tool:?}");
assert_eq!(tolerance(&a), 50.0, "{tool:?}");
}
for tool in [Tool::Gradient, Tool::PaintBucket] {
let mut a = app(tool);
press(&mut a, 3, false, 0.0);
assert_eq!(a.ui.tool_options.fill_opacity, 30.0, "{tool:?}");
assert_eq!(tolerance(&a), 50.0, "{tool:?}");
}
let mut a = app(Tool::Move);
press(&mut a, 3, false, 0.0);
assert!((layer(&a).0 - 0.3).abs() < 1e-6);
assert_eq!(tolerance(&a), 50.0);
// The tools whose number is a strength, exposure or tolerance of their own still ignore the digits.
for tool in [Tool::ColorReplacement, Tool::Dodge, Tool::Smudge, Tool::MagicEraser] {
let mut a = app(tool);
let before = (a.session.tools.brush.clone(), layer(&a), a.ui.tool_options.clone());
press(&mut a, 3, false, 0.0);
assert_eq!((a.session.tools.brush.clone(), layer(&a), a.ui.tool_options.clone()), before, "{tool:?}");
}
}
/// Through the whole app: number keys typed over the canvas (no widget focused).
#[test]
fn number_keys_set_the_tolerance_in_the_app() {
use egui_kittest::Harness;
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
app(Tool::BackgroundEraser)
});
h.run_steps(4);
let key = |h: &mut Harness<'_, PhotocraftApp>, k: Key| {
h.event(Event::Key { key: k, physical_key: Some(k), pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.event(Event::Key { key: k, physical_key: Some(k), pressed: false, repeat: false, modifiers: Modifiers::NONE });
h.run_steps(2);
};
key(&mut h, Key::Num3);
assert_eq!(tolerance(h.state()), 30.0);
}
@@ -0,0 +1,310 @@
//! #11909: the Background Eraser's Tolerance takes whole numbers 1..100; a value typed past the
//! range becomes the closest one and, once the field is left, an alert with OK says so.
//! `paint.backgroundEraser` clamps `tolerance` to 1..100 too, and the options bar's controls carry
//! the reference application's tooltips.
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::PhotocraftApp;
use crate::eraser_ui::TOLERANCE_RANGE_ALERT;
use crate::state::{DialogKind, Tool};
fn app_harness() -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 200, "height": 150})).unwrap();
app.ui.tool = Tool::BackgroundEraser;
app
});
h.run_steps(5);
h
}
fn bar(tool: Tool) -> Harness<'static, PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 80, "height": 80})).unwrap();
app.ui.tool = tool;
let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(4);
h
}
/// Types `text` into the Tolerance field, then Tabs out of it.
fn type_tolerance(h: &mut Harness<'static, PhotocraftApp>, text: &str) {
h.query_all_by_role(egui::accesskit::Role::SpinButton)
.find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:"))
.expect("the Tolerance field")
.click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(text.into()));
h.run_steps(1);
h.key_press(egui::Key::Tab);
h.run_steps(3);
}
fn alert(h: &Harness<'static, PhotocraftApp>) -> Option<String> {
h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).and_then(|d| d.fields.get("message")).and_then(|m| m.as_str()).map(str::to_owned)
}
fn tolerance(h: &Harness<'static, PhotocraftApp>) -> f32 {
h.state().ui.tool_options.bg_tolerance
}
#[test]
fn tolerance_past_the_range_takes_the_closest_value_and_alerts() {
for (typed, want) in [("0", 1.0), ("150", 100.0), ("-5", 1.0)] {
let mut h = app_harness();
type_tolerance(&mut h, typed);
assert_eq!(tolerance(&h), want, "{typed}");
assert_eq!(alert(&h).as_deref(), Some(TOLERANCE_RANGE_ALERT), "{typed}");
h.get_by_label("OK").click();
h.run_steps(4);
assert_eq!(alert(&h), None, "{typed}: OK closes the alert");
assert_eq!(tolerance(&h), want, "{typed}: the clamped value is kept");
}
}
#[test]
fn the_alert_is_a_modal_the_control_channel_sees() {
let mut h = app_harness();
type_tolerance(&mut h, "150");
let dialogs = serde_json::to_value(&h.state().ui.dialogs).unwrap();
assert!(dialogs.to_string().contains(TOLERANCE_RANGE_ALERT), "{dialogs}");
assert!(h.query_by_label("OK").is_some(), "the alert has an OK button");
}
#[test]
fn tolerance_in_range_stores_a_whole_number_without_an_alert() {
let mut h = app_harness();
type_tolerance(&mut h, "33.6");
assert_eq!(tolerance(&h), 34.0);
assert_eq!(alert(&h), None);
type_tolerance(&mut h, "100");
assert_eq!(tolerance(&h), 100.0);
assert_eq!(alert(&h), None, "the end of the range is in it");
type_tolerance(&mut h, "abc");
assert_eq!(tolerance(&h), 100.0, "not a number: the value stays");
assert_eq!(alert(&h), None);
}
#[test]
fn a_leading_zero_typed_key_by_key_keeps_the_text() {
let mut h = app_harness();
h.query_all_by_role(egui::accesskit::Role::SpinButton)
.find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:"))
.expect("the Tolerance field")
.click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
for c in ["0", "5"] {
h.event(egui::Event::Text(c.into()));
h.run_steps(2);
}
h.key_press(egui::Key::Tab);
h.run_steps(3);
assert_eq!(tolerance(&h), 5.0, "0 then 5 is 05, not 15");
assert_eq!(alert(&h), None, "05 is in range");
}
#[test]
fn a_tolerance_set_elsewhere_during_an_edit_wins_over_the_typed_text() {
let mut h = app_harness();
h.query_all_by_role(egui::accesskit::Role::SpinButton)
.find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:"))
.expect("the Tolerance field")
.click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("150".into()));
h.run_steps(1);
// The bar goes away mid-edit and a preset sets the Tolerance meanwhile.
h.state_mut().ui.panels.options_bar = false;
h.run_steps(2);
h.state_mut().ui.tool_options.bg_tolerance = 30.0;
h.state_mut().ui.panels.options_bar = true;
h.run_steps(1);
// From the first frame back, the field shows the preset's value.
let shown = h
.query_all_by_role(egui::accesskit::Role::SpinButton)
.find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:"))
.expect("the Tolerance field")
.accesskit_node()
.numeric_value();
assert_eq!(shown, Some(30.0), "the field shows the preset's value, not the typed 150");
h.run_steps(2);
assert_eq!(tolerance(&h), 30.0, "the preset's value, not the typed 150");
}
#[test]
fn an_expression_committed_with_enter_past_the_range_alerts() {
let mut h = app_harness();
h.query_all_by_role(egui::accesskit::Role::SpinButton)
.find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:"))
.expect("the Tolerance field")
.click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("50*4".into()));
h.run_steps(1);
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert_eq!(tolerance(&h), 100.0);
assert_eq!(alert(&h).as_deref(), Some(TOLERANCE_RANGE_ALERT));
}
#[test]
fn a_restored_tolerance_out_of_range_shows_as_the_field_stores_it() {
for (saved, want) in [(0.0, 1.0), (33.6, 34.0), (f32::NAN, 50.0)] {
let mut h = app_harness();
h.state_mut().ui.tool_options.bg_tolerance = saved;
h.run_steps(3);
assert_eq!(tolerance(&h), want, "{saved}");
assert_eq!(alert(&h), None, "{saved}: no alert for a restored value");
}
}
#[test]
fn a_restored_fraction_reaches_the_stroke_as_a_whole_number() {
// The options bar need not have drawn: the stroke's params round it themselves.
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
for (saved, want) in [(23.6, 24.0), (0.0, 1.0), (f32::NAN, 50.0)] {
app.ui.tool_options.bg_tolerance = saved;
let p = crate::eraser_ui::background_eraser_params(&app, &[[1.0, 1.0, 1.0]]);
assert_eq!(p["tolerance"].as_f64(), Some(want), "{saved}");
}
}
#[test]
fn a_label_scrub_past_100_does_not_alert() {
let mut h = app_harness();
type_tolerance(&mut h, "90");
// The field keeps the keyboard while the caption is scrubbed from 90 past the end.
let field = h
.query_all_by_role(egui::accesskit::Role::SpinButton)
.find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:"))
.expect("the Tolerance field");
let rect = field.rect();
field.click();
h.run_steps(1);
// The caption sits just left of the field.
let from = egui::pos2(rect.left() - 25.0, rect.center().y);
h.event(egui::Event::PointerMoved(from));
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.run_steps(1);
for k in 1..=6 {
h.event(egui::Event::PointerMoved(from + vec2(50.0 * k as f32, 0.0)));
h.run_steps(1);
}
let to = from + vec2(300.0, 0.0);
h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(3);
h.key_press(egui::Key::Tab);
h.run_steps(3);
assert_eq!(tolerance(&h), 100.0, "the scrub reached the end");
assert_eq!(alert(&h), None, "a scrub stops at 100 without an alert");
}
#[test]
fn an_edit_cut_off_by_hiding_the_bar_leaves_no_stale_alert() {
let mut h = app_harness();
let field = |h: &Harness<'static, PhotocraftApp>| {
h.query_all_by_role(egui::accesskit::Role::SpinButton)
.find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:"))
.expect("the Tolerance field")
.rect()
.center()
};
// 150 typed, then the bar goes away before the field is left.
let at = field(&h);
h.event(egui::Event::PointerMoved(at));
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("150".into()));
h.run_steps(1);
h.state_mut().ui.panels.options_bar = false;
h.run_steps(3);
h.state_mut().ui.panels.options_bar = true;
h.run_steps(3);
assert_eq!(tolerance(&h), 100.0);
// Back in the field and out again without a change: nothing to say.
type_tolerance(&mut h, "100");
assert_eq!(alert(&h), None, "no alert for an edit that was already cut off");
}
/// The accessible descriptions (tooltips) of the widgets of `role` named `label`.
fn descriptions(h: &Harness<'static, PhotocraftApp>, role: Option<egui::accesskit::Role>, label: &str) -> Vec<String> {
let of = |n: egui_kittest::Node<'_>| n.accesskit_node().description().map(|d| d.to_string());
match role {
Some(role) => h.query_all_by_role(role).filter(|n| n.accesskit_node().label().as_deref() == Some(label)).filter_map(of).collect(),
None => h.query_all_by_label(label).filter_map(of).collect(),
}
}
#[test]
fn the_bar_has_the_reference_tooltips() {
use egui::accesskit::Role;
for (role, label, tip) in [
(Role::Button, "Brush Preset picker", "Click to open the Brush Preset picker"),
(Role::ComboBox, "Limits:", "How far to let the erasing spread"),
(Role::SpinButton, "Tolerance:", "Erase range of similar colors"),
(Role::CheckBox, "Protect Foreground Color", "Do not erase the foreground swatch color"),
] {
let mut h = bar(Tool::BackgroundEraser);
assert!(h.query_by_label(tip).is_none(), "{label}: no tooltip before the hover");
let at = h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(label)).expect(label).rect().center();
h.hover_at(at);
h.run_steps(8);
assert!(h.query_by_label(tip).is_some(), "{label}: resting on it shows {tip:?}");
}
}
#[test]
fn the_other_tools_keep_their_brush_chip_tooltip() {
for tool in [Tool::Eraser, Tool::Pencil] {
let h = bar(tool);
let found = descriptions(&h, None, "Brush Preset picker");
assert!(found.iter().any(|d| d == "Brush Preset picker"), "{tool:?}: {found:?}");
}
}
/// The alpha at `(x, y)` after a Background Eraser stroke over white and a square one level off
/// white, with `tolerance`.
fn erased_alpha(tolerance: serde_json::Value, (x, y): (i32, i32)) -> f32 {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 40})).unwrap();
s.execute("select.rect", json!({"x": 30, "y": 0, "width": 34, "height": 40, "antiAlias": false})).unwrap();
s.execute("edit.fill", json!({"color": "#feffff"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.execute(
"paint.backgroundEraser",
json!({"points": [[4, 20], [56, 20]], "size": 16, "hardness": 1, "sampling": "once", "limits": "discontiguous", "tolerance": tolerance}),
)
.unwrap();
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3]
}
#[test]
fn the_command_clamps_tolerance_to_1_through_100() {
// Sampled white; the square is 1/255 off it: Tolerance 1 % reaches it, 0 % would not.
let near = (45, 20);
assert!(erased_alpha(json!(1), near) < 1.0, "1 % erases the near-white square");
assert_eq!(erased_alpha(json!(0), near), erased_alpha(json!(1), near), "0 is taken as 1");
assert_eq!(erased_alpha(json!(-20), near), erased_alpha(json!(1), near), "below the range is taken as 1");
assert_eq!(erased_alpha(json!(150), (6, 20)), erased_alpha(json!(100), (6, 20)), "150 is taken as 100");
}
#[test]
fn the_params_doc_says_1_through_100() {
let spec = photocraft_engine::commands::find("paint.backgroundEraser").expect("registered");
assert!(spec.params.contains(r#""tolerance":1..100=50"#), "{}", spec.params);
}
@@ -0,0 +1,146 @@
//! The Brush's Opacity starts at 1 %, as in Photoshop (#11812): its options-bar field takes whole
//! numbers from 1 to 100, the digit keys `00` set 100 %, and `tools.setBrush` floors opacity at 1 %.
use egui::{Event, Key, Modifiers, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::PhotocraftApp;
use crate::opacity_keys::press;
use crate::state::Tool;
fn app(tool: Tool) -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.ui.tool = tool;
app
}
fn options_bar(tool: Tool, theme: crate::theme::ThemeKind) -> Harness<'static, PhotocraftApp> {
let mut ready = false;
let mut h = Harness::builder().with_size(vec2(1400.0, 60.0)).build_ui_state(
move |ui, app: &mut PhotocraftApp| {
if !ready {
crate::theme::install_fonts(ui.ctx());
crate::theme::apply(ui.ctx(), theme);
ready = true;
return;
}
crate::panels::options_bar(app, ui);
},
app(tool),
);
h.run_steps(4);
h
}
/// Types `text` into the options bar's Opacity field and presses Enter.
fn type_opacity(h: &mut Harness<'_, PhotocraftApp>, text: &str) -> f32 {
// "Opacity:" in the Photoshop-look themes, "Opacity" in the others.
let field = h
.query_all(egui_kittest::kittest::by().role(egui::accesskit::Role::SpinButton))
.find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == "Opacity"))
.unwrap_or_else(|| panic!("the {:?} Opacity field", h.state().ui.tool))
.rect();
h.hover_at(field.center());
h.run();
h.drag_at(field.center());
h.run();
h.drop_at(field.center());
h.run_steps(2);
h.event(Event::Key { key: Key::A, physical_key: Some(Key::A), pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
h.run();
h.event(Event::Text(text.into()));
h.run_steps(2);
h.event(Event::Key { key: Key::Enter, physical_key: Some(Key::Enter), pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.run_steps(3);
h.state().session.tools.brush.opacity
}
/// In the Photoshop-look themes and the others (their options bars lay the Brush out apart); the
/// Pencil and Eraser fields take 1-100 whole numbers in Photoshop too.
#[test]
fn the_brush_opacity_field_takes_whole_numbers_from_1_to_100() {
use crate::theme::ThemeKind;
for theme in [ThemeKind::ProMedium, ThemeKind::Studio] {
for tool in [Tool::Brush, Tool::Pencil, Tool::Eraser] {
let mut h = options_bar(tool, theme);
for (typed, want) in [("0", 0.01), ("-10", 0.01), ("150", 1.0), ("45", 0.45), ("33.7", 0.34)] {
let got = type_opacity(&mut h, typed);
assert!((got - want).abs() < 1e-6, "{theme:?} {tool:?} typed {typed}: {got}, want {want}");
}
}
}
}
#[test]
fn double_zero_sets_the_brush_to_100_percent() {
let mut a = app(Tool::Brush);
a.run("tools.setBrush", json!({"brush": {"opacity": 0.3}})).unwrap();
press(&mut a, 0, false, 0.0);
press(&mut a, 0, false, 100.0);
assert_eq!(a.session.tools.brush.opacity, 1.0, "00 = 100%");
// Other pairs are the exact value; single digits are tens; 0 alone is 100%.
for (digits, want) in [([0, 7], 0.07), ([4, 5], 0.45)] {
press(&mut a, digits[0], false, 10_000.0);
press(&mut a, digits[1], false, 10_100.0);
assert!((a.session.tools.brush.opacity - want).abs() < 1e-6, "{digits:?}");
}
for (d, want) in [(3, 0.3), (9, 0.9), (0, 1.0), (1, 0.1)] {
press(&mut a, d, false, 20_000.0 + f64::from(d) * 10_000.0);
assert!((a.session.tools.brush.opacity - want).abs() < 1e-6, "{d}");
}
// With build-up on, ⇧ digits set the opacity: `00` is 100% there too.
a.session.tools.brush.build_up = true;
press(&mut a, 2, true, 200_000.0);
press(&mut a, 0, true, 300_000.0);
press(&mut a, 0, true, 300_100.0);
assert_eq!(a.session.tools.brush.opacity, 1.0);
}
#[test]
fn double_zero_on_flow_keeps_its_one_percent() {
let mut a = app(Tool::Brush);
press(&mut a, 0, true, 0.0);
press(&mut a, 0, true, 100.0);
assert_eq!(a.session.tools.brush.flow, 0.01, "⇧00 is Flow's 1%, unchanged");
}
#[test]
fn set_brush_floors_opacity_at_one_percent() {
let mut a = app(Tool::Brush);
for params in [json!({"brush": {"opacity": 0}}), json!({"opacity": 0.0}), json!({"brush": {"opacity": 0.004}})] {
a.run("tools.setBrush", json!({"brush": {"opacity": 0.5}})).unwrap();
a.run("tools.setBrush", params.clone()).unwrap();
assert_eq!(a.session.tools.brush.opacity, 0.01, "{params}");
}
a.run("tools.setBrush", json!({"brush": {"opacity": 0.37}})).unwrap();
assert!((a.session.tools.brush.opacity - 0.37).abs() < 1e-6, "values above the floor are kept");
}
/// The Pencil's `00` is 100 % too (the Pencil has no Flow, so ⇧ digits are not involved).
#[test]
fn double_zero_sets_the_pencil_to_100_percent() {
let mut a = app(Tool::Pencil);
a.run("tools.setBrush", json!({"brush": {"opacity": 0.3}})).unwrap();
press(&mut a, 0, false, 0.0);
press(&mut a, 0, false, 100.0);
assert_eq!(a.session.tools.brush.opacity, 1.0, "00 = 100%");
}
/// An opacity set outside the field (a `tools.setBrush` fraction, an older saved 0) shows as the
/// whole percent in 1-100 the field can hold.
#[test]
fn the_opacity_field_shows_outside_values_as_whole_percents() {
let mut h = options_bar(Tool::Brush, crate::theme::ThemeKind::ProMedium);
for (stored, shown) in [(0.337, 34.0), (0.0, 1.0), (0.004, 1.0)] {
h.state_mut().session.tools.brush.opacity = stored;
h.run_steps(2);
let value = h
.query_all(egui_kittest::kittest::by().role(egui::accesskit::Role::SpinButton))
.find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == "Opacity"))
.and_then(|n| n.accesskit_node().numeric_value());
assert_eq!(value, Some(shown), "stored {stored}");
assert_eq!(h.state().session.tools.brush.opacity, stored, "showing it does not change it");
}
}
+81 -1
View File
@@ -46,6 +46,15 @@ pub struct CanvasToolMenu {
/// had when it opened.
#[serde(default)]
pub crop: Option<Vec<String>>,
/// The Color Sampler menu's sampler: the one under the pointer when it opened (its index),
/// `None` off a sampler, where every row is greyed.
#[serde(default)]
pub sampler: Option<usize>,
/// Where that sampler was when the menu opened: the active document's index and the sampler's
/// position. Once a control command deletes, moves or renumbers samplers, or another document
/// becomes active, the index may name a different sampler, so the menu closes and Delete greys.
#[serde(default)]
pub sampler_at: Option<(usize, [f64; 2])>,
}
/// A misspelled word in the type layer being edited (`edit.checkSpelling`'s `list` entry).
@@ -303,6 +312,8 @@ pub fn open_crop(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32;
guide: false,
spelling: None,
crop: Some(users),
sampler: None,
sampler_at: None,
});
crate::canvas_popup::mark_open(ctx, menu_id());
true
@@ -445,7 +456,50 @@ pub const PEN_MENU: &[Row] = &[
Some(("Disable Symmetry Path", "paint.symmetryDisable")),
];
/// Tools whose plain canvas right-click offers selection actions.
/// The Color Sampler menu's Delete row: removes the sampler the menu opened on.
pub const SAMPLER_DELETE: &str = "view.colorSamplers.delete";
/// The Color Sampler's canvas menu (#11733), in the reference application's order: Delete, then
/// the readout modes for the sampler under the pointer. The readout rows are this menu's own ids
/// and stay greyed until samplers have their own readout mode.
pub const SAMPLER_MENU: &[Row] = &[
Some(("Delete", SAMPLER_DELETE)),
None,
Some(("Actual Color", "colorSampler.readout.actual")),
Some(("Proof Color", "colorSampler.readout.proof")),
None,
Some(("Grayscale", "colorSampler.readout.gray")),
Some(("RGB Color", "colorSampler.readout.rgb")),
Some(("Web Color", "colorSampler.readout.web")),
Some(("HSB Color", "colorSampler.readout.hsb")),
Some(("HSL Color", "colorSampler.readout.hsl")),
Some(("CMYK Color", "colorSampler.readout.cmyk")),
Some(("Lab Color", "colorSampler.readout.lab")),
None,
Some(("Grayscale 16 bit", "colorSampler.readout.gray16")),
Some(("RGB 16 bit", "colorSampler.readout.rgb16")),
Some(("CMYK 16 bit", "colorSampler.readout.cmyk16")),
Some(("Lab 16 bit", "colorSampler.readout.lab16")),
None,
Some(("Total Ink", "colorSampler.readout.totalInk")),
];
/// Does the Color Sampler menu's index still name the sampler it opened on, in the same document?
/// `true` off a sampler, where there is nothing to go stale.
fn sampler_current(app: &PhotocraftApp, menu: &CanvasToolMenu) -> bool {
let Some(i) = menu.sampler else { return true };
let now = app.session.active_index().zip(app.session.active().and_then(|d| d.color_samplers.get(i).copied()));
now.is_some() && now == menu.sampler_at
}
/// Is `menu` the Color Sampler's own menu (not the pasteboard, guide or transform menu opened
/// with it)?
fn sampler_menu(menu: &CanvasToolMenu) -> bool {
menu.tool == Tool::ColorSampler && !menu.transform && !menu.pasteboard && !menu.guide && menu.crop.is_none() && menu.anchor.is_none()
}
/// Tools whose plain canvas right-click opens a menu: the selection tools' actions, the path
/// menu and the Color Sampler's.
pub fn applies(tool: Tool) -> bool {
matches!(
tool,
@@ -461,6 +515,7 @@ pub fn applies(tool: Tool) -> bool {
// Its brush is set from the options bar's chip; the canvas right-click is the
// selection menu, as in Photoshop (#7268).
| Tool::QuickSelection
| Tool::ColorSampler
) || path_menu(tool)
}
@@ -510,6 +565,8 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] {
TYPE_LAYER_MENU
} else if path_menu(menu.tool) {
PEN_MENU
} else if sampler_menu(menu) {
SAMPLER_MENU
} else {
selection_rows(menu.has_selection)
}
@@ -649,6 +706,8 @@ pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) ->
guide: false,
spelling: None,
crop: None,
sampler: None,
sampler_at: None,
});
crate::canvas_popup::mark_open(ctx, menu_id());
true
@@ -674,6 +733,9 @@ pub fn engine_call(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) ->
_ => (command.into(), json!({})),
};
}
if sampler_menu(menu) {
return (command.into(), menu.sampler.map_or(json!({}), |i| json!({"index": i})));
}
match pasteboard_choice(command) {
Some(c) if menu.pasteboard => ("prefs.set".into(), json!({"values": {"interface.canvasColor": c.name()}})),
_ if menu.pasteboard => ("prefs.set".into(), json!({})),
@@ -727,6 +789,8 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos:
guide: false,
spelling: None,
crop: None,
sampler: None,
sampler_at: None,
});
crate::canvas_popup::mark_open(ctx, menu_id());
true
@@ -758,6 +822,8 @@ pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui
guide: true,
spelling: None,
crop: None,
sampler: None,
sampler_at: None,
});
crate::canvas_popup::mark_open(ctx, menu_id());
true
@@ -810,6 +876,10 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str)
if menu.type_layer {
return TYPE_LAYER_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command);
}
// Off a sampler every row is greyed. The readout rows wait for per-sampler readout modes.
if sampler_menu(menu) {
return command == SAMPLER_DELETE && menu.sampler.is_some() && sampler_current(app, menu);
}
if menu.transform || !path_menu(menu.tool) {
return crate::menus::is_enabled(app, command);
}
@@ -870,6 +940,8 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]
let has_path = crate::vector_ui::active_path_name(app).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2);
let path_name = crate::vector_ui::active_path_name(app);
let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None };
let sampler = if tool == Tool::ColorSampler { doc.and_then(|d| crate::analysis_ui::sampler_at(app, d)) } else { None };
let sampler_at = sampler.and_then(|i| Some((app.session.active_index()?, *app.session.active()?.color_samplers.get(i)?)));
app.ui.canvas_tool_menu = Some(CanvasToolMenu {
pos,
tool,
@@ -884,6 +956,8 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]
guide: false,
spelling,
crop: None,
sampler,
sampler_at,
});
crate::canvas_popup::mark_open(ctx, menu_id());
true
@@ -911,6 +985,8 @@ pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32;
guide: false,
spelling: None,
crop: None,
sampler: None,
sampler_at: None,
});
crate::canvas_popup::mark_open(ctx, menu_id());
true
@@ -964,6 +1040,9 @@ pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) {
choose_type(app, ctx, command)
} else if path_menu(menu.tool) && !menu.transform {
choose_pen(app, ctx, &menu, command)
} else if sampler_menu(&menu) {
let (id, params) = engine_call(app, &menu, command);
app.run(&id, params).map(|_| ())
} else if command == "select.toWorkPath" {
// Photoshop's Make Work Path… asks for the tolerance first.
spec_dialog(app, command, "Make Work Path", r##"{"tolerance":0.5..10=2}"##, serde_json::Map::new());
@@ -1153,6 +1232,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) {
|| (menu.text && app.ui.text_edit.is_none())
|| (menu.type_layer && app.ui.text_edit.is_some())
|| (menu.crop.is_some() && !crate::crop_ui::pending(app))
|| (sampler_menu(&menu) && !sampler_current(app, &menu))
{
app.ui.canvas_tool_menu = None;
return;
@@ -71,6 +71,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
command: cmd,
params,
k,
tool_colors: (app.session.tools.foreground, app.session.tools.background),
};
let key = request.doc.0 ^ (1u64 << 61);
// Every filter's preview computes off the UI thread in the desktop app: Gaussian Blur at
@@ -128,6 +129,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
task.target,
&documents,
&color,
Some(task.tool_colors),
),
}
.map(|doc| {
@@ -172,6 +174,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
request.target,
&documents,
&app.session.color.settings,
Some(request.tool_colors),
),
}
.map(|doc| {
+5 -1
View File
@@ -146,6 +146,7 @@ fn is_point_tool(t: Tool) -> bool {
| Tool::EllipseShape
| Tool::Triangle
| Tool::Polygon
| Tool::Star
| Tool::Line
| Tool::Type
| Tool::VerticalType
@@ -334,7 +335,10 @@ pub(crate) fn snap_click(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers
/// the pixel grid.
fn pixel_round(app: &PhotocraftApp, p: [f64; 2]) -> [f64; 2] {
if app.session.prefs().tools.snap_vector_tools_and_transforms_to_pixel_grid
&& matches!(app.ui.tool, Tool::Pen | Tool::CurvaturePen | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line)
&& matches!(
app.ui.tool,
Tool::Pen | Tool::CurvaturePen | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::Line
)
{
[p[0].round(), p[1].round()]
} else {
+1 -1
View File
@@ -947,7 +947,7 @@ fn alt_over_the_box_shows_the_reference_point_pointer() {
for p in [[55.0, 52.0], [30.0, 30.0], [200.0, 200.0]] {
assert_eq!(crate::transform_tool::cursor(&app, &xf, p, alt), Some(egui::CursorIcon::Crosshair), "{p:?}");
}
assert_eq!(crate::transform_tool::cursor(&app, &xf, [55.0, 52.0], egui::Modifiers::NONE), Some(egui::CursorIcon::Move));
assert_eq!(crate::transform_tool::cursor(&app, &xf, [55.0, 52.0], egui::Modifiers::NONE), Some(egui::CursorIcon::Default));
assert_ne!(crate::transform_tool::cursor(&app, &xf, [40.0, 40.0], alt), Some(egui::CursorIcon::Crosshair), "a corner handle stays a handle");
}
+3 -7
View File
@@ -274,13 +274,9 @@ fn render_first_run_content(app: &mut PhotocraftApp, ui: &mut egui::Ui, content_
});
}
/// Wayland has no native file drops (winit 0.30, #386), so the hint offers File › Open and paste.
pub(crate) fn start_screen_drop_hint(app: &PhotocraftApp) -> std::borrow::Cow<'static, str> {
if app.services.is_wayland {
crate::i18n::fmt(tl!("Use File › Open, or paste a copied image with {paste}."), &[("paste", &crate::notices::paste_hint(app))]).into()
} else {
tl!("Drop an image or PSD anywhere to open it.").into()
}
/// Hint displayed on the start screen for opening files.
pub(crate) fn start_screen_drop_hint(_app: &PhotocraftApp) -> std::borrow::Cow<'static, str> {
tl!("Drop an image or PSD anywhere to open it.").into()
}
/// Recent files listed on the Home screen.
+1 -1
View File
@@ -736,7 +736,7 @@ fn drop_slot_line(app: &mut PhotocraftApp, ui: &egui::Ui) {
if ui.input(|i| i.raw.hovered_files.is_empty()) {
return;
}
let at = app.services.cursor_pos.as_mut().and_then(|f| f(ui.ctx()));
let at = app.cursor_pos(ui.ctx());
let crate::file_open::DropTarget::Tabs(slot) = app.drop_target(ui.ctx(), at) else { return };
let Some(tabs) = app.tab_strip.as_ref().map(|s| &s.tabs) else { return };
let Some((r, after)) = tabs.iter().find(|(i, _)| *i == slot).map(|&(_, r)| (r, false)).or_else(|| tabs.last().map(|&(_, r)| (r, true))) else {
+169 -5
View File
@@ -276,6 +276,7 @@ fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() {
command: "filter.blur.gaussianBlur".into(),
params: json!({"radius": 999.0}),
k: 1,
tool_colors: (app.session.tools.foreground, app.session.tools.background),
};
let (told, cancelled) = std::sync::mpsc::channel();
app.filter_preview_worker
@@ -329,6 +330,7 @@ fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::syn
command: command.into(),
params,
k: 1,
tool_colors: (app.session.tools.foreground, app.session.tools.background),
};
let doc = app.session.documents()[0].doc.clone();
let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect();
@@ -347,6 +349,7 @@ fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::syn
key.target,
&documents,
&Default::default(),
Some(key.tool_colors),
)
.map(|d| {
let buffer = photocraft_compose::flatten(&d);
@@ -396,6 +399,169 @@ fn a_held_preview_frame_stays_on_the_canvas_when_the_proxy_factor_changes() {
assert_eq!((k, size), (1, [2400, 2200]));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn indexed_matte_preview_matches_commit_and_refreshes_tool_colors_inline_and_on_worker() {
for background in [false, true] {
for depth in [8, 16, 32] {
for matte in ["foreground", "background"] {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.background_jobs = background;
app.run("file.new", json!({"width": 64, "height": 48, "depth": depth, "background": "transparent"})).unwrap();
app.run("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
app.run("edit.colorSettings", json!({"workingRgb": "display-p3"})).unwrap();
app.session
.edit("Translucent edge", |doc, active| {
let format = doc.pixel_format();
doc.layer_mut(active.unwrap())
.unwrap()
.surface_mut()
.unwrap()
.fill_rect(photocraft_geom::Rect::new(0, 0, 32, 48), &photocraft_raster::from_rgba(&format, [1.0, 0.0, 0.0, 0.5]));
Ok(())
})
.unwrap();
let source = app.session.active().unwrap().doc.clone();
let params = json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte});
crate::filter_dialog::open(&mut app, "image.mode.indexedColor").unwrap();
app.ui.dialogs.last_mut().unwrap().fields.extend(params.as_object().unwrap().clone());
let ctx = egui::Context::default();
let mut previous = None;
for (foreground, background_color) in [("#3366cc", "#cc6633"), ("#26bf59", "#bf26a6")] {
app.session.execute("tools.setColors", json!({"foreground": foreground, "background": background_color})).unwrap();
let colors = (app.session.tools.foreground, app.session.tools.background);
let shown = ensure_filter_preview(&mut app, 0, &ctx);
if background {
assert!(shown.is_none(), "old tool colors must not remain visible");
}
drive_until(&mut app, &ctx, "the current matte colors", |app| {
app.filter_preview.as_ref().is_some_and(|p| p.key.tool_colors == colors && p.result.is_some())
});
let preview = app.filter_preview.as_ref().unwrap().result.as_ref().unwrap();
let mut applied = photocraft_engine::Session::new();
applied.color.settings = app.session.color.settings.clone();
applied.tools.foreground = colors.0;
applied.tools.background = colors.1;
applied.add_document((*source).clone(), None);
applied.execute("image.mode.indexedColor", params.clone()).unwrap();
let committed = &applied.active().unwrap().doc;
assert_eq!(preview.icc_profile, source.icc_profile);
assert_eq!(preview.color_table, committed.color_table);
let actual = preview.layers[0].surface().unwrap().read_region(preview.bounds());
let expected = committed.layers[0].surface().unwrap().read_region(committed.bounds());
assert_eq!(actual, expected, "{matte}, {depth}-bit, worker={background}");
if let Some(previous) = previous {
assert_ne!(actual, previous, "changing the selected tool color refreshes the pixels");
}
previous = Some(actual);
assert_eq!(app.session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Rgb, "preview does not commit");
}
}
}
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn cross_scale_indexed_matte_preview_rejects_old_tool_colors_from_cached_and_worker_results() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.background_jobs = true;
app.run("file.new", json!({"width": 2400, "height": 2200, "depth": 8, "background": "transparent"})).unwrap();
app.run("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
app.run("edit.colorSettings", json!({"workingRgb": "display-p3"})).unwrap();
app.session
.edit("Translucent edge", |doc, active| {
let format = doc.pixel_format();
doc.layer_mut(active.unwrap())
.unwrap()
.surface_mut()
.unwrap()
.fill_rect(photocraft_geom::Rect::new(0, 0, 32, 48), &photocraft_raster::from_rgba(&format, [1.0, 0.0, 0.0, 0.5]));
Ok(())
})
.unwrap();
app.ui.views.get_mut(0).expect("the new document's view").zoom = 0.25;
let params = json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "foreground"});
crate::filter_dialog::open(&mut app, "image.mode.indexedColor").unwrap();
app.ui.dialogs.last_mut().unwrap().fields.extend(params.as_object().unwrap().clone());
app.session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap();
let ctx = egui::Context::default();
drive_until(&mut app, &ctx, "the first indexed preview", |a| a.filter_preview.as_ref().is_some_and(|p| p.result.is_some()));
let old = app.filter_preview.as_ref().expect("the first preview").key.clone();
assert_eq!(old.k, 2, "the zoomed-out large document uses the reduced preview");
app.session.execute("tools.setColors", json!({"foreground": "#26bf59", "background": "#bf26a6"})).unwrap();
app.ui.views.get_mut(0).expect("the new document's view").zoom = 1.0;
let new_colors = (app.session.tools.foreground, app.session.tools.background);
let new = crate::filter_dialog::FilterPreviewKey { k: 1, tool_colors: new_colors, ..old.clone() };
assert_ne!(old.tool_colors, new.tool_colors);
assert_ne!(old.k, new.k, "the cache and request use different preview factors");
// Keep the current worker pending so the only possible frame is the cached old-color one.
let (release_new, wait_new) = std::sync::mpsc::channel();
app.filter_preview_worker
.start(new.clone(), ctx.clone(), move |_| {
wait_new.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job");
crate::dialogs::filter_preview_worker::Computed { result: None, ms: 0.0 }
})
.expect("the worker starts");
assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "the cached old-color frame is not painted while the new worker runs");
release_new.send(()).expect("released");
drive_until(&mut app, &ctx, "the new worker to finish", |a| !a.filter_preview_worker.busy());
assert_eq!(app.filter_preview.as_ref().expect("the current request").key, new);
assert!(app.filter_preview.as_ref().unwrap().result.is_none());
// Start an old-color worker while its request is current, then move the dialog to a new
// cross-scale request before the old result lands. Its real preview must not replace the
// current request through the loose worker-result gate.
app.session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap();
app.ui.views.get_mut(0).expect("the new document's view").zoom = 0.25;
let old_worker = old.clone();
let doc = app.session.documents()[0].doc.clone();
let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect();
let color = app.session.color.settings.clone();
let (release_old, wait_old) = std::sync::mpsc::channel();
app.filter_preview_worker
.start(old_worker.clone(), ctx.clone(), move |_| {
wait_old.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job");
let result = crate::filter_dialog::preview_document_for_target(
&doc,
old_worker.active,
&old_worker.command,
&old_worker.params,
old_worker.k,
None,
old_worker.target,
&documents,
&color,
Some(old_worker.tool_colors),
)
.map(|doc| {
let buffer = photocraft_compose::flatten(&doc);
(std::sync::Arc::new(doc), buffer)
});
crate::dialogs::filter_preview_worker::Computed { result, ms: 0.0 }
})
.expect("the worker starts");
assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "the old cached request is not current");
app.session.execute("tools.setColors", json!({"foreground": "#26bf59", "background": "#bf26a6"})).unwrap();
app.ui.views.get_mut(0).expect("the new document's view").zoom = 1.0;
app.ui.dialogs[0].fields.insert("matte".into(), json!("background"));
let mut new_late = new.clone();
new_late.params.as_object_mut().unwrap().insert("matte".into(), json!("background"));
assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "the current request has no result while the old worker runs");
release_old.send(()).expect("released");
drive_until(&mut app, &ctx, "the stale old-color worker to finish", |a| {
if let Some(shown) = &a.filter_preview {
assert_eq!(shown.key.tool_colors, new.tool_colors, "the stale old-color worker result was not painted");
assert_ne!(shown.key.k, old.k, "the stale old-scale worker result was not painted");
}
a.filter_preview.as_ref().is_some_and(|p| p.key == new_late && p.result.is_some()) && !a.filter_preview_worker.busy()
});
assert_eq!(app.filter_preview.as_ref().expect("the current request").key, new_late);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_preview_computed_mid_drag_reaches_the_canvas_and_then_converges() {
@@ -502,6 +668,7 @@ fn a_mid_drag_empty_result_leaves_the_preview_alone() {
command: "filter.blur.gaussianBlur".into(),
params: json!({"radius": moved}),
k: 1,
tool_colors: (app.session.tools.foreground, app.session.tools.background),
};
let (release_empty, wait) = std::sync::mpsc::channel::<()>();
app.filter_preview_worker
@@ -1409,14 +1576,11 @@ fn clone_overlay_is_clipped_to_a_shaped_tip() {
}
#[test]
fn wayland_start_screen_hint_does_not_claim_file_drop_works() {
fn wayland_start_screen_hint_offers_file_drop() {
let x11 = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
let wayland = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { is_wayland: true, ..Default::default() });
assert!(start_screen_drop_hint(&x11).starts_with("Drop"));
// Pasting a copied image file works on Wayland (#338): the hint says how.
let hint = start_screen_drop_hint(&wayland);
assert!(!hint.contains("Drop"), "{hint}");
assert!(hint.ends_with(&format!("paste a copied image with {}.", crate::notices::paste_hint(&wayland))), "{hint}");
assert!(start_screen_drop_hint(&wayland).starts_with("Drop"));
}
/// A tiling window manager can hand PhotoCraft a canvas narrower than the Home card (460
+46 -39
View File
@@ -1,6 +1,6 @@
use super::selection::floating_outline;
use super::view_xform::ViewXform;
use super::{Color32, LayerContent, PhotocraftApp, Pos2, Rect, Stroke, Tool, Vec2, pos2, vec2};
use super::{Color32, LayerContent, PhotocraftApp, Pos2, Rect, Stroke, Tool, Vec2, vec2};
/// View › Show › Layer Edges: the colour of the active layer's outline.
pub(crate) const LAYER_EDGES: Color32 = Color32::from_rgb(0x2d, 0x8c, 0xeb);
@@ -75,50 +75,53 @@ pub(super) fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Op
Some(Rect::from_two_pos(xf.to_screen(b.x0 as f32, b.y0 as f32), xf.to_screen(b.x1 as f32, b.y1 as f32)))
}
/// The Move tool shows transform handles even before a Free Transform session exists.
/// Use the same hit areas for pointer-down and hover, so a control never behaves like
/// resize/rotate while showing the ordinary four-arrow Move cursor (#2871).
/// Express the unopened screen rectangle in the same corner order as a transform quad.
fn controls_quad(r: Rect) -> [[f64; 2]; 4] {
[r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|p| [f64::from(p.x), f64::from(p.y)])
}
/// Classify screen coordinates with the fixed screen-space tolerance, without a pivot.
fn controls_zone(r: Rect, p: Pos2) -> crate::transform_tool::Hit {
crate::state::TransformSession::box_hit(&controls_quad(r), [f64::from(p.x), f64::from(p.y)], crate::transform_tool::HANDLE_PX)
}
/// Share the open session's screen-sized zones before the first interaction (#11097).
pub(super) fn transform_controls_cursor(r: Rect, p: Pos2) -> Option<egui::CursorIcon> {
let handles = [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()];
let grab = crate::transform_tool::HANDLE_PX as f32;
for (i, handle) in handles.into_iter().enumerate() {
if handle.distance(p) <= grab {
return Some(match i {
0 | 4 => egui::CursorIcon::ResizeNwSe,
2 | 6 => egui::CursorIcon::ResizeNeSw,
1 | 5 => egui::CursorIcon::ResizeVertical,
_ => egui::CursorIcon::ResizeHorizontal,
});
}
}
// The rotation band: the pointer gives way to the curved rotate arrow (`transform_controls_turn`).
in_rotation_band(r, p).then_some(egui::CursorIcon::None)
}
fn in_rotation_band(r: Rect, p: Pos2) -> bool {
r.expand(18.0).contains(p) && !r.expand(5.0).contains(p)
}
/// In the rotation band just outside the Move tool's transform controls, the screen direction the
/// curved rotate arrow bends round: into the box along the nearest corner's bisector, as Free
/// Transform draws it (#4658). Before, the band showed a plain alias pointer, so nothing said a
/// drag there rotates.
pub(super) fn transform_controls_turn(r: Rect, p: Pos2) -> Option<Vec2> {
if !in_rotation_band(r, p)
|| [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()]
.into_iter()
.any(|h| h.distance(p) <= crate::transform_tool::HANDLE_PX as f32)
{
if !p.is_finite() {
return None;
}
let corner = pos2(if p.x < r.center().x { r.left() } else { r.right() }, if p.y < r.center().y { r.top() } else { r.bottom() });
Some(vec2((r.center().x - corner.x).signum(), (r.center().y - corner.y).signum()).normalized() * 16.0)
use crate::transform_tool::Hit;
Some(match controls_zone(r, p) {
Hit::Corner(0 | 2) => egui::CursorIcon::ResizeNwSe,
Hit::Corner(_) => egui::CursorIcon::ResizeNeSw,
Hit::Edge(0 | 2) => egui::CursorIcon::ResizeVertical,
Hit::Edge(_) => egui::CursorIcon::ResizeHorizontal,
Hit::Outside => egui::CursorIcon::None,
Hit::Inside | Hit::Pivot => egui::CursorIcon::Default,
})
}
/// A visible handle starts scaling; the narrow band just outside the box starts rotation.
/// The interior stays the normal Move-tool drag target.
/// At any distance outside the controls, the same edge/corner direction as Free Transform.
pub(super) fn transform_controls_turn(r: Rect, p: Pos2) -> Option<Vec2> {
if controls_zone(r, p) != crate::transform_tool::Hit::Outside {
return None;
}
let k = crate::state::TransformSession::box_turn_direction(&controls_quad(r), [f64::from(p.x), f64::from(p.y)])?;
Some(vec2(k[0] as f32, k[1] as f32) * 16.0)
}
/// Resize from the shared handle zones and keep Move's existing rotation press band.
/// Outside presses beyond that band still reach the Move tool, even where hover paints a turn arc.
pub(super) fn transform_controls_hit(r: Rect, p: Pos2) -> bool {
transform_controls_cursor(r, p).is_some()
if !p.is_finite() {
return false;
}
use crate::transform_tool::Hit;
match controls_zone(r, p) {
Hit::Corner(_) | Hit::Edge(_) => true,
Hit::Outside => r.expand(18.0).contains(p) && !r.expand(5.0).contains(p),
Hit::Inside | Hit::Pivot => false,
}
}
/// The reference application's alert when a Move-tool transform control is dragged on a frame
@@ -177,3 +180,7 @@ pub(super) fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::P
painter.rect_stroke(h, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside);
}
}
#[cfg(test)]
#[path = "../transform_hit_zone_tests.rs"]
mod hit_zone_tests;
@@ -328,21 +328,20 @@ fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interacti
(r.center_bottom(), egui::CursorIcon::ResizeVertical),
(r.right_center(), egui::CursorIcon::ResizeHorizontal),
(r.left_center(), egui::CursorIcon::ResizeHorizontal),
// Between handles: the rotation band (a point above the top-centre handle is that handle),
// where the curved rotate arrow replaces the pointer (#4658).
// Just beyond the outward edge band, the curved rotate arrow replaces the pointer (#4658).
(pos2(r.left() + r.width() * 0.25, r.top() - 12.0), egui::CursorIcon::None),
] {
assert_eq!(transform_controls_cursor(r, p), Some(expected), "hover at {p:?}");
assert!(transform_controls_hit(r, p), "same region must start a transform");
}
assert_eq!(transform_controls_cursor(r, r.center()), None, "interior stays Move");
assert_eq!(transform_controls_cursor(r, pos2(r.center().x, r.top() - 30.0)), None);
// The rotate arrow bends round the nearest corner, pointing into the box; handles and the
// interior have none.
let into = |p: Pos2| transform_controls_turn(r, p).map(|v| (v.x.signum(), v.y.signum()));
assert_eq!(into(pos2(r.left() + r.width() * 0.25, r.top() - 12.0)), Some((1.0, 1.0)), "top left");
assert_eq!(into(pos2(r.right() + 12.0, r.bottom() - r.height() * 0.25)), Some((-1.0, -1.0)), "bottom right");
assert_eq!(into(pos2(r.left() - 12.0, r.bottom() + 12.0)), Some((1.0, -1.0)), "beyond the bottom-left corner");
assert_eq!(transform_controls_cursor(r, r.center()), Some(egui::CursorIcon::Default), "interior uses the default arrow");
assert_eq!(transform_controls_cursor(r, pos2(r.center().x, r.top() - 30.0)), Some(egui::CursorIcon::None));
// The rotate arrow points into the nearest edge or corner. Handles and the interior have none.
let into = |p: Pos2| transform_controls_turn(r, p);
assert_eq!(into(pos2(r.left() + r.width() * 0.25, r.top() - 12.0)), Some(vec2(0.0, 16.0)), "top edge");
assert_eq!(into(pos2(r.right() + 12.0, r.bottom() - r.height() * 0.25)), Some(vec2(-16.0, 0.0)), "right edge");
let corner = into(pos2(r.left() - 12.0, r.bottom() + 12.0)).unwrap();
assert!(corner.x > 0.0 && corner.y < 0.0, "beyond the bottom-left corner");
assert_eq!(into(r.left_top()), None);
assert_eq!(into(r.center()), None);
@@ -351,7 +350,7 @@ fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interacti
let next = transform_controls_rect(&app, &xf).expect("new active shape controls");
assert_ne!(r, next);
assert_eq!(transform_controls_cursor(next, next.right_bottom()), Some(egui::CursorIcon::ResizeNwSe));
assert_eq!(transform_controls_cursor(next, next.center()), None);
assert_eq!(transform_controls_cursor(next, next.center()), Some(egui::CursorIcon::Default));
}
#[test]
+51 -2
View File
@@ -17,6 +17,8 @@ use crate::tone::{self, HistSource};
const PREFIX: &str = "image.adjustments.";
const CURVE_PICKER: &str = "__curvePicker";
const CURVE_PICKER_BASE: &str = "__curvePickerBase";
/// Set once a Photo Filter dialog has drawn: its editor memory was refreshed for this opening.
const PHOTO_FILTER_FRESH: &str = "__photoFilterFresh";
fn picker(value: Option<&Value>) -> Option<photocraft_engine::adjust_params::CurvesEyedropper> {
use photocraft_engine::adjust_params::CurvesEyedropper;
@@ -282,8 +284,33 @@ pub fn reset(app: &PhotocraftApp, ctx: &egui::Context, fields: &mut Map<String,
}
}
/// Opens the dialog for `command` with the kind's neutral settings.
/// Settings an adjustment dialog keeps from its last OK although it opens at its neutral ones:
/// the reference application's Photo Filter reopens at Warming Filter (85) and 25 % every time,
/// but with Preserve Luminosity as last confirmed (measured 2026-11-08, #9879). ⌥ still reopens
/// at all the last settings ([`open_last`]).
const KEEPS_LAST: &[(&str, &str)] = &[("photoFilter", "preserveLuminosity")];
/// Opens the dialog for `command` at the kind's neutral settings, except the [`KEEPS_LAST`] ones,
/// which keep their last confirmed value.
pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
let id = open_neutral(app, command)?;
let kind = command.strip_prefix(PREFIX).unwrap_or_default();
let kept: Vec<(String, Value)> = match app.session.prefs().dialogs.get(command) {
Some(last) => KEEPS_LAST
.iter()
.filter(|(k, _)| *k == kind)
.filter_map(|(_, key)| last.get(*key).filter(|v| v.is_boolean()).map(|v| ((*key).to_owned(), v.clone())))
.collect(),
None => Vec::new(),
};
if let Some(d) = app.ui.dialog_mut(id) {
d.fields.extend(kept);
}
Some(id)
}
/// Opens the dialog for `command` with the kind's neutral settings.
pub fn open_neutral(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k))?;
let spec = photocraft_engine::commands::find(command)?;
let mode = curve_mode(app, kind);
@@ -342,7 +369,7 @@ fn combined_lab_target(fields: &Map<String, Value>) -> bool {
/// adjustment's shortcut, ⌥⌘L / ⌥⌘M, #8900), or at the neutral ones when there are none or they
/// don't fit the current colour mode.
pub fn open_last(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
let id = open(app, command)?;
let id = open_neutral(app, command)?;
let kind = command.strip_prefix(PREFIX).unwrap_or_default();
let mode = curve_mode(app, kind);
let Some(last) = app.session.prefs().dialogs.get(command).cloned() else { return Some(id) };
@@ -372,6 +399,22 @@ pub fn open_last(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
Some(id)
}
/// `params` of the adjustment `command` with the keys the dialog would otherwise fill in wrongly:
/// a recorded Photo Filter that names only its `filter` gets that preset's `color`, not the
/// dialog's neutral one. Every recorded value is kept as it was (a round trip through the engine
/// would rewrite them: float colours as hex, a pencil curve smoothed again). `None` when nothing
/// needs adding, or for params the engine rejects.
pub(crate) fn complete_params(app: &PhotocraftApp, command: &str, params: &Value) -> Option<Value> {
let kind = command.strip_prefix(PREFIX).filter(|k| *k == "photoFilter")?;
// A `null` colour reads as none, as the engine reads it.
let recorded = params.as_object().filter(|p| p.contains_key("filter") && p.get("color").is_none_or(Value::is_null))?;
let adjustment = photocraft_engine::adjust_params::from_params(kind, params, None, curve_mode(app, kind)).ok()?;
let color = photocraft_engine::adjust_params::to_params(&adjustment).get("color").cloned()?;
let mut done = recorded.clone();
done.insert("color".into(), color);
Some(Value::Object(done))
}
/// Remember an adjustment dialog's settings after a successful OK, for [`open_last`]. Editing a
/// smart filter's settings is not a use of the dialog's own (as `filter_dialog::remember`).
pub(crate) fn remember(app: &mut PhotocraftApp, fields: &Map<String, Value>) {
@@ -430,6 +473,12 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String,
let mask = fields.get("target").and_then(Value::as_str) == Some("mask");
let filter_mask = fields.get("target").and_then(Value::as_str) == Some("filterMask");
let mode = curve_mode_for_fields(app, &kind, fields);
// Each opening starts from the settings it opened at: Photo Filter's Filter / Color choice
// follows its colour, whatever a cancelled opening left in the editor memory.
if kind == "photoFilter" && !fields.contains_key(PHOTO_FILTER_FRESH) {
adjust_editors::forget_photo_filter_mode(ui.ctx(), dialog_mem(&kind));
fields.insert(PHOTO_FILTER_FRESH.into(), json!(false));
}
if matches!(kind.as_str(), "levels" | "curves") {
picker_controls(ui, fields, mode);
ui.add_space(4.0);
@@ -939,6 +939,118 @@ fn curves_on_a_targeted_filter_mask_is_a_gray_plane() {
assert_eq!(curve_mode(&app, "curves"), photocraft_doc::ColorMode::Grayscale);
}
/// #9879: the reference application's Photo Filter reopens at Warming Filter (85) and 25 % after
/// any OK, but keeps Preserve Luminosity as last confirmed (measured 2026-11-08); ⌥ reopens at all
/// the last settings; Levels still opens at its neutral settings, and a smart filter's dialog
/// never takes the last ones.
#[test]
fn photo_filter_keeps_only_preserve_luminosity_from_its_last_ok() {
let mut app = app_with_image();
let cmd = "image.adjustments.photoFilter";
let first = open_neutral(&mut app, cmd).unwrap();
let neutral = crate::filter_dialog::params_of(&app.ui.dialog_mut(first).unwrap().fields.clone());
app.ui.dialogs.clear();
let id = open(&mut app, cmd).unwrap();
let mut sample = photocraft_engine::adjust_params::to_params(
&photocraft_engine::adjust_params::from_params("photoFilter", &sample_params("photoFilter"), None, photocraft_doc::ColorMode::Rgb).unwrap(),
);
// Preserve Luminosity is on by default; the sample turns it off with the other settings.
assert_eq!(neutral["preserveLuminosity"], json!(true));
sample["preserveLuminosity"] = json!(false);
assert_ne!(sample["color"], neutral["color"], "the sample differs from the neutral settings");
assert_ne!(sample["density"], neutral["density"]);
if let Value::Object(p) = sample.clone() {
app.ui.dialog_mut(id).unwrap().fields.extend(p);
}
crate::dialogs::confirm(&mut app, id).unwrap();
let again = open(&mut app, cmd).unwrap();
let reopened = crate::filter_dialog::params_of(&app.ui.dialog_mut(again).unwrap().fields.clone());
assert_eq!(reopened["preserveLuminosity"], json!(false), "Preserve Luminosity off is kept");
assert_eq!(reopened["color"], neutral["color"], "the colour is the neutral one again");
assert_eq!(reopened["density"], neutral["density"], "and so is the density");
// Turned on again and confirmed, it reopens on.
app.ui.dialog_mut(again).unwrap().fields.insert("preserveLuminosity".into(), json!(true));
crate::dialogs::confirm(&mut app, again).unwrap();
let again = open(&mut app, cmd).unwrap();
assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(again).unwrap().fields.clone()), neutral, "all neutral again");
app.ui.dialogs.clear();
// ⌥ reopens at every last setting (#8900).
let id = open(&mut app, cmd).unwrap();
if let Value::Object(p) = sample.clone() {
app.ui.dialog_mut(id).unwrap().fields.extend(p);
}
crate::dialogs::confirm(&mut app, id).unwrap();
let alt = open_last(&mut app, cmd).unwrap();
assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(alt).unwrap().fields.clone()), sample, "⌥ reopens at the last settings");
app.ui.dialogs.clear();
let smart = open_neutral(&mut app, cmd).unwrap();
assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(smart).unwrap().fields.clone()), neutral, "open_neutral ignores them");
app.ui.dialogs.clear();
let levels = "image.adjustments.levels";
let id = open(&mut app, levels).unwrap();
app.ui.dialog_mut(id).unwrap().fields.insert("inBlack".into(), json!(30));
crate::dialogs::confirm(&mut app, id).unwrap();
let again = open(&mut app, levels).unwrap();
let defaults =
photocraft_engine::adjust_params::to_params(&photocraft_engine::adjust_params::default_for("levels", photocraft_doc::ColorMode::Rgb).unwrap());
assert_eq!(app.ui.dialog_mut(again).unwrap().fields["inBlack"], defaults["inBlack"], "Levels opens neutral without ⌥");
}
/// #9879: Photo Filter reopens with Filter chosen for its neutral preset colour, even after an OK
/// with Color chosen (the choice lives in the editor memory), as the reference application does;
/// ⌥ reopens a custom colour with Color chosen, also after an opening that chose Filter and was
/// cancelled.
#[test]
fn photo_filter_reopens_with_the_choice_its_colour_implies() {
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image());
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
let cmd = "image.adjustments.photoFilter";
let mode = dialog_mem("photoFilter").with(crate::adjust_editors::PHOTO_FILTER_MODE);
let id = open(h.state_mut(), cmd).unwrap();
h.run_steps(2);
let neutral = h.state_mut().ui.dialog_mut(id).unwrap().fields["color"].clone();
// Color chosen (what clicking its radio stores), a custom colour, OK.
h.ctx.data_mut(|d| d.insert_temp(mode, true));
h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("#123456"));
h.run_steps(2);
crate::dialogs::confirm(h.state_mut(), id).unwrap();
h.run_steps(1);
let id = open(h.state_mut(), cmd).unwrap();
h.run_steps(2);
assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["color"], neutral, "the neutral colour again");
assert_eq!(h.ctx.data(|d| d.get_temp::<bool>(mode)), Some(false), "Filter is chosen for the preset colour");
// That opening is cancelled with Filter chosen; ⌥ brings the custom colour back with Color.
h.state_mut().ui.close_dialog(id);
h.run_steps(1);
let id = open_last(h.state_mut(), cmd).unwrap();
h.run_steps(2);
assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["color"], json!("#123456"));
assert_eq!(h.ctx.data(|d| d.get_temp::<bool>(mode)), Some(true), "Color is chosen for the custom colour");
}
/// #9879 review: a recorded Photo Filter that names only its preset completes to that preset's
/// colour, so editing it as a smart filter doesn't swap in the dialog's neutral colour. Recorded
/// values are kept as they were, and nothing else is rewritten.
#[test]
fn recorded_photo_filter_settings_complete_to_their_preset_colour() {
let app = app_with_image();
let pf = "image.adjustments.photoFilter";
let done = complete_params(&app, pf, &json!({"filter": "cooling80", "density": 60, "extra": [1]})).unwrap();
assert_eq!(done, json!({"filter": "cooling80", "density": 60, "extra": [1], "color": "#006dff"}), "only the colour is added");
// A recorded colour (here a float triple the engine would rewrite as hex) is left alone.
assert!(complete_params(&app, pf, &json!({"filter": "cooling80", "color": [0.5, 0.0, 0.0]})).is_none());
let null = complete_params(&app, pf, &json!({"filter": "cooling80", "color": null})).unwrap();
assert_eq!(null["color"], json!("#006dff"), "a null colour completes from the preset, as the engine reads it");
assert!(complete_params(&app, pf, &json!({"density": 60})).is_none(), "no preset to take a colour from");
assert!(complete_params(&app, pf, &json!({"filter": "nope"})).is_none(), "rejected params");
// Other adjustments keep their recorded values exactly (a pencil curve isn't smoothed again).
let curves = json!({"pencil": true, "smooth": 2, "rgb": [0, 255]});
assert!(complete_params(&app, "image.adjustments.curves", &curves).is_none());
assert!(complete_params(&app, "filter.blur.gaussian", &json!({"radius": 2})).is_none(), "not an adjustment");
}
#[test]
fn captured_filter_mask_curves_stay_gray_after_selecting_native_channels() {
let mut app = app_with_image();
@@ -31,6 +31,7 @@ mod levels;
mod selective_color;
mod session;
pub(crate) use basic::PHOTO_FILTER_MODE;
#[cfg(test)]
pub(crate) use basic::row_value;
#[cfg(test)]
@@ -75,6 +76,12 @@ pub fn has_editor(kind: &str) -> bool {
KINDS.contains(&kind)
}
/// Forget Photo Filter's Filter / Color choice in the editor memory `mem`, so the editor derives it
/// from the colour again: a choice changed and then cancelled must not outlive the dialog (#9879).
pub(crate) fn forget_photo_filter_mode(ctx: &egui::Context, mem: egui::Id) {
ctx.data_mut(|d| d.remove::<bool>(mem.with(PHOTO_FILTER_MODE)));
}
/// Kinds that draw a histogram behind their controls.
pub fn needs_histogram(kind: &str) -> bool {
matches!(kind, "levels" | "curves" | "threshold")
@@ -194,12 +194,16 @@ pub(super) fn black_white(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Ed
// ---------------------------------------------------------------------------------------------
// Photo Filter
/// The editor memory key of Photo Filter's Filter / Color choice (unset: Color for a colour that
/// is no preset).
pub(crate) const PHOTO_FILTER_MODE: &str = "pf-mode";
pub(super) fn photo_filter(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
let mut e = Edit::default();
let mut c = rgb_of(v, "color", [236.0 / 255.0, 138.0 / 255.0, 0.0]);
let hex = adjust_params::hex(c);
let preset = PHOTO_FILTERS.iter().find(|f| adjust_params::hex(f.2.map(|x| f32::from(x) / 255.0)) == hex).map(|f| f.0);
let mode_id = cx.mem.with("pf-mode");
let mode_id = cx.mem.with(PHOTO_FILTER_MODE);
let mut use_color: bool = ui.data(|d| d.get_temp(mode_id)).unwrap_or(preset.is_none());
ui.horizontal(|ui| {
if ui.radio(!use_color, tl!("Filter:")).clicked() {
@@ -661,6 +661,57 @@ fn gradient_map_strip_adds_selects_and_removes_stops_without_deleting_the_last_p
assert_eq!(layer(&h).1, original, "keep two stops");
}
/// #10742: a Gradient Map stop dragged down off the bar is removed on release (one history step);
/// while it is off the bar the live preview already leaves it out, and dragging it back onto the
/// bar before release puts it back. The last two stops can't be dragged off.
#[test]
fn gradient_map_stop_dragged_down_off_the_bar_is_removed_and_dragging_back_cancels() {
let mut h = app_harness("gradientMap", "rgb", 8);
let (id, _) = layer(&h);
h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "stops": [[0, "#000000"], [0.5, "#ff0000"], [1, "#ffffff"]]})).unwrap();
h.run_steps(3);
let three = layer(&h).1;
let before_cancel = h.state().session.active().unwrap().history.past_len();
let live_stops = |h: &Harness<'_, PhotocraftApp>| h.state().live_adjust.as_ref().and_then(|(_, v)| v["stops"].as_array().map(Vec::len));
// Off and back: nothing removed.
let start = map_handle(&h, 0.5);
let away = start + vec2(0.0, 30.0);
h.hover_at(start);
h.run_steps(1);
h.drag_at(start);
h.run_steps(1);
h.hover_at(start + vec2(0.0, 15.0));
h.run_steps(1);
h.hover_at(away);
h.run_steps(1);
assert_eq!(live_stops(&h), Some(2), "off the bar the preview leaves the stop out");
h.hover_at(start);
h.run_steps(1);
assert_eq!(live_stops(&h), Some(3), "back on the bar the stop returns");
h.drop_at(start);
h.run_steps(3);
assert_eq!(map_stops(&layer(&h).1), map_stops(&three), "dragging back cancels the removal");
assert_eq!(h.state().session.active().unwrap().history.past_len(), before_cancel, "a cancelled drag adds no history step");
// Off and released: removed in one step.
let steps = h.state().session.active().unwrap().history.past_len();
drag(&mut h, start, away);
assert_eq!(map_stops(&layer(&h).1), vec![(0.0, [0, 0, 0]), (1.0, [255, 255, 255])]);
assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1);
assert!(h.state().live_adjust.is_none());
h.state_mut().run("edit.undo", json!({})).unwrap();
h.run_steps(3);
assert_eq!(layer(&h).1, three);
h.state_mut().run("edit.redo", json!({})).unwrap();
h.run_steps(3);
// Two stops stay.
let two = layer(&h).1;
for at in [0.0, 1.0] {
let from = map_handle(&h, at);
drag(&mut h, from, from + vec2(0.0, 40.0));
assert_eq!(map_stops(&layer(&h).1), map_stops(&two), "two stops always remain");
}
}
#[test]
fn gradient_map_drag_clamps_at_the_endpoints_and_reverse_keeps_stop_coordinates() {
let mut h = app_harness("gradientMap", "rgb", 8);
@@ -271,6 +271,10 @@ fn set_field(f: &mut Map<String, Value>, field: &str, value: Value) -> Result<()
/// Opens the Color Picker dialog `id`'s body asked for ([`request`], [`request_field`]), on its
/// colour: OK sets that field of the dialog (not the foreground), Cancel leaves it as it was.
///
/// A dialog can provide `__pickColorDefault` when its field is a non-colour choice that has not
/// yet been replaced by the picked colour. The temporary default seeds the picker without
/// changing the parent field; it is removed before the picker opens.
pub fn open_requested(app: &mut PhotocraftApp, id: u64) {
let Some(d) = app.ui.dialog_mut(id) else { return };
let (title, field) = match d.fields.remove(REQUEST) {
@@ -282,7 +286,11 @@ pub fn open_requested(app: &mut PhotocraftApp, id: u64) {
}
_ => return,
};
let rgb = field_value(&d.fields, &field).and_then(parse_hex).unwrap_or([0.0; 3]);
let rgb = field_value(&d.fields, &field)
.and_then(parse_hex)
.or_else(|| d.fields.get("__pickColorDefault").and_then(Value::as_str).and_then(parse_hex))
.unwrap_or([0.0; 3]);
d.fields.remove("__pickColorDefault");
open_for_field(app, &title, rgb, id, &field);
}
+4 -4
View File
@@ -209,7 +209,7 @@ pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result<Value
let docs: Vec<_> =
layers.into_iter().map(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, id).map_err(|e| e.to_string())).collect::<Result<_, _>>()?;
let suggested = format!("{}.png", export_name(&st.doc.name));
app.pick_save(&suggested, move |app, path| {
app.pick_export(&suggested, move |app, path| {
if !path.to_ascii_lowercase().ends_with(".png") {
return Err("Quick Export as PNG writes .png files".into());
}
@@ -1050,7 +1050,7 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
let ext = s_fmt(f);
let suggested = format!("{stem}.{ext}");
let f = f.clone();
app.pick_save(&suggested, move |app, path| {
app.pick_export(&suggested, move |app, path| {
let r = write_export(app, &doc, &f, &path, &source_profile)?;
// An action being recorded keeps a whole-document export with its destination and
// settings (#7207). A layer's export isn't recorded: its layer is this document's.
@@ -1112,7 +1112,7 @@ fn confirm_layers(app: &mut PhotocraftApp, f: &Map<String, Value>, ids: &[photoc
let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a);
let suggested = format!("{}.{}", export_name(stem), s_fmt(f));
let (f, settings) = (f.clone(), settings(f));
app.pick_save(&suggested, move |app, path| {
app.pick_export(&suggested, move |app, path| {
let mut exported = Vec::new();
for (doc, path) in docs.iter().zip(batch_paths(&path, &docs)) {
let out = export_document(doc, &f, None, &source_profile)?;
@@ -1151,7 +1151,7 @@ pub fn quick_export_png(app: &mut PhotocraftApp) -> Result<Value, String> {
let st = app.session.active().ok_or("no document")?;
let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a);
let (suggested, doc) = (format!("{stem}.{fmt}"), st.doc.id);
return app.pick_save(&suggested, move |app, path| {
return app.pick_export(&suggested, move |app, path| {
app.refocus(doc)?;
quick_export(app, json!({"path": path}))
});
+1 -1
View File
@@ -584,7 +584,7 @@ pub(super) fn web_confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Re
let st = WebSettings::from_params(&p, "file.export.saveForWebLegacy").map_err(|e| e.to_string())?;
let base = photocraft_doc::slices::base_name(&doc);
let suggested = if has_slices && html { format!("{base}.html") } else { format!("{base}.{}", st.format.ext()) };
app.pick_save(&suggested, move |app, path| {
app.pick_export(&suggested, move |app, path| {
app.refocus(doc.id)?;
if has_slices {
let dir = path.rfind(['/', '\\']).map(|i| path[..i].to_string()).unwrap_or_else(|| ".".into());
+123 -1
View File
@@ -6,6 +6,8 @@
use std::sync::Arc;
use photocraft_cms::{ColorSpace, TransformOptions};
use photocraft_color::ColorMode;
use photocraft_doc::Document;
use photocraft_engine::color_cmds::ColorSettings;
use photocraft_engine::installed_profiles::InstalledProfile;
@@ -431,6 +433,9 @@ fn default_value(app: &PhotocraftApp, command: &str, p: &Param) -> Option<Value>
/// Command-specific open defaults (ruler straighten, warp from layer, …), not remembered prefs.
fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map<String, Value>) {
if command == "image.mode.indexedColor" {
indexed_matte_defaults(app, fields);
}
if command == "image.rotation.arbitrary" {
straighten_defaults(app, fields);
}
@@ -859,6 +864,109 @@ fn replace_color_result(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
}
}
const INDEXED_MATTE_FOREGROUND: &str = "__indexedMatteForeground";
const INDEXED_MATTE_BACKGROUND: &str = "__indexedMatteBackground";
const INDEXED_MATTE_COLOR_ERROR: &str = "__indexedMatteColorError";
/// Resolve a tool colour into the encoded samples used by Indexed Color's matte.
///
/// The picker and command fields carry document RGB coordinates. Tool swatches are
/// working-RGB coordinates, so only the named tool choices need this conversion here.
fn indexed_matte_document_color(app: &PhotocraftApp, doc: &Document, color: [f32; 4]) -> Result<[f32; 3], String> {
let destination = match photocraft_engine::color_cmds::mode_space(doc.mode) {
ColorSpace::Rgb | ColorSpace::Gray => photocraft_engine::color_cmds::document_profile(doc),
_ => photocraft_engine::color_cmds::composite_profile(doc),
};
let source = app.session.color.working(ColorMode::Rgb);
let options = TransformOptions { intent: app.session.color.settings.intent(), bpc: app.session.color.settings.bpc, ..Default::default() };
let transform = photocraft_cms::transform::cached(&source, &destination, options).map_err(|e| e.to_string())?;
let mut output = [0.0; 16];
transform.eval(&color[..3], &mut output);
let rgb = if destination.color_space == ColorSpace::Gray { [output[0]; 3] } else { [output[0], output[1], output[2]] };
if rgb.iter().any(|v| !v.is_finite()) {
return Err("cannot convert matte colour to finite document samples".into());
}
Ok(rgb.map(|v| v.clamp(0.0, 1.0)))
}
fn indexed_matte_defaults(app: &PhotocraftApp, fields: &mut Map<String, Value>) {
let Some(doc) = app.session.active().map(|state| state.doc.as_ref()) else { return };
for (key, color) in [(INDEXED_MATTE_FOREGROUND, app.session.tools.foreground), (INDEXED_MATTE_BACKGROUND, app.session.tools.background)] {
match indexed_matte_document_color(app, doc, color) {
Ok(rgb) => {
fields.insert(key.into(), json!(crate::color_picker_ui::hex(rgb)));
}
Err(error) => {
fields.insert(INDEXED_MATTE_COLOR_ERROR.into(), json!(error));
}
}
}
}
fn indexed_matte_seed(fields: &Map<String, Value>, value: &str) -> Option<[f32; 3]> {
match value {
"foreground" => fields.get(INDEXED_MATTE_FOREGROUND).and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex),
"background" => fields.get(INDEXED_MATTE_BACKGROUND).and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex),
"black" => Some([0.0; 3]),
"gray" => Some([128.0 / 255.0; 3]),
"netscapeGray" => Some([192.0 / 255.0; 3]),
"none" | "white" => Some([1.0; 3]),
_ => crate::color_picker_ui::parse_hex(value),
}
}
fn indexed_matte_row(ui: &mut egui::Ui, fields: &mut Map<String, Value>) {
let value = fields.get("matte").and_then(Value::as_str).unwrap_or("none");
let mut choice = if value.starts_with('#') { "custom" } else { value };
let color = indexed_matte_seed(fields, value);
let mut changed = false;
let mut pick = false;
ui.horizontal(|ui| {
ui.label(egui::RichText::new(tl!("Matte")).color(Tokens::get(ui.ctx()).text_dim));
changed = crate::widgets::dropdown(
ui,
"indexed-matte",
"Matte",
&mut choice,
&[
("none", "None"),
("foreground", "Foreground Color"),
("background", "Background Color"),
("white", "White"),
("black", "Black"),
("gray", "50% Gray"),
("netscapeGray", tl!("Netscape Gray")),
("custom", "Other…"),
],
170.0,
);
if choice == "custom"
&& let Some(color) = color
{
let bytes = color.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
pick = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), tl!("Matte")).clicked();
}
});
if color.is_none()
&& let Some(error) = fields.get(INDEXED_MATTE_COLOR_ERROR).and_then(Value::as_str)
{
ui.colored_label(Tokens::get(ui.ctx()).danger, error);
}
let custom = choice == "custom";
if changed {
if custom && let Some(color) = color {
// Keep the previous matte until the picker confirms; the picker uses this only as
// its initial document-encoded colour when switching from a named matte or None.
fields.insert("__pickColorDefault".into(), json!(crate::color_picker_ui::hex(color)));
} else if !custom {
fields.insert("matte".into(), json!(choice.to_owned()));
}
}
if custom && color.is_some() && (changed || pick) {
crate::color_picker_ui::request_field(fields, "matte", &crate::color_picker_ui::title_for("Matte"));
}
}
/// Dialog body for filter commands.
pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
let t = Tokens::get(ui.ctx());
@@ -875,6 +983,10 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
crate::select_mask_view::controls(ui, f);
}
for p in parse_spec(&spec) {
if cmd == "image.mode.indexedColor" && p.key == "matte" {
indexed_matte_row(ui, f);
continue;
}
if zoom_center::owns(&cmd, f) && matches!(p.key.as_str(), "centerX" | "centerY") {
if p.key == "centerX" {
zoom_center::row(ui, f);
@@ -1193,6 +1305,7 @@ pub fn preview_document_with(
photocraft_engine::channel_cmds::ChannelTarget::Composite,
&[],
&ColorSettings::default(),
None,
)
}
@@ -1200,6 +1313,8 @@ pub fn preview_document_with(
/// `documents` are the open documents in session order: document params (Match Color's Source,
/// Displace's map) index into them. `color` is the app's Edit › Color Settings: Assign and Convert
/// to Profile's `working` is the working space chosen there, not the built-in default.
/// `tool_colors` carries the caller's working-space foreground/background values; standalone
/// previews without a session use the engine's default tool colors.
#[allow(clippy::too_many_arguments)]
pub(crate) fn preview_document_for_target(
doc: &Document,
@@ -1211,6 +1326,7 @@ pub(crate) fn preview_document_for_target(
target: photocraft_engine::channel_cmds::ChannelTarget,
documents: &[Arc<Document>],
color: &ColorSettings,
tool_colors: Option<([f32; 4], [f32; 4])>,
) -> Option<Document> {
if command == crate::select_mask_view::COMMAND {
return crate::select_mask_view::preview_document(doc, active, params, k, cancel);
@@ -1246,6 +1362,10 @@ pub(crate) fn preview_document_for_target(
}
let mut s = photocraft_engine::Session::new();
s.color.settings = color.clone();
if let Some((foreground, background)) = tool_colors {
s.tools.foreground = foreground;
s.tools.background = background;
}
s.set_inline_job_ctx(cancel.cloned());
let doc_id = proxy.id;
s.add_document(proxy, None);
@@ -1388,11 +1508,12 @@ pub struct FilterPreviewKey {
pub command: String,
pub params: Value,
pub k: u32,
pub tool_colors: ([f32; 4], [f32; 4]),
}
impl FilterPreviewKey {
/// Everything except the parameters: same dialog, document, revision, layer, channel target,
/// command and proxy factor.
/// command, proxy factor and tool colors.
///
/// The canvas shows whatever this preview was computed for, so a result whose parameters are
/// a few frames old still belongs on screen while a slider is moving; matching on everything
@@ -1414,6 +1535,7 @@ impl FilterPreviewKey {
&& self.active == other.active
&& self.target == other.target
&& self.command == other.command
&& self.tool_colors == other.tool_colors
}
}
@@ -90,6 +90,34 @@ fn display_names_are_not_split_like_camel_case_keys() {
assert_eq!(source_label("centerX"), "Center X");
}
#[test]
fn indexed_matte_tool_seeds_use_document_encoded_rgb() {
use photocraft_cms::Transform;
let mut session = photocraft_engine::Session::new();
session.color.settings.working_rgb = "display-p3".into();
session.execute("file.new", json!({"width": 2, "height": 2, "background": "transparent"})).unwrap();
session.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap();
let app = PhotocraftApp::new(session, crate::Services::default());
let mut fields = Map::new();
indexed_matte_defaults(&app, &mut fields);
let doc = app.session.active().unwrap().doc.clone();
let source = app.session.color.working(ColorMode::Rgb);
let destination = photocraft_engine::color_cmds::document_profile(&doc);
let transform = Transform::new(&source, &destination, app.session.color.settings.intent(), app.session.color.settings.bpc).unwrap();
for (key, input) in [(INDEXED_MATTE_FOREGROUND, [0.2, 0.4, 0.8]), (INDEXED_MATTE_BACKGROUND, [0.8, 0.4, 0.2])] {
let mut output = [0.0; 16];
transform.eval(&input, &mut output);
let expected = crate::color_picker_ui::hex([output[0], output[1], output[2]]);
assert_eq!(fields.get(key).and_then(Value::as_str), Some(expected.as_str()), "{key}");
assert_eq!(
indexed_matte_seed(&fields, if key == INDEXED_MATTE_FOREGROUND { "foreground" } else { "background" }),
crate::color_picker_ui::parse_hex(&expected)
);
}
}
/// Convert to Profile's and Proof Setup's `bpc` read "Bpc": spelled out.
#[test]
fn black_point_compensation_is_spelled_out() {
@@ -106,6 +134,7 @@ fn key() -> FilterPreviewKey {
command: "filter.blur.gaussianBlur".into(),
params: json!({"radius": 4.0}),
k: 1,
tool_colors: ([0.0, 0.0, 0.0, 1.0], [1.0; 4]),
}
}
@@ -128,6 +157,8 @@ fn same_target_ignores_parameters_but_nothing_else() {
|k: &mut FilterPreviewKey| k.target = photocraft_engine::channel_cmds::ChannelTarget::LayerMask,
|k: &mut FilterPreviewKey| k.command = "filter.blur.motionBlur".into(),
|k: &mut FilterPreviewKey| k.k = 2,
|k: &mut FilterPreviewKey| k.tool_colors.0 = [0.2, 0.4, 0.8, 1.0],
|k: &mut FilterPreviewKey| k.tool_colors.1 = [0.8, 0.4, 0.2, 1.0],
] {
let mut other = base.clone();
break_it(&mut other);
@@ -653,6 +684,7 @@ fn smart_displace_preview_uses_the_map_document() {
photocraft_engine::channel_cmds::ChannelTarget::Composite,
&documents,
&ColorSettings::default(),
None,
)
.unwrap_or_else(|| panic!("map {map}: no preview"));
assert!(photocraft_compose::render(&preview, doc.bounds()).px == want, "map {map}: the preview differs from what OK applies");
@@ -695,6 +727,7 @@ fn match_color_preview_uses_the_source_document() {
photocraft_engine::channel_cmds::ChannelTarget::Composite,
&documents,
&ColorSettings::default(),
None,
)
.unwrap_or_else(|| panic!("{label}: no preview"));
let got = preview.layers[0].surface().unwrap().pixel(24, 16);
@@ -711,6 +744,7 @@ fn match_color_preview_uses_the_source_document() {
photocraft_engine::channel_cmds::ChannelTarget::Composite,
&documents,
&ColorSettings::default(),
None,
)
.unwrap();
let px = preview.layers[0].surface().unwrap().pixel(12, 8);
@@ -1716,3 +1750,80 @@ fn replace_color_localized_color_clusters() {
assert!(px(2)[1] > 0.5, "near the point: shifted to green {:?}", px(2));
assert!(px(38)[0] > 0.9 && px(38)[1] < 0.1, "far away: still red {:?}", px(38));
}
#[test]
fn indexed_matte_dropdown_and_picker_change_the_applied_edge_color() {
use egui::accesskit::Role;
use egui_kittest::{Harness, kittest::Queryable};
for (choice, matte) in [("Black", [0.0, 0.0, 0.0]), ("50% Gray", [128.0 / 255.0; 3]), ("Netscape Gray", [192.0 / 255.0; 3]), ("Other…", [0.0, 0.0, 1.0])]
{
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width": 2, "height": 1, "depth": 32, "background": "transparent"})).unwrap();
session
.edit("fixture", |doc, active| {
let bounds = doc.bounds();
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().write_region(bounds, &[1.0, 0.0, 0.0, 0.75, 0.0, 0.0, 0.0, 0.0]);
Ok(())
})
.unwrap();
let mut app = PhotocraftApp::new(session, crate::Services::default());
let mut harness = Harness::builder().with_size(egui::vec2(900.0, 1000.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app);
PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]);
let id = open(harness.state_mut(), "image.mode.indexedColor").unwrap();
harness.state_mut().ui.dialog_mut(id).unwrap().fields.insert("palette".into(), json!("exact"));
harness.run_steps(3);
harness.query_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).expect("Matte dropdown").click();
harness.run_steps(2);
harness.get_by_label(choice).click();
harness.run_steps(3);
if choice == "Other…" {
let picker = harness.state().ui.dialogs.last().unwrap().id;
assert_ne!(picker, id);
harness.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), json!("#0000ff"));
crate::dialogs::confirm(harness.state_mut(), picker).unwrap();
harness.state_mut().ui.dialogs.retain(|dialog| dialog.id != picker);
harness.run_steps(3);
}
harness.get_by_label("OK").click();
harness.run_steps(3);
let doc = &harness.state().session.active().unwrap().doc;
assert_eq!(doc.mode, photocraft_color::ColorMode::Indexed);
let surface = doc.layers[0].surface().unwrap();
let edge = surface.rgba(0, 0);
let expected = [0.75 + 0.25 * matte[0], 0.25 * matte[1], 0.25 * matte[2]];
assert!(edge.iter().zip(expected).all(|(got, want)| (got - want).abs() <= 1.0 / 255.0) && edge[3] == 1.0, "{choice}: {edge:?} vs {expected:?}");
assert_eq!(surface.rgba(1, 0)[3], 0.0);
}
}
/// Selecting Other… must not replace None until the custom colour picker is confirmed.
#[test]
fn indexed_matte_cancel_keeps_the_previous_choice() {
use egui::accesskit::Role;
use egui_kittest::{Harness, kittest::Queryable};
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width": 2, "height": 1, "depth": 32, "background": "transparent"})).unwrap();
let mut app = PhotocraftApp::new(session, crate::Services::default());
let mut harness = Harness::builder().with_size(egui::vec2(900.0, 1000.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app);
PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]);
let id = open(harness.state_mut(), "image.mode.indexedColor").unwrap();
harness.run_steps(3);
harness.query_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).expect("Matte dropdown").click();
harness.run_steps(2);
harness.get_by_label("Other…").click();
harness.run_steps(3);
let picker = harness.state().ui.dialogs.last().expect("custom matte picker").id;
assert_ne!(picker, id);
let parent = harness.state().ui.dialogs.iter().find(|dialog| dialog.id == id).expect("Indexed Color dialog");
assert_eq!(parent.fields.get("matte").and_then(Value::as_str), None, "opening Other… does not commit a matte");
assert_eq!(harness.state().ui.dialogs.last().unwrap().fields["color"], "#ffffff", "the previous default still seeds the picker");
crate::dialogs::cancel(harness.state_mut(), picker).unwrap();
harness.run_steps(3);
let parent = harness.state().ui.dialogs.iter().find(|dialog| dialog.id == id).expect("Indexed Color dialog");
assert_eq!(parent.fields.get("matte").and_then(Value::as_str), None, "cancel restores the previous None choice");
assert!(!parent.fields.contains_key("__pickColorDefault"));
}
@@ -334,6 +334,7 @@ mod tests {
ChannelTarget::Alpha(0),
&[],
&Default::default(),
Some((app.session.tools.foreground, app.session.tools.background)),
)
.unwrap();
let ctx = egui::Context::default();
@@ -123,6 +123,7 @@ mod tests {
command: "image.mode.indexedColor".into(),
params: json!({"colors": colors}),
k: 1,
tool_colors: ([0.0, 0.0, 0.0, 1.0], [1.0; 4]),
}
}
@@ -23,6 +23,16 @@ pub(super) const KEY: &str = "stops";
/// The dialog field holding the transparency stops.
pub(super) const OPACITY_KEY: &str = "opacityStops";
/// A colour stop being dragged on the page's ramp.
#[derive(Clone, Copy, Debug)]
struct StopDrag {
/// The stop's index (it changes as the stop passes others).
index: usize,
/// The stop while it is pulled off the bar: deleted from the gradient, so the ramp and the
/// canvas show it gone; dragging back onto the bar puts it back.
removed: Option<(f32, Color)>,
}
/// Where the last drawn ramp bar is, for tests that drive it: `(effect id, bar rect)`.
pub(crate) fn bar_id() -> egui::Id {
egui::Id::unique("fx-gradient-bar")
@@ -207,39 +217,67 @@ pub(super) fn row(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String
ui.painter().rect_filled(chip, 0.0, Color32::from_rgb(q(r), q(g), q(b)));
ui.painter().rect_stroke(chip, 0.0, Stroke::new(if i == selected { 1.5 } else { 1.0 }, ink), StrokeKind::Outside);
}
// Pointer: press on a marker selects it and starts a drag; a drag moves it, and a drag that
// leaves the strip deletes it on release (two stops always stay); a click under the bar with
// no marker adds a stop; a double-click on a marker opens the Color Picker.
// Pointer: press on a marker selects it and starts a drag; a drag moves it, and a drag down
// off the strip deletes it (the ramp shows it gone, dragging back puts it back, two stops
// always stay); a click under the bar with no marker adds a stop; a double-click on a
// marker opens the Color Picker.
if resp.drag_started()
&& let Some(p) = ui.input(|i| i.pointer.press_origin())
{
if let Some(i) = hit(p) {
ui.data_mut(|d| d.insert_temp(drag_key, i));
ui.data_mut(|d| d.insert_temp(drag_key, StopDrag { index: i, removed: None }));
ui.data_mut(|d| d.insert_temp(sel_key, i));
} else {
ui.data_mut(|d| d.remove::<usize>(drag_key));
ui.data_mut(|d| d.remove::<StopDrag>(drag_key));
}
}
let dragging: Option<usize> = ui.data(|d| d.get_temp(drag_key));
if let (Some(i), Some(p)) = (dragging, resp.interact_pointer_pos()) {
let away = p.y > outer.bottom() + 24.0 || p.y < bar.top() - 24.0;
if resp.drag_stopped() {
ui.data_mut(|d| d.remove::<usize>(drag_key));
if away && stops.len() > 2 {
edit(app, f, effect, disp, json!({"action": "delete", "index": i}));
ui.data_mut(|d| d.insert_temp(sel_key, 0usize));
let dragging: Option<StopDrag> = ui.data(|d| d.get_temp(drag_key));
if let (Some(mut drag), Some(p)) = (dragging, resp.interact_pointer_pos()) {
let off = crate::gradient_ui::off_strip(p, bar);
let loc = loc_of(p.x);
// The release frame applies the same rule (its last move may cross the edge), then ends
// the drag.
if resp.dragged() || resp.drag_stopped() {
match drag.removed {
None if off && stops.len() > 2 => {
if let Some(stop) = stops.get(drag.index).copied()
&& edit(app, f, effect, disp, json!({"action": "delete", "index": drag.index})).is_some()
{
drag.removed = Some(stop);
ui.data_mut(|d| d.insert_temp(sel_key, 0usize));
}
}
Some((_, color)) if !off => {
let mut back = stops.clone();
back.push((loc, color));
back.sort_by(|a, b| a.0.total_cmp(&b.0));
let index = back.iter().rposition(|s| s.0 == loc).unwrap_or(0);
let mut fill = fill.clone();
if let Fill::Gradient { stops, .. } = &mut fill {
*stops = back;
}
commit(f, effect, disp, &fill);
drag = StopDrag { index, removed: None };
ui.data_mut(|d| d.insert_temp(sel_key, index));
}
Some(_) => {}
None => {
if (loc - stops.get(drag.index).map_or(loc, |s| s.0)).abs() > 1e-4
&& let Some(at) = edit(app, f, effect, disp, json!({"action": "move", "index": drag.index, "location": loc}))
{
drag.index = at;
ui.data_mut(|d| d.insert_temp(sel_key, at));
}
}
}
} else if resp.dragged() && !away {
let loc = loc_of(p.x);
if (loc - stops.get(i).map_or(loc, |s| s.0)).abs() > 1e-4
&& let Some(at) = edit(app, f, effect, disp, json!({"action": "move", "index": i, "location": loc}))
{
ui.data_mut(|d| d.insert_temp(drag_key, at));
ui.data_mut(|d| d.insert_temp(sel_key, at));
if resp.drag_stopped() {
ui.data_mut(|d| d.remove::<StopDrag>(drag_key));
} else {
ui.data_mut(|d| d.insert_temp(drag_key, drag));
}
}
} else if resp.drag_stopped() {
ui.data_mut(|d| d.remove::<usize>(drag_key));
ui.data_mut(|d| d.remove::<StopDrag>(drag_key));
}
if resp.double_clicked()
&& let Some(p) = resp.interact_pointer_pos()
@@ -385,6 +423,72 @@ mod tests {
assert_eq!(stops_in(h.state(), parent).len(), 2);
}
/// #10742: on the Gradient Overlay page a colour stop dragged down off the bar (about a
/// marker's height) disappears while it is off, is gone on release, and comes back when
/// dragged back onto the bar first.
#[test]
fn a_stop_dragged_off_the_ramp_shows_gone_and_dragging_back_cancels() {
let (mut app, parent) = dialog_app();
let effect = crate::layer_style::effects_of(&app.ui.dialogs[0].fields)[0]["id"].as_str().unwrap().to_string();
set_param(&mut app.ui.dialog_mut(parent).unwrap().fields, &effect, KEY, json!([[0.0, "#000000"], [0.5, "#ff0000"], [1.0, "#ffffff"]]));
let mut h = harness(app, parent);
let (_, bar): (String, Rect) = h.ctx.data(|d| d.get_temp(bar_id())).expect("the ramp was drawn");
let mid = pos2(bar.center().x, bar.bottom() + 9.0);
let away = pos2(mid.x, mid.y + 22.0);
press(&mut h, mid);
h.event(egui::Event::PointerMoved(pos2(mid.x, mid.y + 11.0)));
h.run_steps(1);
h.event(egui::Event::PointerMoved(away));
h.run_steps(1);
assert_eq!(stops_in(h.state(), parent).len(), 2, "off the bar the stop is gone");
h.event(egui::Event::PointerMoved(mid));
h.run_steps(1);
let back = stops_in(h.state(), parent);
assert_eq!(back.len(), 3, "back on the bar it returns: {back:?}");
release(&mut h, mid);
let back = stops_in(h.state(), parent);
assert!(back.len() == 3 && (back[1].0 - 0.5).abs() < 0.01 && super::super::hex(&back[1].1) == "#ff0000", "{back:?}");
press(&mut h, mid);
h.event(egui::Event::PointerMoved(pos2(mid.x, mid.y + 11.0)));
h.run_steps(1);
h.event(egui::Event::PointerMoved(away));
h.run_steps(1);
release(&mut h, away);
let stops = stops_in(h.state(), parent);
assert_eq!(stops.iter().map(|s| super::super::hex(&s.1)).collect::<Vec<_>>(), ["#000000", "#ffffff"], "{stops:?}");
}
/// The release frame counts: a stop that leaves the strip in the frame it is released is
/// removed, and one brought back onto the strip in that frame is kept.
#[test]
fn the_release_frame_decides_whether_a_stop_comes_off_the_ramp() {
for back in [true, false] {
let (mut app, parent) = dialog_app();
let effect = crate::layer_style::effects_of(&app.ui.dialogs[0].fields)[0]["id"].as_str().unwrap().to_string();
set_param(&mut app.ui.dialog_mut(parent).unwrap().fields, &effect, KEY, json!([[0.0, "#000000"], [0.5, "#ff0000"], [1.0, "#ffffff"]]));
let mut h = harness(app, parent);
let (_, bar): (String, Rect) = h.ctx.data(|d| d.get_temp(bar_id())).expect("the ramp was drawn");
let mid = pos2(bar.center().x, bar.bottom() + 9.0);
let away = pos2(mid.x, mid.y + 30.0);
press(&mut h, mid);
h.event(egui::Event::PointerMoved(pos2(mid.x, mid.y + 11.0)));
h.run_steps(1);
if back {
h.event(egui::Event::PointerMoved(away));
h.run_steps(1);
assert_eq!(stops_in(h.state(), parent).len(), 2, "off the strip the stop is gone");
}
let to = if back { mid } else { away };
// The last move and the release in one frame (`Harness::event` gives each its own).
let input = &mut h.input_mut().events;
input.push(egui::Event::PointerMoved(to));
input.push(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
let stops = stops_in(h.state(), parent);
assert_eq!(stops.len(), if back { 3 } else { 2 }, "back {back}: {stops:?}");
}
}
/// A preset from the Gradients panel becomes the page's stops; the Delete button and the
/// Location field work on the selected stop.
#[test]
+1
View File
@@ -17,6 +17,7 @@ fn filter_dialog_with_preview(background: bool) -> (PhotocraftApp, u64) {
command: "filter.blur.gaussianBlur".into(),
params: serde_json::json!({"radius": 4.0}),
k: 1,
tool_colors: (app.session.tools.foreground, app.session.tools.background),
};
app.filter_preview = Some(crate::filter_dialog::FilterPreview { key, result: result.map(std::sync::Arc::new), committing: false });
(app, id)
+70 -10
View File
@@ -148,17 +148,37 @@ impl PhotocraftApp {
/// (#1826, #1866). A caller's explicit directory is kept. The chosen folder is remembered for
/// the document the dialog was asked for.
pub(crate) fn pick_save(&mut self, suggested: &str, then: impl FnOnce(&mut Self, String) -> Result<Value, String> + 'static) -> Result<Value, String> {
self.pick_save_in(suggested, false, then)
}
/// [`Self::pick_save`] for the export flows (Export As, Quick Export, Save for Web, ...): starts in
/// the folder [`export_start_dir`] picks (#10192), and once `then` has exported, remembers the
/// chosen file's folder in `export.lastFolder`; a failed or cancelled export leaves it alone.
pub(crate) fn pick_export(&mut self, suggested: &str, then: impl FnOnce(&mut Self, String) -> Result<Value, String> + 'static) -> Result<Value, String> {
self.pick_save_in(suggested, true, then)
}
fn pick_save_in(
&mut self,
suggested: &str,
export: bool,
then: impl FnOnce(&mut Self, String) -> Result<Value, String> + 'static,
) -> Result<Value, String> {
let mut suggested = std::path::PathBuf::from(suggested);
let doc = self.session.active().map(|d| d.doc.id);
// Closed documents' folders are no longer needed.
let open: Vec<_> = self.session.documents().iter().map(|d| d.doc.id).collect();
self.save_dirs.retain(|id, _| open.contains(id));
if suggested.parent().is_some_and(|p| p.as_os_str().is_empty())
&& let Some(dir) = doc
if suggested.parent().is_some_and(|p| p.as_os_str().is_empty()) {
let document_dir = doc
.and_then(|d| self.save_dirs.get(&d).cloned())
.or_else(|| self.session.active().and_then(|d| d.path.as_deref()).and_then(|p| std::path::Path::new(p).parent()).map(Path::to_path_buf))
{
suggested = dir.join(suggested);
// An export doesn't start in a folder that is gone.
.filter(|dir| !export || folder_exists(dir))
.or_else(|| self.session.active().and_then(|d| d.path.as_deref()).and_then(|p| std::path::Path::new(p).parent()).map(Path::to_path_buf));
let remembered = export.then(|| self.session.prefs().export.last_folder.clone());
if let Some(dir) = export_start_dir(remembered.as_deref(), document_dir, folder_exists) {
suggested = dir.join(suggested);
}
}
// The format comes from the extension, so a name typed without one (common where file
// extensions are hidden, #5039) gets the suggested file's extension, as Photoshop's
@@ -169,12 +189,20 @@ impl PhotocraftApp {
FileDialogAnswer::SaveTo(path) => {
let path = saved_path(app, &path, suggested_ext.as_deref());
// The web answers a download name, which has no folder to remember.
if let Some(doc) = doc
&& let Some(dir) = Path::new(&path).parent().filter(|p| !p.as_os_str().is_empty())
{
app.save_dirs.insert(doc, dir.to_path_buf());
let dir = doc.zip(Path::new(&path).parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf));
// An export's folder only once it has exported: a failed one doesn't move where
// the next export starts.
if !export && let Some((doc, dir)) = dir.clone() {
app.save_dirs.insert(doc, dir);
}
then(app, path)
let exported = then(app, path.clone())?;
if export {
if let Some((doc, dir)) = dir {
app.save_dirs.insert(doc, dir);
}
app.remember_export_folder(&path);
}
Ok(exported)
}
_ => Err(UNEXPECTED.into()),
})?;
@@ -184,6 +212,16 @@ impl PhotocraftApp {
Ok(asked)
}
/// Remember the folder of an export that succeeded as where the next export dialog starts.
/// The web answers a download name, which has no folder, and leaves it alone.
fn remember_export_folder(&mut self, path: &str) {
let Some(dir) = Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()) else { return };
let dir = dir.to_string_lossy().into_owned();
if self.session.prefs().export.last_folder != dir {
self.session.prefs.edit(|p| p.export.last_folder = dir);
}
}
/// Whether a save to `path` replaces a file the save dialog didn't ask about: the dialog
/// answered `answered`, and [`saved_path`] changed it. A file at `path` that
/// [`Services::same_file`](crate::Services::same_file) finds is the same entry as `answered` (the
@@ -370,6 +408,28 @@ fn saved_path(app: &PhotocraftApp, answered: &str, suggested_ext: Option<&str>)
}
}
/// Whether `dir` is a folder on disk. The web has no file system, so nothing is remembered there.
#[cfg(not(target_arch = "wasm32"))]
fn folder_exists(dir: &Path) -> bool {
dir.is_dir()
}
#[cfg(target_arch = "wasm32")]
fn folder_exists(_dir: &Path) -> bool {
false
}
/// The folder an export dialog starts in (#10192): the `remembered` folder of the last export
/// while `exists` finds it, else the document's own folder (`document_dir`, whatever it is),
/// else none, which leaves the choice to the system dialog.
pub(crate) fn export_start_dir(
remembered: Option<&str>,
document_dir: Option<std::path::PathBuf>,
exists: impl Fn(&Path) -> bool,
) -> Option<std::path::PathBuf> {
remembered.filter(|d| !d.is_empty()).map(std::path::PathBuf::from).filter(|d| exists(d)).or(document_dir)
}
/// The folder an open dialog starts in: the directory of the most recent file (UI-217-3).
pub(crate) fn last_used_dir(recent: &[String]) -> Option<String> {
let dir = std::path::Path::new(recent.first()?).parent()?;
+98
View File
@@ -1517,3 +1517,101 @@ fn import_variable_data_sets_menu_asks_for_a_csv_and_imports_it() {
app.poll_file_dialog(&ctx, None);
assert_eq!(app.session.active().map(|d| d.doc.variables.data_sets.len()), Some(2));
}
/// #10192: the folder an export dialog starts in, as a pure decision.
#[test]
fn export_start_dir_prefers_an_existing_remembered_folder() {
use std::path::PathBuf;
let doc = Some(PathBuf::from("/proj"));
let all_exist = |_: &Path| true;
let none_exist = |_: &Path| false;
// Remembered and present: used.
assert_eq!(export_start_dir(Some("/renders"), doc.clone(), all_exist), Some(PathBuf::from("/renders")));
// Remembered but gone: the document's folder.
assert_eq!(export_start_dir(Some("/renders"), doc.clone(), none_exist), doc);
// Nothing remembered (unset or empty): the document's folder, or nothing for an untitled one.
assert_eq!(export_start_dir(None, doc.clone(), all_exist), doc);
assert_eq!(export_start_dir(Some(""), doc.clone(), all_exist), doc);
assert_eq!(export_start_dir(None, None, all_exist), None);
assert_eq!(export_start_dir(Some("/renders"), None, none_exist), None);
}
/// #10192: exports start in the last successfully exported folder, across documents; a failed or
/// cancelled export, a folder that is gone and other save dialogs change nothing.
#[test]
fn exports_start_in_the_last_exported_folder() {
let (mut app, open, _) = app();
let ctx = egui::Context::default();
let root = tempfile::tempdir().unwrap();
let renders = root.path().join("renders");
std::fs::create_dir(&renders).unwrap();
let renders_text = renders.to_string_lossy().into_owned();
app.session.active_mut().unwrap().path = Some("/proj/original.psd".into());
let suggested = |open: &Open| match &open.borrow()[0].0 {
FileDialogRequest::Save { suggested } => suggested.clone(),
other => panic!("save dialog expected, got {other:?}"),
};
let remembered = |app: &PhotocraftApp| app.session.prefs().export.last_folder.clone();
// No export yet: beside the document. Cancelled, nothing is remembered.
app.pick_export("a.png", |_, _| Ok(Value::Null)).unwrap();
app.poll_file_dialog(&ctx, None);
assert_eq!(suggested(&open), joined("/proj", "a.png"));
answer(&open, None);
app.poll_file_dialog(&ctx, None);
assert_eq!(remembered(&app), "");
// The user picks another folder, but the export fails: nothing is remembered.
app.pick_export("a.png", |_, _| Err("disk full".into())).unwrap();
app.poll_file_dialog(&ctx, None);
answer(&open, Some(FileDialogAnswer::SaveTo(joined(&renders_text, "a.png"))));
app.poll_file_dialog(&ctx, None);
assert_eq!(remembered(&app), "");
// ...and the next export still starts beside the document, not in the failed export's folder.
app.pick_export("a.png", |_, _| Ok(Value::Null)).unwrap();
app.poll_file_dialog(&ctx, None);
assert_eq!(suggested(&open), joined("/proj", "a.png"));
answer(&open, None);
app.poll_file_dialog(&ctx, None);
// A successful export is remembered...
app.pick_export("a.png", |_, _| Ok(Value::Null)).unwrap();
app.poll_file_dialog(&ctx, None);
answer(&open, Some(FileDialogAnswer::SaveTo(joined(&renders_text, "a.png"))));
app.poll_file_dialog(&ctx, None);
assert_eq!(remembered(&app), renders_text);
// ...and starts the next export, of any document, even an untitled one.
app.run("file.new", json!({"width": 4, "height": 4})).unwrap();
app.pick_export("b.png", |_, _| Ok(Value::Null)).unwrap();
app.poll_file_dialog(&ctx, None);
assert_eq!(suggested(&open), joined(&renders_text, "b.png"));
// A cancelled dialog changes nothing.
answer(&open, None);
app.poll_file_dialog(&ctx, None);
assert_eq!(remembered(&app), renders_text);
// Other save dialogs keep their own start.
app.pick_save("c.psd", |_, _| Ok(Value::Null)).unwrap();
app.poll_file_dialog(&ctx, None);
assert_eq!(suggested(&open), "c.psd");
answer(&open, None);
app.poll_file_dialog(&ctx, None);
// The folder disappears: back to the document's folder.
std::fs::remove_dir(&renders).unwrap();
app.session.set_active(0);
app.pick_export("d.png", |_, _| Ok(Value::Null)).unwrap();
app.poll_file_dialog(&ctx, None);
assert_eq!(suggested(&open), joined("/proj", "d.png"));
answer(&open, None);
app.poll_file_dialog(&ctx, None);
}
#[test]
fn the_last_export_folder_is_a_preference_that_old_files_lack() {
let prefs = photocraft_engine::prefs::Preferences::default();
assert_eq!(prefs.export.last_folder, "");
let mut json = serde_json::to_value(&prefs).unwrap();
json["export"]["lastFolder"] = "/renders".into();
let loaded: photocraft_engine::prefs::Preferences = serde_json::from_value(json.clone()).unwrap();
assert_eq!(loaded.export.last_folder, "/renders");
// Settings saved before the field existed still load.
json["export"].as_object_mut().unwrap().remove("lastFolder");
let old: photocraft_engine::prefs::Preferences = serde_json::from_value(json).unwrap();
assert_eq!(old.export.last_folder, "");
}
+8 -2
View File
@@ -334,16 +334,22 @@ impl PhotocraftApp {
}
}
/// The pointer position, from the OS cursor service when available, falling back to egui's
/// last-known pointer position (e.g. on Wayland).
pub(crate) fn cursor_pos(&mut self, ctx: &egui::Context) -> Option<egui::Pos2> {
self.services.cursor_pos.as_mut().and_then(|f| f(ctx)).or_else(|| ctx.input(|i| i.pointer.latest_pos()))
}
/// Which of the files called `names`, dropped onto the window just now, are placed on the
/// active document's canvas rather than opened, for a shell that reads dropped files itself
/// (the browser reads them asynchronously, so the web shell can't hand them to
/// [`open_dropped`](Self::open_dropped)). It delivers those through
/// [`Services::place_inbox`](crate::Services::place_inbox) and the rest through
/// [`Services::inbox`](crate::Services::inbox). The pointer comes from
/// [`Services::cursor_pos`](crate::Services::cursor_pos). As with a desktop canvas drop, a Free
/// [`cursor_pos`](Self::cursor_pos). As with a desktop canvas drop, a Free
/// Transform still open is applied first (#4833).
pub fn dropped_on_canvas(&mut self, ctx: &egui::Context, names: &[String]) -> Vec<bool> {
let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx));
let at = self.cursor_pos(ctx);
let canvas = self.drop_target(ctx, at) == DropTarget::Canvas;
let places: Vec<bool> = names.iter().map(|n| canvas && !crate::preset_files_ui::is_preset_file(n)).collect();
if places.contains(&true) {
+1
View File
@@ -3601,6 +3601,7 @@ curves Smooth تنعيم
Pick a different document for each channel. اختر مستندًا مختلفًا لكل قناة.
A picked document is no longer open. أحد المستندات المختارة لم يعد مفتوحًا.
A picked document is no longer a grayscale document of the same size. أحد المستندات المختارة لم يعد مستندًا بتدرج الرمادي بالحجم نفسه.
Netscape Gray رمادي Netscape
# Move tool options bar (#11381)
Align top edges محاذاة الحواف العلوية
Align vertical centers محاذاة المراكز الرأسية
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4347,6 +4347,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Pro každý kanál vyberte jiný dokument.
A picked document is no longer open. Jeden z vybraných dokumentů už není otevřený.
A picked document is no longer a grayscale document of the same size. Jeden z vybraných dokumentů už není dokument ve stupních šedi stejné velikosti.
Netscape Gray Šedá Netscape
# Move tool options bar (#11381)
Align top edges Zarovnat horní okraje
Align vertical centers Zarovnat svislé středy
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4813,6 +4813,7 @@ cameraRaw White Balance: As Shot Hvidbalance: Som fotograferet
Pick a different document for each channel. Vælg et andet dokument til hver kanal.
A picked document is no longer open. Et af de valgte dokumenter er ikke længere åbent.
A picked document is no longer a grayscale document of the same size. Et af de valgte dokumenter er ikke længere et dokument i gråtoner i samme størrelse.
Netscape Gray Netscape-grå
# Move tool options bar (#11381)
Align top edges Juster øverste kanter
Align vertical centers Juster lodrette midter
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -3642,6 +3642,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Wählen Sie für jeden Kanal ein anderes Dokument.
A picked document is no longer open. Ein ausgewähltes Dokument ist nicht mehr geöffnet.
A picked document is no longer a grayscale document of the same size. Ein ausgewähltes Dokument ist kein Graustufen-Dokument derselben Größe mehr.
Netscape Gray Netscape-Grau
# Move tool options bar (#11381)
Align top edges Obere Kanten ausrichten
Align vertical centers Vertikale Mitten ausrichten
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4306,6 +4306,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Επιλέξτε διαφορετικό έγγραφο για κάθε κανάλι.
A picked document is no longer open. Ένα από τα επιλεγμένα έγγραφα δεν είναι πλέον ανοιχτό.
A picked document is no longer a grayscale document of the same size. Ένα από τα επιλεγμένα έγγραφα δεν είναι πλέον έγγραφο σε κλίμακα του γκρι ίδιου μεγέθους.
Netscape Gray Γκρι Netscape
# Move tool options bar (#11381)
Align top edges Στοίχιση πάνω άκρων
Align vertical centers Στοίχιση κατακόρυφων κέντρων
Can't render this file because it contains an unexpected character in line 47 and column 53.
+1
View File
@@ -4506,6 +4506,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Elija un documento distinto para cada canal.
A picked document is no longer open. Uno de los documentos elegidos ya no está abierto.
A picked document is no longer a grayscale document of the same size. Uno de los documentos elegidos ya no es un documento en escala de grises del mismo tamaño.
Netscape Gray Gris Netscape
# Move tool options bar (#11381)
Align top edges Alinear bordes superiores
Align vertical centers Alinear centros verticales
Can't render this file because it contains an unexpected character in line 4 and column 47.
+1
View File
@@ -4814,6 +4814,7 @@ cameraRaw White Balance: As Shot Valkotasapaino: kuvauksen mukainen
Pick a different document for each channel. Valitse jokaiselle kanavalle eri asiakirja.
A picked document is no longer open. Yksi valituista asiakirjoista ei ole enää auki.
A picked document is no longer a grayscale document of the same size. Yksi valituista asiakirjoista ei ole enää samankokoinen harmaasävyasiakirja.
Netscape Gray Netscape-harmaa
# Move tool options bar (#11381)
Align top edges Tasaa yläreunat
Align vertical centers Tasaa pystykeskikohdat
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4629,6 +4629,7 @@ shape Appearance Apparence
Pick a different document for each channel. Choisissez un document différent pour chaque canal.
A picked document is no longer open. Un des documents choisis n'est plus ouvert.
A picked document is no longer a grayscale document of the same size. Un des documents choisis n'est plus un document en niveaux de gris de même taille.
Netscape Gray Gris Netscape
# Move tool options bar (#11381)
Align top edges Aligner les bords supérieurs
Align vertical centers Aligner les centres verticaux
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -675,6 +675,7 @@ cameraRaw Yellow पीला
Pick a different document for each channel. हर चैनल के लिए अलग डॉक्यूमेंट चुनें।
A picked document is no longer open. चुना गया एक डॉक्यूमेंट अब खुला नहीं है।
A picked document is no longer a grayscale document of the same size. चुना गया एक डॉक्यूमेंट अब उसी आकार का ग्रेस्केल डॉक्यूमेंट नहीं है।
Netscape Gray Netscape धूसर
# Move tool options bar (#11381)
Align top edges ऊपरी किनारे संरेखित करें
Align vertical centers ऊर्ध्वाधर केंद्र संरेखित करें
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4513,6 +4513,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Minden csatornához másik dokumentumot válasszon.
A picked document is no longer open. Az egyik kiválasztott dokumentum már nincs megnyitva.
A picked document is no longer a grayscale document of the same size. Az egyik kiválasztott dokumentum már nem azonos méretű szürkeárnyalatos dokumentum.
Netscape Gray Netscape-szürke
# Move tool options bar (#11381)
Align top edges Felső szélek igazítása
Align vertical centers Függőleges középpontok igazítása
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -3629,6 +3629,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Pilih dokumen yang berbeda untuk setiap channel.
A picked document is no longer open. Salah satu dokumen yang dipilih sudah tidak terbuka.
A picked document is no longer a grayscale document of the same size. Salah satu dokumen yang dipilih bukan lagi dokumen grayscale dengan ukuran yang sama.
Netscape Gray Abu-abu Netscape
# Move tool options bar (#11381)
Align top edges Ratakan tepi atas
Align vertical centers Ratakan pusat vertikal
Can't render this file because it contains an unexpected character in line 4 and column 47.
+1
View File
@@ -4705,6 +4705,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Scegli un documento diverso per ogni canale.
A picked document is no longer open. Uno dei documenti scelti non è più aperto.
A picked document is no longer a grayscale document of the same size. Uno dei documenti scelti non è più un documento in scala di grigio delle stesse dimensioni.
Netscape Gray Grigio Netscape
# Move tool options bar (#11381)
Align top edges Allinea i bordi superiori
Align vertical centers Allinea i centri verticali
Can't render this file because it contains an unexpected character in line 79 and column 53.
+1
View File
@@ -4277,6 +4277,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. チャンネルごとに別のドキュメントを選択してください。
A picked document is no longer open. 選択したドキュメントの一つが開かれていません。
A picked document is no longer a grayscale document of the same size. 選択したドキュメントの一つが、同じサイズのグレースケールのドキュメントではなくなりました。
Netscape Gray Netscape グレー
# Move tool options bar (#11381)
Align top edges 上端を揃える
Align vertical centers 垂直方向中央を揃える
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -3833,6 +3833,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. 채널마다 다른 문서를 선택하십시오.
A picked document is no longer open. 선택한 문서 중 하나가 더 이상 열려 있지 않습니다.
A picked document is no longer a grayscale document of the same size. 선택한 문서 중 하나가 더 이상 같은 크기의 회색 음영 문서가 아닙니다.
Netscape Gray Netscape 회색
# Rows that #8185 adds on top of the catalog above.
Working CMY Plate 작업용 CMY 판
Can't render this file because it contains an unexpected character in line 63 and column 53.
+1
View File
@@ -4813,6 +4813,7 @@ cameraRaw White Balance: As Shot Hvitbalanse: som fotografert
Pick a different document for each channel. Velg et annet dokument for hver kanal.
A picked document is no longer open. Et av de valgte dokumentene er ikke lenger åpent.
A picked document is no longer a grayscale document of the same size. Et av de valgte dokumentene er ikke lenger et dokument i gråtoner av samme størrelse.
Netscape Gray Netscape-grå
# Move tool options bar (#11381)
Align top edges Juster øverste kanter
Align vertical centers Juster loddrette midtpunkter
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4360,6 +4360,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Kies voor elk kanaal een ander document.
A picked document is no longer open. Een gekozen document is niet meer geopend.
A picked document is no longer a grayscale document of the same size. Een gekozen document is geen grijswaardendocument van hetzelfde formaat meer.
Netscape Gray Netscape-grijs
# Move tool options bar (#11381)
Align top edges Bovenranden uitlijnen
Align vertical centers Verticale middens uitlijnen
Can't render this file because it contains an unexpected character in line 8 and column 34.
+1
View File
@@ -4224,6 +4224,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Wybierz inny dokument dla każdego kanału.
A picked document is no longer open. Jeden z wybranych dokumentów nie jest już otwarty.
A picked document is no longer a grayscale document of the same size. Jeden z wybranych dokumentów nie jest już dokumentem w skali szarości o tym samym rozmiarze.
Netscape Gray Szarość Netscape
# Move tool options bar (#11381)
Align top edges Wyrównaj górne krawędzie
Align vertical centers Wyrównaj środki w pionie
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4520,6 +4520,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Escolha um documento diferente para cada canal.
A picked document is no longer open. Um dos documentos escolhidos não está mais aberto.
A picked document is no longer a grayscale document of the same size. Um dos documentos escolhidos não é mais um documento em tons de cinza do mesmo tamanho.
Netscape Gray Cinza Netscape
# Move tool options bar (#11381)
Align top edges Alinhar bordas superiores
Align vertical centers Alinhar centros verticais
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4791,6 +4791,7 @@ shape Appearance Оформление
Pick a different document for each channel. Выберите отдельный документ для каждого канала.
A picked document is no longer open. Один из выбранных документов больше не открыт.
A picked document is no longer a grayscale document of the same size. Один из выбранных документов больше не является документом в градациях серого того же размера.
Netscape Gray Серый Netscape
# Move tool options bar (#11381)
Align top edges Выровнять верхние края
Align vertical centers Выровнять центры по вертикали
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4672,6 +4672,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Izaberite drugi dokument za svaki kanal.
A picked document is no longer open. Jedan izabrani dokument više nije otvoren.
A picked document is no longer a grayscale document of the same size. Jedan izabrani dokument više nije dokument u nijansama sive iste veličine.
Netscape Gray Netscape siva
# Move tool options bar (#11381)
Align top edges Poravnaj gornje ivice
Align vertical centers Poravnaj vertikalne centre
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4811,6 +4811,7 @@ cameraRaw White Balance: As Shot Vitbalans: som tagen
Pick a different document for each channel. Välj ett annat dokument för varje kanal.
A picked document is no longer open. Ett av de valda dokumenten är inte längre öppet.
A picked document is no longer a grayscale document of the same size. Ett av de valda dokumenten är inte längre ett gråskaledokument i samma storlek.
Netscape Gray Netscape-grå
# Move tool options bar (#11381)
Align top edges Justera överkanter
Align vertical centers Justera vertikala mittpunkter
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -4337,6 +4337,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Her kanal için farklı bir belge seçin.
A picked document is no longer open. Seçilen belgelerden biri artık açık değil.
A picked document is no longer a grayscale document of the same size. Seçilen belgelerden biri artık aynı boyutta gri tonlamalı bir belge değil.
Netscape Gray Netscape Grisi
# Move tool options bar (#11381)
Align top edges Üst kenarları hizala
Align vertical centers Dikey merkezleri hizala
Can't render this file because it contains an unexpected character in line 8 and column 34.
+1
View File
@@ -4317,6 +4317,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Виберіть окремий документ для кожного каналу.
A picked document is no longer open. Один із вибраних документів більше не відкрито.
A picked document is no longer a grayscale document of the same size. Один із вибраних документів більше не є документом у градаціях сірого того самого розміру.
Netscape Gray Сірий Netscape
# Move tool options bar (#11381)
Align top edges Вирівняти верхні краї
Align vertical centers Вирівняти центри по вертикалі
Can't render this file because it contains an unexpected character in line 152 and column 53.
+1
View File
@@ -4111,6 +4111,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. Chọn một tài liệu khác cho mỗi kênh.
A picked document is no longer open. Một tài liệu đã chọn không còn mở.
A picked document is no longer a grayscale document of the same size. Một tài liệu đã chọn không còn là tài liệu thang xám cùng kích thước.
Netscape Gray Xám Netscape
# Move tool options bar (#11381)
Align top edges Căn các cạnh trên
Align vertical centers Căn các tâm dọc
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -3298,6 +3298,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. 请为每个通道选择不同的文档。
A picked document is no longer open. 所选的一个文档已不再打开。
A picked document is no longer a grayscale document of the same size. 所选的一个文档已不再是同样大小的灰度文档。
Netscape Gray Netscape 灰色
# Move tool options bar (#11381)
Align top edges 顶端对齐
Align vertical centers 垂直居中对齐
Can't render this file because it contains an unexpected character in line 63 and column 53.
+1
View File
@@ -3255,6 +3255,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Pick a different document for each channel. 請為每個色版選擇不同的文件。
A picked document is no longer open. 所選的一個文件已不再開啟。
A picked document is no longer a grayscale document of the same size. 所選的一個文件已不再是相同大小的灰階文件。
Netscape Gray Netscape 灰色
# Move tool options bar (#11381)
Align top edges 對齊頂端
Align vertical centers 垂直置中對齊
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -179,6 +179,7 @@ pub fn tool_icon(t: Tool) -> &'static str {
Tool::EllipseShape => "circle",
Tool::Triangle => "triangle",
Tool::Polygon => "pentagon",
Tool::Star => "star",
Tool::Line => "slash",
Tool::CustomShape => "cloud",
}
+16 -10
View File
@@ -1,8 +1,9 @@
//! Number keys set opacity (#352): 1 = 10% … 9 = 90%, 0 = 100%; two digits
//! typed quickly set an exact value (4 then 5 = 45%, 0 then 0 = 0%). With the Brush, Pencil or
//! typed quickly set an exact value (4 then 5 = 45%; 0 then 0 = 100% for the Brush and the Pencil, #11812). With the Brush, Pencil or
//! Eraser they set the brush's Opacity (⇧: Flow; swapped while airbrush build-up is on); with the Gradient or Paint Bucket their
//! Opacity; with tools that have no opacity of their own (Move, the selection tools, Type…) the
//! active layer's Opacity (⇧: Fill). Tools whose number is a strength or exposure are left alone.
//! active layer's Opacity (⇧: Fill); with the Background Eraser its Tolerance (#11907). Tools whose
//! number is a strength or exposure are left alone.
use egui::{Event, Key};
use serde_json::json;
@@ -25,6 +26,8 @@ enum Target {
},
/// The Gradient / Paint Bucket opacity option.
ToolOpacity,
/// The Background Eraser's Tolerance option.
BgTolerance,
/// The active layer's opacity (⇧: fill).
Layer,
None,
@@ -35,6 +38,7 @@ fn target(tool: Tool) -> Target {
Tool::Brush | Tool::Eraser | Tool::CloneStamp | Tool::HistoryBrush => Target::Brush { flow: true },
Tool::Pencil => Target::Brush { flow: false },
Tool::Gradient | Tool::PaintBucket => Target::ToolOpacity,
Tool::BackgroundEraser => Target::BgTolerance,
// Their options-bar number is a strength, exposure or tolerance, not this opacity.
t if t.is_brushlike() || t == Tool::MagicEraser => Target::None,
_ => Target::Layer,
@@ -107,9 +111,13 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) {
let shift = shift ^ (build_up && matches!(target(tool), Target::Brush { flow: true }));
match (target(app.ui.tool), shift) {
(Target::Brush { .. }, false) => {
// Clone Stamp's and History Brush's Opacity fields (and their strokes) start at 1%, so
// `00` sets the 1% they actually paint with rather than showing a 0% they can't do.
let v = if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush) { v.max(0.01) } else { v };
// The painting tools' Opacity fields (and `tools.setBrush`) start at 1%, so `00` sets the
// 1% they actually paint with rather than a 0% they can't do. The Brush's and the
// Pencil's `00` is 100%, as in Photoshop (#11812); only `00` gives 0 here.
let v = match tool {
Tool::Brush | Tool::Pencil if v <= 0.0 => 1.0,
_ => v.max(0.01),
};
let _ = app.run("tools.setBrush", json!({ "brush": { "opacity": v } }));
}
// The options bar's Flow field starts at 1%.
@@ -117,6 +125,8 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) {
let _ = app.run("tools.setBrush", json!({ "brush": { "flow": v.max(0.01) } }));
}
(Target::ToolOpacity, false) => app.ui.tool_options.fill_opacity = percent,
// The Tolerance field starts at 1%; `00` (0%) keeps today's value rather than guessing.
(Target::BgTolerance, false) if percent >= 1.0 => app.ui.tool_options.bg_tolerance = percent,
(Target::Layer, _) => {
// The locked Background has no opacity or fill.
let Some(st) = app.session.active() else { return };
@@ -163,7 +173,7 @@ mod tests {
press(&mut a, 0, false, 9000.0);
assert_eq!(a.session.tools.brush.opacity, 1.0, "0 = 100%");
press(&mut a, 0, false, 9100.0);
assert_eq!(a.session.tools.brush.opacity, 0.0, "00 = 0%");
assert_eq!(a.session.tools.brush.opacity, 1.0, "00 = 100%");
press(&mut a, 2, true, 20000.0);
assert!((a.session.tools.brush.flow - 0.2).abs() < 1e-6);
press(&mut a, 0, true, 30000.0);
@@ -224,10 +234,6 @@ mod tests {
press(&mut a, 0, false, 100.0);
assert!((a.session.tools.brush.opacity - 0.01).abs() < 1e-6, "{tool:?}");
}
let mut a = app(Tool::Brush);
press(&mut a, 0, false, 0.0);
press(&mut a, 0, false, 100.0);
assert!(a.session.tools.brush.opacity.abs() < 1e-6, "the Brush itself still goes to 0%");
}
#[test]
+15 -5
View File
@@ -907,8 +907,9 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) {
crate::opacity_keys::handle(app, ctx);
}
/// Selects a tool from its letter key. Pressing the key of the current group cycles within it; with
/// the Shift-switch preference only ⇧+key cycles. Returns true when a tool key was handled.
/// Selects a tool from its letter key. Entering a group uses its remembered eligible tool or the
/// first eligible tool in toolbar order. Pressing the key of the current group cycles within it.
/// With the Shift-switch preference, only ⇧+key cycles. Returns true when a tool key was handled.
fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &impl Fn(Key) -> bool) -> bool {
let shift_switch = app.session.prefs().tools.use_shift_key_for_tool_switch;
for t in Tool::ALL {
@@ -920,15 +921,20 @@ fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &im
if cycle_shift || pressed(k) {
let before = app.ui.tool;
let mut group: Vec<Tool> = Tool::ALL.iter().copied().filter(|x| x.key() == t.key() && crate::tool_shortcuts::uses_default(app, *x)).collect();
// Shift+key (the cycle and the fallback to the group's first tool) uses the toolbar
// flyout's order; plain keys keep the `Tool::ALL` order.
// Shift+key cycles in toolbar flyout order.
if cycle_shift {
group.sort_by_key(|x| crate::panels::toolbar::toolbar_position(*x));
}
app.ui.tool = match group.iter().position(|x| *x == app.ui.tool) {
Some(i) if shift_switch && !cycle_shift => group[i],
Some(i) => group[(i + 1) % group.len()],
None => app.ui.group_tools.iter().copied().find(|last| group.contains(last)).unwrap_or(group[0]),
None => app
.ui
.group_tools
.iter()
.copied()
.find(|last| group.contains(last))
.unwrap_or_else(|| group.iter().copied().min_by_key(|tool| crate::panels::toolbar::toolbar_position(*tool)).unwrap_or(t)),
};
crate::tool_memory::ended_by_tool(app);
// `consume_key` ignores extra ⇧ and ⌥: a ⇧/⌥ switch is never spring-loaded.
@@ -946,3 +952,7 @@ fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &im
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "tool_key_default_tests.rs"]
mod tool_key_default_tests;
@@ -0,0 +1,89 @@
use super::{Key, Modifiers, PhotocraftApp, Tool, handle};
use crate::panels::toolbar::TOOL_SECTIONS;
use crate::spring_tools::key_of;
use std::collections::HashSet;
fn app() -> PhotocraftApp {
PhotocraftApp::new(photocraft_engine::Session::new(), Default::default())
}
fn press(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: Modifiers) {
let raw = egui::RawInput {
events: vec![
egui::Event::ModifiersChanged(modifiers),
egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers },
egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers },
],
..Default::default()
};
ctx.begin_pass(raw);
handle(app, ctx);
ctx.end_pass().textures_delta.clear();
}
/// A fresh app enters each default letter group at its first toolbar tool under either preference.
#[test]
fn fresh_tool_letters_pick_the_first_tool_in_toolbar_order() {
for shift_switch in [true, false] {
let mut checked = HashSet::new();
for tool in TOOL_SECTIONS.iter().flat_map(|section| section.iter()).flat_map(|slot| slot.iter()).copied() {
let Some(key) = key_of(tool.key()) else { continue };
if !checked.insert(key) {
continue;
}
let mut app = app();
app.session.edit_prefs(|prefs| prefs.tools.use_shift_key_for_tool_switch = shift_switch);
if app.ui.tool.key() == tool.key() {
app.ui.tool = Tool::Brush;
}
press(&mut app, &egui::Context::default(), key, Modifiers::NONE);
assert_eq!(app.ui.tool, tool, "{key:?}, Shift switch: {shift_switch}");
}
assert_eq!(checked, Tool::ALL.into_iter().filter_map(|tool| key_of(tool.key())).collect::<HashSet<_>>());
}
}
/// A remembered Magic Wand takes precedence over the fresh W default, even when hidden.
#[test]
fn plain_w_returns_to_the_remembered_magic_wand() {
for hidden in [false, true] {
let mut app = app();
let ctx = egui::Context::default();
if hidden {
app.session.edit_prefs(|prefs| prefs.toolbar.hidden = vec!["MagicWand".to_owned()]);
}
app.ui.tool = Tool::MagicWand;
press(&mut app, &ctx, Key::B, Modifiers::NONE);
assert_eq!(app.ui.tool, Tool::Brush);
press(&mut app, &ctx, Key::W, Modifiers::NONE);
assert_eq!(app.ui.tool, Tool::MagicWand, "hidden: {hidden}");
}
}
/// Shift+W follows the flyout order and wraps. With the default preference, plain W keeps
/// the current tool when it already belongs to the group.
#[test]
fn shift_w_cycles_in_toolbar_order() {
let mut app = app();
let ctx = egui::Context::default();
app.ui.tool = Tool::ObjectSelection;
for expected in [Tool::QuickSelection, Tool::MagicWand, Tool::ObjectSelection] {
press(&mut app, &ctx, Key::W, Modifiers::SHIFT);
assert_eq!(app.ui.tool, expected);
}
press(&mut app, &ctx, Key::W, Modifiers::NONE);
assert_eq!(app.ui.tool, Tool::ObjectSelection);
}
#[test]
fn remapped_first_tool_is_skipped_by_its_default_letter() {
let mut app = app();
let ctx = egui::Context::default();
app.run("prefs.set", serde_json::json!({"path": "shortcuts.tools.select.objectSelection", "value": "F6"})).unwrap();
press(&mut app, &ctx, Key::W, Modifiers::NONE);
assert_eq!(app.ui.tool, Tool::QuickSelection);
press(&mut app, &ctx, Key::F6, Modifiers::NONE);
assert_eq!(app.ui.tool, Tool::ObjectSelection);
}
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff. Show more