PhotoCraft: An open-source, photo editor written by scratch in pure Rust
continued wip
Brandon Thomasae92ac20bff0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 91e0f863a..35c2b8575 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -90,6 +90,7 @@ jobs:- { crate: codecs, name: decode_jpeg }- { crate: codecs, name: decode_tiff }- { crate: codecs, name: decode_exr }+ - { crate: format, name: load }steps:- uses: actions/checkout@v4- uses: dtolnay/rust-toolchain@nightlydiff --git a/AGENTS.md b/AGENTS.mdindex bc11f7060..0735bdf8b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -20,15 +20,15 @@ crates/geom color raster L0 foundation (runtime pixel formats, COW tiles, blend math)psd codecs L0 standalone format crates (no workspace deps; publishable)doc L1 document model (layers, masks, adjustments, effects: pure data)- ops paint L2 history/undo, brush engine- compose L3 CPU reference compositor (the oracle for GPU work)+ ops paint algo text L2 history, brush engine, imaging algorithms, text engine+ compose gpu format L3 CPU compositor (the oracle), wgpu compositor, .pcraft native formatio L4 document <-> PSD / flat formatsengine L5 Session + command registry (every action is a command)- ui-egui L6 egui shell (thin: all actions go through the engine)+ ui-egui automation L6 egui shell (thin: all actions go through the engine); MCP servertestkit test helpersapps/photocraft desktop app (eframe/wgpu), TCP control server- photocraft-cli headless CLI+ photocraft-cli headless CLI (convert/info/run/batch/commands/mcp)xtask/ cargo xtask layers | wasm | ci | stats | corpus```@@ -53,10 +53,16 @@ cargo xtask layerscargo xtask wasm # if you touched L0–L6```-Parallel agents: use your own target dir (`CARGO_TARGET_DIR=target/agent-<name>`) to avoid the Cargo build lock, and edit only the crates you own. Keep every `Cargo.toml` valid at all times: the `crates/*` glob means one broken manifest breaks everyone's build.+Parallel agents: use your own target dir (`CARGO_TARGET_DIR=target/agent-<name>`) to avoid the Cargo build lock, and edit only the crates you own. Keep every `Cargo.toml` valid at all times: the `crates/*` glob means one broken manifest breaks everyone's build. **Create or rewrite manifests atomically**: write to a temp file outside `crates/`, then `mv` it into place.## 5. Where things are tracked- `plan/` (local, gitignored): research, parity plan, execution plan, estimates.- `docs/roadmap.md`: milestones M0–M12 and their status.- `log/` (local, gitignored): the dev log.++## 6. Keeping the native format complete++`photocraft-format` deliberately fails to compile when a `photocraft-doc` struct gains a field, so+nothing is silently dropped from `.pcraft` saves. When you add a doc field, add it to+`crates/format/src/manifest.rs` and `convert.rs` with `#[serde(default)]` so older files still load.diff --git a/Cargo.lock b/Cargo.lockindex 3e0e3a1a9..3f4968bba 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -134,6 +134,15 @@ dependencies = ["zerocopy",]+[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]+[[package]]name = "aligned"version = "0.4.3"@@ -192,6 +201,18 @@ dependencies = ["libc",]+[[package]]+name = "anes"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"+[[package]]name = "anyhow"version = "1.0.104"@@ -464,7 +485,7 @@ dependencies = ["log","num-rational","num-traits",- "pastey",+ "pastey 0.1.1","rayon","thiserror 2.0.21","v_frame",@@ -557,6 +578,19 @@ dependencies = ["no_std_io2",]+[[package]]+name = "blake3"+version = "1.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae"+dependencies = [+ "arrayvec",+ "cc",+ "cfg-if",+ "constant_time_eq",+ "cpufeatures",+]+[[package]]name = "block2"version = "0.5.1"@@ -683,6 +717,12 @@ dependencies = ["wayland-client",]+[[package]]+name = "cast"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"+[[package]]name = "cc"version = "1.5.1"@@ -716,6 +756,70 @@ dependencies = ["libc",]+[[package]]+name = "chrono"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"+dependencies = [+ "iana-time-zone",+ "num-traits",+ "serde",+ "windows-link",+]++[[package]]+name = "ciborium"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"+dependencies = [+ "ciborium-io",+ "ciborium-ll",+ "serde",+]++[[package]]+name = "ciborium-io"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"++[[package]]+name = "ciborium-ll"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"+dependencies = [+ "ciborium-io",+ "half",+]++[[package]]+name = "clap"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"+dependencies = [+ "clap_builder",+]++[[package]]+name = "clap_builder"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"+dependencies = [+ "anstyle",+ "clap_lex",+]++[[package]]+name = "clap_lex"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"+[[package]]name = "clipboard-win"version = "5.4.1"@@ -780,6 +884,12 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "constant_time_eq"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"+[[package]]name = "core-foundation"version = "0.9.4"@@ -820,6 +930,15 @@ dependencies = ["libc",]+[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]+[[package]]name = "crc32fast"version = "1.5.2"@@ -829,6 +948,40 @@ dependencies = ["cfg-if",]+[[package]]+name = "criterion"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"+dependencies = [+ "anes",+ "cast",+ "ciborium",+ "clap",+ "criterion-plot",+ "is-terminal",+ "itertools 0.10.5",+ "num-traits",+ "once_cell",+ "oorandom",+ "regex",+ "serde",+ "serde_derive",+ "serde_json",+ "tinytemplate",+ "walkdir",+]++[[package]]+name = "criterion-plot"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"+dependencies = [+ "cast",+ "itertools 0.10.5",+]+[[package]]name = "crossbeam-deque"version = "0.8.8"@@ -866,6 +1019,40 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"+[[package]]+name = "darling"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"+dependencies = [+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 3.0.6",+]++[[package]]+name = "darling_macro"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"+dependencies = [+ "darling_core",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "data-url"version = "0.3.2"@@ -903,6 +1090,17 @@ dependencies = ["objc2 0.6.4",]+[[package]]+name = "displaydoc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "dlib"version = "0.5.3"@@ -933,6 +1131,12 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"+[[package]]+name = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"+[[package]]name = "ecolor"version = "0.36.2"@@ -1354,6 +1558,20 @@ dependencies = ["bytemuck",]+[[package]]+name = "fontique"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6688bc1294fe7117d788937b6c53480169b29c566954af490830d4c09da9516a"+dependencies = [+ "hashbrown 0.17.1",+ "linebender_resource_handle",+ "memmap2",+ "parlance",+ "read-fonts",+ "smallvec",+]+[[package]]name = "foreign-types"version = "0.5.0"@@ -1381,12 +1599,48 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"+[[package]]+name = "futures"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-io",+ "futures-sink",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-channel"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"+dependencies = [+ "futures-core",+ "futures-sink",+]+[[package]]name = "futures-core"version = "0.3.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"+[[package]]+name = "futures-executor"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]+[[package]]name = "futures-io"version = "0.3.34"@@ -1417,6 +1671,12 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "futures-sink"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"+[[package]]name = "futures-task"version = "0.3.34"@@ -1429,9 +1689,13 @@ version = "0.3.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"dependencies = [+ "futures-channel","futures-core",+ "futures-io","futures-macro",+ "futures-sink","futures-task",+ "memchr","pin-project-lite","slab",]@@ -1672,6 +1936,164 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "icu_collections"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"+dependencies = [+ "displaydoc",+ "litemap",+ "serde",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_locale_fallback"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"+dependencies = [+ "icu_locale_core",+ "icu_locale_fallback_data",+ "icu_provider",+ "potential_utf",+ "tinystr",+ "zerovec",+]++[[package]]+name = "icu_locale_fallback_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"++[[package]]+name = "icu_normalizer"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"++[[package]]+name = "icu_properties"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"++[[package]]+name = "icu_provider"+version = "2.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "serde",+ "stable_deref_trait",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_segmenter"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db"+dependencies = [+ "icu_collections",+ "icu_locale_fallback",+ "icu_provider",+ "icu_segmenter_data",+ "potential_utf",+ "smallvec",+ "utf8_iter",+ "zerovec",+]++[[package]]+name = "icu_segmenter_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad"++[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"+[[package]]name = "image"version = "0.25.10"@@ -1723,6 +2145,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"dependencies = ["equivalent","hashbrown 0.17.1",+ "serde",+ "serde_core",][[package]]@@ -1745,6 +2169,17 @@ dependencies = ["once_cell",]+[[package]]+name = "is-terminal"+version = "0.4.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"+dependencies = [+ "hermit-abi",+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "is-wsl"version = "0.4.0"@@ -1755,6 +2190,15 @@ dependencies = ["once_cell",]+[[package]]+name = "itertools"+version = "0.10.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"+dependencies = [+ "either",+]+[[package]]name = "itertools"version = "0.14.0"@@ -1988,6 +2432,12 @@ version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"+[[package]]+name = "litemap"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"+[[package]]name = "litrs"version = "1.0.0"@@ -2071,6 +2521,17 @@ dependencies = ["simd-adler32",]+[[package]]+name = "mio"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"+dependencies = [+ "libc",+ "wasi",+ "windows-sys 0.61.2",+]+[[package]]name = "moxcms"version = "0.8.1"@@ -2585,6 +3046,12 @@ version = "1.21.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"+[[package]]+name = "oorandom"+version = "11.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"+[[package]]name = "open"version = "5.4.4"@@ -2653,6 +3120,39 @@ dependencies = ["windows-link",]+[[package]]+name = "parlance"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b6937eda350acc1a5d05872c3cbf99fe78619c269096e2be3d4a350058639d5"++[[package]]+name = "parley"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22d2ff88bd3f7d68d1d9b09c7e6209f9a8e8c05088295140a2bcf2e9b17038c5"+dependencies = [+ "fontique",+ "harfrust",+ "hashbrown 0.17.1",+ "icu_normalizer",+ "icu_properties",+ "icu_segmenter",+ "linebender_resource_handle",+ "parlance",+ "parley_data",+ "skrifa",+]++[[package]]+name = "parley_data"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1567535334d6ba2d3cde19221ba9a7bd0fabb3cbd99046ddfb10ae061cfcc889"+dependencies = [+ "icu_properties",+]+[[package]]name = "paste"version = "1.0.15"@@ -2665,6 +3165,12 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"+[[package]]+name = "pastey"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"+[[package]]name = "peniko"version = "0.6.1"@@ -2731,6 +3237,7 @@ dependencies = [name = "photocraft"version = "0.1.0"dependencies = [+ "arboard","eframe","egui","log",@@ -2759,9 +3266,38 @@ dependencies = ["serde_json",]+[[package]]+name = "photocraft-automation"+version = "0.1.0"+dependencies = [+ "base64",+ "photocraft-codecs",+ "photocraft-compose",+ "photocraft-doc",+ "photocraft-engine",+ "photocraft-format",+ "photocraft-geom",+ "photocraft-io",+ "rmcp",+ "schemars",+ "serde",+ "serde_json",+ "thiserror 2.0.21",+ "tokio",+]+[[package]]name = "photocraft-cli"version = "0.1.0"+dependencies = [+ "photocraft-automation",+ "photocraft-codecs",+ "photocraft-engine",+ "photocraft-format",+ "photocraft-io",+ "serde_json",+ "tokio",+][[package]]name = "photocraft-codecs"@@ -2792,11 +3328,15 @@ dependencies = [name = "photocraft-compose"version = "0.1.0"dependencies = [+ "criterion","photocraft-color","photocraft-doc","photocraft-geom",+ "photocraft-paint","photocraft-raster",+ "photocraft-vector","proptest",+ "rayon",][[package]]@@ -2811,17 +3351,37 @@ dependencies = [][[package]]-name = "photocraft-engine"+name = "photocraft-engine"+version = "0.1.0"+dependencies = [+ "photocraft-algo",+ "photocraft-color",+ "photocraft-compose",+ "photocraft-doc",+ "photocraft-geom",+ "photocraft-ops",+ "photocraft-paint",+ "photocraft-raster",+ "photocraft-text",+ "photocraft-vector",+ "serde",+ "serde_json",+ "thiserror 2.0.21",+]++[[package]]+name = "photocraft-format"version = "0.1.0"dependencies = [- "photocraft-algo",+ "blake3",+ "flate2",+ "photocraft-codecs","photocraft-color",- "photocraft-compose","photocraft-doc","photocraft-geom",- "photocraft-ops",- "photocraft-paint","photocraft-raster",+ "proptest",+ "ruzstd","serde","serde_json","thiserror 2.0.21",@@ -2834,6 +3394,20 @@ dependencies = ["serde",]+[[package]]+name = "photocraft-gpu"+version = "0.1.0"+dependencies = [+ "log",+ "photocraft-color",+ "photocraft-compose",+ "photocraft-doc",+ "photocraft-geom",+ "photocraft-raster",+ "pollster 1.0.1",+ "wgpu",+]+[[package]]name = "photocraft-io"version = "0.1.0"@@ -2842,9 +3416,12 @@ dependencies = ["photocraft-color","photocraft-compose","photocraft-doc",+ "photocraft-format","photocraft-geom","photocraft-psd","photocraft-raster",+ "photocraft-text",+ "photocraft-vector","proptest","thiserror 2.0.21",]@@ -2896,6 +3473,19 @@ dependencies = ["photocraft-raster",]+[[package]]+name = "photocraft-text"+version = "0.1.0"+dependencies = [+ "parley",+ "photocraft-color",+ "photocraft-doc",+ "photocraft-geom",+ "photocraft-psd",+ "photocraft-raster",+ "skrifa",+]+[[package]]name = "photocraft-ui-egui"version = "0.1.0"@@ -2905,16 +3495,32 @@ dependencies = ["egui_extras","egui_kittest","log",+ "photocraft-algo","photocraft-color","photocraft-compose","photocraft-doc","photocraft-engine","photocraft-geom",+ "photocraft-gpu",+ "photocraft-io","photocraft-raster",+ "photocraft-text",+ "rayon","serde","serde_json",]+[[package]]+name = "photocraft-vector"+version = "0.1.0"+dependencies = [+ "photocraft-color",+ "photocraft-doc",+ "photocraft-geom",+ "photocraft-raster",+ "rayon",+]+[[package]]name = "photocraft-web"version = "0.1.0"@@ -3065,6 +3671,17 @@ dependencies = ["portable-atomic",]+[[package]]+name = "potential_utf"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"+dependencies = [+ "serde_core",+ "writeable",+ "zerovec",+]+[[package]]name = "ppv-lite86"version = "0.2.21"@@ -3400,6 +4017,49 @@ dependencies = ["bitflags 2.13.2",]+[[package]]+name = "ref-cast"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "regex"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]+[[package]]name = "regex-syntax"version = "0.8.11"@@ -3462,6 +4122,42 @@ dependencies = ["bytemuck",]+[[package]]+name = "rmcp"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fae7019994ae0fe4ada40b732f798f3ff26f0f04facb1477f1bf37eb4f18a2d3"+dependencies = [+ "chrono",+ "futures",+ "indexmap",+ "pastey 0.2.3",+ "pin-project-lite",+ "rmcp-macros",+ "schemars",+ "serde",+ "serde_json",+ "thiserror 2.0.21",+ "tokio",+ "tokio-stream",+ "tokio-util",+ "tracing",+ "uuid",+]++[[package]]+name = "rmcp-macros"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7e66877136e969d5a2d561ee5841b17717a0619aebd64abb47a2a2f46e34683"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "serde_json",+ "syn 3.0.6",+]+[[package]]name = "roxmltree"version = "0.20.0"@@ -3533,6 +4229,15 @@ dependencies = ["wait-timeout",]+[[package]]+name = "ruzstd"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a252f5e20f038fe7b4ea53e073e65398d652c864cc162fc77c56c2f13717b888"+dependencies = [+ "twox-hash",+]+[[package]]name = "same-file"version = "1.0.6"@@ -3542,6 +4247,32 @@ dependencies = ["winapi-util",]+[[package]]+name = "schemars"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"+dependencies = [+ "chrono",+ "dyn-clone",+ "ref-cast",+ "schemars_derive",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars_derive"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d98c67716b46af2f0b8cf752abc930f6f9aecfbf671ecfb531db8a31dbe4e2ba"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 3.0.6",+]+[[package]]name = "scoped-tls"version = "1.0.1"@@ -3596,6 +4327,17 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "serde_derive_internals"+version = "0.30.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "serde_json"version = "1.0.151"@@ -3794,6 +4536,16 @@ dependencies = ["serde",]+[[package]]+name = "socket2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "spirv"version = "0.4.0+sdk-1.4.341.0"@@ -3824,6 +4576,12 @@ dependencies = ["float-cmp",]+[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"+[[package]]name = "svgtypes"version = "0.15.3"@@ -3856,6 +4614,17 @@ dependencies = ["unicode-ident",]+[[package]]+name = "synstructure"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "tempfile"version = "3.27.0"@@ -3970,13 +4739,76 @@ dependencies = ["strict-num",]+[[package]]+name = "tinystr"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"+dependencies = [+ "displaydoc",+ "serde_core",+ "zerovec",+]++[[package]]+name = "tinytemplate"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "tokio"version = "1.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"dependencies = [+ "bytes",+ "libc",+ "mio",+ "pin-project-lite",+ "socket2",+ "tokio-macros",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-macros"+version = "2.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "tokio-stream"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "tokio-util"+version = "0.7.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "libc","pin-project-lite",+ "tokio",][[package]]@@ -4054,6 +4886,12 @@ dependencies = ["once_cell",]+[[package]]+name = "twox-hash"+version = "2.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5283634e518fe9e82c7b20520bb4bc209009fd16c82077c802f8111ecbb0117a"+[[package]]name = "type-map"version = "0.5.1"@@ -4126,12 +4964,19 @@ dependencies = ["xmlwriter",]+[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+[[package]]name = "uuid"version = "1.26.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"dependencies = [+ "getrandom 0.4.3","js-sys","serde_core","wasm-bindgen",@@ -4200,6 +5045,12 @@ dependencies = ["winapi-util",]+[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"+[[package]]name = "wasip2"version = "1.0.4+wasi-0.2.12"@@ -4959,6 +5810,12 @@ version = "0.57.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"+[[package]]+name = "writeable"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"+[[package]]name = "x11-dl"version = "2.21.0"@@ -5041,6 +5898,29 @@ version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"+[[package]]+name = "yoke"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "synstructure",+]+[[package]]name = "zbus"version = "5.19.0"@@ -5167,6 +6047,62 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "synstructure",+]++[[package]]+name = "zerotrie"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "zerovec"+version = "0.11.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"+dependencies = [+ "serde",+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "zlib-rs"version = "0.6.8"diff --git a/Cargo.toml b/Cargo.tomlindex c0f30ad8b..6275592e6 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -19,9 +19,14 @@ photocraft-ops = { path = "crates/ops" }photocraft-psd = { path = "crates/psd" }photocraft-codecs = { path = "crates/codecs" }photocraft-compose = { path = "crates/compose" }+photocraft-gpu = { path = "crates/gpu" }photocraft-paint = { path = "crates/paint" }photocraft-algo = { path = "crates/algo" }photocraft-io = { path = "crates/io" }+photocraft-text = { path = "crates/text" }+photocraft-vector = { path = "crates/vector" }+photocraft-format = { path = "crates/format" }+photocraft-automation = { path = "crates/automation" }photocraft-engine = { path = "crates/engine" }photocraft-ui-egui = { path = "crates/ui-egui" }photocraft-testkit = { path = "crates/testkit" }@@ -41,6 +46,7 @@ egui_kittest = "0.36"rfd = "0.17"log = "0.4"rayon = "1"+criterion = { version = "0.5", default-features = false }[workspace.lints.rust]unsafe_code = "deny"diff --git a/apps/photocraft-cli/Cargo.toml b/apps/photocraft-cli/Cargo.tomlindex 9da00eb4a..8e07dcebb 100644--- a/apps/photocraft-cli/Cargo.toml+++ b/apps/photocraft-cli/Cargo.toml@@ -1,5 +1,6 @@[package]name = "photocraft-cli"+description = "Headless Photocraft: convert, inspect, run commands, batch, MCP server"version.workspace = trueedition.workspace = truelicense.workspace = true@@ -7,8 +8,20 @@ license.workspace = true[lints]workspace = true+[lib]+name = "photocraft_cli"+path = "src/lib.rs"+[[bin]]-name = "photocraft"+name = "photocraft-cli"path = "src/main.rs"[dependencies]+photocraft-automation = { path = "../../crates/automation" }+photocraft-engine = { workspace = true }+photocraft-io = { workspace = true }+photocraft-format = { path = "../../crates/format" }+photocraft-codecs = { workspace = true }+serde_json = { workspace = true }+tokio = { version = "1", features = ["rt-multi-thread", "macros"] }+diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rsnew file mode 100644index 000000000..a5ebea9bc--- /dev/null+++ b/apps/photocraft-cli/src/lib.rs@@ -0,0 +1,406 @@+//! Headless Photocraft command line. `run` is the whole program, so it can be+//! tested in-process as well as through the binary.++use std::io::Write;+use std::path::{Path, PathBuf};++use photocraft_automation::{Headless, PhotocraftMcp, files};+use photocraft_io::ExportOptions;+use serde_json::{Value, json};++pub const USAGE: &str = "\+photocraft-cli: headless Photocraft++USAGE:+ photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>]+ Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …).+ photocraft-cli info <file> [--compact]+ Print the document as JSON (size, mode, depth, layer tree).+ photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>]+ Open a file, run engine commands in order, save the result. Each --params+ applies to the preceding --cmd. Prints each command's JSON result.+ photocraft-cli batch --actions <actions.json> --in <dir> --out <dir> [--format <ext>]+ Apply an action list ([{\"command\": id, \"params\": {…}}, …]) to every image in a directory.+ photocraft-cli commands [--json] [--filter <text>]+ List the engine command registry.+ photocraft-cli mcp [--bridge <127.0.0.1:port>]+ Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control <port>`).+";++struct Args {+ positional: Vec<String>,+ flags: Vec<(String, Option<String>)>,+}++const VALUE_FLAGS: &[&str] = &[+ "--format",+ "--quality",+ "--new",+ "--cmd",+ "--params",+ "--out",+ "--actions",+ "--in",+ "--filter",+ "--bridge",+];++fn parse(args: &[String]) -> Result<Args, String> {+ let mut a = Args {+ positional: Vec::new(),+ flags: Vec::new(),+ };+ let mut i = 0;+ while i < args.len() {+ let s = &args[i];+ if let Some((k, v)) = s.split_once('=').filter(|(k, _)| k.starts_with("--")) {+ a.flags.push((k.to_owned(), Some(v.to_owned())));+ } else if VALUE_FLAGS.contains(&s.as_str()) {+ let v = args+ .get(i + 1)+ .ok_or_else(|| format!("{s} needs a value"))?;+ a.flags.push((s.clone(), Some(v.clone())));+ i += 1;+ } else if s.starts_with("--") {+ a.flags.push((s.clone(), None));+ } else {+ a.positional.push(s.clone());+ }+ i += 1;+ }+ Ok(a)+}++impl Args {+ fn get(&self, k: &str) -> Option<&str> {+ self.flags+ .iter()+ .rev()+ .find(|(f, _)| f == k)+ .and_then(|(_, v)| v.as_deref())+ }+ fn has(&self, k: &str) -> bool {+ self.flags.iter().any(|(f, _)| f == k)+ }+}++type R = Result<(), String>;++/// Run the CLI. Returns the process exit code (0 ok, 1 failure, 2 usage).+pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {+ let Some(cmd) = args.first() else {+ let _ = write!(err, "{USAGE}");+ return 2;+ };+ let parsed = match parse(&args[1..]) {+ Ok(p) => p,+ Err(e) => {+ let _ = writeln!(err, "error: {e}\n\n{USAGE}");+ return 2;+ }+ };+ let r = match cmd.as_str() {+ "convert" => convert(&parsed, out, err),+ "info" => info(&parsed, out),+ "run" => run_cmds(&parsed, out, err),+ "batch" => batch(&parsed, out, err),+ "commands" => commands(&parsed, out),+ "mcp" => mcp(&parsed),+ "-h" | "--help" | "help" => {+ let _ = write!(out, "{USAGE}");+ return 0;+ }+ "--version" | "version" => {+ let _ = writeln!(out, "photocraft-cli {}", env!("CARGO_PKG_VERSION"));+ return 0;+ }+ other => {+ let _ = writeln!(err, "error: unknown command `{other}`\n\n{USAGE}");+ return 2;+ }+ };+ match r {+ Ok(()) => 0,+ Err(e) => {+ let _ = writeln!(err, "error: {e}");+ 1+ }+ }+}++fn export_opts(a: &Args) -> Result<ExportOptions, String> {+ let mut o = ExportOptions::default();+ if let Some(q) = a.get("--quality") {+ let q: u8 = q.parse().map_err(|_| format!("bad --quality `{q}`"))?;+ o.encode.jpeg_quality = q.clamp(1, 100);+ }+ Ok(o)+}++fn warn_all(err: &mut dyn Write, ws: &[String]) {+ for w in ws {+ let _ = writeln!(err, "warning: {w}");+ }+}++fn convert(a: &Args, _out: &mut dyn Write, err: &mut dyn Write) -> R {+ let [input, output] = a.positional.as_slice() else {+ return Err("convert needs <in> <out>".into());+ };+ let o = files::open(Path::new(input)).map_err(|e| e.to_string())?;+ warn_all(err, &o.warnings);+ let ws = files::save(+ &o.document,+ Path::new(output),+ a.get("--format"),+ &export_opts(a)?,+ None,+ )+ .map_err(|e| e.to_string())?;+ warn_all(err, &ws);+ Ok(())+}++fn print_json(out: &mut dyn Write, v: &Value, compact: bool) -> R {+ let s = if compact {+ serde_json::to_string(v)+ } else {+ serde_json::to_string_pretty(v)+ }+ .map_err(|e| e.to_string())?;+ writeln!(out, "{s}").map_err(|e| e.to_string())+}++fn info(a: &Args, out: &mut dyn Write) -> R {+ let [file] = a.positional.as_slice() else {+ return Err("info needs <file>".into());+ };+ let mut h = Headless::new();+ let opened = h.open(Path::new(file)).map_err(|e| e.to_string())?;+ let mut doc = h.inspect(None).map_err(|e| e.to_string())?;+ doc["warnings"] = opened["warnings"].clone();+ doc["file"] = json!(file);+ // Drop per-session noise.+ if let Value::Object(m) = &mut doc {+ for k in ["history", "canUndo", "canRedo", "revision"] {+ m.remove(k);+ }+ }+ print_json(out, &doc, a.has("--compact"))+}++/// `(id, params)` pairs from repeated `--cmd`/`--params` flags.+fn command_list(a: &Args) -> Result<Vec<(String, Value)>, String> {+ let mut cmds: Vec<(String, Value)> = Vec::new();+ for (k, v) in &a.flags {+ match (k.as_str(), v) {+ ("--cmd", Some(id)) => cmds.push((id.clone(), json!({}))),+ ("--params", Some(p)) => {+ let last = cmds.last_mut().ok_or("--params must follow a --cmd")?;+ last.1 = serde_json::from_str(p)+ .map_err(|e| format!("bad --params JSON for `{}`: {e}", last.0))?;+ }+ _ => {}+ }+ }+ Ok(cmds)+}++fn run_cmds(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {+ let mut h = Headless::new();+ match (a.positional.as_slice(), a.get("--new")) {+ ([file], None) => {+ let o = h.open(Path::new(file)).map_err(|e| e.to_string())?;+ let ws: Vec<String> = serde_json::from_value(o["warnings"].clone()).unwrap_or_default();+ warn_all(err, &ws);+ }+ ([], Some(new)) => {+ let p: Value = serde_json::from_str(new).map_err(|e| format!("bad --new JSON: {e}"))?;+ h.command_run("file.new", p).map_err(|e| e.to_string())?;+ }+ _ => return Err("run needs exactly one of <file> or --new <json>".into()),+ }+ let cmds = command_list(a)?;+ if cmds.is_empty() && a.get("--out").is_none() {+ return Err("run needs at least one --cmd (or --out)".into());+ }+ for (id, params) in cmds {+ let r = h+ .command_run(&id, params)+ .map_err(|e| format!("`{id}`: {e}"))?;+ print_json(out, &json!({"command": id, "result": r}), true)?;+ }+ if let Some(o) = a.get("--out") {+ let r = h+ .save(+ None,+ Some(Path::new(o)),+ a.get("--format"),+ &export_opts(a)?,+ )+ .map_err(|e| e.to_string())?;+ let ws: Vec<String> = serde_json::from_value(r["warnings"].clone()).unwrap_or_default();+ warn_all(err, &ws);+ }+ Ok(())+}++/// Parse an actions file: `[{"command": id, "params": {…}}]` or+/// `{"actions": [...]}`; `"id"` is accepted for `"command"`.+pub fn parse_actions(text: &str) -> Result<Vec<(String, Value)>, String> {+ let v: Value = serde_json::from_str(text).map_err(|e| format!("actions JSON: {e}"))?;+ let list = match &v {+ Value::Array(a) => a.clone(),+ Value::Object(m) => m+ .get("actions")+ .and_then(Value::as_array)+ .cloned()+ .ok_or("actions JSON: expected an array or {\"actions\": [...]}")?,+ _ => return Err("actions JSON: expected an array".into()),+ };+ list.into_iter()+ .enumerate()+ .map(|(i, a)| {+ let id = a+ .get("command")+ .or_else(|| a.get("id"))+ .and_then(Value::as_str)+ .ok_or_else(|| format!("action {i}: missing \"command\""))?;+ Ok((+ id.to_owned(),+ a.get("params").cloned().unwrap_or_else(|| json!({})),+ ))+ })+ .collect()+}++fn is_input(p: &Path) -> bool {+ let known = |e: &str| {+ matches!(e, "pcraft" | "psd" | "psb")+ || photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read)+ };+ p.is_file()+ && p.extension()+ .is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))+}++fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {+ let actions_path = a.get("--actions").ok_or("batch needs --actions <file>")?;+ let in_dir = PathBuf::from(a.get("--in").ok_or("batch needs --in <dir>")?);+ let out_dir = PathBuf::from(a.get("--out").ok_or("batch needs --out <dir>")?);+ let text = std::fs::read_to_string(actions_path).map_err(|e| format!("{actions_path}: {e}"))?;+ let actions = parse_actions(&text)?;+ let opts = export_opts(a)?;+ std::fs::create_dir_all(&out_dir).map_err(|e| e.to_string())?;+ let mut inputs: Vec<PathBuf> = std::fs::read_dir(&in_dir)+ .map_err(|e| format!("{}: {e}", in_dir.display()))?+ .flatten()+ .map(|e| e.path())+ .filter(|p| is_input(p))+ .collect();+ inputs.sort();+ let (mut ok, mut failed) = (0, 0);+ for input in &inputs {+ let ext = a+ .get("--format")+ .map(str::to_owned)+ .or_else(|| input.extension().map(|e| e.to_string_lossy().into_owned()))+ .unwrap_or_else(|| "png".into());+ let stem = input+ .file_stem()+ .map(|s| s.to_string_lossy().into_owned())+ .unwrap_or_default();+ let target = out_dir.join(format!("{stem}.{ext}"));+ let r = (|| -> Result<Vec<String>, String> {+ let mut h = Headless::new();+ h.open(input).map_err(|e| e.to_string())?;+ for (id, p) in &actions {+ h.command_run(id, p.clone())+ .map_err(|e| format!("`{id}`: {e}"))?;+ }+ let r = h+ .save(None, Some(&target), Some(&ext), &opts)+ .map_err(|e| e.to_string())?;+ Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default())+ })();+ match r {+ Ok(ws) => {+ ok += 1;+ let _ = writeln!(out, "ok {} -> {}", input.display(), target.display());+ warn_all(err, &ws);+ }+ Err(e) => {+ failed += 1;+ let _ = writeln!(err, "FAIL {}: {e}", input.display());+ }+ }+ }+ let _ = writeln!(out, "{ok} succeeded, {failed} failed");+ if failed > 0 {+ Err(format!("{failed} file(s) failed"))+ } else {+ Ok(())+ }+}++fn commands(a: &Args, out: &mut dyn Write) -> R {+ let h = Headless::new();+ let list = h.command_list();+ let needle = a.get("--filter").map(str::to_lowercase);+ let items: Vec<&Value> = list+ .as_array()+ .map(|v| v.iter().collect::<Vec<_>>())+ .unwrap_or_default()+ .into_iter()+ .filter(|c| {+ needle.as_ref().is_none_or(|n| {+ format!(+ "{} {}",+ c["id"].as_str().unwrap_or(""),+ c["label"].as_str().unwrap_or("")+ )+ .to_lowercase()+ .contains(n)+ })+ })+ .collect();+ if a.has("--json") {+ return print_json(+ out,+ &Value::Array(items.into_iter().cloned().collect()),+ false,+ );+ }+ for c in items {+ let menu = c["menu"]+ .as_array()+ .map(|m| {+ m.iter()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>()+ .join(" > ")+ })+ .unwrap_or_default();+ writeln!(+ out,+ "{:<44} {:<32} {}",+ c["id"].as_str().unwrap_or(""),+ c["label"].as_str().unwrap_or(""),+ menu+ )+ .map_err(|e| e.to_string())?;+ }+ Ok(())+}++fn mcp(a: &Args) -> R {+ let server = match a.get("--bridge") {+ Some(addr) => PhotocraftMcp::bridge(addr).map_err(|e| e.to_string())?,+ None => PhotocraftMcp::headless(),+ };+ let rt = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .build()+ .map_err(|e| e.to_string())?;+ rt.block_on(server.serve_stdio()).map_err(|e| e.to_string())+}diff --git a/apps/photocraft-cli/src/main.rs b/apps/photocraft-cli/src/main.rsindex f328e4d9d..5585399e6 100644--- a/apps/photocraft-cli/src/main.rs+++ b/apps/photocraft-cli/src/main.rs@@ -1 +1,5 @@-fn main() {}+fn main() {+ let args: Vec<String> = std::env::args().skip(1).collect();+ let code = photocraft_cli::run(&args, &mut std::io::stdout(), &mut std::io::stderr());+ std::process::exit(code);+}diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rsnew file mode 100644index 000000000..c4573c5db--- /dev/null+++ b/apps/photocraft-cli/tests/cli.rs@@ -0,0 +1,334 @@+//! Process-level tests of the `photocraft-cli` binary.++use std::io::{BufRead, BufReader, Write};+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++use serde_json::{Value, json};++fn bin() -> Command {+ Command::new(env!("CARGO_BIN_EXE_photocraft-cli"))+}++fn tmp(name: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("pc-cli-{}-{name}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++fn write_png(path: &Path, w: u32, h: u32, seed: u8) {+ let data: Vec<u8> = (0..w * h * 4)+ .map(|i| (i as u8).wrapping_mul(seed).wrapping_add(seed))+ .collect();+ let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgba, data)+ .unwrap();+ std::fs::write(+ path,+ photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default())+ .unwrap(),+ )+ .unwrap();+}++fn ok(cmd: &mut Command) -> (String, String) {+ let o = cmd.output().unwrap();+ let (out, err) = (+ String::from_utf8_lossy(&o.stdout).into_owned(),+ String::from_utf8_lossy(&o.stderr).into_owned(),+ );+ assert!(+ o.status.success(),+ "exit {:?}\nstdout: {out}\nstderr: {err}",+ o.status+ );+ (out, err)+}++#[test]+fn usage_and_unknown_command() {+ let o = bin().output().unwrap();+ assert_eq!(o.status.code(), Some(2));+ assert!(String::from_utf8_lossy(&o.stderr).contains("USAGE"));+ let o = bin().arg("frobnicate").output().unwrap();+ assert_eq!(o.status.code(), Some(2));+ let (out, _) = ok(bin().arg("--help"));+ assert!(out.contains("convert"));+ let (out, _) = ok(bin().arg("--version"));+ assert!(out.starts_with("photocraft-cli "));+}++#[test]+fn convert_png_pcraft_png_is_lossless() {+ let d = tmp("convert");+ let (a, b, c) = (d.join("a.png"), d.join("b.pcraft"), d.join("c.png"));+ write_png(&a, 37, 23, 7);+ ok(bin().args(["convert"]).arg(&a).arg(&b));+ assert!(photocraft_format::is_pcraft(&std::fs::read(&b).unwrap()));+ ok(bin().args(["convert"]).arg(&b).arg(&c));+ let x = photocraft_codecs::decode(&std::fs::read(&a).unwrap()).unwrap();+ let y = photocraft_codecs::decode(&std::fs::read(&c).unwrap()).unwrap();+ assert_eq!(x.to_rgba8(), y.to_rgba8());+ // Format override and lossy warning path.+ ok(bin()+ .args(["convert"])+ .arg(&a)+ .arg(d.join("out.bin"))+ .args(["--format", "jpg", "--quality", "60"]));+ assert!(+ photocraft_codecs::detect(&std::fs::read(d.join("out.bin")).unwrap())+ == Some(photocraft_codecs::Format::Jpeg)+ );+ std::fs::remove_dir_all(d).unwrap();+}++#[test]+fn convert_errors() {+ let d = tmp("converr");+ let o = bin()+ .args(["convert", "/missing/in.png"])+ .arg(d.join("x.png"))+ .output()+ .unwrap();+ assert_eq!(o.status.code(), Some(1));+ let o = bin().args(["convert", "only-one"]).output().unwrap();+ assert_eq!(o.status.code(), Some(1));+ std::fs::remove_dir_all(d).unwrap();+}++#[test]+fn info_prints_layer_tree_json() {+ let d = tmp("info");+ let a = d.join("a.png");+ write_png(&a, 10, 6, 3);+ let (out, _) = ok(bin().arg("info").arg(&a));+ let v: Value = serde_json::from_str(&out).unwrap();+ assert_eq!(v["width"], 10);+ assert_eq!(v["height"], 6);+ assert_eq!(v["layers"][0]["name"], "Background");+ assert!(v.get("history").is_none());+ let (out, _) = ok(bin().arg("info").arg(&a).arg("--compact"));+ assert_eq!(out.trim().lines().count(), 1);+ std::fs::remove_dir_all(d).unwrap();+}++#[test]+fn run_commands_and_save() {+ let d = tmp("run");+ let out_pc = d.join("r.pcraft");+ let (out, _) = ok(bin()+ .args(["run", "--new", r#"{"width":40,"height":30,"name":"Run"}"#])+ .args(["--cmd", "layer.new.layer", "--params", r#"{"name":"Ink"}"#])+ .args([+ "--cmd",+ "paint.stroke",+ "--params",+ r##"{"points":[[2,2,1],[30,20,1]],"size":5,"color":"#00ff00"}"##,+ ])+ .args(["--cmd", "document.inspect"])+ .arg("--out")+ .arg(&out_pc));+ let lines: Vec<Value> = out+ .lines()+ .map(|l| serde_json::from_str(l).unwrap())+ .collect();+ assert_eq!(lines.len(), 3);+ assert_eq!(lines[2]["command"], "document.inspect");+ let (info, _) = ok(bin().arg("info").arg(&out_pc));+ let v: Value = serde_json::from_str(&info).unwrap();+ assert_eq!(v["name"], "Run");+ let names: Vec<&str> = v["layers"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|l| l["name"].as_str())+ .collect();+ assert_eq!(names, ["Ink", "Background"]);+ // Continue from the saved file and export PNG.+ let png = d.join("r.png");+ ok(bin()+ .arg("run")+ .arg(&out_pc)+ .args(["--cmd", "layer.new.layer"])+ .arg("--out")+ .arg(&png));+ assert_eq!(+ photocraft_codecs::decode(&std::fs::read(&png).unwrap())+ .unwrap()+ .dimensions(),+ (40, 30)+ );+ std::fs::remove_dir_all(d).unwrap();+}++#[test]+fn run_errors() {+ let o = bin()+ .args(["run", "--new", "{}", "--cmd", "no.such"])+ .output()+ .unwrap();+ assert_eq!(o.status.code(), Some(1));+ assert!(String::from_utf8_lossy(&o.stderr).contains("unknown command"));+ let o = bin()+ .args(["run", "--new", "{}", "--params", "{}"])+ .output()+ .unwrap();+ assert_eq!(o.status.code(), Some(1));+ let o = bin()+ .args(["run", "--new", "{", "--cmd", "x"])+ .output()+ .unwrap();+ assert_eq!(o.status.code(), Some(1));+}++#[test]+fn batch_applies_actions_to_directory() {+ let d = tmp("batch");+ let (inp, outp) = (d.join("in"), d.join("out"));+ std::fs::create_dir_all(&inp).unwrap();+ write_png(&inp.join("one.png"), 12, 8, 1);+ write_png(&inp.join("two.png"), 9, 9, 2);+ std::fs::write(inp.join("notes.txt"), "ignored").unwrap();+ let actions = d.join("actions.json");+ std::fs::write(+ &actions,+ json!([{"command": "layer.new.layer", "params": {"name": "Batch"}}]).to_string(),+ )+ .unwrap();+ let (out, _) = ok(bin()+ .args(["batch", "--actions"])+ .arg(&actions)+ .arg("--in")+ .arg(&inp)+ .arg("--out")+ .arg(&outp)+ .args(["--format", "pcraft"]));+ assert!(out.contains("2 succeeded, 0 failed"), "{out}");+ for n in ["one", "two"] {+ let (info, _) = ok(bin().arg("info").arg(outp.join(format!("{n}.pcraft"))));+ let v: Value = serde_json::from_str(&info).unwrap();+ assert_eq!(v["layers"][0]["name"], "Batch");+ }+ // A failing action reports and exits 1.+ std::fs::write(&actions, r#"{"actions":[{"id":"no.such.command"}]}"#).unwrap();+ let o = bin()+ .args(["batch", "--actions"])+ .arg(&actions)+ .arg("--in")+ .arg(&inp)+ .arg("--out")+ .arg(&outp)+ .output()+ .unwrap();+ assert_eq!(o.status.code(), Some(1));+ assert!(String::from_utf8_lossy(&o.stderr).contains("FAIL"));+ std::fs::remove_dir_all(d).unwrap();+}++#[test]+fn parse_actions_formats() {+ let a =+ photocraft_cli::parse_actions(r#"[{"command":"a","params":{"x":1}},{"id":"b"}]"#).unwrap();+ assert_eq!(+ a,+ vec![+ ("a".to_string(), json!({"x":1})),+ ("b".to_string(), json!({}))+ ]+ );+ assert!(+ photocraft_cli::parse_actions(r#"{"actions":[{"command":"c"}]}"#)+ .unwrap()+ .len()+ == 1+ );+ assert!(photocraft_cli::parse_actions(r#"[{"params":{}}]"#).is_err());+ assert!(photocraft_cli::parse_actions("7").is_err());+}++#[test]+fn commands_listing() {+ let (out, _) = ok(bin().arg("commands"));+ assert!(out.contains("file.new"));+ let (out, _) = ok(bin().args(["commands", "--json", "--filter", "layer.new"]));+ let v: Value = serde_json::from_str(&out).unwrap();+ assert!(v.as_array().unwrap().iter().all(|c| {+ c["id"].as_str().unwrap().contains("layer.new")+ || c["label"]+ .as_str()+ .unwrap()+ .to_lowercase()+ .contains("layer.new")+ }));+}++#[test]+fn in_process_run_matches_binary() {+ let mut out = Vec::new();+ let mut err = Vec::new();+ let code = photocraft_cli::run(+ &["commands".into(), "--filter".into(), "file.new".into()],+ &mut out,+ &mut err,+ );+ assert_eq!(code, 0);+ assert!(String::from_utf8(out).unwrap().contains("file.new"));+}++#[test]+fn mcp_stdio_handshake_and_tool_call() {+ let mut child = bin()+ .arg("mcp")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .unwrap();+ let mut stdin = child.stdin.take().unwrap();+ let mut stdout = BufReader::new(child.stdout.take().unwrap());+ let mut send = |v: Value| {+ writeln!(stdin, "{v}").unwrap();+ stdin.flush().unwrap();+ };+ let mut recv = |id: u64| -> Value {+ loop {+ let mut line = String::new();+ assert!(stdout.read_line(&mut line).unwrap() > 0, "server closed");+ let v: Value = serde_json::from_str(&line).unwrap();+ if v["id"] == id {+ return v;+ }+ }+ };+ send(+ json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{+ "protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}),+ );+ let init = recv(1);+ assert_eq!(init["result"]["serverInfo"]["name"], "photocraft", "{init}");+ send(json!({"jsonrpc":"2.0","method":"notifications/initialized"}));+ send(json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}));+ let tools = recv(2);+ let names: Vec<&str> = tools["result"]["tools"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|t| t["name"].as_str())+ .collect();+ assert!(+ names.contains(&"command_run") && names.contains(&"doc_render_preview"),+ "{names:?}"+ );+ send(+ json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"doc_new","arguments":{"width":8,"height":8}}}),+ );+ let r = recv(3);+ assert_ne!(r["result"]["isError"], true, "{r}");+ send(+ json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"doc_render_preview","arguments":{}}}),+ );+ let r = recv(4);+ assert_eq!(r["result"]["content"][0]["type"], "image", "{r}");+ let _ = child.kill();+ let _ = child.wait();+}diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rsindex d5c018c60..df84dd9cc 100644--- a/apps/photocraft-web/src/web.rs+++ b/apps/photocraft-web/src/web.rs@@ -127,8 +127,12 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {.map(|r| r.document).map_err(|e| e.to_string())})),- export: Some(Box::new(|doc: &Document, path: &str| {- photocraft_io::export(doc, path, &Default::default())+ export: Some(Box::new(|doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings| {+ let mut opts = photocraft_io::ExportOptions::default();+ if let Some(q) = settings.jpeg_quality {+ opts.encode.jpeg_quality = q;+ }+ photocraft_io::export(doc, path, &opts).map(|r| r.bytes).map_err(|e| e.to_string())})),diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.tomlindex 28d31ad1f..405134fd0 100644--- a/apps/photocraft/Cargo.toml+++ b/apps/photocraft/Cargo.toml@@ -25,3 +25,4 @@ log = { workspace = true }[target.'cfg(not(target_arch = "wasm32"))'.dependencies]rfd = { workspace = true }+arboard = "3"diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rsindex a86083d68..01978b88f 100644--- a/apps/photocraft/src/services.rs+++ b/apps/photocraft/src/services.rs@@ -11,7 +11,13 @@ const IMAGE_EXTS: &[&str] = &["psd", "psb", "png", "jpg", "jpeg", "tif", "tiff",pub fn native() -> Services {Services {import: Some(Box::new(|name: &str, bytes: &[u8]| photocraft_io::import(name, bytes).map(|r| r.document).map_err(|e| e.to_string()))),- export: Some(Box::new(|doc: &Document, path: &str| photocraft_io::export(doc, path, &Default::default()).map(|r| r.bytes).map_err(|e| e.to_string()))),+ export: Some(Box::new(|doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings| {+ let mut opts = photocraft_io::ExportOptions::default();+ if let Some(q) = settings.jpeg_quality {+ opts.encode.jpeg_quality = q;+ }+ photocraft_io::export(doc, path, &opts).map(|r| r.bytes).map_err(|e| e.to_string())+ })),pick_open: Some(Box::new(|| {let path = rfd::FileDialog::new().add_filter("Images", IMAGE_EXTS).pick_file()?;let bytes = std::fs::read(&path).ok()?;@@ -31,6 +37,14 @@ pub fn native() -> Services {photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string())})),inbox: None,+ clipboard_set_image: Some(Box::new(|w: u32, h: u32, px: &[u8]| {+ let mut cb = arboard::Clipboard::new().map_err(|e| e.to_string())?;+ cb.set_image(arboard::ImageData { width: w as usize, height: h as usize, bytes: std::borrow::Cow::Borrowed(px) }).map_err(|e| e.to_string())+ })),+ clipboard_get_image: Some(Box::new(|| {+ let img = arboard::Clipboard::new().ok()?.get_image().ok()?;+ Some((img.width as u32, img.height as u32, img.bytes.into_owned()))+ })),}}diff --git a/assets/icons/align-center.svg b/assets/icons/align-center.svgnew file mode 100644index 000000000..a7b6d5395--- /dev/null+++ b/assets/icons/align-center.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M21 5H3" />+ <path d="M17 12H7" />+ <path d="M19 19H5" />+</svg>diff --git a/assets/icons/align-justify.svg b/assets/icons/align-justify.svgnew file mode 100644index 000000000..1848d500d--- /dev/null+++ b/assets/icons/align-justify.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M3 5h18" />+ <path d="M3 12h18" />+ <path d="M3 19h18" />+</svg>diff --git a/assets/icons/align-left.svg b/assets/icons/align-left.svgnew file mode 100644index 000000000..703d45510--- /dev/null+++ b/assets/icons/align-left.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M21 5H3" />+ <path d="M15 12H3" />+ <path d="M17 19H3" />+</svg>diff --git a/assets/icons/align-right.svg b/assets/icons/align-right.svgnew file mode 100644index 000000000..fba40f367--- /dev/null+++ b/assets/icons/align-right.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M21 5H3" />+ <path d="M21 12H9" />+ <path d="M21 19H7" />+</svg>diff --git a/assets/icons/ban.svg b/assets/icons/ban.svgnew file mode 100644index 000000000..301db8040--- /dev/null+++ b/assets/icons/ban.svg@@ -0,0 +1,14 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="10" />+ <path d="M4.929 4.929 19.07 19.071" />+</svg>diff --git a/assets/icons/circle.svg b/assets/icons/circle.svgnew file mode 100644index 000000000..1717bb4ba--- /dev/null+++ b/assets/icons/circle.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="10" />+</svg>diff --git a/assets/icons/cloud.svg b/assets/icons/cloud.svgnew file mode 100644index 000000000..96c52fc8e--- /dev/null+++ b/assets/icons/cloud.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z" />+</svg>diff --git a/assets/icons/diamond.svg b/assets/icons/diamond.svgnew file mode 100644index 000000000..28756d1d8--- /dev/null+++ b/assets/icons/diamond.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z" />+</svg>diff --git a/assets/icons/flame.svg b/assets/icons/flame.svgnew file mode 100644index 000000000..9a7749168--- /dev/null+++ b/assets/icons/flame.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4" />+</svg>diff --git a/assets/icons/grid-2x2.svg b/assets/icons/grid-2x2.svgnew file mode 100644index 000000000..097eb5c22--- /dev/null+++ b/assets/icons/grid-2x2.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M12 3v18" />+ <path d="M3 12h18" />+ <rect x="3" y="3" width="18" height="18" rx="2" />+</svg>diff --git a/assets/icons/lasso-select.svg b/assets/icons/lasso-select.svgnew file mode 100644index 000000000..d5f7c99ab--- /dev/null+++ b/assets/icons/lasso-select.svg@@ -0,0 +1,17 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M7 22a5 5 0 0 1-2-4" />+ <path d="M7 16.93c.96.43 1.96.74 2.99.91" />+ <path d="M3.34 14A6.8 6.8 0 0 1 2 10c0-4.42 4.48-8 10-8s10 3.58 10 8a7.19 7.19 0 0 1-.33 2" />+ <path d="M5 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z" />+ <path d="M14.33 22h-.09a.35.35 0 0 1-.24-.32v-10a.34.34 0 0 1 .33-.34c.08 0 .15.03.21.08l7.34 6a.33.33 0 0 1-.21.59h-4.49l-2.57 3.85a.35.35 0 0 1-.28.14z" />+</svg>diff --git a/assets/icons/lollipop.svg b/assets/icons/lollipop.svgnew file mode 100644index 000000000..0a3fda956--- /dev/null+++ b/assets/icons/lollipop.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="11" cy="11" r="8" />+ <path d="m21 21-4.3-4.3" />+ <path d="M11 11a2 2 0 0 0 4 0 4 4 0 0 0-8 0 6 6 0 0 0 12 0" />+</svg>diff --git a/assets/icons/pentagon.svg b/assets/icons/pentagon.svgnew file mode 100644index 000000000..4cbc0830d--- /dev/null+++ b/assets/icons/pentagon.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M10.83 2.38a2 2 0 0 1 2.34 0l8 5.74a2 2 0 0 1 .73 2.25l-3.04 9.26a2 2 0 0 1-1.9 1.37H7.04a2 2 0 0 1-1.9-1.37L2.1 10.37a2 2 0 0 1 .73-2.25z" />+</svg>diff --git a/assets/icons/play.svg b/assets/icons/play.svgnew file mode 100644index 000000000..199743ed2--- /dev/null+++ b/assets/icons/play.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z" />+</svg>diff --git a/assets/icons/pointer.svg b/assets/icons/pointer.svgnew file mode 100644index 000000000..fdde19f4a--- /dev/null+++ b/assets/icons/pointer.svg@@ -0,0 +1,17 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M22 14a8 8 0 0 1-8 8" />+ <path d="M18 11v-1a2 2 0 0 0-2-2a2 2 0 0 0-2 2" />+ <path d="M14 10V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1" />+ <path d="M10 9.5V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v10" />+ <path d="M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15" />+</svg>diff --git a/assets/icons/rectangle-horizontal.svg b/assets/icons/rectangle-horizontal.svgnew file mode 100644index 000000000..71d1275a3--- /dev/null+++ b/assets/icons/rectangle-horizontal.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="20" height="12" x="2" y="6" rx="2" />+</svg>diff --git a/assets/icons/rotate-cw.svg b/assets/icons/rotate-cw.svgnew file mode 100644index 000000000..6795f1576--- /dev/null+++ b/assets/icons/rotate-cw.svg@@ -0,0 +1,14 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" />+ <path d="M21 3v5h-5" />+</svg>diff --git a/assets/icons/scaling.svg b/assets/icons/scaling.svgnew file mode 100644index 000000000..6c10bcdd0--- /dev/null+++ b/assets/icons/scaling.svg@@ -0,0 +1,16 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />+ <path d="M14 15H9v-5" />+ <path d="M16 3h5v5" />+ <path d="M21 3 9 15" />+</svg>diff --git a/assets/icons/scan-line.svg b/assets/icons/scan-line.svgnew file mode 100644index 000000000..3e8da0936--- /dev/null+++ b/assets/icons/scan-line.svg@@ -0,0 +1,17 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M3 7V5a2 2 0 0 1 2-2h2" />+ <path d="M17 3h2a2 2 0 0 1 2 2v2" />+ <path d="M21 17v2a2 2 0 0 1-2 2h-2" />+ <path d="M7 21H5a2 2 0 0 1-2-2v-2" />+ <path d="M7 12h10" />+</svg>diff --git a/assets/icons/slash.svg b/assets/icons/slash.svgnew file mode 100644index 000000000..391dc6ad0--- /dev/null+++ b/assets/icons/slash.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M22 2 2 22" />+</svg>diff --git a/assets/icons/spline.svg b/assets/icons/spline.svgnew file mode 100644index 000000000..2841d121a--- /dev/null+++ b/assets/icons/spline.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="19" cy="5" r="2" />+ <circle cx="5" cy="19" r="2" />+ <path d="M5 17A12 12 0 0 1 17 5" />+</svg>diff --git a/assets/icons/square-dashed-mouse-pointer.svg b/assets/icons/square-dashed-mouse-pointer.svgnew file mode 100644index 000000000..e09b4ea58--- /dev/null+++ b/assets/icons/square-dashed-mouse-pointer.svg@@ -0,0 +1,22 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M12.034 12.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.943l-3.444 1.068a1 1 0 0 0-.66.66l-1.067 3.443a.5.5 0 0 1-.943.033z" />+ <path d="M5 3a2 2 0 0 0-2 2" />+ <path d="M19 3a2 2 0 0 1 2 2" />+ <path d="M5 21a2 2 0 0 1-2-2" />+ <path d="M9 3h1" />+ <path d="M9 21h2" />+ <path d="M14 3h1" />+ <path d="M3 9v1" />+ <path d="M21 9v2" />+ <path d="M3 14v1" />+</svg>diff --git a/assets/icons/text-cursor.svg b/assets/icons/text-cursor.svgnew file mode 100644index 000000000..2aadd3ca5--- /dev/null+++ b/assets/icons/text-cursor.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M17 22h-1a4 4 0 0 1-4-4V6a4 4 0 0 1 4-4h1" />+ <path d="M7 22h1a4 4 0 0 0 4-4" />+ <path d="M7 2h1a4 4 0 0 1 4 4" />+</svg>diff --git a/assets/icons/triangle-alert.svg b/assets/icons/triangle-alert.svgnew file mode 100644index 000000000..3232fb062--- /dev/null+++ b/assets/icons/triangle-alert.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" />+ <path d="M12 9v4" />+ <path d="M12 17h.01" />+</svg>diff --git a/assets/icons/triangle-right.svg b/assets/icons/triangle-right.svgnew file mode 100644index 000000000..1bc536513--- /dev/null+++ b/assets/icons/triangle-right.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M22 18a2 2 0 0 1-2 2H3c-1.1 0-1.3-.6-.4-1.3L20.4 4.3c.9-.7 1.6-.4 1.6.7Z" />+</svg>diff --git a/assets/icons/triangle.svg b/assets/icons/triangle.svgnew file mode 100644index 000000000..728f1fcc1--- /dev/null+++ b/assets/icons/triangle.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M13.73 4a2 2 0 0 0-3.46 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" />+</svg>diff --git a/assets/icons/unlink.svg b/assets/icons/unlink.svgnew file mode 100644index 000000000..a89aa2f1c--- /dev/null+++ b/assets/icons/unlink.svg@@ -0,0 +1,18 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71" />+ <path d="m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71" />+ <line x1="8" x2="8" y1="2" y2="5" />+ <line x1="2" x2="5" y1="8" y2="8" />+ <line x1="16" x2="16" y1="19" y2="22" />+ <line x1="19" x2="22" y1="16" y2="16" />+</svg>diff --git a/assets/icons/wand.svg b/assets/icons/wand.svgnew file mode 100644index 000000000..29d5dc5c5--- /dev/null+++ b/assets/icons/wand.svg@@ -0,0 +1,21 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M15 4V2" />+ <path d="M15 16v-2" />+ <path d="M8 9h2" />+ <path d="M20 9h2" />+ <path d="M17.8 11.8 19 13" />+ <path d="M15 9h.01" />+ <path d="M17.8 6.2 19 5" />+ <path d="m3 21 9-9" />+ <path d="M12.2 6.2 11 5" />+</svg>diff --git a/crates/algo/examples/bench_retouch.rs b/crates/algo/examples/bench_retouch.rsnew file mode 100644index 000000000..b36c8af92--- /dev/null+++ b/crates/algo/examples/bench_retouch.rs@@ -0,0 +1,40 @@+//! Timing of the retouch kernels alone (no document plumbing): Poisson seamless clone and+//! PatchMatch completion on a disc-shaped region, RGBA.+//! `cargo run --release -p photocraft-algo --example bench_retouch`+use std::time::Instant;++use photocraft_algo::{inpaint, poisson};++fn main() {+ for d in [50usize, 100, 200, 300] {+ let n = d + 6;+ let (w, h, ch) = (n, n, 4);+ let img: Vec<f32> = (0..w * h).flat_map(|i| {+ let (x, y) = ((i % w) as f32, (i / w) as f32);+ let v = 0.5 + 0.2 * (x * 0.1).sin() * (y * 0.13).cos();+ [v, v * 0.8, 0.3, 1.0]+ }).collect();+ let src: Vec<f32> = img.iter().map(|v| v * 0.7).collect();+ let r = d as f32 / 2.0;+ let mask: Vec<bool> = (0..w * h).map(|i| ((i % w) as f32 - n as f32 / 2.0).hypot((i / w) as f32 - n as f32 / 2.0) < r).collect();+ let t = Instant::now();+ let out = poisson::seamless_clone(w, h, ch, &src, &img, &mask);+ println!("seamless_clone {d:>3} px disc: {:>8.1?} ({})", t.elapsed(), out.len());+ // Completion on a region with a margin, like Spot Healing.+ let m = d + 16;+ let (cw, chh) = (d + 2 * m, d + 2 * m);+ let cimg: Vec<f32> = (0..cw * chh).flat_map(|i| {+ let (x, y) = ((i % cw) as f32, (i / cw) as f32);+ let v = 0.5 + 0.2 * (x * 0.1).sin() * (y * 0.13).cos();+ [v, v * 0.8, 0.3, 1.0]+ }).collect();+ let c = cw as f32 / 2.0;+ let hole: Vec<bool> = (0..cw * chh).map(|i| ((i % cw) as f32 - c).hypot((i / cw) as f32 - c) < r + 2.0).collect();+ let t = Instant::now();+ let _ = inpaint::complete(cw, chh, ch, &cimg, &hole, &inpaint::CompleteParams::default());+ println!("complete {d:>3} px disc: {:>8.1?}", t.elapsed());+ let t = Instant::now();+ let _ = inpaint::best_offset(cw, chh, ch, &cimg, &hole, (d / 8).clamp(3, 16), m as i32);+ println!("best_offset {d:>3} px disc: {:>8.1?}", t.elapsed());+ }+}diff --git a/crates/algo/examples/bench_smartselect.rs b/crates/algo/examples/bench_smartselect.rsnew file mode 100644index 000000000..8e8c5807f--- /dev/null+++ b/crates/algo/examples/bench_smartselect.rs@@ -0,0 +1,100 @@+//! Timing: smart selection on a large synthetic RGBA8 layer (default 6016×6016): a textured+//! disc (radius = 1/3 of the size) on a noisy background.+//! `cargo run --release -p photocraft-algo --example bench_smartselect [size]`+use std::time::Instant;++use photocraft_algo::matting::{self, RefineParams};+use photocraft_algo::segment::{Rng, SurfaceSampler, focus, grabcut, quick, subject};+use photocraft_algo::selection::{Region, SelectionMode, combine_region};+use photocraft_color::PixelFormat;+use photocraft_geom::Rect;+use photocraft_raster::Surface;++fn main() {+ let n: i32 = std::env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(6016);+ let (c, rad) = (n as f32 / 2.0, n as f32 / 3.0);+ let canvas = Rect::new(0, 0, n, n);+ let t = Instant::now();+ let mut s = Surface::new(PixelFormat::RGBA8);+ let rows: Vec<Vec<u8>> = {+ let make = |y: i32| -> Vec<u8> {+ let mut rng = Rng::new(y as u64 + 1);+ let mut row = Vec::with_capacity(n as usize * 4);+ for x in 0..n {+ let (dx, dy) = (x as f32 + 0.5 - c, y as f32 + 0.5 - c);+ let inside = dx * dx + dy * dy <= rad * rad;+ let noise = 0.05 * rng.normal();+ let p = if inside {+ let t = ((x + y) as f32 * 0.05).sin() * 0.5 + 0.5;+ [0.85 + 0.05 * t + noise, 0.2 + 0.3 * t + noise, 0.15 + noise]+ } else {+ [0.25 + noise, 0.45 + noise, 0.7 + noise]+ };+ row.extend(p.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8));+ row.push(255);+ }+ row+ };+ use rayon::prelude::*;+ (0..n).into_par_iter().map(make).collect()+ };+ for (y, row) in rows.iter().enumerate() {+ s.write_interleaved(Rect::new(0, y as i32, n, y as i32 + 1), row);+ }+ drop(rows);+ println!("built {n}x{n} RGBA8 in {:.2?}", t.elapsed());+ let sampler = SurfaceSampler(&s);+ let truth_iou = |r: &Region| -> f32 {+ let (mut i, mut u) = (0u64, 0u64);+ let step = (n / 1000).max(1);+ for y in (0..n).step_by(step as usize) {+ for x in (0..n).step_by(step as usize) {+ let (dx, dy) = (x as f32 + 0.5 - c, y as f32 + 0.5 - c);+ let a = r.at(x, y) >= 0.5;+ let b = dx * dx + dy * dy <= rad * rad;+ i += (a && b) as u64;+ u += (a || b) as u64;+ }+ }+ i as f32 / u.max(1) as f32+ };++ // Quick selection: small and large brush strokes inside the disc near its edge.+ for size in [30.0f32, 300.0] {+ let x = c + rad - size * 2.0;+ let t = Instant::now();+ let r = quick::quick_select(&sampler, canvas, &[(x, c - size), (x, c + size)], size, quick::WORK_PX).expect("region");+ println!("quick selection stroke (brush {size} px): {:.2?} (region {}x{})", t.elapsed(), r.bbox.width(), r.bbox.height());+ }++ // Object selection (rectangle around the disc).+ let m = (rad * 1.15) as i32;+ let rect = Rect::new(c as i32 - m, c as i32 - m, c as i32 + m, c as i32 + m);+ let t = Instant::now();+ let obj = grabcut::object_select(&sampler, canvas, rect, 160_000).expect("object");+ println!("object selection: {:.2?} IoU {:.4}", t.elapsed(), truth_iou(&obj));++ // Select subject.+ let t = Instant::now();+ let subj = subject::select_subject(&sampler, canvas).expect("subject");+ println!("select subject: {:.2?} IoU {:.4}", t.elapsed(), truth_iou(&subj));++ // Refine edge on a 20 px band (selection = the object result as a surface).+ let sel = combine_region(None, Some(&obj), SelectionMode::Replace).expect("selection");+ let content = sel.content_bounds();+ let p = RefineParams { radius: 20.0, smooth: 10.0, feather: 1.0, contrast: 10.0, ..Default::default() };+ let t = Instant::now();+ let refined = matting::refine_mask(&sampler, &matting::surface_reader(&sel), content, canvas, &p).expect("refined");+ println!("refine edge (radius 20): {:.2?}", t.elapsed());+ let t = Instant::now();+ let _ = matting::refine_mask(&sampler, &matting::surface_reader(&sel), content, canvas, &RefineParams { smart_radius: true, ..p }).expect("refined");+ println!("refine edge (radius 20, smart): {:.2?}", t.elapsed());+ let t = Instant::now();+ let dec = matting::decontaminate(&s, &refined, 20.0, 100.0);+ println!("decontaminate: {:.2?} ({} tiles)", t.elapsed(), dec.tile_count());++ // Focus area.+ let t = Instant::now();+ let _ = focus::focus_area(&sampler, canvas, 0.5, 0.0);+ println!("focus area: {:.2?}", t.elapsed());+}diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rsindex ff8b56393..0051975b8 100644--- a/crates/algo/src/blur.rs+++ b/crates/algo/src/blur.rs@@ -170,8 +170,7 @@ pub(crate) fn surface(src: &Image, out: Rect, ctx: &Ctx, radius: f32, threshold:for y in out.y0..out.y1 {for x in out.x0..out.x1 {let p = src.px(x, y);- for c in 0..cc {- let v0 = p[c];+ for (c, &v0) in p.iter().enumerate().take(cc) {let (mut acc, mut wsum) = (0.0, 0.0);for yy in y - r..=y + r {for xx in x - r..=x + r {diff --git a/crates/algo/src/inpaint.rs b/crates/algo/src/inpaint.rsnew file mode 100644index 000000000..e77b9f5cf--- /dev/null+++ b/crates/algo/src/inpaint.rs@@ -0,0 +1,711 @@+//! Hole filling for Spot Healing: patch-based completion, proximity match and texture synthesis.+//!+//! * [`complete`], content-aware fill: the multi-scale "space-time completion" EM scheme of+//! Y. Wexler, E. Shechtman, M. Irani, *Space-Time Completion of Video*, IEEE TPAMI 2007, with the+//! nearest-neighbour field computed by C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman,+//! *PatchMatch: A Randomized Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009+//! (random init, propagation, exponentially shrinking random search). Each EM iteration finds, for+//! every patch overlapping the hole, its most similar fully-known patch, then re-estimates hole+//! pixels by a similarity-weighted vote of the overlapping matches. Coarse-to-fine over an image+//! pyramid (the coarsest level is initialised by membrane interpolation), so large holes stay cheap.+//! * [`best_offset`], proximity match: the single displacement whose surrounding ring best matches the+//! ring around the hole (sum of squared differences), i.e. an automatic Healing Brush source.+//! * [`synthesize`], create texture: patch-based texture synthesis in the style of A. Efros,+//! W. Freeman, *Image Quilting for Texture Synthesis and Transfer*, SIGGRAPH 2001 (blocks picked from+//! random candidates by overlap error, feathered overlap instead of a min-cut seam).+//!+//! All functions take interleaved `w × h × ch` normalised floats (any colour model/depth) and a+//! `w × h` hole mask, and return a full buffer equal to the input outside the hole. They are+//! deterministic (fixed-seed hash RNG, results independent of thread count).++use crate::poisson::membrane_fill;++/// Below this many grid cells a level runs single-threaded (thread hand-off costs more than it saves).+#[cfg(not(target_arch = "wasm32"))]+const PAR_MIN: usize = 128 * 128;++/// SplitMix64: tiny deterministic RNG.+#[derive(Clone)]+struct Rng(u64);+impl Rng {+ fn new(seed: u64) -> Self {+ Rng(seed ^ 0x9E37_79B9_7F4A_7C15)+ }+ fn next(&mut self) -> u64 {+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);+ let mut z = self.0;+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+ }+ /// Uniform integer in `lo..=hi`.+ fn range(&mut self, lo: i32, hi: i32) -> i32 {+ if hi <= lo {+ return lo;+ }+ lo + (self.next() % (hi - lo + 1) as u64) as i32+ }+}++/// Parameters for [`complete`].+#[derive(Clone, Debug, PartialEq)]+pub struct CompleteParams {+ /// Patch radius (patches are `2r+1` square).+ pub patch_radius: usize,+ /// EM iterations at the coarsest level (finer levels use fewer, down to `min_em_iters`).+ pub em_iters: usize,+ pub min_em_iters: usize,+ /// PatchMatch passes per EM iteration.+ pub pm_iters: usize,+ /// Levels where the hole is wider than this (in that level's pixels) only *refine* the upsampled+ /// match field (one local PatchMatch pass and one vote), which keeps big holes tractable: the+ /// structure is decided at coarse scale, fine levels just add detail.+ pub refine_extent: usize,+ pub seed: u64,+}++impl Default for CompleteParams {+ fn default() -> Self {+ Self { patch_radius: 3, em_iters: 8, min_em_iters: 2, pm_iters: 2, refine_extent: 96, seed: 1 }+ }+}++/// One pyramid level.+#[derive(Clone)]+struct Level {+ w: usize,+ h: usize,+ img: Vec<f32>,+ hole: Vec<bool>,+}++fn downsample(l: &Level, ch: usize) -> Level {+ let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2));+ let mut img = vec![0.0f32; w * h * ch];+ let mut hole = vec![false; w * h];+ for y in 0..h {+ for x in 0..w {+ let mut n = 0.0f32;+ let o = (y * w + x) * ch;+ for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {+ let (sx, sy) = (x * 2 + dx, y * 2 + dy);+ if sx >= l.w || sy >= l.h {+ continue;+ }+ let si = sy * l.w + sx;+ if l.hole[si] {+ hole[y * w + x] = true;+ } else {+ for c in 0..ch {+ img[o + c] += l.img[si * ch + c];+ }+ n += 1.0;+ }+ }+ if n > 0.0 {+ for c in 0..ch {+ img[o + c] /= n;+ }+ }+ }+ }+ Level { w, h, img, hole }+}++/// Summed-area table of a boolean grid (`(w+1) × (h+1)`).+fn integral(w: usize, h: usize, m: &[bool]) -> Vec<u32> {+ let mut s = vec![0u32; (w + 1) * (h + 1)];+ for y in 0..h {+ let mut row = 0u32;+ for x in 0..w {+ row += u32::from(m[y * w + x]);+ s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row;+ }+ }+ s+}++/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`.+fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 {+ let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);+ let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh));+ if x1 <= x0 || y1 <= y0 {+ return 0;+ }+ let w1 = gw + 1;+ s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0]+}++fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> {+ let mut b: Option<(usize, usize, usize, usize)> = None;+ for y in 0..h {+ for x in 0..w {+ if hole[y * w + x] {+ b = Some(match b {+ None => (x, y, x + 1, y + 1),+ Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)),+ });+ }+ }+ }+ b+}++/// Per-level PatchMatch/EM state.+struct Solver<'a> {+ w: usize,+ h: usize,+ ch: usize,+ r: i32,+ img: &'a mut Vec<f32>,+ hole: &'a [bool],+ /// Valid source centres: the whole patch is inside the grid and contains no hole pixel.+ valid: Vec<bool>,+ valid_list: Vec<(i32, i32)>,+ /// Target centres (patch overlaps the hole), row-major.+ targets: Vec<bool>,+}++impl Solver<'_> {+ #[inline]+ fn is_valid(&self, x: i32, y: i32) -> bool {+ x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize]+ }++ /// SSD between the (clipped) target patch at `t` and the source patch at `s`, per sample.+ fn dist(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 {+ let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r);+ let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32;+ let mut sum = 0.0f32;+ let mut n = 0usize;+ for dy in -r..=r {+ let ty = t.1 + dy;+ if ty < 0 || ty >= h {+ continue;+ }+ let sy = s.1 + dy;+ for dx in -r..=r {+ let tx = t.0 + dx;+ if tx < 0 || tx >= w {+ continue;+ }+ let ti = (ty as usize * self.w + tx as usize) * ch;+ let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch;+ for c in 0..ch {+ let d = self.img[ti + c] - self.img[si + c];+ sum += d * d;+ }+ n += ch;+ }+ // Early out: the mean can only be ≥ sum / (full patch size).+ if sum > cutoff * full {+ return f32::INFINITY;+ }+ }+ if n == 0 { f32::INFINITY } else { sum / n as f32 }+ }++ /// One PatchMatch pass over all target rows, in parallel bands (each band propagates within itself).+ fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) {+ const BAND: usize = 16;+ let w = self.w;+ let reverse = pass % 2 == 1;+ let band_fn = |bi: usize, nn: &mut [(i32, i32)], co: &mut [f32]| {+ let mut rng = Rng::new(seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40));+ let y0 = bi * BAND;+ let rows = nn.len() / w;+ let step: i32 = if reverse { -1 } else { 1 };+ for ry in 0..rows {+ let ly = if reverse { rows - 1 - ry } else { ry };+ let y = y0 + ly;+ for rx in 0..w {+ let x = if reverse { w - 1 - rx } else { rx };+ let li = ly * w + x;+ if !self.targets[y * w + x] {+ continue;+ }+ let t = (x as i32, y as i32);+ let (mut best, mut bc) = (nn[li], co[li]);+ // Propagation from the already-visited neighbours (within this band).+ let nx = x as i32 - step;+ if nx >= 0 && (nx as usize) < w {+ let c = nn[ly * w + nx as usize];+ let cand = (c.0 + step, c.1);+ if self.is_valid(cand.0, cand.1) && cand != best {+ let d = self.dist(t, cand, bc);+ if d < bc {+ (best, bc) = (cand, d);+ }+ }+ }+ let nly = ly as i32 - step;+ if nly >= 0 && (nly as usize) < rows {+ let c = nn[nly as usize * w + x];+ let cand = (c.0, c.1 + step);+ if self.is_valid(cand.0, cand.1) && cand != best {+ let d = self.dist(t, cand, bc);+ if d < bc {+ (best, bc) = (cand, d);+ }+ }+ }+ // Random search in exponentially shrinking windows.+ let mut rad = search_radius;+ while rad >= 1 {+ let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad));+ if self.is_valid(cand.0, cand.1) && cand != best {+ let d = self.dist(t, cand, bc);+ if d < bc {+ (best, bc) = (cand, d);+ }+ }+ rad /= 2;+ }+ nn[li] = best;+ co[li] = bc;+ }+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ if w * self.h >= PAR_MIN {+ use rayon::prelude::*;+ nnf.par_chunks_mut(BAND * w).zip(cost.par_chunks_mut(BAND * w)).enumerate().for_each(|(bi, (nn, co))| band_fn(bi, nn, co));+ return;+ }+ for (bi, (nn, co)) in nnf.chunks_mut(BAND * w).zip(cost.chunks_mut(BAND * w)).enumerate() {+ band_fn(bi, nn, co);+ }+ }++ /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches.+ fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) {+ let (w, h, ch, r) = (self.w, self.h, self.ch, self.r);+ // σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this).+ let mut cs: Vec<f32> = cost.iter().zip(&self.targets).filter(|(c, t)| **t && c.is_finite()).map(|(c, _)| *c).collect();+ let sigma2 = if cs.is_empty() {+ 1.0+ } else {+ let k = (cs.len() * 3 / 4).min(cs.len() - 1);+ let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b));+ v.max(1e-6)+ };+ let img = &*self.img;+ let row = |y: usize| -> Vec<(usize, Vec<f32>)> {+ let mut out = Vec::new();+ for x in 0..w {+ if !self.hole[y * w + x] {+ continue;+ }+ let mut acc = vec![0.0f32; ch];+ let mut wsum = 0.0f32;+ for dy in -r..=r {+ let ty = y as i32 + dy;+ if ty < 0 || ty as usize >= h {+ continue;+ }+ for dx in -r..=r {+ let tx = x as i32 + dx;+ if tx < 0 || tx as usize >= w {+ continue;+ }+ let ti = ty as usize * w + tx as usize;+ if !self.targets[ti] || !cost[ti].is_finite() {+ continue;+ }+ let s = nnf[ti];+ let (sx, sy) = (s.0 - dx, s.1 - dy);+ let wt = (-cost[ti] / (2.0 * sigma2)).exp().max(1e-8);+ let si = (sy as usize * w + sx as usize) * ch;+ for c in 0..ch {+ acc[c] += img[si + c] * wt;+ }+ wsum += wt;+ }+ }+ if wsum > 0.0 {+ acc.iter_mut().for_each(|v| *v /= wsum);+ out.push((x, acc));+ }+ }+ out+ };+ #[cfg(not(target_arch = "wasm32"))]+ let rows: Vec<Vec<(usize, Vec<f32>)>> = if w * h >= PAR_MIN {+ use rayon::prelude::*;+ (0..h).into_par_iter().map(row).collect()+ } else {+ (0..h).map(row).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let rows: Vec<Vec<(usize, Vec<f32>)>> = (0..h).map(row).collect();+ for (y, r) in rows.into_iter().enumerate() {+ for (x, v) in r {+ self.img[(y * w + x) * ch..(y * w + x + 1) * ch].copy_from_slice(&v);+ }+ }+ }+}++/// Content-aware completion of `hole` (see module docs). Returns `None` when there is no fully-known+/// patch to copy from (the caller can fall back to [`membrane_fill`]).+pub fn complete(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], p: &CompleteParams) -> Option<Vec<f32>> {+ assert_eq!(img.len(), w * h * ch);+ assert_eq!(hole.len(), w * h);+ let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Some(img.to_vec()) };+ let r = p.patch_radius.max(1);+ let psz = 2 * r + 1;+ // Pyramid: shrink until the hole is a few patches across.+ let mut levels = vec![Level { w, h, img: img.to_vec(), hole: hole.to_vec() }];+ let mut ext = (bx1 - bx0).max(by1 - by0);+ let mut exts = vec![ext];+ loop {+ let l = levels.last().expect("non-empty");+ if ext <= 2 * psz || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz {+ break;+ }+ let d = downsample(l, ch);+ levels.push(d);+ ext = ext.div_ceil(2);+ exts.push(ext);+ }+ let nlev = levels.len();+ let mut nnf: Vec<(i32, i32)> = Vec::new();+ let mut prev: Option<(usize, usize, Vec<f32>)> = None;+ for li in (0..nlev).rev() {+ let Level { w: lw, h: lh, img: mut limg, hole: lhole } = levels[li].clone();+ // Initialise the hole: membrane at the coarsest level, upsampled result elsewhere.+ match &prev {+ None => limg = membrane_fill(lw, lh, ch, &limg, &lhole),+ Some((pw, ph, pimg)) => {+ for y in 0..lh {+ for x in 0..lw {+ if lhole[y * lw + x] {+ let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1));+ let (d, s) = ((y * lw + x) * ch, (sy * pw + sx) * ch);+ limg[d..d + ch].copy_from_slice(&pimg[s..s + ch]);+ }+ }+ }+ }+ }+ let ri = r as i32;+ let hs = integral(lw, lh, &lhole);+ let mut valid = vec![false; lw * lh];+ let mut valid_list = Vec::new();+ let mut targets = vec![false; lw * lh];+ for y in 0..lh as i32 {+ for x in 0..lw as i32 {+ let cnt = window_count(&hs, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1);+ let inside = x >= ri && y >= ri && x + ri < lw as i32 && y + ri < lh as i32;+ let i = y as usize * lw + x as usize;+ if inside && cnt == 0 {+ valid[i] = true;+ valid_list.push((x, y));+ }+ targets[i] = cnt > 0;+ }+ }+ if valid_list.is_empty() {+ if li == 0 {+ return None;+ }+ prev = Some((lw, lh, limg));+ nnf.clear();+ continue;+ }+ let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets };+ // NNF init: upsampled from the coarser level where possible, random otherwise.+ let mut rng = Rng::new(p.seed ^ (li as u64) << 20);+ let pw_prev = prev.as_ref().map_or(0, |p| p.0);+ let old = std::mem::take(&mut nnf);+ let mut new_nnf = vec![(0i32, 0i32); lw * lh];+ for y in 0..lh {+ for x in 0..lw {+ if !solver.targets[y * lw + x] {+ continue;+ }+ let mut cand = None;+ if !old.is_empty() && pw_prev > 0 {+ let pi = (y / 2) * pw_prev + (x / 2);+ if let Some(&(sx, sy)) = old.get(pi) {+ let c = (sx * 2 + (x % 2) as i32, sy * 2 + (y % 2) as i32);+ if solver.is_valid(c.0, c.1) {+ cand = Some(c);+ }+ }+ }+ new_nnf[y * lw + x] = cand.unwrap_or_else(|| solver.valid_list[(rng.next() % solver.valid_list.len() as u64) as usize]);+ }+ }+ nnf = new_nnf;+ let refine_only = li + 1 < nlev && exts[li] > p.refine_extent;+ let em = if li + 1 == nlev {+ p.em_iters+ } else if refine_only {+ 1+ } else {+ (p.em_iters >> (nlev - 1 - li)).max(p.min_em_iters)+ };+ let pm_iters = if refine_only { 1 } else { p.pm_iters };+ let full_search = (lw.max(lh)) as i32;+ let mut cost = vec![f32::INFINITY; lw * lh];+ for it in 0..em {+ // Costs change as hole pixels are re-estimated: refresh before each PatchMatch.+ for (i, c) in cost.iter_mut().enumerate() {+ if solver.targets[i] {+ *c = solver.dist(((i % lw) as i32, (i / lw) as i32), nnf[i], f32::INFINITY);+ }+ }+ // Wide random search on coarse levels / first iteration, local refinement afterwards.+ let radius = if refine_only {+ 2+ } else if li + 1 == nlev || it == 0 {+ full_search+ } else {+ (4 * psz as i32).min(full_search)+ };+ for pass in 0..pm_iters {+ solver.patchmatch(&mut nnf, &mut cost, pass + it * pm_iters, p.seed.wrapping_add((li * 1000 + it) as u64), radius);+ }+ solver.vote(&nnf, &cost);+ }+ prev = Some((lw, lh, limg));+ }+ prev.map(|(_, _, img)| img)+}++/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the+/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the+/// hole. `None` if no displacement fits.+pub fn best_offset(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ring: usize, max_radius: i32) -> Option<(i32, i32)> {+ let (bx0, by0, bx1, by1) = hole_bbox(w, h, hole)?;+ let ring = ring.max(1) as i32;+ let hs = integral(w, h, hole);+ // Sample points: the hole's ring (dilated minus hole), subsampled for speed.+ let mut pts = Vec::new();+ let (x0, y0) = (bx0 as i32 - ring, by0 as i32 - ring);+ let (x1, y1) = (bx1 as i32 + ring, by1 as i32 + ring);+ for y in y0.max(0)..y1.min(h as i32) {+ for x in x0.max(0)..x1.min(w as i32) {+ if hole[y as usize * w + x as usize] {+ continue;+ }+ if window_count(&hs, w, h, x - ring, y - ring, x + ring + 1, y + ring + 1) > 0 {+ pts.push((x, y));+ }+ }+ }+ let stride = (pts.len() / 2000).max(1);+ let pts: Vec<(i32, i32)> = pts.into_iter().step_by(stride).collect();+ let eval = |dx: i32, dy: i32| -> Option<f32> {+ let (hx0, hy0, hx1, hy1) = (x0 + dx, y0 + dy, x1 + dx, y1 + dy);+ let inside = hx0 >= 0 && hy0 >= 0 && hx1 <= w as i32 && hy1 <= h as i32;+ if (dx, dy) == (0, 0) || !inside || window_count(&hs, w, h, hx0, hy0, hx1, hy1) != 0 {+ return None;+ }+ let mut e = 0.0f32;+ for &(x, y) in &pts {+ let (a, b) = ((y as usize * w + x as usize) * ch, ((y + dy) as usize * w + (x + dx) as usize) * ch);+ for c in 0..ch {+ let d = img[a + c] - img[b + c];+ e += d * d;+ }+ }+ // Mild preference for nearer sources on ties.+ Some(e / pts.len().max(1) as f32 * (1.0 + 1e-3 * ((dx * dx + dy * dy) as f32).sqrt() / max_radius.max(1) as f32))+ };+ // Coarse grid over the search window, then a full-resolution refinement around the winner.+ let step = (max_radius / 24).max(1);+ let mut best: Option<((i32, i32), f32)> = None;+ let consider = |dx: i32, dy: i32, best: &mut Option<((i32, i32), f32)>| {+ if let Some(e) = eval(dx, dy)+ && best.is_none_or(|(_, be)| e < be)+ {+ *best = Some(((dx, dy), e));+ }+ };+ let mut dy = -max_radius;+ while dy <= max_radius {+ let mut dx = -max_radius;+ while dx <= max_radius {+ consider(dx, dy, &mut best);+ dx += step;+ }+ dy += step;+ }+ if step > 1+ && let Some(((bx, by), _)) = best+ {+ for dy in (by - step)..=(by + step) {+ for dx in (bx - step)..=(bx + step) {+ consider(dx, dy, &mut best);+ }+ }+ }+ best.map(|b| b.0)+}++/// Create texture: fill the hole with blocks of surrounding texture (see module docs).+pub fn synthesize(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], block: usize, seed: u64) -> Vec<f32> {+ let mut out = img.to_vec();+ let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return out };+ let b = block.max(4) as i32;+ let ov = (b / 3).max(1);+ let hs = integral(w, h, hole);+ // Candidate block origins: whole block (with overlap) inside the grid and outside the hole.+ let mut cands = Vec::new();+ for y in ov..(h as i32 - b - ov) {+ for x in ov..(w as i32 - b - ov) {+ if window_count(&hs, w, h, x - ov, y - ov, x + b + ov, y + b + ov) == 0 {+ cands.push((x, y));+ }+ }+ }+ if cands.is_empty() {+ return membrane_fill(w, h, ch, img, hole);+ }+ let mut filled: Vec<bool> = hole.iter().map(|x| !x).collect();+ let mut rng = Rng::new(seed);+ let mut by = by0 as i32;+ while by < by1 as i32 {+ let mut bx = bx0 as i32;+ while bx < bx1 as i32 {+ if window_count(&hs, w, h, bx, by, bx + b, by + b) > 0 {+ // Pick the candidate whose block best agrees with already-known pixels around/inside.+ let mut best = (cands[0], f32::INFINITY);+ for _ in 0..48 {+ let c = cands[(rng.next() % cands.len() as u64) as usize];+ let (mut e, mut n) = (0.0f32, 0u32);+ for y in (by - ov)..(by + b + ov) {+ for x in (bx - ov)..(bx + b + ov) {+ if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 || !filled[y as usize * w + x as usize] {+ continue;+ }+ let (a, s) = ((y as usize * w + x as usize) * ch, ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch);+ for k in 0..ch {+ let d = out[a + k] - img[s + k];+ e += d * d;+ }+ n += 1;+ }+ }+ let e = if n == 0 { 0.0 } else { e / n as f32 };+ if e < best.1 {+ best = (c, e);+ }+ }+ let c = best.0;+ for y in (by - ov)..(by + b + ov) {+ for x in (bx - ov)..(bx + b + ov) {+ if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 {+ continue;+ }+ let i = y as usize * w + x as usize;+ if !hole[i] {+ continue;+ }+ let (a, s) = (i * ch, ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch);+ // Feather into already-synthesised overlap.+ let k = if filled[i] { 0.5 } else { 1.0 };+ for q in 0..ch {+ out[a + q] += (img[s + q] - out[a + q]) * k;+ }+ filled[i] = true;+ }+ }+ }+ bx += b;+ }+ by += b;+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Smooth gradient plus deterministic fine noise.+ fn texture(w: usize, h: usize) -> Vec<f32> {+ let mut rng = Rng::new(7);+ (0..w * h)+ .flat_map(|i| {+ let (x, y) = ((i % w) as f32, (i / w) as f32);+ let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02;+ [0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n]+ })+ .collect()+ }++ fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec<bool> {+ (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect()+ }++ fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 {+ let (mut e, mut n) = (0.0f32, 0);+ for (i, hh) in hole.iter().enumerate() {+ if *hh {+ for c in 0..ch {+ e += (a[i * ch + c] - b[i * ch + c]).powi(2);+ n += 1;+ }+ }+ }+ (e / n as f32).sqrt()+ }++ #[test]+ fn completion_fills_blemish_from_texture() {+ let (w, h, ch) = (96, 96, 3);+ let clean = texture(w, h);+ let hole = disc(w, h, 48.0, 48.0, 9.0);+ let mut dirty = clean.clone();+ for (i, hh) in hole.iter().enumerate() {+ if *hh {+ dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]);+ }+ }+ let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap();+ let before = hole_rmse(&dirty, &clean, &hole, ch);+ let after = hole_rmse(&out, &clean, &hole, ch);+ assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}");+ // Outside the hole untouched.+ assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b));+ // Deterministic.+ assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap());+ }++ #[test]+ fn completion_continues_structure() {+ // Vertical stripes: the filled hole should keep the stripes (not a blur).+ let (w, h, ch) = (80, 80, 1);+ let clean: Vec<f32> = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect();+ let hole = disc(w, h, 40.0, 40.0, 7.0);+ let dirty: Vec<f32> = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect();+ let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap();+ let err = hole_rmse(&out, &clean, &hole, ch);+ assert!(err < 0.15, "{err}");+ }++ #[test]+ fn proximity_finds_matching_offset() {+ let (w, h, ch) = (80, 60, 1);+ // Periodic pattern with period 10 in x: a match is any multiple-of-10 displacement.+ let img: Vec<f32> = (0..w * h).map(|i| ((i % w) as f32 * std::f32::consts::TAU / 10.0).sin() * 0.4 + 0.5).collect();+ let hole = disc(w, h, 40.0, 30.0, 5.0);+ let (dx, dy) = best_offset(w, h, ch, &img, &hole, 3, 20).unwrap();+ assert_eq!(dx.rem_euclid(10), 0, "dx {dx} dy {dy}");+ assert!((dx, dy) != (0, 0));+ }++ #[test]+ fn synthesis_fills_hole_with_plausible_values() {+ let (w, h, ch) = (64, 64, 3);+ let clean = texture(w, h);+ let hole = disc(w, h, 32.0, 32.0, 6.0);+ let out = synthesize(w, h, ch, &clean, &hole, 8, 3);+ let err = hole_rmse(&out, &clean, &hole, ch);+ assert!(err < 0.15, "{err}");+ assert!(out.iter().all(|v| v.is_finite()));+ }+}diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rsindex 67e87d5a4..89de57b53 100644--- a/crates/algo/src/lib.rs+++ b/crates/algo/src/lib.rs@@ -22,6 +22,15 @@ mod distort;mod image;mod noise;mod other;+pub mod paint;+pub mod resample;+pub mod selection;+pub mod segment;+pub mod matting;+pub mod transform;+pub mod poisson;+pub mod inpaint;+pub mod retouch;mod sharpen;mod stylize;diff --git a/crates/algo/src/matting.rs b/crates/algo/src/matting.rsnew file mode 100644index 000000000..256401b7a--- /dev/null+++ b/crates/algo/src/matting.rs@@ -0,0 +1,732 @@+//! Edge refinement ("Select and Mask" / Refine Edge) and colour decontamination.+//!+//! * Soft edges come from the **guided filter** (K. He, J. Sun and X. Tang, "Guided Image+//! Filtering", ECCV 2010 / PAMI 2013): filtering the binary selection with the image as guide+//! fits a local linear model `α ≈ aᵀI + b` in every window, so the mask takes on the image's+//! soft transitions (hair, blur) inside a band of `radius` pixels around the selection edge.+//! "Smart radius" adapts the band per pixel to the transition width observed in the image.+//! * Then, in Photoshop's order: Smooth, Feather (Gaussian, σ = feather / 2), Contrast and+//! Shift Edge (grey dilation / erosion).+//! * **Decontaminate colours** replaces fringe colours by the normalised-convolution average of+//! nearby fully selected pixels, blended by `amount` and the fringe's transparency.+//!+//! Work is tiled: only tiles near the selection boundary are processed (in parallel on native+//! targets), so cost scales with the boundary length rather than the selection area.++use photocraft_color::PixelFormat;+use photocraft_geom::Rect;+use photocraft_raster::Surface;+use serde::{Deserialize, Serialize};++use crate::segment::{RgbImage, Sampler};+use crate::selection::{Region, edt};++/// Select and Mask parameters (Photoshop's units).+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct RefineParams {+ /// Edge-detection band radius in pixels (0 = no edge detection).+ pub radius: f32,+ /// Adapt the band to the edge's observed softness.+ pub smart_radius: bool,+ /// 0–100.+ pub smooth: f32,+ /// Pixels.+ pub feather: f32,+ /// 0–100.+ pub contrast: f32,+ /// −100–100 (% of `max(radius, 4 px)`).+ pub shift_edge: f32,+}++impl Default for RefineParams {+ fn default() -> Self {+ Self { radius: 0.0, smart_radius: false, smooth: 0.0, feather: 0.0, contrast: 0.0, shift_edge: 0.0 }+ }+}++/// Guided-filter regulariser (colour guide, samples in 0–1).+pub const EPS: f32 = 1e-4;+const TILE: i32 = 256;++impl RefineParams {+ fn gf_radius(&self) -> usize {+ self.radius.ceil().clamp(1.0, 64.0) as usize+ }+ fn smooth_sigma(&self) -> f32 {+ self.smooth.clamp(0.0, 100.0) / 100.0 * 4.0+ }+ fn feather_sigma(&self) -> f32 {+ self.feather.max(0.0) / 2.0+ }+ fn shift_px(&self) -> i32 {+ (self.shift_edge.clamp(-100.0, 100.0) / 100.0 * self.radius.max(4.0)).round().clamp(-64.0, 64.0) as i32+ }+ fn uses_image(&self) -> bool {+ self.radius > 0.0+ }+ /// Pixels read around an output pixel.+ pub fn halo(&self) -> i32 {+ let edge = if self.uses_image() {+ let g = self.gf_radius() as i32;+ (self.radius.ceil() as i32).max(2 * g + if self.smart_radius { g + 1 } else { 0 })+ } else {+ 0+ };+ edge + (3.0 * self.smooth_sigma()).ceil() as i32 + (3.0 * self.feather_sigma()).ceil() as i32 + self.shift_px().abs() + 2+ }+ /// How far the refined mask can extend beyond the original.+ pub fn spread(&self) -> i32 {+ (if self.uses_image() { self.radius.ceil() as i32 } else { 0 }) + (3.0 * self.smooth_sigma()).ceil() as i32 + (3.0 * self.feather_sigma()).ceil() as i32 + self.shift_px().max(0) + 1+ }+}++/// Box mean with radius `r` (window clipped to the image, divided by the pixel count).+pub fn box_mean(src: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {+ let mut tmp = vec![0.0f32; w * h];+ let mut pre = vec![0.0f64; w.max(h) + 1];+ for y in 0..h {+ let row = &src[y * w..(y + 1) * w];+ for x in 0..w {+ pre[x + 1] = pre[x] + row[x] as f64;+ }+ for x in 0..w {+ let (lo, hi) = (x.saturating_sub(r), (x + r + 1).min(w));+ tmp[y * w + x] = ((pre[hi] - pre[lo]) / (hi - lo) as f64) as f32;+ }+ }+ let mut out = vec![0.0f32; w * h];+ let mut col = vec![0.0f64; (h + 1) * w];+ for y in 0..h {+ for x in 0..w {+ col[(y + 1) * w + x] = col[y * w + x] + tmp[y * w + x] as f64;+ }+ }+ for y in 0..h {+ let (lo, hi) = (y.saturating_sub(r), (y + r + 1).min(h));+ let n = (hi - lo) as f64;+ for x in 0..w {+ out[y * w + x] = ((col[hi * w + x] - col[lo * w + x]) / n) as f32;+ }+ }+ out+}++/// Guided filter with a grayscale guide.+pub fn guided_filter_gray(guide: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec<f32> {+ let mi = box_mean(guide, w, h, r);+ let mp = box_mean(p, w, h, r);+ let ip: Vec<f32> = guide.iter().zip(p).map(|(a, b)| a * b).collect();+ let ii: Vec<f32> = guide.iter().map(|a| a * a).collect();+ let mip = box_mean(&ip, w, h, r);+ let mii = box_mean(&ii, w, h, r);+ let mut a = vec![0.0f32; w * h];+ let mut b = vec![0.0f32; w * h];+ for i in 0..w * h {+ let var = mii[i] - mi[i] * mi[i];+ let cov = mip[i] - mi[i] * mp[i];+ a[i] = cov / (var + eps);+ b[i] = mp[i] - a[i] * mi[i];+ }+ let ma = box_mean(&a, w, h, r);+ let mb = box_mean(&b, w, h, r);+ (0..w * h).map(|i| ma[i] * guide[i] + mb[i]).collect()+}++/// Guided filter with a colour guide (He et al., Eq. 19–21: `a_k = (Σ_k + εU)⁻¹ cov_k(I, p)`).+pub fn guided_filter_color(guide: &RgbImage, p: &[f32], r: usize, eps: f32) -> Vec<f32> {+ let (w, h) = (guide.w, guide.h);+ let n = w * h;+ let ch = |c: usize| -> Vec<f32> { guide.px.iter().map(|q| q[c]).collect() };+ let chans = [ch(0), ch(1), ch(2)];+ let m: Vec<Vec<f32>> = chans.iter().map(|c| box_mean(c, w, h, r)).collect();+ let mp = box_mean(p, w, h, r);+ let mip: Vec<Vec<f32>> = chans.iter().map(|c| box_mean(&c.iter().zip(p).map(|(a, b)| a * b).collect::<Vec<_>>(), w, h, r)).collect();+ let pairs = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)];+ let mii: Vec<Vec<f32>> = pairs.iter().map(|&(a, b)| box_mean(&chans[a].iter().zip(&chans[b]).map(|(x, y)| x * y).collect::<Vec<_>>(), w, h, r)).collect();+ let mut av = [vec![0.0f32; n], vec![0.0f32; n], vec![0.0f32; n]];+ let mut bv = vec![0.0f32; n];+ for i in 0..n {+ let mu = [m[0][i] as f64, m[1][i] as f64, m[2][i] as f64];+ let s = |k: usize, a: usize, b: usize| mii[k][i] as f64 - mu[a] * mu[b];+ let e = eps as f64;+ let (rr, rg, rb, gg, gb, bb) = (s(0, 0, 0) + e, s(1, 0, 1), s(2, 0, 2), s(3, 1, 1) + e, s(4, 1, 2), s(5, 2, 2) + e);+ let cov = [mip[0][i] as f64 - mu[0] * mp[i] as f64, mip[1][i] as f64 - mu[1] * mp[i] as f64, mip[2][i] as f64 - mu[2] * mp[i] as f64];+ // Inverse of the symmetric 3×3 matrix.+ let i00 = gg * bb - gb * gb;+ let i01 = gb * rb - rg * bb;+ let i02 = rg * gb - gg * rb;+ let i11 = rr * bb - rb * rb;+ let i12 = rb * rg - rr * gb;+ let i22 = rr * gg - rg * rg;+ let det = rr * i00 + rg * i01 + rb * i02;+ let (a0, a1, a2) = if det.abs() < 1e-30 {+ (0.0, 0.0, 0.0)+ } else {+ ((i00 * cov[0] + i01 * cov[1] + i02 * cov[2]) / det, (i01 * cov[0] + i11 * cov[1] + i12 * cov[2]) / det, (i02 * cov[0] + i12 * cov[1] + i22 * cov[2]) / det)+ };+ av[0][i] = a0 as f32;+ av[1][i] = a1 as f32;+ av[2][i] = a2 as f32;+ bv[i] = (mp[i] as f64 - a0 * mu[0] - a1 * mu[1] - a2 * mu[2]) as f32;+ }+ let ma: Vec<Vec<f32>> = av.iter().map(|a| box_mean(a, w, h, r)).collect();+ let mb = box_mean(&bv, w, h, r);+ (0..n).map(|i| ma[0][i] * chans[0][i] + ma[1][i] * chans[1][i] + ma[2][i] * chans[2][i] + mb[i]).collect()+}++/// Separable Gaussian blur (edge-clamped).+pub fn gaussian_blur(src: &[f32], w: usize, h: usize, sigma: f32) -> Vec<f32> {+ if sigma < 0.1 {+ return src.to_vec();+ }+ let r = (sigma * 3.0).ceil() as i64;+ let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();+ let s: f32 = k.iter().sum();+ let k: Vec<f32> = k.iter().map(|v| v / s).collect();+ let mut tmp = vec![0.0f32; w * h];+ for y in 0..h {+ for x in 0..w {+ let mut a = 0.0;+ for (i, kv) in k.iter().enumerate() {+ let xx = (x as i64 + i as i64 - r).clamp(0, w as i64 - 1) as usize;+ a += src[y * w + xx] * kv;+ }+ tmp[y * w + x] = a;+ }+ }+ let mut out = vec![0.0f32; w * h];+ for y in 0..h {+ for x in 0..w {+ let mut a = 0.0;+ for (i, kv) in k.iter().enumerate() {+ let yy = (y as i64 + i as i64 - r).clamp(0, h as i64 - 1) as usize;+ a += tmp[yy * w + x] * kv;+ }+ out[y * w + x] = a;+ }+ }+ out+}++/// Grey dilation (`grow`) or erosion by about `r` pixels: alternating 3×3 square and cross steps+/// (an octagonal structuring element).+pub fn morph(src: &[f32], w: usize, h: usize, r: usize, grow: bool) -> Vec<f32> {+ let mut cur = src.to_vec();+ let mut nxt = cur.clone();+ let pick = |a: f32, b: f32| if grow { a.max(b) } else { a.min(b) };+ for k in 0..r {+ let square = k % 2 == 0;+ for y in 0..h {+ for x in 0..w {+ let mut v = cur[y * w + x];+ for dy in -1i32..=1 {+ for dx in -1i32..=1 {+ if (dx != 0 && dy != 0 && !square) || (dx == 0 && dy == 0) {+ continue;+ }+ let (nx, ny) = (x as i32 + dx, y as i32 + dy);+ if nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h {+ v = pick(v, cur[ny as usize * w + nx as usize]);+ }+ }+ }+ nxt[y * w + x] = v;+ }+ }+ std::mem::swap(&mut cur, &mut nxt);+ }+ cur+}++/// Running max (or min) over a window of radius `r` (edge-clipped), van Herk / Gil–Werman:+/// three comparisons per sample whatever the radius.+fn running_extreme(src: &[f32], out: &mut [f32], r: usize, max: bool, g: &mut Vec<f32>, hb: &mut Vec<f32>) {+ let n = src.len();+ let k = 2 * r + 1;+ let f = |a: f32, b: f32| if max { a.max(b) } else { a.min(b) };+ let pad = if max { f32::NEG_INFINITY } else { f32::INFINITY };+ let m = (n + 2 * r).div_ceil(k) * k;+ g.clear();+ g.resize(m, pad);+ hb.clear();+ hb.resize(m, pad);+ let p = |j: usize| if j >= r && j < r + n { src[j - r] } else { pad };+ for j in 0..m {+ g[j] = if j % k == 0 { p(j) } else { f(g[j - 1], p(j)) };+ }+ for j in (0..m).rev() {+ hb[j] = if j % k == k - 1 || j == m - 1 { p(j) } else { f(hb[j + 1], p(j)) };+ }+ for (i, o) in out.iter_mut().enumerate() {+ *o = f(hb[i], g[i + 2 * r]);+ }+}++/// Running max (or min) over a square window of radius `r` (edge-clipped), separable.+fn max_square(src: &[f32], w: usize, h: usize, r: usize, max: bool) -> Vec<f32> {+ let (mut g, mut hb) = (Vec::new(), Vec::new());+ let mut tmp = vec![0.0f32; w * h];+ for y in 0..h {+ running_extreme(&src[y * w..(y + 1) * w], &mut tmp[y * w..(y + 1) * w], r, max, &mut g, &mut hb);+ }+ let mut out = vec![0.0f32; w * h];+ let (mut col, mut res) = (vec![0.0f32; h], vec![0.0f32; h]);+ for x in 0..w {+ for y in 0..h {+ col[y] = tmp[y * w + x];+ }+ running_extreme(&col, &mut res, r, max, &mut g, &mut hb);+ for y in 0..h {+ out[y * w + x] = res[y];+ }+ }+ out+}++/// Per-pixel transition width (pixels) of the guide's luminance: local range / local max+/// gradient over a window of radius `r` (a sharp step gives ~2, a ramp of width L gives ~L).+pub fn edge_width(img: &RgbImage, r: usize) -> Vec<f32> {+ let (w, h) = (img.w, img.h);+ let y: Vec<f32> = img.px.iter().map(|p| 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]).collect();+ let mut g = vec![0.0f32; w * h];+ for yy in 0..h {+ for xx in 0..w {+ let at = |x: usize, y2: usize| y[y2 * w + x];+ let gx = (at((xx + 1).min(w - 1), yy) - at(xx.saturating_sub(1), yy)) / 2.0;+ let gy = (at(xx, (yy + 1).min(h - 1)) - at(xx, yy.saturating_sub(1))) / 2.0;+ g[yy * w + xx] = (gx * gx + gy * gy).sqrt();+ }+ }+ let gm = max_square(&g, w, h, r, true);+ let hi = max_square(&y, w, h, r, true);+ let lo = max_square(&y, w, h, r, false);+ (0..w * h).map(|i| (hi[i] - lo[i]) / gm[i].max(1e-4)).collect()+}++/// Refines a soft mask buffer `m` (`w × h`) with `img` as guide (required when `radius > 0`).+pub fn refine_buffer(img: Option<&RgbImage>, m: &[f32], w: usize, h: usize, p: &RefineParams) -> Vec<f32> {+ let mut a = m.to_vec();+ if let (true, Some(img)) = (p.uses_image(), img) {+ let bin: Vec<bool> = m.iter().map(|v| *v >= 0.5).collect();+ let mut boundary = vec![false; w * h];+ let mut any = false;+ for y in 0..h {+ for x in 0..w {+ let i = y * w + x;+ let v = bin[i];+ let diff = (x > 0 && bin[i - 1] != v) || (x + 1 < w && bin[i + 1] != v) || (y > 0 && bin[i - w] != v) || (y + 1 < h && bin[i + w] != v);+ boundary[i] = diff;+ any |= diff;+ }+ }+ if any {+ let dist = edt(&boundary, w, h);+ let r = p.gf_radius();+ let q = guided_filter_color(img, m, r, EPS);+ let widths = p.smart_radius.then(|| edge_width(img, r));+ for i in 0..w * h {+ let reff = match &widths {+ Some(wd) => wd[i].clamp(1.5, p.radius.max(1.5)),+ None => p.radius,+ };+ let wgt = (reff + 1.0 - dist[i]).clamp(0.0, 1.0);+ if wgt > 0.0 {+ a[i] = m[i] + (q[i].clamp(0.0, 1.0) - m[i]) * wgt;+ }+ }+ }+ }+ let ss = p.smooth_sigma();+ if ss >= 0.3 {+ a = gaussian_blur(&a, w, h, ss);+ let gain = 1.0 + ss;+ for v in &mut a {+ *v = ((*v - 0.5) * gain + 0.5).clamp(0.0, 1.0);+ }+ }+ a = gaussian_blur(&a, w, h, p.feather_sigma());+ if p.contrast > 0.0 {+ let gain = 1.0 / (1.0 - 0.99 * p.contrast.clamp(0.0, 100.0) / 100.0);+ for v in &mut a {+ *v = ((*v - 0.5) * gain + 0.5).clamp(0.0, 1.0);+ }+ }+ let d = p.shift_px();+ if d != 0 {+ a = morph(&a, w, h, d.unsigned_abs() as usize, d > 0);+ }+ a+}++/// Refines a selection mask. `mask(r)` returns coverage over `r` (row-major); `content` bounds+/// its non-zero pixels; the result is clipped to `canvas`. `sampler` supplies the guide image+/// (only read when `radius > 0`). Returns `None` when nothing remains selected.+pub fn refine_mask(sampler: &dyn Sampler, mask: &(dyn Fn(Rect) -> Vec<f32> + Sync), content: Rect, canvas: Rect, p: &RefineParams) -> Option<Region> {+ let content = content.intersect(&canvas);+ if content.is_empty() {+ return None;+ }+ let bbox = content.inflate(p.spread()).intersect(&canvas);+ let halo = p.halo();+ let mut tiles = Vec::new();+ let mut y = bbox.y0;+ while y < bbox.y1 {+ let mut x = bbox.x0;+ while x < bbox.x1 {+ tiles.push(Rect::new(x, y, (x + TILE).min(bbox.x1), (y + TILE).min(bbox.y1)));+ x += TILE;+ }+ y += TILE;+ }+ let run = |t: &Rect| -> (Rect, Vec<u8>) {+ let r = t.inflate(halo).intersect(&canvas);+ let m = mask(r);+ let (rw, rh) = (r.width() as usize, r.height() as usize);+ let first = m.first().copied().unwrap_or(0.0);+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ let (cx, cy, cw, ch) = ((t.x0 - r.x0) as usize, (t.y0 - r.y0) as usize, t.width() as usize, t.height() as usize);+ let core = |buf: &[f32]| -> Vec<u8> {+ let mut out = Vec::with_capacity(cw * ch);+ for yy in 0..ch {+ out.extend(buf[(cy + yy) * rw + cx..(cy + yy) * rw + cx + cw].iter().map(|v| q(*v)));+ }+ out+ };+ if (first == 0.0 || first == 1.0) && m.iter().all(|v| *v == first) {+ return (*t, vec![q(first); cw * ch]);+ }+ let img = p.uses_image().then(|| sampler.rgb(r));+ let out = refine_buffer(img.as_ref(), &m, rw, rh, p);+ (*t, core(&out))+ };+ #[cfg(not(target_arch = "wasm32"))]+ let results: Vec<(Rect, Vec<u8>)> = {+ use rayon::prelude::*;+ tiles.par_iter().map(run).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let results: Vec<(Rect, Vec<u8>)> = tiles.iter().map(run).collect();+ let bw = bbox.width() as usize;+ let mut out = vec![0u8; bw * bbox.height() as usize];+ for (t, data) in results {+ let cw = t.width() as usize;+ for (yy, row) in data.chunks_exact(cw).enumerate() {+ let o = ((t.y0 - bbox.y0) as usize + yy) * bw + (t.x0 - bbox.x0) as usize;+ out[o..o + cw].copy_from_slice(row);+ }+ }+ crate::segment::trim_region(Region { bbox, mask: out })+}++/// A mask reader over a [`Region`] (zero outside its box).+pub fn region_reader(reg: &Region) -> impl Fn(Rect) -> Vec<f32> + Sync + '_ {+ move |r: Rect| {+ let mut v = Vec::with_capacity(r.width() as usize * r.height() as usize);+ for y in r.y0..r.y1 {+ for x in r.x0..r.x1 {+ v.push(reg.at(x, y));+ }+ }+ v+ }+}++/// A mask reader over a selection surface (channel 0).+pub fn surface_reader(s: &Surface) -> impl Fn(Rect) -> Vec<f32> + Sync + '_ {+ move |r: Rect| crate::selection::mask_from_surface(Some(s), r)+}++/// GRAY8 surface (default 0) holding a region's coverage (a selection or a layer mask).+pub fn region_surface(reg: &Region) -> Surface {+ let mut s = Surface::from_interleaved(PixelFormat::GRAY8, reg.bbox, ®.mask);+ s.prune();+ s+}++fn tiles_of(area: Rect) -> Vec<Rect> {+ let mut tiles = Vec::new();+ let mut y = area.y0;+ while y < area.y1 {+ let mut x = area.x0;+ while x < area.x1 {+ tiles.push(Rect::new(x, y, (x + TILE).min(area.x1), (y + TILE).min(area.y1)));+ x += TILE;+ }+ y += TILE;+ }+ tiles+}++fn par_tiles<T: Send>(tiles: &[Rect], f: impl Fn(&Rect) -> Option<T> + Sync + Send) -> Vec<T> {+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ tiles.par_iter().filter_map(f).collect()+ }+ #[cfg(target_arch = "wasm32")]+ {+ tiles.iter().filter_map(f).collect()+ }+}++/// Decontaminates colours in the soft fringe of `alpha`: each fringe pixel moves towards the+/// average colour of nearby fully selected pixels (normalised convolution with a box of radius+/// `max(radius, 3)`, widened ×4 where no such pixel is near), by `amount`% scaled by its+/// transparency. Works in the surface's own colour channels (any model / depth).+pub fn decontaminate(src: &Surface, alpha: &Region, radius: f32, amount: f32) -> Surface {+ let fmt = src.format();+ let n = fmt.channels();+ let nc = n - fmt.alpha as usize;+ let rad = radius.max(3.0).ceil() as usize;+ let halo = (rad * 4) as i32;+ let amount = amount.clamp(0.0, 100.0) / 100.0;+ let soft = |a: f32| a > 0.02 && a < 0.98;+ let results = par_tiles(&tiles_of(alpha.bbox), |t| {+ if !(t.y0..t.y1).any(|y| (t.x0..t.x1).any(|x| soft(alpha.at(x, y)))) {+ return None;+ }+ let r = t.inflate(halo);+ let (rw, rh) = (r.width() as usize, r.height() as usize);+ let mut px = Vec::new();+ src.read_region_into(r, &mut px);+ let al: Vec<f32> = (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).map(move |x| alpha.at(x, y))).collect();+ let wts: Vec<f32> = (0..rw * rh).map(|i| if al[i] >= 0.98 { if fmt.alpha { px[i * n + n - 1] } else { 1.0 } } else { 0.0 }).collect();+ let den = box_mean(&wts, rw, rh, rad);+ let den2 = box_mean(&wts, rw, rh, rad * 4);+ let mut nums = Vec::with_capacity(nc);+ for c in 0..nc {+ let v: Vec<f32> = (0..rw * rh).map(|i| wts[i] * px[i * n + c]).collect();+ nums.push((box_mean(&v, rw, rh, rad), box_mean(&v, rw, rh, rad * 4)));+ }+ let (cx, cy, cw, ch) = ((t.x0 - r.x0) as usize, (t.y0 - r.y0) as usize, t.width() as usize, t.height() as usize);+ let mut out = Vec::with_capacity(cw * ch * n);+ for yy in 0..ch {+ for xx in 0..cw {+ let i = (cy + yy) * rw + cx + xx;+ let a = al[i];+ let k = if soft(a) { amount * ((1.0 - a) * 4.0).clamp(0.0, 1.0) } else { 0.0 };+ for c in 0..n {+ let v = px[i * n + c];+ if c >= nc || k == 0.0 {+ out.push(v);+ continue;+ }+ let f = if den[i] > 1e-4 {+ nums[c].0[i] / den[i]+ } else if den2[i] > 1e-4 {+ nums[c].1[i] / den2[i]+ } else {+ v+ };+ out.push(v + (f - v) * k);+ }+ }+ }+ Some((*t, out))+ });+ let mut out = src.clone();+ for (t, data) in results {+ out.write_region(t, &data);+ }+ out+}++/// The pixels of `src` with their alpha multiplied by `alpha` (zero outside its box); the result+/// has an alpha channel even if `src` does not.+pub fn masked_copy(src: &Surface, alpha: &Region) -> Surface {+ let fmt = src.format();+ let n = fmt.channels();+ let out_fmt = PixelFormat { alpha: true, ..fmt };+ let m = out_fmt.channels();+ let results = par_tiles(&tiles_of(alpha.bbox), |t| {+ let mut px = Vec::new();+ src.read_region_into(*t, &mut px);+ let mut out = Vec::with_capacity(t.width() as usize * t.height() as usize * m);+ let mut any = false;+ let mut i = 0;+ for y in t.y0..t.y1 {+ for x in t.x0..t.x1 {+ let a = alpha.at(x, y);+ let p = &px[i * n..(i + 1) * n];+ out.extend_from_slice(&p[..m - 1]);+ let sa = if fmt.alpha { p[n - 1] } else { 1.0 };+ out.push(sa * a);+ any |= sa * a > 0.0;+ i += 1;+ }+ }+ any.then_some((*t, out))+ });+ let mut out = Surface::new(out_fmt);+ for (t, data) in results {+ out.write_region(t, &data);+ }+ out.prune();+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::segment::ImageSampler;+ use photocraft_color::SampleType;++ /// Horizontal blend from `a` (left) to `b` (right) across a Gaussian-blurred edge at x = 40.+ fn blurred_edge(w: usize, h: usize, sigma: f32) -> (RgbImage, Vec<f32>) {+ let (a, b) = ([0.9f32, 0.8, 0.2], [0.1f32, 0.2, 0.6]);+ // True foreground fraction (a = foreground) = 1 − Φ((x − 40) / σ).+ let erf = |x: f32| {+ let t = 1.0 / (1.0 + 0.327_591_1 * x.abs());+ let y = 1.0 - (((((1.061_405_4 * t - 1.453_152_1) * t) + 1.421_413_7) * t - 0.284_496_74) * t + 0.254_829_6) * t * (-x * x).exp();+ if x >= 0.0 { y } else { -y }+ };+ let alpha: Vec<f32> = (0..w).map(|x| 0.5 * (1.0 - erf((x as f32 + 0.5 - 40.0) / (sigma * std::f32::consts::SQRT_2)))).collect();+ let img = RgbImage::from_fn(w, h, |x, _| [0, 1, 2].map(|c| a[c] * alpha[x] + b[c] * (1.0 - alpha[x])));+ (img, alpha)+ }++ #[test]+ fn max_square_matches_naive() {+ let (w, h) = (17, 11);+ let src: Vec<f32> = (0..w * h).map(|i| ((i * 37) % 23) as f32).collect();+ for r in [1usize, 2, 5] {+ for max in [true, false] {+ let fast = max_square(&src, w, h, r, max);+ for y in 0..h {+ for x in 0..w {+ let mut v = if max { f32::MIN } else { f32::MAX };+ for yy in y.saturating_sub(r)..(y + r + 1).min(h) {+ for xx in x.saturating_sub(r)..(x + r + 1).min(w) {+ v = if max { v.max(src[yy * w + xx]) } else { v.min(src[yy * w + xx]) };+ }+ }+ assert_eq!(fast[y * w + x], v, "r={r} max={max} ({x},{y})");+ }+ }+ }+ }+ }++ #[test]+ fn box_mean_matches_naive() {+ let (w, h) = (13, 9);+ let src: Vec<f32> = (0..w * h).map(|i| ((i * 7) % 11) as f32).collect();+ let fast = box_mean(&src, w, h, 2);+ for y in 0..h {+ for x in 0..w {+ let (mut s, mut n) = (0.0, 0.0);+ for yy in y.saturating_sub(2)..(y + 3).min(h) {+ for xx in x.saturating_sub(2)..(x + 3).min(w) {+ s += src[yy * w + xx];+ n += 1.0;+ }+ }+ assert!((fast[y * w + x] - s / n).abs() < 1e-4);+ }+ }+ }++ #[test]+ fn guided_filter_matting_softens_blurred_edge() {+ let (w, h) = (80usize, 20usize);+ let (img, truth) = blurred_edge(w, h, 3.0);+ let m: Vec<f32> = (0..w * h).map(|i| if (i % w) < 40 { 1.0 } else { 0.0 }).collect();+ let p = RefineParams { radius: 10.0, ..Default::default() };+ let a = refine_buffer(Some(&img), &m, w, h, &p);+ let row = &a[10 * w..11 * w];+ let soft = row.iter().filter(|v| **v > 0.05 && **v < 0.95).count();+ assert!(soft >= 6, "only {soft} soft pixels: {row:?}");+ for x in 0..w {+ assert!((row[x] - truth[x]).abs() < 0.12, "x={x}: {} vs {}", row[x], truth[x]);+ if x > 0 {+ assert!(row[x] <= row[x - 1] + 0.02, "not monotone at {x}");+ }+ }+ // Outside the band the mask is untouched.+ assert_eq!(row[5], 1.0);+ assert_eq!(row[75], 0.0);+ // Smart radius keeps a sharp edge sharp.+ let sharp = RgbImage::from_fn(w, h, |x, _| if x < 40 { [0.9, 0.8, 0.2] } else { [0.1, 0.2, 0.6] });+ let s = refine_buffer(Some(&sharp), &m, w, h, &RefineParams { radius: 10.0, smart_radius: true, ..Default::default() });+ let soft = s[10 * w..11 * w].iter().filter(|v| **v > 0.05 && **v < 0.95).count();+ assert!(soft <= 2, "sharp edge became soft: {soft}");+ }++ #[test]+ fn feather_contrast_and_shift() {+ let (w, h) = (60usize, 10usize);+ let m: Vec<f32> = (0..w * h).map(|i| if (i % w) < 30 { 1.0 } else { 0.0 }).collect();+ let f = refine_buffer(None, &m, w, h, &RefineParams { feather: 6.0, ..Default::default() });+ assert!(f[5 * w + 29] > 0.5 && f[5 * w + 29] < 0.8 && f[5 * w + 31] > 0.1);+ let c = refine_buffer(None, &f, w, h, &RefineParams { contrast: 100.0, ..Default::default() });+ assert!(c[5 * w + 29] == 1.0 && c[5 * w + 31] == 0.0);+ let grown = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: 100.0, ..Default::default() });+ assert_eq!(grown[5 * w + 33], 1.0);+ assert_eq!(grown[5 * w + 34], 0.0);+ let shrunk = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: -50.0, ..Default::default() });+ assert_eq!(shrunk[5 * w + 27], 1.0);+ assert_eq!(shrunk[5 * w + 28], 0.0);+ let sm = refine_buffer(None, &m, w, h, &RefineParams { smooth: 50.0, ..Default::default() });+ assert!(sm[5 * w + 10] == 1.0 && sm[5 * w + 50] == 0.0);+ }++ #[test]+ fn refine_mask_tiles_match_single_buffer() {+ // Tiled processing gives the same result as processing the whole image at once.+ let (w, h) = (600usize, 300usize);+ let (img, _) = blurred_edge(w, h, 2.0);+ let s = ImageSampler { img: &img, origin: (0, 0) };+ let mut mask = vec![0u8; w * h];+ for y in 0..h {+ for x in 0..w {+ let (dx, dy) = (x as f32 - 40.0, y as f32 - 150.0);+ mask[y * w + x] = if dx * dx * 0.05 + dy * dy < 120.0 * 120.0 || x < 40 { 255 } else { 0 };+ }+ }+ let reg = Region { bbox: Rect::new(0, 0, w as i32, h as i32), mask };+ let p = RefineParams { radius: 6.0, feather: 2.0, contrast: 10.0, ..Default::default() };+ let canvas = reg.bbox;+ let out = refine_mask(&s, ®ion_reader(®), canvas, canvas, &p).unwrap();+ let whole: Vec<f32> = reg.mask.iter().map(|v| *v as f32 / 255.0).collect();+ let full = refine_buffer(Some(&img), &whole, w, h, &p);+ let mut maxd = 0.0f32;+ for y in 0..h {+ for x in 0..w {+ maxd = maxd.max((out.at(x as i32, y as i32) - full[y * w + x]).abs());+ }+ }+ assert!(maxd <= 1.5 / 255.0, "tiles differ by {maxd}");+ }++ #[test]+ fn decontaminate_and_masked_copy_any_depth() {+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {+ let fmt = PixelFormat::RGBA8.with_sample(sample);+ let mut s = Surface::new(fmt);+ // Foreground red on the left, background blue on the right; fringe pixel at x = 10 is a mix.+ s.fill_rect(Rect::new(0, 0, 10, 8), &[1.0, 0.0, 0.0, 1.0]);+ s.fill_rect(Rect::new(10, 0, 20, 8), &[0.5, 0.0, 0.5, 1.0]);+ s.fill_rect(Rect::new(11, 0, 20, 8), &[0.0, 0.0, 1.0, 1.0]);+ let mask: Vec<u8> = (0..20 * 8).map(|i| match i % 20 { x if x < 10 => 255, 10 => 128, _ => 0 }).collect();+ let a = Region { bbox: Rect::new(0, 0, 20, 8), mask };+ let d = decontaminate(&s, &a, 3.0, 100.0);+ let p = d.pixel(10, 4);+ assert!(p[0] > 0.9 && p[2] < 0.1, "{sample:?}: {p:?}");+ assert_eq!(d.pixel(15, 4), s.pixel(15, 4));+ let c = masked_copy(&d, &a);+ assert_eq!(c.format(), fmt);+ assert!((c.pixel(10, 4)[3] - 128.0 / 255.0).abs() < 0.01);+ assert_eq!(c.pixel(15, 4)[3], 0.0);+ assert_eq!(c.pixel(3, 3)[0], 1.0);+ }+ // Sources without alpha gain an alpha channel.+ let mut g = Surface::new(PixelFormat::GRAY8);+ g.fill_rect(Rect::new(0, 0, 4, 4), &[0.5]);+ let a = Region { bbox: Rect::new(0, 0, 2, 4), mask: vec![255; 8] };+ let c = masked_copy(&g, &a);+ assert_eq!(c.format(), PixelFormat::GRAYA8);+ assert_eq!(c.pixel(3, 1)[1], 0.0);+ assert!((c.pixel(1, 1)[0] - 0.5).abs() < 0.01 && c.pixel(1, 1)[1] == 1.0);+ }+}diff --git a/crates/algo/src/noise.rs b/crates/algo/src/noise.rsindex c80b0599f..8f4cea4ca 100644--- a/crates/algo/src/noise.rs+++ b/crates/algo/src/noise.rs@@ -32,7 +32,7 @@ pub(crate) fn add(src: &Image, out: Rect, ctx: &Ctx, amount: f32, dist: Distribucontinue;}let (x, y) = (out.x0 + (i % w) as i32, out.y0 + (i / w) as i32);- for c in 0..cc {+ for (c, pv) in px.iter_mut().enumerate().take(cc) {let ch = if mono { 0 } else { c as u32 };let v = match dist {Distribution::Uniform => (hash01(x, y, ch, seed) - 0.5) * 2.0 * a,@@ -43,7 +43,7 @@ pub(crate) fn add(src: &Image, out: Rect, ctx: &Ctx, amount: f32, dist: Distribu}};// Integer storage clamps on write; float surfaces keep the value.- px[c] += v;+ *pv += v;}}resdiff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rsnew file mode 100644index 000000000..ba01c2c00--- /dev/null+++ b/crates/algo/src/paint.rs@@ -0,0 +1,205 @@+//! Paint helpers: bucket fill and the gradient tool.++use photocraft_color::blend::{self, BlendMode};+use photocraft_geom::Rect;+use photocraft_raster::{Surface, from_rgba_into};+use serde::{Deserialize, Serialize};++/// Gradient tool shape.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum GradientShape {+ #[default]+ Linear,+ Radial,+ Angle,+ Reflected,+ Diamond,+}++/// Gradient tool parameter `t` for a drag from `from` to `to`.+pub fn tool_gradient_t(shape: GradientShape, from: (f32, f32), to: (f32, f32), x: f32, y: f32) -> f32 {+ let (dx, dy) = (to.0 - from.0, to.1 - from.1);+ let len = (dx * dx + dy * dy).sqrt().max(1e-6);+ let (ux, uy) = (dx / len, dy / len);+ let (px, py) = (x - from.0, y - from.1);+ let along = px * ux + py * uy;+ let across = -px * uy + py * ux;+ let t = match shape {+ GradientShape::Linear => along / len,+ GradientShape::Radial => (px * px + py * py).sqrt() / len,+ GradientShape::Reflected => along.abs() / len,+ GradientShape::Diamond => (along.abs() + across.abs()) / len,+ GradientShape::Angle => (across.atan2(along) / std::f32::consts::TAU).rem_euclid(1.0),+ };+ t.clamp(0.0, 1.0)+}++/// Samples RGBA stops (sorted by position) at `t`.+pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] {+ match stops {+ [] => [0.0; 4],+ [s] => s.1,+ _ => {+ if t <= stops[0].0 {+ return stops[0].1;+ }+ for w in stops.windows(2) {+ if t <= w[1].0 {+ let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 };+ return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k);+ }+ }+ stops[stops.len() - 1].1+ }+ }+}++/// Composites `color(i)` over `area` of the surface with per-pixel coverage.+fn composite_area(+ s: &mut Surface,+ area: Rect,+ blend_mode: BlendMode,+ coverage: impl Fn(i32, i32) -> f32 + Sync,+ color: impl Fn(i32, i32) -> [f32; 4] + Sync,+ lock_transparency: bool,+) {+ // Composite tile by tile (in parallel on native); tiles with zero coverage are left untouched,+ // so their copy-on-write storage (and GPU residency) survives.+ let fmt = s.format();+ let n = fmt.channels();+ let tiles: Vec<Rect> = area.tiles().map(|tc| tc.rect().intersect(&area)).filter(|r| !r.is_empty()).collect();+ let src: &Surface = s;+ let work = |r: &Rect| -> Option<(Rect, Vec<f32>)> {+ let w = r.width() as usize;+ let mut any = false;+ let mut region: Vec<f32> = Vec::new();+ let mut enc = [0.0f32; 8];+ for y in r.y0..r.y1 {+ for x in r.x0..r.x1 {+ let k = coverage(x, y);+ if k <= 0.0 {+ continue;+ }+ if !any {+ region = src.read_region(*r);+ any = true;+ }+ let i = ((y - r.y0) as usize * w + (x - r.x0) as usize) * n;+ let px = &mut region[i..i + n];+ let d = photocraft_raster::to_rgba(&fmt, px);+ let mut o = blend::composite(blend_mode, d, color(x, y), k);+ if lock_transparency {+ o[3] = d[3];+ }+ from_rgba_into(&fmt, o, &mut enc);+ px.copy_from_slice(&enc[..n]);+ }+ }+ any.then_some((*r, region))+ };+ #[cfg(not(target_arch = "wasm32"))]+ let done: Vec<(Rect, Vec<f32>)> = {+ use rayon::prelude::*;+ tiles.par_iter().filter_map(work).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let done: Vec<(Rect, Vec<f32>)> = tiles.iter().filter_map(work).collect();+ for (r, region) in done {+ s.write_region(r, ®ion);+ }+}++/// Gradient tool over `area` (the selection bounds or canvas).+#[allow(clippy::too_many_arguments)]+pub fn paint_gradient(+ s: &mut Surface,+ area: Rect,+ from: (f32, f32),+ to: (f32, f32),+ shape: GradientShape,+ stops: &[(f32, [f32; 4])],+ reverse: bool,+ opacity: f32,+ blend_mode: BlendMode,+ selection: Option<&Surface>,+) {+ composite_area(+ s,+ area,+ blend_mode,+ |x, y| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)),+ |x, y| {+ let t = tool_gradient_t(shape, from, to, x as f32 + 0.5, y as f32 + 0.5);+ sample_stops(stops, if reverse { 1.0 - t } else { t })+ },+ false,+ );+}++/// Paint bucket: fills the region similar to the seed pixel (on the layer's+/// own pixels) within `area`, respecting the selection.+#[allow(clippy::too_many_arguments)]+pub fn bucket_fill(+ s: &mut Surface,+ area: Rect,+ seed: (i32, i32),+ tolerance: f32,+ contiguous: bool,+ anti_alias: bool,+ color: [f32; 4],+ opacity: f32,+ selection: Option<&Surface>,+) -> bool {+ if !area.contains(seed.0, seed.1) {+ return false;+ }+ let img = crate::selection::rgba8_image(s, area);+ let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false };+ drop(img);+ // Composite only over the filled region's box.+ let b = region.bbox;+ composite_area(s, b, BlendMode::Normal, |x, y| region.at(x, y) * opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)), |_, _| color, false);+ true+}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_color::PixelFormat;++ #[test]+ fn gradient_t_shapes() {+ let (f, t) = ((0.0, 0.0), (10.0, 0.0));+ assert_eq!(tool_gradient_t(GradientShape::Linear, f, t, 5.0, 3.0), 0.5);+ assert_eq!(tool_gradient_t(GradientShape::Linear, f, t, -5.0, 0.0), 0.0);+ assert_eq!(tool_gradient_t(GradientShape::Radial, f, t, 0.0, 5.0), 0.5);+ assert_eq!(tool_gradient_t(GradientShape::Reflected, f, t, -5.0, 0.0), 0.5);+ assert_eq!(tool_gradient_t(GradientShape::Diamond, f, t, 2.5, 2.5), 0.5);+ assert!((tool_gradient_t(GradientShape::Angle, f, t, 0.0, 5.0) - 0.25).abs() < 1e-5);+ }++ #[test]+ fn gradient_paints_ramp_within_selection() {+ let mut s = Surface::new(PixelFormat::RGBA8);+ let a = Rect::new(0, 0, 11, 2);+ let mut sel = Surface::new(PixelFormat::GRAY8);+ sel.fill_rect(Rect::new(0, 0, 11, 1), &[1.0]);+ paint_gradient(&mut s, a, (0.5, 0.0), (10.5, 0.0), GradientShape::Linear, &[(0.0, [0.0, 0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 1.0, 1.0])], false, 1.0, BlendMode::Normal, Some(&sel));+ assert!(s.pixel(0, 0)[0] < 0.01 && s.pixel(10, 0)[0] > 0.99);+ assert!((s.pixel(5, 0)[0] - 0.5).abs() < 0.01);+ assert_eq!(s.pixel(5, 1)[3], 0.0, "outside the selection");+ }++ #[test]+ fn bucket_fills_contiguous_region() {+ let mut s = Surface::new(PixelFormat::RGBA8);+ let a = Rect::new(0, 0, 10, 10);+ s.fill_rect(a, &[1.0, 1.0, 1.0, 1.0]);+ s.fill_rect(Rect::new(5, 0, 6, 10), &[0.0, 0.0, 0.0, 1.0]);+ assert!(bucket_fill(&mut s, a, (1, 1), 10.0, true, false, [1.0, 0.0, 0.0, 1.0], 1.0, None));+ assert_eq!(s.pixel(2, 2), vec![1.0, 0.0, 0.0, 1.0]);+ assert_eq!(s.pixel(8, 2), vec![1.0, 1.0, 1.0, 1.0]);+ assert!(!bucket_fill(&mut s, a, (50, 1), 10.0, true, false, [1.0, 0.0, 0.0, 1.0], 1.0, None));+ }+}diff --git a/crates/algo/src/poisson.rs b/crates/algo/src/poisson.rsnew file mode 100644index 000000000..9ad965070--- /dev/null+++ b/crates/algo/src/poisson.rs@@ -0,0 +1,298 @@+//! Gradient-domain ("Poisson") blending, the core of the Healing Brush and Spot Healing.+//!+//! Method: P. Pérez, M. Gangnet, A. Blake, *Poisson Image Editing*, ACM SIGGRAPH 2003. Seamless+//! cloning finds `f` over a region Ω minimising `∬_Ω |∇f − v|²` with `f = f*` (the destination) on+//! the boundary ∂Ω, which gives the Poisson equation `Δf = div v`. With the guidance field taken as+//! the source gradient, `v = ∇g`, the solution splits as `f = g + h` where `h` is the *membrane*+//! (harmonic) interpolant of the boundary mismatch: `Δh = 0` in Ω, `h = f* − g` on ∂Ω (§3 of the+//! paper). So the healed pixels keep the source's texture (its gradients) while their colour and+//! lighting are pulled to match the destination around the stroke.+//!+//! The Laplace equation is solved on the 4-connected pixel grid by successive over-relaxation (SOR,+//! Gauss–Seidel with over-relaxation), accelerated *cascadically*: the problem is restricted to a+//! half-resolution grid recursively, solved there, bilinearly prolonged as the initial guess, and only+//! a few SOR sweeps are needed per level to remove the remaining high-frequency error. Harmonic+//! functions are smooth, so the coarse guess is already close; this keeps a 300 px dab at a few+//! milliseconds.+//!+//! Buffers are planar-per-call but interleaved at the API: `w × h × ch` normalised floats in any+//! colour model (channels are solved independently, in parallel on native targets).++/// Convergence threshold (max per-sweep update) for the SOR sweeps.+const TOL: f32 = 2e-5;+/// SOR sweeps (cap) and relaxation factor on every level above the coarsest: tuned so a 96×72 disc+/// is within ~1e-3 of a fully converged Gauss–Seidel solve (below one 8-bit step).+const FINE_ITERS: usize = 30;+const FINE_OMEGA: f32 = 1.7;++/// Solve `Δv = 0` on `unknown` pixels with Dirichlet values from the known pixels of `v`+/// (out-of-grid neighbours are ignored, i.e. a Neumann boundary). `v` holds the known values on+/// entry and the solution on exit. Cascadic multigrid + SOR.+pub fn solve_membrane(w: usize, h: usize, unknown: &[bool], v: &mut [f32]) {+ assert_eq!(unknown.len(), w * h);+ assert_eq!(v.len(), w * h);+ solve_rec(w, h, unknown, v, 0);+}++fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize) {+ let n_unknown = unknown.iter().filter(|u| **u).count();+ if n_unknown == 0 {+ return;+ }+ let known: Vec<f32> = v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x).collect();+ if known.is_empty() {+ return; // nothing to interpolate from+ }+ if w >= 8 && h >= 8 && n_unknown > 64 && depth < 16 {+ // Restrict: a coarse pixel is known if any of its children is (value = mean of known children).+ let (cw, chh) = (w.div_ceil(2), h.div_ceil(2));+ let mut cu = vec![true; cw * chh];+ let mut cv = vec![0.0f32; cw * chh];+ for cy in 0..chh {+ for cx in 0..cw {+ let (mut s, mut n) = (0.0f32, 0u32);+ for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {+ let (x, y) = (cx * 2 + dx, cy * 2 + dy);+ if x < w && y < h && !unknown[y * w + x] {+ s += v[y * w + x];+ n += 1;+ }+ }+ if n > 0 {+ cu[cy * cw + cx] = false;+ cv[cy * cw + cx] = s / n as f32;+ }+ }+ }+ solve_rec(cw, chh, &cu, &mut cv, depth + 1);+ // Prolong: bilinear sample of the coarse solution as the initial guess.+ for y in 0..h {+ let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (chh - 1) as f32);+ let y0 = fy.floor() as usize;+ let y1 = (y0 + 1).min(chh - 1);+ let ty = fy - y0 as f32;+ for x in 0..w {+ if !unknown[y * w + x] {+ continue;+ }+ let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (cw - 1) as f32);+ let x0 = fx.floor() as usize;+ let x1 = (x0 + 1).min(cw - 1);+ let tx = fx - x0 as f32;+ let a = cv[y0 * cw + x0] + (cv[y0 * cw + x1] - cv[y0 * cw + x0]) * tx;+ let b = cv[y1 * cw + x0] + (cv[y1 * cw + x1] - cv[y1 * cw + x0]) * tx;+ v[y * w + x] = a + (b - a) * ty;+ }+ }+ sor(w, h, unknown, v, FINE_ITERS, FINE_OMEGA);+ } else {+ let mean = known.iter().sum::<f32>() / known.len() as f32;+ for (x, u) in v.iter_mut().zip(unknown) {+ if *u {+ *x = mean;+ }+ }+ sor(w, h, unknown, v, 2000, 1.85);+ }+}++/// SOR sweeps over the unknown pixels until the largest update drops below [`TOL`].+fn sor(w: usize, h: usize, unknown: &[bool], v: &mut [f32], max_iter: usize, omega: f32) {+ // Precompute the unknown pixels and which neighbours exist.+ let cells: Vec<(u32, u8)> = (0..w * h)+ .filter(|&i| unknown[i])+ .map(|i| {+ let (x, y) = (i % w, i / w);+ let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3);+ (i as u32, m)+ })+ .collect();+ for _ in 0..max_iter {+ let mut max_d = 0.0f32;+ for &(i, m) in &cells {+ let i = i as usize;+ let (s, n) = if m == 0b1111 {+ (v[i - 1] + v[i + 1] + v[i - w] + v[i + w], 4.0)+ } else {+ let mut s = 0.0;+ let mut n = 0.0;+ if m & 1 != 0 {+ s += v[i - 1];+ n += 1.0;+ }+ if m & 2 != 0 {+ s += v[i + 1];+ n += 1.0;+ }+ if m & 4 != 0 {+ s += v[i - w];+ n += 1.0;+ }+ if m & 8 != 0 {+ s += v[i + w];+ n += 1.0;+ }+ if n == 0.0 {+ continue;+ }+ (s, n)+ };+ let d = omega * (s / n - v[i]);+ v[i] += d;+ max_d = max_d.max(d.abs());+ }+ if max_d < TOL {+ break;+ }+ }+}++/// Reference solver for tests: plain Gauss–Seidel from a zero start until the update is below `tol`.+pub fn solve_membrane_reference(w: usize, h: usize, unknown: &[bool], v: &mut [f32], tol: f32, max_iter: usize) {+ for (x, u) in v.iter_mut().zip(unknown) {+ if *u {+ *x = 0.0;+ }+ }+ for _ in 0..max_iter {+ let mut max_d = 0.0f32;+ for y in 0..h {+ for x in 0..w {+ let i = y * w + x;+ if !unknown[i] {+ continue;+ }+ let (mut s, mut n) = (0.0, 0.0);+ for (nx, ny) in [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)] {+ if nx < w && ny < h {+ s += v[ny * w + nx];+ n += 1.0;+ }+ }+ if n > 0.0 {+ let nv = s / n;+ max_d = max_d.max((nv - v[i]).abs());+ v[i] = nv;+ }+ }+ }+ if max_d < tol {+ break;+ }+ }+}++/// Map `f` over the channels of an interleaved buffer as planar slices (parallel on native).+fn per_channel(w: usize, h: usize, ch: usize, f: impl Fn(usize) -> Vec<f32> + Sync + Send) -> Vec<f32> {+ #[cfg(not(target_arch = "wasm32"))]+ let planes: Vec<Vec<f32>> = if w * h >= 64 * 64 {+ use rayon::prelude::*;+ (0..ch).into_par_iter().map(&f).collect()+ } else {+ (0..ch).map(&f).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let planes: Vec<Vec<f32>> = (0..ch).map(&f).collect();+ let mut out = vec![0.0f32; w * h * ch];+ for (c, p) in planes.iter().enumerate() {+ for (i, v) in p.iter().enumerate() {+ out[i * ch + c] = *v;+ }+ }+ out+}++/// Seamless cloning (Pérez et al. 2003, guidance field `v = ∇src`): returns `f` with `f = dst` outside+/// `mask` and, inside, `src` plus the membrane that removes the boundary mismatch. So the result keeps+/// the source's texture and takes the destination's colour and lighting.+///+/// `src`/`dst` are interleaved `w × h × ch`; `mask` has `w × h` entries (`true` = healed). Pixels on the+/// grid edge that are in the mask see a Neumann (free) boundary there, so callers should leave a one+/// pixel unmasked margin for a fully Dirichlet problem.+pub fn seamless_clone(w: usize, h: usize, ch: usize, src: &[f32], dst: &[f32], mask: &[bool]) -> Vec<f32> {+ assert_eq!(src.len(), w * h * ch);+ assert_eq!(dst.len(), w * h * ch);+ assert_eq!(mask.len(), w * h);+ per_channel(w, h, ch, |c| {+ let mut hv: Vec<f32> = (0..w * h).map(|i| if mask[i] { 0.0 } else { dst[i * ch + c] - src[i * ch + c] }).collect();+ solve_membrane(w, h, mask, &mut hv);+ (0..w * h).map(|i| if mask[i] { src[i * ch + c] + hv[i] } else { dst[i * ch + c] }).collect()+ })+}++/// Membrane fill (no source texture): harmonic interpolation of the known pixels into `hole`.+pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) -> Vec<f32> {+ per_channel(w, h, ch, |c| {+ let mut v: Vec<f32> = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect();+ solve_membrane(w, h, hole, &mut v);+ v+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec<bool> {+ (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect()+ }++ #[test]+ fn membrane_reproduces_linear_boundary() {+ // A linear function is harmonic: the solve must reproduce it exactly inside the hole.+ let (w, h) = (80, 60);+ let unknown = disc(w, h, 40.0, 30.0, 20.0);+ let truth: Vec<f32> = (0..w * h).map(|i| 0.2 + 0.005 * (i % w) as f32 + 0.003 * (i / w) as f32).collect();+ let mut v: Vec<f32> = truth.iter().zip(&unknown).map(|(t, u)| if *u { 0.0 } else { *t }).collect();+ solve_membrane(w, h, &unknown, &mut v);+ let err = v.iter().zip(&truth).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max);+ assert!(err < 2e-3, "{err}");+ }++ #[test]+ fn multigrid_matches_reference_solve() {+ let (w, h) = (96, 72);+ let unknown = disc(w, h, 45.0, 36.0, 28.0);+ // Arbitrary, non-harmonic boundary data.+ let init: Vec<f32> = (0..w * h).map(|i| ((i % w) as f32 * 0.21).sin() * 0.3 + ((i / w) as f32 * 0.13).cos() * 0.2 + 0.5).collect();+ let mut fast = init.clone();+ solve_membrane(w, h, &unknown, &mut fast);+ let mut reference = init.clone();+ solve_membrane_reference(w, h, &unknown, &mut reference, 1e-7, 100_000);+ let err = fast.iter().zip(&reference).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max);+ assert!(err < 2e-3, "max error vs reference {err}");+ // Known pixels untouched.+ assert!(fast.iter().zip(&init).zip(&unknown).all(|((a, b), u)| *u || a == b));+ }++ #[test]+ fn seamless_clone_takes_destination_colour_and_source_texture() {+ let (w, h, ch) = (64, 64, 3);+ let mask = disc(w, h, 32.0, 32.0, 20.0);+ // Destination: flat reddish; source: bluish with a stripe texture.+ let dst: Vec<f32> = (0..w * h).flat_map(|_| [0.7, 0.3, 0.2]).collect();+ let tex = |x: usize| if (x / 4).is_multiple_of(2) { 0.05 } else { -0.05 };+ let src: Vec<f32> = (0..w * h).flat_map(|i| {+ let t = tex(i % w);+ [0.1 + t, 0.2 + t, 0.8 + t]+ }).collect();+ let out = seamless_clone(w, h, ch, &src, &dst, &mask);+ // Mean colour inside the mask matches the destination.+ let inside: Vec<usize> = (0..w * h).filter(|&i| mask[i]).collect();+ for c in 0..ch {+ let m = inside.iter().map(|&i| out[i * ch + c]).sum::<f32>() / inside.len() as f32;+ assert!((m - dst[c]).abs() < 0.02, "channel {c} mean {m}");+ }+ // Source gradients carried: horizontal differences inside match the source's.+ let (mut e, mut n) = (0.0f32, 0);+ for &i in &inside {+ if mask[i + 1] {+ e += ((out[(i + 1) * ch] - out[i * ch]) - (src[(i + 1) * ch] - src[i * ch])).abs();+ n += 1;+ }+ }+ assert!(e / (n as f32) < 0.01, "gradient error {}", e / n as f32);+ // Outside untouched.+ assert_eq!(&out[..3], &dst[..3]);+ }+}diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rsnew file mode 100644index 000000000..63a4f724d--- /dev/null+++ b/crates/algo/src/resample.rs@@ -0,0 +1,289 @@+//! High-quality separable resampling of surfaces (Image Size).++use photocraft_geom::Rect;+use photocraft_raster::Surface;+use serde::{Deserialize, Serialize};++use crate::image::{premultiply, unpremultiply};++/// Resampling method (Photoshop's Image Size options).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum Resample {+ Nearest,+ Bilinear,+ #[default]+ Bicubic,+ Lanczos,+ /// Lanczos followed by a light sharpening when enlarging.+ PreserveDetails,+}++impl Resample {+ fn support(self) -> f64 {+ match self {+ Resample::Nearest => 0.5,+ Resample::Bilinear => 1.0,+ Resample::Bicubic => 2.0,+ Resample::Lanczos | Resample::PreserveDetails => 3.0,+ }+ }+ fn weight(self, x: f64) -> f64 {+ let x = x.abs();+ match self {+ Resample::Nearest => {+ if x <= 0.5 {+ 1.0+ } else {+ 0.0+ }+ }+ Resample::Bilinear => (1.0 - x).max(0.0),+ Resample::Bicubic => {+ // Keys cubic, a = -0.5 (Catmull-Rom).+ let a = -0.5;+ if x < 1.0 {+ (a + 2.0) * x * x * x - (a + 3.0) * x * x + 1.0+ } else if x < 2.0 {+ a * x * x * x - 5.0 * a * x * x + 8.0 * a * x - 4.0 * a+ } else {+ 0.0+ }+ }+ Resample::Lanczos | Resample::PreserveDetails => {+ if x < 1e-9 {+ 1.0+ } else if x < 3.0 {+ let px = std::f64::consts::PI * x;+ 3.0 * px.sin() * (px / 3.0).sin() / (px * px)+ } else {+ 0.0+ }+ }+ }+ }+}++/// Per-output-sample source window and normalized weights.+struct Taps {+ start: i32,+ weights: Vec<f32>,+}++/// Taps for mapping output coordinate `o` (in `[dst0, dst1)`) to the source+/// via `u = (o + 0.5) / scale - 0.5`.+fn taps(dst0: i32, dst1: i32, scale: f64, filter: Resample) -> Vec<Taps> {+ let stretch = if scale < 1.0 { 1.0 / scale } else { 1.0 };+ let support = filter.support() * stretch;+ (dst0..dst1)+ .map(|o| {+ let u = (o as f64 + 0.5) / scale - 0.5;+ if filter == Resample::Nearest && scale >= 1.0 {+ return Taps { start: (u + 0.5).floor() as i32, weights: vec![1.0] };+ }+ let lo = (u - support).ceil() as i32;+ let hi = (u + support).floor() as i32;+ let mut w: Vec<f64> = (lo..=hi).map(|i| filter.weight((i as f64 - u) / stretch)).collect();+ let s: f64 = w.iter().sum();+ if s.abs() > 1e-12 {+ for v in &mut w {+ *v /= s;+ }+ }+ Taps { start: lo, weights: w.into_iter().map(|v| v as f32).collect() }+ })+ .collect()+}++/// Output rectangle for `r` scaled by `(sx, sy)` about the origin.+pub fn scaled_rect(r: Rect, sx: f64, sy: f64) -> Rect {+ if r.is_empty() {+ return Rect::EMPTY;+ }+ Rect::new((r.x0 as f64 * sx).floor() as i32, (r.y0 as f64 * sy).floor() as i32, (r.x1 as f64 * sx).ceil() as i32, (r.y1 as f64 * sy).ceil() as i32)+}++/// Resizes a surface by `(sx, sy)` about the document origin. The surface's+/// default pixel is kept (masks keep their "reveal all" background).+pub fn resize_surface(s: &Surface, sx: f64, sy: f64, filter: Resample) -> Surface {+ let fmt = s.format();+ let mut out = Surface::with_default(fmt, &s.default_pixel());+ let src = s.content_bounds();+ let dst = scaled_rect(src, sx, sy);+ if dst.is_empty() {+ return out;+ }+ let n = fmt.channels();+ let alpha = fmt.alpha;+ let hx = taps(dst.x0, dst.x1, sx, filter);+ let vy = taps(dst.y0, dst.y1, sy, filter);+ let x_lo = hx.iter().map(|t| t.start).min().unwrap_or(0);+ let x_hi = hx.iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(0);+ let dw = dst.width() as usize;+ const BAND: usize = 64;+ let bands: Vec<(usize, usize)> = (0..vy.len()).step_by(BAND).map(|b| (b, (b + BAND).min(vy.len()))).collect();+ let run = |&(b0, b1): &(usize, usize)| -> (Rect, Vec<f32>) {+ let y_lo = vy[b0..b1].iter().map(|t| t.start).min().unwrap_or(0);+ let y_hi = vy[b0..b1].iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(0);+ let read = Rect::new(x_lo, y_lo, x_hi, y_hi);+ let mut rows = s.read_region(read);+ premultiply(&mut rows, n, alpha);+ let rw = read.width() as usize;+ // Horizontal pass: every source row in the band → dw samples.+ let nrows = read.height() as usize;+ let mut tmp = vec![0.0f32; nrows * dw * n];+ for r in 0..nrows {+ let row = &rows[r * rw * n..(r + 1) * rw * n];+ for (ox, t) in hx.iter().enumerate() {+ let d = &mut tmp[(r * dw + ox) * n..(r * dw + ox + 1) * n];+ for (k, w) in t.weights.iter().enumerate() {+ let sx_ = (t.start + k as i32 - x_lo) as usize;+ let sp = &row[sx_ * n..(sx_ + 1) * n];+ for c in 0..n {+ d[c] += sp[c] * w;+ }+ }+ }+ }+ // Vertical pass.+ let mut res = vec![0.0f32; (b1 - b0) * dw * n];+ for (oy, t) in vy[b0..b1].iter().enumerate() {+ let d = &mut res[oy * dw * n..(oy + 1) * dw * n];+ for (k, w) in t.weights.iter().enumerate() {+ let r = (t.start + k as i32 - y_lo) as usize;+ let sp = &tmp[r * dw * n..(r + 1) * dw * n];+ for (dv, sv) in d.iter_mut().zip(sp) {+ *dv += sv * w;+ }+ }+ }+ if alpha {+ for px in res.chunks_exact_mut(n) {+ px[n - 1] = px[n - 1].clamp(0.0, 1.0);+ }+ }+ unpremultiply(&mut res, n, alpha);+ (Rect::new(dst.x0, dst.y0 + b0 as i32, dst.x1, dst.y0 + b1 as i32), res)+ };+ #[cfg(not(target_arch = "wasm32"))]+ let parts: Vec<(Rect, Vec<f32>)> = {+ use rayon::prelude::*;+ bands.par_iter().map(run).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let parts: Vec<(Rect, Vec<f32>)> = bands.iter().map(run).collect();+ for (r, d) in parts {+ out.write_region(r, &d);+ }+ if filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) {+ let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };+ let area = crate::output_area(&p, out.content_bounds(), dst, None);+ out = crate::apply(&out, &p, area, dst, None);+ }+ out.prune();+ out+}++/// Moves a surface by whole pixels (default pixel kept).+pub fn translate_surface(s: &Surface, dx: i32, dy: i32) -> Surface {+ let mut out = Surface::with_default(s.format(), &s.default_pixel());+ let r = s.content_bounds();+ if !r.is_empty() {+ out.write_interleaved(r.translate(dx, dy), &s.to_interleaved(r));+ }+ out+}++/// Keeps only the pixels inside `keep` (others become the default pixel).+pub fn crop_surface(s: &Surface, keep: Rect) -> Surface {+ let mut out = Surface::with_default(s.format(), &s.default_pixel());+ let r = s.content_bounds().intersect(&keep);+ if !r.is_empty() {+ out.write_interleaved(r, &s.to_interleaved(r));+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_color::{ColorMode, PixelFormat, SampleType};++ fn ramp(sample: SampleType) -> Surface {+ let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));+ let r = Rect::new(0, 0, 64, 32);+ let v: Vec<f32> = (0..32).flat_map(|_| (0..64).flat_map(|x| [x as f32 / 63.0, 0.5, 1.0 - x as f32 / 63.0, 1.0])).collect();+ s.write_region(r, &v);+ s+ }++ #[test]+ fn identity_scale_is_lossless() {+ for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] {+ let s = ramp(SampleType::U16);+ let o = resize_surface(&s, 1.0, 1.0, f);+ let r = Rect::new(0, 0, 64, 32);+ let (a, b) = (s.read_region(r), o.read_region(r));+ let d = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);+ assert!(d < 1e-4, "{f:?} {d}");+ }+ }++ #[test]+ fn half_and_double_sizes() {+ for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos, Resample::PreserveDetails] {+ let s = ramp(SampleType::F32);+ let half = resize_surface(&s, 0.5, 0.5, f);+ assert_eq!(half.content_bounds(), Rect::new(0, 0, 32, 16), "{f:?}");+ let p = half.pixel(16, 8);+ assert!((p[1] - 0.5).abs() < 0.02 && (p[3] - 1.0).abs() < 1e-3, "{f:?} {p:?}");+ let dbl = resize_surface(&s, 2.0, 2.0, f);+ assert_eq!(dbl.content_bounds(), Rect::new(0, 0, 128, 64), "{f:?}");+ // Mid-gray channel and the ramp's monotonicity are preserved.+ let row: Vec<f32> = (8..120).map(|x| dbl.pixel(x, 30)[0]).collect();+ assert!(row.windows(2).all(|w| w[1] >= w[0] - 0.02), "{f:?}");+ }+ }++ #[test]+ fn downscale_averages_checkerboard() {+ let mut s = Surface::new(PixelFormat::RGBA8);+ for y in 0..64 {+ for x in 0..64 {+ let v = ((x + y) % 2) as f32;+ s.write_pixel(x, y, &[v, v, v, 1.0]);+ }+ }+ let o = resize_surface(&s, 0.25, 0.25, Resample::Bicubic);+ let p = o.pixel(8, 8);+ assert!((p[0] - 0.5).abs() < 0.05, "{p:?}");+ }++ #[test]+ fn transparent_edges_do_not_darken() {+ let mut s = Surface::new(PixelFormat::RGBA32F);+ s.fill_rect(Rect::new(10, 10, 20, 20), &[1.0, 0.0, 0.0, 1.0]);+ let o = resize_surface(&s, 1.7, 1.7, Resample::Lanczos);+ let edge = o.pixel(17, 25);+ assert!(edge[3] > 0.0 && (edge[0] - 1.0).abs() < 0.05 && edge[1].abs() < 0.05, "{edge:?}");+ }++ #[test]+ fn masks_keep_default_pixel() {+ let fmt = PixelFormat::GRAY8;+ let mut m = Surface::with_default(fmt, &[1.0]);+ m.fill_rect(Rect::new(0, 0, 10, 10), &[0.0]);+ let o = resize_surface(&m, 2.0, 2.0, Resample::Bilinear);+ assert_eq!(o.default_pixel(), vec![1.0]);+ assert!(o.pixel(5, 5)[0] < 0.01);+ }++ #[test]+ fn translate_and_crop() {+ let s = ramp(SampleType::U8);+ let t = translate_surface(&s, 5, -3);+ assert_eq!(t.pixel(15, 7), s.pixel(10, 10));+ let c = crop_surface(&s, Rect::new(0, 0, 10, 10));+ assert_eq!(c.content_bounds(), Rect::new(0, 0, 10, 10));+ }+}diff --git a/crates/algo/src/retouch.rs b/crates/algo/src/retouch.rsnew file mode 100644index 000000000..6e6b8f109--- /dev/null+++ b/crates/algo/src/retouch.rs@@ -0,0 +1,298 @@+//! Per-pixel and per-dab kernels for the toning and focus retouching tools: Dodge, Burn, Sponge,+//! Blur, Sharpen. The brush engine (`photocraft-paint`) decides *where* and *how strongly* each dab+//! applies; these functions decide *what* happens to the pixels.+//!+//! Tone curves are our own design, chosen to match the observed behaviour of Photoshop's tools:+//! the selected range is affected most, pure black and white stay put for Midtones, and+//! "Protect Tones" works on luminance (scaling RGB so hue and saturation are kept, with gamut+//! compression instead of per-channel clipping).++use serde::{Deserialize, Serialize};++/// Tonal range targeted by Dodge/Burn.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum ToneRange {+ Shadows,+ #[default]+ Midtones,+ Highlights,+}++/// Rec. 601 luma of a straight RGB triple.+#[inline]+pub fn luma(c: [f32; 3]) -> f32 {+ 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]+}++/// The dodge/burn transfer for one value `v` (0..1) with strength `e` (0..1).+#[inline]+pub fn tone_curve(v: f32, e: f32, range: ToneRange, burn: bool) -> f32 {+ let v = v.max(0.0);+ let e = e.clamp(0.0, 1.0);+ match (range, burn) {+ // Gamma bend, weighted to peak at mid-grey: 0 and 1 are fixed points.+ (ToneRange::Midtones, false) => {+ let w = (4.0 * v * (1.0 - v)).clamp(0.0, 1.0);+ v + w * (v.min(1.0).powf(1.0 / (1.0 + e)) - v)+ }+ (ToneRange::Midtones, true) => {+ let w = (4.0 * v * (1.0 - v)).clamp(0.0, 1.0);+ v + w * (v.min(1.0).powf(1.0 + e) - v)+ }+ // Shadows / highlights: `v + e·w·(target − v)` with weight (1−v)² or v², so the chosen end+ // moves most (black lifts when dodging shadows, white drops when burning highlights).+ (ToneRange::Shadows, false) => v + e * (1.0 - v.min(1.0)).powi(2) * (1.0 - v.min(1.0)),+ (ToneRange::Shadows, true) => v - e * (1.0 - v.min(1.0)).powi(2) * v,+ (ToneRange::Highlights, false) => v + e * v.min(1.0).powi(2) * (1.0 - v.min(1.0)),+ (ToneRange::Highlights, true) => v - e * v.min(1.0).powi(2) * v,+ }+}++/// Bring an RGB triple back into 0..1 while keeping its luma (mix toward grey), instead of clipping+/// each channel (which would shift hue).+#[inline]+fn compress_gamut(c: [f32; 3], l: f32) -> [f32; 3] {+ let l = l.clamp(0.0, 1.0);+ let (lo, hi) = (c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2]));+ let mut t = 1.0f32;+ if hi > 1.0 && hi - l > 1e-9 {+ t = t.min((1.0 - l) / (hi - l));+ }+ if lo < 0.0 && l - lo > 1e-9 {+ t = t.min(l / (l - lo));+ }+ [l + (c[0] - l) * t, l + (c[1] - l) * t, l + (c[2] - l) * t]+}++/// Dodge (`burn = false`) or Burn one straight-RGB colour with strength `e` (0..1).+///+/// With `protect_tones`, the curve is applied to luma and the colour scaled to the new luma+/// (hue and saturation preserved, gamut-compressed); otherwise each channel goes through the curve.+pub fn dodge_burn(c: [f32; 3], e: f32, range: ToneRange, burn: bool, protect_tones: bool) -> [f32; 3] {+ if e <= 0.0 {+ return c;+ }+ if protect_tones {+ let l = luma(c);+ let nl = tone_curve(l, e, range, burn);+ let out = if l > 1e-6 { [c[0] * nl / l, c[1] * nl / l, c[2] * nl / l] } else { [nl; 3] };+ compress_gamut(out, nl)+ } else {+ [tone_curve(c[0], e, range, burn), tone_curve(c[1], e, range, burn), tone_curve(c[2], e, range, burn)]+ }+}++/// HSV-style saturation (chroma / max) of an RGB triple.+#[inline]+pub fn saturation(c: [f32; 3]) -> f32 {+ let (lo, hi) = (c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2]));+ if hi <= 1e-6 { 0.0 } else { ((hi - lo) / hi).clamp(0.0, 1.0) }+}++/// Sponge: move a colour away from (`saturate`) or toward its luma grey by `amount` (0..1).+///+/// `vibrance` damps the change where it would clip: saturating affects already-saturated colours+/// less, desaturating affects near-grey colours less (so they never fully collapse to grey in one+/// pass). Saturation is gamut-compressed around luma, never clipped per channel.+pub fn sponge(c: [f32; 3], amount: f32, saturate: bool, vibrance: bool) -> [f32; 3] {+ let mut a = amount.clamp(0.0, 1.0);+ if a <= 0.0 {+ return c;+ }+ let s = saturation(c);+ if vibrance {+ a *= if saturate { 1.0 - s } else { 0.25 + 0.75 * s };+ }+ let l = luma(c);+ let k = if saturate { 1.0 + a } else { 1.0 - a };+ compress_gamut([l + (c[0] - l) * k, l + (c[1] - l) * k, l + (c[2] - l) * k], l)+}++/// Gaussian blur of the window `[x0, x1) × [y0, y1)` of an interleaved `w × h × ch` buffer, reading+/// neighbours with edge clamping. With an alpha channel (`alpha = Some(index)`), colour is blurred+/// premultiplied so transparent pixels don't bleed their (meaningless) colour. Returns the window's+/// blurred pixels (`(x1−x0) × (y1−y0) × ch`).+#[allow(clippy::too_many_arguments)]+pub fn local_blur(data: &[f32], w: usize, h: usize, ch: usize, alpha: Option<usize>, win: (usize, usize, usize, usize), sigma: f32) -> Vec<f32> {+ let (x0, y0, x1, y1) = win;+ let (ow, oh) = (x1 - x0, y1 - y0);+ let r = (sigma * 3.0).ceil().max(1.0) as i32;+ let k: Vec<f32> = (-r..=r).map(|i| (-((i * i) as f32) / (2.0 * sigma * sigma).max(1e-6)).exp()).collect();+ let ks: f32 = k.iter().sum();+ let k: Vec<f32> = k.into_iter().map(|v| v / ks).collect();+ let get = |x: i32, y: i32, out: &mut [f32]| {+ let (xx, yy) = (x.clamp(0, w as i32 - 1) as usize, y.clamp(0, h as i32 - 1) as usize);+ let i = (yy * w + xx) * ch;+ out.copy_from_slice(&data[i..i + ch]);+ if let Some(a) = alpha {+ let av = out[a];+ for (c, v) in out.iter_mut().enumerate() {+ if c != a {+ *v *= av;+ }+ }+ }+ };+ // Horizontal pass over the window rows extended vertically by r.+ let th = oh + 2 * r as usize;+ let mut tmp = vec![0.0f32; ow * th * ch];+ let mut px = vec![0.0f32; ch];+ for ty in 0..th {+ let y = y0 as i32 + ty as i32 - r;+ for ox in 0..ow {+ let o = (ty * ow + ox) * ch;+ for (i, kv) in k.iter().enumerate() {+ get(x0 as i32 + ox as i32 + i as i32 - r, y, &mut px);+ for c in 0..ch {+ tmp[o + c] += px[c] * kv;+ }+ }+ }+ }+ let mut out = vec![0.0f32; ow * oh * ch];+ for oy in 0..oh {+ for ox in 0..ow {+ let o = (oy * ow + ox) * ch;+ for (i, kv) in k.iter().enumerate() {+ let s = ((oy + i) * ow + ox) * ch;+ for c in 0..ch {+ out[o + c] += tmp[s + c] * kv;+ }+ }+ if let Some(a) = alpha {+ let av = out[o + a];+ for c in 0..ch {+ if c != a {+ out[o + c] = if av > 1e-6 { out[o + c] / av } else { data[((y0 + oy) * w + x0 + ox) * ch + c] };+ }+ }+ }+ }+ }+ out+}++/// Unsharp-mask sharpen of a window (same layout as [`local_blur`]): `v + amount·(v − blur(v))`.+///+/// With `protect_detail`, each result is clamped to the 3×3 neighbourhood's range, which stops+/// halos and noise from being amplified into new extremes. Alpha is left unchanged.+#[allow(clippy::too_many_arguments)]+pub fn local_sharpen(data: &[f32], w: usize, h: usize, ch: usize, alpha: Option<usize>, win: (usize, usize, usize, usize), amount: f32, protect_detail: bool) -> Vec<f32> {+ let (x0, y0, x1, y1) = win;+ let ow = x1 - x0;+ let blur = local_blur(data, w, h, ch, alpha, win, 1.0);+ let mut out = vec![0.0f32; blur.len()];+ for y in y0..y1 {+ for x in x0..x1 {+ let o = ((y - y0) * ow + (x - x0)) * ch;+ let i = (y * w + x) * ch;+ for c in 0..ch {+ let v = data[i + c];+ if Some(c) == alpha {+ out[o + c] = v;+ continue;+ }+ let mut s = v + amount * (v - blur[o + c]);+ if protect_detail {+ let (mut lo, mut hi) = (v, v);+ for (dx, dy) in [(-1i32, -1i32), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] {+ let (nx, ny) = ((x as i32 + dx).clamp(0, w as i32 - 1) as usize, (y as i32 + dy).clamp(0, h as i32 - 1) as usize);+ let nv = data[(ny * w + nx) * ch + c];+ lo = lo.min(nv);+ hi = hi.max(nv);+ }+ s = s.clamp(lo, hi);+ }+ out[o + c] = s;+ }+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn dodge_midtones_affects_midtones_most() {+ let g = |v: f32| dodge_burn([v; 3], 0.5, ToneRange::Midtones, false, true)[0] - v;+ assert!(g(0.5) > 0.1, "{}", g(0.5));+ assert!(g(0.5) > 2.0 * g(0.1));+ assert!(g(0.5) > 2.0 * g(0.95));+ assert_eq!(dodge_burn([0.0; 3], 0.5, ToneRange::Midtones, false, true), [0.0; 3]);+ let b = dodge_burn([0.5; 3], 0.5, ToneRange::Midtones, true, true)[0];+ assert!(b < 0.45);+ }++ #[test]+ fn ranges_target_their_tones() {+ let d = |v: f32, r| tone_curve(v, 0.5, r, false) - v;+ assert!(d(0.1, ToneRange::Shadows) > d(0.9, ToneRange::Shadows));+ assert!(d(0.9, ToneRange::Highlights) > d(0.1, ToneRange::Highlights));+ let b = |v: f32, r| v - tone_curve(v, 0.5, r, true);+ assert!(b(0.9, ToneRange::Highlights) > b(0.2, ToneRange::Highlights));+ assert!(b(0.3, ToneRange::Shadows) / 0.3 > b(0.9, ToneRange::Shadows) / 0.9);+ }++ #[test]+ fn protect_tones_keeps_hue() {+ let c = [0.6, 0.3, 0.2];+ let p = dodge_burn(c, 0.8, ToneRange::Midtones, false, true);+ assert!(p.iter().all(|v| (0.0..=1.0).contains(v)));+ // Ratios (hue) preserved when nothing clips.+ assert!((p[0] / p[1] - c[0] / c[1]).abs() < 0.05, "{p:?}");+ }++ #[test]+ fn sponge_changes_saturation() {+ let c = [0.8, 0.4, 0.3];+ let d = sponge(c, 0.5, false, false);+ assert!(saturation(d) < saturation(c));+ assert!((luma(d) - luma(c)).abs() < 1e-4);+ let s = sponge(c, 0.5, true, false);+ assert!(saturation(s) > saturation(c));+ assert!(s.iter().all(|v| (0.0..=1.0).contains(v)));+ // Vibrance protects already-saturated colours when saturating.+ let v = sponge([1.0, 0.1, 0.1], 0.5, true, true);+ let nv = sponge([1.0, 0.1, 0.1], 0.5, true, false);+ assert!((v[1] - 0.1).abs() <= (nv[1] - 0.1).abs());+ assert_eq!(sponge([0.5; 3], 1.0, false, false), [0.5; 3]);+ }++ #[test]+ fn blur_reduces_variance_and_sharpen_increases_it() {+ let (w, h, ch) = (16, 16, 1);+ let data: Vec<f32> = (0..w * h).map(|i| if (i % w + i / w) % 2 == 0 { 0.2 } else { 0.8 }).collect();+ let var = |v: &[f32]| {+ let m = v.iter().sum::<f32>() / v.len() as f32;+ v.iter().map(|x| (x - m).powi(2)).sum::<f32>() / v.len() as f32+ };+ let win = (4, 4, 12, 12);+ let orig: Vec<f32> = (4..12).flat_map(|y| (4..12).map(move |x| (x, y))).map(|(x, y)| data[y * w + x]).collect();+ let b = local_blur(&data, w, h, ch, None, win, 1.5);+ assert!(var(&b) < var(&orig) * 0.2);+ let smooth: Vec<f32> = (0..w * h).map(|i| 0.3 + 0.03 * (i % w) as f32 + if i % w == 8 { 0.2 } else { 0.0 }).collect();+ let s = local_sharpen(&smooth, w, h, ch, None, win, 1.0, false);+ let so: Vec<f32> = (4..12).flat_map(|y| (4..12).map(move |x| (x, y))).map(|(x, y)| smooth[y * w + x]).collect();+ assert!(var(&s) > var(&so));+ // Protect detail never exceeds the local range.+ let sp = local_sharpen(&smooth, w, h, ch, None, win, 4.0, true);+ let hi = smooth.iter().cloned().fold(0.0, f32::max);+ assert!(sp.iter().all(|v| *v <= hi + 1e-6));+ }++ #[test]+ fn blur_ignores_transparent_colour() {+ // Red opaque next to transparent green: blurred colour stays red.+ let (w, h, ch) = (8, 1, 4);+ let data: Vec<f32> = (0..w).flat_map(|x| if x < 4 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0, 0.0] }).collect();+ let b = local_blur(&data, w, h, ch, Some(3), (2, 0, 6, 1), 1.0);+ for p in b.chunks_exact(4) {+ if p[3] > 0.01 {+ assert!(p[0] > 0.99 && p[1] < 0.01, "{p:?}");+ }+ }+ }+}diff --git a/crates/algo/src/segment/focus.rs b/crates/algo/src/segment/focus.rsnew file mode 100644index 000000000..17973bdf5--- /dev/null+++ b/crates/algo/src/segment/focus.rs@@ -0,0 +1,85 @@+//! Focus Area (heuristic): selects the in-focus parts of an image.+//!+//! Sharpness is measured as local Laplacian energy (the classic "sum of modified Laplacian" /+//! Laplacian focus measure, Nayar & Nakagawa, "Shape from Focus", PAMI 1994) on a working copy,+//! normalised by its 99th percentile. `noise` subtracts a noise floor; `range` (0–1, Photoshop's+//! "In-Focus Range") lowers the threshold as it grows. The thresholded map is smoothed with a+//! guided filter (image as guide) so it follows object edges, cleaned, and upsampled with a soft+//! edge.++use photocraft_geom::Rect;++use super::{Region, Sampler, clean_mask};+use crate::matting::{box_mean, guided_filter_color};++/// Working-resolution budget (pixels).+pub const WORK_PX: usize = 1_000_000;++/// Per-pixel normalised sharpness (`0..=1`) of `img`.+pub fn sharpness(img: &super::RgbImage, noise: f32) -> Vec<f32> {+ let (w, h) = (img.w, img.h);+ let y: Vec<f32> = img.px.iter().map(|p| 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]).collect();+ let at = |x: usize, yy: usize| y[yy * w + x];+ let mut lap = vec![0.0f32; w * h];+ for yy in 0..h {+ for x in 0..w {+ let c = at(x, yy);+ let l = (2.0 * c - at(x.saturating_sub(1), yy) - at((x + 1).min(w - 1), yy)).abs() + (2.0 * c - at(x, yy.saturating_sub(1)) - at(x, (yy + 1).min(h - 1))).abs();+ lap[yy * w + x] = l;+ }+ }+ let r = (w.min(h) / 60).max(3);+ let e = box_mean(&lap, w, h, r);+ let mut sorted = e.clone();+ let k = ((sorted.len() as f32 * 0.99) as usize).min(sorted.len().saturating_sub(1));+ let p99 = *sorted.select_nth_unstable_by(k, |a, b| a.total_cmp(b)).1;+ let floor = noise.clamp(0.0, 1.0) * 0.5;+ e.iter().map(|v| ((v / p99.max(1e-6)).min(1.0) - floor).max(0.0) / (1.0 - floor).max(1e-3)).collect()+}++/// Focus Area selection over `canvas`.+pub fn focus_area(sampler: &dyn Sampler, canvas: Rect, range: f32, noise: f32) -> Option<Region> {+ if canvas.width() < 4 || canvas.height() < 4 {+ return None;+ }+ let step = super::scale_for(canvas, WORK_PX);+ let img = sampler.rgb_scaled(canvas, step);+ let (w, h) = (img.w, img.h);+ let s = sharpness(&img, noise);+ let t = 0.05 + 0.9 * (1.0 - range.clamp(0.0, 1.0)).powi(2);+ let bin: Vec<f32> = s.iter().map(|v| if *v >= t { 1.0 } else { 0.0 }).collect();+ let r = (w.min(h) / 50).max(2);+ let smooth = guided_filter_color(&img, &bin, r, 1e-2);+ let mask: Vec<bool> = smooth.iter().map(|v| *v >= 0.5).collect();+ let mask = clean_mask(&mask, w, h, 0.05, 0.02);+ if !mask.iter().any(|v| *v) {+ return None;+ }+ // Soft upsampling: bilinear field, steepened to about a working pixel of transition.+ let field: Vec<f32> = mask.iter().zip(&smooth).map(|(m, v)| if *m { v.clamp(0.5, 1.0) } else { v.clamp(0.0, 0.5) }).collect();+ let (fw, fh) = (canvas.width() as usize, canvas.height() as usize);+ let st = step as f32;+ let mut out = vec![0u8; fw * fh];+ let row = |yy: usize, o: &mut [u8]| {+ let fy = ((yy as f32 + 0.5) / st - 0.5).clamp(0.0, (h - 1) as f32);+ let (y0, ty) = (fy.floor() as usize, fy.fract());+ let y1 = (y0 + 1).min(h - 1);+ for (xx, px) in o.iter_mut().enumerate() {+ let fx = ((xx as f32 + 0.5) / st - 0.5).clamp(0.0, (w - 1) as f32);+ let (x0, tx) = (fx.floor() as usize, fx.fract());+ let x1 = (x0 + 1).min(w - 1);+ let top = field[y0 * w + x0] * (1.0 - tx) + field[y0 * w + x1] * tx;+ let bot = field[y1 * w + x0] * (1.0 - tx) + field[y1 * w + x1] * tx;+ let v = top * (1.0 - ty) + bot * ty;+ *px = (((v - 0.5) * 3.0 + 0.5).clamp(0.0, 1.0) * 255.0).round() as u8;+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ out.par_chunks_mut(fw).enumerate().for_each(|(y, o)| row(y, o));+ }+ #[cfg(target_arch = "wasm32")]+ out.chunks_mut(fw).enumerate().for_each(|(y, o)| row(y, o));+ super::trim_region(Region { bbox: canvas, mask: out })+}diff --git a/crates/algo/src/segment/gmm.rs b/crates/algo/src/segment/gmm.rsnew file mode 100644index 000000000..8a35a32b8--- /dev/null+++ b/crates/algo/src/segment/gmm.rs@@ -0,0 +1,257 @@+//! Gaussian mixture colour models with full 3×3 covariances.+//!+//! Fitting: k-means++ seeding (Arthur & Vassilvitskii, "k-means++: The Advantages of Careful+//! Seeding", SODA 2007), Lloyd iterations, then a few EM steps (Dempster, Laird & Rubin 1977).+//! GrabCut's per-iteration update (assign every sample to its most likely component, re-estimate)+//! is [`Gmm::refit`]. Covariances get a small ridge so flat colour areas stay well-conditioned.++use super::Rng;++/// One Gaussian component.+#[derive(Clone, Debug, PartialEq)]+pub struct Component {+ pub weight: f32,+ pub mean: [f32; 3],+ pub cov: [[f32; 3]; 3],+ inv: [[f64; 3]; 3],+ /// `ln(weight) − ½ ln det Σ − 3/2 ln 2π`.+ log_norm: f64,+}++impl Component {+ fn new(weight: f64, mean: [f64; 3], cov: [[f64; 3]; 3], reg: f64) -> Option<Self> {+ let mut c = cov;+ for (i, row) in c.iter_mut().enumerate() {+ row[i] += reg;+ }+ let det = c[0][0] * (c[1][1] * c[2][2] - c[1][2] * c[2][1]) - c[0][1] * (c[1][0] * c[2][2] - c[1][2] * c[2][0]) + c[0][2] * (c[1][0] * c[2][1] - c[1][1] * c[2][0]);+ if det <= 1e-30 || weight <= 0.0 {+ return None;+ }+ let inv = [+ [(c[1][1] * c[2][2] - c[1][2] * c[2][1]) / det, (c[0][2] * c[2][1] - c[0][1] * c[2][2]) / det, (c[0][1] * c[1][2] - c[0][2] * c[1][1]) / det],+ [(c[1][2] * c[2][0] - c[1][0] * c[2][2]) / det, (c[0][0] * c[2][2] - c[0][2] * c[2][0]) / det, (c[0][2] * c[1][0] - c[0][0] * c[1][2]) / det],+ [(c[1][0] * c[2][1] - c[1][1] * c[2][0]) / det, (c[0][1] * c[2][0] - c[0][0] * c[2][1]) / det, (c[0][0] * c[1][1] - c[0][1] * c[1][0]) / det],+ ];+ let log_norm = weight.ln() - 0.5 * det.ln() - 1.5 * (2.0 * std::f64::consts::PI).ln();+ Some(Component {+ weight: weight as f32,+ mean: mean.map(|v| v as f32),+ cov: c.map(|r| r.map(|v| v as f32)),+ inv,+ log_norm,+ })+ }++ /// `ln(weight · N(z; μ, Σ))`.+ #[inline]+ pub fn log_weighted(&self, z: [f32; 3]) -> f64 {+ let d = [(z[0] - self.mean[0]) as f64, (z[1] - self.mean[1]) as f64, (z[2] - self.mean[2]) as f64];+ let m = &self.inv;+ let q = d[0] * (m[0][0] * d[0] + m[0][1] * d[1] + m[0][2] * d[2]) + d[1] * (m[1][0] * d[0] + m[1][1] * d[1] + m[1][2] * d[2]) + d[2] * (m[2][0] * d[0] + m[2][1] * d[1] + m[2][2] * d[2]);+ self.log_norm - 0.5 * q+ }+}++/// A Gaussian mixture over RGB (`0..=1`).+#[derive(Clone, Debug, PartialEq)]+pub struct Gmm {+ pub comps: Vec<Component>,+ /// Ridge added to covariance diagonals.+ pub reg: f32,+}++/// Default covariance ridge: about one 8-bit level of standard deviation.+pub const DEFAULT_REG: f32 = 2e-5;++#[derive(Default, Clone, Copy)]+struct Acc {+ n: f64,+ s: [f64; 3],+ ss: [[f64; 3]; 3],+}++impl Acc {+ fn add(&mut self, z: [f32; 3], w: f64) {+ let z = z.map(|v| v as f64);+ self.n += w;+ for i in 0..3 {+ self.s[i] += w * z[i];+ for j in 0..3 {+ self.ss[i][j] += w * z[i] * z[j];+ }+ }+ }+ fn component(&self, total: f64, reg: f32) -> Option<Component> {+ if self.n <= 0.0 {+ return None;+ }+ let m = self.s.map(|v| v / self.n);+ let mut c = [[0.0f64; 3]; 3];+ for i in 0..3 {+ for j in 0..3 {+ c[i][j] = self.ss[i][j] / self.n - m[i] * m[j];+ }+ }+ Component::new(self.n / total, m, c, reg as f64)+ }+}++impl Gmm {+ /// Fits `k` components (fewer if there are not enough distinct samples). `None` without samples.+ pub fn fit(samples: &[[f32; 3]], k: usize, reg: f32) -> Option<Gmm> {+ Self::fit_em(samples, k, reg, 3)+ }++ /// [`Gmm::fit`] with an explicit number of EM iterations after k-means.+ pub fn fit_em(samples: &[[f32; 3]], k: usize, reg: f32, em_iters: usize) -> Option<Gmm> {+ if samples.is_empty() {+ return None;+ }+ let k = k.clamp(1, samples.len());+ let centers = kmeans(samples, k, 10);+ let mut labels = vec![0usize; samples.len()];+ for (l, z) in labels.iter_mut().zip(samples) {+ *l = nearest(¢ers, *z);+ }+ let mut g = Self::from_labels(samples, &labels, centers.len(), reg)?;+ for _ in 0..em_iters {+ g = g.em_step(samples).unwrap_or(g);+ }+ Some(g)+ }++ /// Component statistics from hard assignments.+ pub fn from_labels(samples: &[[f32; 3]], labels: &[usize], k: usize, reg: f32) -> Option<Gmm> {+ let mut acc = vec![Acc::default(); k];+ for (z, l) in samples.iter().zip(labels) {+ acc[*l].add(*z, 1.0);+ }+ let total = samples.len() as f64;+ let comps: Vec<Component> = acc.iter().filter_map(|a| a.component(total, reg)).collect();+ (!comps.is_empty()).then_some(Gmm { comps, reg })+ }++ /// One EM step (soft responsibilities).+ fn em_step(&self, samples: &[[f32; 3]]) -> Option<Gmm> {+ let k = self.comps.len();+ let mut acc = vec![Acc::default(); k];+ let mut lw = vec![0.0f64; k];+ for z in samples {+ let mut mx = f64::MIN;+ for (c, l) in self.comps.iter().zip(lw.iter_mut()) {+ *l = c.log_weighted(*z);+ mx = mx.max(*l);+ }+ let mut sum = 0.0;+ for l in lw.iter_mut() {+ *l = (*l - mx).exp();+ sum += *l;+ }+ for (a, l) in acc.iter_mut().zip(&lw) {+ let r = l / sum;+ if r > 1e-6 {+ a.add(*z, r);+ }+ }+ }+ let total = samples.len() as f64;+ let comps: Vec<Component> = acc.iter().filter_map(|a| a.component(total, self.reg)).collect();+ (!comps.is_empty()).then_some(Gmm { comps, reg: self.reg })+ }++ /// GrabCut update: assign each sample to its most likely component and re-estimate.+ pub fn refit(&self, samples: &[[f32; 3]]) -> Option<Gmm> {+ let labels: Vec<usize> = samples.iter().map(|z| self.component_of(*z)).collect();+ Self::from_labels(samples, &labels, self.comps.len(), self.reg)+ }++ /// Index of the most likely component for `z`.+ pub fn component_of(&self, z: [f32; 3]) -> usize {+ let mut best = 0;+ let mut bv = f64::MIN;+ for (i, c) in self.comps.iter().enumerate() {+ let v = c.log_weighted(z);+ if v > bv {+ bv = v;+ best = i;+ }+ }+ best+ }++ /// `ln p(z)`.+ pub fn log_prob(&self, z: [f32; 3]) -> f64 {+ let mut mx = f64::MIN;+ let mut vals = [0.0f64; 16];+ let n = self.comps.len().min(16);+ for (v, c) in vals.iter_mut().zip(&self.comps) {+ *v = c.log_weighted(z);+ mx = mx.max(*v);+ }+ let s: f64 = vals[..n].iter().map(|v| (v - mx).exp()).sum();+ mx + s.ln()+ }++ /// `−ln p(z)`, clamped to a finite range.+ pub fn neg_log(&self, z: [f32; 3]) -> f32 {+ (-self.log_prob(z)).clamp(-50.0, 200.0) as f32+ }+}++fn nearest(centers: &[[f32; 3]], z: [f32; 3]) -> usize {+ let mut best = 0;+ let mut bd = f32::MAX;+ for (i, c) in centers.iter().enumerate() {+ let d = super::d2(*c, z);+ if d < bd {+ bd = d;+ best = i;+ }+ }+ best+}++/// k-means with k-means++ seeding (deterministic seed). Drops empty clusters.+pub fn kmeans(samples: &[[f32; 3]], k: usize, iters: usize) -> Vec<[f32; 3]> {+ let mut rng = Rng::new(0x5EED + samples.len() as u64);+ let mut centers = vec![samples[(rng.next_u64() % samples.len() as u64) as usize]];+ let mut dist: Vec<f32> = samples.iter().map(|z| super::d2(*z, centers[0])).collect();+ while centers.len() < k {+ let total: f64 = dist.iter().map(|d| *d as f64).sum();+ if total <= 1e-12 {+ break;+ }+ let mut t = rng.f32() as f64 * total;+ let mut pick = samples.len() - 1;+ for (i, d) in dist.iter().enumerate() {+ t -= *d as f64;+ if t <= 0.0 {+ pick = i;+ break;+ }+ }+ let c = samples[pick];+ centers.push(c);+ for (d, z) in dist.iter_mut().zip(samples) {+ *d = d.min(super::d2(*z, c));+ }+ }+ for _ in 0..iters {+ let mut sums = vec![([0.0f64; 3], 0usize); centers.len()];+ for z in samples {+ let i = nearest(¢ers, *z);+ for (acc, v) in sums[i].0.iter_mut().zip(z) {+ *acc += *v as f64;+ }+ sums[i].1 += 1;+ }+ let new: Vec<[f32; 3]> = sums.iter().filter(|s| s.1 > 0).map(|(s, n)| s.map(|v| (v / *n as f64) as f32)).collect();+ let done = new == centers;+ centers = new;+ if done {+ break;+ }+ }+ centers+}diff --git a/crates/algo/src/segment/grabcut.rs b/crates/algo/src/segment/grabcut.rsnew file mode 100644index 000000000..8cceee058--- /dev/null+++ b/crates/algo/src/segment/grabcut.rs@@ -0,0 +1,118 @@+//! GrabCut and rectangle Object Selection.+//!+//! Implemented from C. Rother, V. Kolmogorov and A. Blake, "GrabCut: Interactive Foreground+//! Extraction using Iterated Graph Cuts", SIGGRAPH 2004: a trimap (definite / probable+//! foreground and background), 5-component full-covariance GMMs per side, and iterated+//! "assign components → learn GMMs → min cut" steps with the contrast-sensitive smoothness term+//! `γ e^{−β‖z_m − z_n‖²} / dist(m, n)` (γ = 50, β from the mean squared neighbour difference).++use photocraft_geom::Rect;++use super::gmm::{DEFAULT_REG, Gmm};+use super::{HARD_BG, HARD_FG, FREE, Region, RgbImage, Sampler, contrast_beta, data_costs, grid_cut, subsample};++/// Definite background.+pub const BG: u8 = 0;+/// Definite foreground.+pub const FG: u8 = 1;+/// Probable background.+pub const PR_BG: u8 = 2;+/// Probable foreground.+pub const PR_FG: u8 = 3;++/// GrabCut's smoothness weight.+pub const GAMMA: f32 = 50.0;+/// Components per GMM.+pub const K: usize = 5;+const MAX_SAMPLES: usize = 40_000;++fn is_fg(t: u8) -> bool {+ t == FG || t == PR_FG+}++/// Runs `iters` GrabCut iterations, updating the probable labels of `trimap` in place. Returns+/// the final (foreground, background) models, or `None` if either side has no pixels.+pub fn grabcut(img: &RgbImage, trimap: &mut [u8], iters: usize) -> Option<(Gmm, Gmm)> {+ let beta = contrast_beta(img);+ let fixed: Vec<u8> = trimap+ .iter()+ .map(|t| match *t {+ FG => HARD_FG,+ BG => HARD_BG,+ _ => FREE,+ })+ .collect();+ let mut models: Option<(Gmm, Gmm)> = None;+ for _ in 0..iters.max(1) {+ let (mut fs, mut bs) = (Vec::new(), Vec::new());+ for (p, t) in img.px.iter().zip(trimap.iter()) {+ if is_fg(*t) { fs.push(*p) } else { bs.push(*p) }+ }+ let (fs, bs) = (subsample(&fs, MAX_SAMPLES), subsample(&bs, MAX_SAMPLES));+ let (fg, bg) = match &models {+ None => (Gmm::fit(&fs, K, DEFAULT_REG)?, Gmm::fit(&bs, K, DEFAULT_REG)?),+ Some((f, b)) => (f.refit(&fs).unwrap_or_else(|| f.clone()), b.refit(&bs).unwrap_or_else(|| b.clone())),+ };+ let (cf, cb) = data_costs(img, &fg, &bg);+ let cut = grid_cut(img, &cf, &cb, &fixed, GAMMA, beta);+ let mut changed = 0usize;+ for (t, fgnd) in trimap.iter_mut().zip(&cut) {+ if *t == PR_BG || *t == PR_FG {+ let nt = if *fgnd { PR_FG } else { PR_BG };+ changed += (nt != *t) as usize;+ *t = nt;+ }+ }+ models = Some((fg, bg));+ if changed * 2000 < trimap.len() {+ break;+ }+ }+ models+}++/// Object Selection (rectangle mode): GrabCut initialised from `rect` (outside = background,+/// inside = probable foreground). Runs on a working copy of about `work_px` pixels, then re-cuts+/// the boundary at full resolution. `canvas` bounds the analysis.+pub fn object_select(sampler: &dyn Sampler, canvas: Rect, rect: Rect, work_px: usize) -> Option<Region> {+ let rect = rect.intersect(&canvas);+ if rect.width() < 2 || rect.height() < 2 {+ return None;+ }+ let margin = ((rect.width().max(rect.height()) as f32 * 0.15).ceil() as i32).max(8);+ let window = rect.inflate(margin).intersect(&canvas);+ let step = super::scale_for(window, work_px);+ let img = sampler.rgb_scaled(window, step);+ let (lw, lh) = (img.w, img.h);+ let mut trimap = vec![BG; lw * lh];+ // Working pixel (x, y) covers doc pixels [x0 + x·step, …); its centre decides inside/outside.+ let inside = |x: usize, y: usize| {+ let (cx, cy) = (window.x0 + (x * step + step / 2) as i32, window.y0 + (y * step + step / 2) as i32);+ rect.contains(cx, cy)+ };+ let mut any_bg = false;+ for y in 0..lh {+ for x in 0..lw {+ if inside(x, y) {+ trimap[y * lw + x] = PR_FG;+ } else {+ any_bg = true;+ }+ }+ }+ if !any_bg {+ // The rectangle covers the whole canvas: use a thin outer ring as background.+ let ring = (lw.min(lh) / 50).max(1);+ for y in 0..lh {+ for x in 0..lw {+ if x < ring || y < ring || x + ring >= lw || y + ring >= lh {+ trimap[y * lw + x] = BG;+ }+ }+ }+ }+ let (fg, bg) = grabcut(&img, &mut trimap, 8)?;+ let low: Vec<bool> = trimap.iter().map(|t| is_fg(*t)).collect();+ let low = super::clean_mask(&low, lw, lh, 0.1, 0.002);+ super::finish_region(sampler, window, step, &low, lw, lh, Some((&fg, &bg)))+}diff --git a/crates/algo/src/segment/maxflow.rs b/crates/algo/src/segment/maxflow.rsnew file mode 100644index 000000000..8243b8188--- /dev/null+++ b/crates/algo/src/segment/maxflow.rs@@ -0,0 +1,363 @@+//! Boykov–Kolmogorov max-flow / min-cut.+//!+//! Implemented from Y. Boykov and V. Kolmogorov, "An Experimental Comparison of Min-Cut/Max-Flow+//! Algorithms for Energy Minimization in Vision", IEEE PAMI 26(9), 2004: two search trees+//! (source tree S, sink tree T) grow towards each other; each S–T contact gives an augmenting+//! path; saturated tree edges create orphans that are re-adopted (or freed) before growing again.+//! Search trees are reused between augmentations, which makes the algorithm very fast on the+//! short-path grid graphs of image segmentation.++use std::collections::VecDeque;++const NONE: u32 = u32::MAX;+const TERMINAL: u32 = u32::MAX - 1;+const ORPHAN: u32 = u32::MAX - 2;+const INF_DIST: u32 = u32::MAX;+/// Residual capacities at or below this count as saturated (guards against float round-off+/// leaving tiny positive residuals that would cause long chains of negligible augmentations).+const EPS: f32 = 1e-5;++/// A directed graph with source/sink terminal capacities.+#[derive(Clone, Debug, Default)]+pub struct Graph {+ // Nodes.+ first: Vec<u32>,+ /// Residual terminal capacity: `> 0` from the source, `< 0` to the sink.+ tr_cap: Vec<f32>,+ parent: Vec<u32>,+ is_sink: Vec<bool>,+ ts: Vec<u32>,+ dist: Vec<u32>,+ active: Vec<bool>,+ // Arcs (stored in pairs: arc `a` and its reverse `a ^ 1`).+ head: Vec<u32>,+ next: Vec<u32>,+ r_cap: Vec<f32>,+ flow: f64,+}++impl Graph {+ /// A graph with `nodes` nodes and room for `edges` undirected edge pairs.+ pub fn with_capacity(nodes: usize, edges: usize) -> Self {+ Graph {+ first: vec![NONE; nodes],+ tr_cap: vec![0.0; nodes],+ parent: vec![NONE; nodes],+ is_sink: vec![false; nodes],+ ts: vec![0; nodes],+ dist: vec![0; nodes],+ active: vec![false; nodes],+ head: Vec::with_capacity(edges * 2),+ next: Vec::with_capacity(edges * 2),+ r_cap: Vec::with_capacity(edges * 2),+ flow: 0.0,+ }+ }++ pub fn node_count(&self) -> usize {+ self.first.len()+ }++ /// Adds capacities from the source and to the sink (accumulating). Only the difference is+ /// kept per node; the common part is flow that must pass anyway.+ pub fn add_tweights(&mut self, i: usize, cap_source: f32, cap_sink: f32) {+ let delta = self.tr_cap[i];+ let (mut s, mut t) = (cap_source, cap_sink);+ if delta > 0.0 {+ s += delta;+ } else {+ t -= delta;+ }+ self.flow += s.min(t) as f64;+ self.tr_cap[i] = s - t;+ }++ /// Adds an edge `i → j` with capacity `cap` and `j → i` with `rev_cap`.+ pub fn add_edge(&mut self, i: usize, j: usize, cap: f32, rev_cap: f32) {+ debug_assert!(i != j);+ let a = self.head.len() as u32;+ self.head.push(j as u32);+ self.next.push(self.first[i]);+ self.r_cap.push(cap);+ self.first[i] = a;+ self.head.push(i as u32);+ self.next.push(self.first[j]);+ self.r_cap.push(rev_cap);+ self.first[j] = a + 1;+ }++ /// After [`Graph::maxflow`]: is node `i` on the source side of the minimum cut? Nodes+ /// reachable from neither terminal are reported on the sink side (the smallest source set).+ pub fn in_source(&self, i: usize) -> bool {+ self.parent[i] != NONE && !self.is_sink[i]+ }++ /// The flow value found by the last [`Graph::maxflow`].+ pub fn flow(&self) -> f64 {+ self.flow+ }++ fn arcs(&self, i: usize) -> ArcIter<'_> {+ ArcIter { g: self, a: self.first[i] }+ }++ /// Computes the maximum flow (= minimum cut capacity).+ pub fn maxflow(&mut self) -> f64 {+ let n = self.node_count();+ let mut queue: VecDeque<u32> = VecDeque::new();+ let mut orphans: VecDeque<u32> = VecDeque::new();+ for i in 0..n {+ self.active[i] = false;+ self.ts[i] = 0;+ if self.tr_cap[i].abs() > EPS {+ self.is_sink[i] = self.tr_cap[i] < 0.0;+ self.parent[i] = TERMINAL;+ self.dist[i] = 1;+ self.active[i] = true;+ queue.push_back(i as u32);+ } else {+ self.parent[i] = NONE;+ }+ }+ let mut time = 0u32;+ while let Some(i) = queue.pop_front() {+ let i = i as usize;+ self.active[i] = false;+ if self.parent[i] == NONE {+ continue;+ }+ // Growth stage.+ let mut contact = NONE;+ let sink = self.is_sink[i];+ let mut a = self.first[i];+ while a != NONE {+ let au = a as usize;+ let j = self.head[au] as usize;+ let cap = if sink { self.r_cap[au ^ 1] } else { self.r_cap[au] };+ if cap > EPS {+ if self.parent[j] == NONE {+ self.is_sink[j] = sink;+ self.parent[j] = a ^ 1;+ self.ts[j] = self.ts[i];+ self.dist[j] = self.dist[i] + 1;+ if !self.active[j] {+ self.active[j] = true;+ queue.push_back(j as u32);+ }+ } else if self.is_sink[j] != sink {+ // Arc from the S side to the T side.+ contact = if sink { a ^ 1 } else { a };+ break;+ } else if self.ts[j] <= self.ts[i] && self.dist[j] > self.dist[i] {+ // Heuristic: shorten paths to the terminal.+ self.parent[j] = a ^ 1;+ self.ts[j] = self.ts[i];+ self.dist[j] = self.dist[i] + 1;+ }+ }+ a = self.next[au];+ }+ if contact == NONE {+ continue;+ }+ // Keep scanning this node after the augmentation.+ if !self.active[i] {+ self.active[i] = true;+ queue.push_front(i as u32);+ }+ time += 1;+ self.augment(contact as usize, &mut orphans);+ // Adoption stage.+ while let Some(o) = orphans.pop_front() {+ self.adopt(o as usize, time, &mut queue, &mut orphans);+ }+ }+ self.flow+ }++ fn augment(&mut self, m: usize, orphans: &mut VecDeque<u32>) {+ let u = self.head[m ^ 1] as usize;+ let v = self.head[m] as usize;+ // Bottleneck.+ let mut b = self.r_cap[m];+ let mut x = u;+ loop {+ let a = self.parent[x];+ if a == TERMINAL {+ break;+ }+ b = b.min(self.r_cap[a as usize ^ 1]);+ x = self.head[a as usize] as usize;+ }+ b = b.min(self.tr_cap[x]);+ let mut x = v;+ loop {+ let a = self.parent[x];+ if a == TERMINAL {+ break;+ }+ b = b.min(self.r_cap[a as usize]);+ x = self.head[a as usize] as usize;+ }+ b = b.min(-self.tr_cap[x]);+ // Push.+ self.r_cap[m ^ 1] += b;+ self.r_cap[m] -= b;+ let mut x = u;+ loop {+ let a = self.parent[x];+ if a == TERMINAL {+ break;+ }+ let au = a as usize;+ self.r_cap[au] += b;+ self.r_cap[au ^ 1] -= b;+ let up = self.head[au] as usize;+ if self.r_cap[au ^ 1] <= EPS {+ self.parent[x] = ORPHAN;+ orphans.push_back(x as u32);+ }+ x = up;+ }+ self.tr_cap[x] -= b;+ if self.tr_cap[x] <= EPS {+ self.parent[x] = ORPHAN;+ orphans.push_back(x as u32);+ }+ let mut x = v;+ loop {+ let a = self.parent[x];+ if a == TERMINAL {+ break;+ }+ let au = a as usize;+ self.r_cap[au ^ 1] += b;+ self.r_cap[au] -= b;+ let up = self.head[au] as usize;+ if self.r_cap[au] <= EPS {+ self.parent[x] = ORPHAN;+ orphans.push_back(x as u32);+ }+ x = up;+ }+ self.tr_cap[x] += b;+ if self.tr_cap[x] >= -EPS {+ self.parent[x] = ORPHAN;+ orphans.push_back(x as u32);+ }+ self.flow += b as f64;+ }++ fn adopt(&mut self, i: usize, time: u32, queue: &mut VecDeque<u32>, orphans: &mut VecDeque<u32>) {+ let sink = self.is_sink[i];+ let mut best = NONE;+ let mut d_min = INF_DIST;+ let mut a = self.first[i];+ while a != NONE {+ let au = a as usize;+ let cap = if sink { self.r_cap[au] } else { self.r_cap[au ^ 1] };+ let j = self.head[au] as usize;+ if cap > EPS && self.is_sink[j] == sink && self.parent[j] != NONE {+ // Does j's path lead to a terminal?+ let mut d = 0u32;+ let mut k = j;+ loop {+ if self.ts[k] == time {+ d = d.saturating_add(self.dist[k]);+ break;+ }+ let pa = self.parent[k];+ d += 1;+ if pa == TERMINAL {+ self.ts[k] = time;+ self.dist[k] = 1;+ break;+ }+ if pa == ORPHAN {+ d = INF_DIST;+ break;+ }+ k = self.head[pa as usize] as usize;+ }+ if d < INF_DIST {+ if d < d_min {+ best = a;+ d_min = d;+ }+ // Cache distances along the path.+ let mut k = j;+ let mut dd = d;+ while self.ts[k] != time {+ self.ts[k] = time;+ self.dist[k] = dd;+ dd -= 1;+ k = self.head[self.parent[k] as usize] as usize;+ }+ }+ }+ a = self.next[au];+ }+ if best != NONE {+ self.parent[i] = best;+ self.ts[i] = time;+ self.dist[i] = d_min + 1;+ return;+ }+ // No parent: i becomes free.+ self.parent[i] = NONE;+ let mut a = self.first[i];+ while a != NONE {+ let au = a as usize;+ let j = self.head[au] as usize;+ let pj = self.parent[j];+ if self.is_sink[j] == sink && pj != NONE {+ let cap = if sink { self.r_cap[au] } else { self.r_cap[au ^ 1] };+ if cap > EPS && !self.active[j] {+ self.active[j] = true;+ queue.push_back(j as u32);+ }+ if pj != TERMINAL && pj != ORPHAN && self.head[pj as usize] as usize == i {+ self.parent[j] = ORPHAN;+ orphans.push_back(j as u32);+ }+ }+ a = self.next[au];+ }+ }+}++struct ArcIter<'a> {+ g: &'a Graph,+ a: u32,+}++impl Iterator for ArcIter<'_> {+ /// `(neighbour, residual capacity out, residual capacity in)`.+ type Item = (usize, f32, f32);+ fn next(&mut self) -> Option<Self::Item> {+ if self.a == NONE {+ return None;+ }+ let a = self.a as usize;+ self.a = self.g.next[a];+ Some((self.g.head[a] as usize, self.g.r_cap[a], self.g.r_cap[a ^ 1]))+ }+}++impl Graph {+ /// Sum of residual capacities on arcs leaving the source side of the cut (zero after+ /// [`Graph::maxflow`]: no augmenting path remains).+ pub fn residual_out_of_source_side(&self) -> f32 {+ let mut s = 0.0;+ for i in 0..self.node_count() {+ if self.in_source(i) {+ for (j, out, _) in self.arcs(i) {+ if !self.in_source(j) {+ s += out;+ }+ }+ }+ }+ s+ }+}diff --git a/crates/algo/src/segment/mod.rs b/crates/algo/src/segment/mod.rsnew file mode 100644index 000000000..e73bc4bd5--- /dev/null+++ b/crates/algo/src/segment/mod.rs@@ -0,0 +1,637 @@+//! Smart selection: interactive segmentation for Photoshop's Quick Selection, Object Selection,+//! Select Subject and Focus Area.+//!+//! Everything here is classical (no learned models) and implemented from the published papers:+//!+//! * [`maxflow`]: Boykov–Kolmogorov min-cut / max-flow (Boykov & Kolmogorov, "An Experimental+//! Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision", PAMI 2004).+//! * [`gmm`]: Gaussian mixture colour models (k-means++ initialisation, Arthur & Vassilvitskii+//! 2007; EM refinement).+//! * [`slic`]: SLIC superpixels (Achanta et al., "SLIC Superpixels Compared to State-of-the-Art+//! Superpixel Methods", PAMI 2012).+//! * [`grabcut`]: GrabCut (Rother, Kolmogorov & Blake, SIGGRAPH 2004): iterated graph cuts+//! (Boykov & Jolly, ICCV 2001) with GMM colour models.+//! * [`quick`]: Quick Selection brush: stroke seeds, geodesic background sampling (Criminisi et+//! al., "GeoS", ECCV 2008; Bai & Sapiro 2007) and a contrast-sensitive graph cut, in the spirit+//! of "Paint Selection" (Liu, Sun & Shum, SIGGRAPH 2009).+//! * [`subject`]: Select Subject: superpixel saliency (boundary connectivity + background-weighted+//! contrast, Zhu et al., "Saliency Optimization from Robust Background Detection", CVPR 2014;+//! frequency-tuned saliency, Achanta et al., CVPR 2009) seeding a GrabCut. Heuristic.+//! * [`focus`]: Focus Area: local Laplacian energy (sharpness) thresholding. Heuristic.+//!+//! Large images are processed at a reduced working resolution and the boundary is then re-cut+//! at full resolution in a narrow band (tile by tile, in parallel on native targets).+//!+//! Colour analysis runs on straight RGB samples in `0..=1` read through a [`Sampler`], so any+//! bit depth or colour model can be segmented; results are 8-bit coverage [`Region`]s.++pub mod focus;+pub mod gmm;+pub mod grabcut;+pub mod maxflow;+pub mod quick;+pub mod slic;+pub mod subject;++use photocraft_geom::Rect;+use photocraft_raster::Surface;++pub use crate::selection::Region;+use gmm::Gmm;+use maxflow::Graph;++/// Row-major RGB image, samples in `0..=1`.+#[derive(Clone, Debug, PartialEq)]+pub struct RgbImage {+ pub w: usize,+ pub h: usize,+ pub px: Vec<[f32; 3]>,+}++impl RgbImage {+ pub fn new(w: usize, h: usize) -> Self {+ Self { w, h, px: vec![[0.0; 3]; w * h] }+ }+ pub fn from_fn(w: usize, h: usize, mut f: impl FnMut(usize, usize) -> [f32; 3]) -> Self {+ let mut px = Vec::with_capacity(w * h);+ for y in 0..h {+ for x in 0..w {+ px.push(f(x, y));+ }+ }+ Self { w, h, px }+ }+ #[inline]+ pub fn at(&self, x: usize, y: usize) -> [f32; 3] {+ self.px[y * self.w + x]+ }+ /// Straight RGBA to RGB, compositing transparent pixels over mid gray (so transparency is a+ /// colour the models can separate).+ pub fn from_rgba(px: &[[f32; 4]], w: usize, h: usize) -> Self {+ debug_assert_eq!(px.len(), w * h);+ let px = px+ .iter()+ .map(|p| {+ let a = p[3].clamp(0.0, 1.0);+ [0, 1, 2].map(|c| p[c].clamp(0.0, 1.0) * a + 0.5 * (1.0 - a))+ })+ .collect();+ Self { w, h, px }+ }+ /// Box-average downsampling by an integer `step` (output `ceil(w/step) × ceil(h/step)`).+ pub fn downsample(&self, step: usize) -> RgbImage {+ if step <= 1 {+ return self.clone();+ }+ let (ow, oh) = (self.w.div_ceil(step), self.h.div_ceil(step));+ let mut out = RgbImage::new(ow, oh);+ for oy in 0..oh {+ for ox in 0..ow {+ let mut acc = [0.0f32; 3];+ let mut n = 0.0;+ for y in oy * step..((oy + 1) * step).min(self.h) {+ for x in ox * step..((ox + 1) * step).min(self.w) {+ let p = self.at(x, y);+ for c in 0..3 {+ acc[c] += p[c];+ }+ n += 1.0;+ }+ }+ out.px[oy * ow + ox] = acc.map(|v| v / n);+ }+ }+ out+ }+}++/// Where the segmentation algorithms read colours from (a layer, the composite, a test image).+pub trait Sampler: Sync {+ /// Straight RGBA (`0..=1`) over `r` (document pixels), row-major.+ fn rgba(&self, r: Rect) -> Vec<[f32; 4]>;++ /// RGB over `r` at full resolution.+ fn rgb(&self, r: Rect) -> RgbImage {+ RgbImage::from_rgba(&self.rgba(r), r.width() as usize, r.height() as usize)+ }++ /// RGB over `r`, box-downsampled by `step`, read in horizontal strips (in parallel on native)+ /// so the full-resolution area is never held in memory at once.+ fn rgb_scaled(&self, r: Rect, step: usize) -> RgbImage {+ if step <= 1 {+ return self.rgb(r);+ }+ let (w, h) = (r.width() as usize, r.height() as usize);+ let (ow, oh) = (w.div_ceil(step), h.div_ceil(step));+ let rows_per = (64usize.div_ceil(step)).max(1);+ let strips: Vec<usize> = (0..oh.div_ceil(rows_per)).collect();+ let run = |si: &usize| -> Vec<[f32; 3]> {+ let oy0 = si * rows_per;+ let oy1 = (oy0 + rows_per).min(oh);+ let y0 = r.y0 + (oy0 * step) as i32;+ let y1 = (r.y0 + (oy1 * step) as i32).min(r.y1);+ let strip = self.rgb(Rect::new(r.x0, y0, r.x1, y1));+ strip.downsample(step).px+ };+ #[cfg(not(target_arch = "wasm32"))]+ let parts: Vec<Vec<[f32; 3]>> = {+ use rayon::prelude::*;+ strips.par_iter().map(run).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let parts: Vec<Vec<[f32; 3]>> = strips.iter().map(run).collect();+ let mut px = Vec::with_capacity(ow * oh);+ for p in parts {+ px.extend(p);+ }+ RgbImage { w: ow, h: oh, px }+ }+}++/// Samples a raster surface (any format; converted to straight RGBA).+pub struct SurfaceSampler<'a>(pub &'a Surface);++impl Sampler for SurfaceSampler<'_> {+ fn rgba(&self, r: Rect) -> Vec<[f32; 4]> {+ let mut px = vec![[0.0f32; 4]; r.width() as usize * r.height() as usize];+ if !r.is_empty() {+ self.0.read_rgba_into(r, &mut px);+ }+ px+ }+}++/// Samples an in-memory RGB image placed at `origin` (tests, benchmarks).+pub struct ImageSampler<'a> {+ pub img: &'a RgbImage,+ pub origin: (i32, i32),+}++impl Sampler for ImageSampler<'_> {+ fn rgba(&self, r: Rect) -> Vec<[f32; 4]> {+ let mut out = Vec::with_capacity(r.width() as usize * r.height() as usize);+ for y in r.y0..r.y1 {+ for x in r.x0..r.x1 {+ let (ix, iy) = (x - self.origin.0, y - self.origin.1);+ if ix < 0 || iy < 0 || ix as usize >= self.img.w || iy as usize >= self.img.h {+ out.push([0.0; 4]);+ } else {+ let p = self.img.at(ix as usize, iy as usize);+ out.push([p[0], p[1], p[2], 1.0]);+ }+ }+ }+ out+ }+}++/// Integer working-resolution step so that `area` holds at most about `max_px` pixels.+pub fn scale_for(area: Rect, max_px: usize) -> usize {+ let n = area.width() as f64 * area.height() as f64;+ ((n / max_px.max(1) as f64).sqrt().ceil() as usize).max(1)+}++#[inline]+fn d2(a: [f32; 3], b: [f32; 3]) -> f32 {+ let (x, y, z) = (a[0] - b[0], a[1] - b[1], a[2] - b[2]);+ x * x + y * y + z * z+}++/// The 4 forward neighbour offsets of an 8-connected grid and their lengths.+const NB: [(i32, i32, f32); 4] = [(1, 0, 1.0), (0, 1, 1.0), (1, 1, std::f32::consts::SQRT_2), (-1, 1, std::f32::consts::SQRT_2)];++/// GrabCut's contrast parameter: `β = 1 / (2 ⟨‖z_m − z_n‖²⟩)` over 8-neighbour pairs.+pub fn contrast_beta(img: &RgbImage) -> f32 {+ let (w, h) = (img.w as i32, img.h as i32);+ let mut sum = 0.0f64;+ let mut n = 0u64;+ for y in 0..h {+ for x in 0..w {+ let a = img.px[(y * w + x) as usize];+ for (dx, dy, _) in NB {+ let (nx, ny) = (x + dx, y + dy);+ if nx >= 0 && nx < w && ny < h {+ sum += d2(a, img.px[(ny * w + nx) as usize]) as f64;+ n += 1;+ }+ }+ }+ }+ if n == 0 || sum <= 1e-12 { 0.0 } else { (n as f64 / (2.0 * sum)) as f32 }+}++/// Pixel label constraint for [`grid_cut`].+pub const FREE: u8 = 0;+pub const HARD_FG: u8 = 1;+pub const HARD_BG: u8 = 2;++/// Binary labelling of a grid by one min cut (Boykov & Jolly 2001):+/// minimises `Σ D_p(l_p) + Σ_{p~q} [l_p ≠ l_q] γ e^{-β‖z_p−z_q‖²} / dist(p,q)` over the+/// 8-connected grid. `cost_fg[i]` / `cost_bg[i]` are the data costs of labelling pixel `i`+/// foreground / background; `fixed[i]` is [`FREE`], [`HARD_FG`] or [`HARD_BG`]. Only free pixels+/// become graph nodes (links to fixed neighbours fold into terminal capacities). Returns+/// `true` for foreground.+pub fn grid_cut(img: &RgbImage, cost_fg: &[f32], cost_bg: &[f32], fixed: &[u8], gamma: f32, beta: f32) -> Vec<bool> {+ let (w, h) = (img.w as i32, img.h as i32);+ let n = img.w * img.h;+ let mut idx = vec![u32::MAX; n];+ let mut count = 0u32;+ for i in 0..n {+ if fixed[i] == FREE {+ idx[i] = count;+ count += 1;+ }+ }+ let mut out: Vec<bool> = fixed.iter().map(|f| *f == HARD_FG).collect();+ if count == 0 {+ return out;+ }+ let mut g = Graph::with_capacity(count as usize, count as usize * 4);+ for i in 0..n {+ if idx[i] != u32::MAX {+ g.add_tweights(idx[i] as usize, cost_bg[i], cost_fg[i]);+ }+ }+ for y in 0..h {+ for x in 0..w {+ let i = (y * w + x) as usize;+ let a = img.px[i];+ for (dx, dy, len) in NB {+ let (nx, ny) = (x + dx, y + dy);+ if nx < 0 || nx >= w || ny >= h {+ continue;+ }+ let j = (ny * w + nx) as usize;+ let wt = gamma * (-beta * d2(a, img.px[j])).exp() / len;+ match (idx[i] != u32::MAX, idx[j] != u32::MAX) {+ (true, true) => g.add_edge(idx[i] as usize, idx[j] as usize, wt, wt),+ // Neighbour fixed: disagreeing with it costs `wt`.+ (true, false) => add_fixed_link(&mut g, idx[i] as usize, fixed[j], wt),+ (false, true) => add_fixed_link(&mut g, idx[j] as usize, fixed[i], wt),+ (false, false) => {}+ }+ }+ }+ }+ g.maxflow();+ for i in 0..n {+ if idx[i] != u32::MAX {+ out[i] = g.in_source(idx[i] as usize);+ }+ }+ out+}++fn add_fixed_link(g: &mut Graph, node: usize, fixed: u8, wt: f32) {+ if fixed == HARD_FG {+ // Labelling `node` background cuts the link.+ g.add_tweights(node, wt, 0.0);+ } else {+ g.add_tweights(node, 0.0, wt);+ }+}++/// Data costs `(−ln p(z|fg), −ln p(z|bg))` for every pixel.+pub fn data_costs(img: &RgbImage, fg: &Gmm, bg: &Gmm) -> (Vec<f32>, Vec<f32>) {+ let eval = |p: &[f32; 3]| (fg.neg_log(*p), bg.neg_log(*p));+ #[cfg(not(target_arch = "wasm32"))]+ let v: Vec<(f32, f32)> = {+ use rayon::prelude::*;+ img.px.par_iter().map(eval).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let v: Vec<(f32, f32)> = img.px.iter().map(eval).collect();+ v.into_iter().unzip()+}++/// Labels 8-connected components of `mask`; returns (labels with 0 = background, sizes indexed by label).+pub fn components(mask: &[bool], w: usize, h: usize) -> (Vec<u32>, Vec<usize>) {+ let mut lab = vec![0u32; w * h];+ let mut sizes = vec![0usize];+ let mut stack = Vec::new();+ for s in 0..w * h {+ if !mask[s] || lab[s] != 0 {+ continue;+ }+ let l = sizes.len() as u32;+ sizes.push(0);+ lab[s] = l;+ stack.push(s);+ while let Some(i) = stack.pop() {+ sizes[l as usize] += 1;+ let (x, y) = ((i % w) as i32, (i / w) as i32);+ for dy in -1..=1 {+ for dx in -1..=1 {+ let (nx, ny) = (x + dx, y + dy);+ if nx < 0 || ny < 0 || nx >= w as i32 || ny >= h as i32 {+ continue;+ }+ let j = ny as usize * w + nx as usize;+ if mask[j] && lab[j] == 0 {+ lab[j] = l;+ stack.push(j);+ }+ }+ }+ }+ }+ (lab, sizes)+}++/// Keeps the connected components of `mask` that contain a `seed` pixel.+pub fn keep_seeded(mask: &[bool], seeds: &[bool], w: usize, h: usize) -> Vec<bool> {+ let (lab, sizes) = components(mask, w, h);+ let mut keep = vec![false; sizes.len()];+ for (l, s) in lab.iter().zip(seeds) {+ if *s && *l != 0 {+ keep[*l as usize] = true;+ }+ }+ lab.iter().map(|l| keep[*l as usize] && *l != 0).collect()+}++/// Keeps components at least `frac` of the largest one and fills holes (4-connected background+/// areas not touching the border) smaller than `hole_frac` of the kept area.+pub fn clean_mask(mask: &[bool], w: usize, h: usize, frac: f32, hole_frac: f32) -> Vec<bool> {+ let (lab, sizes) = components(mask, w, h);+ let largest = sizes.iter().skip(1).copied().max().unwrap_or(0);+ if largest == 0 {+ return vec![false; w * h];+ }+ let min = (largest as f32 * frac).ceil() as usize;+ let mut out: Vec<bool> = lab.iter().map(|l| *l != 0 && sizes[*l as usize] >= min).collect();+ let area = out.iter().filter(|v| **v).count();+ let max_hole = (area as f32 * hole_frac) as usize;+ let inv: Vec<bool> = out.iter().map(|v| !v).collect();+ let (hl, hs) = components4(&inv, w, h);+ let mut touches = vec![false; hs.len()];+ for x in 0..w {+ touches[hl[x] as usize] = true;+ touches[hl[(h - 1) * w + x] as usize] = true;+ }+ for y in 0..h {+ touches[hl[y * w] as usize] = true;+ touches[hl[y * w + w - 1] as usize] = true;+ }+ for (o, l) in out.iter_mut().zip(&hl) {+ if *l != 0 && !touches[*l as usize] && hs[*l as usize] <= max_hole {+ *o = true;+ }+ }+ out+}++fn components4(mask: &[bool], w: usize, h: usize) -> (Vec<u32>, Vec<usize>) {+ let mut lab = vec![0u32; w * h];+ let mut sizes = vec![0usize];+ let mut stack = Vec::new();+ for s in 0..w * h {+ if !mask[s] || lab[s] != 0 {+ continue;+ }+ let l = sizes.len() as u32;+ sizes.push(0);+ lab[s] = l;+ stack.push(s);+ while let Some(i) = stack.pop() {+ sizes[l as usize] += 1;+ let (x, y) = (i % w, i / w);+ let n = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)];+ for j in n.into_iter().flatten() {+ if mask[j] && lab[j] == 0 {+ lab[j] = l;+ stack.push(j);+ }+ }+ }+ }+ (lab, sizes)+}++/// Softens a hard 0/255 mask's edges: edge pixels blend with their 3×3 neighbourhood (the same+/// rule as the magic wand's anti-aliasing).+pub fn antialias_u8(mask: &mut [u8], w: usize, h: usize) {+ let src = mask.to_vec();+ let at = |x: i32, y: i32, v: u8| if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 { v } else { src[y as usize * w + x as usize] };+ let row = |y: usize, out: &mut [u8]| {+ for (x, o) in out.iter_mut().enumerate() {+ let v = src[y * w + x];+ let mut sum = 0u32;+ let mut edge = false;+ for dy in -1..=1 {+ for dx in -1..=1 {+ let n = at(x as i32 + dx, y as i32 + dy, v);+ edge |= n != v;+ sum += n as u32;+ }+ }+ if edge {+ let avg = sum as f32 / (9.0 * 255.0);+ let f = if v > 127 { 0.5 + 0.5 * avg } else { 0.5 * avg };+ *o = (f * 255.0).round() as u8;+ }+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ mask.par_chunks_mut(w).enumerate().for_each(|(y, r)| row(y, r));+ }+ #[cfg(target_arch = "wasm32")]+ mask.chunks_mut(w).enumerate().for_each(|(y, r)| row(y, r));+}++/// Shrinks a region's box to its non-zero pixels (`None` if empty).+pub fn trim_region(r: Region) -> Option<Region> {+ let w = r.bbox.width() as usize;+ if w == 0 {+ return None;+ }+ let h = r.mask.len() / w;+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);+ for y in 0..h {+ let row = &r.mask[y * w..(y + 1) * w];+ if let (Some(a), Some(b)) = (row.iter().position(|v| *v != 0), row.iter().rposition(|v| *v != 0)) {+ x0 = x0.min(a);+ x1 = x1.max(b + 1);+ y0 = y0.min(y);+ y1 = y + 1;+ }+ }+ if x0 == usize::MAX {+ return None;+ }+ if (x0, y0, x1, y1) == (0, 0, w, h) {+ return Some(r);+ }+ let nw = x1 - x0;+ let mut mask = Vec::with_capacity(nw * (y1 - y0));+ for y in y0..y1 {+ mask.extend_from_slice(&r.mask[y * w + x0..y * w + x1]);+ }+ let b = r.bbox;+ Some(Region { bbox: Rect::new(b.x0 + x0 as i32, b.y0 + y0 as i32, b.x0 + x1 as i32, b.y0 + y1 as i32), mask })+}++/// Turns a working-resolution labelling over `window` (sampled with `step`) into a full-resolution+/// region. With `step > 1` the boundary is re-cut at full resolution in a band about `step`+/// pixels wide around the upsampled boundary, using the given colour models, tile by tile.+/// The result is anti-aliased by one pixel.+pub fn finish_region(sampler: &dyn Sampler, window: Rect, step: usize, low: &[bool], lw: usize, lh: usize, models: Option<(&Gmm, &Gmm)>) -> Option<Region> {+ let (w, h) = (window.width() as usize, window.height() as usize);+ let mut mask = vec![0u8; w * h];+ if step <= 1 {+ for (m, l) in mask.iter_mut().zip(low) {+ *m = if *l { 255 } else { 0 };+ }+ } else {+ // Band blocks: working pixels with a differently labelled pixel within one block.+ let mut band = vec![false; lw * lh];+ for y in 0..lh {+ for x in 0..lw {+ let v = low[y * lw + x];+ 'n: for dy in -1i32..=1 {+ for dx in -1i32..=1 {+ let (nx, ny) = (x as i32 + dx, y as i32 + dy);+ if nx >= 0 && ny >= 0 && (nx as usize) < lw && (ny as usize) < lh && low[ny as usize * lw + nx as usize] != v {+ band[y * lw + x] = true;+ break 'n;+ }+ }+ }+ }+ }+ let fill = |y: usize, row: &mut [u8]| {+ let ly = (y / step).min(lh - 1);+ for (x, o) in row.iter_mut().enumerate() {+ *o = if low[ly * lw + (x / step).min(lw - 1)] { 255 } else { 0 };+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ mask.par_chunks_mut(w).enumerate().for_each(|(y, r)| fill(y, r));+ }+ #[cfg(target_arch = "wasm32")]+ mask.chunks_mut(w).enumerate().for_each(|(y, r)| fill(y, r));+ if let Some((fg, bg)) = models {+ refine_band(sampler, window, step, low, &band, lw, lh, fg, bg, &mut mask);+ }+ }+ antialias_u8(&mut mask, w, h);+ trim_region(Region { bbox: window, mask })+}++/// Full-resolution graph cut restricted to the band blocks (see [`finish_region`]).+#[allow(clippy::too_many_arguments)]+fn refine_band(sampler: &dyn Sampler, window: Rect, step: usize, low: &[bool], band: &[bool], lw: usize, lh: usize, fg: &Gmm, bg: &Gmm, mask: &mut [u8]) {+ const T: i32 = 192;+ const HALO: i32 = 12;+ let w = window.width() as usize;+ let block = |x: i32, y: i32| -> usize { ((y - window.y0) as usize / step).min(lh - 1) * lw + ((x - window.x0) as usize / step).min(lw - 1) };+ let mut tiles = Vec::new();+ let mut ty = window.y0;+ while ty < window.y1 {+ let mut tx = window.x0;+ while tx < window.x1 {+ let t = Rect::new(tx, ty, (tx + T).min(window.x1), (ty + T).min(window.y1));+ // Any band block overlapping the tile?+ let (bx0, by0) = ((t.x0 - window.x0) as usize / step, (t.y0 - window.y0) as usize / step);+ let (bx1, by1) = (((t.x1 - 1 - window.x0) as usize / step).min(lw - 1), ((t.y1 - 1 - window.y0) as usize / step).min(lh - 1));+ if (by0..=by1).any(|by| (bx0..=bx1).any(|bx| band[by * lw + bx])) {+ tiles.push(t);+ }+ tx += T;+ }+ ty += T;+ }+ let run = |t: &Rect| -> (Rect, Vec<bool>) {+ let r = t.inflate(HALO).intersect(&window);+ let img = sampler.rgb(r);+ let (rw, rh) = (r.width() as usize, r.height() as usize);+ let mut fixed = vec![FREE; rw * rh];+ let mut cfg = vec![0.0f32; rw * rh];+ let mut cbg = vec![0.0f32; rw * rh];+ for yy in 0..rh {+ for xx in 0..rw {+ let i = yy * rw + xx;+ let b = block(r.x0 + xx as i32, r.y0 + yy as i32);+ let lab = low[b];+ if !band[b] {+ fixed[i] = if lab { HARD_FG } else { HARD_BG };+ continue;+ }+ let p = img.px[i];+ // Colour likelihoods plus a weak prior towards the working-resolution label.+ cfg[i] = fg.neg_log(p) + if lab { 0.0 } else { 0.4 };+ cbg[i] = bg.neg_log(p) + if lab { 0.4 } else { 0.0 };+ }+ }+ let beta = contrast_beta(&img);+ let cut = grid_cut(&img, &cfg, &cbg, &fixed, 50.0, beta);+ let (cw, ch) = (t.width() as usize, t.height() as usize);+ let mut core = Vec::with_capacity(cw * ch);+ for yy in 0..ch {+ let sy = (t.y0 - r.y0) as usize + yy;+ let sx = (t.x0 - r.x0) as usize;+ core.extend_from_slice(&cut[sy * rw + sx..sy * rw + sx + cw]);+ }+ (*t, core)+ };+ #[cfg(not(target_arch = "wasm32"))]+ let results: Vec<(Rect, Vec<bool>)> = {+ use rayon::prelude::*;+ tiles.par_iter().map(run).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let results: Vec<(Rect, Vec<bool>)> = tiles.iter().map(run).collect();+ for (t, core) in results {+ let cw = t.width() as usize;+ for (yy, row) in core.chunks_exact(cw).enumerate() {+ let o = (t.y0 - window.y0) as usize * w + yy * w + (t.x0 - window.x0) as usize;+ for (m, v) in mask[o..o + cw].iter_mut().zip(row) {+ *m = if *v { 255 } else { 0 };+ }+ }+ }+}++/// Deterministic pseudo-random numbers (xorshift) for sampling and tests.+#[derive(Clone, Debug)]+pub struct Rng(u64);++impl Rng {+ pub fn new(seed: u64) -> Self {+ Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)+ }+ pub fn next_u64(&mut self) -> u64 {+ let mut x = self.0;+ x ^= x << 13;+ x ^= x >> 7;+ x ^= x << 17;+ self.0 = x;+ x+ }+ /// Uniform in `[0, 1)`.+ pub fn f32(&mut self) -> f32 {+ (self.next_u64() >> 40) as f32 / (1u64 << 24) as f32+ }+ /// Standard normal (Box–Muller).+ pub fn normal(&mut self) -> f32 {+ let u = self.f32().max(1e-7);+ let v = self.f32();+ (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()+ }+}++/// Every `k`-th element so that at most `max` remain.+pub fn subsample<T: Copy>(v: &[T], max: usize) -> Vec<T> {+ if v.len() <= max {+ return v.to_vec();+ }+ let k = v.len().div_ceil(max);+ v.iter().step_by(k).copied().collect()+}++#[cfg(test)]+mod tests;diff --git a/crates/algo/src/segment/quick.rs b/crates/algo/src/segment/quick.rsnew file mode 100644index 000000000..612898f11--- /dev/null+++ b/crates/algo/src/segment/quick.rs@@ -0,0 +1,245 @@+//! Quick Selection brush.+//!+//! A brush stroke seeds a graph cut in a working window around the stroke:+//!+//! 1. Stroked pixels are hard foreground; a GMM of their colours is the foreground model.+//! 2. A geodesic distance from the stroke over a barrier map (the colour gradient of a lightly+//! smoothed image above the texture level found under the stroke; raster-scan geodesic+//! transform, Toivanen 1996; Criminisi, Sharp & Blake, "GeoS: Geodesic Image Segmentation",+//! ECCV 2008) separates what is reachable without crossing an edge from what lies behind+//! edges. Pixels behind edges are+//! sampled for the background GMM (mixed with a uniform outlier density, so a window without+//! any edge simply selects everything similar), and the distance also enters the data term.+//! 3. A contrast-sensitive min cut (Boykov & Jolly 2001) snaps the result to image edges; only+//! components touching the stroke are kept.+//!+//! This follows the spirit of "Paint Selection" (Liu, Sun & Shum, SIGGRAPH 2009) and of+//! geodesic matting (Bai & Sapiro, ICCV 2007). Large windows run at a reduced working resolution+//! and the boundary is re-cut at full resolution.++use photocraft_geom::Rect;++use super::gmm::Gmm;+use super::{HARD_FG, FREE, Region, RgbImage, Sampler, contrast_beta, grid_cut, keep_seeded, subsample};++/// Covariance ridge for the (often tiny) stroke sample: ~6 levels of standard deviation.+const QREG: f32 = 6e-4;+/// Geodesic distance (colour units above noise) that counts as "behind an edge".+const EDGE: f32 = 0.06;+/// Neighbour colour steps below this never count as edges (smooth shading, fine noise).+const MIN_STEP: f32 = 0.03;+/// Data-term weight of the geodesic distance (nats per `EDGE`).+const KAPPA: f32 = 2.0;+const GAMMA: f32 = 50.0;++/// Default working-resolution budget (pixels) for a stroke.+pub const WORK_PX: usize = 160_000;++/// Grows a selection from a brush stroke (`points` in document pixels, brush diameter `size`).+/// Returns the new region (to be added to or subtracted from the current selection), or `None`+/// when the stroke misses the canvas.+pub fn quick_select(sampler: &dyn Sampler, canvas: Rect, points: &[(f32, f32)], size: f32, work_px: usize) -> Option<Region> {+ if points.is_empty() {+ return None;+ }+ let size = size.max(1.0);+ let r = size / 2.0;+ let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);+ for &(x, y) in points {+ x0 = x0.min(x - r);+ y0 = y0.min(y - r);+ x1 = x1.max(x + r);+ y1 = y1.max(y + r);+ }+ let bbox = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32 + 1, y1.ceil() as i32 + 1).intersect(&canvas);+ if bbox.is_empty() {+ return None;+ }+ let margin = (size * 6.0).max(512.0) as i32;+ let window = bbox.inflate(margin).intersect(&canvas);+ let step = super::scale_for(window, work_px);+ let img = sampler.rgb_scaled(window, step);+ let (lw, lh) = (img.w, img.h);+ let st = step as f32;+ let pts: Vec<(f32, f32)> = points.iter().map(|&(x, y)| ((x - window.x0 as f32) / st, (y - window.y0 as f32) / st)).collect();+ let seeds = stroke_mask(&pts, (r / st).max(0.75), lw, lh);+ if !seeds.iter().any(|s| *s) {+ return None;+ }+ let (fg, bg, low) = segment(&img, &seeds);+ if !low.iter().any(|v| *v) {+ return None;+ }+ super::finish_region(sampler, window, step, &low, lw, lh, Some((&fg, &bg)))+}++/// The working-resolution segmentation: (foreground model, background model, labels).+pub fn segment(img: &RgbImage, seeds: &[bool]) -> (Gmm, Gmm, Vec<bool>) {+ let (lw, lh) = (img.w, img.h);+ let geo = geodesic(img, seeds);+ let fs: Vec<[f32; 3]> = img.px.iter().zip(seeds).filter(|(_, s)| **s).map(|(p, _)| *p).collect();+ let bs: Vec<[f32; 3]> = img.px.iter().zip(&geo).filter(|(_, d)| **d > EDGE).map(|(p, _)| *p).collect();+ let fs = subsample(&fs, 20_000);+ let bs = subsample(&bs, 20_000);+ let fg = Gmm::fit(&fs, (fs.len() / 40).clamp(1, 4), QREG).unwrap_or_else(broad_model);+ let bg = if bs.len() >= 30 { Gmm::fit(&bs, 6, QREG) } else { None };+ let eval = |(p, d): (&[f32; 3], &f32)| -> (f32, f32) {+ let cf = fg.neg_log(*p) + KAPPA * (d / EDGE).min(4.0);+ let cb = match &bg {+ Some(b) => -((0.85 * b.log_prob(*p).exp() + 0.15).ln() as f32),+ None => 0.0,+ };+ (cf, cb)+ };+ #[cfg(not(target_arch = "wasm32"))]+ let costs: Vec<(f32, f32)> = {+ use rayon::prelude::*;+ img.px.par_iter().zip(geo.par_iter()).map(eval).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let costs: Vec<(f32, f32)> = img.px.iter().zip(geo.iter()).map(eval).collect();+ let (cf, cb): (Vec<f32>, Vec<f32>) = costs.into_iter().unzip();+ let fixed: Vec<u8> = seeds.iter().map(|s| if *s { HARD_FG } else { FREE }).collect();+ let cut = grid_cut(img, &cf, &cb, &fixed, GAMMA, contrast_beta(img));+ let low = keep_seeded(&cut, seeds, lw, lh);+ (fg, bg.unwrap_or_else(broad_model), low)+}++/// A near-uniform density over the RGB cube.+pub fn broad_model() -> Gmm {+ let corners: Vec<[f32; 3]> = (0..8).map(|i| [(i & 1) as f32, ((i >> 1) & 1) as f32, ((i >> 2) & 1) as f32]).collect();+ Gmm::fit(&corners, 1, 0.0).expect("non-degenerate")+}++/// Pixels within `radius` (working pixels) of the polyline `pts`, plus each point's own pixel.+pub fn stroke_mask(pts: &[(f32, f32)], radius: f32, w: usize, h: usize) -> Vec<bool> {+ let mut m = vec![false; w * h];+ let segs: Vec<((f32, f32), (f32, f32))> = if pts.len() == 1 { vec![(pts[0], pts[0])] } else { pts.windows(2).map(|p| (p[0], p[1])).collect() };+ for (a, b) in segs {+ let x0 = ((a.0.min(b.0) - radius).floor().max(0.0)) as usize;+ let y0 = ((a.1.min(b.1) - radius).floor().max(0.0)) as usize;+ let x1 = ((a.0.max(b.0) + radius).ceil().max(0.0) as usize).min(w);+ let y1 = ((a.1.max(b.1) + radius).ceil().max(0.0) as usize).min(h);+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let len2 = dx * dx + dy * dy;+ for y in y0..y1 {+ for x in x0..x1 {+ let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);+ let t = if len2 > 0.0 { (((px - a.0) * dx + (py - a.1) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 };+ let (qx, qy) = (a.0 + t * dx - px, a.1 + t * dy - py);+ if qx * qx + qy * qy <= radius * radius {+ m[y * w + x] = true;+ }+ }+ }+ }+ for &(x, y) in pts {+ if x >= 0.0 && y >= 0.0 && (x as usize) < w && (y as usize) < h {+ m[y as usize * w + x as usize] = true;+ }+ }+ m+}++fn blur3(img: &RgbImage) -> RgbImage {+ let (w, h) = (img.w, img.h);+ let mut tmp = img.clone();+ for y in 0..h {+ for x in 0..w {+ let (l, r) = (img.at(x.saturating_sub(1), y), img.at((x + 1).min(w - 1), y));+ let c = img.at(x, y);+ tmp.px[y * w + x] = [0, 1, 2].map(|k| (l[k] + c[k] + r[k]) / 3.0);+ }+ }+ let mut out = tmp.clone();+ for y in 0..h {+ for x in 0..w {+ let (u, d) = (tmp.at(x, y.saturating_sub(1)), tmp.at(x, (y + 1).min(h - 1)));+ let c = tmp.at(x, y);+ out.px[y * w + x] = [0, 1, 2].map(|k| (u[k] + c[k] + d[k]) / 3.0);+ }+ }+ out+}++/// Geodesic distance from `seeds` over a barrier map: each pixel costs its colour gradient+/// magnitude (smoothed image) above the texture level of the stroke (twice the median gradient+/// under it), plus a tiny spatial term. Raster-scan approximation (two forward/backward sweeps,+/// 8-neighbours).+pub fn geodesic(img: &RgbImage, seeds: &[bool]) -> Vec<f32> {+ let (w, h) = (img.w, img.h);+ let sm = blur3(&blur3(img));+ // Texture level of what the user painted: median local gradient over the stroke (grown by+ // two pixels). Gradual colour changes and texture at that level cost nothing.+ let mut near = vec![false; w * h];+ for (i, _) in seeds.iter().enumerate().filter(|(_, s)| **s) {+ let (x, y) = (i % w, i / w);+ for yy in y.saturating_sub(2)..(y + 3).min(h) {+ near[yy * w + x.saturating_sub(2)..yy * w + (x + 3).min(w)].fill(true);+ }+ }+ // Colour gradient magnitude (central differences) of the smoothed image.+ let mut g = vec![0.0f32; w * h];+ for y in 0..h {+ for x in 0..w {+ let (l, r) = (sm.at(x.saturating_sub(1), y), sm.at((x + 1).min(w - 1), y));+ let (u, dn) = (sm.at(x, y.saturating_sub(1)), sm.at(x, (y + 1).min(h - 1)));+ g[y * w + x] = ((super::d2(l, r) + super::d2(u, dn)) * 0.25).sqrt();+ }+ }+ let mut diffs: Vec<f32> = (0..w * h).filter(|i| near[*i]).map(|i| g[i]).collect();+ let tau = if diffs.is_empty() {+ 0.0+ } else {+ let mid = diffs.len() / 2;+ *diffs.select_nth_unstable_by(mid, |a, b| a.total_cmp(b)).1+ };+ let thr = (2.0 * tau).max(MIN_STEP);+ // Crossing pixels whose gradient exceeds the texture level costs the excess: a barrier map,+ // so an edge costs about its contrast whatever direction the path crosses it.+ let e: Vec<f32> = g.iter().map(|v| (v - thr).max(0.0)).collect();+ let cost = |a: usize, b: usize, len: f32| len * (0.5 * (e[a] + e[b]) + 1e-6);+ let mut d: Vec<f32> = seeds.iter().map(|s| if *s { 0.0 } else { f32::INFINITY }).collect();+ let sq = std::f32::consts::SQRT_2;+ for _ in 0..2 {+ for y in 0..h {+ for x in 0..w {+ let i = y * w + x;+ let mut v = d[i];+ if x > 0 {+ v = v.min(d[i - 1] + cost(i, i - 1, 1.0));+ }+ if y > 0 {+ v = v.min(d[i - w] + cost(i, i - w, 1.0));+ if x > 0 {+ v = v.min(d[i - w - 1] + cost(i, i - w - 1, sq));+ }+ if x + 1 < w {+ v = v.min(d[i - w + 1] + cost(i, i - w + 1, sq));+ }+ }+ d[i] = v;+ }+ }+ for y in (0..h).rev() {+ for x in (0..w).rev() {+ let i = y * w + x;+ let mut v = d[i];+ if x + 1 < w {+ v = v.min(d[i + 1] + cost(i, i + 1, 1.0));+ }+ if y + 1 < h {+ v = v.min(d[i + w] + cost(i, i + w, 1.0));+ if x + 1 < w {+ v = v.min(d[i + w + 1] + cost(i, i + w + 1, sq));+ }+ if x > 0 {+ v = v.min(d[i + w - 1] + cost(i, i + w - 1, sq));+ }+ }+ d[i] = v;+ }+ }+ }+ d+}diff --git a/crates/algo/src/segment/slic.rs b/crates/algo/src/segment/slic.rsnew file mode 100644index 000000000..ab0508018--- /dev/null+++ b/crates/algo/src/segment/slic.rs@@ -0,0 +1,174 @@+//! SLIC superpixels.+//!+//! Implemented from R. Achanta, A. Shaji, K. Smith, A. Lucchi, P. Fua and S. Süsstrunk, "SLIC+//! Superpixels Compared to State-of-the-Art Superpixel Methods", IEEE PAMI 34(11), 2012: k-means+//! in CIELAB + xy restricted to a 2S×2S window around each centre, distance+//! `D = sqrt(d_lab² + (d_xy / S)² m²)`, centres seeded on a grid and moved to the lowest gradient+//! in their 3×3 neighbourhood, then connectivity enforcement (small fragments join a neighbour).++use super::RgbImage;++/// sRGB (`0..=1`) to CIELAB (D65), L in `0..=100`.+pub fn rgb_to_lab(c: [f32; 3]) -> [f32; 3] {+ let lin = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };+ let (r, g, b) = (lin(c[0]), lin(c[1]), lin(c[2]));+ let x = (0.412_456_4 * r + 0.357_576_1 * g + 0.180_437_5 * b) / 0.950_47;+ let y = 0.212_672_9 * r + 0.715_152_2 * g + 0.072_175 * b;+ let z = (0.019_333_9 * r + 0.119_192 * g + 0.950_304_1 * b) / 1.088_83;+ let f = |t: f32| if t > 0.008_856 { t.cbrt() } else { 7.787 * t + 16.0 / 116.0 };+ let (fx, fy, fz) = (f(x), f(y), f(z));+ [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]+}++/// A superpixel labelling.+#[derive(Clone, Debug)]+pub struct Superpixels {+ pub w: usize,+ pub h: usize,+ /// Label per pixel, `0..count`.+ pub labels: Vec<u32>,+ pub count: usize,+ /// Grid interval S used.+ pub step: f32,+}++/// Segments `img` into about `target` superpixels. `compactness` is SLIC's `m` (10 is typical+/// for CIELAB), `iters` the number of k-means iterations (10 in the paper).+pub fn slic(img: &RgbImage, target: usize, compactness: f32, iters: usize) -> Superpixels {+ let (w, h) = (img.w, img.h);+ let lab: Vec<[f32; 3]> = img.px.iter().map(|p| rgb_to_lab(*p)).collect();+ slic_lab(&lab, w, h, target, compactness, iters)+}++/// [`slic`] on a CIELAB image.+pub fn slic_lab(lab: &[[f32; 3]], w: usize, h: usize, target: usize, compactness: f32, iters: usize) -> Superpixels {+ let n = w * h;+ if n == 0 {+ return Superpixels { w, h, labels: Vec::new(), count: 0, step: 1.0 };+ }+ let s = ((n as f32 / target.max(1) as f32).sqrt()).max(1.0);+ let grad = |x: usize, y: usize| -> f32 {+ let at = |x: usize, y: usize| lab[y.min(h - 1) * w + x.min(w - 1)];+ let (l, r) = (at(x.saturating_sub(1), y), at(x + 1, y));+ let (u, d) = (at(x, y.saturating_sub(1)), at(x, y + 1));+ super::d2(l, r) + super::d2(u, d)+ };+ // Seed centres: [L, a, b, x, y].+ let mut centers: Vec<[f32; 5]> = Vec::new();+ let mut y = s / 2.0;+ while y < h as f32 {+ let mut x = s / 2.0;+ while x < w as f32 {+ let (cx, cy) = (x as usize, y as usize);+ let (mut bx, mut by, mut bg) = (cx, cy, f32::MAX);+ for yy in cy.saturating_sub(1)..=(cy + 1).min(h - 1) {+ for xx in cx.saturating_sub(1)..=(cx + 1).min(w - 1) {+ let g = grad(xx, yy);+ if g < bg {+ (bx, by, bg) = (xx, yy, g);+ }+ }+ }+ let c = lab[by * w + bx];+ centers.push([c[0], c[1], c[2], bx as f32, by as f32]);+ x += s;+ }+ y += s;+ }+ let mut labels = vec![u32::MAX; n];+ let mut dist = vec![f32::MAX; n];+ let wxy = (compactness / s).powi(2);+ let r = s.ceil() as i64;+ for _ in 0..iters.max(1) {+ dist.fill(f32::MAX);+ for (k, c) in centers.iter().enumerate() {+ let (cx, cy) = (c[3].round() as i64, c[4].round() as i64);+ for yy in (cy - r).max(0)..(cy + r + 1).min(h as i64) {+ for xx in (cx - r).max(0)..(cx + r + 1).min(w as i64) {+ let i = yy as usize * w + xx as usize;+ let p = lab[i];+ let dc = super::d2(p, [c[0], c[1], c[2]]);+ let (dx, dy) = (xx as f32 - c[3], yy as f32 - c[4]);+ let d = dc + (dx * dx + dy * dy) * wxy;+ if d < dist[i] {+ dist[i] = d;+ labels[i] = k as u32;+ }+ }+ }+ }+ let mut sums = vec![[0.0f64; 6]; centers.len()];+ for (i, l) in labels.iter().enumerate() {+ if *l == u32::MAX {+ continue;+ }+ let p = lab[i];+ let s = &mut sums[*l as usize];+ s[0] += p[0] as f64;+ s[1] += p[1] as f64;+ s[2] += p[2] as f64;+ s[3] += (i % w) as f64;+ s[4] += (i / w) as f64;+ s[5] += 1.0;+ }+ for (c, s) in centers.iter_mut().zip(&sums) {+ if s[5] > 0.0 {+ *c = [0, 1, 2, 3, 4].map(|j| (s[j] / s[5]) as f32);+ }+ }+ }+ // Unreached pixels (possible at the far edges): nearest centre by label of a neighbour.+ for i in 0..n {+ if labels[i] == u32::MAX {+ labels[i] = if i > 0 { labels[i - 1] } else { 0 };+ }+ }+ let (labels, count) = enforce_connectivity(&labels, w, h, ((s * s) / 4.0) as usize);+ Superpixels { w, h, labels, count, step: s }+}++/// Relabels 4-connected components; components smaller than `min_size` merge into the adjacent+/// component found before them (as in the SLIC paper's post-processing).+fn enforce_connectivity(labels: &[u32], w: usize, h: usize, min_size: usize) -> (Vec<u32>, usize) {+ let n = w * h;+ let mut out = vec![u32::MAX; n];+ let mut next = 0u32;+ let mut comp = Vec::new();+ for s in 0..n {+ if out[s] != u32::MAX {+ continue;+ }+ // Adjacent already-labelled component (to merge into if this one is small).+ let (sx, sy) = (s % w, s / w);+ let mut adj = None;+ for j in [(sx > 0).then(|| s - 1), (sy > 0).then(|| s - w)].into_iter().flatten() {+ if out[j] != u32::MAX {+ adj = Some(out[j]);+ }+ }+ comp.clear();+ comp.push(s);+ out[s] = next;+ let mut k = 0;+ while k < comp.len() {+ let i = comp[k];+ k += 1;+ let (x, y) = (i % w, i / w);+ for j in [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)].into_iter().flatten() {+ if out[j] == u32::MAX && labels[j] == labels[s] {+ out[j] = next;+ comp.push(j);+ }+ }+ }+ match adj {+ Some(a) if comp.len() < min_size => {+ for &i in &comp {+ out[i] = a;+ }+ }+ _ => next += 1,+ }+ }+ (out, next as usize)+}diff --git a/crates/algo/src/segment/subject.rs b/crates/algo/src/segment/subject.rsnew file mode 100644index 000000000..6002672ad--- /dev/null+++ b/crates/algo/src/segment/subject.rs@@ -0,0 +1,270 @@+//! Select Subject (classical, heuristic).+//!+//! Photoshop uses a learned model; we approximate it with salient-object detection feeding a+//! GrabCut:+//!+//! 1. SLIC superpixels on a working-resolution copy.+//! 2. Per-superpixel saliency from "Saliency Optimization from Robust Background Detection"+//! (W. Zhu, S. Liang, Y. Wei and J. Sun, CVPR 2014): boundary connectivity+//! `BndCon(p) = Len_bnd(p) / sqrt(Area(p))` over geodesic colour distances gives a background+//! probability; background-weighted contrast gives foreground cues; a least-squares+//! optimisation with smoothness between neighbours combines them.+//! 3. Blended with frequency-tuned saliency (R. Achanta, S. Hemami, F. Estrada and+//! S. Süsstrunk, "Frequency-tuned Salient Region Detection", CVPR 2009): distance of the+//! lightly blurred CIELAB image from its mean colour.+//! 4. Otsu's threshold on the saliency map seeds a GrabCut trimap (low-saliency border pixels+//! are definite background); the result is cleaned (small islands dropped, small holes+//! filled) and re-cut at full resolution.+//!+//! Works well for a distinct object on a comparatively plain background; it is not a semantic+//! segmenter.++use std::cmp::Ordering;+use std::collections::BinaryHeap;++use photocraft_geom::Rect;++use super::grabcut::{self, BG, PR_BG, PR_FG};+use super::slic::{rgb_to_lab, slic_lab};+use super::{Region, Sampler};++/// Working-resolution budget (pixels).+pub const WORK_PX: usize = 110_000;+const SIGMA_CLR: f32 = 10.0;+const SIGMA_SPA: f32 = 0.25;++/// Selects the most salient object on the canvas.+pub fn select_subject(sampler: &dyn Sampler, canvas: Rect) -> Option<Region> {+ if canvas.width() < 4 || canvas.height() < 4 {+ return None;+ }+ let step = super::scale_for(canvas, WORK_PX);+ let img = sampler.rgb_scaled(canvas, step);+ let (w, h) = (img.w, img.h);+ let sal = saliency(&img);+ let t = otsu(&sal).clamp(0.15, 0.85);+ let mut trimap = vec![PR_BG; w * h];+ let mut any_fg = false;+ for y in 0..h {+ for x in 0..w {+ let i = y * w + x;+ let border = x == 0 || y == 0 || x + 1 == w || y + 1 == h;+ trimap[i] = if sal[i] >= t {+ any_fg = true;+ PR_FG+ } else if border || sal[i] < 0.4 * t {+ BG+ } else {+ PR_BG+ };+ }+ }+ if !any_fg {+ return None;+ }+ let (fg, bg) = grabcut::grabcut(&img, &mut trimap, 6)?;+ let low: Vec<bool> = trimap.iter().map(|v| *v == PR_FG || *v == grabcut::FG).collect();+ let low = super::clean_mask(&low, w, h, 0.2, 0.05);+ if !low.iter().any(|v| *v) {+ return None;+ }+ super::finish_region(sampler, canvas, step, &low, w, h, Some((&fg, &bg)))+}++/// Per-pixel saliency in `0..=1` (see the module docs).+pub fn saliency(img: &super::RgbImage) -> Vec<f32> {+ let (w, h) = (img.w, img.h);+ let lab: Vec<[f32; 3]> = img.px.iter().map(|p| rgb_to_lab(*p)).collect();+ let target = ((w * h) / 150).clamp(16, 400);+ let sp = slic_lab(&lab, w, h, target, 10.0, 8);+ let n = sp.count;+ // Region statistics.+ let mut mean = vec![[0.0f64; 3]; n];+ let mut pos = vec![[0.0f64; 2]; n];+ let mut cnt = vec![0.0f64; n];+ let mut on_border = vec![false; n];+ for y in 0..h {+ for x in 0..w {+ let l = sp.labels[y * w + x] as usize;+ let c = lab[y * w + x];+ for k in 0..3 {+ mean[l][k] += c[k] as f64;+ }+ pos[l][0] += x as f64 / w as f64;+ pos[l][1] += y as f64 / h as f64;+ cnt[l] += 1.0;+ if x == 0 || y == 0 || x + 1 == w || y + 1 == h {+ on_border[l] = true;+ }+ }+ }+ let mean: Vec<[f32; 3]> = mean.iter().zip(&cnt).map(|(m, c)| m.map(|v| (v / c.max(1.0)) as f32)).collect();+ let pos: Vec<[f32; 2]> = pos.iter().zip(&cnt).map(|(p, c)| p.map(|v| (v / c.max(1.0)) as f32)).collect();+ let dapp = |a: usize, b: usize| super::d2(mean[a], mean[b]).sqrt();+ // Adjacency.+ let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];+ let mut link = |a: usize, b: usize| {+ if a != b && !adj[a].contains(&b) {+ adj[a].push(b);+ adj[b].push(a);+ }+ };+ for y in 0..h {+ for x in 0..w {+ let l = sp.labels[y * w + x] as usize;+ if x + 1 < w {+ link(l, sp.labels[y * w + x + 1] as usize);+ }+ if y + 1 < h {+ link(l, sp.labels[(y + 1) * w + x] as usize);+ }+ }+ }+ // Boundary connectivity from all-pairs geodesic distances (Dijkstra per region).+ let mut wbg = vec![0.0f32; n];+ let mut geo = vec![f32::INFINITY; n];+ for (p, wb) in wbg.iter_mut().enumerate() {+ dijkstra(p, &adj, &dapp, &mut geo);+ let (mut area, mut len) = (0.0f32, 0.0f32);+ for q in 0..n {+ let s = (-geo[q] * geo[q] / (2.0 * SIGMA_CLR * SIGMA_CLR)).exp();+ area += s;+ if on_border[q] {+ len += s;+ }+ }+ let bnd = len / area.max(1e-6).sqrt();+ *wb = 1.0 - (-bnd * bnd / 2.0).exp();+ }+ // Background-weighted contrast.+ let mut wctr = vec![0.0f32; n];+ for p in 0..n {+ let mut s = 0.0;+ for q in 0..n {+ let (dx, dy) = (pos[p][0] - pos[q][0], pos[p][1] - pos[q][1]);+ let wspa = (-(dx * dx + dy * dy) / (2.0 * SIGMA_SPA * SIGMA_SPA)).exp();+ s += dapp(p, q) * wspa * wbg[q];+ }+ wctr[p] = s;+ }+ let mx = wctr.iter().copied().fold(0.0f32, f32::max).max(1e-6);+ let wfg: Vec<f32> = wctr.iter().map(|v| v / mx).collect();+ // Saliency optimisation: min Σ wbg s² + Σ wfg (s−1)² + Σ_{i~j} w_ij (s_i − s_j)² (Gauss–Seidel).+ let wij: Vec<Vec<f32>> = (0..n).map(|p| adj[p].iter().map(|&q| (-dapp(p, q).powi(2) / (2.0 * SIGMA_CLR * SIGMA_CLR)).exp() + 0.1).collect()).collect();+ let mut s = wfg.clone();+ for _ in 0..200 {+ for p in 0..n {+ let (mut num, mut den) = (wfg[p], wbg[p] + wfg[p]);+ for (q, wq) in adj[p].iter().zip(&wij[p]) {+ num += wq * s[*q];+ den += wq;+ }+ s[p] = num / den.max(1e-6);+ }+ }+ // Frequency-tuned saliency.+ let mut mean_all = [0.0f64; 3];+ for c in &lab {+ for k in 0..3 {+ mean_all[k] += c[k] as f64;+ }+ }+ let mean_all = mean_all.map(|v| (v / lab.len() as f64) as f32);+ let blurred = super::RgbImage { w, h, px: lab.clone() };+ let blurred = blur_lab(&blurred);+ let ft: Vec<f32> = blurred.px.iter().map(|c| super::d2(*c, mean_all).sqrt()).collect();+ let ftmax = ft.iter().copied().fold(0.0f32, f32::max).max(1e-6);+ let smin = s.iter().copied().fold(f32::MAX, f32::min);+ let smax = s.iter().copied().fold(f32::MIN, f32::max);+ let srange = (smax - smin).max(1e-6);+ let mut out: Vec<f32> = sp.labels.iter().zip(&ft).map(|(l, f)| 0.75 * (s[*l as usize] - smin) / srange + 0.25 * f / ftmax).collect();+ let (lo, hi) = out.iter().fold((f32::MAX, f32::MIN), |(a, b), v| (a.min(*v), b.max(*v)));+ let r = (hi - lo).max(1e-6);+ for v in &mut out {+ *v = (*v - lo) / r;+ }+ out+}++fn blur_lab(img: &super::RgbImage) -> super::RgbImage {+ let (w, h) = (img.w, img.h);+ let mut cur = img.clone();+ for _ in 0..2 {+ let mut tmp = cur.clone();+ for y in 0..h {+ for x in 0..w {+ let (l, c, r) = (cur.at(x.saturating_sub(1), y), cur.at(x, y), cur.at((x + 1).min(w - 1), y));+ tmp.px[y * w + x] = [0, 1, 2].map(|k| (l[k] + 2.0 * c[k] + r[k]) / 4.0);+ }+ }+ for y in 0..h {+ for x in 0..w {+ let (u, c, d) = (tmp.at(x, y.saturating_sub(1)), tmp.at(x, y), tmp.at(x, (y + 1).min(h - 1)));+ cur.px[y * w + x] = [0, 1, 2].map(|k| (u[k] + 2.0 * c[k] + d[k]) / 4.0);+ }+ }+ }+ cur+}++#[derive(PartialEq)]+struct Item(f32, usize);+impl Eq for Item {}+impl Ord for Item {+ fn cmp(&self, o: &Self) -> Ordering {+ o.0.total_cmp(&self.0)+ }+}+impl PartialOrd for Item {+ fn partial_cmp(&self, o: &Self) -> Option<Ordering> {+ Some(self.cmp(o))+ }+}++fn dijkstra(src: usize, adj: &[Vec<usize>], wt: &dyn Fn(usize, usize) -> f32, dist: &mut [f32]) {+ dist.fill(f32::INFINITY);+ dist[src] = 0.0;+ let mut heap = BinaryHeap::new();+ heap.push(Item(0.0, src));+ while let Some(Item(d, u)) = heap.pop() {+ if d > dist[u] {+ continue;+ }+ for &v in &adj[u] {+ let nd = d + wt(u, v);+ if nd < dist[v] {+ dist[v] = nd;+ heap.push(Item(nd, v));+ }+ }+ }+}++/// Otsu's threshold of values in `0..=1` (256 bins).+pub fn otsu(v: &[f32]) -> f32 {+ let mut hist = [0u64; 256];+ for x in v {+ hist[(x.clamp(0.0, 1.0) * 255.0).round() as usize] += 1;+ }+ let total = v.len() as f64;+ let sum: f64 = hist.iter().enumerate().map(|(i, c)| i as f64 * *c as f64).sum();+ let (mut wb, mut sb, mut best, mut bt) = (0.0f64, 0.0f64, -1.0f64, 0usize);+ for (t, c) in hist.iter().enumerate() {+ wb += *c as f64;+ if wb == 0.0 {+ continue;+ }+ let wf = total - wb;+ if wf == 0.0 {+ break;+ }+ sb += t as f64 * *c as f64;+ let (mb, mf) = (sb / wb, (sum - sb) / wf);+ let between = wb * wf * (mb - mf) * (mb - mf);+ if between > best {+ best = between;+ bt = t;+ }+ }+ (bt as f32 + 0.5) / 255.0+}diff --git a/crates/algo/src/segment/tests.rs b/crates/algo/src/segment/tests.rsnew file mode 100644index 000000000..d9383b7e2--- /dev/null+++ b/crates/algo/src/segment/tests.rs@@ -0,0 +1,465 @@+use super::gmm::Gmm;+use super::maxflow::Graph;+use super::*;+use photocraft_geom::Rect;++// ---------- max-flow ----------++#[test]+fn maxflow_tiny_graph() {+ // s→a 3, s→b 2, a→b 1, a→t 2, b→t 3: max flow 5.+ let mut g = Graph::with_capacity(2, 1);+ g.add_tweights(0, 3.0, 2.0);+ g.add_tweights(1, 2.0, 3.0);+ g.add_edge(0, 1, 1.0, 0.0);+ assert_eq!(g.maxflow(), 5.0);+}++#[test]+fn maxflow_clrs_network() {+ // The classic textbook network (max flow 23): v1..v4 = 0..3.+ let mut g = Graph::with_capacity(4, 5);+ g.add_tweights(0, 16.0, 0.0);+ g.add_tweights(1, 13.0, 0.0);+ g.add_tweights(2, 0.0, 20.0);+ g.add_tweights(3, 0.0, 4.0);+ g.add_edge(0, 1, 10.0, 4.0);+ g.add_edge(0, 2, 12.0, 0.0);+ g.add_edge(2, 1, 9.0, 0.0);+ g.add_edge(1, 3, 14.0, 0.0);+ g.add_edge(3, 2, 7.0, 0.0);+ assert_eq!(g.maxflow(), 23.0);+ // Min cut {s, v1, v2, v4} | {v3, t}.+ assert!(g.in_source(0) && g.in_source(1) && g.in_source(3));+ assert!(!g.in_source(2));+ assert_eq!(g.residual_out_of_source_side(), 0.0);+}++/// Reference max flow (Edmonds–Karp on a dense matrix; node 0 = s, n−1 = t).+fn edmonds_karp(cap: &mut [Vec<f64>]) -> f64 {+ let n = cap.len();+ let mut flow = 0.0;+ loop {+ let mut prev = vec![usize::MAX; n];+ prev[0] = 0;+ let mut q = std::collections::VecDeque::from([0usize]);+ while let Some(u) = q.pop_front() {+ for v in 0..n {+ if prev[v] == usize::MAX && cap[u][v] > 1e-9 {+ prev[v] = u;+ q.push_back(v);+ }+ }+ }+ if prev[n - 1] == usize::MAX {+ return flow;+ }+ let mut b = f64::MAX;+ let mut v = n - 1;+ while v != 0 {+ b = b.min(cap[prev[v]][v]);+ v = prev[v];+ }+ let mut v = n - 1;+ while v != 0 {+ cap[prev[v]][v] -= b;+ cap[v][prev[v]] += b;+ v = prev[v];+ }+ flow += b;+ }+}++#[test]+fn maxflow_matches_reference_on_random_graphs() {+ let mut rng = Rng::new(7);+ for trial in 0..60 {+ let n = 3 + (trial % 12);+ let mut g = Graph::with_capacity(n, n * 3);+ let mut cap = vec![vec![0.0f64; n + 2]; n + 2];+ let mut edges = Vec::new();+ for i in 0..n {+ let (s, t) = ((rng.f32() * 10.0).round(), (rng.f32() * 10.0).round());+ let (s, t) = (if rng.f32() < 0.4 { 0.0 } else { s }, if rng.f32() < 0.4 { 0.0 } else { t });+ g.add_tweights(i, s, t);+ cap[0][i + 1] += s as f64;+ cap[i + 1][n + 1] += t as f64;+ }+ for i in 0..n {+ for j in i + 1..n {+ if rng.f32() < 0.35 {+ let (a, b) = ((rng.f32() * 8.0).round(), (rng.f32() * 8.0).round());+ g.add_edge(i, j, a, b);+ cap[i + 1][j + 1] += a as f64;+ cap[j + 1][i + 1] += b as f64;+ edges.push((i, j, a, b));+ }+ }+ }+ let orig = cap.clone();+ let reference = edmonds_karp(&mut cap);+ let f = g.maxflow();+ assert!((f - reference).abs() < 1e-3, "trial {trial}: {f} vs {reference}");+ // The reported cut has exactly that capacity.+ let side = |i: usize| g.in_source(i);+ let mut cut = 0.0;+ for i in 0..n {+ if side(i) {+ cut += orig[i + 1][n + 1];+ } else {+ cut += orig[0][i + 1];+ }+ }+ for &(i, j, a, b) in &edges {+ if side(i) && !side(j) {+ cut += a as f64;+ }+ if side(j) && !side(i) {+ cut += b as f64;+ }+ }+ assert!((cut - reference).abs() < 1e-3, "trial {trial}: cut {cut} vs flow {reference}");+ }+}++#[test]+fn grid_cut_separates_two_halves() {+ let img = RgbImage::from_fn(20, 10, |x, _| if x < 10 { [0.9, 0.1, 0.1] } else { [0.1, 0.1, 0.9] });+ let n = img.w * img.h;+ let mut fixed = vec![FREE; n];+ fixed[5 * 20 + 1] = HARD_FG;+ fixed[5 * 20 + 18] = HARD_BG;+ let zeros = vec![0.0; n];+ let beta = contrast_beta(&img);+ let cut = grid_cut(&img, &zeros, &zeros, &fixed, 50.0, beta);+ for y in 0..10 {+ for x in 0..20 {+ assert_eq!(cut[y * 20 + x], x < 10, "({x},{y})");+ }+ }+}++// ---------- GMM ----------++#[test]+fn gmm_recovers_synthetic_clusters() {+ let mut rng = Rng::new(3);+ let truth = [([0.2f32, 0.3, 0.8], 0.03f32, 0.5f32), ([0.8, 0.2, 0.1], 0.05, 0.3), ([0.5, 0.9, 0.4], 0.02, 0.2)];+ let mut samples = Vec::new();+ for (mean, sd, w) in truth {+ for _ in 0..(w * 6000.0) as usize {+ samples.push(mean.map(|m| m + sd * rng.normal()));+ }+ }+ let g = Gmm::fit(&samples, 3, gmm::DEFAULT_REG).unwrap();+ assert_eq!(g.comps.len(), 3);+ for (mean, sd, w) in truth {+ let c = g.comps.iter().min_by(|a, b| d2(a.mean, mean).total_cmp(&d2(b.mean, mean))).unwrap();+ assert!(d2(c.mean, mean).sqrt() < 0.01, "{:?} vs {mean:?}", c.mean);+ assert!((c.weight - w).abs() < 0.03, "{} vs {w}", c.weight);+ let var = c.cov[0][0];+ assert!((var.sqrt() - sd).abs() < 0.01, "sd {} vs {sd}", var.sqrt());+ }+ assert!(g.neg_log([0.2, 0.3, 0.8]) < g.neg_log([0.5, 0.5, 0.5]));+ // Refit keeps the model stable.+ let r = g.refit(&samples).unwrap();+ assert_eq!(r.comps.len(), 3);+}++// ---------- SLIC ----------++#[test]+fn slic_counts_compactness_and_edges() {+ let mut rng = Rng::new(11);+ let (w, h) = (120usize, 120usize);+ let img = RgbImage::from_fn(w, h, |x, _| if x < 60 { [0.8, 0.3, 0.2] } else { [0.2, 0.5, 0.8] });+ let img = RgbImage { px: img.px.iter().map(|p| p.map(|v| (v + 0.02 * rng.normal()).clamp(0.0, 1.0))).collect(), ..img };+ let sp = slic::slic(&img, 64, 10.0, 10);+ assert!((40..=90).contains(&sp.count), "count {}", sp.count);+ let mut bbox = vec![(usize::MAX, usize::MAX, 0usize, 0usize); sp.count];+ let mut left = vec![0usize; sp.count];+ let mut total = vec![0usize; sp.count];+ for y in 0..h {+ for x in 0..w {+ let l = sp.labels[y * w + x] as usize;+ let b = &mut bbox[l];+ *b = (b.0.min(x), b.1.min(y), b.2.max(x), b.3.max(y));+ total[l] += 1;+ if x < 60 {+ left[l] += 1;+ }+ }+ }+ let s = sp.step;+ for (l, b) in bbox.iter().enumerate() {+ assert!(total[l] > 0);+ assert!(((b.2 - b.0 + 1) as f32) <= 3.0 * s && ((b.3 - b.1 + 1) as f32) <= 3.0 * s, "superpixel {l} too elongated: {b:?} (S={s})");+ // Superpixels respect the strong colour edge.+ let purity = left[l].max(total[l] - left[l]) as f32 / total[l] as f32;+ assert!(purity > 0.95, "superpixel {l} straddles the edge ({purity})");+ }+}++// ---------- GrabCut / object selection ----------++/// A textured disc on a noisy background: (image, ground-truth mask).+pub(crate) fn disc_scene(w: usize, h: usize, cx: f32, cy: f32, r: f32, seed: u64) -> (RgbImage, Vec<bool>) {+ let mut rng = Rng::new(seed);+ let mut img = RgbImage::new(w, h);+ let mut truth = vec![false; w * h];+ for y in 0..h {+ for x in 0..w {+ let (dx, dy) = (x as f32 + 0.5 - cx, y as f32 + 0.5 - cy);+ let inside = dx * dx + dy * dy <= r * r;+ truth[y * w + x] = inside;+ let n = 0.05 * rng.normal();+ img.px[y * w + x] = if inside {+ // Stripes between two warm colours plus noise.+ let t = (((x + y) as f32 * 0.35).sin() * 0.5 + 0.5).clamp(0.0, 1.0);+ [0.85 + 0.05 * t + n, 0.2 + 0.3 * t + n, 0.15 + n]+ } else {+ [0.25 + n, 0.45 + n, 0.7 + n]+ }+ .map(|v| v.clamp(0.0, 1.0));+ }+ }+ (img, truth)+}++pub(crate) fn iou(region: &Region, truth: &[bool], w: usize, h: usize) -> f32 {+ let (mut inter, mut uni) = (0usize, 0usize);+ for y in 0..h {+ for x in 0..w {+ let a = region.at(x as i32, y as i32) >= 0.5;+ let b = truth[y * w + x];+ inter += (a && b) as usize;+ uni += (a || b) as usize;+ }+ }+ inter as f32 / uni.max(1) as f32+}++#[test]+fn grabcut_trimap_on_disc() {+ let (img, truth) = disc_scene(120, 100, 60.0, 50.0, 30.0, 1);+ let mut tri = vec![grabcut::BG; img.w * img.h];+ for y in 12..88 {+ for x in 22..98 {+ tri[y * img.w + x] = grabcut::PR_FG;+ }+ }+ grabcut::grabcut(&img, &mut tri, 8).unwrap();+ let (mut inter, mut uni) = (0, 0);+ for (t, g) in tri.iter().zip(&truth) {+ let a = *t == grabcut::PR_FG || *t == grabcut::FG;+ inter += (a && *g) as usize;+ uni += (a || *g) as usize;+ }+ let iou = inter as f32 / uni as f32;+ assert!(iou > 0.95, "IoU {iou}");+}++#[test]+fn object_select_disc_full_resolution() {+ let (img, truth) = disc_scene(200, 160, 100.0, 80.0, 50.0, 2);+ let s = ImageSampler { img: &img, origin: (0, 0) };+ let canvas = Rect::new(0, 0, 200, 160);+ let reg = grabcut::object_select(&s, canvas, Rect::new(40, 20, 160, 140), 1_000_000).unwrap();+ let v = iou(®, &truth, 200, 160);+ assert!(v > 0.95, "IoU {v}");+}++#[test]+fn object_select_downsampled_with_band_refinement() {+ let (img, truth) = disc_scene(640, 480, 330.0, 250.0, 150.0, 3);+ let s = ImageSampler { img: &img, origin: (0, 0) };+ let canvas = Rect::new(0, 0, 640, 480);+ // A small working budget forces step > 1 and the full-resolution band re-cut.+ let reg = grabcut::object_select(&s, canvas, Rect::new(160, 80, 500, 420), 20_000).unwrap();+ let v = iou(®, &truth, 640, 480);+ assert!(v > 0.95, "IoU {v}");+ // Boundary accuracy: few pixels wrong far (> 2 px) from the true edge.+ let mut far_wrong = 0;+ for y in 0..480 {+ for x in 0..640 {+ let (dx, dy) = (x as f32 + 0.5 - 330.0, y as f32 + 0.5 - 250.0);+ let d = (dx * dx + dy * dy).sqrt() - 150.0;+ if d.abs() > 2.0 && (reg.at(x, y) >= 0.5) != truth[y as usize * 640 + x as usize] {+ far_wrong += 1;+ }+ }+ }+ assert!(far_wrong < 300, "{far_wrong} pixels wrong away from the edge");+}++// ---------- Quick selection ----------++/// Left: textured warm region; right: cool region; strong vertical edge at x = 60.+fn two_regions(w: usize, h: usize) -> RgbImage {+ let mut rng = Rng::new(5);+ RgbImage::from_fn(w, h, |x, y| {+ let n = 0.04 * rng.normal();+ let t = ((x as f32 * 0.5).sin() * (y as f32 * 0.3).cos()) * 0.05;+ if x < 60 { [0.8 + t + n, 0.5 + n, 0.3 + t] } else { [0.2 + n, 0.35 + t, 0.6 + n] }.map(|v| v.clamp(0.0, 1.0))+ })+}++#[test]+fn quick_select_grows_without_leaking() {+ let img = two_regions(140, 100);+ let s = ImageSampler { img: &img, origin: (0, 0) };+ let canvas = Rect::new(0, 0, 140, 100);+ let reg = quick::quick_select(&s, canvas, &[(20.0, 50.0), (35.0, 50.0)], 8.0, quick::WORK_PX).unwrap();+ let mut inside = 0;+ for y in 0..100 {+ for x in 0..140 {+ let v = reg.at(x, y);+ if x >= 62 {+ assert!(v < 0.5, "leaked across the edge at ({x},{y}): {v}");+ }+ if x < 58 && v >= 0.5 {+ inside += 1;+ }+ }+ }+ // Grew over (nearly) the whole left region, far beyond the stroke.+ assert!(inside as f32 > 0.97 * (58.0 * 100.0), "only {inside} pixels selected");+}++#[test]+fn quick_select_stops_at_thin_line() {+ // Same colour on both sides of a dark 2-pixel line.+ let mut rng = Rng::new(9);+ let img = RgbImage::from_fn(120, 80, |x, _| {+ let n = 0.03 * rng.normal();+ if x == 60 || x == 61 { [0.05, 0.05, 0.05] } else { [0.6 + n, 0.6 + n, 0.55 + n] }+ });+ let s = ImageSampler { img: &img, origin: (0, 0) };+ let reg = quick::quick_select(&s, Rect::new(0, 0, 120, 80), &[(30.0, 40.0)], 6.0, quick::WORK_PX).unwrap();+ assert!(reg.at(10, 10) >= 0.5 && reg.at(50, 70) >= 0.5);+ for y in 0..80 {+ for x in 63..120 {+ assert!(reg.at(x, y) < 0.5, "crossed the line at ({x},{y})");+ }+ }+}++#[test]+fn quick_select_downsampled_window() {+ // A larger image with a small working budget: step > 1 plus band refinement.+ let (img, truth) = disc_scene(600, 500, 300.0, 250.0, 180.0, 4);+ let s = ImageSampler { img: &img, origin: (0, 0) };+ let reg = quick::quick_select(&s, Rect::new(0, 0, 600, 500), &[(260.0, 250.0), (340.0, 250.0)], 30.0, 15_000).unwrap();+ let v = iou(®, &truth, 600, 500);+ assert!(v > 0.93, "IoU {v}");+}++// ---------- Select subject ----------++#[test]+fn select_subject_finds_centred_object() {+ let (img, truth) = disc_scene(200, 150, 100.0, 75.0, 40.0, 6);+ let s = ImageSampler { img: &img, origin: (0, 0) };+ let reg = subject::select_subject(&s, Rect::new(0, 0, 200, 150)).unwrap();+ let v = iou(®, &truth, 200, 150);+ assert!(v > 0.9, "IoU {v}");+}++#[test]+fn saliency_highlights_the_object() {+ let (img, truth) = disc_scene(120, 90, 60.0, 45.0, 22.0, 8);+ let sal = subject::saliency(&img);+ let (mut fi, mut fn_, mut bi, mut bn) = (0.0, 0.0, 0.0, 0.0);+ for (s, t) in sal.iter().zip(&truth) {+ if *t {+ fi += s;+ fn_ += 1.0;+ } else {+ bi += s;+ bn += 1.0;+ }+ }+ assert!(fi / fn_ > 0.6 && bi / bn < 0.25, "fg {} bg {}", fi / fn_, bi / bn);+}++// ---------- Focus area ----------++#[test]+fn focus_area_selects_sharp_half() {+ let mut rng = Rng::new(12);+ let (w, h) = (160usize, 100usize);+ let noise: Vec<f32> = (0..w * h).map(|_| rng.f32()).collect();+ // Right half: heavily blurred copy of the texture.+ let blurred = crate::matting::box_mean(&noise, w, h, 4);+ let img = RgbImage::from_fn(w, h, |x, y| {+ let v = if x < 80 { noise[y * w + x] } else { blurred[y * w + x] };+ [v, v * 0.8, 0.3]+ });+ let s = ImageSampler { img: &img, origin: (0, 0) };+ let reg = focus::focus_area(&s, Rect::new(0, 0, w as i32, h as i32), 0.5, 0.0).unwrap();+ let (mut l, mut r) = (0usize, 0usize);+ for y in 0..h as i32 {+ for x in 0..w as i32 {+ if reg.at(x, y) >= 0.5 {+ if x < 80 { l += 1 } else { r += 1 }+ }+ }+ }+ assert!(l as f32 > 0.85 * 80.0 * h as f32, "sharp half {l}");+ assert!((r as f32) < 0.1 * 80.0 * h as f32, "blurred half {r}");+}++// ---------- helpers ----------++#[test]+fn sampler_downsampling_matches_image_downsample() {+ let img = RgbImage::from_fn(37, 29, |x, y| [x as f32 / 37.0, y as f32 / 29.0, ((x * y) % 7) as f32 / 7.0]);+ let s = ImageSampler { img: &img, origin: (5, 3) };+ let a = s.rgb_scaled(Rect::new(5, 3, 42, 32), 4);+ let b = img.downsample(4);+ assert_eq!((a.w, a.h), (b.w, b.h));+ for (p, q) in a.px.iter().zip(&b.px) {+ for c in 0..3 {+ assert!((p[c] - q[c]).abs() < 1e-5);+ }+ }+}++#[test]+fn clean_mask_drops_islands_and_fills_holes() {+ let (w, h) = (40, 40);+ let mut m = vec![false; w * h];+ for y in 5..30 {+ for x in 5..30 {+ m[y * w + x] = true;+ }+ }+ m[15 * w + 15] = false; // hole+ m[36 * w + 36] = true; // island+ let c = clean_mask(&m, w, h, 0.1, 0.05);+ assert!(c[15 * w + 15]);+ assert!(!c[36 * w + 36]);+}++#[test]+fn geodesic_distance_jumps_across_edges() {+ let img = two_regions(140, 100);+ let seeds = quick::stroke_mask(&[(20.0, 50.0)], 4.0, 140, 100);+ let d = quick::geodesic(&img, &seeds);+ assert!(d[50 * 140 + 40] < 0.02, "same region {}", d[50 * 140 + 40]);+ assert!(d[50 * 140 + 100] > 0.1, "across the edge {}", d[50 * 140 + 100]);+}++#[test]+fn geodesic_barrier_blocks_oblique_crossings() {+ // A large disc whose slightly tilted edge crosses the image: paths running along the soft+ // edge must not sneak across it.+ let (img, truth) = disc_scene(352, 372, -470.0, 186.0, 668.0, 4);+ let seeds = quick::stroke_mask(&[(175.0, 176.0), (175.0, 196.0)], 5.0, 352, 372);+ assert!(seeds.iter().zip(&truth).all(|(s, t)| !*s || *t));+ let d = quick::geodesic(&img, &seeds);+ assert!(d[186 * 352 + 100] < 0.02);+ for y in (0..372).step_by(31) {+ assert!(d[y * 352 + 291] > 0.1, "row {y}: {}", d[y * 352 + 291]);+ }+}diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rsnew file mode 100644index 000000000..8ae5a4c43--- /dev/null+++ b/crates/algo/src/selection.rs@@ -0,0 +1,728 @@+//! Selection algorithms on coverage masks (`w × h` row-major `f32` in+//! `0..=1` over an area): magic wand / flood regions, colour range,+//! modify (expand, contract, border, smooth, feather), anti-aliased lasso,+//! and combining with an existing selection.++use photocraft_color::PixelFormat;+use photocraft_geom::Rect;+use photocraft_raster::Surface;+use serde::{Deserialize, Serialize};++/// How a new selection combines with the current one.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum SelectionMode {+ #[default]+ Replace,+ Add,+ Subtract,+ Intersect,+}++impl SelectionMode {+ /// Parses `replace|add|subtract|intersect` (unknown → replace).+ pub fn parse(s: &str) -> Self {+ match s {+ "add" => SelectionMode::Add,+ "subtract" => SelectionMode::Subtract,+ "intersect" => SelectionMode::Intersect,+ _ => SelectionMode::Replace,+ }+ }+}++/// Reads a selection surface over `area` (no selection → all zero).+pub fn mask_from_surface(s: Option<&Surface>, area: Rect) -> Vec<f32> {+ let n = area.width() as usize * area.height() as usize;+ match s {+ None => vec![0.0; n],+ Some(s) => {+ let mut v = Vec::new();+ s.read_region_into(area, &mut v);+ let ch = s.channels();+ if ch > 1 { v.chunks_exact(ch).map(|p| p[0]).collect() } else { v }+ }+ }+}++/// Builds a GRAY8 selection surface from a mask over `area`.+pub fn mask_to_surface(m: &[f32], area: Rect) -> Surface {+ let mut s = Surface::new(PixelFormat::GRAY8);+ if !area.is_empty() {+ s.write_region(area, m);+ }+ s.prune();+ s+}++/// Combines `new` with `old` by `mode`. Returns `None` when nothing is selected.+pub fn combine(old: Option<&Surface>, new: &[f32], area: Rect, mode: SelectionMode) -> Option<Surface> {+ let prev = mask_from_surface(old, area);+ // Quantize to the 8-bit grid selections are stored on, so combining a+ // mask with itself is exact.+ let q: Vec<f32> = new.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0).collect();+ let new = &q[..];+ let out: Vec<f32> = match mode {+ SelectionMode::Replace => new.to_vec(),+ SelectionMode::Add => prev.iter().zip(new).map(|(a, b)| a.max(*b)).collect(),+ SelectionMode::Subtract => prev.iter().zip(new).map(|(a, b)| (a - b).max(0.0)).collect(),+ SelectionMode::Intersect => prev.iter().zip(new).map(|(a, b)| a.min(*b)).collect(),+ };+ // Below half an 8-bit step is nothing (selections are stored as 8-bit).+ let out: Vec<f32> = out.into_iter().map(|v| if v < 0.5 / 255.0 { 0.0 } else { v }).collect();+ if out.iter().all(|v| *v <= 0.0) {+ return None;+ }+ Some(mask_to_surface(&out, area))+}++fn close(a: [f32; 4], b: [f32; 4], tol: f32) -> bool {+ (0..4).all(|c| (a[c] - b[c]).abs() * 255.0 <= tol + 1e-3)+}++/// Pixels similar to the seed pixel (per-channel difference ≤ `tolerance`+/// levels, alpha included). `contiguous` limits to the 4-connected region+/// around the seed. `px` covers `area`.+pub fn magic_wand(px: &[[f32; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Vec<f32> {+ let (w, h) = (area.width() as usize, area.height() as usize);+ let mut m = vec![0.0f32; w * h];+ if !area.contains(seed.0, seed.1) {+ return m;+ }+ let si = (seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize;+ let target = px[si];+ if contiguous {+ let mut stack = vec![si];+ m[si] = 1.0;+ while let Some(i) = stack.pop() {+ let (x, y) = (i % w, i / w);+ let mut visit = |j: usize| {+ if m[j] == 0.0 && close(px[j], target, tolerance) {+ m[j] = 1.0;+ stack.push(j);+ }+ };+ if x > 0 {+ visit(i - 1);+ }+ if x + 1 < w {+ visit(i + 1);+ }+ if y > 0 {+ visit(i - w);+ }+ if y + 1 < h {+ visit(i + w);+ }+ }+ } else {+ for (v, p) in m.iter_mut().zip(px) {+ if close(*p, target, tolerance) {+ *v = 1.0;+ }+ }+ }+ if anti_alias {+ antialias(&mut m, w, h);+ }+ m+}++/// Straight RGBA8 copy of `area` of a surface, read in parallel bands on native.+pub fn rgba8_image(s: &Surface, area: Rect) -> Vec<[u8; 4]> {+ let (w, h) = (area.width() as usize, area.height() as usize);+ let mut img = vec![[0u8; 4]; w * h];+ if w == 0 || h == 0 {+ return img;+ }+ let band = 256usize;+ let read = |bi: usize, chunk: &mut [[u8; 4]]| {+ let y0 = area.y0 + (bi * band) as i32;+ s.read_rgba8_into(Rect::new(area.x0, y0, area.x1, y0 + (chunk.len() / w) as i32), chunk);+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ img.par_chunks_mut(w * band).enumerate().for_each(|(bi, c)| read(bi, c));+ }+ #[cfg(target_arch = "wasm32")]+ img.chunks_mut(w * band).enumerate().for_each(|(bi, c)| read(bi, c));+ img+}++/// A selected region: 8-bit coverage over `bbox` (row-major), the bounding box of the pixels+/// touched (including the anti-aliased fringe).+#[derive(Clone, Debug, PartialEq)]+pub struct Region {+ pub bbox: Rect,+ pub mask: Vec<u8>,+}++impl Region {+ /// Coverage (0–1) at document pixel `(x, y)`; zero outside the box.+ pub fn at(&self, x: i32, y: i32) -> f32 {+ if !self.bbox.contains(x, y) {+ return 0.0;+ }+ self.mask[(y - self.bbox.y0) as usize * self.bbox.width() as usize + (x - self.bbox.x0) as usize] as f32 / 255.0+ }+}++/// Magic wand on 8-bit pixels: a scanline flood fill (or a global match) that only allocates a+/// byte mark per pixel, then anti-aliases just the edges inside the touched bounding box.+/// Matches [`magic_wand`] for 8-bit sources. `None` if the seed is outside `area`.+pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option<Region> {+ if !area.contains(seed.0, seed.1) {+ return None;+ }+ let (w, h) = (area.width() as usize, area.height() as usize);+ let target = img[(seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize];+ let tol = (tolerance + 1e-3).floor().max(0.0) as i32;+ let similar = |p: [u8; 4]| (0..4).all(|c| (p[c] as i32 - target[c] as i32).abs() <= tol);+ let mut marks = vec![0u8; w * h];+ let (mut bx0, mut by0, mut bx1, mut by1) = (usize::MAX, usize::MAX, 0usize, 0usize);+ if contiguous {+ // Span fill: fill a run, then scan the rows above and below it for new seeds.+ let mut stack = vec![((seed.0 - area.x0) as usize, (seed.1 - area.y0) as usize)];+ while let Some((x, y)) = stack.pop() {+ let row = y * w;+ if marks[row + x] != 0 {+ continue;+ }+ let (mut l, mut r) = (x, x);+ while l > 0 && marks[row + l - 1] == 0 && similar(img[row + l - 1]) {+ l -= 1;+ }+ while r + 1 < w && marks[row + r + 1] == 0 && similar(img[row + r + 1]) {+ r += 1;+ }+ marks[row + l..=row + r].fill(255);+ (bx0, bx1, by0, by1) = (bx0.min(l), bx1.max(r), by0.min(y), by1.max(y));+ for ny in [y.wrapping_sub(1), y + 1] {+ if ny >= h {+ continue;+ }+ let nrow = ny * w;+ let mut in_run = false;+ for nx in l..=r {+ let ok = marks[nrow + nx] == 0 && similar(img[nrow + nx]);+ if ok && !in_run {+ stack.push((nx, ny));+ }+ in_run = ok;+ }+ }+ }+ } else {+ let scan = |y: usize, row: &mut [u8]| -> Option<(usize, usize)> {+ let mut span: Option<(usize, usize)> = None;+ for (x, m) in row.iter_mut().enumerate() {+ if similar(img[y * w + x]) {+ *m = 255;+ span = Some(span.map_or((x, x), |(a, _)| (a, x)));+ }+ }+ span+ };+ #[cfg(not(target_arch = "wasm32"))]+ let spans: Vec<Option<(usize, usize)>> = {+ use rayon::prelude::*;+ marks.par_chunks_mut(w).enumerate().map(|(y, row)| scan(y, row)).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let spans: Vec<Option<(usize, usize)>> = marks.chunks_mut(w).enumerate().map(|(y, row)| scan(y, row)).collect();+ for (y, sp) in spans.iter().enumerate() {+ if let Some((a, b)) = sp {+ (bx0, bx1, by0, by1) = (bx0.min(*a), bx1.max(*b), by0.min(y), by1.max(y));+ }+ }+ }+ if bx0 == usize::MAX {+ return None;+ }+ // One pixel of fringe for anti-aliasing, clamped to the area.+ let pad = anti_alias as usize;+ let (x0, y0) = (bx0.saturating_sub(pad), by0.saturating_sub(pad));+ let (x1, y1) = ((bx1 + 1 + pad).min(w), (by1 + 1 + pad).min(h));+ let bw = x1 - x0;+ let at = |x: usize, y: usize| marks[y * w + x];+ let mut mask = vec![0u8; bw * (y1 - y0)];+ let fill_row = |yy: usize, out: &mut [u8]| {+ let y = y0 + yy;+ for (xx, o) in out.iter_mut().enumerate() {+ let x = x0 + xx;+ let v = at(x, y);+ *o = v;+ if !anti_alias {+ continue;+ }+ // Same rule as `antialias`: edge pixels blend with their 3×3 neighbourhood; neighbours+ // outside the area count as the pixel itself.+ let mut sum = 0u32;+ let mut edge = false;+ for dy in -1i32..=1 {+ for dx in -1i32..=1 {+ let (nx, ny) = (x as i32 + dx, y as i32 + dy);+ let n = if nx < 0 || ny < 0 || nx >= w as i32 || ny >= h as i32 { v } else { at(nx as usize, ny as usize) };+ edge |= n != v;+ sum += n as u32;+ }+ }+ if edge {+ let avg = sum as f32 / (9.0 * 255.0);+ let f = if v > 127 { 0.5 + 0.5 * avg } else { 0.5 * avg };+ *o = (f * 255.0).round() as u8;+ }+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ mask.par_chunks_mut(bw).enumerate().for_each(|(yy, row)| fill_row(yy, row));+ }+ #[cfg(target_arch = "wasm32")]+ mask.chunks_mut(bw).enumerate().for_each(|(yy, row)| fill_row(yy, row));+ let bbox = Rect::new(area.x0 + x0 as i32, area.y0 + y0 as i32, area.x0 + x1 as i32, area.y0 + y1 as i32);+ Some(Region { bbox, mask })+}++/// Combines a [`Region`] with the current selection, touching only the region's box (outside it+/// the new mask is zero). Returns `None` when nothing remains selected.+pub fn combine_region(old: Option<&Surface>, new: Option<&Region>, mode: SelectionMode) -> Option<Surface> {+ let empty = Region { bbox: Rect::EMPTY, mask: Vec::new() };+ let new = new.unwrap_or(&empty);+ let b = new.bbox;+ let prev_u8 = |s: &Surface| -> Vec<u8> {+ let mut v = Vec::new();+ s.read_region_into(b, &mut v);+ let ch = s.channels();+ v.chunks_exact(ch).map(|p| (p[0].clamp(0.0, 1.0) * 255.0).round() as u8).collect()+ };+ let from_bytes = |bytes: &[u8]| -> Option<Surface> {+ if b.is_empty() || bytes.iter().all(|v| *v == 0) {+ return None;+ }+ let mut s = Surface::from_interleaved(PixelFormat::GRAY8, b, bytes);+ s.prune();+ Some(s)+ };+ let nonempty = |s: Surface| -> Option<Surface> { (!s.content_bounds().is_empty()).then_some(s) };+ match (mode, old) {+ (SelectionMode::Replace, _) | (SelectionMode::Add, None) => from_bytes(&new.mask),+ (SelectionMode::Subtract | SelectionMode::Intersect, None) => None,+ (SelectionMode::Intersect, Some(o)) => {+ let p = prev_u8(o);+ from_bytes(&p.iter().zip(&new.mask).map(|(a, b)| *a.min(b)).collect::<Vec<_>>())+ }+ (SelectionMode::Add | SelectionMode::Subtract, Some(o)) => {+ if b.is_empty() {+ return nonempty(o.clone());+ }+ let p = prev_u8(o);+ let out: Vec<f32> = p+ .iter()+ .zip(&new.mask)+ .map(|(a, n)| if mode == SelectionMode::Add { *a.max(n) } else { a.saturating_sub(*n) } as f32 / 255.0)+ .collect();+ let mut s = o.clone();+ s.write_region(b, &out);+ s.prune();+ nonempty(s)+ }+ }+}++/// Softens hard mask edges: edge pixels become the 3×3 average.+fn antialias(m: &mut [f32], w: usize, h: usize) {+ let src = m.to_vec();+ for y in 0..h {+ for x in 0..w {+ let i = y * w + x;+ let mut sum = 0.0;+ let mut cnt = 0.0;+ let mut edge = false;+ for dy in -1i32..=1 {+ for dx in -1i32..=1 {+ let (xx, yy) = (x as i32 + dx, y as i32 + dy);+ let v = if xx < 0 || yy < 0 || xx >= w as i32 || yy >= h as i32 { src[i] } else { src[yy as usize * w + xx as usize] };+ edge |= v != src[i];+ sum += v;+ cnt += 1.0;+ }+ }+ if edge {+ // Keep selected pixels mostly selected, add a soft fringe.+ m[i] = if src[i] > 0.5 { 0.5 + 0.5 * sum / cnt } else { 0.5 * sum / cnt };+ }+ }+ }+}++/// Colour Range: coverage falls off linearly with the per-channel colour+/// distance; `fuzziness` in levels (0–200).+pub fn color_range(px: &[[f32; 4]], color: [f32; 3], fuzziness: f32) -> Vec<f32> {+ let f = fuzziness.max(0.0) + 1.0;+ px.iter()+ .map(|p| {+ if p[3] <= 0.0 {+ return 0.0;+ }+ let d = (0..3).map(|c| (p[c] - color[c]).abs() * 255.0).fold(0.0f32, f32::max);+ (1.0 - d / f).clamp(0.0, 1.0)+ })+ .collect()+}++/// 1D squared distance transform (Felzenszwalb & Huttenlocher).+fn dt1(f: &[f32], out: &mut [f32], v: &mut [usize], z: &mut [f32]) {+ let n = f.len();+ let mut k = 0usize;+ v[0] = 0;+ z[0] = f32::NEG_INFINITY;+ z[1] = f32::INFINITY;+ for q in 1..n {+ loop {+ let p = v[k];+ let s = ((f[q] + (q * q) as f32) - (f[p] + (p * p) as f32)) / (2.0 * (q as f32 - p as f32));+ if s <= z[k] && k > 0 {+ k -= 1;+ continue;+ }+ if s <= z[k] {+ v[0] = q;+ z[0] = f32::NEG_INFINITY;+ z[1] = f32::INFINITY;+ break;+ }+ k += 1;+ v[k] = q;+ z[k] = s;+ z[k + 1] = f32::INFINITY;+ break;+ }+ }+ k = 0;+ for (q, o) in out.iter_mut().enumerate() {+ while z[k + 1] < q as f32 {+ k += 1;+ }+ let d = q as f32 - v[k] as f32;+ *o = d * d + f[v[k]];+ }+}++/// Euclidean distance to the nearest `true` pixel.+pub fn edt(inside: &[bool], w: usize, h: usize) -> Vec<f32> {+ let mut g: Vec<f32> = inside.iter().map(|&b| if b { 0.0 } else { 1e20 }).collect();+ let n = w.max(h).max(1);+ let (mut f, mut o, mut v, mut z) = (vec![0.0; n], vec![0.0; n], vec![0usize; n], vec![0.0f32; n + 1]);+ for x in 0..w {+ for y in 0..h {+ f[y] = g[y * w + x];+ }+ dt1(&f[..h], &mut o[..h], &mut v, &mut z);+ for y in 0..h {+ g[y * w + x] = o[y];+ }+ }+ for y in 0..h {+ f[..w].copy_from_slice(&g[y * w..(y + 1) * w]);+ dt1(&f[..w], &mut o[..w], &mut v, &mut z);+ for x in 0..w {+ g[y * w + x] = o[x].sqrt();+ }+ }+ g+}++/// Grows the selection by `r` pixels.+pub fn expand(m: &[f32], w: usize, h: usize, r: f32) -> Vec<f32> {+ let inside: Vec<bool> = m.iter().map(|v| *v >= 0.5).collect();+ let d = edt(&inside, w, h);+ // A pixel whose centre is `d` away from the nearest selected centre is+ // covered when d ≤ r (fractional radii give partial coverage).+ m.iter().zip(d).map(|(v, d)| v.max((r + 1.0 - d).clamp(0.0, 1.0))).collect()+}++/// Shrinks the selection by `r` pixels.+pub fn contract(m: &[f32], w: usize, h: usize, r: f32) -> Vec<f32> {+ let inv: Vec<f32> = m.iter().map(|v| 1.0 - v).collect();+ expand(&inv, w, h, r).into_iter().map(|v| 1.0 - v).collect()+}++/// A band of width `r` straddling the selection edge.+pub fn border(m: &[f32], w: usize, h: usize, r: f32) -> Vec<f32> {+ let outer = expand(m, w, h, r / 2.0);+ let inner = contract(m, w, h, r / 2.0);+ outer.iter().zip(inner).map(|(o, i)| (o - i).max(0.0)).collect()+}++fn box_blur(m: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {+ if r == 0 {+ return m.to_vec();+ }+ let mut tmp = vec![0.0f32; m.len()];+ let win = (2 * r + 1) as f32;+ for y in 0..h {+ for x in 0..w {+ let mut s = 0.0;+ for k in x as i64 - r as i64..=x as i64 + r as i64 {+ s += m[y * w + k.clamp(0, w as i64 - 1) as usize];+ }+ tmp[y * w + x] = s / win;+ }+ }+ let mut out = vec![0.0f32; m.len()];+ for y in 0..h {+ for x in 0..w {+ let mut s = 0.0;+ for k in y as i64 - r as i64..=y as i64 + r as i64 {+ s += tmp[k.clamp(0, h as i64 - 1) as usize * w + x];+ }+ out[y * w + x] = s / win;+ }+ }+ out+}++/// Smooth: removes specks and rounds corners (box average, then re-threshold).+pub fn smooth(m: &[f32], w: usize, h: usize, r: f32) -> Vec<f32> {+ box_blur(m, w, h, r.max(0.0).round() as usize).into_iter().map(|v| ((v - 0.5) * 4.0 + 0.5).clamp(0.0, 1.0)).collect()+}++/// Feather: Gaussian blur of the mask with sigma = radius / 2.+pub fn feather(m: &[f32], w: usize, h: usize, radius: f32) -> Vec<f32> {+ let sigma = radius.max(0.0) / 2.0;+ if sigma < 0.1 {+ return m.to_vec();+ }+ let r = (sigma * 3.0).ceil() as i64;+ let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();+ let s: f32 = k.iter().sum();+ let k: Vec<f32> = k.iter().map(|v| v / s).collect();+ let mut tmp = vec![0.0f32; m.len()];+ for y in 0..h {+ for x in 0..w {+ let mut a = 0.0;+ for (i, kv) in k.iter().enumerate() {+ let xx = x as i64 + i as i64 - r;+ if xx >= 0 && xx < w as i64 {+ a += m[y * w + xx as usize] * kv;+ }+ }+ tmp[y * w + x] = a;+ }+ }+ let mut out = vec![0.0f32; m.len()];+ for y in 0..h {+ for x in 0..w {+ let mut a = 0.0;+ for (i, kv) in k.iter().enumerate() {+ let yy = y as i64 + i as i64 - r;+ if yy >= 0 && yy < h as i64 {+ a += tmp[yy as usize * w + x] * kv;+ }+ }+ out[y * w + x] = a;+ }+ }+ out+}++/// Anti-aliased polygon (even-odd) coverage over `area`: exact horizontal+/// coverage, 4 sub-rows per pixel row (or 1 when not anti-aliased).+pub fn polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec<f32> {+ let (w, h) = (area.width() as usize, area.height() as usize);+ let mut m = vec![0.0f32; w * h];+ if points.len() < 3 {+ return m;+ }+ let sub = if anti_alias { 4 } else { 1 };+ let mut xs: Vec<f32> = Vec::new();+ for py in 0..h {+ for s in 0..sub {+ let y = area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32;+ xs.clear();+ for i in 0..points.len() {+ let (a, b) = (points[i], points[(i + 1) % points.len()]);+ if (a.1 <= y && b.1 > y) || (b.1 <= y && a.1 > y) {+ xs.push(a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0));+ }+ }+ xs.sort_by(|a, b| a.total_cmp(b));+ for span in xs.chunks_exact(2) {+ let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32));+ if x1 <= x0 {+ continue;+ }+ let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w));+ for cx in c0..c1 {+ let cov = if anti_alias { ((cx + 1) as f32).min(x1) - (cx as f32).max(x0) } else {+ let c = cx as f32 + 0.5;+ if c >= x0 && c < x1 { 1.0 } else { 0.0 }+ };+ m[py * w + cx] += cov.max(0.0) / sub as f32;+ }+ }+ }+ }+ for v in &mut m {+ *v = v.min(1.0);+ }+ m+}++#[cfg(test)]+mod tests {+ use super::*;++ fn img(w: usize, h: usize, f: impl Fn(usize, usize) -> [f32; 4]) -> Vec<[f32; 4]> {+ (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| f(x, y)).collect()+ }++ #[test]+ fn wand_contiguous_vs_global() {+ // Two separate red squares on white.+ let px = img(20, 10, |x, _| if (2..6).contains(&x) || (12..16).contains(&x) { [1.0, 0.0, 0.0, 1.0] } else { [1.0; 4] });+ let a = Rect::new(0, 0, 20, 10);+ let c = magic_wand(&px, a, (3, 3), 10.0, true, false);+ assert_eq!(c.iter().filter(|v| **v > 0.0).count(), 40);+ let g = magic_wand(&px, a, (3, 3), 10.0, false, false);+ assert_eq!(g.iter().filter(|v| **v > 0.0).count(), 80);+ let aa = magic_wand(&px, a, (3, 3), 10.0, true, true);+ assert!(aa[3 * 20 + 6] > 0.0 && aa[3 * 20 + 6] < 1.0);+ assert!(magic_wand(&px, a, (50, 3), 10.0, true, false).iter().all(|v| *v == 0.0));+ }++ #[test]+ fn wand_tolerance() {+ let px = img(10, 1, |x, _| [x as f32 * 10.0 / 255.0, 0.0, 0.0, 1.0]);+ let m = magic_wand(&px, Rect::new(0, 0, 10, 1), (0, 0), 25.0, true, false);+ assert_eq!(m.iter().filter(|v| **v > 0.0).count(), 3);+ }++ #[test]+ fn color_range_falloff() {+ let px = vec![[1.0, 0.0, 0.0, 1.0], [0.9, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.0]];+ let m = color_range(&px, [1.0, 0.0, 0.0], 40.0);+ assert_eq!(m[0], 1.0);+ assert!(m[1] > 0.3 && m[1] < 1.0);+ assert_eq!(m[2], 0.0);+ assert_eq!(m[3], 0.0);+ }++ fn square(w: usize, h: usize) -> Vec<f32> {+ (0..w * h).map(|i| if (5..15).contains(&(i % w)) && (5..15).contains(&(i / w)) { 1.0 } else { 0.0 }).collect()+ }++ #[test]+ fn expand_contract_border() {+ let m = square(20, 20);+ let e = expand(&m, 20, 20, 2.0);+ assert_eq!(e[10 * 20 + 3], 1.0);+ assert_eq!(e[10 * 20 + 2], 0.0);+ let c = contract(&m, 20, 20, 2.0);+ assert_eq!(c[10 * 20 + 6], 0.0);+ assert_eq!(c[10 * 20 + 7], 1.0);+ let b = border(&m, 20, 20, 4.0);+ assert_eq!(b[10 * 20 + 10], 0.0);+ assert!(b[10 * 20 + 5] > 0.5 && b[10 * 20 + 4] > 0.5);+ }++ #[test]+ fn smooth_removes_specks_and_feather_softens() {+ let mut m = square(20, 20);+ m[2 * 20 + 2] = 1.0;+ let s = smooth(&m, 20, 20, 1.0);+ assert_eq!(s[2 * 20 + 2], 0.0);+ assert_eq!(s[10 * 20 + 10], 1.0);+ let f = feather(&square(20, 20), 20, 20, 4.0);+ let edge = f[10 * 20 + 5];+ assert!(edge > 0.3 && edge < 0.8, "{edge}");+ let sum: f32 = f.iter().sum();+ assert!((sum - 100.0).abs() < 1.0);+ }++ #[test]+ fn polygon_area_and_aa() {+ let a = Rect::new(0, 0, 20, 20);+ let sq = polygon(&[(2.0, 2.0), (12.0, 2.0), (12.0, 12.0), (2.0, 12.0)], a, true);+ let area: f32 = sq.iter().sum();+ assert!((area - 100.0).abs() < 1e-3, "{area}");+ let tri = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, true);+ let area: f32 = tri.iter().sum();+ assert!((area - 50.0).abs() < 1.0, "{area}");+ assert!(tri.iter().any(|v| *v > 0.0 && *v < 1.0));+ let hard = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, false);+ assert!(hard.iter().all(|v| *v == 0.0 || *v == 1.0));+ assert!(polygon(&[(0.0, 0.0), (1.0, 1.0)], a, true).iter().all(|v| *v == 0.0));+ }++ #[test]+ fn combine_modes() {+ let a = Rect::new(0, 0, 4, 1);+ let old = mask_to_surface(&[1.0, 1.0, 0.0, 0.0], a);+ let new = [0.0, 1.0, 1.0, 0.0];+ let v = |s: Option<Surface>| mask_from_surface(s.as_ref(), a);+ assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Replace)), vec![0.0, 1.0, 1.0, 0.0]);+ assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Add)), vec![1.0, 1.0, 1.0, 0.0]);+ assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Subtract)), vec![1.0, 0.0, 0.0, 0.0]);+ assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Intersect)), vec![0.0, 1.0, 0.0, 0.0]);+ assert!(combine(Some(&old), &[1.0; 4], a, SelectionMode::Subtract).is_none());+ assert_eq!(SelectionMode::parse("add"), SelectionMode::Add);+ }++ fn blobs(w: i32, h: i32) -> Vec<[u8; 4]> {+ // Deterministic blotchy image with gradients and hard edges.+ (0..w * h)+ .map(|i| {+ let (x, y) = (i % w, i / w);+ let v = ((x * 7 + y * 3) % 23 + if (x / 5 + y / 4) % 3 == 0 { 120 } else { 0 }) as u8;+ [v, v / 2, 255 - v, if x % 11 == 0 { 128 } else { 255 }]+ })+ .collect()+ }++ #[test]+ fn wand_region_matches_reference_magic_wand() {+ let (w, h) = (37, 29);+ let area = Rect::new(3, -2, 3 + w, -2 + h);+ let img = blobs(w, h);+ let f: Vec<[f32; 4]> = img.iter().map(|p| p.map(|v| v as f32 / 255.0)).collect();+ for (seed, tol, contiguous, aa) in [((10, 5), 10.0, true, true), ((10, 5), 10.0, true, false), ((20, 20), 40.0, false, true), ((4, -2), 0.0, true, true), ((30, 10), 255.0, true, true)] {+ let reference = magic_wand(&f, area, seed, tol, contiguous, aa);+ let r = wand_region(&img, area, seed, tol, contiguous, aa).unwrap();+ for y in area.y0..area.y1 {+ for x in area.x0..area.x1 {+ let want = (reference[((y - area.y0) * w + x - area.x0) as usize] * 255.0).round();+ assert!((r.at(x, y) * 255.0 - want).abs() <= 1.0, "{seed:?} {tol} {contiguous} {aa} at {x},{y}: {} vs {want}", r.at(x, y) * 255.0);+ }+ }+ }+ assert!(wand_region(&img, area, (0, 0), 10.0, true, true).is_none());+ }++ #[test]+ fn combine_region_matches_combine() {+ let area = Rect::new(0, 0, 40, 30);+ let mut old = Surface::new(PixelFormat::GRAY8);+ old.fill_rect(Rect::new(5, 5, 25, 20), &[1.0]);+ old.fill_rect(Rect::new(8, 8, 10, 10), &[0.4]);+ let img = blobs(40, 30);+ let region = wand_region(&img, area, (12, 12), 30.0, true, true).unwrap();+ let full: Vec<f32> = (0..area.height()).flat_map(|y| (0..area.width()).map(move |x| (x, y))).map(|(x, y)| region.at(x as i32, y as i32)).collect();+ for mode in [SelectionMode::Replace, SelectionMode::Add, SelectionMode::Subtract, SelectionMode::Intersect] {+ let a = combine(Some(&old), &full, area, mode);+ let b = combine_region(Some(&old), Some(®ion), mode);+ assert_eq!(a.is_some(), b.is_some(), "{mode:?}");+ if let (Some(a), Some(b)) = (a, b) {+ for y in 0..30 {+ for x in 0..40 {+ assert!((a.pixel(x, y)[0] - b.pixel(x, y)[0]).abs() < 1.5 / 255.0, "{mode:?} {x},{y}");+ }+ }+ }+ }+ assert!(combine_region(None, None, SelectionMode::Subtract).is_none());+ }+}diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rsnew file mode 100644index 000000000..d3bb5c1c3--- /dev/null+++ b/crates/algo/src/transform.rs@@ -0,0 +1,355 @@+//! Free Transform: projective warps of surfaces.+//!+//! A transform is described by where the four corners of a source rectangle land (a quad). Scale,+//! rotate, skew and flips are affine special cases; Distort and Perspective use the full+//! homography. Warping is an inverse mapping with premultiplied-alpha sampling (nearest, bilinear+//! or Catmull-Rom bicubic), processed per destination tile (in parallel on native) so memory stays+//! bounded by the tile working set. Large reductions are pre-filtered with a proper resize first,+//! so shrinking a layer doesn't alias.++use photocraft_color::PixelFormat;+use photocraft_geom::Rect;+use photocraft_raster::Surface;+use serde::{Deserialize, Serialize};++use crate::resample::{Resample, resize_surface};++/// 3×3 projective matrix, row-major: `[x', y', w'] = H · [x, y, 1]`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Homography(pub [f64; 9]);++impl Homography {+ pub const IDENTITY: Homography = Homography([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);++ pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {+ let m = &self.0;+ let w = m[6] * x + m[7] * y + m[8];+ ((m[0] * x + m[1] * y + m[2]) / w, (m[3] * x + m[4] * y + m[5]) / w)+ }++ pub fn mul(&self, o: &Homography) -> Homography {+ let (a, b) = (&self.0, &o.0);+ let mut r = [0.0; 9];+ for i in 0..3 {+ for j in 0..3 {+ r[i * 3 + j] = (0..3).map(|k| a[i * 3 + k] * b[k * 3 + j]).sum();+ }+ }+ Homography(r)+ }++ pub fn inverse(&self) -> Option<Homography> {+ let m = &self.0;+ let c = [+ m[4] * m[8] - m[5] * m[7],+ m[2] * m[7] - m[1] * m[8],+ m[1] * m[5] - m[2] * m[4],+ m[5] * m[6] - m[3] * m[8],+ m[0] * m[8] - m[2] * m[6],+ m[2] * m[3] - m[0] * m[5],+ m[3] * m[7] - m[4] * m[6],+ m[1] * m[6] - m[0] * m[7],+ m[0] * m[4] - m[1] * m[3],+ ];+ let det = m[0] * c[0] + m[1] * c[3] + m[2] * c[6];+ if det.abs() < 1e-12 {+ return None;+ }+ Some(Homography(c.map(|v| v / det)))+ }++ /// Unit square → quad (corners in order: (0,0), (1,0), (1,1), (0,1)).+ fn square_to_quad(q: [[f64; 2]; 4]) -> Option<Homography> {+ let [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = q;+ let (sx, sy) = (x0 - x1 + x2 - x3, y0 - y1 + y2 - y3);+ if sx.abs() < 1e-12 && sy.abs() < 1e-12 {+ // Affine.+ return Some(Homography([x1 - x0, x3 - x0, x0, y1 - y0, y3 - y0, y0, 0.0, 0.0, 1.0]));+ }+ let (dx1, dx2, dy1, dy2) = (x1 - x2, x3 - x2, y1 - y2, y3 - y2);+ let den = dx1 * dy2 - dx2 * dy1;+ if den.abs() < 1e-12 {+ return None;+ }+ let g = (sx * dy2 - dx2 * sy) / den;+ let h = (dx1 * sy - sx * dy1) / den;+ Some(Homography([x1 - x0 + g * x1, x3 - x0 + h * x3, x0, y1 - y0 + g * y1, y3 - y0 + h * y3, y0, g, h, 1.0]))+ }++ /// The transform taking rectangle `r` (x0, y0, x1, y1) onto `quad` (corners clockwise from+ /// top-left). `None` for degenerate quads.+ pub fn rect_to_quad(r: [f64; 4], quad: [[f64; 2]; 4]) -> Option<Homography> {+ let (w, h) = (r[2] - r[0], r[3] - r[1]);+ if w <= 0.0 || h <= 0.0 {+ return None;+ }+ let to_unit = Homography([1.0 / w, 0.0, -r[0] / w, 0.0, 1.0 / h, -r[1] / h, 0.0, 0.0, 1.0]);+ Some(Self::square_to_quad(quad)?.mul(&to_unit))+ }++ /// Approximate linear scale of the mapping near `(x, y)` (sqrt of the Jacobian determinant).+ pub fn local_scale(&self, x: f64, y: f64) -> f64 {+ let e = 0.5;+ let (a, b) = (self.apply(x - e, y), self.apply(x + e, y));+ let (c, d) = (self.apply(x, y - e), self.apply(x, y + e));+ let (jx, jy) = ((b.0 - a.0, b.1 - a.1), (d.0 - c.0, d.1 - c.1));+ (jx.0 * jy.1 - jx.1 * jy.0).abs().sqrt()+ }+}++/// Resampling used by transforms (Photoshop's interpolation menu).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum Interp {+ Nearest,+ Bilinear,+ #[default]+ Bicubic,+}++impl Interp {+ pub fn parse(s: &str) -> Self {+ match s {+ "nearest" | "nearestNeighbor" => Interp::Nearest,+ "bilinear" => Interp::Bilinear,+ _ => Interp::Bicubic,+ }+ }+}++fn catmull_rom(t: f64) -> [f64; 4] {+ let t2 = t * t;+ let t3 = t2 * t;+ [+ -0.5 * t3 + t2 - 0.5 * t,+ 1.5 * t3 - 2.5 * t2 + 1.0,+ -1.5 * t3 + 2.0 * t2 + 0.5 * t,+ 0.5 * t3 - 0.5 * t2,+ ]+}++/// Warp `src` (its content inside `src_rect`) by `h` (source → destination document space).+/// The result has the same format as `src`, with alpha added if `src` had none; pixels outside+/// the warped quad are transparent.+pub fn warp_surface(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp) -> Surface {+ let mut fmt = src.format();+ let converted;+ let mut src = if fmt.alpha {+ src+ } else {+ fmt = PixelFormat::new(fmt.mode, fmt.sample, true);+ converted = src.convert(fmt);+ &converted+ };+ let mut out = Surface::new(fmt);+ if src_rect.is_empty() {+ return out;+ }+ let mut h = *h;+ let mut src_rect = src_rect;+ // Pre-reduce for large downscales (bicubic alone aliases below ~50%).+ let (cx, cy) = ((src_rect.x0 + src_rect.x1) as f64 / 2.0, (src_rect.y0 + src_rect.y1) as f64 / 2.0);+ let scale = h.local_scale(cx, cy);+ let reduced;+ if interp != Interp::Nearest && scale < 0.5 && scale > 0.0 {+ let f = 2f64.powf(scale.log2().ceil()).min(1.0); // remaining scale lands in [0.5, 1)+ reduced = resize_surface(src, f, f, Resample::Bicubic);+ src = &reduced;+ h = h.mul(&Homography([1.0 / f, 0.0, 0.0, 0.0, 1.0 / f, 0.0, 0.0, 0.0, 1.0]));+ src_rect = crate::resample::scaled_rect(src_rect, f, f);+ }+ let Some(inv) = h.inverse() else { return out };+ // Destination bounds: the warped corners (plus a pixel for filter support).+ let corners = [(src_rect.x0, src_rect.y0), (src_rect.x1, src_rect.y0), (src_rect.x1, src_rect.y1), (src_rect.x0, src_rect.y1)].map(|(x, y)| h.apply(x as f64, y as f64));+ if corners.iter().any(|c| !c.0.is_finite() || !c.1.is_finite()) {+ return out;+ }+ let lim = 1 << 20;+ let bx0 = corners.iter().map(|c| c.0).fold(f64::MAX, f64::min).floor().max(-(lim as f64)) as i32 - 1;+ let by0 = corners.iter().map(|c| c.1).fold(f64::MAX, f64::min).floor().max(-(lim as f64)) as i32 - 1;+ let bx1 = corners.iter().map(|c| c.0).fold(f64::MIN, f64::max).ceil().min(lim as f64) as i32 + 1;+ let by1 = corners.iter().map(|c| c.1).fold(f64::MIN, f64::max).ceil().min(lim as f64) as i32 + 1;+ let dst = Rect::new(bx0, by0, bx1, by1);+ let n = fmt.channels();+ let a = n - 1;+ let tiles: Vec<Rect> = dst.tiles().map(|tc| tc.rect().intersect(&dst)).filter(|r| !r.is_empty()).collect();+ let src_ref: &Surface = src;+ let work = |t: &Rect| -> Option<(Rect, Vec<f32>)> {+ // Source footprint of this tile (inverse-mapped corners), padded for the filter.+ let tc = [(t.x0, t.y0), (t.x1, t.y0), (t.x1, t.y1), (t.x0, t.y1)].map(|(x, y)| inv.apply(x as f64, y as f64));+ let fx0 = tc.iter().map(|c| c.0).fold(f64::MAX, f64::min).floor() as i32 - 3;+ let fy0 = tc.iter().map(|c| c.1).fold(f64::MAX, f64::min).floor() as i32 - 3;+ let fx1 = tc.iter().map(|c| c.0).fold(f64::MIN, f64::max).ceil() as i32 + 3;+ let fy1 = tc.iter().map(|c| c.1).fold(f64::MIN, f64::max).ceil() as i32 + 3;+ let foot = Rect::new(fx0, fy0, fx1, fy1).intersect(&src_rect);+ if foot.is_empty() || !src_ref.has_tiles_in(foot) {+ return None;+ }+ // Premultiplied source window.+ let mut px = src_ref.read_region(foot);+ for p in px.chunks_exact_mut(n) {+ let al = p[a];+ for v in &mut p[..a] {+ *v *= al;+ }+ }+ let fw = foot.width() as usize;+ let at = |x: i32, y: i32, c: usize| -> f64 {+ if x < foot.x0 || y < foot.y0 || x >= foot.x1 || y >= foot.y1 {+ 0.0+ } else {+ px[((y - foot.y0) as usize * fw + (x - foot.x0) as usize) * n + c] as f64+ }+ };+ let w = t.width() as usize;+ let mut outp = vec![0.0f32; w * t.height() as usize * n];+ let mut any = false;+ let mut acc = [0.0f64; 8];+ for y in t.y0..t.y1 {+ for x in t.x0..t.x1 {+ let (u, v) = inv.apply(x as f64 + 0.5, y as f64 + 0.5);+ let (u, v) = (u - 0.5, v - 0.5);+ if u < src_rect.x0 as f64 - 1.0 || v < src_rect.y0 as f64 - 1.0 || u > src_rect.x1 as f64 || v > src_rect.y1 as f64 {+ continue;+ }+ acc[..n].fill(0.0);+ match interp {+ Interp::Nearest => {+ let (ix, iy) = ((u + 0.5).floor() as i32, (v + 0.5).floor() as i32);+ for (c, s) in acc.iter_mut().enumerate().take(n) {+ *s = at(ix, iy, c);+ }+ }+ Interp::Bilinear => {+ let (ix, iy) = (u.floor() as i32, v.floor() as i32);+ let (fx, fy) = (u - ix as f64, v - iy as f64);+ for (dy, wy) in [(0, 1.0 - fy), (1, fy)] {+ for (dx, wx) in [(0, 1.0 - fx), (1, fx)] {+ for (c, s) in acc.iter_mut().enumerate().take(n) {+ *s += at(ix + dx, iy + dy, c) * wx * wy;+ }+ }+ }+ }+ Interp::Bicubic => {+ let (ix, iy) = (u.floor() as i32, v.floor() as i32);+ let (wx, wy) = (catmull_rom(u - ix as f64), catmull_rom(v - iy as f64));+ for (j, wyj) in wy.iter().enumerate() {+ for (i, wxi) in wx.iter().enumerate() {+ let k = wxi * wyj;+ for (c, s) in acc.iter_mut().enumerate().take(n) {+ *s += at(ix - 1 + i as i32, iy - 1 + j as i32, c) * k;+ }+ }+ }+ }+ }+ let al = acc[a].clamp(0.0, 1.0);+ if al <= 0.0 {+ continue;+ }+ any = true;+ let o = ((y - t.y0) as usize * w + (x - t.x0) as usize) * n;+ for c in 0..a {+ outp[o + c] = (acc[c] / al).clamp(0.0, 1.0) as f32;+ }+ outp[o + a] = al as f32;+ }+ }+ any.then_some((*t, outp))+ };+ #[cfg(not(target_arch = "wasm32"))]+ let done: Vec<(Rect, Vec<f32>)> = {+ use rayon::prelude::*;+ tiles.par_iter().filter_map(work).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let done: Vec<(Rect, Vec<f32>)> = tiles.iter().filter_map(work).collect();+ for (r, v) in done {+ out.write_region(r, &v);+ }+ out.prune();+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rgba() -> Surface {+ Surface::new(PixelFormat::RGBA8)+ }++ #[test]+ fn homography_maps_rect_corners_and_inverts() {+ let r = [10.0, 20.0, 110.0, 70.0];+ let q = [[0.0, 0.0], [200.0, 10.0], [180.0, 150.0], [-20.0, 120.0]];+ let h = Homography::rect_to_quad(r, q).unwrap();+ for (p, e) in [(10.0, 20.0), (110.0, 20.0), (110.0, 70.0), (10.0, 70.0)].iter().zip(q) {+ let (x, y) = h.apply(p.0, p.1);+ assert!((x - e[0]).abs() < 1e-9 && (y - e[1]).abs() < 1e-9, "{p:?} → {x},{y} vs {e:?}");+ }+ let inv = h.inverse().unwrap();+ let (x, y) = inv.apply(90.0, 60.0);+ let (bx, by) = h.apply(x, y);+ assert!((bx - 90.0).abs() < 1e-9 && (by - 60.0).abs() < 1e-9);+ assert!(Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).is_none() || Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).unwrap().inverse().is_none());+ }++ #[test]+ fn identity_and_translation_are_exact() {+ let mut s = rgba();+ s.fill_rect(Rect::new(4, 4, 20, 12), &[1.0, 0.5, 0.0, 1.0]);+ let r = s.content_bounds();+ for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] {+ let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]);+ let o = warp_surface(&s, r, &h, interp);+ assert_eq!(o.content_bounds(), Rect::new(11, 1, 27, 9), "{interp:?}");+ assert_eq!(o.pixel(15, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0], "{interp:?}");+ }+ }++ #[test]+ fn scale_doubles_size_and_rotation_keeps_area() {+ let mut s = rgba();+ s.fill_rect(Rect::new(0, 0, 40, 20), &[0.2, 0.4, 0.6, 1.0]);+ let r = s.content_bounds();+ let up = warp_surface(&s, r, &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], [[0.0, 0.0], [80.0, 0.0], [80.0, 40.0], [0.0, 40.0]]).unwrap(), Interp::Bicubic);+ let b = up.content_bounds();+ assert!(b.width() >= 80 && b.width() <= 82 && b.height() >= 40 && b.height() <= 42, "{b:?}");+ // 90° rotation about (20, 10): a 40×20 box becomes 20×40.+ let q = [[30.0, -10.0], [30.0, 30.0], [10.0, 30.0], [10.0, -10.0]];+ let rot = warp_surface(&s, r, &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], q).unwrap(), Interp::Bilinear);+ let b = rot.content_bounds();+ assert!(b.width().abs_diff(20) <= 2 && b.height().abs_diff(40) <= 2, "{b:?}");+ let p = rot.pixel(20, 10);+ assert!((p[0] - 0.2).abs() < 0.01 && p[3] > 0.99, "{p:?}");+ }++ #[test]+ fn large_downscale_is_prefiltered() {+ // A 1px checkerboard shrunk 8× must come out ~50% grey, not aliased black/white.+ let mut s = rgba();+ for y in 0..64 {+ for x in 0..64 {+ let v = ((x + y) % 2) as f32;+ s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]);+ }+ }+ let h = Homography::rect_to_quad([0.0, 0.0, 64.0, 64.0], [[0.0, 0.0], [8.0, 0.0], [8.0, 8.0], [0.0, 8.0]]).unwrap();+ let o = warp_surface(&s, s.content_bounds(), &h, Interp::Bicubic);+ let p = o.pixel(4, 4);+ assert!((p[0] - 0.5).abs() < 0.1, "{p:?}");+ }++ #[test]+ fn surfaces_without_alpha_gain_it() {+ let mut s = Surface::new(PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, false));+ s.fill_rect(Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0]);+ let h = Homography([1.0, 0.0, 5.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);+ let o = warp_surface(&s, Rect::new(0, 0, 10, 10), &h, Interp::Nearest);+ assert!(o.format().alpha);+ assert_eq!(o.pixel(2, 2)[3], 0.0);+ assert_eq!(o.pixel(7, 2), vec![1.0, 0.0, 0.0, 1.0]);+ }+}diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.tomlnew file mode 100644index 000000000..cdb23bd41--- /dev/null+++ b/crates/automation/Cargo.toml@@ -0,0 +1,30 @@+[package]+name = "photocraft-automation"+description = "MCP server (rmcp) over the Photocraft engine, plus a bridge to a running GUI"+version.workspace = true+edition.workspace = true+license.workspace = true+rust-version.workspace = true++[lints]+workspace = true++[dependencies]+photocraft-geom = { workspace = true }+photocraft-doc = { workspace = true }+photocraft-compose = { workspace = true }+photocraft-codecs = { workspace = true }+photocraft-io = { workspace = true }+photocraft-format = { path = "../format" }+photocraft-engine = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+thiserror = { workspace = true }+rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] }+tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }+base64 = "0.22"+schemars = "1"++[dev-dependencies]+rmcp = { version = "3.5", default-features = false, features = ["client", "server", "macros", "transport-io"] }+tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }diff --git a/crates/automation/src/bridge.rs b/crates/automation/src/bridge.rsnew file mode 100644index 000000000..e11b137aa--- /dev/null+++ b/crates/automation/src/bridge.rs@@ -0,0 +1,137 @@+//! Client for the desktop app's JSON-lines control protocol+//! (`docs/control-protocol.md`): one JSON request per line, replies matched+//! by `id`. Keeps one connection and reconnects on failure.++use std::sync::atomic::{AtomicU64, Ordering};+use std::time::Duration;++use serde_json::{Value, json};+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};+use tokio::net::TcpStream;+use tokio::sync::Mutex;++use crate::AutomationError;++type Conn = (+ BufReader<tokio::net::tcp::OwnedReadHalf>,+ tokio::net::tcp::OwnedWriteHalf,+);++pub struct BridgeClient {+ addr: String,+ conn: Mutex<Option<Conn>>,+ next_id: AtomicU64,+ timeout: Duration,+}++impl BridgeClient {+ /// `addr` such as `127.0.0.1:7878`. Only loopback addresses are accepted,+ /// matching the server, which binds to loopback only.+ pub fn new(addr: impl Into<String>) -> Result<Self, AutomationError> {+ let addr = addr.into();+ let host = addr.rsplit_once(':').map(|(h, _)| h).unwrap_or(&addr);+ if !matches!(host, "127.0.0.1" | "localhost" | "[::1]" | "::1") {+ return Err(AutomationError::BadRequest(format!(+ "bridge address must be loopback, got `{addr}`"+ )));+ }+ Ok(BridgeClient {+ addr,+ conn: Mutex::new(None),+ next_id: AtomicU64::new(1),+ timeout: Duration::from_secs(60),+ })+ }++ pub fn with_timeout(mut self, t: Duration) -> Self {+ self.timeout = t;+ self+ }++ pub fn addr(&self) -> &str {+ &self.addr+ }++ /// Call a control method; returns its `result` or the app's error.+ pub async fn call(&self, method: &str, params: Value) -> Result<Value, AutomationError> {+ let mut guard = self.conn.lock().await;+ // One retry with a fresh connection (the app may have restarted).+ for attempt in 0..2 {+ if guard.is_none() {+ let s = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(&self.addr))+ .await+ .map_err(|_| AutomationError::Bridge(format!("timed out connecting to {}", self.addr)))?+ .map_err(|e| {+ AutomationError::Bridge(format!(+ "cannot connect to {} ({e}); start the app with `photocraft --control <port>`",+ self.addr+ ))+ })?;+ let (r, w) = s.into_split();+ *guard = Some((BufReader::new(r), w));+ }+ let id = self.next_id.fetch_add(1, Ordering::Relaxed);+ let conn = guard.as_mut().expect("connected");+ match tokio::time::timeout(self.timeout, exchange(conn, id, method, ¶ms)).await {+ Ok(Ok(v)) => return v,+ Ok(Err(e)) if attempt == 0 => {+ *guard = None;+ let _ = e;+ }+ Ok(Err(e)) => {+ *guard = None;+ return Err(e);+ }+ Err(_) => {+ *guard = None;+ return Err(AutomationError::Bridge(format!(+ "`{method}` timed out after {:?}",+ self.timeout+ )));+ }+ }+ }+ Err(AutomationError::Bridge("unreachable".into()))+ }+}++/// Outer `Err` = transport failure (retryable); inner = app-level result.+async fn exchange(+ conn: &mut Conn,+ id: u64,+ method: &str,+ params: &Value,+) -> Result<Result<Value, AutomationError>, AutomationError> {+ let mut line = serde_json::to_string(&json!({"id": id, "method": method, "params": params}))+ .map_err(|e| AutomationError::Other(e.to_string()))?;+ line.push('\n');+ let io = |e: std::io::Error| AutomationError::Bridge(e.to_string());+ conn.1.write_all(line.as_bytes()).await.map_err(io)?;+ conn.1.flush().await.map_err(io)?;+ let mut buf = String::new();+ loop {+ buf.clear();+ let n = conn.0.read_line(&mut buf).await.map_err(io)?;+ if n == 0 {+ return Err(AutomationError::Bridge(+ "connection closed by the app".into(),+ ));+ }+ let Ok(v) = serde_json::from_str::<Value>(buf.trim()) else {+ continue;+ };+ if v.get("id").and_then(Value::as_u64) != Some(id) {+ continue; // stale reply from an earlier, timed-out request+ }+ return Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {+ Ok(v.get("result").cloned().unwrap_or(Value::Null))+ } else {+ Err(AutomationError::App(+ v.get("error")+ .and_then(Value::as_str)+ .unwrap_or("unknown error")+ .to_owned(),+ ))+ });+ }+}diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rsnew file mode 100644index 000000000..75c83aaca--- /dev/null+++ b/crates/automation/src/files.rs@@ -0,0 +1,102 @@+//! File I/O shared by the MCP server and the CLI: open/save any supported+//! format, with `.pcraft` (ZIP or directory bundle) handled natively.++use std::path::Path;++use photocraft_doc::Document;+use photocraft_format::{PcraftWriter, SaveOptions};+use photocraft_io::ExportOptions;++use crate::AutomationError;++/// Result of opening a file.+pub struct Opened {+ pub document: Document,+ pub warnings: Vec<String>,+}++/// Open a document from disk. Directory bundles and `.pcraft` ZIPs load+/// natively; everything else goes through `photocraft-io` (PSD, PNG, …).+pub fn open(path: &Path) -> Result<Opened, AutomationError> {+ if path.is_dir() {+ return Ok(Opened {+ document: photocraft_format::load_path(path)?,+ warnings: Vec::new(),+ });+ }+ let bytes =+ std::fs::read(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;+ let name = path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ let r = photocraft_io::import(&name, &bytes)?;+ Ok(Opened {+ document: r.document,+ warnings: r.warnings,+ })+}++/// Previews for a `.pcraft` bundle.+pub fn previews(doc: &Document) -> SaveOptions {+ SaveOptions {+ thumbnail: Some(photocraft_compose::thumbnail(doc, 256)),+ composite: Some(photocraft_compose::thumbnail(doc, 1024)),+ }+}++/// Save or export `doc` to `path`, choosing the format from the extension+/// (or `format_override`, an extension such as `"png"`). `writer` makes+/// repeated `.pcraft` saves incremental. Returns warnings about lost data.+pub fn save(+ doc: &Document,+ path: &Path,+ format_override: Option<&str>,+ opts: &ExportOptions,+ writer: Option<&mut PcraftWriter>,+) -> Result<Vec<String>, AutomationError> {+ let ext = format_override+ .map(|f| f.trim_start_matches('.').to_ascii_lowercase())+ .or_else(|| {+ path.extension()+ .map(|e| e.to_string_lossy().to_ascii_lowercase())+ })+ .ok_or_else(|| {+ AutomationError::BadRequest(format!(+ "cannot tell the format of `{}`; pass a format",+ path.display()+ ))+ })?;+ if ext == photocraft_format::EXTENSION {+ let mut local = PcraftWriter::new();+ let w = writer.unwrap_or(&mut local);+ w.save_path(doc, path, &previews(doc))?;+ return Ok(Vec::new());+ }+ let r = photocraft_io::export(doc, &ext, opts)?;+ if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {+ std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(e.to_string()))?;+ }+ std::fs::write(path, &r.bytes)+ .map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;+ Ok(r.warnings)+}++/// Flattened document as PNG, scaled to fit `max_side` (0 = full size).+pub fn render_png(doc: &Document, max_side: u32) -> Result<Vec<u8>, AutomationError> {+ let side = if max_side == 0 {+ doc.size.width.max(doc.size.height)+ } else {+ max_side+ };+ let img = photocraft_compose::thumbnail(doc, side.max(1));+ let image = photocraft_codecs::Image::from_u8(+ img.width,+ img.height,+ photocraft_codecs::ChannelLayout::Rgba,+ img.pixels,+ )+ .map_err(|e| AutomationError::Other(e.to_string()))?;+ photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default())+ .map_err(|e| AutomationError::Other(e.to_string()))+}diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rsnew file mode 100644index 000000000..5572b3edf--- /dev/null+++ b/crates/automation/src/headless.rs@@ -0,0 +1,157 @@+//! Headless backend: a `photocraft_engine::Session` plus file I/O. Synchronous+//! and UI-free; the MCP server and the CLI both drive it.++use std::collections::HashMap;+use std::path::{Path, PathBuf};++use photocraft_engine::{Session, command_specs};+use photocraft_format::PcraftWriter;+use photocraft_io::ExportOptions;+use serde_json::{Value, json};++use crate::{AutomationError, files};++/// A headless editing session.+#[derive(Default)]+pub struct Headless {+ pub session: Session,+ /// Incremental `.pcraft` writers per document id.+ writers: HashMap<u64, PcraftWriter>,+}++impl Headless {+ pub fn new() -> Self {+ Self::default()+ }++ fn doc_index(&self, index: Option<usize>) -> Result<usize, AutomationError> {+ match index {+ Some(i) if i < self.session.documents().len() => Ok(i),+ Some(i) => Err(AutomationError::BadRequest(format!(+ "no document at index {i}"+ ))),+ None => self+ .session+ .active_index()+ .ok_or_else(|| AutomationError::BadRequest("no document open".into())),+ }+ }++ /// Open a file and make it the active document.+ pub fn open(&mut self, path: &Path) -> Result<Value, AutomationError> {+ let o = files::open(path)?;+ let index = self+ .session+ .add_document(o.document, Some(path.to_string_lossy().into_owned()));+ let d = &self.session.documents()[index];+ Ok(json!({+ "index": index,+ "name": d.doc.name,+ "width": d.doc.size.width,+ "height": d.doc.size.height,+ "layers": d.doc.layer_count(),+ "warnings": o.warnings,+ }))+ }++ /// Save (`.pcraft` or any export format by extension). With no path,+ /// saves to the document's own path.+ pub fn save(+ &mut self,+ index: Option<usize>,+ path: Option<&Path>,+ format: Option<&str>,+ opts: &ExportOptions,+ ) -> Result<Value, AutomationError> {+ let i = self.doc_index(index)?;+ let st = &self.session.documents()[i];+ let target: PathBuf = match (path, &st.path) {+ (Some(p), _) => p.to_path_buf(),+ (None, Some(p)) => PathBuf::from(p),+ (None, None) => {+ return Err(AutomationError::BadRequest(+ "document has no path; pass `path`".into(),+ ));+ }+ };+ let doc = st.doc.clone();+ let writer = self.writers.entry(doc.id.0).or_default();+ let warnings = files::save(&doc, &target, format, opts, Some(writer))?;+ let is_native = format+ .map(|f| f.trim_start_matches('.').eq_ignore_ascii_case("pcraft"))+ .unwrap_or_else(|| {+ target+ .extension()+ .is_some_and(|e| e.eq_ignore_ascii_case("pcraft"))+ });+ if is_native {+ self.session.set_active(i);+ if let Some(st) = self.session.active_mut() {+ st.saved_revision = st.revision;+ st.path = Some(target.to_string_lossy().into_owned());+ }+ }+ Ok(json!({ "path": target.to_string_lossy(), "warnings": warnings }))+ }++ pub fn inspect(&self, index: Option<usize>) -> Result<Value, AutomationError> {+ let i = self.doc_index(index)?;+ Ok(photocraft_engine::inspect::document(+ &self.session.documents()[i],+ ))+ }++ pub fn render_png(+ &self,+ index: Option<usize>,+ max_side: u32,+ ) -> Result<Vec<u8>, AutomationError> {+ let i = self.doc_index(index)?;+ files::render_png(&self.session.documents()[i].doc, max_side)+ }++ pub fn session_list(&self) -> Value {+ photocraft_engine::inspect::session(&self.session)+ }++ pub fn select(&mut self, index: usize) -> Result<Value, AutomationError> {+ if self.session.set_active(index) {+ Ok(self.session_list())+ } else {+ Err(AutomationError::BadRequest(format!(+ "no document at index {index}"+ )))+ }+ }++ pub fn close(&mut self, index: Option<usize>) -> Result<Value, AutomationError> {+ let i = self.doc_index(index)?;+ if let Some(d) = self.session.close(i) {+ self.writers.remove(&d.doc.id.0);+ }+ Ok(self.session_list())+ }++ pub fn command_list(&self) -> Value {+ Value::Array(+ command_specs()+ .iter()+ .map(|c| {+ json!({+ "id": c.id,+ "label": c.label,+ "menu": c.menu,+ "shortcut": c.shortcut,+ "params": c.params,+ "enabled": self.session.is_enabled(c.id),+ })+ })+ .collect(),+ )+ }++ pub fn command_run(&mut self, id: &str, params: Value) -> Result<Value, AutomationError> {+ let params = if params.is_null() { json!({}) } else { params };+ Ok(self.session.execute(id, params)?)+ }+}diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rsnew file mode 100644index 000000000..ba0631b44--- /dev/null+++ b/crates/automation/src/lib.rs@@ -0,0 +1,43 @@+//! # photocraft-automation+//!+//! Agent-facing automation (architecture §12):+//!+//! * [`PhotocraftMcp`]: an MCP server (official `rmcp` SDK) exposing session,+//! document and command tools. Headless mode drives an in-process+//! [`photocraft_engine::Session`]; bridge mode forwards to a running desktop+//! app over the JSON-lines control protocol (`docs/control-protocol.md`), so+//! agents can also inspect, screenshot and click the live UI.+//! * [`Headless`]: the synchronous session + file I/O core, shared with the CLI.+//! * [`files`]: open/save any supported format, `.pcraft` natively.+//!+//! L6, no UI-toolkit dependencies.+#![forbid(unsafe_code)]++pub mod bridge;+pub mod files;+pub mod headless;+pub mod server;++pub use bridge::BridgeClient;+pub use headless::Headless;+pub use server::{Backend, PhotocraftMcp};++#[derive(Debug, thiserror::Error)]+pub enum AutomationError {+ #[error("{0}")]+ BadRequest(String),+ #[error("I/O: {0}")]+ Io(String),+ #[error(transparent)]+ Engine(#[from] photocraft_engine::EngineError),+ #[error(transparent)]+ Import(#[from] photocraft_io::IoError),+ #[error(transparent)]+ Format(#[from] photocraft_format::FormatError),+ #[error("bridge: {0}")]+ Bridge(String),+ #[error("app: {0}")]+ App(String),+ #[error("{0}")]+ Other(String),+}diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rsnew file mode 100644index 000000000..9cb40a103--- /dev/null+++ b/crates/automation/src/server.rs@@ -0,0 +1,627 @@+//! The MCP server (rmcp). Tool names use `snake_case` with underscores (dots+//! are not valid in every client's tool-name grammar).++use std::path::PathBuf;+use std::sync::{Arc, Mutex};++use base64::Engine as _;+use rmcp::handler::server::router::tool::ToolRouter;+use rmcp::handler::server::wrapper::Parameters;+use rmcp::model::{CallToolResult, ContentBlock as Content};+use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt, tool, tool_handler, tool_router};+use schemars::JsonSchema;+use serde::Deserialize;+use serde_json::{Value, json};++use crate::bridge::BridgeClient;+use crate::headless::Headless;+use crate::{AutomationError, files};++/// Where tools are executed.+pub enum Backend {+ /// In-process engine session.+ Headless(Arc<Mutex<Headless>>),+ /// A running desktop app reached over the control protocol.+ Bridge(Arc<BridgeClient>),+}++#[derive(Clone)]+pub struct PhotocraftMcp {+ backend: Arc<Backend>,+ tool_router: ToolRouter<Self>,+}++// ---------------------------------------------------------------------------+// Parameters+// ---------------------------------------------------------------------------++#[derive(Debug, Default, Deserialize, JsonSchema)]+pub struct DocIndex {+ /// Document index from `session_list` (default: the active document).+ #[serde(default)]+ pub index: Option<usize>,+}++#[derive(Debug, Deserialize, JsonSchema)]+pub struct OpenParams {+ /// Absolute path of the file to open (.pcraft, .psd, .png, .jpg, .tif, .exr, …).+ pub path: String,+}++#[derive(Debug, Default, Deserialize, JsonSchema)]+pub struct NewParams {+ #[serde(default)]+ pub width: Option<u32>,+ #[serde(default)]+ pub height: Option<u32>,+ /// rgb | gray | cmyk | lab+ #[serde(default)]+ pub mode: Option<String>,+ /// 8 | 16 | 32+ #[serde(default)]+ pub depth: Option<u32>,+ /// white | black | transparent | #rrggbb+ #[serde(default)]+ pub background: Option<String>,+ #[serde(default)]+ pub name: Option<String>,+}++#[derive(Debug, Default, Deserialize, JsonSchema)]+pub struct SaveParams {+ /// Target path; the extension selects the format. Omit to save to the document's own path.+ #[serde(default)]+ pub path: Option<String>,+ /// Format override as an extension (pcraft, psd, png, jpg, tif, webp, exr, …).+ #[serde(default)]+ pub format: Option<String>,+ /// JPEG quality 1..100 for lossy exports.+ #[serde(default)]+ pub quality: Option<u8>,+ #[serde(default)]+ pub index: Option<usize>,+}++#[derive(Debug, Default, Deserialize, JsonSchema)]+pub struct PreviewParams {+ #[serde(default)]+ pub index: Option<usize>,+ /// Longest side of the returned PNG in pixels (default 1024, 0 = full size).+ #[serde(default)]+ pub max_side: Option<u32>,+}++#[derive(Debug, Deserialize, JsonSchema)]+pub struct SelectParams {+ pub index: usize,+}++#[derive(Debug, Default, Deserialize, JsonSchema)]+pub struct ListParams {+ /// Only commands whose id or label contains this text (case-insensitive).+ #[serde(default)]+ pub filter: Option<String>,+ /// Only commands that can run right now.+ #[serde(default)]+ pub enabled_only: Option<bool>,+}++#[derive(Debug, Deserialize, JsonSchema)]+pub struct RunParams {+ /// Command id, e.g. `layer.new.layer`, `filter.blur.gaussian`.+ pub id: String,+ /// Command parameters as a JSON object (see the `params` doc in `command_list`).+ #[serde(default)]+ pub params: Option<Value>,+}++#[derive(Debug, Deserialize, JsonSchema)]+pub struct PointerParams {+ /// Events in document coordinates: `[{"kind":"down|move|up","x":..,"y":..,"pressure":..}]`.+ pub events: Vec<Value>,+ /// Modifier keys, e.g. `{"shift":true}`.+ #[serde(default)]+ pub modifiers: Option<Value>,+}++#[derive(Debug, Deserialize, JsonSchema)]+pub struct MenuParams {+ /// Menu item / command id.+ pub id: String,+}++#[derive(Debug, Deserialize, JsonSchema)]+pub struct UiSetParams {+ /// Fields accepted by the control method `ui.set` (tool, panels, zoom, center, dark).+ pub fields: Value,+}++#[derive(Debug, Deserialize, JsonSchema)]+pub struct ControlParams {+ /// Any control-protocol method, e.g. `ui.dialog.open`.+ pub method: String,+ #[serde(default)]+ pub params: Option<Value>,+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++fn ok_json(v: &Value) -> CallToolResult {+ CallToolResult::success(vec![Content::text(+ serde_json::to_string_pretty(v).unwrap_or_default(),+ )])+}++fn fail(e: impl std::fmt::Display) -> CallToolResult {+ CallToolResult::error(vec![Content::text(e.to_string())])+}++fn png_result(png: &[u8], note: String) -> CallToolResult {+ let b64 = base64::engine::general_purpose::STANDARD.encode(png);+ CallToolResult::success(vec![Content::image(b64, "image/png"), Content::text(note)])+}++fn to_result(r: Result<Value, AutomationError>) -> Result<CallToolResult, McpError> {+ Ok(match r {+ Ok(v) => ok_json(&v),+ Err(e) => fail(e),+ })+}++fn bridge_only(name: &str) -> Result<CallToolResult, McpError> {+ Ok(fail(format!(+ "`{name}` drives the live GUI and needs bridge mode: run `photocraft-cli mcp --bridge 127.0.0.1:<port>` \+ with the app started as `photocraft --control <port>`"+ )))+}++impl PhotocraftMcp {+ pub fn headless() -> Self {+ Self::with_backend(Backend::Headless(Arc::new(Mutex::new(Headless::new()))))+ }++ pub fn bridge(addr: &str) -> Result<Self, AutomationError> {+ Ok(Self::with_backend(Backend::Bridge(Arc::new(+ BridgeClient::new(addr)?,+ ))))+ }++ pub fn with_backend(backend: Backend) -> Self {+ PhotocraftMcp {+ backend: Arc::new(backend),+ tool_router: Self::tool_router(),+ }+ }++ /// Serve MCP over stdin/stdout until the client disconnects.+ pub async fn serve_stdio(self) -> Result<(), AutomationError> {+ let running = self+ .serve(rmcp::transport::stdio())+ .await+ .map_err(|e| AutomationError::Other(format!("MCP init: {e}")))?;+ running+ .waiting()+ .await+ .map_err(|e| AutomationError::Other(e.to_string()))?;+ Ok(())+ }++ /// Run `f` on the headless session on a blocking thread.+ async fn headless_op<T: Send + 'static>(+ &self,+ f: impl FnOnce(&mut Headless) -> Result<T, AutomationError> + Send + 'static,+ ) -> Option<Result<T, AutomationError>> {+ let Backend::Headless(h) = &*self.backend else {+ return None;+ };+ let h = h.clone();+ Some(+ tokio::task::spawn_blocking(move || {+ let mut g = h+ .lock()+ .map_err(|_| AutomationError::Other("session lock poisoned".into()))?;+ f(&mut g)+ })+ .await+ .unwrap_or_else(|e| Err(AutomationError::Other(format!("task failed: {e}")))),+ )+ }++ fn bridge_client(&self) -> Option<&BridgeClient> {+ match &*self.backend {+ Backend::Bridge(b) => Some(b),+ Backend::Headless(_) => None,+ }+ }++ async fn screenshot(+ &self,+ b: &BridgeClient,+ max_side: Option<u32>,+ ) -> Result<CallToolResult, McpError> {+ let path =+ std::env::temp_dir().join(format!("photocraft-mcp-shot-{}.png", std::process::id()));+ if let Err(e) = b+ .call("ui.screenshot", json!({"path": path.to_string_lossy()}))+ .await+ {+ return Ok(fail(e));+ }+ let bytes = match std::fs::read(&path) {+ Ok(b) => b,+ Err(e) => return Ok(fail(format!("screenshot file: {e}"))),+ };+ let _ = std::fs::remove_file(&path);+ let bytes = match max_side {+ Some(m) if m > 0 => downscale_png(&bytes, m).unwrap_or(bytes),+ _ => bytes,+ };+ Ok(png_result(+ &bytes,+ "screenshot of the live app window".into(),+ ))+ }+}++fn downscale_png(png: &[u8], max_side: u32) -> Option<Vec<u8>> {+ let img = photocraft_codecs::decode(png).ok()?;+ let (w, h) = img.dimensions();+ if w.max(h) <= max_side {+ return None;+ }+ let s = max_side as f32 / w.max(h) as f32;+ let (nw, nh) = (+ ((w as f32 * s) as u32).max(1),+ ((h as f32 * s) as u32).max(1),+ );+ let src = img.to_rgba8();+ let mut out = vec![0u8; (nw * nh * 4) as usize];+ for y in 0..nh {+ for x in 0..nw {+ let sx = ((x as f32 + 0.5) / s) as u32;+ let sy = ((y as f32 + 0.5) / s) as u32;+ let si = ((sy.min(h - 1) * w + sx.min(w - 1)) * 4) as usize;+ let di = ((y * nw + x) * 4) as usize;+ out[di..di + 4].copy_from_slice(&src[si..si + 4]);+ }+ }+ let small =+ photocraft_codecs::Image::from_u8(nw, nh, photocraft_codecs::ChannelLayout::Rgba, out)+ .ok()?;+ photocraft_codecs::encode(&small, photocraft_codecs::Format::Png, &Default::default()).ok()+}++// ---------------------------------------------------------------------------+// Tools+// ---------------------------------------------------------------------------++#[tool_router]+impl PhotocraftMcp {+ #[tool(description = "List open documents (index, name, size, dirty) and the active index.")]+ async fn session_list(&self) -> Result<CallToolResult, McpError> {+ if let Some(r) = self.headless_op(|h| Ok(h.session_list())).await {+ return to_result(r);+ }+ let b = self.bridge_client().expect("bridge");+ to_result(b.call("ui.inspect", json!({})).await)+ }++ #[tool(+ description = "Open an image or document file and make it active. Returns index, size and import warnings."+ )]+ async fn doc_open(+ &self,+ Parameters(p): Parameters<OpenParams>,+ ) -> Result<CallToolResult, McpError> {+ let path = PathBuf::from(&p.path);+ if let Some(r) = self.headless_op(move |h| h.open(&path)).await {+ return to_result(r);+ }+ let b = self.bridge_client().expect("bridge");+ to_result(b.call("app.open", json!({"path": p.path})).await)+ }++ #[tool(description = "Create a new document (defaults: 1920x1080 RGB 8-bit white).")]+ async fn doc_new(+ &self,+ Parameters(p): Parameters<NewParams>,+ ) -> Result<CallToolResult, McpError> {+ let mut params = serde_json::Map::new();+ if let Some(v) = p.width {+ params.insert("width".into(), v.into());+ }+ if let Some(v) = p.height {+ params.insert("height".into(), v.into());+ }+ if let Some(v) = p.mode {+ params.insert("mode".into(), v.into());+ }+ if let Some(v) = p.depth {+ params.insert("depth".into(), v.into());+ }+ if let Some(v) = p.background {+ params.insert("background".into(), v.into());+ }+ if let Some(v) = p.name {+ params.insert("name".into(), v.into());+ }+ self.run_command("file.new".into(), Value::Object(params))+ .await+ }++ #[tool(+ description = "Save the document. `.pcraft` is the lossless native format (incremental); other extensions \+ (psd, png, jpg, tif, webp, exr, …) export. Returns warnings about anything the format cannot hold."+ )]+ async fn doc_save(+ &self,+ Parameters(p): Parameters<SaveParams>,+ ) -> Result<CallToolResult, McpError> {+ self.save_impl(p).await+ }++ #[tool(+ description = "Export the document to another format (same as doc_save with an explicit path/format)."+ )]+ async fn doc_export(+ &self,+ Parameters(p): Parameters<SaveParams>,+ ) -> Result<CallToolResult, McpError> {+ if p.path.is_none() {+ return Ok(fail("doc_export needs `path`"));+ }+ self.save_impl(p).await+ }++ #[tool(+ description = "Document state as JSON: layer tree (top to bottom), history, selection, active layer."+ )]+ async fn doc_inspect(+ &self,+ Parameters(p): Parameters<DocIndex>,+ ) -> Result<CallToolResult, McpError> {+ if let Some(r) = self.headless_op(move |h| h.inspect(p.index)).await {+ return to_result(r);+ }+ let b = self.bridge_client().expect("bridge");+ to_result(+ b.call(+ "engine.execute",+ json!({"command": "document.inspect", "params": {}}),+ )+ .await,+ )+ }++ #[tool(+ description = "Render the flattened document and return it as a PNG image (bridge mode: window screenshot)."+ )]+ async fn doc_render_preview(+ &self,+ Parameters(p): Parameters<PreviewParams>,+ ) -> Result<CallToolResult, McpError> {+ let max = p.max_side.unwrap_or(1024);+ if let Some(r) = self.headless_op(move |h| h.render_png(p.index, max)).await {+ return Ok(match r {+ Ok(png) => png_result(&png, format!("flattened preview (max side {max})")),+ Err(e) => fail(e),+ });+ }+ let b = self.bridge_client().expect("bridge");+ self.screenshot(b, Some(max)).await+ }++ #[tool(description = "Make the document at `index` active.")]+ async fn doc_select(+ &self,+ Parameters(p): Parameters<SelectParams>,+ ) -> Result<CallToolResult, McpError> {+ match self.headless_op(move |h| h.select(p.index)).await {+ Some(r) => to_result(r),+ None => bridge_only_headless("doc_select"),+ }+ }++ #[tool(description = "Close a document (default: the active one) without saving.")]+ async fn doc_close(+ &self,+ Parameters(p): Parameters<DocIndex>,+ ) -> Result<CallToolResult, McpError> {+ match self.headless_op(move |h| h.close(p.index)).await {+ Some(r) => to_result(r),+ None => bridge_only_headless("doc_close"),+ }+ }++ #[tool(+ description = "List engine commands: id, label, menu path, shortcut, parameter doc, enabled now."+ )]+ async fn command_list(+ &self,+ Parameters(p): Parameters<ListParams>,+ ) -> Result<CallToolResult, McpError> {+ let all = if let Some(r) = self.headless_op(|h| Ok(h.command_list())).await {+ r+ } else {+ let b = self.bridge_client().expect("bridge");+ b.call("engine.commands", json!({})).await+ };+ let all = match all {+ Ok(v) => v,+ Err(e) => return Ok(fail(e)),+ };+ let needle = p.filter.map(|f| f.to_lowercase());+ let enabled_only = p.enabled_only.unwrap_or(false);+ let items: Vec<Value> = all+ .as_array()+ .cloned()+ .unwrap_or_else(|| {+ all.get("commands")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default()+ })+ .into_iter()+ .filter(|c| {+ let hay = format!(+ "{} {}",+ c.get("id").and_then(Value::as_str).unwrap_or(""),+ c.get("label").and_then(Value::as_str).unwrap_or("")+ )+ .to_lowercase();+ needle.as_ref().is_none_or(|n| hay.contains(n))+ && (!enabled_only || c.get("enabled").and_then(Value::as_bool).unwrap_or(true))+ })+ .collect();+ Ok(ok_json(&Value::Array(items)))+ }++ #[tool(+ description = "Run an engine command by id with JSON params (see command_list). Returns the command's JSON result."+ )]+ async fn command_run(+ &self,+ Parameters(p): Parameters<RunParams>,+ ) -> Result<CallToolResult, McpError> {+ self.run_command(p.id, p.params.unwrap_or_else(|| json!({})))+ .await+ }++ // ----- live-GUI tools (bridge mode) -----++ #[tool(+ description = "Bridge mode: full UI state of the live app (tool, panels, views, dialogs, menu tree)."+ )]+ async fn ui_inspect(&self) -> Result<CallToolResult, McpError> {+ match self.bridge_client() {+ Some(b) => to_result(b.call("ui.inspect", json!({})).await),+ None => bridge_only("ui_inspect"),+ }+ }++ #[tool(description = "Bridge mode: screenshot of the live app window as PNG.")]+ async fn ui_screenshot(+ &self,+ Parameters(p): Parameters<PreviewParams>,+ ) -> Result<CallToolResult, McpError> {+ match self.bridge_client() {+ Some(b) => self.screenshot(b, p.max_side).await,+ None => bridge_only("ui_screenshot"),+ }+ }++ #[tool(+ description = "Bridge mode: send pointer events (document coordinates) to the active tool."+ )]+ async fn ui_pointer(+ &self,+ Parameters(p): Parameters<PointerParams>,+ ) -> Result<CallToolResult, McpError> {+ match self.bridge_client() {+ Some(b) => {+ let mut params = json!({"events": p.events});+ if let Some(m) = p.modifiers {+ params["modifiers"] = m;+ }+ to_result(b.call("ui.pointer", params).await)+ }+ None => bridge_only("ui_pointer"),+ }+ }++ #[tool(description = "Bridge mode: activate a menu item by id.")]+ async fn ui_menu_invoke(+ &self,+ Parameters(p): Parameters<MenuParams>,+ ) -> Result<CallToolResult, McpError> {+ match self.bridge_client() {+ Some(b) => to_result(b.call("ui.menu.invoke", json!({"id": p.id})).await),+ None => bridge_only("ui_menu_invoke"),+ }+ }++ #[tool(description = "Bridge mode: change UI state (tool, panels, zoom, center, dark).")]+ async fn ui_set(+ &self,+ Parameters(p): Parameters<UiSetParams>,+ ) -> Result<CallToolResult, McpError> {+ match self.bridge_client() {+ Some(b) => to_result(b.call("ui.set", p.fields).await),+ None => bridge_only("ui_set"),+ }+ }++ #[tool(+ description = "Bridge mode: call any control-protocol method (docs/control-protocol.md) with raw params."+ )]+ async fn control_call(+ &self,+ Parameters(p): Parameters<ControlParams>,+ ) -> Result<CallToolResult, McpError> {+ match self.bridge_client() {+ Some(b) => to_result(+ b.call(&p.method, p.params.unwrap_or_else(|| json!({})))+ .await,+ ),+ None => bridge_only("control_call"),+ }+ }+}++fn bridge_only_headless(name: &str) -> Result<CallToolResult, McpError> {+ Ok(fail(format!(+ "`{name}` is only available in headless mode (in the GUI use the window/tab UI or control_call)"+ )))+}++impl PhotocraftMcp {+ async fn run_command(&self, id: String, params: Value) -> Result<CallToolResult, McpError> {+ let (id2, params2) = (id.clone(), params.clone());+ if let Some(r) = self+ .headless_op(move |h| h.command_run(&id2, params2))+ .await+ {+ return to_result(r);+ }+ let b = self.bridge_client().expect("bridge");+ to_result(+ b.call("engine.execute", json!({"command": id, "params": params}))+ .await,+ )+ }++ async fn save_impl(&self, p: SaveParams) -> Result<CallToolResult, McpError> {+ if self.bridge_client().is_some() {+ let b = self.bridge_client().expect("bridge");+ let Some(path) = p.path else {+ return Ok(fail("bridge mode needs `path`"));+ };+ return to_result(b.call("app.save", json!({"path": path})).await);+ }+ let r = self+ .headless_op(move |h| {+ let mut opts = photocraft_io::ExportOptions::default();+ if let Some(q) = p.quality {+ opts.encode.jpeg_quality = q.clamp(1, 100);+ }+ let path = p.path.map(PathBuf::from);+ h.save(p.index, path.as_deref(), p.format.as_deref(), &opts)+ })+ .await+ .expect("headless");+ to_result(r)+ }+}++#[tool_handler(router = self.tool_router, name = "photocraft", instructions = "Photocraft image editor. Every edit is an engine command: call `command_list` to discover ids and parameter docs, then `command_run`. Use `doc_open`/`doc_new` first, `doc_inspect` for the layer tree, `doc_render_preview` to see the result, and `doc_save` (.pcraft is lossless native; .psd/.png/.jpg/.tif… export). In bridge mode the `ui_*` tools drive the live app (inspect, screenshot, pointer, menus).")]+impl ServerHandler for PhotocraftMcp {}++/// Used by the render helper in tests and the CLI.+pub fn render_document_png(+ doc: &photocraft_doc::Document,+ max_side: u32,+) -> Result<Vec<u8>, AutomationError> {+ files::render_png(doc, max_side)+}diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rsnew file mode 100644index 000000000..a7b1fc1db--- /dev/null+++ b/crates/automation/tests/mcp.rs@@ -0,0 +1,411 @@+//! Spin the MCP server in-process (tokio duplex), call tools as a client.++use std::io::Write;++use base64::Engine as _;+use photocraft_automation::PhotocraftMcp;+use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig};+use rmcp::service::RunningService;+use rmcp::{ClientHandler, RoleClient, ServiceExt};+use serde_json::{Value, json};+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};++#[derive(Clone, Default)]+struct Client;+impl ClientHandler for Client {+ fn get_info(&self) -> ClientConfig {+ ClientConfig::default()+ }+}++async fn connect(server: PhotocraftMcp) -> RunningService<RoleClient, Client> {+ let (s, c) = tokio::io::duplex(1 << 20);+ tokio::spawn(async move {+ if let Ok(running) = server.serve(s).await {+ let _ = running.waiting().await;+ }+ });+ Client.serve(c).await.expect("client init")+}++async fn call(+ client: &RunningService<RoleClient, Client>,+ name: &str,+ args: Value,+) -> CallToolResult {+ let mut p = CallToolRequestParams::new(name.to_owned());+ if let Value::Object(m) = args {+ p = p.with_arguments(m);+ }+ client.call_tool(p).await.expect("call_tool transport")+}++fn text(r: &CallToolResult) -> String {+ r.content+ .iter()+ .filter_map(|c| c.as_text())+ .map(|t| t.text.clone())+ .collect::<Vec<_>>()+ .join("\n")+}++fn json_of(r: &CallToolResult) -> Value {+ assert_ne!(r.is_error, Some(true), "tool error: {}", text(r));+ serde_json::from_str(&text(r)).unwrap_or_else(|e| panic!("not JSON ({e}): {}", text(r)))+}++fn tmp(name: &str) -> std::path::PathBuf {+ let d = std::env::temp_dir().join(format!("pc-mcp-{}-{name}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++#[tokio::test(flavor = "multi_thread")]+async fn lists_expected_tools() {+ let client = connect(PhotocraftMcp::headless()).await;+ let tools = client.list_all_tools().await.unwrap();+ let names: Vec<String> = tools.iter().map(|t| t.name.to_string()).collect();+ for n in [+ "session_list",+ "doc_open",+ "doc_new",+ "doc_save",+ "doc_export",+ "doc_inspect",+ "doc_render_preview",+ "doc_select",+ "doc_close",+ "command_list",+ "command_run",+ "ui_inspect",+ "ui_screenshot",+ "ui_pointer",+ "ui_menu_invoke",+ "ui_set",+ "control_call",+ ] {+ assert!(+ names.contains(&n.to_string()),+ "missing tool {n}: {names:?}"+ );+ }+ for t in &tools {+ assert!(+ t.name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '_'),+ "tool name `{}`",+ t.name+ );+ assert!(t.description.as_ref().is_some_and(|d| !d.is_empty()));+ }+ let info = client.peer_info().expect("server info");+ assert_eq!(info.server_info.as_ref().unwrap().name, "photocraft");+ assert!(+ info.instructions+ .as_ref()+ .is_some_and(|i| i.contains("command_list"))+ );+ client.cancel().await.unwrap();+}++#[tokio::test(flavor = "multi_thread")]+async fn headless_edit_render_save_roundtrip() {+ let dir = tmp("edit");+ let client = connect(PhotocraftMcp::headless()).await;++ let r = call(+ &client,+ "doc_new",+ json!({"width": 64, "height": 48, "background": "white", "name": "Agent"}),+ )+ .await;+ assert_ne!(r.is_error, Some(true), "{}", text(&r));+ let r = call(+ &client,+ "command_run",+ json!({"id": "layer.new.layer", "params": {"name": "Ink"}}),+ )+ .await;+ assert_ne!(r.is_error, Some(true), "{}", text(&r));+ let r = call(+ &client,+ "command_run",+ json!({"id": "paint.stroke", "params": {"points": [[5, 5, 1.0], [50, 40, 1.0]], "size": 6, "color": "#ff0000"}}),+ )+ .await;+ assert_ne!(r.is_error, Some(true), "{}", text(&r));++ let doc = json_of(&call(&client, "doc_inspect", json!({})).await);+ assert_eq!(doc["width"], 64);+ let names: Vec<&str> = doc["layers"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|l| l["name"].as_str())+ .collect();+ assert_eq!(names, ["Ink", "Background"]);++ let r = call(&client, "doc_render_preview", json!({"max_side": 32})).await;+ let img = r+ .content+ .iter()+ .find_map(|c| c.as_image())+ .expect("image content");+ assert_eq!(img.mime_type, "image/png");+ let png = base64::engine::general_purpose::STANDARD+ .decode(&img.data)+ .unwrap();+ let decoded = photocraft_codecs::decode(&png).unwrap();+ assert_eq!(decoded.dimensions(), (32, 24));++ let pc = dir.join("agent.pcraft");+ let r = json_of(&call(&client, "doc_save", json!({"path": pc.to_string_lossy()})).await);+ assert_eq!(r["path"], pc.to_string_lossy().as_ref());+ let png_path = dir.join("agent.png");+ json_of(+ &call(+ &client,+ "doc_export",+ json!({"path": png_path.to_string_lossy()}),+ )+ .await,+ );+ let jpg_path = dir.join("agent.jpg");+ json_of(+ &call(+ &client,+ "doc_export",+ json!({"path": jpg_path.to_string_lossy(), "quality": 70}),+ )+ .await,+ );+ assert!(photocraft_codecs::decode(&std::fs::read(&png_path).unwrap()).is_ok());+ assert!(std::fs::metadata(&jpg_path).unwrap().len() > 100);++ // Re-open the native file: identical layer tree.+ let o = json_of(&call(&client, "doc_open", json!({"path": pc.to_string_lossy()})).await);+ assert_eq!(o["index"], 1);+ let doc2 = json_of(&call(&client, "doc_inspect", json!({"index": 1})).await);+ assert_eq!(doc2["layers"].as_array().unwrap().len(), 2);+ let sess = json_of(&call(&client, "session_list", json!({})).await);+ assert_eq!(sess["documents"].as_array().unwrap().len(), 2);+ json_of(&call(&client, "doc_close", json!({"index": 1})).await);+ json_of(&call(&client, "doc_select", json!({"index": 0})).await);+ client.cancel().await.unwrap();+ std::fs::remove_dir_all(dir).unwrap();+}++#[tokio::test(flavor = "multi_thread")]+async fn command_list_filters() {+ let client = connect(PhotocraftMcp::headless()).await;+ let all = json_of(&call(&client, "command_list", json!({})).await);+ let n_all = all.as_array().unwrap().len();+ assert!(n_all > 20);+ let blur = json_of(&call(&client, "command_list", json!({"filter": "blur"})).await);+ assert!(!blur.as_array().unwrap().is_empty() && blur.as_array().unwrap().len() < n_all);+ assert!(+ blur.as_array()+ .unwrap()+ .iter()+ .all(|c| c["params"].is_string())+ );+ let enabled = json_of(&call(&client, "command_list", json!({"enabled_only": true})).await);+ assert!(+ enabled+ .as_array()+ .unwrap()+ .iter()+ .any(|c| c["id"] == "file.new")+ );+ assert!(+ !enabled+ .as_array()+ .unwrap()+ .iter()+ .any(|c| c["id"] == "layer.new.layer"),+ "needs a document"+ );+ client.cancel().await.unwrap();+}++#[tokio::test(flavor = "multi_thread")]+async fn errors_are_tool_errors_not_crashes() {+ let client = connect(PhotocraftMcp::headless()).await;+ let r = call(&client, "command_run", json!({"id": "no.such.command"})).await;+ assert_eq!(r.is_error, Some(true));+ assert!(text(&r).contains("unknown command"));+ let r = call(&client, "doc_inspect", json!({})).await;+ assert_eq!(r.is_error, Some(true));+ let r = call(+ &client,+ "doc_open",+ json!({"path": "/definitely/missing.png"}),+ )+ .await;+ assert_eq!(r.is_error, Some(true));+ let r = call(&client, "ui_inspect", json!({})).await;+ assert_eq!(r.is_error, Some(true));+ assert!(text(&r).contains("bridge"));+ let r = call(&client, "doc_export", json!({})).await;+ assert_eq!(r.is_error, Some(true));+ // Server still alive.+ json_of(&call(&client, "session_list", json!({})).await);+ client.cancel().await.unwrap();+}++#[tokio::test(flavor = "multi_thread")]+async fn open_png_and_inspect() {+ let dir = tmp("open");+ let img = photocraft_codecs::Image::from_u8(+ 8,+ 4,+ photocraft_codecs::ChannelLayout::Rgb,+ vec![200; 96],+ )+ .unwrap();+ let path = dir.join("in.png");+ std::fs::File::create(&path)+ .unwrap()+ .write_all(+ &photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default())+ .unwrap(),+ )+ .unwrap();+ let client = connect(PhotocraftMcp::headless()).await;+ let o = json_of(&call(&client, "doc_open", json!({"path": path.to_string_lossy()})).await);+ assert_eq!(+ (o["width"].as_u64(), o["height"].as_u64()),+ (Some(8), Some(4))+ );+ let px = json_of(+ &call(+ &client,+ "command_run",+ json!({"id": "document.pixel", "params": {"x": 1, "y": 1}}),+ )+ .await,+ );+ assert!(px.to_string().contains("0.78"), "{px}");+ client.cancel().await.unwrap();+ std::fs::remove_dir_all(dir).unwrap();+}++// ---------------------------------------------------------------------------+// Bridge mode against a fake control server+// ---------------------------------------------------------------------------++async fn fake_app() -> (String, tokio::task::JoinHandle<Vec<Value>>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap().to_string();+ let h = tokio::spawn(async move {+ let mut seen = Vec::new();+ let (sock, _) = listener.accept().await.unwrap();+ let (r, mut w) = sock.into_split();+ let mut lines = BufReader::new(r).lines();+ while let Ok(Some(line)) = lines.next_line().await {+ let req: Value = serde_json::from_str(&line).unwrap();+ let id = req["id"].clone();+ let method = req["method"].as_str().unwrap_or("").to_owned();+ let reply = match method.as_str() {+ "ui.inspect" => {+ json!({"id": id, "ok": true, "result": {"tool": "brush", "panels": ["layers"]}})+ }+ "engine.execute" => {+ json!({"id": id, "ok": true, "result": {"ran": req["params"]["command"]}})+ }+ "engine.commands" => {+ json!({"id": id, "ok": true, "result": [{"id": "file.new", "label": "New…", "enabled": true}]})+ }+ "ui.screenshot" => {+ let path = req["params"]["path"].as_str().unwrap().to_owned();+ let img = photocraft_codecs::Image::from_u8(+ 40,+ 20,+ photocraft_codecs::ChannelLayout::Rgba,+ vec![9; 3200],+ )+ .unwrap();+ std::fs::write(+ &path,+ photocraft_codecs::encode(+ &img,+ photocraft_codecs::Format::Png,+ &Default::default(),+ )+ .unwrap(),+ )+ .unwrap();+ json!({"id": id, "ok": true, "result": {"path": path}})+ }+ _ => json!({"id": id, "ok": false, "error": format!("unknown tool `{method}`")}),+ };+ // A stale line first, to check id matching.+ w.write_all(b"{\"id\":999999,\"ok\":true,\"result\":null}\n")+ .await+ .unwrap();+ w.write_all(format!("{reply}\n").as_bytes()).await.unwrap();+ seen.push(req);+ }+ seen+ });+ (addr, h)+}++#[tokio::test(flavor = "multi_thread")]+async fn bridge_forwards_to_control_protocol() {+ let (addr, app) = fake_app().await;+ let client = connect(PhotocraftMcp::bridge(&addr).unwrap()).await;++ let ui = json_of(&call(&client, "ui_inspect", json!({})).await);+ assert_eq!(ui["tool"], "brush");+ let r = json_of(+ &call(+ &client,+ "command_run",+ json!({"id": "layer.new.layer", "params": {"name": "X"}}),+ )+ .await,+ );+ assert_eq!(r["ran"], "layer.new.layer");+ let l = json_of(&call(&client, "command_list", json!({})).await);+ assert_eq!(l[0]["id"], "file.new");+ let shot = call(&client, "ui_screenshot", json!({"max_side": 20})).await;+ let img = shot+ .content+ .iter()+ .find_map(|c| c.as_image())+ .expect("image");+ let png = base64::engine::general_purpose::STANDARD+ .decode(&img.data)+ .unwrap();+ assert_eq!(+ photocraft_codecs::decode(&png).unwrap().dimensions(),+ (20, 10)+ );+ let e = call(&client, "control_call", json!({"method": "bogus.method"})).await;+ assert_eq!(e.is_error, Some(true));+ assert!(text(&e).contains("unknown tool"));+ let r = call(&client, "doc_select", json!({"index": 0})).await;+ assert_eq!(r.is_error, Some(true));++ client.cancel().await.unwrap();+ app.abort();+}++#[test]+fn bridge_rejects_non_loopback() {+ assert!(PhotocraftMcp::bridge("10.0.0.5:7878").is_err());+ assert!(PhotocraftMcp::bridge("127.0.0.1:7878").is_ok());+ assert!(PhotocraftMcp::bridge("localhost:1").is_ok());+}++#[tokio::test(flavor = "multi_thread")]+async fn bridge_reports_unreachable_app() {+ let client = connect(PhotocraftMcp::bridge("127.0.0.1:1").unwrap()).await;+ let r = call(&client, "ui_inspect", json!({})).await;+ assert_eq!(r.is_error, Some(true));+ assert!(text(&r).contains("--control"), "{}", text(&r));+ client.cancel().await.unwrap();+}diff --git a/crates/compose/Cargo.toml b/crates/compose/Cargo.tomlindex efa46bede..45bdb4bdf 100644--- a/crates/compose/Cargo.toml+++ b/crates/compose/Cargo.toml@@ -12,6 +12,16 @@ photocraft-geom = { workspace = true }photocraft-color = { workspace = true }photocraft-raster = { workspace = true }photocraft-doc = { workspace = true }+photocraft-vector = { workspace = true }++[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+rayon = { workspace = true }[dev-dependencies]proptest = { workspace = true }+criterion = { workspace = true }+photocraft-paint = { workspace = true }++[[bench]]+name = "compose"+harness = falsediff --git a/crates/compose/benches/compose.rs b/crates/compose/benches/compose.rsnew file mode 100644index 000000000..00ce91004--- /dev/null+++ b/crates/compose/benches/compose.rs@@ -0,0 +1,76 @@+//! `cargo bench -p photocraft-compose`+use criterion::{Criterion, criterion_group, criterion_main};+use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};+use photocraft_doc::{Adjustment, Document, Layer, LayerContent, LayerMask, Size};+use photocraft_geom::Rect;+use photocraft_raster::Surface;++fn filled(n: u32, seed: u8) -> Surface {+ let r = Rect::new(0, 0, n as i32, n as i32);+ let mut s = Surface::new(PixelFormat::RGBA8);+ let row: Vec<u8> = (0..n).flat_map(|x| [(x as u8).wrapping_mul(seed), (x / 3) as u8, seed, 200]).collect();+ let bytes: Vec<u8> = (0..n).flat_map(|_| row.iter().copied()).collect();+ s.write_interleaved(r, &bytes);+ s+}++/// 6016² document, 5 layers: background, masked, multiply, curves, screen (opacity/fill).+fn five_layer_doc(n: u32) -> Document {+ let mut d = Document::with_background("bench", Size::new(n, n), ColorMode::Rgb, SampleType::U8, Color::WHITE);+ let mut a = Layer::new("masked", LayerContent::Raster(filled(n, 3)));+ let mut m = LayerMask::reveal_all();+ m.surface.fill_rect(Rect::new(0, 0, n as i32 / 2, n as i32), &[0.3]);+ a.mask = Some(m);+ d.layers.push(a);+ let mut b = Layer::new("multiply", LayerContent::Raster(filled(n, 7)));+ b.blend = BlendMode::Multiply;+ d.layers.push(b);+ d.layers.push(Layer::new("curves", LayerContent::Adjustment(Adjustment::identity_curves())));+ let mut c = Layer::new("screen", LayerContent::Raster(filled(n, 11)));+ c.blend = BlendMode::Screen;+ c.opacity = 0.7;+ c.fill_opacity = 0.8;+ d.layers.push(c);+ d+}++/// 2048² document with 20 masked layers.+fn mask_heavy_doc() -> Document {+ let n = 2048;+ let mut d = Document::with_background("masks", Size::new(n, n), ColorMode::Rgb, SampleType::U8, Color::WHITE);+ for i in 0..20u8 {+ let mut l = Layer::new(format!("l{i}"), LayerContent::Raster(filled(n, i + 2)));+ let mut m = LayerMask::hide_all();+ m.surface.fill_rect(Rect::new(i as i32 * 50, 0, i as i32 * 50 + 1200, n as i32), &[0.8]);+ l.mask = Some(m);+ l.opacity = 0.6;+ d.layers.push(l);+ }+ d+}++fn benches(c: &mut Criterion) {+ let doc = five_layer_doc(6016);+ let mut g = c.benchmark_group("compose");+ g.sample_size(10);+ g.bench_function("flatten_6016_5_layers", |b| b.iter(|| photocraft_compose::flatten(&doc)));+ let masks = mask_heavy_doc();+ g.bench_function("flatten_2048_20_masked_layers", |b| b.iter(|| photocraft_compose::flatten(&masks)));+ let stroke = photocraft_paint::Stroke {+ brush: photocraft_paint::BrushSettings { size: 60.0, hardness: 0.5, ..Default::default() },+ points: (0..500).map(|i| photocraft_paint::StrokePoint { x: 100.0 + i as f64 * 7.0, y: 1000.0 + (i as f64 * 0.05).sin() * 400.0, pressure: 1.0 }).collect(),+ };+ let base = filled(4096, 5);+ let mut sel = Surface::with_default(PixelFormat::GRAY8, &[1.0]);+ sel.fill_rect(Rect::new(0, 0, 2000, 4096), &[0.5]);+ g.bench_function("paint_stroke_500pt_60px_with_selection", |b| {+ b.iter(|| {+ let mut s = base.clone();+ photocraft_paint::apply_stroke(&mut s, &stroke, Some(&sel), false)+ })+ });+ g.finish();+}++criterion_group!(compose_benches, benches);+criterion_main!(compose_benches);diff --git a/crates/compose/examples/bench_flatten.rs b/crates/compose/examples/bench_flatten.rsnew file mode 100644index 000000000..acaaa84cb--- /dev/null+++ b/crates/compose/examples/bench_flatten.rs@@ -0,0 +1,41 @@+//! Timing: flatten a 6016² document with 5 layers (mask, adjustment, blend modes).+//! `cargo run --release -p photocraft-compose --example bench_flatten [size]`+use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};+use photocraft_doc::{Adjustment, Document, Layer, LayerContent, LayerMask, Size};+use photocraft_geom::Rect;+use photocraft_raster::Surface;++pub fn bench_doc(n: u32) -> Document {+ let mut d = Document::with_background("bench", Size::new(n, n), ColorMode::Rgb, SampleType::U8, Color::WHITE);+ let r = Rect::new(0, 0, n as i32, n as i32);+ let fill = |seed: u8| {+ let mut s = Surface::new(PixelFormat::RGBA8);+ let row: Vec<u8> = (0..n).flat_map(|x| [(x as u8).wrapping_mul(seed), (x / 3) as u8, seed, 200]).collect();+ let bytes: Vec<u8> = (0..n).flat_map(|_| row.iter().copied()).collect();+ s.write_interleaved(r, &bytes);+ s+ };+ let mut a = Layer::new("masked", LayerContent::Raster(fill(3)));+ let mut m = LayerMask::reveal_all();+ m.surface.fill_rect(Rect::new(0, 0, n as i32 / 2, n as i32), &[0.3]);+ a.mask = Some(m);+ d.layers.push(a);+ let mut b = Layer::new("multiply", LayerContent::Raster(fill(7)));+ b.blend = BlendMode::Multiply;+ d.layers.push(b);+ d.layers.push(Layer::new("curves", LayerContent::Adjustment(Adjustment::identity_curves())));+ let mut c = Layer::new("screen", LayerContent::Raster(fill(11)));+ c.blend = BlendMode::Screen;+ c.opacity = 0.7;+ c.fill_opacity = 0.8;+ d.layers.push(c);+ d+}++fn main() {+ let n: u32 = std::env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(6016);+ let d = bench_doc(n);+ let t = std::time::Instant::now();+ let out = photocraft_compose::flatten(&d);+ println!("flatten {n}x{n}, {} layers: {:.2?} (px0 {:?})", d.layers.len(), t.elapsed(), out.px[0]);+}diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex 72da18fab..471ebe56e 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -21,7 +21,7 @@ use photocraft_color::blend::BlendMode;use psblend as blend;use photocraft_doc::{Document, Fill, Layer, LayerContent};use photocraft_geom::Rect;-use photocraft_raster::{Rgba8Image, Surface, to_rgba};+use photocraft_raster::{Rgba8Image, Surface};/// Straight-alpha RGBA float buffer covering a rectangle.#[derive(Clone, Debug, PartialEq)]@@ -64,11 +64,55 @@ impl Buffer {}}-/// Composite the whole document over `rect`.+/// Tile size for parallel rendering (tile results are independent).+pub const RENDER_TILE: i32 = 256;++/// Composite the whole document over `rect`, in parallel 256² tiles on+/// native targets (single-threaded on wasm).pub fn render(doc: &Document, rect: Rect) -> Buffer {- let mut buf = Buffer::transparent(rect);- composite_stack(&doc.layers, &mut buf, &Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::for_mode(doc.mode), light: doc.global_light });- buf+ render_tiled(doc, rect, RENDER_TILE)+}++/// [`render`] with an explicit tile size (tests check tile independence).+pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer {+ let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::for_mode(doc.mode), light: doc.global_light };+ if rect.width() as i32 <= tile && rect.height() as i32 <= tile {+ let mut buf = Buffer::transparent(rect);+ composite_stack(&doc.layers, &mut buf, &cx);+ return buf;+ }+ let mut tiles = Vec::new();+ let mut y = rect.y0;+ while y < rect.y1 {+ let mut x = rect.x0;+ while x < rect.x1 {+ tiles.push(Rect::new(x, y, (x + tile).min(rect.x1), (y + tile).min(rect.y1)));+ x += tile;+ }+ y += tile;+ }+ let run = |t: &Rect| {+ let mut b = Buffer::transparent(*t);+ composite_stack(&doc.layers, &mut b, &cx);+ b+ };+ #[cfg(not(target_arch = "wasm32"))]+ let parts: Vec<Buffer> = {+ use rayon::prelude::*;+ tiles.par_iter().map(run).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let parts: Vec<Buffer> = tiles.iter().map(run).collect();+ let mut out = Buffer::transparent(rect);+ let w = rect.width() as usize;+ for part in parts {+ let pw = part.rect.width() as usize;+ for (row, src) in part.px.chunks_exact(pw).enumerate() {+ let o = ((part.rect.y0 - rect.y0) as usize + row) * w + (part.rect.x0 - rect.x0) as usize;+ out.px[o..o + pw].copy_from_slice(src);+ }+ }+ out}/// Composite the full canvas.@@ -159,8 +203,24 @@ fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect {}}-fn mask_at(layer: &Layer, x: i32, y: i32) -> f32 {- layer.mask.as_ref().map_or(1.0, |m| m.value(x, y))+/// The layer's effective mask over `rect` (row-major), read once per tile: the pixel mask+/// times the rasterized vector mask.+fn mask_vals(layer: &Layer, rect: Rect) -> Option<Vec<f32>> {+ let vector = layer.vector_mask.as_ref().map(|vm| photocraft_vector::vector_mask_values(vm, rect));+ let Some(m) = layer.mask.as_ref() else { return vector };+ let mut v = Vec::new();+ m.values_into(rect, &mut v);+ if let Some(vm) = vector {+ for (a, b) in v.iter_mut().zip(vm) {+ *a *= b;+ }+ }+ Some(v)+}++#[inline]+fn mask_k(m: &Option<Vec<f32>>, i: usize) -> f32 {+ m.as_ref().map_or(1.0, |v| v[i])}/// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer.@@ -183,22 +243,17 @@ fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buffer> {None => Buffer::transparent(rect),},};- if layer.mask.is_some() {- for y in rect.y0..rect.y1 {- for x in rect.x0..rect.x1 {- let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize;- buf.px[i][3] *= mask_at(layer, x, y);- }+ if let Some(m) = mask_vals(layer, rect) {+ for (p, k) in buf.px.iter_mut().zip(&m) {+ p[3] *= k;}}Some(buf)}pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer {- let fmt = s.format();- let n = fmt.channels();- let raw = s.read_region(rect);- let px = raw.chunks_exact(n).map(|p| to_rgba(&fmt, p)).collect();+ let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize];+ s.read_rgba_into(rect, &mut px);Buffer { rect, px }}@@ -250,9 +305,29 @@ fn sample_stops(stops: &[(f32, photocraft_color::Color)], t: f32) -> [f32; 4] {}}+/// `true` when a pixel-backed layer has nothing to contribute in `rect`:+/// no allocated tiles there, a transparent default, and no effects (which+/// could reach in from outside). Clipped layers depend on the base, so they+/// vanish with it.+fn empty_in(layer: &Layer, rect: Rect) -> bool {+ if effects::has_effects(layer) {+ return false;+ }+ match &layer.content {+ LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_) => match layer.surface() {+ Some(s) => !s.has_tiles_in(rect) && s.default_pixel().last().is_some_and(|a| *a <= 0.0) && s.format().alpha,+ None => true,+ },+ _ => false,+ }+}+/// Composite `layer` (plus its clipping group) onto `backdrop`.fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {let rect = backdrop.rect;+ if empty_in(layer, rect) {+ return;+ }let opacity = layer.opacity * layer.fill_opacity;// Pass-through groups composite their children straight into the backdrop.@@ -262,15 +337,13 @@ fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx:{let before = backdrop.clone();composite_stack(&g.children, backdrop, cx);- let needs_mix = opacity < 1.0 || layer.mask.is_some();+ let needs_mix = opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some();if needs_mix {- for y in rect.y0..rect.y1 {- for x in rect.x0..rect.x1 {- let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize;- let k = opacity * mask_at(layer, x, y);- let (a, b) = (before.px[i], backdrop.px[i]);- backdrop.px[i] = std::array::from_fn(|c| a[c] + (b[c] - a[c]) * k);- }+ let mv = mask_vals(layer, rect);+ for (i, (p, a)) in backdrop.px.iter_mut().zip(&before.px).enumerate() {+ let k = opacity * mask_k(&mv, i);+ let b = *p;+ *p = std::array::from_fn(|c| a[c] + (b[c] - a[c]) * k);}}// Layers clipped to a pass-through group sit atop the group's@@ -313,10 +386,11 @@ fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx:for c in clipped.iter().filter(|c| c.visible) {composite_atop(c, &mut adjusted, cx);}+ let mv = mask_vals(layer, rect);for y in rect.y0..rect.y1 {for x in rect.x0..rect.x1 {let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize;- let k = opacity * mask_at(layer, x, y);+ let k = opacity * mask_k(&mv, i);if k <= 0.0 {continue;}@@ -357,10 +431,9 @@ fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) {if let LayerContent::Adjustment(adj) = &layer.content {let mut adjusted = base.clone();adjust::apply_with(adj, &mut adjusted, cx.transfer);+ let mv = mask_vals(layer, rect);for (i, p) in base.px.iter_mut().enumerate() {- let x = rect.x0 + (i as i32 % rect.width() as i32);- let y = rect.y0 + (i as i32 / rect.width() as i32);- let k = layer.opacity * layer.fill_opacity * mask_at(layer, x, y);+ let k = layer.opacity * layer.fill_opacity * mask_k(&mv, i);let a = adjusted.px[i];let bl = blend::blend_rgb(layer.blend, [p[0], p[1], p[2]], [a[0], a[1], a[2]]);for c in 0..3 {diff --git a/crates/compose/src/psblend.rs b/crates/compose/src/psblend.rsindex 91e166a3e..90fa9ab69 100644--- a/crates/compose/src/psblend.rs+++ b/crates/compose/src/psblend.rs@@ -63,10 +63,24 @@ pub fn composite(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity:if as_ <= 0.0 {return backdrop;}+ let ao = as_ + ab * (1.0 - as_);+ if mode == BlendMode::Normal {+ // Fast path: B(Cb, Cs) = Cs.+ if ao <= 0.0 {+ return [0.0; 4];+ }+ let kb = ab * (1.0 - as_);+ let inv = 1.0 / ao;+ return [+ (kb * backdrop[0] + as_ * source[0]) * inv,+ (kb * backdrop[1] + as_ * source[1]) * inv,+ (kb * backdrop[2] + as_ * source[2]) * inv,+ ao,+ ];+ }let cb = [backdrop[0], backdrop[1], backdrop[2]];let cs = [source[0], source[1], source[2]];let b = blend_rgb(mode, cb, cs);- let ao = as_ + ab * (1.0 - as_);if ao <= 0.0 {return [0.0; 4];}@@ -106,7 +120,10 @@ mod tests {}let (cb, cs) = ([0.2, 0.5, 0.9], [0.7, 0.1, 0.4]);assert_eq!(blend_rgb(m, cb, cs), generic::blend_rgb(m, cb, cs));- assert_eq!(composite(m, [0.2, 0.5, 0.9, 0.7], [0.7, 0.1, 0.4, 0.6], 0.8), generic::composite(m, [0.2, 0.5, 0.9, 0.7], [0.7, 0.1, 0.4, 0.6], 0.8));+ let (a, b) = (composite(m, [0.2, 0.5, 0.9, 0.7], [0.7, 0.1, 0.4, 0.6], 0.8), generic::composite(m, [0.2, 0.5, 0.9, 0.7], [0.7, 0.1, 0.4, 0.6], 0.8));+ for c in 0..4 {+ assert!((a[c] - b[c]).abs() < 1e-6, "{m:?} {a:?} {b:?}");+ }}}}diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex e4f76a223..d039e5c80 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -566,3 +566,66 @@ fn effects_render_identically_in_tiles() {assert!(close4(t, full.get(x, y)), "({x},{y})");}}++#[test]+fn parallel_tiles_match_single_pass() {+ // A document exercising masks, clipping, groups, adjustments, fills and effects.+ let mut d = doc_white(97, 61);+ let mut a = solid_layer("a", Rect::new(5, 5, 70, 50), [1.0, 0.2, 0.1, 0.8]);+ let mut m = LayerMask::reveal_all();+ m.surface.fill_rect(Rect::new(0, 0, 40, 61), &[0.25]);+ m.density = 0.8;+ a.mask = Some(m);+ a.effects.items.push(stroke(3.0, StrokePosition::Outside));+ d.layers.push(a);+ let mut clip = solid_layer("clip", Rect::new(30, 0, 97, 61), [0.0, 1.0, 0.0, 1.0]);+ clip.clipped = true;+ clip.blend = photocraft_color::BlendMode::Multiply;+ d.layers.push(clip);+ let mut g = Layer::group("g", vec![solid_layer("in", Rect::new(50, 20, 90, 60), [0.2, 0.3, 0.9, 1.0])]);+ g.opacity = 0.6;+ d.layers.push(g);+ d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)));+ let mut f = Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::rgb(0.5, 0.5, 0.0))));+ f.opacity = 0.3;+ d.layers.push(f);+ let r = d.bounds();+ let whole = render_tiled(&d, r, 10_000);+ for tile in [7, 16, 33] {+ assert_eq!(render_tiled(&d, r, tile), whole, "tile {tile}");+ }+ assert_eq!(render(&d, r), whole);+}++#[test]+fn vector_mask_combines_with_pixel_mask() {+ use photocraft_doc::{Path, Subpath, VectorMask};+ let mut d = doc_white(8, 8);+ let mut l = solid_layer("k", Rect::new(0, 0, 8, 8), [0.0, 0.0, 0.0, 1.0]);+ // Vector mask reveals x in 0..4 (and half of column 4); the pixel mask hides rows 0..2.+ l.vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (4.5, 0.0), (4.5, 8.0), (0.0, 8.0)])])));+ let mut m = LayerMask::reveal_all();+ m.surface.fill_rect(Rect::new(0, 0, 8, 2), &[0.0]);+ l.mask = Some(m);+ d.layers.push(l);+ assert!(close4(px(&d, 1, 4), [0.0, 0.0, 0.0, 1.0]));+ assert!(close4(px(&d, 6, 4), [1.0; 4]));+ assert!(close4(px(&d, 4, 4), [0.5, 0.5, 0.5, 1.0]));+ assert!(close4(px(&d, 1, 1), [1.0; 4]));+ // Tiled rendering gives the same result.+ let whole = render_tiled(&d, d.bounds(), 3);+ assert_eq!(whole.px, render_tiled(&d, d.bounds(), 256).px);+ // Density and disabling.+ let top = d.layers.len() - 1;+ let vm = d.layers[top].vector_mask.as_mut().unwrap();+ vm.density = 0.5;+ assert!(close4(px(&d, 6, 4), [0.5, 0.5, 0.5, 1.0]));+ d.layers[top].vector_mask.as_mut().unwrap().enabled = false;+ assert!(close4(px(&d, 6, 4), [0.0, 0.0, 0.0, 1.0]));+ // Without a pixel mask the vector mask alone applies.+ d.layers[top].mask = None;+ d.layers[top].vector_mask.as_mut().unwrap().enabled = true;+ d.layers[top].vector_mask.as_mut().unwrap().density = 1.0;+ assert!(close4(px(&d, 1, 1), [0.0, 0.0, 0.0, 1.0]));+ assert!(close4(px(&d, 6, 1), [1.0; 4]));+}diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex 4439cfcaa..d1efb6681 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -9,6 +9,8 @@pub mod adjust;pub mod effects;+pub mod text;+pub mod vector;use std::sync::Arc;use std::sync::atomic::{AtomicU64, Ordering};@@ -21,6 +23,10 @@ pub use effects::{pub use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};pub use photocraft_geom::{Affine, Rect, Size};pub use photocraft_raster::Surface;+pub use vector::{+ ClippingPath, FillRule, Knot, LineCap, LineJoin, LiveShape, NamedPath, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath,+ VectorMask,+};use serde::{Deserialize, Serialize};static NEXT_ID: AtomicU64 = AtomicU64::new(1);@@ -38,6 +44,12 @@ impl LayerId {}}+/// Advance the process-wide id counter (shared by layer and document ids) past `max`, so ids+/// loaded from a file never collide with ids minted later.+pub fn ensure_ids_above(max: u64) {+ NEXT_ID.fetch_max(max.saturating_add(1), Ordering::Relaxed);+}+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]pub struct DocId(pub u64);@@ -92,9 +104,31 @@ impl LayerMask {if !self.enabled {return 1.0;}- let v = self.surface.pixel(x, y)[0];+ let v = self.surface.sample_channel(x, y, 0);1.0 - self.density * (1.0 - v)}++ /// Effective mask values over `r` (row-major) into `out`, including+ /// density; all ones when disabled.+ pub fn values_into(&self, r: Rect, out: &mut Vec<f32>) {+ let n = r.width() as usize * r.height() as usize;+ if !self.enabled {+ out.clear();+ out.resize(n, 1.0);+ return;+ }+ self.surface.read_region_into(r, out);+ let ch = self.surface.channels();+ if ch > 1 {+ let v: Vec<f32> = out.chunks_exact(ch).map(|p| p[0]).collect();+ *out = v;+ }+ if self.density < 1.0 {+ for v in out.iter_mut() {+ *v = 1.0 - self.density * (1.0 - *v);+ }+ }+ }}/// Layer styles. Parsed PSD effect data is kept raw until the effects engine lands (M9).@@ -133,15 +167,97 @@ pub struct TextLayer {/// Data of the PSD `TySh` block. On export it replaces the `TySh` entry in/// [`Layer::psd_blocks`] (the text engine updates this field when it edits text).pub psd_raw: Option<Arc<Vec<u8>>>,+ /// Character style runs (see [`text`]). Empty = one run built from `font_family`, `size_pt`+ /// and `color`, which otherwise mirror the first run (summary for simple UIs).+ pub runs: Vec<text::TextRun>,+ /// Paragraph style runs. Empty = default paragraph style.+ pub paragraphs: Vec<text::ParagraphRun>,+ /// Point or paragraph (box) text.+ pub shape: text::TextShape,+ pub orientation: text::Orientation,+ pub antialias: text::AntiAlias,+ /// Warp settings (stored; not rendered yet).+ pub warp: Option<text::TextWarp>,}-#[derive(Clone, Debug, PartialEq)]-pub struct ShapeLayer {- pub fill: Option<Fill>,- pub cache: Option<Surface>,- /// Data of the PSD vector mask block (`vsms`, else `vmsk`). On export it- /// replaces that entry in [`Layer::psd_blocks`].- pub psd_raw: Option<Arc<Vec<u8>>>,+impl Default for TextLayer {+ fn default() -> Self {+ Self {+ text: String::new(),+ font_family: String::new(),+ size_pt: 12.0,+ color: Color::BLACK,+ transform: Affine::IDENTITY,+ cache: None,+ psd_raw: None,+ runs: Vec::new(),+ paragraphs: Vec::new(),+ shape: text::TextShape::Point,+ orientation: text::Orientation::Horizontal,+ antialias: text::AntiAlias::Smooth,+ warp: None,+ }+ }+}++impl TextLayer {+ /// Character runs covering exactly `text.len()` bytes, each on a char boundary.+ pub fn char_runs(&self) -> Vec<text::TextRun> {+ let base = text::CharStyle { font_family: self.font_family.clone(), size_pt: self.size_pt, color: self.color, ..Default::default() };+ normalize_runs(&self.text, self.runs.iter().map(|r| (r.len, r.style.clone())).collect(), base)+ .into_iter()+ .map(|(len, style)| text::TextRun { len, style })+ .collect()+ }+ /// Paragraph runs covering exactly `text.len()` bytes.+ pub fn paragraph_runs(&self) -> Vec<text::ParagraphRun> {+ normalize_runs(&self.text, self.paragraphs.iter().map(|r| (r.len, r.style.clone())).collect(), text::ParagraphStyle::default())+ .into_iter()+ .map(|(len, style)| text::ParagraphRun { len, style })+ .collect()+ }+ /// Copies the first run's family, size and colour into the summary fields.+ pub fn sync_summary(&mut self) {+ if let Some(r) = self.runs.first() {+ self.font_family = r.style.font_family.clone();+ self.size_pt = r.style.size_pt;+ self.color = r.style.color;+ }+ }+}++/// Stretches/truncates `(len, style)` runs to cover `text` exactly, snapping to char boundaries+/// and dropping empty runs (keeps one run for empty text).+fn normalize_runs<S: Clone>(text: &str, runs: Vec<(usize, S)>, base: S) -> Vec<(usize, S)> {+ let total = text.len();+ if total == 0 {+ return vec![(0, runs.into_iter().next().map_or(base, |r| r.1))];+ }+ let mut out: Vec<(usize, S)> = Vec::new();+ let mut at = 0usize;+ for (len, style) in runs {+ if at >= total {+ break;+ }+ let mut end = (at + len).min(total);+ while !text.is_char_boundary(end) {+ end += 1;+ }+ if end > at {+ out.push((end - at, style));+ at = end;+ }+ }+ if at < total {+ match out.last_mut() {+ Some(last) => last.0 += total - at,+ None => out.push((total, base.clone())),+ }+ }+ if out.is_empty() {+ out.push((0, base));+ }+ out}#[derive(Clone, Debug, PartialEq)]@@ -225,6 +341,9 @@ pub struct Layer {/// Clipped to the layer below (clipping mask).pub clipped: bool,pub mask: Option<LayerMask>,+ /// Vector mask (Layer › Vector Mask), applied together with `mask`. Shape layers keep their+ /// outline in [`ShapeLayer::path`] instead.+ pub vector_mask: Option<VectorMask>,pub effects: Effects,pub label: LabelColor,pub content: LayerContent,@@ -255,6 +374,7 @@ impl Layer {fill_opacity: 1.0,clipped: false,mask: None,+ vector_mask: None,effects: Effects { enabled: true, ..Default::default() },label: LabelColor::None,content,@@ -364,6 +484,12 @@ pub struct Document {pub metadata: Metadata,/// Global light used by layer effects (PSD resources 1037/1049).pub global_light: GlobalLight,+ /// Saved paths (Paths panel), top to bottom.+ pub paths: Vec<NamedPath>,+ /// The (unsaved) work path.+ pub work_path: Option<Path>,+ /// Clipping path used on export (names one of `paths`).+ pub clipping_path: Option<ClippingPath>,}/// Where a layer lives in the tree: indices from the root down.@@ -385,6 +511,9 @@ impl Document {selection: None,metadata: Metadata::default(),global_light: GlobalLight::default(),+ paths: Vec::new(),+ work_path: None,+ clipping_path: None,}}@@ -632,3 +761,15 @@ mod tests {assert_eq!(snap.layers[0].surface().unwrap().pixel(0, 0), vec![1.0; 4]);}}++#[cfg(test)]+mod id_tests {+ #[test]+ fn ensure_ids_above_advances_counter() {+ let far = super::LayerId::fresh().0 + 1000;+ super::ensure_ids_above(far);+ assert!(super::LayerId::fresh().0 > far);+ super::ensure_ids_above(3); // never moves backwards+ assert!(super::DocId::fresh().0 > far);+ }+}diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rsnew file mode 100644index 000000000..ba9037c37--- /dev/null+++ b/crates/doc/src/text.rs@@ -0,0 +1,332 @@+//! Typed style model for type (text) layers: character runs, paragraph runs, point/box shape and+//! warp. Pure data; layout and rendering live in `photocraft-text`.+//!+//! Units follow Photoshop's Character/Paragraph panels: sizes, leading, indents and spacing are in+//! **points** (converted to pixels with the document resolution: `px = pt * dpi / 72`), tracking+//! is in 1/1000 em, and box bounds are in text-space **pixels** (before the layer transform).+//!+//! Runs cover the text by **UTF-8 byte length**, in order. A run list whose lengths don't add up+//! to `text.len()` is normalised by [`crate::TextLayer::char_runs`] (the last run is stretched or+//! truncated), so edits never produce unstyled text.++use photocraft_color::Color;+use serde::{Deserialize, Serialize};++/// Kerning mode (Photoshop: Metrics, Optical, 0).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum Kerning {+ /// Font kerning (`kern` feature).+ #[default]+ Metrics,+ /// Photoshop's optical kerning; rendered like `Metrics` for now.+ Optical,+ /// No kerning.+ Off,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum Caps {+ #[default]+ Normal,+ SmallCaps,+ AllCaps,+}++/// An OpenType feature setting, e.g. `{ tag: "ss01", value: 1 }`.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct FontFeature {+ pub tag: String,+ pub value: u16,+}++/// A variable-font axis setting, e.g. `{ axis: "wght", value: 650.0 }`.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct FontVariation {+ pub axis: String,+ pub value: f32,+}++/// Character style (Photoshop's Character panel).+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct CharStyle {+ /// Family name ("Inter"). Empty = the default family.+ pub font_family: String,+ /// Face style name as shown in the UI ("Bold Italic"); informational, `weight`/`italic` rule.+ pub font_style: String,+ /// PostScript name from a PSD (`ArialMT`), used to find the exact face when present.+ pub postscript_name: Option<String>,+ /// CSS-style weight, 100–900.+ pub weight: u16,+ pub italic: bool,+ pub size_pt: f32,+ pub color: Color,+ /// Letter spacing in 1/1000 em.+ pub tracking: f32,+ /// Baseline-to-baseline distance in points; `None` = auto (paragraph `auto_leading` × size).+ pub leading_pt: Option<f32>,+ /// Positive raises the text.+ pub baseline_shift_pt: f32,+ pub horizontal_scale: f32,+ pub vertical_scale: f32,+ pub underline: bool,+ pub strikethrough: bool,+ pub faux_bold: bool,+ pub faux_italic: bool,+ pub kerning: Kerning,+ pub caps: Caps,+ /// Standard ligatures (`liga`/`clig`).+ pub ligatures: bool,+ /// Discretionary ligatures (`dlig`).+ pub discretionary_ligatures: bool,+ /// Extra OpenType features (`ss01`, `onum`, `tnum`, …).+ pub features: Vec<FontFeature>,+ /// Variable-font axis values.+ pub variations: Vec<FontVariation>,+ /// BCP-47 language tag (affects shaping and line breaking).+ pub language: Option<String>,+}++impl Default for CharStyle {+ fn default() -> Self {+ Self {+ font_family: String::new(),+ font_style: String::new(),+ postscript_name: None,+ weight: 400,+ italic: false,+ size_pt: 12.0,+ color: Color::BLACK,+ tracking: 0.0,+ leading_pt: None,+ baseline_shift_pt: 0.0,+ horizontal_scale: 1.0,+ vertical_scale: 1.0,+ underline: false,+ strikethrough: false,+ faux_bold: false,+ faux_italic: false,+ kerning: Kerning::Metrics,+ caps: Caps::Normal,+ ligatures: true,+ discretionary_ligatures: false,+ features: Vec::new(),+ variations: Vec::new(),+ language: None,+ }+ }+}++/// A character style applied to `len` UTF-8 bytes.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct TextRun {+ pub len: usize,+ pub style: CharStyle,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum TextAlign {+ #[default]+ Left,+ Center,+ Right,+ /// Justified, last line left.+ JustifyLeft,+ /// Justified, last line centered.+ JustifyCenter,+ /// Justified, last line right.+ JustifyRight,+ /// Justified including the last line.+ JustifyAll,+}++impl TextAlign {+ pub fn is_justified(self) -> bool {+ matches!(+ self,+ Self::JustifyLeft | Self::JustifyCenter | Self::JustifyRight | Self::JustifyAll+ )+ }+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum TextDirection {+ /// From the first strong character (Unicode bidi rules).+ #[default]+ Auto,+ Ltr,+ Rtl,+}++/// Paragraph style (Photoshop's Paragraph panel).+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct ParagraphStyle {+ pub align: TextAlign,+ pub first_line_indent_pt: f32,+ pub start_indent_pt: f32,+ pub end_indent_pt: f32,+ pub space_before_pt: f32,+ pub space_after_pt: f32,+ /// Auto leading as a multiple of the font size (Photoshop default 1.2).+ pub auto_leading: f32,+ pub direction: TextDirection,+ pub hyphenate: bool,+}++impl Default for ParagraphStyle {+ fn default() -> Self {+ Self {+ align: TextAlign::Left,+ first_line_indent_pt: 0.0,+ start_indent_pt: 0.0,+ end_indent_pt: 0.0,+ space_before_pt: 0.0,+ space_after_pt: 0.0,+ auto_leading: 1.2,+ direction: TextDirection::Auto,+ hyphenate: false,+ }+ }+}++/// A paragraph style applied to `len` UTF-8 bytes (whole paragraphs, including the break).+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct ParagraphRun {+ pub len: usize,+ pub style: ParagraphStyle,+}++/// Point text grows from its anchor (text-space origin = first baseline at the anchor);+/// paragraph (box) text wraps inside a rectangle.+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]+pub enum TextShape {+ #[default]+ Point,+ /// Text-space pixels, before the layer transform.+ Box {+ x: f32,+ y: f32,+ width: f32,+ height: f32,+ },+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum Orientation {+ #[default]+ Horizontal,+ /// Vertical type: modelled for round trip, rendered horizontally for now.+ Vertical,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum AntiAlias {+ None,+ Sharp,+ Crisp,+ Strong,+ #[default]+ Smooth,+}++/// Warp text settings (Photoshop `warp` descriptor). Placeholder: stored and round-tripped,+/// not yet applied by the renderer.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct TextWarp {+ /// `warpNone`, `warpArc`, `warpFlag`, …+ pub style: String,+ /// Bend in percent (-100..100).+ pub value: f32,+ pub horizontal_distortion: f32,+ pub vertical_distortion: f32,+ /// Horizontal (true) or vertical warp axis.+ pub horizontal: bool,+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::TextLayer;++ fn run(len: usize, size: f32) -> TextRun {+ TextRun {+ len,+ style: CharStyle {+ size_pt: size,+ ..Default::default()+ },+ }+ }++ #[test]+ fn runs_are_normalized_to_the_text() {+ let base = TextLayer {+ text: "héllo".into(),+ size_pt: 9.0,+ ..Default::default()+ };+ // No runs: one run from the summary fields.+ let r = base.char_runs();+ assert_eq!(r.len(), 1);+ assert_eq!((r[0].len, r[0].style.size_pt), (6, 9.0));+ // Too short: last run stretched. Split inside 'é' snaps to the char boundary.+ let t = TextLayer {+ runs: vec![run(2, 10.0), run(1, 20.0)],+ ..base.clone()+ };+ let r = t.char_runs();+ assert_eq!(r.iter().map(|r| r.len).collect::<Vec<_>>(), vec![3, 3]);+ // Too long: truncated; empty runs dropped.+ let t = TextLayer {+ runs: vec![run(0, 1.0), run(100, 10.0), run(5, 20.0)],+ ..base.clone()+ };+ let r = t.char_runs();+ assert_eq!(r.len(), 1);+ assert_eq!((r[0].len, r[0].style.size_pt), (6, 10.0));+ // Empty text keeps the first run's style.+ let t = TextLayer {+ text: String::new(),+ runs: vec![run(0, 33.0)],+ ..base.clone()+ };+ assert_eq!(t.char_runs()[0].style.size_pt, 33.0);+ assert_eq!(t.paragraph_runs().len(), 1);+ }++ #[test]+ fn summary_follows_first_run() {+ let mut t = TextLayer {+ text: "ab".into(),+ runs: vec![TextRun {+ len: 2,+ style: CharStyle {+ font_family: "X".into(),+ size_pt: 7.0,+ ..Default::default()+ },+ }],+ ..Default::default()+ };+ t.sync_summary();+ assert_eq!((t.font_family.as_str(), t.size_pt), ("X", 7.0));+ }++ #[test]+ fn styles_serialize() {+ let s = CharStyle {+ features: vec![FontFeature {+ tag: "ss01".into(),+ value: 1,+ }],+ ..Default::default()+ };+ let v = serde_json::to_value(&s).unwrap();+ let back: CharStyle = serde_json::from_value(v).unwrap();+ assert_eq!(back, s);+ // Missing keys take defaults.+ let p: ParagraphStyle = serde_json::from_str(r#"{"align":"Center"}"#).unwrap();+ assert_eq!((p.align, p.auto_leading), (TextAlign::Center, 1.2));+ }+}diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rsnew file mode 100644index 000000000..e3e17e7da--- /dev/null+++ b/crates/doc/src/vector.rs@@ -0,0 +1,309 @@+//! Vector data: paths (Pen tool), shape layers, saved/work paths and vector masks. Pure data;+//! rasterization lives in `photocraft-vector`, PSD mapping in `photocraft-io`.+//!+//! Coordinates are **document pixels** (f64, y down), cubic Bézier. A subpath is a list of knots;+//! segment `i` runs from `knots[i].anchor` via `knots[i].out_ctrl` and `knots[i+1].in_ctrl` to+//! `knots[i+1].anchor` (closed subpaths add the segment back to the first knot). A knot whose+//! control points equal its anchor is a corner with straight segments.+//!+//! Path operations follow Photoshop: every subpath is filled on its own (with the path's+//! [`FillRule`]) and folded, in order, into the result with its [`PathOp`]; the first subpath+//! always acts as "combine" (see [`Path::effective_op`]; verified against Photoshop's pixels in+//! the PSD corpus). [`Path::inverted`] inverts the final area. A vector mask without subpaths+//! reveals everything (Photoshop's fresh "Add Vector Mask").++use std::sync::Arc;++use photocraft_color::Color;+use photocraft_geom::{Affine, Point};+use serde::{Deserialize, Serialize};++use crate::{Fill, Surface};++/// A Bézier knot (anchor + two control points).+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+pub struct Knot {+ pub anchor: Point,+ /// Control point of the segment arriving at this knot.+ pub in_ctrl: Point,+ /// Control point of the segment leaving this knot.+ pub out_ctrl: Point,+ /// Smooth (linked) knot: the Pen tool keeps both handles collinear.+ #[serde(default)]+ pub smooth: bool,+}++impl Knot {+ /// A corner knot with retracted handles.+ pub fn corner(x: f64, y: f64) -> Self {+ let p = Point::new(x, y);+ Knot { anchor: p, in_ctrl: p, out_ctrl: p, smooth: false }+ }+ /// A smooth knot with explicit handles.+ pub fn smooth(anchor: Point, in_ctrl: Point, out_ctrl: Point) -> Self {+ Knot { anchor, in_ctrl, out_ctrl, smooth: true }+ }+ pub fn transform(&self, a: &Affine) -> Knot {+ Knot { anchor: a.apply(self.anchor), in_ctrl: a.apply(self.in_ctrl), out_ctrl: a.apply(self.out_ctrl), smooth: self.smooth }+ }+}++/// How a subpath combines with the subpaths before it (Photoshop's path operations).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum PathOp {+ /// Combine shapes (union).+ #[default]+ Combine,+ /// Subtract front shape.+ Subtract,+ /// Intersect shape areas.+ Intersect,+ /// Exclude overlapping shapes (xor).+ Exclude,+}++/// Winding rule used to fill each subpath.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum FillRule {+ #[default]+ NonZero,+ EvenOdd,+}++#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct Subpath {+ pub closed: bool,+ pub knots: Vec<Knot>,+ #[serde(default)]+ pub op: PathOp,+}++impl Subpath {+ /// Closed polygon through `pts` (corner knots).+ pub fn polygon(pts: &[(f64, f64)]) -> Self {+ Subpath { closed: true, knots: pts.iter().map(|&(x, y)| Knot::corner(x, y)).collect(), op: PathOp::Combine }+ }+ /// Open polyline through `pts`.+ pub fn polyline(pts: &[(f64, f64)]) -> Self {+ Subpath { closed: false, ..Self::polygon(pts) }+ }+ pub fn with_op(mut self, op: PathOp) -> Self {+ self.op = op;+ self+ }+ /// Cubic segments `[p0, c1, c2, p1]`.+ pub fn segments(&self) -> Vec<[Point; 4]> {+ let n = self.knots.len();+ if n < 2 {+ return Vec::new();+ }+ let count = if self.closed { n } else { n - 1 };+ (0..count)+ .map(|i| {+ let a = &self.knots[i];+ let b = &self.knots[(i + 1) % n];+ [a.anchor, a.out_ctrl, b.in_ctrl, b.anchor]+ })+ .collect()+ }+}++/// A vector path: subpaths plus how they are filled and combined.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct Path {+ pub subpaths: Vec<Subpath>,+ #[serde(default)]+ pub fill_rule: FillRule,+ /// The final area is inverted (PSD vector-mask invert flag / "initial fill rule" = 1).+ #[serde(default)]+ pub inverted: bool,+}++impl Path {+ pub fn new(subpaths: Vec<Subpath>) -> Self {+ Path { subpaths, fill_rule: FillRule::NonZero, inverted: false }+ }+ pub fn is_empty(&self) -> bool {+ self.subpaths.iter().all(|s| s.knots.is_empty())+ }+ /// The operation actually applied for subpath `i`: Photoshop applies the first subpath as+ /// "combine" whatever its stored operation (a lone "intersect" shape still draws).+ pub fn effective_op(&self, i: usize) -> PathOp {+ if i == 0 { PathOp::Combine } else { self.subpaths[i].op }+ }+ pub fn transform(&self, a: &Affine) -> Path {+ let mut p = self.clone();+ for s in &mut p.subpaths {+ for k in &mut s.knots {+ *k = k.transform(a);+ }+ }+ p+ }+ /// Bounds of all anchors and control points `(x0, y0, x1, y1)` (a superset of the curve).+ pub fn control_bounds(&self) -> Option<(f64, f64, f64, f64)> {+ let mut it = self.subpaths.iter().flat_map(|s| s.knots.iter()).flat_map(|k| [k.anchor, k.in_ctrl, k.out_ctrl]);+ let first = it.next()?;+ Some(it.fold((first.x, first.y, first.x, first.y), |b, p| (b.0.min(p.x), b.1.min(p.y), b.2.max(p.x), b.3.max(p.y))))+ }+}++/// A document-level path (Paths panel entry).+#[derive(Clone, Debug, Default, PartialEq)]+pub struct NamedPath {+ pub name: String,+ pub path: Path,+ /// Original PSD path resource data; reused on export while it still decodes to `path`.+ pub psd_raw: Option<Arc<Vec<u8>>>,+}++/// The document's clipping path (PSD resource 2999): which saved path clips on export.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct ClippingPath {+ pub name: String,+ /// Output flatness in device pixels (0 = printer default).+ pub flatness: f32,+}++/// A layer's vector mask (Layer › Vector Mask).+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct VectorMask {+ pub path: Path,+ pub enabled: bool,+ /// Moves with the layer.+ pub linked: bool,+ /// Density `0..=1` (Properties panel), like [`crate::LayerMask::density`].+ pub density: f32,+ /// Feather radius in px (stored; rendered unfeathered for now).+ pub feather: f32,+}++impl VectorMask {+ pub fn new(path: Path) -> Self {+ VectorMask { path, enabled: true, linked: true, density: 1.0, feather: 0.0 }+ }+}++/// Where a stroke sits relative to the path.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum StrokeAlign {+ Inside,+ #[default]+ Center,+ Outside,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum LineCap {+ #[default]+ Butt,+ Round,+ Square,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum LineJoin {+ #[default]+ Miter,+ Round,+ Bevel,+}++/// Shape stroke (Photoshop's shape "Stroke" options, not the layer-style stroke).+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct ShapeStroke {+ /// Width in px.+ pub width: f32,+ pub paint: Fill,+ pub opacity: f32,+ pub align: StrokeAlign,+ pub cap: LineCap,+ pub join: LineJoin,+ /// Miter limit as a multiple of the width (Photoshop default 100 → effectively always+ /// mitered; SVG-style 4 is common elsewhere).+ pub miter_limit: f32,+ /// Dash pattern in multiples of the stroke width (Photoshop's convention); empty = solid.+ pub dashes: Vec<f32>,+ /// Dash offset in multiples of the width.+ pub dash_offset: f32,+}++impl Default for ShapeStroke {+ fn default() -> Self {+ ShapeStroke {+ width: 3.0,+ paint: Fill::Solid(Color::BLACK),+ opacity: 1.0,+ align: StrokeAlign::Center,+ cap: LineCap::Butt,+ join: LineJoin::Miter,+ miter_limit: 100.0,+ dashes: Vec::new(),+ dash_offset: 0.0,+ }+ }+}++/// Parametric ("live") shape the path was generated from, kept for re-editing (Properties panel).+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "camelCase")]+pub enum LiveShape {+ /// Rectangle `[x, y, w, h]` with corner radii `[tl, tr, br, bl]` (all zero = sharp).+ Rect { rect: [f64; 4], radii: [f64; 4] },+ Ellipse { rect: [f64; 4] },+ /// Regular polygon or star inscribed in `rect`; `star_ratio` = inner/outer radius (1 = polygon).+ Polygon { rect: [f64; 4], sides: u32, star_ratio: f64 },+ /// Line from `from` to `to` drawn as a filled bar `weight` px thick.+ Line { from: [f64; 2], to: [f64; 2], weight: f64 },+}++/// A shape layer: a filled and/or stroked path.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct ShapeLayer {+ pub path: Path,+ /// `None` = no fill (Photoshop's fill "none").+ pub fill: Option<Fill>,+ pub stroke: Option<ShapeStroke>,+ pub live: Option<LiveShape>,+ /// Rasterized appearance (from PSD or `photocraft-vector`).+ pub cache: Option<Surface>,+ /// Data of the PSD vector mask block (`vsms`, else `vmsk`). On export it replaces that entry+ /// in [`crate::Layer::psd_blocks`] while it still decodes to `path`.+ pub psd_raw: Option<Arc<Vec<u8>>>,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn segments_open_and_closed() {+ let s = Subpath::polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]);+ assert_eq!(s.segments().len(), 3);+ let o = Subpath::polyline(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]);+ assert_eq!(o.segments().len(), 2);+ assert_eq!(o.segments()[1][3], Point::new(10.0, 10.0));+ }++ #[test]+ fn first_op_is_combine_and_bounds() {+ let p = Path::new(vec![Subpath::polygon(&[(1.0, 2.0), (5.0, 2.0), (5.0, 9.0)]).with_op(PathOp::Intersect)]);+ assert_eq!(p.effective_op(0), PathOp::Combine);+ assert_eq!(p.control_bounds(), Some((1.0, 2.0, 5.0, 9.0)));+ let t = p.transform(&Affine::translate(1.0, 1.0));+ assert_eq!(t.control_bounds(), Some((2.0, 3.0, 6.0, 10.0)));+ }++ #[test]+ fn serde_roundtrip() {+ let p = Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (3.0, 4.0)]).with_op(PathOp::Exclude)]);+ let s = ShapeStroke { dashes: vec![2.0, 1.0], ..Default::default() };+ let j = serde_json::to_string(&(&p, &s, &LiveShape::Rect { rect: [0.0; 4], radii: [1.0; 4] })).unwrap();+ let back: (Path, ShapeStroke, LiveShape) = serde_json::from_str(&j).unwrap();+ assert_eq!(back.0, p);+ assert_eq!(back.1, s);+ let v: Path = serde_json::from_str(r#"{"subpaths":[{"closed":true,"knots":[]}]}"#).unwrap();+ assert_eq!(v.subpaths[0].op, PathOp::Combine);+ }+}diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.tomlindex c97e48250..61a9b8b8a 100644--- a/crates/engine/Cargo.toml+++ b/crates/engine/Cargo.toml@@ -19,3 +19,5 @@ serde_json = { workspace = true }thiserror = { workspace = true }photocraft-paint = { workspace = true }photocraft-algo = { workspace = true }+photocraft-text = { workspace = true }+photocraft-vector = { workspace = true }diff --git a/crates/engine/examples/bench_smartselect_cmds.rs b/crates/engine/examples/bench_smartselect_cmds.rsnew file mode 100644index 000000000..398527f60--- /dev/null+++ b/crates/engine/examples/bench_smartselect_cmds.rs@@ -0,0 +1,59 @@+//! End-to-end timing of the smart selection commands (including sampling the layer and storing+//! the selection / layer) on a 6016×6016 8-bit document: a textured disc on a noisy background.+//! `cargo run --release -p photocraft-engine --example bench_smartselect_cmds [size]`+use std::time::Instant;++use photocraft_algo::segment::Rng;+use photocraft_engine::Session;+use photocraft_geom::Rect;+use serde_json::json;++fn main() {+ let n: i32 = std::env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(6016);+ let (c, rad) = (n as f32 / 2.0, n as f32 / 3.0);+ let mut s = Session::new();+ s.execute("file.new", json!({"width": n, "height": n})).unwrap();+ s.edit("fill", |doc, _| {+ let bg = doc.layers[0].surface_mut().unwrap();+ let ch = bg.channels();+ for band in (0..n).step_by(256) {+ let y1 = (band + 256).min(n);+ let mut data = Vec::with_capacity((n * (y1 - band)) as usize * ch);+ for y in band..y1 {+ let mut rng = Rng::new(y as u64 + 1);+ for x in 0..n {+ let (dx, dy) = (x as f32 + 0.5 - c, y as f32 + 0.5 - c);+ let noise = 0.05 * rng.normal();+ let p = if dx * dx + dy * dy <= rad * rad {+ let t = ((x + y) as f32 * 0.05).sin() * 0.5 + 0.5;+ [0.85 + 0.05 * t + noise, 0.2 + 0.3 * t + noise, 0.15 + noise]+ } else {+ [0.25 + noise, 0.45 + noise, 0.7 + noise]+ };+ data.extend(p.iter().map(|v| v.clamp(0.0, 1.0)).take(ch.min(3)));+ if ch == 4 {+ data.push(1.0);+ }+ }+ }+ bg.write_region(Rect::new(0, band, n, y1), &data);+ }+ Ok(())+ })+ .unwrap();+ let time = |s: &mut Session, label: &str, id: &str, p: serde_json::Value| {+ let t = Instant::now();+ let r = s.execute(id, p).unwrap();+ println!("{label}: {:.2?} {r}", t.elapsed());+ };+ let x = c + rad - 60.0;+ time(&mut s, "select.quick (brush 30)", "select.quick", json!({"points": [[x, c - 30.0], [x, c + 30.0]], "size": 30}));+ time(&mut s, "select.quick (brush 30, add)", "select.quick", json!({"points": [[x - 100.0, c]], "size": 30}));+ let m = (rad * 1.15) as i32;+ time(&mut s, "select.object", "select.object", json!({"rect": [c as i32 - m, c as i32 - m, 2 * m, 2 * m]}));+ time(&mut s, "select.refineEdge (radius 20)", "select.refineEdge", json!({"radius": 20}));+ s.execute("edit.undo", json!({})).unwrap();+ time(&mut s, "select.refineEdge (radius 20, newLayerWithMask + decontaminate)", "select.refineEdge", json!({"radius": 20, "decontaminate": true}));+ time(&mut s, "select.subject", "select.subject", json!({}));+ time(&mut s, "select.focusArea", "select.focusArea", json!({}));+}diff --git a/crates/engine/examples/retouch_bench.rs b/crates/engine/examples/retouch_bench.rsnew file mode 100644index 000000000..c260f8aad--- /dev/null+++ b/crates/engine/examples/retouch_bench.rs@@ -0,0 +1,59 @@+//! Timing: Healing Brush and Spot Healing dab cost on a 6016×6016 document.+//! `cargo run --release -p photocraft-engine --example retouch_bench [side] [depth]`+//!+//! Each measurement is one single-dab stroke through the full command path (`Session::execute`:+//! undo snapshot, source sampling, solve/fill, composite), on a textured area of the canvas.+use std::time::Instant;++use photocraft_engine::Session;+use photocraft_geom::Rect;+use serde_json::json;++fn main() {+ let side: u32 = std::env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(6016);+ let depth: u64 = std::env::args().nth(2).and_then(|v| v.parse().ok()).unwrap_or(8);+ let mut s = Session::new();+ s.execute("file.new", json!({"width": side, "height": side, "depth": depth})).unwrap();+ // Texture a 2048² area in the middle (the rest stays white) with a gradient, noise and blemishes.+ let area = Rect::new(2000, 2000, 4048, 4048).intersect(&Rect::new(0, 0, side as i32, side as i32));+ s.edit("texture", |doc, active| {+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();+ let fmt = surf.format();+ let mut data = Vec::with_capacity(area.width() as usize * area.height() as usize * 4);+ for y in area.y0..area.y1 {+ for x in area.x0..area.x1 {+ let n = ((x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663)) as u32 % 1000) as f32 / 1000.0 * 0.08 - 0.04;+ let blemish = (x % 400 - 200).abs() < 8 && (y % 400 - 200).abs() < 8;+ let v = if blemish { [0.05, 0.05, 0.05, 1.0] } else { [0.3 + 0.0002 * x as f32 + n, 0.4 + ((x + y) as f32 * 0.01).sin() * 0.1 + n, 0.5 + n, 1.0] };+ data.extend(photocraft_raster::from_rgba(&fmt, v));+ }+ }+ surf.write_region(area, &data);+ Ok(())+ })+ .unwrap();+ println!("document {side}x{side}, {depth}-bit RGB");+ let mut k = 0;+ let mut spot = || {+ k += 1;+ (2200 + (k % 4) * 400, 2200 + (k / 4 % 4) * 400)+ };+ for size in [50.0, 100.0, 200.0, 300.0] {+ let (x, y) = spot();+ let t = Instant::now();+ s.execute("paint.healingBrush", json!({"points": [[x, y]], "offset": [-150, -130], "size": size, "hardness": 50})).unwrap();+ println!("healingBrush size {size:>4}: {:>8.1?}", t.elapsed());+ }+ for kind in ["contentAware", "proximityMatch", "createTexture"] {+ for size in [50.0, 100.0, 200.0, 300.0] {+ let (x, y) = spot();+ let t = Instant::now();+ s.execute("paint.spotHealing", json!({"points": [[x, y]], "size": size, "hardness": 50, "type": kind})).unwrap();+ println!("spotHealing {kind:<15} size {size:>4}: {:>8.1?}", t.elapsed());+ }+ }+ // A short multi-dab heal stroke (spacing 25 %): the whole stroke is solved at once.+ let t = Instant::now();+ s.execute("paint.healingBrush", json!({"points": [[2300, 3500], [2700, 3500]], "offset": [0, -300], "size": 100, "hardness": 50})).unwrap();+ println!("healingBrush stroke 400 px long, size 100: {:.1?}", t.elapsed());+}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 0c030b538..413be4c73 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -45,6 +45,30 @@ fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> {let l = d.doc.layer(d.active_layer.unwrap()).unwrap();if matches!(l.content, LayerContent::Raster(_)) { Ok(()) } else { Err(format!("active layer is a {} layer, not a pixel layer", l.content.kind_name())) }}+/// A layer that can be painted: pixels, or any layer with a mask (paint with `"target":"mask"`).+pub(crate) fn has_paintable(s: &Session) -> std::result::Result<(), String> {+ has_layer(s)?;+ let d = s.active().unwrap();+ let l = d.doc.layer(d.active_layer.unwrap()).unwrap();+ if matches!(l.content, LayerContent::Raster(_)) || l.mask.is_some() { Ok(()) } else { Err(format!("active layer is a {} layer without a mask", l.content.kind_name())) }+}++/// Surface a paint command writes to: the layer's pixels, or its mask with `"target":"mask"`.+pub(crate) fn paint_surface<'a>(l: &'a mut Layer, p: &Value) -> Result<&'a mut photocraft_raster::Surface> {+ if !is_mask_target(p) && (l.locks.pixels || l.locks.all) {+ return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name)));+ }+ if is_mask_target(p) {+ l.mask.as_mut().map(|m| &mut m.surface).ok_or_else(|| EngineError::Other("layer has no mask".into()))+ } else {+ l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))+ }+}++pub(crate) fn is_mask_target(p: &Value) -> bool {+ p.get("target").and_then(Value::as_str) == Some("mask")+}+fn can_undo(s: &Session) -> std::result::Result<(), String> {s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to undo".into())}@@ -76,7 +100,7 @@ fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }}/// Integer parameter that also accepts JSON floats (UIs send `12.0`); rounds.-fn int(p: &Value, key: &str) -> Option<i64> {+pub(crate) fn int(p: &Value, key: &str) -> Option<i64> {p.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64)))}@@ -153,26 +177,39 @@ pub fn adjustment_from_params(kind: &str, p: &Value) -> Adjustment {"exposure" => Adjustment::Exposure { exposure: f32_or(p, "exposure", 0.0), offset: f32_or(p, "offset", 0.0), gamma: f32_or(p, "gamma", 1.0) },"vibrance" => Adjustment::Vibrance { vibrance: f32_or(p, "vibrance", 0.0), saturation: f32_or(p, "saturation", 0.0) },"levels" => {- let mut a = Adjustment::identity_levels();- if let Adjustment::Levels { master, .. } = &mut a {- master.in_black = f32_or(p, "inBlack", 0.0) / 255.0;- master.in_white = f32_or(p, "inWhite", 255.0) / 255.0;- master.gamma = f32_or(p, "gamma", 1.0);- }- a+ // Master keys at the top level; per channel under "red"/"green"/"blue" (0–255 levels).+ let ch = |p: &Value| photocraft_doc::adjust::LevelsChannel {+ in_black: f32_or(p, "inBlack", 0.0) / 255.0,+ in_white: f32_or(p, "inWhite", 255.0) / 255.0,+ gamma: f32_or(p, "gamma", 1.0).clamp(0.01, 9.99),+ out_black: f32_or(p, "outBlack", 0.0) / 255.0,+ out_white: f32_or(p, "outWhite", 255.0) / 255.0,+ };+ let per = |k: &str| p.get(k).map(ch).unwrap_or_default();+ Adjustment::Levels { master: ch(p), per_channel: [per("red"), per("green"), per("blue")] }}"curves" => {- let mut a = Adjustment::identity_curves();- if let (Adjustment::Curves { master, .. }, Some(Value::Array(pts))) = (&mut a, p.get("points")) {- let parsed: Vec<CurvePoint> = pts+ // "points" = master curve; "red"/"green"/"blue" = per-channel curves ([[in, out], …], 0–255).+ let parse = |v: Option<&Value>| -> Option<Vec<CurvePoint>> {+ let pts: Vec<CurvePoint> = v?+ .as_array()?.iter().filter_map(|v| {let a = v.as_array()?;Some(CurvePoint { input: a.first()?.as_f64()? as f32 / 255.0, output: a.get(1)?.as_f64()? as f32 / 255.0 })}).collect();- if parsed.len() >= 2 {- *master = parsed;+ (pts.len() >= 2).then_some(pts)+ };+ let mut a = Adjustment::identity_curves();+ if let Adjustment::Curves { master, per_channel } = &mut a {+ if let Some(m) = parse(p.get("points")) {+ *master = m;+ }+ for (i, k) in ["red", "green", "blue"].iter().enumerate() {+ if let Some(c) = parse(p.get(*k)) {+ per_channel[i] = c;+ }}}a@@ -351,7 +388,7 @@ fn build() -> Vec<CommandSpec> {})?;Ok(json!({ "layer": gid.0 }))}),- cmd!("layer.duplicate", "Duplicate Layer…", ["Layer"], Some("Cmd+J"), r##"{"layer":id?}"##, has_layer, |s, p| {+ cmd!("layer.duplicate", "Duplicate Layer…", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| {let id = layer_param(s, p)?;let nid = s.edit("Duplicate Layer", |doc, active| {let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate();@@ -378,7 +415,7 @@ fn build() -> Vec<CommandSpec> {s.select_layer(LayerId(id))?;Ok(Value::Null)}),- cmd!("layer.setProps", "Layer Properties", [], None, r##"{"layer":id?,"name":str?,"visible":bool?,"opacity":0..1?,"fill":0..1?,"blend":"Multiply|…"?,"clipped":bool?,"locked":bool?}"##, has_layer, |s, p| {+ cmd!("layer.setProps", "Layer Properties", [], None, r##"{"layer":id?,"name":str?,"visible":bool?,"opacity":0..1?,"fill":0..1?,"blend":"Multiply|…"?,"clipped":bool?,"locked":bool?,"locks":{"transparency","pixels","position","artboard","all":bool}?}"##, has_layer, |s, p| {let id = layer_param(s, p)?;let label = if p.get("visible").is_some() && p.as_object().is_some_and(|o| o.len() <= 2) { "Layer Visibility" } else { "Layer Properties" };s.edit(label, |doc, _| {@@ -404,6 +441,19 @@ fn build() -> Vec<CommandSpec> {if let Some(v) = p.get("locked").and_then(Value::as_bool) {l.locks.all = v;}+ if let Some(Value::Object(m)) = p.get("locks") {+ for (k, v) in m {+ let v = v.as_bool().unwrap_or(false);+ match k.as_str() {+ "transparency" => l.locks.transparency = v,+ "pixels" => l.locks.pixels = v,+ "position" => l.locks.position = v,+ "artboard" => l.locks.artboard = v,+ "all" => l.locks.all = v,+ other => return Err(bad("layer.setProps", format!("unknown lock `{other}`"))),+ }+ }+ }Ok(())})?;Ok(Value::Null)@@ -544,11 +594,13 @@ fn build() -> Vec<CommandSpec> {return Ok(Value::Null);}s.edit("Move", |doc, _| {+ let snapshot = doc.clone();let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;if l.locks.position || l.locks.all {return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name)));}- translate_layer(l, dx, dy);+ translate_layer(&snapshot, l, dx, dy);+ crate::vector_cmds::translate_vectors(&snapshot, l, dx as f64, dy as f64);Ok(())})?;Ok(Value::Null)@@ -600,7 +652,7 @@ fn build() -> Vec<CommandSpec> {destructive_adjust(s, "Desaturate", Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false })}),// Paint- cmd!("paint.stroke", "Brush Stroke", [], None, r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"color":"#rrggbb"?=foreground,"erase":bool?,"smoothing":0..1?}"##, has_pixel_layer, |s, p| {+ cmd!("paint.stroke", "Brush Stroke", [], None, r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"color":"#rrggbb"?=foreground,"erase":bool?,"smoothing":0..1?,"target":"pixels|mask"="pixels"}"##, has_paintable, |s, p| {let pts: Vec<StrokePoint> = p.get("points").and_then(Value::as_array)@@ -625,6 +677,8 @@ fn build() -> Vec<CommandSpec> {erase: p.get("erase").and_then(Value::as_bool).unwrap_or(false),..base};+ // On a mask the eraser paints the background colour (Photoshop).+ let brush = if is_mask_target(p) && brush.erase { BrushSettings { erase: false, color: s.tools.background, ..brush } } else { brush };let smoothing = f32_or(p, "smoothing", 0.0);let stroke = Stroke { brush, points: if smoothing > 0.0 { photocraft_paint::smooth(&pts, smoothing) } else { pts } };let id = layer_param(s, p)?;@@ -632,8 +686,8 @@ fn build() -> Vec<CommandSpec> {let dmg = s.edit(label, |doc, _| {let sel = doc.selection.clone();let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;- let lock = l.locks.transparency;- let surf = l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?;+ let lock = l.locks.transparency && !is_mask_target(p);+ let surf = paint_surface(l, p)?;Ok(photocraft_paint::apply_stroke(surf, &stroke, sel.as_ref(), lock))})?;if let Some(st) = s.active_mut() {@@ -739,6 +793,15 @@ fn build() -> Vec<CommandSpec> {}v.extend(crate::layer_style::specs());v.extend(crate::filters::specs());+ v.extend(crate::type_cmds::specs());+ v.extend(crate::transform_cmds::specs());+ v.extend(crate::vector_cmds::specs());+ v.extend(crate::smartselect_cmds::specs());+ v.extend(crate::edit_cmds::specs());+ v.extend(crate::retouch_cmds::specs());+ v.extend(crate::image_cmds::specs());+ v.extend(crate::selection_cmds::specs());+ v.extend(crate::paint_cmds::specs());v}@@ -814,17 +877,24 @@ fn combine(a: &Surface, b: &Surface, area: Rect, f: impl Fn(f32, f32) -> f32) ->out}-fn translate_layer(l: &mut Layer, dx: i32, dy: i32) {+/// Move a layer's pixels, linked mask and type by whole pixels (vectors move via+/// `vector_cmds::translate_vectors`).+fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) {+ use photocraft_algo::resample::translate_surface;if let Some(m) = &mut l.mask&& m.linked{- m.surface = pixels::remap_surface(&m.surface, |x, y| (x + dx, y + dy));+ m.surface = translate_surface(&m.surface, dx, dy);}match &mut l.content {- LayerContent::Raster(s) => *s = pixels::remap_surface(s, |x, y| (x + dx, y + dy)),+ LayerContent::Raster(s) => *s = translate_surface(s, dx, dy),+ LayerContent::Text(t) => {+ t.transform = photocraft_geom::Affine::translate(dx as f64, dy as f64).mul(&t.transform);+ crate::type_cmds::refresh(doc, t);+ }LayerContent::Group(g) => {for c in &mut g.children {- translate_layer(c, dx, dy);+ translate_layer(doc, c, dx, dy);}}_ => {}diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rsnew file mode 100644index 000000000..3fbeb3c64--- /dev/null+++ b/crates/engine/src/edit_cmds.rs@@ -0,0 +1,541 @@+//! Everyday Photoshop commands: clipboard (Cut/Copy/Copy Merged/Paste/Paste in Place), Layer via+//! Copy/Cut, Merge Visible, Auto Tone/Contrast/Color, Toggle Last State and Transform Again.++use photocraft_color::PixelFormat;+use photocraft_doc::adjust::LevelsChannel;+use photocraft_doc::{Adjustment, Document, Layer, LayerContent, LayerId};+use photocraft_geom::Rect;+use photocraft_raster::Surface;+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++/// Pixels on the session clipboard, with where they came from (for Paste in Place).+#[derive(Clone, Debug)]+pub struct Clip {+ pub surface: Surface,+ pub bounds: Rect,+}++fn has_doc(s: &Session) -> std::result::Result<(), String> {+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())+}++fn has_pixels(s: &Session) -> std::result::Result<(), String> {+ let d = s.active().ok_or("no document open")?;+ let l = d.active_layer.and_then(|id| d.doc.layer(id)).ok_or("no active layer")?;+ if l.surface().is_some() && matches!(l.content, LayerContent::Raster(_)) { Ok(()) } else { Err("the active layer has no pixels".into()) }+}++fn has_clip(s: &Session) -> std::result::Result<(), String> {+ has_doc(s)?;+ s.clipboard.as_ref().map(|_| ()).ok_or_else(|| "the clipboard is empty".into())+}++fn active_id(s: &Session) -> Result<LayerId> {+ s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))+}++/// The pixels of `src` inside the selection (or all of them), as a straight-alpha surface.+fn lift(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Clip {+ let fmt = src.format();+ let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true);+ let area = match sel {+ Some(m) => m.content_bounds().intersect(&canvas),+ None => src.content_bounds().intersect(&canvas),+ };+ let mut out = Surface::new(with_alpha);+ if area.is_empty() {+ return Clip { surface: out, bounds: Rect::EMPTY };+ }+ let conv = src.convert(with_alpha);+ let mut px = conv.read_region(area);+ let n = with_alpha.channels();+ if let Some(m) = sel {+ let w = area.width() as usize;+ for (i, p) in px.chunks_exact_mut(n).enumerate() {+ p[n - 1] *= m.sample_channel(area.x0 + (i % w) as i32, area.y0 + (i / w) as i32, 0);+ }+ }+ out.write_region(area, &px);+ out.prune();+ let bounds = out.content_bounds();+ Clip { surface: out, bounds }+}++/// Merged composite of the visible document as a surface in the document's format.+fn merged_surface(doc: &Document) -> Surface {+ let buf = photocraft_compose::flatten(doc);+ let fmt = doc.pixel_format();+ let fmt = PixelFormat::new(fmt.mode, fmt.sample, true);+ let data: Vec<f32> = buf.px.iter().flat_map(|p| photocraft_raster::from_rgba(&fmt, *p)).collect();+ let mut s = Surface::new(fmt);+ s.write_region(doc.bounds(), &data);+ s.prune();+ s+}++fn copy(s: &mut Session, merged: bool) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let canvas = d.doc.bounds();+ let clip = if merged {+ lift(&merged_surface(&d.doc), d.doc.selection.as_ref(), canvas)+ } else {+ let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?;+ let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::Other("the active layer has no pixels".into()))?;+ lift(surf, d.doc.selection.as_ref(), canvas)+ };+ if clip.bounds.is_empty() {+ return Err(EngineError::Other("Could not copy: the selected area is empty".into()));+ }+ let b = clip.bounds;+ s.clipboard = Some(clip);+ Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()]}))+}++fn clear_selected(doc: &mut Document, id: LayerId) -> Result<()> {+ let sel = doc.selection.clone();+ let canvas = doc.bounds();+ let surf = doc.layer_mut(id).and_then(|l| l.surface_mut()).ok_or(EngineError::Other("the active layer has no pixels".into()))?;+ let area = sel.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas));+ crate::pixels::clear_surface(surf, area, sel.as_ref());+ surf.prune();+ Ok(())+}++/// Paste as a new layer. `in_place` keeps the original position; otherwise the pixels are centred+/// on `center` (the view centre from the UI) or the canvas, unless they already overlap the canvas.+fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result<Value> {+ let clip = s.clipboard.clone().ok_or(EngineError::Other("the clipboard is empty".into()))?;+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let canvas = d.doc.bounds();+ let fmt = d.doc.pixel_format();+ let (dx, dy) = if in_place || (clip.bounds.intersect(&canvas) == clip.bounds && p.get("center").is_none()) {+ (0, 0)+ } else {+ let c = p.get("center").and_then(Value::as_array).map(|a| (a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0)));+ let (cx, cy) = c.unwrap_or(((canvas.x0 + canvas.x1) as f64 / 2.0, (canvas.y0 + canvas.y1) as f64 / 2.0));+ let b = clip.bounds;+ ((cx - (b.x0 + b.x1) as f64 / 2.0).round() as i32, (cy - (b.y0 + b.y1) as f64 / 2.0).round() as i32)+ };+ let moved = if dx == 0 && dy == 0 { clip.surface.clone() } else { photocraft_algo::resample::translate_surface(&clip.surface, dx, dy) };+ let target = PixelFormat::new(fmt.mode, fmt.sample, true);+ let surf = if moved.format() == target { moved } else { moved.convert(target) };+ let id = s.edit("Paste", |doc, active| {+ let mut l = Layer::raster(doc.next_layer_name("Layer"), target);+ *l.surface_mut().expect("raster") = surf;+ let id = doc.insert_above(*active, l);+ *active = Some(id);+ doc.selection = None;+ Ok(id)+ })?;+ Ok(json!({"layer": id.0, "offset": [dx, dy]}))+}++fn layer_via(s: &mut Session, cut: bool) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let id = active_id(s)?;+ let has_sel = d.doc.selection.is_some();+ if !has_sel && !cut {+ // No selection: Layer via Copy duplicates the whole layer (Photoshop).+ let nid = s.edit("Layer Via Copy", |doc, active| {+ let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;+ let mut dup = src.duplicate();+ dup.name = format!("{} copy", src.name);+ dup.locks = Default::default();+ let nid = doc.insert_above(Some(id), dup);+ *active = Some(nid);+ Ok(nid)+ })?;+ return Ok(json!({"layer": nid.0}));+ }+ let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::Other("the active layer has no pixels".into()))?;+ let clip = lift(surf, d.doc.selection.as_ref(), d.doc.bounds());+ if clip.bounds.is_empty() {+ return Err(EngineError::Other("Could not complete the command: the selected area is empty".into()));+ }+ let label = if cut { "Layer Via Cut" } else { "Layer Via Copy" };+ let nid = s.edit(label, |doc, active| {+ if cut {+ clear_selected(doc, id)?;+ }+ let mut l = Layer::raster(doc.next_layer_name("Layer"), clip.surface.format());+ *l.surface_mut().expect("raster") = clip.surface;+ let nid = doc.insert_above(Some(id), l);+ *active = Some(nid);+ Ok(nid)+ })?;+ Ok(json!({"layer": nid.0}))+}++fn merge_visible(s: &mut Session) -> Result<Value> {+ s.edit("Merge Visible", |doc, active| {+ let visible: Vec<usize> = doc.layers.iter().enumerate().filter(|(_, l)| l.visible).map(|(i, _)| i).collect();+ if visible.len() < 2 && !visible.iter().any(|i| doc.layers[*i].is_group()) {+ return Err(EngineError::Other("there are not enough visible layers to merge".into()));+ }+ let lowest = visible[0];+ let base = doc.layers[lowest].clone();+ let is_background = base.name == "Background" && base.locks.transparency;+ // Composite of visible layers only (hidden ones stay where they are).+ let mut solo = doc.clone();+ solo.layers.retain(|l| l.visible);+ let buf = photocraft_compose::flatten(&solo);+ let buf = if is_background { buf.over_background([1.0, 1.0, 1.0]) } else { buf };+ let fmt = doc.pixel_format();+ let fmt = if is_background { fmt } else { PixelFormat::new(fmt.mode, fmt.sample, true) };+ let data: Vec<f32> = buf.px.iter().flat_map(|p| photocraft_raster::from_rgba(&fmt, *p)).collect();+ let mut merged = Layer::raster(base.name.clone(), fmt);+ merged.locks = base.locks;+ let surf = merged.surface_mut().expect("raster");+ surf.write_region(doc.bounds(), &data);+ surf.prune();+ let mid = merged.id;+ let mut out = Vec::with_capacity(doc.layers.len());+ for (i, l) in doc.layers.drain(..).enumerate() {+ if i == lowest {+ out.push(merged.clone());+ } else if !l.visible {+ out.push(l);+ }+ }+ doc.layers = out;+ *active = Some(mid);+ Ok(())+ })?;+ Ok(Value::Null)+}++/// Histogram of a pixel layer (8-bit bins per channel: R, G, B) inside the selection.+fn histograms(surf: &Surface, area: Rect) -> [[u64; 256]; 3] {+ let mut h = [[0u64; 256]; 3];+ let step = ((area.width() as u64 * area.height() as u64) / 4_000_000).max(1) as usize; // sample big images+ let mut row = vec![[0u8; 4]; area.width() as usize];+ for y in (area.y0..area.y1).step_by(step.isqrt().max(1)) {+ surf.read_rgba8_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row);+ for p in row.iter().step_by(step.isqrt().max(1)) {+ if p[3] == 0 {+ continue;+ }+ for c in 0..3 {+ h[c][p[c] as usize] += 1;+ }+ }+ }+ h+}++/// Black and white points with `clip` (fraction) clipped at each end.+fn clip_points(h: &[u64; 256], clip: f64) -> (f32, f32) {+ let total: u64 = h.iter().sum();+ if total == 0 {+ return (0.0, 1.0);+ }+ let lim = (total as f64 * clip) as u64;+ let (mut acc, mut lo) = (0u64, 0usize);+ while lo < 254 && acc + h[lo] <= lim {+ acc += h[lo];+ lo += 1;+ }+ let (mut acc, mut hi) = (0u64, 255usize);+ while hi > lo + 1 && acc + h[hi] <= lim {+ acc += h[hi];+ hi -= 1;+ }+ (lo as f32 / 255.0, hi as f32 / 255.0)+}++fn median(h: &[u64; 256]) -> f32 {+ let total: u64 = h.iter().sum();+ let mut acc = 0;+ for (i, v) in h.iter().enumerate() {+ acc += v;+ if acc * 2 >= total {+ return i as f32 / 255.0;+ }+ }+ 0.5+}++/// Image › Auto Tone / Auto Contrast / Auto Color (0.1% clipping, Photoshop's defaults).+fn auto_adjust(s: &mut Session, kind: &str) -> Result<Value> {+ let id = active_id(s)?;+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::Other("the active layer has no pixels".into()))?;+ let area = d.doc.selection.as_ref().map_or(d.doc.bounds(), |m| m.content_bounds()).intersect(&d.doc.bounds());+ let h = histograms(surf, area);+ let clip = 0.001;+ let mut per = [LevelsChannel::default(), LevelsChannel::default(), LevelsChannel::default()];+ match kind {+ "contrast" => {+ // Same points for all channels (preserves colour), from the combined histogram.+ let mut all = [0u64; 256];+ for c in &h {+ for (a, v) in all.iter_mut().zip(c) {+ *a += v;+ }+ }+ let (lo, hi) = clip_points(&all, clip);+ for p in &mut per {+ (p.in_black, p.in_white) = (lo, hi);+ }+ }+ _ => {+ for (c, p) in per.iter_mut().enumerate() {+ (p.in_black, p.in_white) = clip_points(&h[c], clip);+ }+ if kind == "color" {+ // Neutralise midtones: move each channel's median onto the average median.+ let meds: Vec<f32> = (0..3).map(|c| median(&h[c])).collect();+ let target = meds.iter().sum::<f32>() / 3.0;+ for (c, p) in per.iter_mut().enumerate() {+ let t = ((meds[c] - p.in_black) / (p.in_white - p.in_black).max(1e-3)).clamp(0.02, 0.98);+ let want = ((target - p.in_black) / (p.in_white - p.in_black).max(1e-3)).clamp(0.02, 0.98);+ // out = t^(1/g) = want → g = ln t / ln want+ p.gamma = (t.ln() / want.ln()).clamp(0.1, 9.99);+ }+ }+ }+ }+ let adj = Adjustment::Levels { master: LevelsChannel::default(), per_channel: per };+ let label = match kind {+ "contrast" => "Auto Contrast",+ "color" => "Auto Color",+ _ => "Auto Tone",+ };+ s.edit(label, |doc, _| {+ let sel = doc.selection.clone();+ let surf = doc.layer_mut(id).and_then(|l| l.surface_mut()).ok_or(EngineError::NoLayer(id))?;+ crate::pixels::adjust_surface(surf, &adj, sel.as_ref());+ Ok(())+ })?;+ Ok(Value::Null)+}++fn toggle_last_state(s: &mut Session) -> Result<Value> {+ let st = s.active().ok_or(EngineError::NoDocument)?;+ let redo = st.history.can_redo();+ Ok(json!(if redo { s.redo() } else { s.undo() }))+}++/// Edit › Transform › Again: replay the last `edit.transform` on the active layer.+fn transform_again(s: &mut Session) -> Result<Value> {+ let (_, last) = s.journal.iter().rev().find(|(id, _)| id == "edit.transform").cloned().ok_or(EngineError::Other("there is no transform to repeat".into()))?;+ let (rect, quad) = (last.get("rect").cloned(), last.get("quad").cloned());+ let mut p = json!({"interpolation": last.get("interpolation").cloned().unwrap_or(json!("bicubic"))});+ match (rect, quad, last.get("matrix").cloned()) {+ (Some(r), Some(q), _) => {+ let v = |x: &Value| -> Vec<f64> { x.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default() };+ let r = v(&r);+ let q: Vec<Vec<f64>> = q.as_array().map(|a| a.iter().map(v).collect()).unwrap_or_default();+ if r.len() != 4 || q.len() != 4 {+ return Err(EngineError::Other("the last transform can't be repeated".into()));+ }+ let h = photocraft_algo::transform::Homography::rect_to_quad([r[0], r[1], r[2], r[3]], [[q[0][0], q[0][1]], [q[1][0], q[1][1]], [q[2][0], q[2][1]], [q[3][0], q[3][1]]])+ .ok_or(EngineError::Other("the last transform can't be repeated".into()))?;+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let l = d.doc.layer(active_id(s)?).ok_or(EngineError::Other("no active layer".into()))?;+ let b = crate::transform_cmds::transform_bounds(&d.doc, l);+ if b.is_empty() {+ return Err(EngineError::Other("nothing to transform".into()));+ }+ let nr = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64];+ let corners = [(nr[0], nr[1]), (nr[2], nr[1]), (nr[2], nr[3]), (nr[0], nr[3])].map(|(x, y)| {+ let (a, b) = h.apply(x, y);+ [a, b]+ });+ p["rect"] = json!(nr);+ p["quad"] = json!(corners);+ }+ (_, _, Some(m)) => p["matrix"] = m,+ _ => return Err(EngineError::Other("the last transform can't be repeated".into())),+ }+ s.execute("edit.transform", p)+}++/// View › New Guide / guide moves (undoable, like Photoshop's "New Guide"/"Move Guide" states).+fn guide_cmd(s: &mut Session, p: &Value, op: &str) -> Result<Value> {+ let vertical = p.get("orientation").and_then(Value::as_str).unwrap_or("horizontal") == "vertical";+ let pos = p.get("position").and_then(Value::as_f64).map(|v| v as f32);+ let index = p.get("index").and_then(Value::as_u64).map(|v| v as usize);+ let label = match op {+ "new" => "New Guide",+ "move" => "Move Guide",+ "delete" => "Delete Guide",+ _ => "Clear Guides",+ };+ s.edit(label, |doc, _| {+ let g = if vertical { &mut doc.guides.vertical } else { &mut doc.guides.horizontal };+ match op {+ "new" => g.push(pos.ok_or(EngineError::Other("missing `position`".into()))?),+ "move" => {+ let i = index.filter(|i| *i < g.len()).ok_or(EngineError::Other("no such guide".into()))?;+ g[i] = pos.ok_or(EngineError::Other("missing `position`".into()))?;+ }+ "delete" => {+ let i = index.filter(|i| *i < g.len()).ok_or(EngineError::Other("no such guide".into()))?;+ g.remove(i);+ }+ _ => {+ doc.guides.horizontal.clear();+ doc.guides.vertical.clear();+ }+ }+ Ok(())+ })?;+ Ok(Value::Null)+}++pub fn specs() -> Vec<CommandSpec> {+ macro_rules! spec {+ ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => {+ CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run }+ };+ }+ vec![+ spec!("edit.cut", "Cut", &["Edit"], Some("Cmd+X"), "{}", has_pixels, |s, _| {+ let r = copy(s, false)?;+ let id = active_id(s)?;+ s.edit("Cut Pixels", |doc, _| clear_selected(doc, id))?;+ Ok(r)+ }),+ spec!("edit.copy", "Copy", &["Edit"], Some("Cmd+C"), "{}", has_pixels, |s, _| copy(s, false)),+ spec!("edit.copyMerged", "Copy Merged", &["Edit"], Some("Cmd+Shift+C"), "{}", has_doc, |s, _| copy(s, true)),+ spec!("edit.paste", "Paste", &["Edit"], Some("Cmd+V"), r##"{"center":[x,y]? (view centre; default keeps the position when it overlaps the canvas)}"##, has_clip, |s, p| paste(s, p, false)),+ spec!("edit.pasteSpecial.pasteInPlace", "Paste in Place", &["Edit", "Paste Special"], Some("Cmd+Shift+V"), "{}", has_clip, |s, p| paste(s, p, true)),+ spec!("layer.new.layerViaCopy", "Layer via Copy", &["Layer", "New"], Some("Cmd+J"), "{}", has_doc, |s, _| layer_via(s, false)),+ spec!("layer.new.layerViaCut", "Layer via Cut", &["Layer", "New"], Some("Cmd+Shift+J"), "{}", has_pixels, |s, _| layer_via(s, true)),+ spec!("layer.mergeVisible", "Merge Visible", &["Layer"], Some("Cmd+Shift+E"), "{}", has_doc, |s, _| merge_visible(s)),+ spec!("image.autoTone", "Auto Tone", &["Image"], Some("Cmd+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "tone")),+ spec!("image.autoContrast", "Auto Contrast", &["Image"], Some("Cmd+Alt+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "contrast")),+ spec!("image.autoColor", "Auto Color", &["Image"], Some("Cmd+Shift+B"), "{}", has_pixels, |s, _| auto_adjust(s, "color")),+ spec!("edit.toggleLastState", "Toggle Last State", &["Edit"], Some("Cmd+Alt+Z"), "{}", has_doc, |s, _| toggle_last_state(s)),+ spec!("edit.transform.again", "Again", &["Edit", "Transform"], Some("Cmd+Shift+T"), "{}", has_doc, |s, _| transform_again(s)),+ spec!("view.newGuide", "New Guide…", &["View"], None, r##"{"orientation":"horizontal|vertical","position":px}"##, has_doc, |s, p| guide_cmd(s, p, "new")),+ spec!("view.moveGuide", "Move Guide", &[], None, r##"{"orientation":"horizontal|vertical","index":n,"position":px}"##, has_doc, |s, p| guide_cmd(s, p, "move")),+ spec!("view.deleteGuide", "Delete Guide", &[], None, r##"{"orientation":"horizontal|vertical","index":n}"##, has_doc, |s, p| guide_cmd(s, p, "delete")),+ spec!("view.clearGuides", "Clear Guides", &["View"], None, "{}", has_doc, |s, p| guide_cmd(s, p, "clear")),+ ]+}++#[cfg(test)]+mod tests {+ use super::*;++ fn session() -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.edit("paint", |doc, a| {+ doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ s+ }++ fn active_bounds(s: &Session) -> Rect {+ let st = s.active().unwrap();+ st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds()+ }++ #[test]+ fn copy_paste_in_place_and_centred() {+ let mut s = session();+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();+ s.execute("edit.copy", json!({})).unwrap();+ s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 30));+ assert!(s.active().unwrap().doc.selection.is_none());+ s.execute("edit.paste", json!({"center": [70, 70]})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(60, 60, 80, 80));+ assert_eq!(s.active().unwrap().doc.layers.len(), 4);+ }++ #[test]+ fn cut_clears_and_layer_via_copy_cut() {+ let mut s = session();+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap();+ s.execute("edit.cut", json!({})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(20, 10, 50, 30));+ let mut s = session();+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap();+ s.execute("layer.new.layerViaCut", json!({})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 30));+ let d = &s.active().unwrap().doc;+ assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 50, 30));+ // Without a selection ⌘J duplicates the layer.+ let mut s = session();+ s.execute("layer.new.layerViaCopy", json!({})).unwrap();+ let d = &s.active().unwrap().doc;+ assert_eq!(d.layers.len(), 3);+ assert!(d.layers[2].name.ends_with("copy"));+ }++ #[test]+ fn merge_visible_keeps_hidden_layers() {+ let mut s = session();+ s.execute("layer.new.layer", json!({})).unwrap();+ let hidden = s.active().unwrap().active_layer.unwrap();+ s.execute("layer.setProps", json!({"layer": hidden.0, "visible": false})).unwrap();+ s.execute("layer.mergeVisible", json!({})).unwrap();+ let d = &s.active().unwrap().doc;+ assert_eq!(d.layers.len(), 2);+ assert_eq!(d.layers[0].name, "Background");+ assert_eq!(d.layers[1].id, hidden);+ assert_eq!(d.layers[0].surface().unwrap().pixel(20, 20)[..3], [1.0, 0.0, 0.0]);+ }++ #[test]+ fn auto_tone_stretches_a_low_contrast_layer() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();+ s.edit("grey ramp", |doc, _| {+ let surf = doc.layers[0].surface_mut().unwrap();+ for x in 0..64 {+ let v = 0.3 + 0.4 * x as f32 / 63.0;+ surf.fill_rect(Rect::new(x, 0, x + 1, 64), &[v, v * 0.9, v * 0.8, 1.0]);+ }+ Ok(())+ })+ .unwrap();+ for cmd in ["image.autoTone", "image.autoContrast", "image.autoColor"] {+ s.execute(cmd, json!({})).unwrap();+ let d = &s.active().unwrap().doc;+ let (a, b) = (d.layers[0].surface().unwrap().pixel(0, 0), d.layers[0].surface().unwrap().pixel(63, 0));+ // Auto Contrast keeps colour (shared points): only the extreme channels reach 0 and 1.+ let (lo, hi) = if cmd == "image.autoContrast" { (a[2], b[0]) } else { (a[0], b[0]) };+ assert!(lo < 0.05 && hi > 0.95, "{cmd}: {a:?} {b:?}");+ s.undo();+ }+ }++ #[test]+ fn toggle_last_state_and_transform_again() {+ let mut s = session();+ s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap();+ s.execute("edit.transform.again", json!({})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30));+ s.execute("edit.toggleLastState", json!({})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(20, 10, 60, 30));+ s.execute("edit.toggleLastState", json!({})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30));+ }++ #[test]+ fn guides_are_undoable() {+ let mut s = session();+ s.execute("view.newGuide", json!({"orientation": "vertical", "position": 40})).unwrap();+ s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 12.5})).unwrap();+ s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 60})).unwrap();+ let g = &s.active().unwrap().doc.guides;+ assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![60.0], vec![12.5]));+ s.execute("view.deleteGuide", json!({"orientation": "horizontal", "index": 0})).unwrap();+ s.undo();+ assert_eq!(s.active().unwrap().doc.guides.horizontal, vec![12.5]);+ s.execute("view.clearGuides", json!({})).unwrap();+ assert!(s.active().unwrap().doc.guides.vertical.is_empty());+ assert!(s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 3, "position": 1})).is_err());+ }+}diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rsnew file mode 100644index 000000000..4b067ef25--- /dev/null+++ b/crates/engine/src/image_cmds.rs@@ -0,0 +1,518 @@+//! Image menu: Image Size, Canvas Size, Crop, Trim, Mode (colour model and+//! bit depth) conversions, Duplicate.++use photocraft_algo::resample::{Resample, crop_surface, resize_surface, translate_surface};+use photocraft_color::{ColorMode, PixelFormat, SampleType};+use photocraft_doc::{Document, Effect, Effects, FxPaint, Layer, LayerContent, Size};+use photocraft_geom::Rect;+use photocraft_raster::Surface;+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++fn has_doc(s: &Session) -> std::result::Result<(), String> {+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())+}++/// Applies `f` to every pixel surface of a layer tree: content (raster or+/// cached text/shape/smart pixels), fill caches, and (if `masks`) masks.+pub(crate) fn for_each_surface(layers: &mut [Layer], masks: bool, f: &mut dyn FnMut(&mut Surface, bool)) {+ for l in layers {+ if masks && let Some(m) = &mut l.mask {+ f(&mut m.surface, true);+ }+ if let Some(fc) = &mut l.fill_cache {+ f(&mut fc.surface, false);+ }+ match &mut l.content {+ LayerContent::Raster(s) => f(s, false),+ LayerContent::Text(t) => {+ if let Some(c) = &mut t.cache {+ f(c, false)+ }+ }+ LayerContent::Shape(sh) => {+ if let Some(c) = &mut sh.cache {+ f(c, false)+ }+ }+ LayerContent::Smart(sm) => {+ if let Some(c) = &mut sm.cache {+ f(c, false)+ }+ }+ LayerContent::Group(g) => for_each_surface(&mut g.children, masks, f),+ _ => {}+ }+ }+}++fn for_each_layer(layers: &mut [Layer], f: &mut dyn FnMut(&mut Layer)) {+ for l in layers {+ f(l);+ if let Some(ch) = l.children_mut() {+ for_each_layer(ch, f);+ }+ }+}++fn scale_effects(fx: &mut Effects, k: f32) {+ for e in &mut fx.items {+ match e {+ Effect::DropShadow(s) | Effect::InnerShadow(s) => {+ s.distance *= k;+ s.size *= k;+ }+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.size *= k,+ Effect::Stroke(s) => s.size *= k,+ Effect::Satin(s) => {+ s.distance *= k;+ s.size *= k;+ }+ Effect::BevelEmboss(b) => {+ b.size *= k;+ b.soften *= k;+ }+ Effect::PatternOverlay { scale, .. } => *scale *= k,+ Effect::GradientOverlay { .. } | Effect::ColorOverlay { .. } => {}+ }+ if let Effect::Stroke(s) = e+ && let FxPaint::Pattern { scale, .. } = &mut s.paint+ {+ *scale *= k;+ }+ }+ // Effects changed: the preserved PSD block no longer applies.+ if k != 1.0 {+ fx.psd_raw = None;+ }+}++fn parse_resample(s: &str) -> Option<Resample> {+ Some(match s {+ "none" => return None,+ "nearest" | "nearestNeighbor" => Resample::Nearest,+ "bilinear" => Resample::Bilinear,+ "lanczos" => Resample::Lanczos,+ "preserveDetails" => Resample::PreserveDetails,+ _ => Resample::Bicubic,+ })+}++/// Image → Image Size.+fn image_size(s: &mut Session, p: &Value) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let (ow, oh) = (d.doc.size.width, d.doc.size.height);+ let resample = parse_resample(p.get("resample").and_then(Value::as_str).unwrap_or("bicubic"));+ let pw = p.get("width").and_then(Value::as_f64);+ let ph = p.get("height").and_then(Value::as_f64);+ // Missing dimension keeps the aspect ratio.+ let (nw, nh) = match (pw, ph) {+ (Some(w), Some(h)) => (w, h),+ (Some(w), None) => (w, w * oh as f64 / ow.max(1) as f64),+ (None, Some(h)) => (h * ow as f64 / oh.max(1) as f64, h),+ (None, None) => (ow as f64, oh as f64),+ };+ let (nw, nh) = (nw.round().clamp(1.0, 300_000.0) as u32, nh.round().clamp(1.0, 300_000.0) as u32);+ let dpi = p.get("resolution").and_then(Value::as_f64).map(|v| v as f32);+ s.edit("Image Size", |doc, _| {+ if let Some(r) = dpi {+ doc.resolution_dpi = r.clamp(1.0, 10_000.0);+ }+ let Some(filter) = resample else { return Ok(()) };+ let (sx, sy) = (nw as f64 / ow.max(1) as f64, nh as f64 / oh.max(1) as f64);+ if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 {+ return Ok(());+ }+ for_each_surface(&mut doc.layers, true, &mut |surf, is_mask| {+ *surf = resize_surface(surf, sx, sy, if is_mask { Resample::Bilinear } else { filter });+ });+ let k = ((sx + sy) / 2.0) as f32;+ for_each_layer(&mut doc.layers, &mut |l| scale_effects(&mut l.effects, k));+ for ch in &mut doc.channels {+ ch.surface = resize_surface(&ch.surface, sx, sy, Resample::Bilinear);+ }+ if let Some(sel) = &doc.selection {+ doc.selection = Some(resize_surface(sel, sx, sy, Resample::Bilinear));+ }+ for g in &mut doc.guides.horizontal {+ *g *= sy as f32;+ }+ for g in &mut doc.guides.vertical {+ *g *= sx as f32;+ }+ doc.size = Size::new(nw, nh);+ Ok(())+ })?;+ Ok(json!({ "width": nw, "height": nh }))+}++/// Moves every surface, channel, selection and guide by `(dx, dy)`.+fn translate_doc(doc: &mut Document, dx: i32, dy: i32) {+ if dx == 0 && dy == 0 {+ return;+ }+ for_each_surface(&mut doc.layers, true, &mut |surf, _| *surf = translate_surface(surf, dx, dy));+ for ch in &mut doc.channels {+ ch.surface = translate_surface(&ch.surface, dx, dy);+ }+ if let Some(sel) = &doc.selection {+ doc.selection = Some(translate_surface(sel, dx, dy));+ }+ for g in &mut doc.guides.horizontal {+ *g += dy as f32;+ }+ for g in &mut doc.guides.vertical {+ *g += dx as f32;+ }+}++/// Crops the document to `r` (in current document coordinates).+fn crop_doc(doc: &mut Document, r: Rect, delete_pixels: bool) {+ if delete_pixels {+ for_each_surface(&mut doc.layers, false, &mut |surf, _| *surf = crop_surface(surf, r));+ }+ translate_doc(doc, -r.x0, -r.y0);+ doc.size = Size::new(r.width(), r.height());+}++fn anchor_factors(a: &str) -> (f64, f64) {+ let x = if a.contains("Left") || a == "left" { 0.0 } else if a.contains("Right") || a == "right" { 1.0 } else { 0.5 };+ let y = if a.starts_with("top") { 0.0 } else if a.starts_with("bottom") { 1.0 } else { 0.5 };+ (x, y)+}++fn extension_color(s: &Session, p: &Value) -> [f32; 4] {+ match p.get("extensionColor").and_then(Value::as_str).unwrap_or("background") {+ "foreground" => s.tools.foreground,+ "white" => [1.0; 4],+ "black" => [0.0, 0.0, 0.0, 1.0],+ "transparent" => [0.0; 4],+ hex if hex.starts_with('#') => {+ let h = hex.trim_start_matches('#');+ let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map_or(0.0, |v| f32::from(v) / 255.0);+ [c(0), c(2), c(4), 1.0]+ }+ _ => s.tools.background,+ }+}++/// Image → Canvas Size.+fn canvas_size(s: &mut Session, p: &Value) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let (ow, oh) = (d.doc.size.width as f64, d.doc.size.height as f64);+ let relative = p.get("relative").and_then(Value::as_bool).unwrap_or(false);+ let w = p.get("width").and_then(Value::as_f64).unwrap_or(if relative { 0.0 } else { ow });+ let h = p.get("height").and_then(Value::as_f64).unwrap_or(if relative { 0.0 } else { oh });+ let (nw, nh) = if relative { (ow + w, oh + h) } else { (w, h) };+ let (nw, nh) = (nw.round().clamp(1.0, 300_000.0) as u32, nh.round().clamp(1.0, 300_000.0) as u32);+ let (ax, ay) = anchor_factors(p.get("anchor").and_then(Value::as_str).unwrap_or("center"));+ let dx = ((nw as f64 - ow) * ax).round() as i32;+ let dy = ((nh as f64 - oh) * ay).round() as i32;+ let ext = extension_color(s, p);+ s.edit("Canvas Size", |doc, _| {+ translate_doc(doc, dx, dy);+ doc.size = Size::new(nw, nh);+ let canvas = doc.bounds();+ let old = Rect::from_xywh(dx, dy, ow as u32, oh as u32);+ // The locked Background layer is extended with the extension colour.+ if ext[3] > 0.0+ && let Some(bg) = doc.layers.first_mut()+ && bg.name == "Background"+ && bg.locks.transparency+ && let LayerContent::Raster(surf) = &mut bg.content+ {+ let fmt = surf.format();+ let px = photocraft_raster::from_rgba(&fmt, ext);+ let keep = surf.content_bounds().intersect(&old);+ let saved = surf.to_interleaved(keep);+ surf.fill_rect(canvas, &px);+ if !keep.is_empty() {+ surf.write_interleaved(keep, &saved);+ }+ }+ Ok(())+ })?;+ Ok(json!({ "width": nw, "height": nh, "offset": [dx, dy] }))+}++/// Image → Crop (to the selection bounds).+fn crop(s: &mut Session, p: &Value) -> Result<Value> {+ let delete = p.get("deleteCroppedPixels").and_then(Value::as_bool).unwrap_or(true);+ let explicit = match (crate::commands::int(p, "x"), crate::commands::int(p, "y"), crate::commands::int(p, "width"), crate::commands::int(p, "height")) {+ (Some(x), Some(y), Some(w), Some(h)) if w > 0 && h > 0 => Some(Rect::new(x as i32, y as i32, (x + w) as i32, (y + h) as i32)),+ _ => None,+ };+ // An explicit rectangle (the Crop tool) may extend past the canvas; a selection crop is clamped.+ let r = explicit.or_else(|| s.active().and_then(|d| d.doc.selection.as_ref().map(|sel| sel.content_bounds().intersect(&d.doc.bounds())))).unwrap_or(Rect::EMPTY);+ if r.is_empty() {+ return Err(EngineError::Other("nothing to crop: pass x/y/width/height or make a selection".into()));+ }+ s.edit("Crop", |doc, _| {+ crop_doc(doc, r, delete);+ doc.selection = None;+ Ok(())+ })?;+ Ok(json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }))+}++/// Image → Trim.+fn trim(s: &mut Session, p: &Value) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let canvas = d.doc.bounds();+ let buf = photocraft_compose::flatten(&d.doc);+ let based = p.get("basedOn").and_then(Value::as_str).unwrap_or("transparent");+ let w = canvas.width() as usize;+ let reference = match based {+ "topLeft" => Some(buf.px[0]),+ "bottomRight" => buf.px.last().copied(),+ _ => None,+ };+ let differs = |q: [f32; 4]| match reference {+ None => q[3] > 0.0,+ Some(r) => (0..4).any(|c| (q[c] * q[3] - r[c] * r[3]).abs() > 0.5 / 255.0 || (c == 3 && (q[3] - r[3]).abs() > 0.5 / 255.0)),+ };+ let mut b = Rect::EMPTY;+ for (i, q) in buf.px.iter().enumerate() {+ if differs(*q) {+ let (x, y) = ((i % w) as i32, (i / w) as i32);+ b = if b.is_empty() { Rect::new(x, y, x + 1, y + 1) } else { b.union(&Rect::new(x, y, x + 1, y + 1)) };+ }+ }+ if b.is_empty() {+ return Err(EngineError::Other("nothing to trim to".into()));+ }+ let side = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(true);+ let r = Rect::new(+ if side("left") { b.x0 } else { canvas.x0 },+ if side("top") { b.y0 } else { canvas.y0 },+ if side("right") { b.x1 } else { canvas.x1 },+ if side("bottom") { b.y1 } else { canvas.y1 },+ );+ s.edit("Trim", |doc, _| {+ crop_doc(doc, r, true);+ Ok(())+ })?;+ Ok(json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }))+}++/// Image → Mode → colour model.+fn convert_mode(s: &mut Session, mode: ColorMode) -> Result<Value> {+ s.edit("Mode Change", |doc, _| {+ if doc.mode == mode {+ return Ok(());+ }+ let fmt = PixelFormat::new(mode, doc.depth, true);+ for_each_surface(&mut doc.layers, false, &mut |surf, _| {+ if surf.format() != fmt {+ *surf = surf.convert(fmt);+ }+ });+ doc.mode = mode;+ Ok(())+ })?;+ Ok(Value::Null)+}++/// Image → Mode → 8/16/32 Bits/Channel.+fn convert_depth(s: &mut Session, depth: SampleType) -> Result<Value> {+ s.edit("Bit Depth", |doc, _| {+ if doc.depth == depth {+ return Ok(());+ }+ for_each_surface(&mut doc.layers, true, &mut |surf, _| {+ let f = surf.format().with_sample(depth);+ *surf = surf.convert(f);+ });+ for ch in &mut doc.channels {+ let f = ch.surface.format().with_sample(depth);+ ch.surface = ch.surface.convert(f);+ }+ doc.depth = depth;+ Ok(())+ })?;+ Ok(Value::Null)+}++/// Image → Duplicate.+fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let mut doc = (*d.doc).clone();+ doc.id = photocraft_doc::DocId::fresh();+ doc.name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("{} copy", d.doc.name));+ if p.get("mergedOnly").and_then(Value::as_bool).unwrap_or(false) {+ let buf = photocraft_compose::flatten(&doc);+ let fmt = doc.pixel_format();+ let mut surf = Surface::new(fmt);+ let vals: Vec<f32> = buf.px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect();+ surf.write_region(doc.bounds(), &vals);+ surf.prune();+ doc.layers = vec![Layer::new("Background", LayerContent::Raster(surf))];+ }+ for_each_layer(&mut doc.layers, &mut |l| l.id = photocraft_doc::LayerId::fresh());+ let name = doc.name.clone();+ let index = s.add_document(doc, None);+ Ok(json!({ "document": index, "name": name }))+}++macro_rules! spec {+ ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => {+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true }+ };+}++/// Image menu command specs.+pub fn specs() -> Vec<CommandSpec> {+ vec![+ spec!("image.imageSize", "Image Size…", ["Image"], r##"{"width":px,"height":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails|none"="bicubic"}"##, has_doc, image_size),+ spec!("image.canvasSize", "Canvas Size…", ["Image"], r##"{"width":px,"height":px,"relative":bool=false,"anchor":"topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"="center","extensionColor":"background|foreground|white|black|transparent|#rrggbb"="background"}"##, has_doc, canvas_size),+ spec!("image.crop", "Crop", ["Image"], r##"{"x":px,"y":px,"width":px,"height":px,"deleteCroppedPixels":bool=true}"##, has_doc, crop),+ spec!("image.trim", "Trim…", ["Image"], r##"{"basedOn":"transparent|topLeft|bottomRight"="transparent","top":bool=true,"bottom":bool=true,"left":bool=true,"right":bool=true}"##, has_doc, trim),+ spec!("image.mode.rgb", "RGB Color", ["Image", "Mode"], "{}", has_doc, |s, _| convert_mode(s, ColorMode::Rgb)),+ spec!("image.mode.grayscale", "Grayscale", ["Image", "Mode"], "{}", has_doc, |s, _| convert_mode(s, ColorMode::Grayscale)),+ spec!("image.mode.cmyk", "CMYK Color", ["Image", "Mode"], "{}", has_doc, |s, _| convert_mode(s, ColorMode::Cmyk)),+ spec!("image.mode.lab", "Lab Color", ["Image", "Mode"], "{}", has_doc, |s, _| convert_mode(s, ColorMode::Lab)),+ spec!("image.mode.bits8", "8 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U8)),+ spec!("image.mode.bits16", "16 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U16)),+ spec!("image.mode.bits32", "32 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::F32)),+ spec!("image.duplicate", "Duplicate…", ["Image"], r##"{"name":str,"mergedOnly":bool=false}"##, has_doc, duplicate),+ ]+}++#[cfg(test)]+mod tests {+ use super::*;++ fn session() -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 20})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.edit("paint", |doc, active| {+ let l = doc.layer_mut(active.unwrap()).unwrap();+ l.surface_mut().unwrap().fill_rect(Rect::new(10, 5, 20, 15), &[1.0, 0.0, 0.0, 1.0]);+ l.mask = Some(photocraft_doc::LayerMask::reveal_all());+ l.effects.items.push(Effect::default_drop_shadow());+ Ok(())+ })+ .unwrap();+ s+ }++ fn doc(s: &Session) -> &Document {+ &s.active().unwrap().doc+ }++ #[test]+ fn image_size_scales_everything() {+ for resample in ["bicubic", "bilinear", "nearest", "lanczos", "preserveDetails"] {+ let mut s = session();+ s.execute("image.imageSize", json!({"width": 80, "resample": resample})).unwrap();+ let d = doc(&s);+ assert_eq!(d.size, Size::new(80, 40), "{resample}");+ let l = &d.layers[1];+ let b = l.surface().unwrap().content_bounds();+ assert!((b.x0 - 20).abs() <= 1 && (b.x1 - 40).abs() <= 1, "{resample} {b:?}");+ let Effect::DropShadow(sh) = &l.effects.items[0] else { panic!() };+ assert_eq!(sh.distance, 10.0);+ assert_eq!(l.mask.as_ref().unwrap().surface.default_pixel(), vec![1.0]);+ }+ }++ #[test]+ fn resolution_only_change() {+ let mut s = session();+ s.execute("image.imageSize", json!({"resolution": 300, "resample": "none", "width": 999})).unwrap();+ assert_eq!(doc(&s).size, Size::new(40, 20));+ assert_eq!(doc(&s).resolution_dpi, 300.0);+ }++ #[test]+ fn canvas_size_anchors_and_extends_background() {+ let mut s = session();+ s.execute("image.canvasSize", json!({"width": 60, "height": 30, "anchor": "topLeft", "extensionColor": "#00ff00"})).unwrap();+ let d = doc(&s);+ assert_eq!(d.size, Size::new(60, 30));+ assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15));+ let bg = d.layers[0].surface().unwrap();+ assert_eq!(bg.pixel(50, 25), vec![0.0, 1.0, 0.0, 1.0]);+ assert_eq!(bg.pixel(5, 5), vec![1.0, 1.0, 1.0, 1.0]);+ let mut s = session();+ s.execute("image.canvasSize", json!({"width": 20, "height": 10, "relative": true, "anchor": "center"})).unwrap();+ assert_eq!(doc(&s).layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 20));+ }++ #[test]+ fn crop_to_selection_and_trim() {+ let mut s = session();+ assert!(s.execute("image.crop", json!({})).is_err(), "no selection, no rect");+ s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap();+ s.execute("image.crop", json!({})).unwrap();+ let d = doc(&s);+ assert_eq!(d.size, Size::new(20, 10));+ assert!(d.selection.is_none());+ assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(5, 3, 15, 10));+ // Trim transparent: hide the background, trim to the red square.+ let mut s = session();+ s.execute("layer.setProps", json!({"layer": doc(&s).layers[0].id.0, "visible": false})).unwrap();+ s.execute("image.trim", json!({"basedOn": "transparent"})).unwrap();+ // The red square (10×10) plus its drop shadow (distance 5, size 5).+ let size = doc(&s).size;+ assert!(size.width > 10 && size.width < 30 && size.height > 10 && size.height < 25, "{size:?}");+ }++ #[test]+ fn crop_to_explicit_rect_can_extend_canvas() {+ let mut s = session();+ s.execute("image.crop", json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap();+ assert_eq!(doc(&s).size, Size::new(10, 10));+ assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(0, 0), vec![1.0, 0.0, 0.0, 1.0]);+ let mut s = session();+ s.execute("image.crop", json!({"x": -10, "y": 0, "width": 60, "height": 20})).unwrap();+ assert_eq!(doc(&s).size, Size::new(60, 20));+ assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 5), vec![1.0, 0.0, 0.0, 1.0]);+ }++ #[test]+ fn trim_based_on_top_left_colour() {+ let mut s = session();+ s.edit("no fx", |doc, _| {+ doc.layers[1].effects.items.clear();+ Ok(())+ })+ .unwrap();+ s.execute("image.trim", json!({"basedOn": "topLeft"})).unwrap();+ assert_eq!(doc(&s).size, Size::new(10, 10));+ }++ #[test]+ fn mode_and_depth_conversions() {+ let mut s = session();+ s.execute("image.mode.grayscale", json!({})).unwrap();+ assert_eq!(doc(&s).mode, ColorMode::Grayscale);+ assert_eq!(doc(&s).layers[1].surface().unwrap().format().mode, ColorMode::Grayscale);+ s.execute("image.mode.bits16", json!({})).unwrap();+ assert_eq!(doc(&s).depth, SampleType::U16);+ assert_eq!(doc(&s).layers[1].surface().unwrap().format().sample, SampleType::U16);+ assert_eq!(doc(&s).layers[1].mask.as_ref().unwrap().surface.format().sample, SampleType::U16);+ s.execute("image.mode.cmyk", json!({})).unwrap();+ s.execute("image.mode.bits32", json!({})).unwrap();+ s.execute("image.mode.lab", json!({})).unwrap();+ s.execute("image.mode.rgb", json!({})).unwrap();+ s.execute("image.mode.bits8", json!({})).unwrap();+ let d = doc(&s);+ assert_eq!((d.mode, d.depth), (ColorMode::Rgb, SampleType::U8));+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(doc(&s).depth, SampleType::F32);+ }++ #[test]+ fn duplicate_document() {+ let mut s = session();+ let r = s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap();+ assert_eq!(r["document"], json!(1));+ assert_eq!(s.documents().len(), 2);+ assert_eq!(doc(&s).layers.len(), 1);+ assert!(doc(&s).name.ends_with("copy"));+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 6ff61a459..f41003301 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -10,6 +10,15 @@ pub mod commands;pub mod inspect;pub mod layer_style;pub mod filters;+pub mod type_cmds;+pub mod transform_cmds;+pub mod vector_cmds;+pub mod smartselect_cmds;+pub mod edit_cmds;+pub mod retouch_cmds;+pub mod image_cmds;+pub mod paint_cmds;+pub mod selection_cmds;mod pixels;use std::sync::Arc;@@ -20,6 +29,7 @@ use serde_json::Value;pub use commands::{CommandSpec, command_specs};pub use photocraft_doc as doc;+pub use photocraft_paint::BrushSettings;#[derive(Debug, thiserror::Error)]pub enum EngineError {@@ -51,12 +61,14 @@ pub struct DocState {pub saved_revision: u64,/// Area changed by the latest revision (None = assume everything changed).pub last_damage: Option<photocraft_geom::Rect>,+ /// Coalescing key of the latest history step (see [`Session::execute`]'s `coalesce` param).+ pub coalesce: Option<String>,}impl DocState {pub fn new(doc: Document, path: Option<String>) -> Self {let active_layer = doc.top_layer();- Self { doc: Arc::new(doc), history: History::default(), active_layer, path, revision: 1, saved_revision: 1, last_damage: None }+ Self { doc: Arc::new(doc), history: History::default(), active_layer, path, revision: 1, saved_revision: 1, last_damage: None, coalesce: None }}pub fn is_dirty(&self) -> bool {self.revision != self.saved_revision@@ -84,6 +96,10 @@ pub struct Session {pub tools: ToolState,/// Log of executed commands (for action recording and debugging).pub journal: Vec<(String, Value)>,+ /// Coalescing key of the command being executed.+ coalesce_request: Option<String>,+ /// Pixels copied with Edit › Copy / Cut (shared by all documents, like Photoshop).+ pub clipboard: Option<edit_cmds::Clip>,}impl Session {@@ -130,12 +146,19 @@ impl Session {}/// Run a command by id with JSON params. Returns a JSON result.+ ///+ /// Any command accepts an optional `"coalesce": "<key>"` param: consecutive edits with the same+ /// key (and no other edit, undo or redo in between) share one history step, like Photoshop's+ /// single "Edit Type Layer" step for a whole typing session or one step per slider drag.pub fn execute(&mut self, id: &str, params: Value) -> Result<Value> {let spec = commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;if let Err(why) = (spec.enabled)(self) {return Err(EngineError::Disabled(id.to_string(), why));}- let r = (spec.run)(self, &commands::inject_kind(id, params.clone()))?;+ self.coalesce_request = params.get("coalesce").and_then(Value::as_str).map(str::to_string);+ let r = (spec.run)(self, &commands::inject_kind(id, params.clone()));+ self.coalesce_request = None;+ let r = r?;if spec.journal {self.journal.push((id.to_string(), params));}@@ -156,7 +179,12 @@ impl Session {let r = f(&mut doc, &mut active)?;st.doc = Arc::new(doc);st.active_layer = active;- st.history.record(label, before);+ let key = self.coalesce_request.clone();+ let st = self.active_mut().ok_or(EngineError::NoDocument)?;+ if key.is_none() || st.coalesce != key || !st.history.can_undo() {+ st.history.record(label, before);+ }+ st.coalesce = key;st.revision += 1;st.last_damage = None;Ok(r)@@ -169,13 +197,19 @@ impl Session {return Err(EngineError::NoLayer(id));}st.active_layer = Some(id);+ // Selecting a layer is not an edit: keep a clean document clean.+ let clean = st.saved_revision == st.revision;st.revision += 1;+ if clean {+ st.saved_revision = st.revision;+ }st.last_damage = Some(photocraft_geom::Rect::EMPTY);Ok(())}pub fn undo(&mut self) -> bool {let Some(st) = self.active_mut() else { return false };+ st.coalesce = None;match st.history.undo(st.doc.clone()) {Some(d) => {st.doc = d;@@ -190,6 +224,7 @@ impl Session {pub fn redo(&mut self) -> bool {let Some(st) = self.active_mut() else { return false };+ st.coalesce = None;match st.history.redo(st.doc.clone()) {Some(d) => {st.doc = d;diff --git a/crates/engine/src/paint_cmds.rs b/crates/engine/src/paint_cmds.rsnew file mode 100644index 000000000..1757036ca--- /dev/null+++ b/crates/engine/src/paint_cmds.rs@@ -0,0 +1,155 @@+//! Paint helpers: Paint Bucket and Gradient tool.++use photocraft_algo::paint::{GradientShape, bucket_fill, paint_gradient};+use serde_json::{Value, json};++use crate::commands::{CommandSpec, blend_from_str};+use crate::{EngineError, Result, Session};++fn f(p: &Value, k: &str, d: f32) -> f32 {+ p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32)+}+fn b(p: &Value, k: &str, d: bool) -> bool {+ p.get(k).and_then(Value::as_bool).unwrap_or(d)+}+fn color(v: Option<&Value>, d: [f32; 4]) -> [f32; 4] {+ match v {+ Some(Value::Array(a)) if a.len() >= 3 => {+ let c: Vec<f32> = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();+ [c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0)]+ }+ Some(Value::String(h)) => {+ let h = h.trim_start_matches('#');+ let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f32::from(v) / 255.0);+ match (c(0), c(2), c(4)) {+ (Some(r), Some(g), Some(b)) => [r, g, b, c(6).unwrap_or(1.0)],+ _ => d,+ }+ }+ _ => d,+ }+}+fn point(p: &Value, k: &str) -> Option<(f32, f32)> {+ let a = p.get(k)?.as_array()?;+ Some((a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32))+}++fn bucket(s: &mut Session, p: &Value) -> Result<Value> {+ let fg = s.tools.foreground;+ let c = color(p.get("color"), fg);+ let (x, y) = (f(p, "x", 0.0).floor() as i32, f(p, "y", 0.0).floor() as i32);+ let (tol, contiguous, aa, opacity) = (f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true), f(p, "opacity", 100.0) / 100.0);+ let filled = s.edit("Paint Bucket", |doc, active| {+ let area = doc.bounds();+ let sel = doc.selection.clone();+ let id = active.ok_or(EngineError::Other("no active layer".into()))?;+ let surf = crate::commands::paint_surface(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?, p)?;+ let ok = bucket_fill(surf, area, (x, y), tol, contiguous, aa, c, opacity, sel.as_ref());+ surf.prune();+ Ok(ok)+ })?;+ Ok(json!({ "filled": filled }))+}++fn gradient(s: &mut Session, p: &Value) -> Result<Value> {+ let from = point(p, "from").ok_or_else(|| EngineError::BadParams { cmd: "paint.gradient".into(), msg: "missing from".into() })?;+ let to = point(p, "to").ok_or_else(|| EngineError::BadParams { cmd: "paint.gradient".into(), msg: "missing to".into() })?;+ let shape = match p.get("style").and_then(Value::as_str).unwrap_or("linear") {+ "radial" => GradientShape::Radial,+ "angle" => GradientShape::Angle,+ "reflected" => GradientShape::Reflected,+ "diamond" => GradientShape::Diamond,+ _ => GradientShape::Linear,+ };+ let (fg, bg) = (s.tools.foreground, s.tools.background);+ let colors: Vec<[f32; 4]> = match p.get("colors").and_then(Value::as_array) {+ Some(a) if !a.is_empty() => a.iter().map(|v| color(Some(v), fg)).collect(),+ _ => vec![fg, bg],+ };+ let n = colors.len();+ let stops: Vec<(f32, [f32; 4])> = colors.into_iter().enumerate().map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, c)).collect();+ let reverse = b(p, "reverse", false);+ let opacity = f(p, "opacity", 100.0) / 100.0;+ let blend = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(photocraft_color::BlendMode::Normal);+ s.edit("Gradient", |doc, active| {+ let sel = doc.selection.clone();+ let area = sel.as_ref().map(|m| m.content_bounds()).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds()).intersect(&doc.bounds());+ let id = active.ok_or(EngineError::Other("no active layer".into()))?;+ let surf = crate::commands::paint_surface(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?, p)?;+ paint_gradient(surf, area, from, to, shape, &stops, reverse, opacity, blend, sel.as_ref());+ Ok(())+ })?;+ Ok(Value::Null)+}++/// Paint helper command specs.+pub fn specs() -> Vec<CommandSpec> {+ vec![+ CommandSpec {+ id: "paint.bucket",+ label: "Paint Bucket",+ menu: &[],+ shortcut: None,+ params: r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"color":"#rrggbb"=foreground,"opacity":1..100=100}"##,+ enabled: crate::commands::has_paintable,+ run: bucket,+ journal: true,+ },+ CommandSpec {+ id: "paint.gradient",+ label: "Gradient",+ menu: &[],+ shortcut: None,+ params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]=[foreground,background],"reverse":bool=false,"opacity":1..100=100,"mode":"normal|multiply|…"="normal"}"##,+ enabled: crate::commands::has_paintable,+ run: gradient,+ journal: true,+ },+ ]+}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_geom::Rect;++ fn session() -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 20, "height": 10})).unwrap();+ s+ }++ fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {+ let d = s.active().unwrap();+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)+ }++ #[test]+ fn bucket_fill_contiguous() {+ let mut s = session();+ s.edit("wall", |doc, _| {+ doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false})).unwrap();+ assert_eq!(px(&s, 5, 5), vec![1.0, 0.0, 0.0, 1.0]);+ assert_eq!(px(&s, 15, 5), vec![1.0, 1.0, 1.0, 1.0]);+ s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#0000ff", "contiguous": false, "antiAlias": false, "tolerance": 0})).unwrap();+ assert_eq!(px(&s, 5, 5), vec![0.0, 0.0, 1.0, 1.0]);+ }++ #[test]+ fn gradient_tool_with_selection_and_reverse() {+ let mut s = session();+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"]})).unwrap();+ assert!(px(&s, 0, 5)[0] < 0.05 && px(&s, 19, 5)[0] > 0.95);+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"], "reverse": true})).unwrap();+ assert!(px(&s, 0, 5)[0] > 0.95);+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 5, "height": 10})).unwrap();+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [0, 10], "colors": ["#ff0000"]})).unwrap();+ assert_eq!(px(&s, 2, 5)[..3], [1.0, 0.0, 0.0]);+ assert!(px(&s, 10, 5)[1] > 0.4, "outside the selection untouched");+ assert!(s.execute("paint.gradient", json!({"from": [0, 0]})).is_err());+ }+}diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rsindex 2402dd079..e216e9cf4 100644--- a/crates/engine/src/pixels.rs+++ b/crates/engine/src/pixels.rs@@ -20,9 +20,11 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surflet w = r.width() as usize;let mut out = Vec::with_capacity(raw.len());for (i, (a, o)) in buf.px.iter().zip(&orig.px).enumerate() {- let k = selection.map_or(1.0, |sel| sel.pixel(r.x0 + (i % w) as i32, r.y0 + (i / w) as i32)[0]);+ let k = selection.map_or(1.0, |sel| sel.sample_channel(r.x0 + (i % w) as i32, r.y0 + (i / w) as i32, 0));let mixed: [f32; 4] = std::array::from_fn(|c| o[c] + (a[c] - o[c]) * k);- out.extend(from_rgba(&fmt, mixed));+ let mut enc = [0.0f32; 8];+ let m = photocraft_raster::from_rgba_into(&fmt, mixed, &mut enc);+ out.extend_from_slice(&enc[..m]);}s.write_region(r, &out);}@@ -36,7 +38,7 @@ pub fn fill_surface(s: &mut Surface, area: Rect, color: [f32; 4], selection: Optfor (i, px) in region.chunks_exact_mut(n).enumerate() {let x = area.x0 + (i % w) as i32;let y = area.y0 + (i / w) as i32;- let k = selection.map_or(1.0, |sel| sel.pixel(x, y)[0]);+ let k = selection.map_or(1.0, |sel| sel.sample_channel(x, y, 0));if k <= 0.0 {continue;}@@ -50,7 +52,9 @@ pub fn fill_surface(s: &mut Surface, area: Rect, color: [f32; 4], selection: Opt}}o[3] = if lock_transparency { d[3] } else { oa };- px.copy_from_slice(&from_rgba(&fmt, o)[..n]);+ let mut enc = [0.0f32; 8];+ photocraft_raster::from_rgba_into(&fmt, o, &mut enc);+ px.copy_from_slice(&enc[..n]);}s.write_region(area, ®ion);}@@ -65,8 +69,12 @@ pub fn clear_surface(s: &mut Surface, area: Rect, selection: Option<&Surface>) {let mut region = s.read_region(area);let w = area.width() as usize;for (i, px) in region.chunks_exact_mut(n).enumerate() {- let k = selection.map_or(1.0, |sel| sel.pixel(area.x0 + (i % w) as i32, area.y0 + (i / w) as i32)[0]);+ let k = selection.map_or(1.0, |sel| sel.sample_channel(area.x0 + (i % w) as i32, area.y0 + (i / w) as i32, 0));px[n - 1] *= 1.0 - k;+ // Fully cleared pixels become the empty pixel, so bounds and tile pruning see them as gone.+ if px[n - 1] <= 0.0 {+ px.fill(0.0);+ }}s.write_region(area, ®ion);s.prune();diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rsnew file mode 100644index 000000000..a782a09e0--- /dev/null+++ b/crates/engine/src/retouch_cmds.rs@@ -0,0 +1,676 @@+//! Retouching tools as commands: Clone Stamp, Healing Brush, Spot Healing Brush, Dodge, Burn,+//! Sponge, Blur, Sharpen, Smudge and History Brush.+//!+//! Every command takes a Photoshop-style brush (`points`, `size`, `hardness`, `opacity`, `flow`,+//! `spacing`, `layer`), respects the active selection as a mask and the layer's transparency lock, and+//! works at any depth (8/16/32f) and colour model. The pixel algorithms live in `photocraft-algo`+//! (`poisson`, `inpaint`, `retouch`) and the dab machinery in `photocraft-paint::retouch`; this module+//! only parses parameters and wires them together.++use photocraft_algo::inpaint::{self, CompleteParams};+use photocraft_algo::poisson;+use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen, sponge};+use photocraft_color::{BlendMode, PixelFormat, SampleType};+use photocraft_doc::{Document, LayerContent, LayerId};+use photocraft_geom::Rect;+use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke, stroke_coverage};+use photocraft_paint::{BrushSettings, Stroke, StrokePoint};+use photocraft_raster::{Surface, from_rgba_into, to_rgba};+use serde_json::{Value, json};++use crate::commands::{CommandSpec, blend_from_str};+use crate::{EngineError, Result, Session};++fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }+}++fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> {+ let d = s.active().ok_or("no document open")?;+ let l = d.active_layer.and_then(|id| d.doc.layer(id)).ok_or("no active layer")?;+ if matches!(l.content, LayerContent::Raster(_)) { Ok(()) } else { Err(format!("active layer is a {} layer, not a pixel layer", l.content.kind_name())) }+}++fn num(p: &Value, k: &str, d: f32) -> f32 {+ p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32)+}+fn flag(p: &Value, k: &str, d: bool) -> bool {+ p.get(k).and_then(Value::as_bool).unwrap_or(d)+}+fn string<'a>(p: &'a Value, k: &str, d: &'a str) -> &'a str {+ p.get(k).and_then(Value::as_str).unwrap_or(d)+}+fn point(p: &Value, k: &str) -> Option<(f64, f64)> {+ let a = p.get(k)?.as_array()?;+ Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?))+}++/// Parse the shared brush params into a stroke on a layer.+fn parse_brush(s: &Session, p: &Value, cmd: &str) -> Result<(Stroke, LayerId)> {+ let pts: Vec<StrokePoint> = p+ .get("points")+ .and_then(Value::as_array)+ .ok_or_else(|| bad(cmd, "missing `points`"))?+ .iter()+ .filter_map(|v| {+ let a = v.as_array()?;+ Some(StrokePoint { x: a.first()?.as_f64()?, y: a.get(1)?.as_f64()?, pressure: a.get(2).and_then(Value::as_f64).unwrap_or(1.0) as f32 })+ })+ .collect();+ if pts.is_empty() {+ return Err(bad(cmd, "`points` is empty"));+ }+ let base = s.tools.brush.clone();+ let pct = |k: &str, d: f32, lo: f32, hi: f32| num(p, k, d).clamp(lo, hi) / 100.0;+ let brush = BrushSettings {+ size: num(p, "size", base.size).max(1.0),+ hardness: pct("hardness", base.hardness * 100.0, 0.0, 100.0),+ opacity: pct("opacity", 100.0, 1.0, 100.0),+ flow: pct("flow", 100.0, 1.0, 100.0),+ spacing: pct("spacing", 25.0, 1.0, 1000.0),+ erase: false,+ ..base+ };+ let id = match p.get("layer").and_then(Value::as_u64) {+ Some(id) => LayerId(id),+ None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))?,+ };+ Ok((Stroke { brush, points: pts }, id))+}++/// Run `f` on the target layer's surface inside one undoable step. `f` gets the pre-stroke document+/// (a cheap copy-on-write snapshot), the surface, the selection and the transparency lock.+fn run_stroke(+ s: &mut Session,+ label: &str,+ id: LayerId,+ f: impl FnOnce(&Document, &mut Surface, Option<&Surface>, bool) -> Result<Rect>,+) -> Result<Rect> {+ let dmg = s.edit(label, |doc, _| {+ let pre = doc.clone();+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ if l.locks.all || l.locks.pixels {+ return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));+ }+ let lock = l.locks.transparency;+ let surf = l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?;+ // No prune: retouching only rewrites pixels inside the stroke, and scanning every tile of a+ // large layer would dominate the cost of a dab.+ f(&pre, surf, pre.selection.as_ref(), lock)+ })?;+ if let Some(st) = s.active_mut() {+ st.last_damage = Some(dmg);+ }+ Ok(dmg)+}++fn damage_json(r: Rect) -> Value {+ json!([r.x0, r.y0, r.width(), r.height()])+}++// ---------------------------------------------------------------------------------------------+// Sampling sources+// ---------------------------------------------------------------------------------------------++/// Which pixels Clone Stamp / Healing Brush sample.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum SampleLayers {+ Current,+ CurrentAndBelow,+ All,+}++fn sample_layers(p: &Value, cmd: &str) -> Result<SampleLayers> {+ match string(p, "sampleLayer", "current") {+ "current" => Ok(SampleLayers::Current),+ "currentAndBelow" => Ok(SampleLayers::CurrentAndBelow),+ "all" => Ok(SampleLayers::All),+ o => Err(bad(cmd, format!("unknown sampleLayer `{o}` (current|currentAndBelow|all)"))),+ }+}++/// Composite pixels of `rect` in `fmt` (native channels): the whole document, or the target layer+/// and everything below it.+fn composite_region(pre: &Document, id: LayerId, which: SampleLayers, rect: Rect, fmt: PixelFormat) -> Region {+ let mut doc = pre.clone();+ if which == SampleLayers::CurrentAndBelow {+ // Hide everything composited after (above) the target in the bottom-to-top walk.+ let walk: Vec<(Vec<usize>, LayerId)> = pre.walk().into_iter().map(|(p, _, l)| (p, l.id)).collect();+ if let Some(pos) = walk.iter().position(|(_, l)| *l == id) {+ for (path, _) in &walk[pos + 1..] {+ if let Some(l) = doc.layer_at_mut(path) {+ l.visible = false;+ }+ }+ }+ }+ let buf = photocraft_compose::render(&doc, rect);+ let n = fmt.channels();+ let mut out = Region::new(rect, n);+ let mut enc = [0.0f32; 8];+ for (i, px) in buf.px.iter().enumerate() {+ from_rgba_into(&fmt, *px, &mut enc);+ out.data[i * n..(i + 1) * n].copy_from_slice(&enc[..n]);+ }+ out+}++/// Pixels to sample at `rect` (document coordinates, already offset to the source position).+fn sample(pre: &Document, id: LayerId, surf: &Surface, which: SampleLayers, rect: Rect) -> Region {+ match which {+ SampleLayers::Current => Region::read(surf, rect),+ _ => composite_region(pre, id, which, rect, surf.format()),+ }+}++/// Integer clone offset from `offset` or `source` (source − first point).+fn clone_offset(p: &Value, stroke: &Stroke, cmd: &str) -> Result<(i32, i32)> {+ if let Some((dx, dy)) = point(p, "offset") {+ return Ok((dx.round() as i32, dy.round() as i32));+ }+ let (sx, sy) = point(p, "source").ok_or_else(|| bad(cmd, "missing `source` ([x,y]) or `offset` ([dx,dy])"))?;+ let f = stroke.points[0];+ Ok(((sx - f.x).round() as i32, (sy - f.y).round() as i32))+}++/// Result JSON shared by Clone Stamp and Healing Brush: the offset used and where the next stroke+/// should sample from if the UI keeps Photoshop's "Aligned" semantics.+fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value, stroke: &Stroke) -> Value {+ let f = stroke.points[0];+ let source = point(p, "source").unwrap_or((f.x + off.0 as f64, f.y + off.1 as f64));+ // Aligned: the offset persists (next stroke samples at its own first point + offset).+ // Non-aligned: every stroke restarts at the original source point.+ json!({ "damage": damage_json(dmg), "offset": [off.0, off.1], "aligned": aligned, "nextSource": if aligned { Value::Null } else { json!([source.0, source.1]) } })+}++fn blend_param(p: &Value, cmd: &str) -> Result<BlendMode> {+ match p.get("mode").and_then(Value::as_str) {+ None => Ok(BlendMode::Normal),+ Some(m) => blend_from_str(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))),+ }+}++/// Clamp results into the storable range: integer depths to 0..1, float depths only below at 0;+/// alpha always 0..1.+fn clamp_samples(fmt: &PixelFormat, data: &mut [f32]) {+ let n = fmt.channels();+ let a = alpha_index(fmt);+ let float = fmt.sample == SampleType::F32;+ for px in data.chunks_exact_mut(n) {+ for (c, v) in px.iter_mut().enumerate() {+ *v = if Some(c) == a || !float { v.clamp(0.0, 1.0) } else { v.max(0.0) };+ }+ }+}++// ---------------------------------------------------------------------------------------------+// Clone Stamp / Healing Brush / History Brush+// ---------------------------------------------------------------------------------------------++fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "paint.cloneStamp";+ let (stroke, id) = parse_brush(s, p, CMD)?;+ let off = clone_offset(p, &stroke, CMD)?;+ let which = sample_layers(p, CMD)?;+ let mode = blend_param(p, CMD)?;+ let aligned = flag(p, "aligned", true);+ let dmg = run_stroke(s, "Clone Stamp", id, |pre, surf, sel, lock| {+ let (bounds, cov) = stroke_coverage(&stroke);+ // Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned.+ let mut paint = sample(pre, id, surf, which, bounds.translate(off.0, off.1));+ paint.rect = bounds;+ Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))+ })?;+ Ok(clone_result(dmg, off, aligned, p, &stroke))+}++/// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve).+fn pad_coverage(bounds: Rect, cov: &[f32], m: i32) -> (Rect, Vec<f32>) {+ let g = bounds.inflate(m);+ let (w, gw) = (bounds.width() as usize, g.width() as usize);+ let mut out = vec![0.0f32; gw * g.height() as usize];+ for (i, c) in cov.iter().enumerate() {+ let (x, y) = (i % w + m as usize, i / w + m as usize);+ out[y * gw + x] = *c;+ }+ (g, out)+}++/// Seamless-clone `src` into `dst` over the mask (both regions cover the same rect). The solve runs+/// only on the mask's bounding box plus a one-pixel Dirichlet ring; the rest is `dst`.+fn heal_region(fmt: &PixelFormat, src: &Region, dst: &Region, mask: &[bool]) -> Region {+ let w = dst.width();+ let bbox = mask.iter().enumerate().filter(|(_, m)| **m).fold(Rect::EMPTY, |r, (i, _)| {+ let (x, y) = (dst.rect.x0 + (i % w) as i32, dst.rect.y0 + (i / w) as i32);+ r.union(&Rect::new(x, y, x + 1, y + 1))+ });+ let mut out = dst.clone();+ if bbox.is_empty() {+ return out;+ }+ let r = bbox.inflate(1).intersect(&dst.rect);+ let (s, d) = (src.crop(r), dst.crop(r));+ let m: Vec<bool> = (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).map(move |x| (x, y))).map(|(x, y)| mask[dst.index(x, y)]).collect();+ let mut data = poisson::seamless_clone(d.width(), d.height(), d.ch, &s.data, &d.data, &m);+ clamp_samples(fmt, &mut data);+ let (n, rw) = (dst.ch, r.width() as usize);+ for y in r.y0..r.y1 {+ let o = out.index(r.x0, y) * n;+ let i = (y - r.y0) as usize * rw * n;+ out.data[o..o + rw * n].copy_from_slice(&data[i..i + rw * n]);+ }+ out+}++fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "paint.healingBrush";+ let (stroke, id) = parse_brush(s, p, CMD)?;+ let off = clone_offset(p, &stroke, CMD)?;+ let which = sample_layers(p, CMD)?;+ let mode = blend_param(p, CMD)?;+ let aligned = flag(p, "aligned", true);+ let dmg = run_stroke(s, "Healing Brush", id, |pre, surf, sel, lock| {+ let (bounds, cov) = stroke_coverage(&stroke);+ let (g, cov) = pad_coverage(bounds, &cov, 2);+ let fmt = surf.format();+ let mut src = sample(pre, id, surf, which, g.translate(off.0, off.1));+ src.rect = g;+ // The destination the texture is fitted to: the layer itself, or what the user sees when+ // sampling several layers (so healing onto an empty layer matches the composite).+ let dst = if which == SampleLayers::Current { Region::read(surf, g) } else { composite_region(pre, id, which, g, fmt) };+ let mask: Vec<bool> = cov.iter().map(|c| *c > 0.0).collect();+ let healed = heal_region(&fmt, &src, &dst, &mask);+ Ok(apply_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode))+ })?;+ Ok(clone_result(dmg, off, aligned, p, &stroke))+}++fn history_brush(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "paint.historyBrush";+ let (stroke, id) = parse_brush(s, p, CMD)?;+ let mode = blend_param(p, CMD)?;+ let st = s.active().ok_or(EngineError::NoDocument)?;+ let explicit = p.get("state").and_then(Value::as_u64).map(|v| v as usize);+ let source_doc = match explicit {+ Some(i) if i == st.history.past_len() => st.doc.clone(),+ Some(i) => st.history.state(i).ok_or_else(|| bad(CMD, format!("no history state {i} (0..={})", st.history.past_len())))?,+ // Default: the oldest state still held (the "Open" snapshot unless it was trimmed).+ None => st.history.state(0).unwrap_or_else(|| st.doc.clone()),+ };+ let src_surface = source_doc+ .layer(id)+ .and_then(|l| l.surface())+ .cloned()+ .ok_or_else(|| EngineError::Other("the layer did not exist (as a pixel layer) in that history state".into()))?;+ let dmg = run_stroke(s, "History Brush", id, |_, surf, sel, lock| {+ let fmt = surf.format();+ let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) };+ let (bounds, cov) = stroke_coverage(&stroke);+ let paint = Region::read(&src, bounds);+ Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))+ })?;+ Ok(json!({ "damage": damage_json(dmg) }))+}++// ---------------------------------------------------------------------------------------------+// Spot Healing+// ---------------------------------------------------------------------------------------------++/// Dilate a mask by `r` pixels (square structuring element).+fn dilate(w: usize, h: usize, m: &[bool], r: usize) -> Vec<bool> {+ let mut tmp = vec![false; w * h];+ for y in 0..h {+ for x in 0..w {+ if m[y * w + x] {+ for xx in x.saturating_sub(r)..(x + r + 1).min(w) {+ tmp[y * w + xx] = true;+ }+ }+ }+ }+ let mut out = vec![false; w * h];+ for y in 0..h {+ for x in 0..w {+ if tmp[y * w + x] {+ for yy in y.saturating_sub(r)..(y + r + 1).min(h) {+ out[yy * w + x] = true;+ }+ }+ }+ }+ out+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum SpotType {+ ContentAware,+ CreateTexture,+ ProximityMatch,+}++/// Fill the stroke area with no source, then gradient-domain blend it into its surroundings.+fn spot_heal_surface(surf: &mut Surface, area: Rect, stroke: &Stroke, kind: SpotType, sel: Option<&Surface>, lock: bool) -> Rect {+ let (bounds, cov) = stroke_coverage(stroke);+ let size = stroke.brush.size;+ let margin = (size.max(8.0) * 1.0).ceil() as i32 + 8;+ let region_rect = bounds.inflate(margin).intersect(&area);+ if region_rect.is_empty() {+ return Rect::EMPTY;+ }+ let fmt = surf.format();+ let img = Region::read(surf, region_rect);+ let (w, h, ch) = (img.width(), img.height(), img.ch);+ let bw = bounds.width() as usize;+ let mut stroke_cov = vec![0.0f32; w * h];+ for (i, c) in cov.iter().enumerate() {+ let (x, y) = (bounds.x0 + (i % bw) as i32, bounds.y0 + (i / bw) as i32);+ if region_rect.contains(x, y) {+ stroke_cov[img.index(x, y)] = *c;+ }+ }+ let hole: Vec<bool> = stroke_cov.iter().map(|c| *c > 0.0).collect();+ if !hole.iter().any(|h| *h) {+ return Rect::EMPTY;+ }+ // Synthesise over a slightly larger domain than the Poisson region, so the solve's boundary pixels+ // carry synthesised values that differ from the untouched surroundings: that mismatch is what the+ // membrane corrects (otherwise the Dirichlet data would be all zero and the blend a no-op).+ let domain = dilate(w, h, &hole, 2);+ let heal_mask = dilate(w, h, &hole, 1);+ let content_aware = |img: &[f32]| inpaint::complete(w, h, ch, img, &domain, &CompleteParams::default()).unwrap_or_else(|| poisson::membrane_fill(w, h, ch, img, &domain));+ let filled = match kind {+ SpotType::ContentAware => content_aware(&img.data),+ SpotType::CreateTexture => inpaint::synthesize(w, h, ch, &img.data, &domain, (size / 4.0).clamp(6.0, 32.0) as usize, 0x5eed),+ SpotType::ProximityMatch => {+ let ring = (size / 8.0).clamp(3.0, 16.0) as usize;+ match inpaint::best_offset(w, h, ch, &img.data, &domain, ring, margin) {+ Some((dx, dy)) => {+ let mut out = img.data.clone();+ for y in 0..h {+ for x in 0..w {+ if domain[y * w + x] {+ let (i, j) = ((y * w + x) * ch, (((y as i32 + dy) as usize) * w + (x as i32 + dx) as usize) * ch);+ out.copy_within(j..j + ch, i);+ }+ }+ }+ out+ }+ None => content_aware(&img.data),+ }+ }+ };+ let src = Region { rect: region_rect, ch, data: filled };+ let healed = heal_region(&fmt, &src, &img, &heal_mask);+ let dmg = bounds.intersect(®ion_rect);+ let dmg_cov: Vec<f32> = (dmg.y0..dmg.y1).flat_map(|y| (dmg.x0..dmg.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x, y)]).collect();+ apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)+}++fn spot_healing(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "paint.spotHealing";+ let (stroke, id) = parse_brush(s, p, CMD)?;+ let kind = match string(p, "type", "contentAware") {+ "contentAware" => SpotType::ContentAware,+ "createTexture" => SpotType::CreateTexture,+ "proximityMatch" => SpotType::ProximityMatch,+ o => return Err(bad(CMD, format!("unknown type `{o}` (contentAware|createTexture|proximityMatch)"))),+ };+ let dmg = run_stroke(s, "Spot Healing Brush", id, |pre, surf, sel, lock| Ok(spot_heal_surface(surf, pre.bounds(), &stroke, kind, sel, lock)))?;+ Ok(json!({ "damage": damage_json(dmg) }))+}++// ---------------------------------------------------------------------------------------------+// Toning (Dodge / Burn / Sponge) and focus (Blur / Sharpen), Smudge+// ---------------------------------------------------------------------------------------------++/// Per-dab strength such that one pass over a point totals roughly `e`, whatever the spacing+/// (about `1/spacing` dabs overlap each point on the stroke's centre line).+#[inline]+fn per_dab(e: f32, spacing: f32) -> f32 {+ 1.0 - (1.0 - e.clamp(0.0, 1.0)).powf(spacing.clamp(0.01, 1.0))+}++/// Apply an RGB colour transform `f(rgb, strength)` to each covered pixel of a dab (through straight+/// RGBA, so it works for Gray/CMYK/Lab too; untouched pixels are never round-tripped).+fn color_dab(fmt: &PixelFormat, work: &mut Region, fp: &Footprint, strength: f32, spacing: f32, f: impl Fn([f32; 3], f32) -> [f32; 3]) {+ let r = fp.rect.intersect(&work.rect);+ let n = fmt.channels();+ let mut enc = [0.0f32; 8];+ for y in r.y0..r.y1 {+ for x in r.x0..r.x1 {+ let k = per_dab(fp.at(x, y) * strength, spacing);+ if k <= 0.0 {+ continue;+ }+ let px = work.px_mut(x, y);+ let rgba = to_rgba(fmt, px);+ let o = f([rgba[0], rgba[1], rgba[2]], k);+ from_rgba_into(fmt, [o[0], o[1], o[2], rgba[3]], &mut enc);+ let a = alpha_index(fmt);+ for c in 0..n {+ if Some(c) != a {+ px[c] = enc[c];+ }+ }+ }+ }+}++fn tone_range(p: &Value, cmd: &str) -> Result<ToneRange> {+ match string(p, "range", "midtones") {+ "shadows" => Ok(ToneRange::Shadows),+ "midtones" => Ok(ToneRange::Midtones),+ "highlights" => Ok(ToneRange::Highlights),+ o => Err(bad(cmd, format!("unknown range `{o}` (shadows|midtones|highlights)"))),+ }+}++fn dodge_burn_cmd(s: &mut Session, p: &Value, burn: bool) -> Result<Value> {+ let cmd = if burn { "paint.burn" } else { "paint.dodge" };+ let (stroke, id) = parse_brush(s, p, cmd)?;+ let range = tone_range(p, cmd)?;+ let exposure = num(p, "exposure", 50.0).clamp(1.0, 100.0) / 100.0;+ let protect = flag(p, "protectTones", true);+ let label = if burn { "Burn Tool" } else { "Dodge Tool" };+ let dmg = run_stroke(s, label, id, |_, surf, sel, lock| {+ let fmt = surf.format();+ let sp = stroke.brush.spacing;+ Ok(apply_dab_stroke(surf, &stroke, sel, lock, 0, |work, fp| color_dab(&fmt, work, fp, exposure, sp, |c, k| dodge_burn(c, k, range, burn, protect))))+ })?;+ Ok(json!({ "damage": damage_json(dmg) }))+}++fn sponge_cmd(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "paint.sponge";+ let (stroke, id) = parse_brush(s, p, CMD)?;+ let saturate = match string(p, "mode", "desaturate") {+ "desaturate" => false,+ "saturate" => true,+ o => return Err(bad(CMD, format!("unknown mode `{o}` (desaturate|saturate)"))),+ };+ let vibrance = flag(p, "vibrance", true);+ let dmg = run_stroke(s, "Sponge Tool", id, |_, surf, sel, lock| {+ let fmt = surf.format();+ let sp = stroke.brush.spacing;+ // Flow is already in each dab's coverage; a full-flow pass moves colours half-way.+ Ok(apply_dab_stroke(surf, &stroke, sel, lock, 0, |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge(c, k, saturate, vibrance))))+ })?;+ Ok(json!({ "damage": damage_json(dmg) }))+}++/// Blur (`sharpen = false`) or Sharpen each dab's footprint in the working copy.+fn focus_cmd(s: &mut Session, p: &Value, sharpen: bool) -> Result<Value> {+ let cmd = if sharpen { "paint.sharpen" } else { "paint.blur" };+ let (stroke, id) = parse_brush(s, p, cmd)?;+ let strength = num(p, "strength", 50.0).clamp(1.0, 100.0) / 100.0;+ let protect = flag(p, "protectDetail", true);+ let sigma = (stroke.brush.size * 0.03).clamp(1.0, 4.0);+ let halo = (sigma * 3.0).ceil() as i32 + 1;+ let label = if sharpen { "Sharpen Tool" } else { "Blur Tool" };+ let dmg = run_stroke(s, label, id, |_, surf, sel, lock| {+ let fmt = surf.format();+ let a = alpha_index(&fmt);+ let sp = stroke.brush.spacing;+ Ok(apply_dab_stroke(surf, &stroke, sel, lock, halo, |work, fp| {+ let r = fp.rect.intersect(&work.rect);+ if r.is_empty() {+ return;+ }+ let (w, h, n) = (work.width(), work.height(), work.ch);+ let win = ((r.x0 - work.rect.x0) as usize, (r.y0 - work.rect.y0) as usize, (r.x1 - work.rect.x0) as usize, (r.y1 - work.rect.y0) as usize);+ let out = if sharpen { local_sharpen(&work.data, w, h, n, a, win, 1.0, protect) } else { local_blur(&work.data, w, h, n, a, win, sigma) };+ let rw = r.width() as usize;+ for y in r.y0..r.y1 {+ for x in r.x0..r.x1 {+ let k = per_dab(fp.at(x, y) * strength, sp);+ if k <= 0.0 {+ continue;+ }+ let o = ((y - r.y0) as usize * rw + (x - r.x0) as usize) * n;+ let px = work.px_mut(x, y);+ for c in 0..n {+ px[c] += (out[o + c] - px[c]) * k;+ }+ }+ }+ }))+ })?;+ Ok(json!({ "damage": damage_json(dmg) }))+}++fn smudge_cmd(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "paint.smudge";+ let (stroke, id) = parse_brush(s, p, CMD)?;+ let strength = num(p, "strength", 50.0).clamp(1.0, 100.0) / 100.0;+ let finger = flag(p, "fingerPainting", false);+ let fg = s.tools.foreground;+ let dmg = run_stroke(s, "Smudge Tool", id, |_, surf, sel, lock| {+ let fmt = surf.format();+ let finger_px = finger.then(|| photocraft_raster::from_rgba(&fmt, fg));+ let max_size = stroke.brush.size;+ let mut sm = Smudge::new(strength, finger_px, max_size);+ Ok(apply_dab_stroke(surf, &stroke, sel, lock, 0, |work, fp| sm.dab(work, fp)))+ })?;+ Ok(json!({ "damage": damage_json(dmg) }))+}++// ---------------------------------------------------------------------------------------------+// Registry+// ---------------------------------------------------------------------------------------------++/// The brush every retouching command shares, plus the tool's own params.+macro_rules! brush_params {+ ($extra:literal) => {+ concat!("{", r#""points":[[x,y,pressure?],…],"size":px=tool size,"hardness":0..100=tool hardness,"opacity":1..100=100,"flow":1..100=100,"spacing":1..1000 (% of size)=25,"layer":id?=active"#, $extra, "}")+ };+}++/// Retouching command specs.+pub fn specs() -> Vec<CommandSpec> {+ vec![+ CommandSpec {+ id: "paint.cloneStamp",+ label: "Clone Stamp",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","source":[sx,sy] (sampled under the first point) | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|multiply|…"="normal" → {"damage","offset","aligned","nextSource"}"#),+ enabled: has_pixel_layer,+ run: clone_stamp,+ journal: true,+ },+ CommandSpec {+ id: "paint.healingBrush",+ label: "Healing Brush",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal" → {"damage","offset","aligned","nextSource"}"#),+ enabled: has_pixel_layer,+ run: healing_brush,+ journal: true,+ },+ CommandSpec {+ id: "paint.spotHealing",+ label: "Spot Healing Brush",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","type":"contentAware|createTexture|proximityMatch"="contentAware""#),+ enabled: has_pixel_layer,+ run: spot_healing,+ journal: true,+ },+ CommandSpec {+ id: "paint.dodge",+ label: "Dodge",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#),+ enabled: has_pixel_layer,+ run: |s, p| dodge_burn_cmd(s, p, false),+ journal: true,+ },+ CommandSpec {+ id: "paint.burn",+ label: "Burn",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#),+ enabled: has_pixel_layer,+ run: |s, p| dodge_burn_cmd(s, p, true),+ journal: true,+ },+ CommandSpec {+ id: "paint.sponge",+ label: "Sponge",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","mode":"desaturate|saturate"="desaturate","vibrance":bool=true (flow = sponge strength)"#),+ enabled: has_pixel_layer,+ run: sponge_cmd,+ journal: true,+ },+ CommandSpec {+ id: "paint.blur",+ label: "Blur",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","strength":1..100=50"#),+ enabled: has_pixel_layer,+ run: |s, p| focus_cmd(s, p, false),+ journal: true,+ },+ CommandSpec {+ id: "paint.sharpen",+ label: "Sharpen",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","strength":1..100=50,"protectDetail":bool=true"#),+ enabled: has_pixel_layer,+ run: |s, p| focus_cmd(s, p, true),+ journal: true,+ },+ CommandSpec {+ id: "paint.smudge",+ label: "Smudge",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","strength":1..100=50,"fingerPainting":bool=false (starts with the foreground colour)"#),+ enabled: has_pixel_layer,+ run: smudge_cmd,+ journal: true,+ },+ CommandSpec {+ id: "paint.historyBrush",+ label: "History Brush",+ menu: &[],+ shortcut: None,+ params: brush_params!(r#","state":index (into history.entries; default 0 = the oldest held state, normally the Open snapshot)"#),+ enabled: has_pixel_layer,+ run: history_brush,+ journal: true,+ },+ ]+}++#[cfg(test)]+mod tests;diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rsnew file mode 100644index 000000000..cd12a55af--- /dev/null+++ b/crates/engine/src/retouch_cmds/tests.rs@@ -0,0 +1,293 @@+use super::*;+use photocraft_color::ColorMode;++const DEPTHS: [u64; 3] = [8, 16, 32];++fn session(w: u32, h: u32, depth: u64, mode: &str) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": w, "height": h, "depth": depth, "mode": mode})).unwrap();+ s+}++/// Straight RGBA of the active layer at a pixel.+fn rgba(s: &Session, x: i32, y: i32) -> [f32; 4] {+ let d = s.active().unwrap();+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)+}++fn paint_layer(s: &mut Session, f: impl Fn(i32, i32) -> [f32; 4]) {+ s.edit("setup", |doc, active| {+ let b = doc.bounds();+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();+ let fmt = surf.format();+ let mut data = Vec::new();+ for y in b.y0..b.y1 {+ for x in b.x0..b.x1 {+ data.extend(photocraft_raster::from_rgba(&fmt, f(x, y)));+ }+ }+ surf.write_region(b, &data);+ Ok(())+ })+ .unwrap();+}++fn tol(depth: u64) -> f32 {+ if depth == 8 { 1.0 / 255.0 + 1e-4 } else { 1e-3 }+}++/// A smooth colour gradient plus deterministic fine noise.+fn texture(x: i32, y: i32) -> [f32; 4] {+ let n = ((x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663)) as u32 % 1000) as f32 / 1000.0 * 0.06 - 0.03;+ [0.3 + 0.004 * x as f32 + n, 0.5 + 0.003 * y as f32 + n, 0.45 + n, 1.0]+}++#[test]+fn clone_stamp_copies_exactly_at_all_depths() {+ for depth in DEPTHS {+ let mut s = session(96, 64, depth, "rgb");+ paint_layer(&mut s, |x, y| [x as f32 / 96.0, y as f32 / 64.0, ((x * 7 + y * 3) % 11) as f32 / 11.0, 1.0]);+ let r = s.execute("paint.cloneStamp", json!({"points": [[60, 30], [80, 30]], "source": [20, 20], "size": 10, "hardness": 100})).unwrap();+ assert_eq!(r["offset"], json!([-40, -10]));+ assert!(r["nextSource"].is_null(), "aligned keeps the offset");+ for x in [60, 70, 80] {+ let (got, want) = (rgba(&s, x, 30), rgba(&s, x - 40, 20));+ for c in 0..4 {+ assert!((got[c] - want[c]).abs() <= tol(depth), "depth {depth} x {x}: {got:?} vs {want:?}");+ }+ }+ // Outside the brush untouched.+ let far = rgba(&s, 70, 50);+ assert!((far[0] - 70.0 / 96.0).abs() <= tol(depth) && (far[1] - 50.0 / 64.0).abs() <= tol(depth));+ // One undo step.+ assert!(s.undo());+ assert!((rgba(&s, 70, 30)[1] - 30.0 / 64.0).abs() <= tol(depth));+ }+}++#[test]+fn clone_stamp_samples_pre_stroke_state_and_non_aligned_returns_source() {+ let mut s = session(80, 20, 16, "rgb");+ paint_layer(&mut s, |x, _| [x as f32 / 80.0, 0.0, 0.0, 1.0]);+ // Source 4 px to the right of the stroke start, stroke runs right: without pre-stroke sampling the+ // stroke would re-clone its own output and smear.+ let r = s.execute("paint.cloneStamp", json!({"points": [[10, 10], [50, 10]], "source": [14, 10], "size": 6, "hardness": 100, "aligned": false})).unwrap();+ assert_eq!(r["nextSource"], json!([14.0, 10.0]));+ for x in [20, 30, 45] {+ assert!((rgba(&s, x, 10)[0] - (x + 4) as f32 / 80.0).abs() < 1e-3, "x {x}");+ }+ assert!(s.execute("paint.cloneStamp", json!({"points": [[1, 1]]})).is_err(), "source is required");+ // An explicit offset works too.+ s.execute("paint.cloneStamp", json!({"points": [[70, 10]], "offset": [-60, 0], "size": 4, "hardness": 100})).unwrap();+ assert!((rgba(&s, 70, 10)[0] - 14.0 / 80.0).abs() < 1e-3, "samples the current state (x=10 was cloned from x=14)");+}++#[test]+fn clone_stamp_sample_all_layers_onto_empty_layer_and_opacity() {+ let mut s = session(64, 32, 8, "rgb");+ paint_layer(&mut s, |x, _| if x < 32 { [1.0, 0.0, 0.0, 1.0] } else { [1.0, 1.0, 1.0, 1.0] });+ s.execute("layer.new.layer", json!({})).unwrap();+ // Current layer is empty: sampling "current" clones transparency (a no-op) …+ s.execute("paint.cloneStamp", json!({"points": [[48, 16]], "source": [16, 16], "size": 8, "hardness": 100})).unwrap();+ assert_eq!(rgba(&s, 48, 16)[3], 0.0);+ // … sampling all layers clones the visible red.+ s.execute("paint.cloneStamp", json!({"points": [[48, 16]], "source": [16, 16], "size": 8, "hardness": 100, "sampleLayer": "all"})).unwrap();+ let p = rgba(&s, 48, 16);+ assert!(p[0] > 0.99 && p[1] < 0.01 && p[3] > 0.99, "{p:?}");+ // currentAndBelow on the bottom layer ignores layers above.+ s.execute("paint.cloneStamp", json!({"points": [[40, 5]], "source": [8, 5], "size": 4, "hardness": 100, "opacity": 50, "sampleLayer": "currentAndBelow"})).unwrap();+ let p = rgba(&s, 40, 5);+ assert!((p[3] - 0.5).abs() < 0.02, "opacity 50 → half alpha {p:?}");+ assert!(s.execute("paint.cloneStamp", json!({"points": [[1, 1]], "source": [0, 0], "sampleLayer": "nope"})).is_err());+}++#[test]+fn clone_stamp_respects_selection_and_cmyk() {+ let mut s = session(64, 32, 8, "cmyk");+ paint_layer(&mut s, |x, _| if x < 32 { [0.0, 0.0, 1.0, 1.0] } else { [1.0, 1.0, 0.0, 1.0] });+ s.execute("select.rect", json!({"x": 40, "y": 0, "width": 8, "height": 32})).unwrap();+ s.execute("paint.cloneStamp", json!({"points": [[36, 16], [56, 16]], "offset": [-30, 0], "size": 8, "hardness": 100})).unwrap();+ assert!(rgba(&s, 44, 16)[2] > 0.95, "inside the selection: cloned blue");+ assert!(rgba(&s, 52, 16)[2] < 0.05, "outside the selection: untouched yellow");+}++#[test]+fn healing_brush_takes_destination_colour_and_source_texture() {+ for depth in [8u64, 32] {+ let mut s = session(128, 64, depth, "rgb");+ // Left: dark blue with strong vertical stripes (the texture); right: flat light orange.+ paint_layer(&mut s, |x, _| {+ if x < 64 {+ let t = if (x / 3) % 2 == 0 { 0.08 } else { -0.08 };+ [0.1 + t + 0.1, 0.15 + t + 0.1, 0.5 + t, 1.0]+ } else {+ [0.9, 0.6, 0.3, 1.0]+ }+ });+ s.execute("paint.healingBrush", json!({"points": [[96, 32]], "source": [32, 32], "size": 30, "hardness": 100})).unwrap();+ // Inside the healed disc: mean ≈ destination colour, variance ≈ source texture.+ let pts: Vec<(i32, i32)> = (-8..=8).flat_map(|dy| (-8..=8).map(move |dx| (96 + dx, 32 + dy))).collect();+ let vals: Vec<[f32; 4]> = pts.iter().map(|&(x, y)| rgba(&s, x, y)).collect();+ let mean: Vec<f32> = (0..3).map(|c| vals.iter().map(|v| v[c]).sum::<f32>() / vals.len() as f32).collect();+ for (c, want) in [0.9f32, 0.6, 0.3].iter().enumerate() {+ assert!((mean[c] - want).abs() < 0.06, "depth {depth} channel {c}: mean {} want {want}", mean[c]);+ }+ let var = vals.iter().map(|v| (v[1] - mean[1]).powi(2)).sum::<f32>() / vals.len() as f32;+ assert!(var > 0.003, "texture carried: variance {var}");+ // Horizontal gradient pattern matches the source stripes (period 6).+ let (a, b) = (rgba(&s, 96, 32)[1] - rgba(&s, 95, 32)[1], rgba(&s, 32, 32)[1] - rgba(&s, 31, 32)[1]);+ assert!((a - b).abs() < 0.03, "gradient {a} vs source {b}");+ // Far away untouched.+ assert!((rgba(&s, 125, 3)[0] - 0.9).abs() <= tol(depth));+ }+}++#[test]+fn spot_healing_removes_blemish_all_types() {+ for (depth, kind) in [(8u64, "contentAware"), (16, "contentAware"), (32, "contentAware"), (8, "proximityMatch"), (16, "createTexture")] {+ let mut s = session(160, 120, depth, "rgb");+ paint_layer(&mut s, |x, y| {+ let d = ((x - 80) as f32).hypot((y - 60) as f32);+ if d < 6.0 { [0.05, 0.03, 0.02, 1.0] } else { texture(x, y) }+ });+ let err = |s: &Session| {+ let mut e = 0.0f32;+ let mut n = 0;+ for y in 52..=68 {+ for x in 72..=88 {+ let (p, t) = (rgba(s, x, y), texture(x, y));+ e += (0..3).map(|c| (p[c] - t[c]).powi(2)).sum::<f32>();+ n += 3;+ }+ }+ (e / n as f32).sqrt()+ };+ let before = err(&s);+ s.execute("paint.spotHealing", json!({"points": [[80, 60]], "size": 20, "hardness": 100, "type": kind})).unwrap();+ let after = err(&s);+ assert!(after < 0.05 && after < before * 0.2, "{kind} depth {depth}: rmse {before} → {after}");+ // Far away untouched.+ let (p, t) = (rgba(&s, 10, 10), texture(10, 10));+ assert!((p[0] - t[0]).abs() <= tol(depth) + 1e-3);+ }+}++#[test]+fn dodge_brightens_midtones_more_than_shadows_and_burn_darkens() {+ for depth in DEPTHS {+ let mut s = session(80, 20, depth, "rgb");+ paint_layer(&mut s, |x, _| if x < 40 { [0.5, 0.5, 0.5, 1.0] } else { [0.08, 0.08, 0.08, 1.0] });+ s.execute("paint.dodge", json!({"points": [[5, 10], [75, 10]], "size": 10, "hardness": 100})).unwrap();+ let (mid, shadow) = (rgba(&s, 20, 10)[0] - 0.5, rgba(&s, 60, 10)[0] - 0.08);+ assert!(mid > 0.05, "depth {depth}: midtone +{mid}");+ assert!(mid > 2.0 * shadow.max(0.0), "depth {depth}: midtone +{mid} shadow +{shadow}");+ s.execute("paint.burn", json!({"points": [[5, 15], [35, 15]], "size": 6, "hardness": 100, "exposure": 80})).unwrap();+ assert!(rgba(&s, 20, 15)[0] < 0.45);+ // Shadows range dodges the dark side more than the grey.+ s.execute("paint.dodge", json!({"points": [[5, 3], [75, 3]], "size": 4, "hardness": 100, "range": "shadows"})).unwrap();+ assert!(rgba(&s, 60, 3)[0] - 0.08 > rgba(&s, 20, 3)[0] - 0.5);+ }+ // Grayscale document too.+ let mut s = session(20, 20, 8, "gray");+ s.execute("paint.burn", json!({"points": [[10, 10]], "size": 6, "hardness": 100, "range": "highlights"})).unwrap();+ assert!(rgba(&s, 10, 10)[0] < 0.9);+ assert_eq!(s.active().unwrap().doc.mode, ColorMode::Grayscale);+}++#[test]+fn sponge_reduces_and_increases_saturation() {+ for depth in DEPTHS {+ let mut s = session(40, 20, depth, "rgb");+ paint_layer(&mut s, |_, _| [0.8, 0.4, 0.3, 1.0]);+ let sat = |p: [f32; 4]| photocraft_algo::retouch::saturation([p[0], p[1], p[2]]);+ let s0 = sat(rgba(&s, 10, 10));+ s.execute("paint.sponge", json!({"points": [[2, 10], [38, 10]], "size": 8, "hardness": 100})).unwrap();+ let s1 = sat(rgba(&s, 10, 10));+ assert!(s1 < s0 * 0.8, "depth {depth}: {s0} → {s1}");+ s.execute("paint.sponge", json!({"points": [[2, 3], [38, 3]], "size": 4, "hardness": 100, "mode": "saturate", "vibrance": false})).unwrap();+ assert!(sat(rgba(&s, 10, 3)) > s0);+ }+}++#[test]+fn blur_reduces_local_variance_and_sharpen_increases_it() {+ for depth in [8u64, 16] {+ let mut s = session(60, 30, depth, "rgb");+ paint_layer(&mut s, |x, y| if (x + y) % 2 == 0 { [0.3, 0.3, 0.3, 1.0] } else { [0.7, 0.7, 0.7, 1.0] });+ let var = |s: &Session, x0: i32| {+ let v: Vec<f32> = (10..20).flat_map(|y| (x0..x0 + 10).map(move |x| (x, y))).map(|(x, y)| rgba(s, x, y)[0]).collect();+ let m = v.iter().sum::<f32>() / v.len() as f32;+ v.iter().map(|a| (a - m).powi(2)).sum::<f32>() / v.len() as f32+ };+ let v0 = var(&s, 10);+ s.execute("paint.blur", json!({"points": [[5, 15], [25, 15]], "size": 20, "hardness": 100, "strength": 100})).unwrap();+ assert!(var(&s, 10) < v0 * 0.5, "depth {depth}: {v0} → {}", var(&s, 10));+ assert!((var(&s, 45) - v0).abs() < 1e-3, "outside untouched");+ // Sharpen a low-contrast checkerboard: contrast grows; Protect Detail caps it at the local range.+ let mut s = session(60, 30, depth, "rgb");+ paint_layer(&mut s, |x, y| if (x + y) % 2 == 0 { [0.45, 0.45, 0.45, 1.0] } else { [0.55, 0.55, 0.55, 1.0] });+ let v0 = var(&s, 10);+ s.execute("paint.sharpen", json!({"points": [[5, 15], [25, 15]], "size": 20, "hardness": 100, "strength": 100, "protectDetail": false})).unwrap();+ assert!(var(&s, 10) > v0 * 1.5, "depth {depth}: {v0} → {}", var(&s, 10));+ s.execute("paint.sharpen", json!({"points": [[35, 15], [55, 15]], "size": 20, "hardness": 100, "strength": 100})).unwrap();+ let hi = (10..20).flat_map(|y| (40..50).map(move |x| (x, y))).map(|(x, y)| rgba(&s, x, y)[0]).fold(0.0, f32::max);+ assert!(hi <= 0.55 + tol(depth), "protect detail: {hi}");+ }+}++#[test]+fn smudge_moves_colour_along_the_stroke() {+ for depth in DEPTHS {+ let mut s = session(100, 30, depth, "rgb");+ paint_layer(&mut s, |x, _| if x < 30 { [1.0, 0.0, 0.0, 1.0] } else { [1.0, 1.0, 1.0, 1.0] });+ s.execute("paint.smudge", json!({"points": [[20, 15], [70, 15]], "size": 12, "hardness": 100, "strength": 80})).unwrap();+ let g = |x| rgba(&s, x, 15)[1];+ assert!(g(36) < 0.6, "depth {depth}: red dragged right ({})", g(36));+ assert!(g(36) < g(65));+ assert!(rgba(&s, 36, 2)[1] > 0.99, "off-stroke untouched");+ s.execute("tools.setColors", json!({"foreground": "#0000ff"})).unwrap();+ s.execute("paint.smudge", json!({"points": [[80, 25], [95, 25]], "size": 6, "hardness": 100, "fingerPainting": true})).unwrap();+ assert!(rgba(&s, 81, 25)[0] < 0.7, "finger painting lays down the foreground colour");+ }+}++#[test]+fn history_brush_restores_earlier_pixels() {+ for depth in [8u64, 32] {+ let mut s = session(40, 20, depth, "rgb");+ s.execute("paint.stroke", json!({"points": [[0, 10], [40, 10]], "size": 12, "hardness": 1.0, "color": "#ff0000"})).unwrap();+ s.execute("paint.stroke", json!({"points": [[0, 10], [40, 10]], "size": 12, "hardness": 1.0, "color": "#00ff00"})).unwrap();+ assert!(rgba(&s, 20, 10)[1] > 0.99);+ // State 1 = after the red stroke.+ s.execute("paint.historyBrush", json!({"points": [[5, 10], [15, 10]], "size": 6, "hardness": 100, "state": 1})).unwrap();+ let p = rgba(&s, 10, 10);+ assert!(p[0] > 0.99 && p[1] < 0.01, "depth {depth}: {p:?}");+ // Default = the Open snapshot: white.+ s.execute("paint.historyBrush", json!({"points": [[25, 10], [35, 10]], "size": 6, "hardness": 100})).unwrap();+ assert!(rgba(&s, 30, 10).iter().all(|v| *v > 0.99));+ assert!(rgba(&s, 20, 10)[1] > 0.99, "between the dabs still green");+ assert!(s.execute("paint.historyBrush", json!({"points": [[5, 10]], "state": 99})).is_err());+ }+}++#[test]+fn history_brush_errors_when_layer_is_new() {+ let mut s = session(20, 20, 8, "rgb");+ s.execute("layer.new.layer", json!({})).unwrap();+ assert!(s.execute("paint.historyBrush", json!({"points": [[5, 5]], "state": 0})).is_err());+}++#[test]+fn retouch_commands_are_registered_and_need_a_pixel_layer() {+ let ids = ["paint.cloneStamp", "paint.healingBrush", "paint.spotHealing", "paint.dodge", "paint.burn", "paint.sponge", "paint.blur", "paint.sharpen", "paint.smudge", "paint.historyBrush"];+ for id in ids {+ let spec = crate::commands::find(id).unwrap_or_else(|| panic!("{id} missing"));+ assert!(spec.params.contains("\"points\"") && spec.params.contains("spacing"), "{id}");+ assert!(!Session::new().is_enabled(id));+ }+ let mut s = session(10, 10, 8, "rgb");+ assert!(s.execute("paint.dodge", json!({"points": []})).is_err());+ assert!(s.execute("paint.dodge", json!({"points": [[1, 1]], "range": "bogus"})).is_err());+ assert!(s.execute("paint.spotHealing", json!({"points": [[1, 1]], "type": "bogus"})).is_err());+}+diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rsnew file mode 100644index 000000000..ccba3024b--- /dev/null+++ b/crates/engine/src/selection_cmds.rs@@ -0,0 +1,295 @@+//! Select menu and selection tools: Magic Wand, Color Range, Modify+//! (expand/contract/border/smooth/feather), Grow, Similar, Lasso.+//! Selections are grayscale coverage surfaces clipped to the canvas.++use photocraft_algo::selection::{self as sel, SelectionMode};+use photocraft_doc::Document;+use photocraft_geom::Rect;+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++fn has_doc(s: &Session) -> std::result::Result<(), String> {+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())+}+fn has_selection(s: &Session) -> std::result::Result<(), String> {+ s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into())+}++fn f(p: &Value, k: &str, d: f32) -> f32 {+ p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32)+}+fn b(p: &Value, k: &str, d: bool) -> bool {+ p.get(k).and_then(Value::as_bool).unwrap_or(d)+}+fn mode(p: &Value) -> SelectionMode {+ SelectionMode::parse(p.get("mode").and_then(Value::as_str).unwrap_or("replace"))+}++/// RGBA pixels the tools sample: the composite, or the active layer.+fn sample_pixels(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[f32; 4]>)> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let area = d.doc.bounds();+ let layer = d.active_layer.and_then(|id| d.doc.layer(id)).and_then(|l| l.surface());+ match (all_layers, layer) {+ (false, Some(surf)) => {+ let mut px = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize];+ surf.read_rgba_into(area, &mut px);+ Ok((area, px))+ }+ _ => Ok((area, photocraft_compose::render(&d.doc, area).px)),+ }+}++fn set_selection(s: &mut Session, label: &str, area: Rect, mask: Vec<f32>, m: SelectionMode) -> Result<Value> {+ let selected = s.edit(label, |doc, _| {+ doc.selection = sel::combine(doc.selection.as_ref(), &mask, area, m);+ Ok(doc.selection.is_some())+ })?;+ Ok(json!({ "selected": selected }))+}++fn current_mask(doc: &Document) -> (Rect, Vec<f32>) {+ let area = doc.bounds();+ (area, sel::mask_from_surface(doc.selection.as_ref(), area))+}++/// 8-bit RGBA of the active layer (or the composite with `all_layers`) over the canvas.+pub(crate) fn sample_rgba8(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[u8; 4]>)> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let area = d.doc.bounds();+ let layer = d.active_layer.and_then(|id| d.doc.layer(id)).and_then(|l| l.surface());+ match (all_layers, layer) {+ (false, Some(surf)) => Ok((area, sel::rgba8_image(surf, area))),+ _ => {+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;+ Ok((area, photocraft_compose::render(&d.doc, area).px.iter().map(|p| p.map(q)).collect()))+ }+ }+}++fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {+ let (x, y) = (f(p, "x", 0.0).floor() as i32, f(p, "y", 0.0).floor() as i32);+ let (area, img) = sample_rgba8(s, b(p, "sampleAllLayers", false))?;+ let region = sel::wand_region(&img, area, (x, y), f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true));+ drop(img);+ let m = mode(p);+ let selected = s.edit("Magic Wand", |doc, _| {+ doc.selection = sel::combine_region(doc.selection.as_ref(), region.as_ref(), m);+ Ok(doc.selection.is_some())+ })?;+ Ok(json!({ "selected": selected }))+}++fn parse_color(p: &Value) -> [f32; 3] {+ match p.get("color") {+ Some(Value::Array(a)) if a.len() >= 3 => [0, 1, 2].map(|i| a[i].as_f64().unwrap_or(0.0) as f32),+ Some(Value::String(h)) => {+ let h = h.trim_start_matches('#');+ let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map_or(0.0, |v| f32::from(v) / 255.0);+ [c(0), c(2), c(4)]+ }+ _ => [0.0; 3],+ }+}++fn color_range(s: &mut Session, p: &Value) -> Result<Value> {+ let color = if p.get("color").is_some() { parse_color(p) } else { let f = s.tools.foreground; [f[0], f[1], f[2]] };+ let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?;+ let mask = sel::color_range(&px, color, f(p, "fuzziness", 40.0));+ set_selection(s, "Color Range", area, mask, mode(p))+}++fn modify(s: &mut Session, p: &Value, op: &str) -> Result<Value> {+ let r = f(p, "radius", 1.0).max(0.0);+ let (area, m) = current_mask(&s.active().ok_or(EngineError::NoDocument)?.doc);+ let (w, h) = (area.width() as usize, area.height() as usize);+ let out = match op {+ "expand" => sel::expand(&m, w, h, r),+ "contract" => sel::contract(&m, w, h, r),+ "border" => sel::border(&m, w, h, r),+ "smooth" => sel::smooth(&m, w, h, r),+ _ => sel::feather(&m, w, h, r),+ };+ let label = match op {+ "expand" => "Expand Selection",+ "contract" => "Contract Selection",+ "border" => "Border Selection",+ "smooth" => "Smooth Selection",+ _ => "Feather Selection",+ };+ set_selection(s, label, area, out, SelectionMode::Replace)+}++/// Grow (contiguous) / Similar (anywhere): pixels whose colour lies within+/// the selected pixels' colour range widened by the tolerance.+fn grow_similar(s: &mut Session, p: &Value, contiguous: bool) -> Result<Value> {+ let tol = f(p, "tolerance", 32.0) / 255.0;+ let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", false))?;+ let (_, m) = current_mask(&s.active().ok_or(EngineError::NoDocument)?.doc);+ let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);+ for (q, v) in px.iter().zip(&m) {+ if *v >= 0.5 {+ for c in 0..4 {+ lo[c] = lo[c].min(q[c]);+ hi[c] = hi[c].max(q[c]);+ }+ }+ }+ if lo[0] > hi[0] {+ return Err(EngineError::Other("selection is empty".into()));+ }+ let inside = |q: &[f32; 4]| (0..4).all(|c| q[c] >= lo[c] - tol - 1e-6 && q[c] <= hi[c] + tol + 1e-6);+ let (w, h) = (area.width() as usize, area.height() as usize);+ let mut out: Vec<f32> = m.iter().map(|v| if *v >= 0.5 { 1.0 } else { 0.0 }).collect();+ if contiguous {+ let mut stack: Vec<usize> = (0..out.len()).filter(|i| out[*i] > 0.0).collect();+ while let Some(i) = stack.pop() {+ let (x, y) = (i % w, i / w);+ let n = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)];+ for j in n.into_iter().flatten() {+ if out[j] == 0.0 && inside(&px[j]) {+ out[j] = 1.0;+ stack.push(j);+ }+ }+ }+ } else {+ for (o, q) in out.iter_mut().zip(&px) {+ if inside(q) {+ *o = 1.0;+ }+ }+ }+ set_selection(s, if contiguous { "Grow" } else { "Similar" }, area, out, SelectionMode::Replace)+}++fn lasso(s: &mut Session, p: &Value) -> Result<Value> {+ let pts: Vec<(f32, f32)> = p+ .get("points")+ .and_then(Value::as_array)+ .map(|a| a.iter().filter_map(|q| Some((q.get(0)?.as_f64()? as f32, q.get(1)?.as_f64()? as f32))).collect())+ .unwrap_or_default();+ if pts.len() < 3 {+ return Err(EngineError::BadParams { cmd: "select.lasso".into(), msg: "needs at least 3 points".into() });+ }+ let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds();+ let mut mask = sel::polygon(&pts, area, b(p, "antiAlias", true));+ let feather = f(p, "feather", 0.0);+ if feather > 0.0 {+ mask = sel::feather(&mask, area.width() as usize, area.height() as usize, feather);+ }+ set_selection(s, "Lasso", area, mask, mode(p))+}++macro_rules! spec {+ ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => {+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true }+ };+}++/// Selection command specs.+pub fn specs() -> Vec<CommandSpec> {+ vec![+ spec!("select.magicWand", "Magic Wand", [], r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"mode":"replace|add|subtract|intersect"="replace"}"##, has_doc, magic_wand),+ spec!("select.colorRange", "Color Range…", ["Select"], r##"{"color":"#rrggbb"=foreground,"fuzziness":0..200=40,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, has_doc, color_range),+ spec!("select.modify.border", "Border…", ["Select", "Modify"], r##"{"radius":1..200=1}"##, has_selection, |s, p| modify(s, p, "border")),+ spec!("select.modify.smooth", "Smooth…", ["Select", "Modify"], r##"{"radius":1..500=1}"##, has_selection, |s, p| modify(s, p, "smooth")),+ spec!("select.modify.expand", "Expand…", ["Select", "Modify"], r##"{"radius":1..500=1}"##, has_selection, |s, p| modify(s, p, "expand")),+ spec!("select.modify.contract", "Contract…", ["Select", "Modify"], r##"{"radius":1..500=1}"##, has_selection, |s, p| modify(s, p, "contract")),+ spec!("select.modify.feather", "Feather…", ["Select", "Modify"], r##"{"radius":0.1..1000=1}"##, has_selection, |s, p| modify(s, p, "feather")),+ spec!("select.grow", "Grow", ["Select"], r##"{"tolerance":0..255=32,"sampleAllLayers":bool=false}"##, has_selection, |s, p| grow_similar(s, p, true)),+ spec!("select.similar", "Similar", ["Select"], r##"{"tolerance":0..255=32,"sampleAllLayers":bool=false}"##, has_selection, |s, p| grow_similar(s, p, false)),+ spec!("select.lasso", "Lasso", [], r##"{"points":[[x,y],…],"mode":"replace|add|subtract|intersect"="replace","antiAlias":bool=true,"feather":px=0}"##, has_doc, lasso),+ ]+}++#[cfg(test)]+mod tests {+ use super::*;++ fn session() -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();+ s.edit("paint", |doc, _| {+ let bg = doc.layers[0].surface_mut().unwrap();+ bg.fill_rect(Rect::new(5, 5, 15, 15), &[1.0, 0.0, 0.0, 1.0]);+ bg.fill_rect(Rect::new(25, 5, 35, 15), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ s+ }++ fn coverage(s: &Session, x: i32, y: i32) -> f32 {+ s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0))+ }++ #[test]+ fn magic_wand_contiguous_and_modes() {+ let mut s = session();+ s.execute("select.magicWand", json!({"x": 7, "y": 7, "antiAlias": false})).unwrap();+ assert_eq!(coverage(&s, 10, 10), 1.0);+ assert_eq!(coverage(&s, 30, 10), 0.0);+ s.execute("select.magicWand", json!({"x": 30, "y": 7, "mode": "add", "antiAlias": false})).unwrap();+ assert_eq!(coverage(&s, 30, 10), 1.0);+ s.execute("select.magicWand", json!({"x": 7, "y": 7, "mode": "subtract", "antiAlias": false})).unwrap();+ assert_eq!(coverage(&s, 10, 10), 0.0);+ s.execute("select.magicWand", json!({"x": 7, "y": 7, "contiguous": false, "antiAlias": false})).unwrap();+ assert_eq!(coverage(&s, 30, 10), 1.0);+ }++ #[test]+ fn color_range_selects_by_colour() {+ let mut s = session();+ s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 10})).unwrap();+ assert_eq!(coverage(&s, 10, 10), 1.0);+ assert_eq!(coverage(&s, 20, 20), 0.0);+ }++ #[test]+ fn modify_commands() {+ let mut s = session();+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();+ s.execute("select.modify.expand", json!({"radius": 2})).unwrap();+ assert_eq!(coverage(&s, 8, 15), 1.0);+ s.execute("select.modify.contract", json!({"radius": 4})).unwrap();+ assert_eq!(coverage(&s, 11, 15), 0.0);+ assert_eq!(coverage(&s, 15, 15), 1.0);+ s.execute("select.modify.border", json!({"radius": 2})).unwrap();+ assert_eq!(coverage(&s, 15, 15), 0.0);+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();+ s.execute("select.modify.feather", json!({"radius": 4})).unwrap();+ let e = coverage(&s, 10, 15);+ assert!(e > 0.2 && e < 0.8, "{e}");+ s.execute("select.modify.smooth", json!({"radius": 2})).unwrap();+ assert!(s.active().unwrap().doc.selection.is_some());+ assert!(!s.is_enabled("select.nothing"));+ }++ #[test]+ fn grow_and_similar() {+ let mut s = session();+ s.execute("select.rect", json!({"x": 6, "y": 6, "width": 2, "height": 2})).unwrap();+ s.execute("select.grow", json!({"tolerance": 5})).unwrap();+ assert_eq!(coverage(&s, 14, 14), 1.0);+ assert_eq!(coverage(&s, 30, 10), 0.0);+ s.execute("select.similar", json!({"tolerance": 5})).unwrap();+ assert_eq!(coverage(&s, 30, 10), 1.0);+ assert_eq!(coverage(&s, 20, 20), 0.0);+ }++ #[test]+ fn lasso_polygon() {+ let mut s = session();+ s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]]})).unwrap();+ assert_eq!(coverage(&s, 2, 2), 1.0);+ assert_eq!(coverage(&s, 18, 18), 0.0);+ assert!(s.execute("select.lasso", json!({"points": [[0, 0], [1, 1]]})).is_err());+ s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]], "mode": "subtract"})).unwrap();+ assert!(s.active().unwrap().doc.selection.is_none());+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(coverage(&s, 2, 2), 1.0);+ }+}diff --git a/crates/engine/src/smartselect_cmds.rs b/crates/engine/src/smartselect_cmds.rsnew file mode 100644index 000000000..1ad708b3f--- /dev/null+++ b/crates/engine/src/smartselect_cmds.rs@@ -0,0 +1,491 @@+//! Smart selection commands: Quick Selection, Object Selection, Select Subject, Select and Mask+//! (Refine Edge) and Focus Area. The algorithms live in `photocraft_algo::segment` and+//! `photocraft_algo::matting`; these commands pick the pixels to analyse (active layer or+//! composite), run them, and store the result as the selection (or a mask / new layer).++use photocraft_algo::matting::{self, RefineParams};+use photocraft_algo::segment::{Sampler, SurfaceSampler, focus, grabcut, quick, subject};+use photocraft_algo::selection::{Region, SelectionMode, combine_region};+use photocraft_doc::{Document, Layer, LayerContent, LayerMask};+use photocraft_geom::Rect;+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++fn has_doc(s: &Session) -> std::result::Result<(), String> {+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())+}+fn has_selection(s: &Session) -> std::result::Result<(), String> {+ s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into())+}++fn f(p: &Value, k: &str, d: f32) -> f32 {+ p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32)+}+fn b(p: &Value, k: &str, d: bool) -> bool {+ p.get(k).and_then(Value::as_bool).unwrap_or(d)+}+fn mode(p: &Value, default: &str) -> SelectionMode {+ let m = p.get("mode").and_then(Value::as_str).unwrap_or(default);+ SelectionMode::parse(if m == "new" { "replace" } else { m })+}+fn bad(cmd: &str, msg: &str) -> EngineError {+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }+}++/// Composite of all visible layers.+struct CompositeSampler<'a>(&'a Document);++impl Sampler for CompositeSampler<'_> {+ fn rgba(&self, r: Rect) -> Vec<[f32; 4]> {+ photocraft_compose::render(self.0, r).px+ }+}++/// Runs `f` with a sampler over the active layer (or the composite with `all_layers`, or when the+/// active layer has no pixels).+fn with_sampler<R>(s: &Session, all_layers: bool, f: impl FnOnce(&dyn Sampler, &Document) -> R) -> Result<R> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let doc = d.doc.clone();+ let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| l.surface());+ Ok(match (all_layers, layer) {+ (false, Some(surf)) => f(&SurfaceSampler(surf), &doc),+ _ => f(&CompositeSampler(&doc), &doc),+ })+}++/// Stores `region` combined with the current selection by `m` as one history step.+fn apply(s: &mut Session, label: &str, region: Option<Region>, m: SelectionMode) -> Result<Value> {+ if region.is_none() && matches!(m, SelectionMode::Add | SelectionMode::Subtract) {+ // Nothing found: leave the selection (and history) alone.+ let selected = s.active().ok_or(EngineError::NoDocument)?.doc.selection.is_some();+ return Ok(json!({ "selected": selected, "changed": false }));+ }+ let bbox = region.as_ref().map(|r| r.bbox);+ let selected = s.edit(label, |doc, _| {+ doc.selection = combine_region(doc.selection.as_ref(), region.as_ref(), m);+ Ok(doc.selection.is_some())+ })?;+ Ok(json!({ "selected": selected, "changed": true, "bounds": bbox.map(|r| [r.x0, r.y0, r.width() as i32, r.height() as i32]) }))+}++fn points(p: &Value) -> Vec<(f32, f32)> {+ p.get("points")+ .and_then(Value::as_array)+ .map(|a| a.iter().filter_map(|q| Some((q.get(0)?.as_f64()? as f32, q.get(1)?.as_f64()? as f32))).collect())+ .unwrap_or_default()+}++/// Auto-Enhance for Quick Selection: a light edge refinement that flows the edge towards image+/// edges and removes blockiness.+const ENHANCE: RefineParams = RefineParams { radius: 4.0, smart_radius: true, smooth: 15.0, feather: 0.0, contrast: 25.0, shift_edge: 0.0 };++fn quick_selection(s: &mut Session, p: &Value) -> Result<Value> {+ let pts = points(p);+ if pts.is_empty() {+ return Err(bad("select.quick", "needs at least one point"));+ }+ let size = f(p, "size", 30.0).clamp(1.0, 5000.0);+ let m = match p.get("mode").and_then(Value::as_str).unwrap_or("add") {+ "subtract" => SelectionMode::Subtract,+ "replace" | "new" => SelectionMode::Replace,+ _ => SelectionMode::Add,+ };+ let enhance = b(p, "enhanceEdge", false);+ let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| {+ let canvas = doc.bounds();+ let r = quick::quick_select(smp, canvas, &pts, size, quick::WORK_PX)?;+ if enhance { matting::refine_mask(smp, &matting::region_reader(&r), r.bbox, canvas, &ENHANCE) } else { Some(r) }+ })?;+ apply(s, "Quick Selection", region, m)+}++fn rect_param(p: &Value) -> Option<Rect> {+ let a = p.get("rect")?.as_array()?;+ let v: Vec<f64> = a.iter().filter_map(Value::as_f64).collect();+ if v.len() < 4 {+ return None;+ }+ // Negative sizes (dragging up/left) are normalised.+ let (x0, x1) = (v[0].min(v[0] + v[2]), v[0].max(v[0] + v[2]));+ let (y0, y1) = (v[1].min(v[1] + v[3]), v[1].max(v[1] + v[3]));+ Some(Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32))+}++fn object_selection(s: &mut Session, p: &Value) -> Result<Value> {+ let rect = rect_param(p).ok_or_else(|| bad("select.object", "needs \"rect\": [x, y, w, h]"))?;+ let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| grabcut::object_select(smp, doc.bounds(), rect, 160_000))?;+ apply(s, "Object Selection", region, mode(p, "replace"))+}++fn select_subject(s: &mut Session, p: &Value) -> Result<Value> {+ let region = with_sampler(s, b(p, "sampleAllLayers", true), |smp, doc| subject::select_subject(smp, doc.bounds()))?;+ apply(s, "Select Subject", region, mode(p, "replace"))+}++fn focus_area(s: &mut Session, p: &Value) -> Result<Value> {+ let (range, noise) = (f(p, "range", 0.5).clamp(0.0, 1.0), f(p, "noise", 0.0).clamp(0.0, 1.0));+ let region = with_sampler(s, b(p, "sampleAllLayers", true), |smp, doc| focus::focus_area(smp, doc.bounds(), range, noise))?;+ apply(s, "Focus Area", region, mode(p, "replace"))+}++fn refine_params(p: &Value) -> RefineParams {+ RefineParams {+ radius: f(p, "radius", 0.0).clamp(0.0, 250.0),+ smart_radius: b(p, "smartRadius", false),+ smooth: f(p, "smooth", 0.0).clamp(0.0, 100.0),+ feather: f(p, "feather", 0.0).clamp(0.0, 1000.0),+ contrast: f(p, "contrast", 0.0).clamp(0.0, 100.0),+ shift_edge: f(p, "shiftEdge", 0.0).clamp(-100.0, 100.0),+ }+}++/// Select and Mask: refines the selection edge, then outputs to the selection, a layer mask on+/// the active layer, or a new layer (with or without a mask). Decontaminating colours needs a+/// new layer, so it upgrades `selection` / `layerMask` output to `newLayerWithMask` (as+/// Photoshop does). New-layer outputs hide the source layer.+fn refine_edge(s: &mut Session, p: &Value) -> Result<Value> {+ let params = refine_params(p);+ let decontaminate = b(p, "decontaminate", false);+ let amount = f(p, "amount", 100.0).clamp(0.0, 100.0);+ let mut output = p.get("output").and_then(Value::as_str).unwrap_or("selection").to_string();+ if !matches!(output.as_str(), "selection" | "layerMask" | "newLayer" | "newLayerWithMask") {+ return Err(bad("select.refineEdge", "output must be selection|layerMask|newLayer|newLayerWithMask"));+ }+ if decontaminate && matches!(output.as_str(), "selection" | "layerMask") {+ output = "newLayerWithMask".into();+ }+ let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| {+ let sel = doc.selection.as_ref()?;+ matting::refine_mask(smp, &matting::surface_reader(sel), sel.content_bounds(), doc.bounds(), ¶ms)+ })?;+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let active = d.active_layer.filter(|id| d.doc.layer(*id).is_some());+ match output.as_str() {+ "selection" => {+ let selected = s.edit("Select and Mask", |doc, _| {+ doc.selection = region.as_ref().map(matting::region_surface);+ Ok(doc.selection.is_some())+ })?;+ Ok(json!({ "output": output, "selected": selected }))+ }+ "layerMask" => {+ let id = active.ok_or_else(|| EngineError::Other("no active layer".into()))?;+ s.edit("Select and Mask", |doc, _| {+ let surface = region.as_ref().map(matting::region_surface).unwrap_or_else(|| photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8));+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(LayerMask { surface, ..LayerMask::reveal_all() });+ doc.selection = None;+ Ok(())+ })?;+ Ok(json!({ "output": output, "layer": id.0, "selected": false }))+ }+ _ => {+ let id = active.ok_or_else(|| EngineError::Other("no active layer".into()))?;+ let src_layer = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;+ let src = src_layer.surface().ok_or_else(|| EngineError::Other(format!("the active layer is a {} layer without pixels", src_layer.content.kind_name())))?;+ let name = format!("{} copy", src_layer.name);+ let empty = Region { bbox: Rect::EMPTY, mask: Vec::new() };+ let reg = region.as_ref().unwrap_or(&empty);+ let pixels = if decontaminate { matting::decontaminate(src, reg, params.radius, amount) } else { src.clone() };+ let with_mask = output == "newLayerWithMask";+ let (content, mask) = if with_mask {+ (pixels, Some(LayerMask { surface: matting::region_surface(reg), ..LayerMask::reveal_all() }))+ } else {+ (matting::masked_copy(&pixels, reg), None)+ };+ let new_id = s.edit("Select and Mask", |doc, act| {+ let mut layer = Layer::new(name, LayerContent::Raster(content));+ layer.mask = mask;+ let nid = doc.insert_above(Some(id), layer);+ if let Some(l) = doc.layer_mut(id) {+ l.visible = false;+ }+ doc.selection = None;+ *act = Some(nid);+ Ok(nid)+ })?;+ Ok(json!({ "output": output, "layer": new_id.0, "selected": false }))+ }+ }+}++macro_rules! spec {+ ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => {+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true }+ };+}++/// Smart selection command specs.+pub fn specs() -> Vec<CommandSpec> {+ vec![+ spec!("select.quick", "Quick Selection", [], r##"{"points":[[x,y],…],"size":px=30,"mode":"add|subtract|replace"="add","sampleAllLayers":bool=false,"enhanceEdge":bool=false}"##, has_doc, quick_selection),+ spec!("select.object", "Object Selection", [], r##"{"rect":[x,y,w,h],"mode":"replace|add|subtract|intersect"="replace","sampleAllLayers":bool=false}"##, has_doc, object_selection),+ spec!("select.subject", "Subject", ["Select"], r##"{"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, has_doc, select_subject),+ spec!(+ "select.refineEdge",+ "Refine Edge",+ [],+ r##"{"radius":px=0,"smartRadius":bool=false,"smooth":0..100=0,"feather":px=0,"contrast":0..100=0,"shiftEdge":-100..100=0,"decontaminate":bool=false,"amount":0..100=100,"output":"selection|layerMask|newLayer|newLayerWithMask"="selection","sampleAllLayers":bool=false}"##,+ has_selection,+ refine_edge+ ),+ spec!("select.focusArea", "Focus Area…", ["Select"], r##"{"range":0..1=0.5,"noise":0..1=0,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, has_doc, focus_area),+ ]+}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_algo::segment::Rng;++ /// A document whose background shows `px(x, y)` (RGB, 0–1), at the given depth.+ fn session_with(w: u32, h: u32, depth: u32, px: impl Fn(u32, u32) -> [f32; 3]) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap();+ s.edit("paint", |doc, _| {+ let bg = doc.layers[0].surface_mut().unwrap();+ let n = bg.channels();+ let mut data = Vec::with_capacity((w * h) as usize * n);+ for y in 0..h {+ for x in 0..w {+ let c = px(x, y);+ data.extend_from_slice(&c[..n.min(3)]);+ if n == 4 {+ data.push(1.0);+ }+ }+ }+ bg.write_region(Rect::new(0, 0, w as i32, h as i32), &data);+ Ok(())+ })+ .unwrap();+ s+ }++ fn noise_field(w: u32, h: u32, seed: u64) -> Vec<f32> {+ let mut rng = Rng::new(seed);+ (0..w * h).map(|_| rng.normal()).collect()+ }++ /// Warm textured left part (x < 60), cool right part.+ fn two_regions(depth: u32) -> Session {+ let nz = noise_field(140, 100, 1);+ session_with(140, 100, depth, move |x, y| {+ let n = 0.04 * nz[(y * 140 + x) as usize];+ if x < 60 { [0.8 + n, 0.5 + n, 0.3] } else { [0.2, 0.35 + n, 0.6 + n] }.map(|v| v.clamp(0.0, 1.0))+ })+ }++ /// Textured disc (centre (100, 80), radius 45) on a noisy background.+ fn disc(depth: u32) -> (Session, impl Fn(i32, i32) -> bool) {+ let nz = noise_field(200, 160, 2);+ let inside = |x: i32, y: i32| {+ let (dx, dy) = (x as f32 + 0.5 - 100.0, y as f32 + 0.5 - 80.0);+ dx * dx + dy * dy <= 45.0 * 45.0+ };+ let s = session_with(200, 160, depth, move |x, y| {+ let n = 0.05 * nz[(y * 200 + x) as usize];+ if inside(x as i32, y as i32) {+ let t = ((x + y) as f32 * 0.35).sin() * 0.5 + 0.5;+ [0.85 + 0.05 * t + n, 0.2 + 0.3 * t + n, 0.15 + n]+ } else {+ [0.25 + n, 0.45 + n, 0.7 + n]+ }+ .map(|v| v.clamp(0.0, 1.0))+ });+ (s, inside)+ }++ fn cov(s: &Session, x: i32, y: i32) -> f32 {+ s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0))+ }++ fn sel_iou(s: &Session, w: i32, h: i32, truth: impl Fn(i32, i32) -> bool) -> f32 {+ let (mut i, mut u) = (0, 0);+ for y in 0..h {+ for x in 0..w {+ let (a, b) = (cov(s, x, y) >= 0.5, truth(x, y));+ i += (a && b) as i32;+ u += (a || b) as i32;+ }+ }+ i as f32 / u.max(1) as f32+ }++ #[test]+ fn quick_selection_add_subtract_undo() {+ for depth in [8, 16] {+ let mut s = two_regions(depth);+ let r = s.execute("select.quick", json!({"points": [[20, 50], [35, 50]], "size": 8})).unwrap();+ assert_eq!(r["selected"], true);+ for y in (0..100).step_by(7) {+ for x in (0..140).step_by(3) {+ let c = cov(&s, x, y);+ if x < 57 {+ assert!(c >= 0.5, "depth {depth}: ({x},{y}) not selected");+ } else if x > 62 {+ assert!(c < 0.5, "depth {depth}: leaked to ({x},{y})");+ }+ }+ }+ // A second stroke on the right adds it.+ s.execute("select.quick", json!({"points": [[100, 50]], "size": 8})).unwrap();+ assert!(cov(&s, 130, 90) >= 0.5 && cov(&s, 10, 10) >= 0.5);+ // Subtract the left region again.+ s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "mode": "subtract"})).unwrap();+ assert!(cov(&s, 10, 10) < 0.5 && cov(&s, 130, 90) >= 0.5);+ s.execute("edit.undo", json!({})).unwrap();+ assert!(cov(&s, 10, 10) >= 0.5);+ assert!(s.execute("select.quick", json!({"points": []})).is_err());+ }+ }++ #[test]+ fn quick_selection_subtract_from_select_all_and_enhance() {+ let mut s = two_regions(8);+ s.execute("select.all", json!({})).unwrap();+ s.execute("select.quick", json!({"points": [[100, 30], [110, 70]], "size": 10, "mode": "subtract"})).unwrap();+ assert!(cov(&s, 10, 50) >= 0.99);+ assert!(cov(&s, 120, 20) < 0.01 && cov(&s, 70, 90) < 0.01);+ s.execute("select.deselect", json!({})).unwrap();+ s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "enhanceEdge": true})).unwrap();+ assert!(cov(&s, 10, 10) >= 0.5 && cov(&s, 100, 50) < 0.5);+ }++ #[test]+ fn object_selection_disc() {+ for depth in [8, 16, 32] {+ let (mut s, inside) = disc(depth);+ s.execute("select.object", json!({"rect": [40, 20, 120, 120]})).unwrap();+ let v = sel_iou(&s, 200, 160, &inside);+ assert!(v > 0.95, "depth {depth}: IoU {v}");+ }+ let (mut s, _) = disc(8);+ assert!(s.execute("select.object", json!({"rect": [1, 2]})).is_err());+ // Negative width/height (drag up-left) work too.+ s.execute("select.object", json!({"rect": [160, 140, -120, -120]})).unwrap();+ assert!(cov(&s, 100, 80) >= 0.5);+ }++ #[test]+ fn select_subject_centred_object() {+ let (mut s, inside) = disc(8);+ assert!(s.is_enabled("select.subject"));+ s.execute("select.subject", json!({})).unwrap();+ let v = sel_iou(&s, 200, 160, inside);+ assert!(v > 0.9, "IoU {v}");+ s.execute("edit.undo", json!({})).unwrap();+ assert!(s.active().unwrap().doc.selection.is_none());+ }++ /// A vertical Gaussian-blurred edge at x = 40 (warm left, cool right) with the left half selected.+ fn blurred_edge_selected() -> Session {+ let mut s = session_with(80, 40, 8, |x, _| {+ let t = 1.0 / (1.0 + ((x as f32 + 0.5 - 40.0) / 1.8).exp());+ [0.9 * t + 0.1 * (1.0 - t), 0.8 * t + 0.2 * (1.0 - t), 0.2 * t + 0.6 * (1.0 - t)]+ });+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap();+ s+ }++ fn soft_count(s: &photocraft_raster::Surface, y: i32) -> usize {+ (0..80).filter(|x| {+ let v = s.sample_channel(*x, y, 0);+ v > 0.05 && v < 0.95+ })+ .count()+ }++ #[test]+ fn refine_edge_outputs_and_undo() {+ // Selection output: the hard edge becomes a soft matte following the blur.+ let mut s = blurred_edge_selected();+ assert!(s.is_enabled("select.refineEdge"));+ s.execute("select.refineEdge", json!({"radius": 8})).unwrap();+ let sel = s.active().unwrap().doc.selection.clone().unwrap();+ assert!(soft_count(&sel, 20) >= 4, "selection edge not soft");+ assert!(sel.sample_channel(5, 20, 0) > 0.99 && sel.sample_channel(75, 20, 0) < 0.01);+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(soft_count(s.active().unwrap().doc.selection.as_ref().unwrap(), 20), 0);++ // Layer mask output.+ let layers_before = s.active().unwrap().doc.layer_count();+ let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "layerMask"})).unwrap();+ let d = s.active().unwrap();+ let l = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap();+ let m = l.mask.as_ref().unwrap();+ assert!(soft_count(&m.surface, 20) >= 4);+ assert!(m.value(5, 20) > 0.99 && m.value(75, 20) < 0.01);+ assert!(d.doc.selection.is_none());+ assert_eq!(d.doc.layer_count(), layers_before);+ s.execute("edit.undo", json!({})).unwrap();+ assert!(s.active().unwrap().doc.layers[0].mask.is_none());+ assert!(s.active().unwrap().doc.selection.is_some());++ // New layer: pixels with the refined alpha; the source is hidden.+ let r = s.execute("select.refineEdge", json!({"radius": 8, "feather": 1, "output": "newLayer"})).unwrap();+ let d = s.active().unwrap();+ let nid = photocraft_doc::LayerId(r["layer"].as_u64().unwrap());+ assert_eq!(d.active_layer, Some(nid));+ assert_eq!(d.doc.layer_count(), layers_before + 1);+ let nl = d.doc.layer(nid).unwrap();+ let surf = nl.surface().unwrap();+ assert!(surf.format().alpha);+ let a = |x: i32| surf.pixel(x, 20)[3];+ assert!(a(5) > 0.99 && a(75) == 0.0 && a(40) > 0.05 && a(40) < 0.95);+ assert!(!d.doc.layers[0].visible);+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(s.active().unwrap().doc.layer_count(), layers_before);+ assert!(s.active().unwrap().doc.layers[0].visible);++ // New layer with mask + decontamination (selection output upgrades to it).+ let r = s.execute("select.refineEdge", json!({"radius": 8, "decontaminate": true, "amount": 100})).unwrap();+ assert_eq!(r["output"], "newLayerWithMask");+ let d = s.active().unwrap();+ let nl = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap();+ assert!(nl.mask.is_some());+ let px = nl.surface().unwrap().pixel(41, 20);+ let orig = d.doc.layers[0].surface().unwrap().pixel(41, 20);+ // The fringe colour moved towards the warm foreground (more red, less blue).+ assert!(px[0] > orig[0] + 0.05 && px[2] < orig[2] - 0.05, "{px:?} vs {orig:?}");+ s.execute("edit.undo", json!({})).unwrap();+ assert!(s.execute("select.refineEdge", json!({"output": "bogus"})).is_err());+ s.execute("select.deselect", json!({})).unwrap();+ assert!(!s.is_enabled("select.refineEdge"));+ }++ #[test]+ fn refine_edge_shift_and_contrast() {+ let mut s = blurred_edge_selected();+ s.execute("select.refineEdge", json!({"shiftEdge": 100})).unwrap();+ assert!(cov(&s, 42, 20) > 0.99);+ s.execute("edit.undo", json!({})).unwrap();+ s.execute("select.refineEdge", json!({"feather": 8, "contrast": 100})).unwrap();+ assert!(cov(&s, 38, 20) == 1.0 && cov(&s, 42, 20) == 0.0);+ }++ #[test]+ fn focus_area_command() {+ let nz = noise_field(160, 100, 3);+ let mut blurred = vec![0.0f32; nz.len()];+ for y in 0..100i32 {+ for x in 0..160i32 {+ let mut a = 0.0;+ for dy in -4..=4 {+ for dx in -4..=4 {+ a += nz[((y + dy).clamp(0, 99) * 160 + (x + dx).clamp(0, 159)) as usize];+ }+ }+ blurred[(y * 160 + x) as usize] = a / 81.0;+ }+ }+ let mut s = session_with(160, 100, 8, move |x, y| {+ let i = (y * 160 + x) as usize;+ let v = 0.5 + 0.15 * if x < 80 { nz[i] } else { blurred[i] * 3.0 };+ [v, v, v].map(|c| c.clamp(0.0, 1.0))+ });+ s.execute("select.focusArea", json!({})).unwrap();+ assert!(cov(&s, 30, 50) >= 0.5 && cov(&s, 130, 50) < 0.5);+ }+}diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex d1ed9941f..2850dd544 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -311,3 +311,112 @@ fn move_to_reorders_and_nests() {s.execute("edit.undo", json!({})).unwrap();assert_eq!(names(&s), ["Background", "B", "A", "G"]);}++#[test]+fn selecting_a_layer_does_not_dirty_the_document() {+ let mut s = session_with_doc();+ let bg = s.active().unwrap().doc.layers[0].id;+ assert!(!s.active().unwrap().is_dirty());+ s.execute("layer.select", json!({"layer": bg.0})).unwrap();+ assert!(!s.active().unwrap().is_dirty());+ s.execute("layer.new.layer", json!({})).unwrap();+ assert!(s.active().unwrap().is_dirty());+}++#[test]+fn coalesced_edits_share_one_history_step() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 20, "height": 20})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ let steps = |s: &Session| s.active().unwrap().history.entries().len();+ let base = steps(&s);+ for o in [10, 20, 30] {+ s.execute("layer.setProps", json!({"opacity": o as f64 / 100.0, "coalesce": "drag-1"})).unwrap();+ }+ assert_eq!(steps(&s), base + 1, "three coalesced edits = one step");+ // A different key starts a new step; an uncoalesced edit breaks the chain.+ s.execute("layer.setProps", json!({"opacity": 0.4, "coalesce": "drag-2"})).unwrap();+ s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap();+ s.execute("layer.setProps", json!({"opacity": 0.6, "coalesce": "drag-2"})).unwrap();+ assert_eq!(steps(&s), base + 4);+ // Undo returns to the state before the whole coalesced run.+ s.undo();+ s.undo();+ s.undo();+ s.undo();+ let st = s.active().unwrap();+ let l = st.doc.layer(st.active_layer.unwrap()).unwrap().opacity;+ assert!((l - 1.0).abs() < 1e-6, "{l}");+}++#[test]+fn type_edit_rerenders_cache_to_new_text() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 800, "height": 400})).unwrap();+ let r = s.execute("type.create", json!({"x": 50, "y": 200, "text": "Lorem Ipsum", "size": 48, "coalesce": "k"})).unwrap();+ let id = r["layer"].as_u64().unwrap();+ let width = |s: &Session| {+ let st = s.active().unwrap();+ st.doc.layer(photocraft_doc::LayerId(id)).unwrap().surface().unwrap().content_bounds().width()+ };+ let w0 = width(&s);+ s.execute("type.edit", json!({"layer": id, "replace": {"start": 0, "end": 11, "text": "Photocraft"}, "coalesce": "k"})).unwrap();+ let w1 = width(&s);+ assert!(w0 > 150 && w1 > 150, "cache widths {w0} → {w1}");+}++#[test]+fn levels_and_curves_params_cover_output_and_channels() {+ use photocraft_doc::Adjustment;+ let a = crate::commands::adjustment_from_params("levels", &json!({"inBlack": 10, "outWhite": 200, "green": {"gamma": 1.5}}));+ let Adjustment::Levels { master, per_channel } = a else { panic!() };+ assert!((master.in_black - 10.0 / 255.0).abs() < 1e-6 && (master.out_white - 200.0 / 255.0).abs() < 1e-6);+ assert_eq!(per_channel[1].gamma, 1.5);+ assert_eq!(per_channel[0].gamma, 1.0);+ let c = crate::commands::adjustment_from_params("curves", &json!({"points": [[0, 0], [128, 160], [255, 255]], "blue": [[0, 20], [255, 235]]}));+ let Adjustment::Curves { master, per_channel } = c else { panic!() };+ assert_eq!(master.len(), 3);+ assert!((per_channel[2][0].output - 20.0 / 255.0).abs() < 1e-6);+ assert_eq!(per_channel[0].len(), 2);+}++#[test]+fn painting_can_target_the_layer_mask() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 40})).unwrap();+ s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();+ let id = s.active().unwrap().active_layer.unwrap();+ s.edit("mask", |doc, _| {+ doc.layer_mut(id).unwrap().mask = Some(photocraft_doc::LayerMask::reveal_all());+ Ok(())+ })+ .unwrap();+ // Adjustment layers are paintable through their mask only.+ assert!(s.execute("paint.stroke", json!({"points": [[20, 20]], "size": 10, "hardness": 1.0, "color": "#000000"})).is_err());+ s.execute("paint.stroke", json!({"points": [[20, 20]], "size": 10, "hardness": 1.0, "color": "#000000", "target": "mask"})).unwrap();+ let m = |s: &Session, x, y| s.active().unwrap().doc.layer(id).unwrap().mask.as_ref().unwrap().surface.pixel(x, y)[0];+ assert!(m(&s, 20, 20) < 0.01, "painted black");+ assert!(m(&s, 2, 2) > 0.99, "rest still revealed");+ // Eraser on a mask paints the background colour (white).+ s.execute("paint.stroke", json!({"points": [[20, 20]], "size": 10, "hardness": 1.0, "erase": true, "target": "mask"})).unwrap();+ assert!(m(&s, 20, 20) > 0.99);+ // Gradient into the mask.+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [40, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap();+ assert!(m(&s, 2, 20) < 0.1 && m(&s, 38, 20) > 0.9);+}++#[test]+fn layer_locks_are_set_and_enforced() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 20, "height": 20})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap();+ assert!(s.execute("paint.stroke", json!({"points": [[5, 5]], "size": 4})).is_err(), "pixel lock blocks painting");+ s.execute("layer.setProps", json!({"locks": {"pixels": false, "position": true}})).unwrap();+ s.execute("paint.stroke", json!({"points": [[5, 5]], "size": 4})).unwrap();+ assert!(s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 3, 0]})).is_err(), "position lock blocks transforms");+ assert!(s.execute("layer.setProps", json!({"locks": {"bogus": true}})).is_err());+ let st = s.active().unwrap();+ let l = st.doc.layer(st.active_layer.unwrap()).unwrap();+ assert!(l.locks.position && !l.locks.pixels);+}diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rsnew file mode 100644index 000000000..7413ae7ef--- /dev/null+++ b/crates/engine/src/transform_cmds.rs@@ -0,0 +1,373 @@+//! Edit › Free Transform / Transform: projective transforms of layers (and the selection).++use photocraft_algo::transform::{Homography, Interp, warp_surface};+use photocraft_color::PixelFormat;+use photocraft_doc::{Document, Layer, LayerContent, LayerId};+use photocraft_geom::{Affine, Rect};+use photocraft_raster::Surface;+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++fn has_layer(s: &Session) -> std::result::Result<(), String> {+ s.active().and_then(|d| d.active_layer).map(|_| ()).ok_or_else(|| "no active layer".into())+}++fn bad(msg: impl Into<String>) -> EngineError {+ EngineError::BadParams { cmd: "edit.transform".into(), msg: msg.into() }+}++/// Document-space bounds a transform of `layer` starts from (what Free Transform frames).+pub fn transform_bounds(doc: &Document, layer: &Layer) -> Rect {+ let content = match &layer.content {+ LayerContent::Group(g) => g.children.iter().map(|l| transform_bounds(doc, l)).fold(Rect::EMPTY, |a, b| a.union(&b)),+ _ => layer.surface().map_or(Rect::EMPTY, Surface::content_bounds),+ };+ let content = if content.is_empty() { layer.mask.as_ref().map_or(Rect::EMPTY, |m| m.surface.content_bounds()) } else { content };+ match &doc.selection {+ Some(sel) if !layer.is_group() => content.intersect(&sel.content_bounds()),+ _ => content,+ }+}++/// Warp a surface whose pixels outside the content read as `default` (masks, selections):+/// warp the content with alpha, then flatten back onto the default value.+fn warp_gray(s: &Surface, h: &Homography, interp: Interp) -> Surface {+ let default = s.default_pixel().first().copied().unwrap_or(0.0);+ let fmt = s.format();+ let src = s.content_bounds();+ let mut out = Surface::with_default(fmt, &[default]);+ if src.is_empty() {+ return out;+ }+ // Content-only copy (default 0 + alpha) so the "outside" is transparent during the warp.+ let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true);+ let mut tmp = Surface::new(with_alpha);+ let v = s.read_region(src);+ tmp.write_region(src, &v.iter().flat_map(|g| [*g, 1.0]).collect::<Vec<f32>>());+ let w = warp_surface(&tmp, src, h, interp);+ // Everything the old content covered becomes default, then the warped content composites over.+ let cover = src.union(&w.content_bounds());+ let old: Vec<f32> = vec![default; cover.width() as usize * cover.height() as usize];+ out.write_region(cover, &old);+ let b = w.content_bounds();+ if !b.is_empty() {+ let px = w.read_region(b);+ let flat: Vec<f32> = px.chunks_exact(2).map(|p| p[0] * p[1] + default * (1.0 - p[1])).collect();+ out.write_region(b, &flat);+ }+ out.prune();+ out+}++fn transform_layer(doc_sel: Option<&Surface>, l: &mut Layer, h: &Homography, affine: Option<Affine>, interp: Interp) -> Result<()> {+ // Photoshop turns the Background into a normal layer before transforming it.+ if l.locks.position && l.name == "Background" {+ l.locks.position = false;+ l.locks.transparency = false;+ l.name = "Layer 0".into();+ }+ if l.locks.position || l.locks.all {+ return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));+ }+ match &mut l.content {+ LayerContent::Group(g) => {+ for c in g.children.iter_mut() {+ transform_layer(None, c, h, affine, interp)?;+ }+ }+ LayerContent::Text(t) => {+ let Some(a) = affine else {+ return Err(EngineError::Other("Distort and Perspective need rasterized type (Type › Rasterize Type Layer)".into()));+ };+ t.transform = a.mul(&t.transform);+ }+ LayerContent::Shape(sh) => {+ let Some(a) = affine else {+ return Err(EngineError::Other("Distort and Perspective need a rasterized shape (Layer › Rasterize › Shape)".into()));+ };+ crate::vector_cmds::transform_shape(sh, &a);+ }+ _ => {+ if let Some(surf) = l.surface_mut() {+ let src = surf.content_bounds();+ *surf = match doc_sel {+ // Only the selected pixels move: lift them, clear them, warp and paste back.+ Some(sel) => {+ let (lifted, mut rest) = split_selected(surf, sel);+ let moved = warp_surface(&lifted, src, h, interp);+ composite_over(&mut rest, &moved);+ rest.prune();+ rest+ }+ None => warp_surface(surf, src, h, interp),+ };+ }+ }+ }+ if let Some(m) = l.mask.as_mut()+ && m.linked+ {+ m.surface = warp_gray(&m.surface, h, interp);+ }+ if let Some(vm) = l.vector_mask.as_mut()+ && vm.linked+ && let Some(a) = affine+ {+ vm.path = vm.path.transform(&a);+ }+ Ok(())+}++/// Split a layer surface by a selection: (selected pixels, everything else), both with alpha.+pub fn split_selected(surf: &Surface, sel: &Surface) -> (Surface, Surface) {+ let fmt = surf.format();+ let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true);+ let mut lifted = Surface::new(with_alpha);+ let mut rest = surf.convert(with_alpha);+ let src = surf.content_bounds();+ if src.is_empty() {+ return (lifted, rest);+ }+ let n = with_alpha.channels();+ let px = rest.read_region(src);+ let mut lp = px.clone();+ let mut rp = px;+ let w = src.width() as usize;+ for (i, (l, r)) in lp.chunks_exact_mut(n).zip(rp.chunks_exact_mut(n)).enumerate() {+ let (x, y) = (src.x0 + (i % w) as i32, src.y0 + (i / w) as i32);+ let k = sel.sample_channel(x, y, 0);+ l[n - 1] *= k;+ r[n - 1] *= 1.0 - k;+ }+ lifted.write_region(src, &lp);+ lifted.prune();+ rest.write_region(src, &rp);+ (lifted, rest)+}++fn refresh_text(doc: &Document, l: &mut Layer) {+ match &mut l.content {+ LayerContent::Text(t) => crate::type_cmds::refresh(doc, t),+ LayerContent::Shape(sh) => crate::vector_cmds::refresh_shape(doc, sh),+ LayerContent::Group(g) => g.children.iter_mut().for_each(|c| refresh_text(doc, c)),+ _ => {}+ }+}++/// Normal-blend `top` over `dst` (both straight alpha, same format).+fn composite_over(dst: &mut Surface, top: &Surface) {+ let b = top.content_bounds();+ if b.is_empty() {+ return;+ }+ let n = dst.format().channels();+ let a = n - 1;+ let t = top.read_region(b);+ let mut d = dst.read_region(b);+ for (dp, tp) in d.chunks_exact_mut(n).zip(t.chunks_exact(n)) {+ let (ta, da) = (tp[a], dp[a]);+ let oa = ta + da * (1.0 - ta);+ if oa > 0.0 {+ for c in 0..a {+ dp[c] = (tp[c] * ta + dp[c] * da * (1.0 - ta)) / oa;+ }+ }+ dp[a] = oa;+ }+ dst.write_region(b, &d);+}++fn quad_param(p: &Value) -> Option<[[f64; 2]; 4]> {+ let a = p.get("quad")?.as_array()?;+ if a.len() != 4 {+ return None;+ }+ let mut q = [[0.0; 2]; 4];+ for (i, v) in a.iter().enumerate() {+ let c = v.as_array()?;+ q[i] = [c.first()?.as_f64()?, c.get(1)?.as_f64()?];+ }+ Some(q)+}++fn transform(s: &mut Session, p: &Value) -> Result<Value> {+ let st = s.active().ok_or(EngineError::NoDocument)?;+ let id = match p.get("layer").and_then(Value::as_u64) {+ Some(v) => LayerId(v),+ None => st.active_layer.ok_or(EngineError::Other("no active layer".into()))?,+ };+ let layer = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?;+ let rect = match p.get("rect").and_then(Value::as_array) {+ Some(r) if r.len() == 4 => {+ let v: Vec<f64> = r.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect();+ [v[0], v[1], v[2], v[3]]+ }+ _ => {+ let b = transform_bounds(&st.doc, layer);+ if b.is_empty() {+ return Err(EngineError::Other("nothing to transform".into()));+ }+ [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]+ }+ };+ let h = if let Some(q) = quad_param(p) {+ Homography::rect_to_quad(rect, q).ok_or_else(|| bad("degenerate quad"))?+ } else if let Some(m) = p.get("matrix").and_then(Value::as_array) {+ let v: Vec<f64> = m.iter().filter_map(Value::as_f64).collect();+ if v.len() != 6 {+ return Err(bad("matrix must be [a, b, c, d, e, f]"));+ }+ // Affine [a b c d e f] maps (x, y) → (a·x + c·y + e, b·x + d·y + f).+ Homography([v[0], v[2], v[4], v[1], v[3], v[5], 0.0, 0.0, 1.0])+ } else {+ return Err(bad("pass `quad` (where the rect's corners go) or `matrix`"));+ };+ if h.inverse().is_none() {+ return Err(bad("the transform collapses the layer"));+ }+ let m = h.0;+ let affine = (m[6].abs() < 1e-12 && m[7].abs() < 1e-12).then(|| Affine { m: [m[0] / m[8], m[3] / m[8], m[1] / m[8], m[4] / m[8], m[2] / m[8], m[5] / m[8]] });+ let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic"));+ s.edit("Free Transform", |doc, _| {+ let sel = doc.selection.clone();+ let is_group = doc.layer(id).is_some_and(Layer::is_group);+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ transform_layer(if is_group { None } else { sel.as_ref() }, l, &h, affine, interp)?;+ // Type layers re-render from their new transform.+ let snapshot = doc.clone();+ if let Some(l) = doc.layer_mut(id) {+ refresh_text(&snapshot, l);+ }+ // The selection outline moves with the pixels.+ if let Some(sel) = &doc.selection {+ doc.selection = Some(warp_gray(sel, &h, Interp::Bilinear)).filter(|s| !s.content_bounds().is_empty());+ }+ Ok(())+ })?;+ Ok(json!({"rect": rect}))+}++pub fn specs() -> Vec<CommandSpec> {+ vec![CommandSpec {+ id: "edit.transform",+ label: "Free Transform",+ menu: &[],+ shortcut: None,+ params: r##"{"layer":id?,"rect":[x0,y0,x1,y1]? (source frame; default = layer content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"interpolation":"bicubic|bilinear|nearest"="bicubic"}"##,+ enabled: has_layer,+ journal: true,+ run: transform,+ }]+}++#[cfg(test)]+mod tests {+ use super::*;++ fn session() -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.edit("paint", |doc, active| {+ let l = doc.layer_mut(active.unwrap()).unwrap();+ l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 20), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ s+ }++ fn active_bounds(s: &Session) -> Rect {+ let st = s.active().unwrap();+ st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds()+ }++ #[test]+ fn scale_via_quad_and_undo() {+ let mut s = session();+ s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]})).unwrap();+ let b = active_bounds(&s);+ assert!(b.width().abs_diff(40) <= 2 && b.height().abs_diff(20) <= 2, "{b:?}");+ s.undo();+ assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20));+ }++ #[test]+ fn affine_matrix_and_perspective() {+ let mut s = session();+ // Translate by (40, 50).+ s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70));+ // Perspective: top edge narrower than the bottom.+ s.execute("edit.transform", json!({"quad": [[55, 60], [65, 60], [75, 70], [45, 70]]})).unwrap();+ let b = active_bounds(&s);+ assert!(b.x0 <= 46 && b.x1 >= 74, "{b:?}");+ assert!(s.execute("edit.transform", json!({"quad": [[0, 0], [0, 0], [0, 0], [0, 0]]})).is_err());+ }++ #[test]+ fn background_becomes_layer_0() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 40})).unwrap();+ s.execute("edit.transform", json!({"quad": [[0, 0], [20, 0], [20, 20], [0, 20]]})).unwrap();+ let st = s.active().unwrap();+ let l = &st.doc.layers[0];+ assert_eq!(l.name, "Layer 0");+ assert!(l.surface().unwrap().format().alpha);+ assert_eq!(l.surface().unwrap().pixel(30, 30)[3], 0.0, "revealed area is transparent");+ }++ #[test]+ fn with_selection_only_selected_pixels_move() {+ let mut s = session();+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();+ s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap();+ let st = s.active().unwrap();+ let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();+ assert_eq!(surf.pixel(15, 15)[3], 0.0, "lifted area is cleared");+ assert_eq!(surf.pixel(25, 15)[3], 1.0, "unselected part stays");+ assert_eq!(surf.pixel(15, 65)[3], 1.0, "moved pixels land");+ let sel = st.doc.selection.as_ref().unwrap().content_bounds();+ assert_eq!((sel.y0, sel.y1), (60, 70), "selection moves too");+ }++ #[test]+ fn type_layers_transform_as_vectors() {+ let mut s = session();+ let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap();+ let id = r["layer"].as_u64().unwrap();+ let w0 = active_bounds(&s).width();+ s.execute("edit.transform", json!({"layer": id, "matrix": [2, 0, 0, 2, -10, -50]})).unwrap();+ let w1 = active_bounds(&s).width();+ assert!(w1 as f32 > w0 as f32 * 1.8, "{w0} → {w1}");+ let st = s.active().unwrap();+ let LayerContent::Text(t) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!() };+ assert!((t.transform.m[0] - 2.0).abs() < 1e-9);+ // Perspective on type is refused, like Photoshop.+ assert!(s.execute("edit.transform", json!({"layer": id, "quad": [[0, 0], [10, 0], [12, 10], [-2, 10]]})).is_err());+ }++ #[test]+ fn shapes_move_and_transform_as_vectors() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 200, "height": 200})).unwrap();+ s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap();+ s.execute("layer.translate", json!({"dx": 30, "dy": 5})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(40, 15, 80, 35));+ s.execute("edit.transform", json!({"matrix": [2, 0, 0, 2, -40, -15]})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(40, 15, 120, 55));+ assert!(s.execute("edit.transform", json!({"quad": [[40, 15], [120, 15], [130, 55], [30, 55]]})).is_err());+ }++ #[test]+ fn type_moves_with_the_move_command() {+ let mut s = session();+ s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap();+ let b0 = active_bounds(&s);+ s.execute("layer.translate", json!({"dx": 20, "dy": 10})).unwrap();+ let b1 = active_bounds(&s);+ assert_eq!((b1.x0 - b0.x0, b1.y0 - b0.y0), (20, 10));+ }+}diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rsnew file mode 100644index 000000000..e38d1f0b2--- /dev/null+++ b/crates/engine/src/type_cmds.rs@@ -0,0 +1,939 @@+//! `type.*` commands: create and edit type (text) layers.+//!+//! Text offsets in parameters and results are **character** indices (Unicode scalar values),+//! so JSON clients never split a UTF-8 sequence. Sizes, leading, indents and spacing are in+//! points (converted with the document resolution); tracking is in 1/1000 em; positions and+//! boxes are document pixels. Every edit re-renders the layer with `photocraft-text` and+//! regenerates its PSD `TySh` data, so the layer saves as editable text.++use std::sync::Arc;++use photocraft_color::Color;+use photocraft_doc::text::{+ AntiAlias, Caps, CharStyle, FontFeature, FontVariation, Kerning, ParagraphRun, ParagraphStyle,+ TextAlign, TextDirection, TextRun, TextShape,+};+use photocraft_doc::{Affine, Document, Layer, LayerContent, LayerId, TextLayer};+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++fn has_doc(s: &Session) -> std::result::Result<(), String> {+ s.active()+ .map(|_| ())+ .ok_or_else(|| "no document open".into())+}++fn layer_id(s: &Session, p: &Value) -> Result<LayerId> {+ match p.get("layer").and_then(Value::as_u64) {+ Some(id) => Ok(LayerId(id)),+ None => s+ .active()+ .and_then(|d| d.active_layer)+ .ok_or(EngineError::Other("no active layer".into())),+ }+}++fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {+ EngineError::BadParams {+ cmd: cmd.into(),+ msg: msg.into(),+ }+}++fn f32p(p: &Value, k: &str) -> Option<f32> {+ p.get(k).and_then(Value::as_f64).map(|v| v as f32)+}++fn color(v: &Value) -> Option<Color> {+ match v {+ Value::Array(a) if a.len() >= 3 => {+ let c: Vec<f32> = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();+ Some(Color::rgba(+ c[0],+ c[1],+ c[2],+ c.get(3).copied().unwrap_or(1.0),+ ))+ }+ Value::String(s) => {+ let s = s.trim_start_matches('#');+ let h = |i: usize| {+ s.get(i..i + 2)+ .and_then(|x| u8::from_str_radix(x, 16).ok())+ .map(|v| f32::from(v) / 255.0)+ };+ match s.len() {+ 6 => Some(Color::rgb(h(0)?, h(2)?, h(4)?)),+ 8 => Some(Color::rgba(h(0)?, h(2)?, h(4)?, h(6)?)),+ _ => None,+ }+ }+ _ => None,+ }+}++/// Normalises line breaks to `\n`.+fn norm_text(s: &str) -> String {+ s.replace("\r\n", "\n").replace('\r', "\n")+}++fn byte_at(text: &str, ci: usize) -> usize {+ text.char_indices().nth(ci).map_or(text.len(), |(b, _)| b)+}++fn char_at(text: &str, bi: usize) -> usize {+ text[..bi.min(text.len())].chars().count()+}++/// `range: [start, end]` in characters → byte range (whole text when absent).+fn range_param(text: &str, p: &Value) -> (usize, usize) {+ match p.get("range").and_then(Value::as_array) {+ Some(r) if r.len() == 2 => {+ let a = r[0].as_u64().unwrap_or(0) as usize;+ let b = r[1].as_u64().unwrap_or(a as u64) as usize;+ let (a, b) = (a.min(b), a.max(b));+ (byte_at(text, a), byte_at(text, b))+ }+ _ => (0, text.len()),+ }+}++/// Applies character-style keys from JSON. Returns true if any key was present.+pub fn apply_char_props(s: &mut CharStyle, p: &Value) -> bool {+ let mut any = false;+ let mut hit = |b: bool| any |= b;+ if let Some(v) = p+ .get("font")+ .or_else(|| p.get("family"))+ .and_then(Value::as_str)+ {+ s.font_family = v.to_string();+ s.postscript_name = None;+ hit(true);+ }+ if let Some(v) = p.get("postscriptName").and_then(Value::as_str) {+ s.postscript_name = Some(v.to_string());+ hit(true);+ }+ if let Some(v) = p.get("fontStyle").and_then(Value::as_str) {+ s.font_style = v.to_string();+ let l = v.to_lowercase();+ s.italic = l.contains("italic") || l.contains("oblique");+ let g = photocraft_text::fonts::guess_from_postscript(&format!("X-{}", v.replace(' ', "")));+ s.weight = g.weight;+ hit(true);+ }+ if let Some(v) = p.get("weight").and_then(Value::as_f64) {+ s.weight = v.clamp(1.0, 1000.0) as u16;+ hit(true);+ }+ if let Some(v) = p.get("italic").and_then(Value::as_bool) {+ s.italic = v;+ hit(true);+ }+ if let Some(v) = f32p(p, "size") {+ s.size_pt = v.max(0.01);+ hit(true);+ }+ if let Some(c) = p.get("color").and_then(color) {+ s.color = c;+ hit(true);+ }+ if let Some(v) = f32p(p, "tracking") {+ s.tracking = v;+ hit(true);+ }+ match p.get("leading") {+ Some(Value::Null) => {+ s.leading_pt = None;+ hit(true);+ }+ Some(Value::String(a)) if a == "auto" => {+ s.leading_pt = None;+ hit(true);+ }+ Some(v) if v.is_number() => {+ s.leading_pt = v.as_f64().map(|x| x as f32);+ hit(true);+ }+ _ => {}+ }+ for (k, f) in [+ ("baselineShift", &mut s.baseline_shift_pt),+ ("horizontalScale", &mut s.horizontal_scale),+ ("verticalScale", &mut s.vertical_scale),+ ] {+ if let Some(v) = f32p(p, k) {+ *f = if k == "baselineShift" {+ v+ } else {+ (v / 100.0).max(0.01)+ };+ hit(true);+ }+ }+ for (k, f) in [+ ("underline", &mut s.underline),+ ("strikethrough", &mut s.strikethrough),+ ("fauxBold", &mut s.faux_bold),+ ("fauxItalic", &mut s.faux_italic),+ ("ligatures", &mut s.ligatures),+ ("discretionaryLigatures", &mut s.discretionary_ligatures),+ ] {+ if let Some(v) = p.get(k).and_then(Value::as_bool) {+ *f = v;+ hit(true);+ }+ }+ if let Some(v) = p.get("kerning").and_then(Value::as_str) {+ s.kerning = match v {+ "optical" => Kerning::Optical,+ "none" | "off" | "0" => Kerning::Off,+ _ => Kerning::Metrics,+ };+ hit(true);+ }+ if let Some(v) = p.get("caps").and_then(Value::as_str) {+ s.caps = match v {+ "small" | "smallCaps" => Caps::SmallCaps,+ "all" | "allCaps" => Caps::AllCaps,+ _ => Caps::Normal,+ };+ hit(true);+ }+ if let Some(Value::Object(m)) = p.get("features") {+ for (tag, v) in m {+ let value = v+ .as_u64()+ .map(|x| x as u16)+ .or_else(|| v.as_bool().map(u16::from))+ .unwrap_or(1);+ s.features.retain(|f| &f.tag != tag);+ s.features.push(FontFeature {+ tag: tag.clone(),+ value,+ });+ }+ hit(true);+ }+ if let Some(Value::Object(m)) = p.get("variations") {+ for (axis, v) in m {+ s.variations.retain(|f| &f.axis != axis);+ if let Some(x) = v.as_f64() {+ s.variations.push(FontVariation {+ axis: axis.clone(),+ value: x as f32,+ });+ }+ }+ hit(true);+ }+ if let Some(v) = p.get("language") {+ s.language = v.as_str().map(str::to_string);+ hit(true);+ }+ any+}++/// Applies paragraph-style keys from JSON. Returns true if any key was present.+pub fn apply_para_props(s: &mut ParagraphStyle, p: &Value) -> bool {+ let mut any = false;+ if let Some(v) = p.get("align").and_then(Value::as_str) {+ s.align = match v {+ "center" => TextAlign::Center,+ "right" => TextAlign::Right,+ "justify" | "justifyLeft" => TextAlign::JustifyLeft,+ "justifyCenter" => TextAlign::JustifyCenter,+ "justifyRight" => TextAlign::JustifyRight,+ "justifyAll" => TextAlign::JustifyAll,+ _ => TextAlign::Left,+ };+ any = true;+ }+ for (k, f) in [+ ("firstLineIndent", &mut s.first_line_indent_pt),+ ("startIndent", &mut s.start_indent_pt),+ ("endIndent", &mut s.end_indent_pt),+ ("spaceBefore", &mut s.space_before_pt),+ ("spaceAfter", &mut s.space_after_pt),+ ("autoLeading", &mut s.auto_leading),+ ] {+ if let Some(v) = f32p(p, k) {+ *f = if k == "autoLeading" { v / 100.0 } else { v };+ any = true;+ }+ }+ if let Some(v) = p.get("direction").and_then(Value::as_str) {+ s.direction = match v {+ "ltr" => TextDirection::Ltr,+ "rtl" => TextDirection::Rtl,+ _ => TextDirection::Auto,+ };+ any = true;+ }+ if let Some(v) = p.get("hyphenate").and_then(Value::as_bool) {+ s.hyphenate = v;+ any = true;+ }+ any+}++fn push_merge<S: PartialEq>(out: &mut Vec<(usize, S)>, len: usize, st: S) {+ if len == 0 {+ return;+ }+ match out.last_mut() {+ Some(last) if last.1 == st => last.0 += len,+ _ => out.push((len, st)),+ }+}++/// Applies `f` to the character style of bytes `a..b` (splitting runs at the edges).+pub fn style_range(t: &mut TextLayer, a: usize, b: usize, f: &dyn Fn(&mut CharStyle)) {+ let runs = t.char_runs();+ if t.text.is_empty() {+ let mut st = runs.into_iter().next().map(|r| r.style).unwrap_or_default();+ f(&mut st);+ t.runs = vec![TextRun { len: 0, style: st }];+ t.sync_summary();+ return;+ }+ let mut out: Vec<(usize, CharStyle)> = Vec::new();+ let mut at = 0;+ for r in runs {+ let (rs, re) = (at, at + r.len);+ at = re;+ let (ca, cb) = (a.clamp(rs, re), b.clamp(rs, re));+ push_merge(&mut out, ca - rs, r.style.clone());+ let mut st = r.style.clone();+ f(&mut st);+ push_merge(&mut out, cb - ca, st);+ push_merge(&mut out, re - cb, r.style);+ }+ t.runs = out+ .into_iter()+ .map(|(len, style)| TextRun { len, style })+ .collect();+ t.sync_summary();+}++/// Applies `f` to every paragraph touching bytes `a..b` (paragraph runs follow paragraphs).+pub fn style_paragraphs(t: &mut TextLayer, a: usize, b: usize, f: &dyn Fn(&mut ParagraphStyle)) {+ let old = t.paragraph_runs();+ let starts: Vec<usize> = old+ .iter()+ .scan(0, |acc, r| {+ let s = *acc;+ *acc += r.len;+ Some(s)+ })+ .collect();+ let style_at = |off: usize| {+ old[starts.iter().rposition(|&s| s <= off).unwrap_or(0)]+ .style+ .clone()+ };+ let mut out: Vec<(usize, ParagraphStyle)> = Vec::new();+ for pr in photocraft_text::layout::split_paragraphs(&t.text) {+ let mut st = style_at(pr.start);+ let touches = (pr.start < b && pr.end > a)+ || (a == b && a >= pr.start && (a < pr.end || pr.end == t.text.len()));+ if touches {+ f(&mut st);+ }+ push_merge(&mut out, pr.len(), st.clone());+ if out.is_empty() {+ out.push((0, st));+ }+ }+ t.paragraphs = out+ .into_iter()+ .map(|(len, style)| ParagraphRun { len, style })+ .collect();+}++/// Replaces bytes `a..b` with `new`, keeping styles: inserted text takes the style of the+/// character before it (or after it at the start).+pub fn replace_text(t: &mut TextLayer, a: usize, b: usize, new: &str) {+ fn adjust<S: Clone + PartialEq>(+ runs: Vec<(usize, S)>,+ a: usize,+ b: usize,+ ins: usize,+ ) -> Vec<(usize, S)> {+ let mut out: Vec<(usize, S)> = Vec::new();+ let mut at = 0;+ let host = runs+ .iter()+ .scan(0, |acc, r| {+ let s = *acc;+ *acc += r.0;+ Some((s, s + r.0))+ })+ .position(|(s, e)| {+ if a == 0 {+ e > 0 || s == 0+ } else {+ a > s && a <= e+ }+ })+ .unwrap_or(0);+ for (i, (len, st)) in runs.into_iter().enumerate() {+ let (rs, re) = (at, at + len);+ at = re;+ let keep = (a.clamp(rs, re) - rs) + (re - b.clamp(rs, re));+ let add = if i == host { ins } else { 0 };+ push_merge(&mut out, keep + add, st);+ }+ out+ }+ let (a, b) = (+ a.min(t.text.len()),+ b.min(t.text.len()).max(a.min(t.text.len())),+ );+ let new = norm_text(new);+ let cr: Vec<(usize, CharStyle)> = t+ .char_runs()+ .into_iter()+ .map(|r| (r.len, r.style))+ .collect();+ let pr: Vec<(usize, ParagraphStyle)> = t+ .paragraph_runs()+ .into_iter()+ .map(|r| (r.len, r.style))+ .collect();+ let first_c = cr.first().map(|r| r.1.clone()).unwrap_or_default();+ let first_p = pr.first().map(|r| r.1.clone()).unwrap_or_default();+ let mut cr = adjust(cr, a, b, new.len());+ let mut pr = adjust(pr, a, b, new.len());+ t.text.replace_range(a..b, &new);+ if cr.is_empty() {+ cr.push((t.text.len(), first_c));+ }+ if pr.is_empty() {+ pr.push((t.text.len(), first_p));+ }+ t.runs = cr+ .into_iter()+ .map(|(len, style)| TextRun { len, style })+ .collect();+ t.paragraphs = pr+ .into_iter()+ .map(|(len, style)| ParagraphRun { len, style })+ .collect();+ t.sync_summary();+}++/// Re-renders the layer's pixels and regenerates its PSD `TySh` data.+pub fn refresh(doc: &Document, t: &mut TextLayer) {+ let dpi = doc.resolution_dpi;+ let mut eng = photocraft_text::shared()+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ let (layout, r) = eng.render(t, dpi, doc.pixel_format());+ t.cache = Some(r.surface);+ t.psd_raw = Some(Arc::new(photocraft_text::psd::build_tysh(+ t,+ dpi,+ layout.bounds(),+ )));+}++fn with_text_layer<R>(+ s: &mut Session,+ p: &Value,+ label: &str,+ f: impl FnOnce(&mut TextLayer, &Document) -> Result<R>,+) -> Result<R> {+ let id = layer_id(s, p)?;+ s.edit(label, |doc, _| {+ let snapshot = doc.clone();+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ let LayerContent::Text(t) = &mut l.content else {+ return Err(EngineError::Other(format!(+ "layer {} is a {} layer, not a type layer",+ id.0,+ l.content.kind_name()+ )));+ };+ let r = f(t, &snapshot)?;+ refresh(&snapshot, t);+ Ok(r)+ })+}++fn layer_name(text: &str) -> String {+ let first = text.lines().next().unwrap_or("").trim();+ let name: String = first.chars().take(40).collect();+ if name.is_empty() {+ "Type Layer".into()+ } else {+ name+ }+}++fn info(s: &Session, p: &Value) -> Result<Value> {+ let id = layer_id(s, p)?;+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;+ let LayerContent::Text(t) = &l.content else {+ return Err(EngineError::Other(format!(+ "layer {} is not a type layer",+ id.0+ )));+ };+ let text = &t.text;+ let mut at = 0;+ let runs: Vec<Value> = t+ .char_runs()+ .into_iter()+ .map(|r| {+ let v = json!({ "start": char_at(text, at), "end": char_at(text, at + r.len), "style": r.style });+ at += r.len;+ v+ })+ .collect();+ let mut at = 0;+ let paragraphs: Vec<Value> = t+ .paragraph_runs()+ .into_iter()+ .map(|r| {+ let v = json!({ "start": char_at(text, at), "end": char_at(text, at + r.len), "style": r.style });+ at += r.len;+ v+ })+ .collect();+ let layout = photocraft_text::shared()+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .layout(t, d.doc.resolution_dpi);+ let lines: Vec<Value> = layout+ .lines+ .iter()+ .map(|ln| json!({ "start": char_at(text, ln.range.start), "end": char_at(text, ln.range.end), "baseline": ln.baseline, "x0": ln.x0, "x1": ln.x1, "ascent": ln.ascent, "descent": ln.descent }))+ .collect();+ let bounds = t+ .cache+ .as_ref()+ .map(|c| c.content_bounds())+ .map(|r| json!([r.x0, r.y0, r.x1, r.y1]));+ Ok(json!({+ "layer": id.0,+ "text": text,+ "shape": t.shape,+ "transform": t.transform.m,+ "antialias": t.antialias,+ "orientation": t.orientation,+ "warp": t.warp,+ "runs": runs,+ "paragraphs": paragraphs,+ "lines": lines,+ "bounds": bounds,+ "pxPerPt": layout.px_per_pt,+ }))+}++const CHAR_PARAMS: &str = r##""font":str,"fontStyle":str,"weight":100..900,"italic":bool,"size":pt,"color":"#rrggbb"|[r,g,b,a],"tracking":1/1000em,"leading":pt|"auto","baselineShift":pt,"horizontalScale":%,"verticalScale":%,"underline":bool,"strikethrough":bool,"fauxBold":bool,"fauxItalic":bool,"kerning":"metrics|optical|none","caps":"normal|small|all","ligatures":bool,"discretionaryLigatures":bool,"features":{"ss01":1},"variations":{"wght":650},"language":str"##;++pub fn specs() -> Vec<CommandSpec> {+ vec![+ CommandSpec {+ id: "type.create",+ label: "New Type Layer",+ menu: &["Layer", "New"],+ shortcut: None,+ params: r##"{"x":px,"y":px (baseline anchor of point text),"text":str,"box":[x,y,w,h]? (paragraph text),"name":str?,"align":"left|center|right|justify…"?, …character keys: "font","size":pt=12,"color",…}"##,+ enabled: has_doc,+ journal: true,+ run: |s, p| {+ let text = norm_text(p.get("text").and_then(Value::as_str).unwrap_or(""));+ let mut style = CharStyle { font_family: photocraft_text::fonts::DEFAULT_FAMILY.into(), ..Default::default() };+ let fg = s.tools.foreground;+ style.color = Color::rgba(fg[0], fg[1], fg[2], fg[3]);+ apply_char_props(&mut style, p);+ let mut para = ParagraphStyle::default();+ apply_para_props(&mut para, p);+ let (shape, transform) = match p.get("box").and_then(Value::as_array) {+ Some(b) if b.len() == 4 => {+ let v: Vec<f32> = b.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();+ if v[2] <= 0.0 || v[3] <= 0.0 {+ return Err(bad("type.create", "box width and height must be positive"));+ }+ (TextShape::Box { x: 0.0, y: 0.0, width: v[2], height: v[3] }, Affine::translate(f64::from(v[0]), f64::from(v[1])))+ }+ _ => (TextShape::Point, Affine::translate(f32p(p, "x").unwrap_or(0.0).into(), f32p(p, "y").unwrap_or(0.0).into())),+ };+ let mut t = TextLayer {+ runs: vec![TextRun { len: text.len(), style }],+ paragraphs: vec![ParagraphRun { len: text.len(), style: para }],+ text,+ shape,+ transform,+ ..Default::default()+ };+ t.sync_summary();+ let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| layer_name(&t.text));+ let id = s.edit("New Type Layer", |doc, active| {+ refresh(doc, &mut t);+ let id = doc.insert_above(*active, Layer::new(name, LayerContent::Text(t)));+ *active = Some(id);+ Ok(id)+ })?;+ let bounds = s.active().and_then(|d| d.doc.layer(id)).and_then(|l| l.surface()).map(|c| c.content_bounds());+ Ok(json!({ "layer": id.0, "bounds": bounds.map(|r| [r.x0, r.y0, r.x1, r.y1]) }))+ },+ },+ CommandSpec {+ id: "type.edit",+ label: "Edit Type",+ menu: &[],+ shortcut: None,+ params: r##"{"layer":id?,"text":str? (replace all, styles kept),"replace":{"start":char,"end":char,"text":str}?,"runs":[{"start":char,"end":char,…character keys}]?,"box":[x,y,w,h]? (to paragraph text),"point":[x,y]? (to point text),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"antialias":"none|sharp|crisp|strong|smooth"?,"name":str?}"##,+ enabled: has_doc,+ journal: true,+ run: |s, p| {+ let id = layer_id(s, p)?;+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);+ with_text_layer(s, p, "Edit Type", |t, _| {+ if let Some(v) = p.get("text").and_then(Value::as_str) {+ let n = t.text.len();+ replace_text(t, 0, n, v);+ }+ if let Some(r) = p.get("replace") {+ let a = byte_at(&t.text, r.get("start").and_then(Value::as_u64).unwrap_or(0) as usize);+ let b = byte_at(&t.text, r.get("end").and_then(Value::as_u64).map_or(usize::MAX, |x| x as usize));+ let new = r.get("text").and_then(Value::as_str).unwrap_or("");+ replace_text(t, a, b.max(a), new);+ }+ if let Some(Value::Array(runs)) = p.get("runs") {+ for r in runs {+ let a = byte_at(&t.text, r.get("start").and_then(Value::as_u64).unwrap_or(0) as usize);+ let b = byte_at(&t.text, r.get("end").and_then(Value::as_u64).map_or(usize::MAX, |x| x as usize));+ style_range(t, a, b, &|st| {+ apply_char_props(st, r);+ });+ }+ }+ let lin = t.transform.m;+ if let Some(b) = p.get("box").and_then(Value::as_array).filter(|b| b.len() == 4) {+ let v: Vec<f64> = b.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect();+ t.shape = TextShape::Box { x: 0.0, y: 0.0, width: v[2].max(1.0) as f32, height: v[3].max(1.0) as f32 };+ t.transform = Affine { m: [lin[0], lin[1], lin[2], lin[3], v[0], v[1]] };+ }+ if let Some(pt) = p.get("point").and_then(Value::as_array).filter(|b| b.len() == 2) {+ t.shape = TextShape::Point;+ t.transform = Affine { m: [lin[0], lin[1], lin[2], lin[3], pt[0].as_f64().unwrap_or(0.0), pt[1].as_f64().unwrap_or(0.0)] };+ }+ if let Some(d) = p.get("move").and_then(Value::as_array).filter(|b| b.len() == 2) {+ t.transform.m[4] += d[0].as_f64().unwrap_or(0.0);+ t.transform.m[5] += d[1].as_f64().unwrap_or(0.0);+ }+ if let Some(m) = p.get("transform").and_then(Value::as_array).filter(|b| b.len() == 6) {+ for (i, v) in m.iter().enumerate() {+ t.transform.m[i] = v.as_f64().unwrap_or(t.transform.m[i]);+ }+ }+ if let Some(a) = p.get("antialias").and_then(Value::as_str) {+ t.antialias = match a {+ "none" => AntiAlias::None,+ "sharp" => AntiAlias::Sharp,+ "crisp" => AntiAlias::Crisp,+ "strong" => AntiAlias::Strong,+ _ => AntiAlias::Smooth,+ };+ }+ Ok(())+ })?;+ if let Some(n) = name {+ s.edit("Rename Layer", |doc, _| {+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.name = n;+ Ok(())+ })?;+ }+ info(s, &json!({ "layer": id.0 }))+ },+ },+ CommandSpec {+ id: "type.setStyle",+ label: "Set Type Style",+ menu: &[],+ shortcut: None,+ params: Box::leak(+ format!(r##"{{"layer":id?,"range":[startChar,endChar]? (default all), {CHAR_PARAMS}, paragraph keys: "align":"left|center|right|justify|justifyCenter|justifyRight|justifyAll","firstLineIndent":pt,"startIndent":pt,"endIndent":pt,"spaceBefore":pt,"spaceAfter":pt,"autoLeading":%,"direction":"auto|ltr|rtl","hyphenate":bool}}"##)+ .into_boxed_str(),+ ),+ enabled: has_doc,+ journal: true,+ run: |s, p| {+ let id = layer_id(s, p)?;+ with_text_layer(s, p, "Set Type Style", |t, _| {+ let (a, b) = range_param(&t.text, p);+ let mut probe = CharStyle::default();+ if apply_char_props(&mut probe, p) {+ style_range(t, a, b, &|st| {+ apply_char_props(st, p);+ });+ }+ let mut pprobe = ParagraphStyle::default();+ if apply_para_props(&mut pprobe, p) {+ style_paragraphs(t, a, b, &|st| {+ apply_para_props(st, p);+ });+ }+ Ok(())+ })?;+ info(s, &json!({ "layer": id.0 }))+ },+ },+ CommandSpec {+ id: "type.rasterize",+ label: "Rasterize Type",+ menu: &["Layer", "Rasterize"],+ shortcut: None,+ params: r##"{"layer":id?}"##,+ enabled: has_doc,+ journal: true,+ run: |s, p| {+ let id = layer_id(s, p)?;+ s.edit("Rasterize Type", |doc, _| {+ let snapshot = doc.clone();+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ let LayerContent::Text(t) = &mut l.content else {+ return Err(EngineError::Other(format!("layer {} is not a type layer", id.0)));+ };+ if t.cache.is_none() {+ refresh(&snapshot, t);+ }+ let surface = t.cache.take().unwrap_or_else(|| photocraft_raster::Surface::new(snapshot.pixel_format()));+ let surface = if surface.format() == snapshot.pixel_format() { surface } else { surface.convert(snapshot.pixel_format()) };+ l.content = LayerContent::Raster(surface);+ l.psd_blocks.retain(|(k, _)| k != b"TySh");+ Ok(())+ })?;+ Ok(json!({ "layer": id.0 }))+ },+ },+ CommandSpec {+ id: "type.info",+ label: "Type Layer Info",+ menu: &[],+ shortcut: None,+ params: r##"{"layer":id?} → text, runs/paragraphs (char offsets + styles), shape, transform, laid-out lines (text space px), bounds"##,+ enabled: has_doc,+ journal: false,+ run: |s, p| info(s, p),+ },+ CommandSpec {+ id: "type.fonts",+ label: "List Fonts",+ menu: &[],+ shortcut: None,+ params: r##"{"family":str? (faces of one family)}"##,+ enabled: |_| Ok(()),+ journal: false,+ run: |_, p| {+ let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner());+ match p.get("family").and_then(Value::as_str) {+ Some(f) => {+ let faces: Vec<Value> = eng.fonts.faces(f).into_iter().map(|x| json!({ "family": x.family, "weight": x.weight, "italic": x.italic, "axes": x.axes })).collect();+ Ok(json!({ "faces": faces }))+ }+ None => Ok(json!({ "families": eng.fonts.families() })),+ }+ },+ },+ ]+}++#[cfg(test)]+mod tests {+ use super::*;++ fn session() -> Session {+ let mut s = Session::new();+ s.execute(+ "file.new",+ json!({"width": 200, "height": 100, "background": "transparent"}),+ )+ .unwrap();+ s+ }++ fn text_layer(s: &Session, id: u64) -> TextLayer {+ match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content {+ LayerContent::Text(t) => t.clone(),+ other => panic!("{}", other.kind_name()),+ }+ }++ #[test]+ fn create_renders_and_is_undoable() {+ let mut s = session();+ let r = s+ .execute(+ "type.create",+ json!({"x": 10, "y": 50, "text": "Hello", "size": 24, "color": "#ff0000"}),+ )+ .unwrap();+ let id = r["layer"].as_u64().unwrap();+ let b = r["bounds"].as_array().unwrap();+ assert!(+ b[0].as_i64().unwrap() >= 9 && b[3].as_i64().unwrap() <= 56,+ "{b:?}"+ );+ let t = text_layer(&s, id);+ assert_eq!(t.text, "Hello");+ assert_eq!(t.runs[0].style.size_pt, 24.0);+ assert!(t.cache.is_some() && t.psd_raw.is_some());+ let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap();+ assert_eq!(l.name, "Hello");+ // Red pixels exist.+ let c = t.cache.as_ref().unwrap();+ let r = c.content_bounds();+ assert!(+ c.read_region(r)+ .chunks_exact(4)+ .any(|p| p[3] > 0.9 && p[0] > 0.9 && p[1] < 0.1)+ );+ // The TySh we generated parses back to the same model.+ let back =+ photocraft_text::psd::text_layer_from_tysh(t.psd_raw.as_ref().unwrap(), 72.0).unwrap();+ assert_eq!(back.text, "Hello");+ let strip = |mut r: Vec<TextRun>| {+ for x in &mut r {+ x.style.postscript_name = None;+ }+ r+ };+ assert_eq!(strip(back.char_runs()), strip(t.char_runs()));+ assert_eq!(+ back.char_runs()[0].style.postscript_name.as_deref(),+ Some("Inter-Regular")+ );+ assert!(s.undo());+ assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none());+ }++ #[test]+ fn edit_replace_keeps_styles() {+ let mut s = session();+ let id = s+ .execute(+ "type.create",+ json!({"x": 0, "y": 40, "text": "Hello world"}),+ )+ .unwrap()["layer"]+ .as_u64()+ .unwrap();+ s.execute(+ "type.setStyle",+ json!({"layer": id, "range": [6, 11], "fauxBold": true, "color": [0, 0, 1]}),+ )+ .unwrap();+ let t = text_layer(&s, id);+ assert_eq!(t.runs.len(), 2);+ assert_eq!(t.runs[0].len, 6);+ assert!(t.runs[1].style.faux_bold);+ // Insert inside the bold word: inherits bold.+ s.execute(+ "type.edit",+ json!({"layer": id, "replace": {"start": 8, "end": 8, "text": "XX"}}),+ )+ .unwrap();+ let t = text_layer(&s, id);+ assert_eq!(t.text, "Hello woXXrld");+ assert_eq!(t.runs[1].len, 7);+ // Delete across the style boundary.+ s.execute(+ "type.edit",+ json!({"layer": id, "replace": {"start": 3, "end": 8, "text": ""}}),+ )+ .unwrap();+ let t = text_layer(&s, id);+ assert_eq!(t.text, "HelXXrld");+ assert_eq!(t.runs.iter().map(|r| r.len).collect::<Vec<_>>(), vec![3, 5]);+ // Whole-text replace with a multi-byte string.+ let info = s+ .execute("type.edit", json!({"layer": id, "text": "Größe ✓\nzwei"}))+ .unwrap();+ assert_eq!(info["lines"].as_array().unwrap().len(), 2);+ let t = text_layer(&s, id);+ assert_eq!(t.runs.iter().map(|r| r.len).sum::<usize>(), t.text.len());+ }++ #[test]+ fn set_style_paragraph_and_box() {+ let mut s = session();+ let id = s+ .execute("type.create", json!({"box": [10, 10, 80, 80], "text": "one two three four five six seven", "size": 12}))+ .unwrap()["layer"]+ .as_u64()+ .unwrap();+ let info = s+ .execute(+ "type.setStyle",+ json!({"layer": id, "align": "center", "leading": 20}),+ )+ .unwrap();+ let lines = info["lines"].as_array().unwrap();+ assert!(lines.len() >= 3);+ let b0 = lines[0]["baseline"].as_f64().unwrap();+ let b1 = lines[1]["baseline"].as_f64().unwrap();+ assert!((b1 - b0 - 20.0).abs() < 1e-3, "explicit leading {b0} {b1}");+ assert_eq!(info["paragraphs"][0]["style"]["align"], "Center");+ let t = text_layer(&s, id);+ assert!(matches!(t.shape, TextShape::Box { width, .. } if width == 80.0));+ // Pixels stay inside the box horizontally.+ let r = t.cache.as_ref().unwrap().content_bounds();+ assert!(r.x0 >= 9 && r.x1 <= 91, "{r:?}");+ // Convert to point text and move.+ s.execute("type.edit", json!({"layer": id, "point": [5, 30]}))+ .unwrap();+ s.execute("type.edit", json!({"layer": id, "move": [10, 0]}))+ .unwrap();+ let t = text_layer(&s, id);+ assert_eq!(t.shape, TextShape::Point);+ assert_eq!(t.transform.m[4], 15.0);+ }++ #[test]+ fn rasterize_and_fonts() {+ let mut s = session();+ let id = s+ .execute("type.create", json!({"x": 5, "y": 30, "text": "Raster"}))+ .unwrap()["layer"]+ .as_u64()+ .unwrap();+ s.execute("type.rasterize", json!({"layer": id})).unwrap();+ let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap();+ assert!(matches!(l.content, LayerContent::Raster(_)));+ assert!(l.surface().unwrap().content_bounds().width() > 10);+ assert!(+ s.execute("type.edit", json!({"layer": id, "text": "x"}))+ .is_err()+ );+ let fonts = s.execute("type.fonts", json!({})).unwrap();+ assert!(+ fonts["families"]+ .as_array()+ .unwrap()+ .iter()+ .any(|f| f == "Inter")+ );+ let faces = s.execute("type.fonts", json!({"family": "Inter"})).unwrap();+ assert!(!faces["faces"].as_array().unwrap().is_empty());+ }++ #[test]+ fn style_range_on_empty_text() {+ let mut t = TextLayer::default();+ style_range(&mut t, 0, 0, &|s| s.size_pt = 40.0);+ assert_eq!(t.runs[0].style.size_pt, 40.0);+ replace_text(&mut t, 0, 0, "abc");+ assert_eq!(t.runs.len(), 1);+ assert_eq!(t.runs[0].len, 3);+ assert_eq!(t.runs[0].style.size_pt, 40.0);+ }+}diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rsnew file mode 100644index 000000000..e9faee798--- /dev/null+++ b/crates/engine/src/vector_cmds.rs@@ -0,0 +1,1200 @@+//! Vector commands: shape layers (`shape.*`), document paths (`path.*`, Paths panel), selection ⇄+//! path, and layer vector masks (`layer.vectorMask.*`).+//!+//! Coordinates are document pixels. Paths in parameters and results use a compact JSON form:+//!+//! ```json+//! {"subpaths":[{"closed":true,"op":"combine|subtract|intersect|exclude",+//! "knots":[[x,y], {"anchor":[x,y],"in":[x,y],"out":[x,y],"smooth":true}, …]}],+//! "fillRule":"nonzero|evenodd", "inverted":false}+//! ```+//!+//! A knot given as `[x, y]` is a corner with retracted handles; `in`/`out` default to the+//! anchor. The serde form of `photocraft_doc::Path` is accepted too. Colours are `"#rrggbb"`,+//! `"#rrggbbaa"` or `[r,g,b,a]` (0..1); opacities are percentages (0..100).+//!+//! Every edit re-renders the shape layer's cache with `photocraft-vector` in one undoable step.+//! PSD blocks stay byte-identical while they still decode to the model (see `photocraft-io`).++use photocraft_algo::selection::{self as sel, SelectionMode};+use photocraft_color::{BlendMode, Color};+use photocraft_doc::{+ Document, Fill, FillRule, GradientStyle, Knot, Layer, LayerContent, LayerId, LineCap, LineJoin, LiveShape, NamedPath, Path, PathOp,+ ShapeLayer, ShapeStroke, StrokeAlign, Subpath, VectorMask,+};+use photocraft_geom::{Affine, Point, Rect};+use photocraft_vector as vector;+use serde_json::{Value, json};++use crate::commands::{CommandSpec, blend_from_str};+use crate::{EngineError, Result, Session};++/// Keys PSD uses for a shape layer's vector data; dropped when a shape is rasterized.+const SHAPE_BLOCKS: [&[u8; 4]; 8] = [b"vmsk", b"vsms", b"vogk", b"vstk", b"vscg", b"SoCo", b"GdFl", b"PtFl"];++fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }+}++fn has_doc(s: &Session) -> std::result::Result<(), String> {+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())+}++fn has_layer(s: &Session) -> std::result::Result<(), String> {+ let d = s.active().ok_or("no document open")?;+ d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into())+}++fn has_selection(s: &Session) -> std::result::Result<(), String> {+ s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into())+}++fn layer_id(s: &Session, p: &Value) -> Result<LayerId> {+ match p.get("layer").and_then(Value::as_u64) {+ Some(id) => Ok(LayerId(id)),+ None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())),+ }+}++fn f64p(p: &Value, k: &str) -> Option<f64> {+ p.get(k).and_then(Value::as_f64)+}++fn pt(v: &Value) -> Option<Point> {+ match v {+ Value::Array(a) if a.len() >= 2 => Some(Point::new(a[0].as_f64()?, a[1].as_f64()?)),+ Value::Object(_) => Some(Point::new(v.get("x")?.as_f64()?, v.get("y")?.as_f64()?)),+ _ => None,+ }+}++fn nums<const N: usize>(p: &Value, k: &str) -> Option<[f64; N]> {+ let a = p.get(k)?.as_array()?;+ if a.len() < N {+ return None;+ }+ let mut out = [0.0; N];+ for (o, v) in out.iter_mut().zip(a) {+ *o = v.as_f64()?;+ }+ Some(out)+}++/// `[tl, tr, br, bl]` from an array or a single number.+fn radii(p: &Value) -> Option<[f64; 4]> {+ match p.get("radii").or_else(|| p.get("radius"))? {+ Value::Number(n) => n.as_f64().map(|r| [r; 4]),+ _ => nums::<4>(p, "radii"),+ }+}++pub(crate) fn color(v: &Value) -> Option<Color> {+ match v {+ Value::Array(a) if a.len() >= 3 => {+ let c: Vec<f32> = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();+ Some(Color::rgba(c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0)))+ }+ Value::String(s) => {+ let s = s.trim_start_matches('#');+ let h = |i: usize| s.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f32::from(v) / 255.0);+ match s.len() {+ 6 => Some(Color::rgb(h(0)?, h(2)?, h(4)?)),+ 8 => Some(Color::rgba(h(0)?, h(2)?, h(4)?, h(6)?)),+ _ => None,+ }+ }+ _ => None,+ }+}++fn hex(c: &Color) -> String {+ let [r, g, b] = c.to_rgb();+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ if c.alpha < 1.0 { format!("#{:02x}{:02x}{:02x}{:02x}", q(r), q(g), q(b), q(c.alpha)) } else { format!("#{:02x}{:02x}{:02x}", q(r), q(g), q(b)) }+}++fn op_from(s: &str) -> Option<PathOp> {+ Some(match s.to_ascii_lowercase().as_str() {+ "combine" | "add" | "union" => PathOp::Combine,+ "subtract" | "minus" => PathOp::Subtract,+ "intersect" => PathOp::Intersect,+ "exclude" | "xor" => PathOp::Exclude,+ _ => return None,+ })+}++fn op_name(op: PathOp) -> &'static str {+ match op {+ PathOp::Combine => "combine",+ PathOp::Subtract => "subtract",+ PathOp::Intersect => "intersect",+ PathOp::Exclude => "exclude",+ }+}++/// Parses a path from the compact JSON form (or the serde form).+pub fn parse_path(v: &Value) -> std::result::Result<Path, String> {+ let subs = v.get("subpaths").and_then(Value::as_array).ok_or("path needs `subpaths`")?;+ let mut out = Vec::with_capacity(subs.len());+ for (i, s) in subs.iter().enumerate() {+ let knots_v = s.get("knots").and_then(Value::as_array).ok_or(format!("subpath {i} needs `knots`"))?;+ let mut knots = Vec::with_capacity(knots_v.len());+ for (j, k) in knots_v.iter().enumerate() {+ let knot = if k.is_array() {+ let a = pt(k).ok_or(format!("knot {i}.{j}: expected [x, y]"))?;+ Knot::corner(a.x, a.y)+ } else {+ let a = k.get("anchor").and_then(pt).ok_or(format!("knot {i}.{j}: missing anchor"))?;+ let get = |keys: &[&str]| keys.iter().find_map(|key| k.get(*key).and_then(pt));+ Knot {+ anchor: a,+ in_ctrl: get(&["in", "inCtrl", "in_ctrl"]).unwrap_or(a),+ out_ctrl: get(&["out", "outCtrl", "out_ctrl"]).unwrap_or(a),+ smooth: k.get("smooth").and_then(Value::as_bool).unwrap_or(false),+ }+ };+ knots.push(knot);+ }+ let op = match s.get("op").and_then(Value::as_str) {+ Some(o) => op_from(o).ok_or(format!("subpath {i}: unknown op `{o}`"))?,+ None => PathOp::Combine,+ };+ out.push(Subpath { closed: s.get("closed").and_then(Value::as_bool).unwrap_or(true), knots, op });+ }+ let fill_rule = match v.get("fillRule").or_else(|| v.get("fill_rule")).and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() {+ Some("evenodd" | "even-odd" | "even_odd") => FillRule::EvenOdd,+ _ => FillRule::NonZero,+ };+ Ok(Path { subpaths: out, fill_rule, inverted: v.get("inverted").and_then(Value::as_bool).unwrap_or(false) })+}++/// The compact JSON form of a path.+pub fn path_json(p: &Path) -> Value {+ let a = |q: Point| json!([q.x, q.y]);+ json!({+ "subpaths": p.subpaths.iter().map(|s| json!({+ "closed": s.closed,+ "op": op_name(s.op),+ "knots": s.knots.iter().map(|k| json!({ "anchor": a(k.anchor), "in": a(k.in_ctrl), "out": a(k.out_ctrl), "smooth": k.smooth })).collect::<Vec<_>>(),+ })).collect::<Vec<_>>(),+ "fillRule": if p.fill_rule == FillRule::EvenOdd { "evenodd" } else { "nonzero" },+ "inverted": p.inverted,+ })+}++fn fill_json(f: &Fill) -> Value {+ match f {+ Fill::Solid(c) => json!(hex(c)),+ Fill::Gradient { stops, angle, scale, style, reverse } => json!({ "gradient": {+ "stops": stops.iter().map(|(t, c)| json!([t, hex(c)])).collect::<Vec<_>>(),+ "angle": angle, "scale": scale * 100.0, "style": format!("{style:?}").to_ascii_lowercase(), "reverse": reverse } }),+ Fill::Pattern { name, scale } => json!({ "pattern": name, "scale": scale * 100.0 }),+ }+}++/// `"#rrggbb"` / `[r,g,b,a]` / `{"gradient":{"stops":[[t,"#hex"],…],"angle","scale","style","reverse"}}` /+/// `{"pattern":name,"scale"}`. `null` → `Ok(None)` (no fill).+fn parse_fill(v: &Value) -> std::result::Result<Option<Fill>, String> {+ if v.is_null() {+ return Ok(None);+ }+ if let Some(c) = color(v) {+ return Ok(Some(Fill::Solid(c)));+ }+ if let Some(g) = v.get("gradient") {+ let stops: Vec<(f32, Color)> = g+ .get("stops")+ .and_then(Value::as_array)+ .map(|a| a.iter().filter_map(|s| Some((s.get(0)?.as_f64()? as f32, color(s.get(1)?)?))).collect())+ .unwrap_or_else(|| vec![(0.0, Color::BLACK), (1.0, Color::WHITE)]);+ let style = match g.get("style").and_then(Value::as_str).unwrap_or("linear") {+ "radial" => GradientStyle::Radial,+ "angle" => GradientStyle::Angle,+ "reflected" => GradientStyle::Reflected,+ "diamond" => GradientStyle::Diamond,+ _ => GradientStyle::Linear,+ };+ return Ok(Some(Fill::Gradient {+ stops,+ angle: f64p(g, "angle").unwrap_or(90.0) as f32,+ scale: f64p(g, "scale").unwrap_or(100.0) as f32 / 100.0,+ style,+ reverse: g.get("reverse").and_then(Value::as_bool).unwrap_or(false),+ }));+ }+ if let Some(name) = v.get("pattern").and_then(Value::as_str) {+ return Ok(Some(Fill::Pattern { name: name.into(), scale: f64p(v, "scale").unwrap_or(100.0) as f32 / 100.0 }));+ }+ Err(format!("unrecognised fill {v}"))+}++fn stroke_json(s: &ShapeStroke) -> Value {+ json!({+ "width": s.width, "fill": fill_json(&s.paint), "opacity": s.opacity * 100.0,+ "align": format!("{:?}", s.align).to_ascii_lowercase(), "cap": format!("{:?}", s.cap).to_ascii_lowercase(),+ "join": format!("{:?}", s.join).to_ascii_lowercase(), "miterLimit": s.miter_limit, "dashes": s.dashes, "dashOffset": s.dash_offset,+ })+}++/// Applies stroke keys onto `base` (`null` → no stroke).+fn parse_stroke(v: &Value, base: Option<ShapeStroke>, fg: Color) -> std::result::Result<Option<ShapeStroke>, String> {+ if v.is_null() || v.as_bool() == Some(false) {+ return Ok(None);+ }+ let mut s = base.unwrap_or(ShapeStroke { paint: Fill::Solid(fg), ..Default::default() });+ if let Some(w) = f64p(v, "width") {+ s.width = w.max(0.0) as f32;+ }+ if let Some(c) = v.get("color").or_else(|| v.get("fill")) {+ s.paint = parse_fill(c)?.ok_or("stroke colour cannot be null")?;+ }+ if let Some(o) = f64p(v, "opacity") {+ s.opacity = (o / 100.0).clamp(0.0, 1.0) as f32;+ }+ if let Some(a) = v.get("align").and_then(Value::as_str) {+ s.align = match a {+ "inside" => StrokeAlign::Inside,+ "outside" => StrokeAlign::Outside,+ "center" | "centre" => StrokeAlign::Center,+ o => return Err(format!("unknown align `{o}`")),+ };+ }+ if let Some(c) = v.get("cap").and_then(Value::as_str) {+ s.cap = match c {+ "butt" => LineCap::Butt,+ "round" => LineCap::Round,+ "square" => LineCap::Square,+ o => return Err(format!("unknown cap `{o}`")),+ };+ }+ if let Some(j) = v.get("join").and_then(Value::as_str) {+ s.join = match j {+ "miter" => LineJoin::Miter,+ "round" => LineJoin::Round,+ "bevel" => LineJoin::Bevel,+ o => return Err(format!("unknown join `{o}`")),+ };+ }+ if let Some(m) = f64p(v, "miterLimit") {+ s.miter_limit = m.max(1.0) as f32;+ }+ if let Some(d) = v.get("dashes") {+ s.dashes = match d {+ Value::Null => Vec::new(),+ Value::Array(a) => a.iter().filter_map(Value::as_f64).map(|x| x.max(0.0) as f32).collect(),+ _ => return Err("`dashes` must be an array (multiples of the width)".into()),+ };+ }+ if let Some(o) = f64p(v, "dashOffset") {+ s.dash_offset = o as f32;+ }+ Ok(Some(s))+}++fn live_json(l: &LiveShape) -> Value {+ serde_json::to_value(l).unwrap_or(Value::Null)+}++/// Builds a live shape from `kind` + geometry params.+fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&LiveShape>) -> Result<LiveShape> {+ let prev_rect = match prev {+ Some(LiveShape::Rect { rect, .. } | LiveShape::Ellipse { rect } | LiveShape::Polygon { rect, .. }) => Some(*rect),+ _ => None,+ };+ let rect = || nums::<4>(p, "rect").or(prev_rect).ok_or_else(|| bad(cmd, "`rect`: [x, y, w, h] is required"));+ Ok(match kind {+ "rect" | "rectangle" => {+ let r = match prev {+ Some(LiveShape::Rect { radii, .. }) => *radii,+ _ => [0.0; 4],+ };+ LiveShape::Rect { rect: rect()?, radii: radii(p).unwrap_or(r) }+ }+ "roundedRect" | "roundRect" => {+ let r = match prev {+ Some(LiveShape::Rect { radii, .. }) if radii.iter().any(|v| *v > 0.0) => *radii,+ _ => [10.0; 4],+ };+ LiveShape::Rect { rect: rect()?, radii: radii(p).unwrap_or(r) }+ }+ "ellipse" => LiveShape::Ellipse { rect: rect()? },+ "polygon" | "star" => {+ let (ps, pr) = match prev {+ Some(LiveShape::Polygon { sides, star_ratio, .. }) => (*sides, *star_ratio),+ _ => (5, if kind == "star" { 0.5 } else { 1.0 }),+ };+ let sides = f64p(p, "sides").map_or(ps, |v| v.round().clamp(3.0, 100.0) as u32);+ let ratio = f64p(p, "starRatio").map_or(if kind == "star" && pr >= 1.0 { 0.5 } else { pr }, |v| v.clamp(0.01, 1.0));+ LiveShape::Polygon { rect: rect()?, sides, star_ratio: if kind == "polygon" && f64p(p, "starRatio").is_none() { 1.0 } else { ratio } }+ }+ "line" => {+ let (pf, pto, pw) = match prev {+ Some(LiveShape::Line { from, to, weight }) => (Some(*from), Some(*to), *weight),+ _ => (None, None, 1.0),+ };+ LiveShape::Line {+ from: nums::<2>(p, "from").or(pf).ok_or_else(|| bad(cmd, "`from`: [x, y] is required"))?,+ to: nums::<2>(p, "to").or(pto).ok_or_else(|| bad(cmd, "`to`: [x, y] is required"))?,+ weight: f64p(p, "weight").unwrap_or(pw).max(0.0),+ }+ }+ o => return Err(bad(cmd, format!("unknown kind `{o}`"))),+ })+}++fn live_kind(l: &LiveShape) -> &'static str {+ match l {+ LiveShape::Rect { radii, .. } if radii.iter().any(|r| *r > 0.0) => "roundedRect",+ LiveShape::Rect { .. } => "rect",+ LiveShape::Ellipse { .. } => "ellipse",+ LiveShape::Polygon { star_ratio, .. } if *star_ratio < 1.0 => "star",+ LiveShape::Polygon { .. } => "polygon",+ LiveShape::Line { .. } => "line",+ }+}++/// Re-renders a shape layer's cache for `doc` (canvas-clipped, document pixel format).+pub fn refresh_shape(doc: &Document, sh: &mut ShapeLayer) {+ sh.cache = Some(vector::render_shape(sh, doc.pixel_format(), doc.bounds()));+}++/// Moves a layer's vector content by `(dx, dy)`: shape paths (re-rendered) and linked vector+/// masks, recursing into groups. For the Move tool / `layer.move`.+pub fn translate_vectors(doc: &Document, l: &mut Layer, dx: f64, dy: f64) {+ let a = Affine::translate(dx, dy);+ if let Some(vm) = l.vector_mask.as_mut()+ && vm.linked+ {+ vm.path = vm.path.transform(&a);+ }+ match &mut l.content {+ LayerContent::Shape(sh) => {+ transform_shape(sh, &a);+ refresh_shape(doc, sh);+ }+ LayerContent::Group(g) => {+ for c in &mut g.children {+ translate_vectors(doc, c, dx, dy);+ }+ }+ _ => {}+ }+}++/// Applies an affine transform to a shape's path, keeping the live shape when the transform+/// is a translation plus axis-aligned scale (otherwise the shape stops being parametric).+pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {+ sh.path = sh.path.transform(a);+ let [m0, m1, m2, m3, tx, ty] = a.m;+ let axis_aligned = m1.abs() < 1e-12 && m2.abs() < 1e-12 && m0 > 0.0 && m3 > 0.0;+ sh.live = match (sh.live.take(), axis_aligned) {+ (Some(l), true) => {+ let r = |r: [f64; 4]| [r[0] * m0 + tx, r[1] * m3 + ty, r[2] * m0, r[3] * m3];+ let pt = |p: [f64; 2]| [p[0] * m0 + tx, p[1] * m3 + ty];+ Some(match l {+ LiveShape::Rect { rect, radii } => {+ let k = m0.min(m3);+ LiveShape::Rect { rect: r(rect), radii: radii.map(|v| v * k) }+ }+ LiveShape::Ellipse { rect } => LiveShape::Ellipse { rect: r(rect) },+ LiveShape::Polygon { rect, sides, star_ratio } => LiveShape::Polygon { rect: r(rect), sides, star_ratio },+ LiveShape::Line { from, to, weight } => LiveShape::Line { from: pt(from), to: pt(to), weight },+ })+ }+ _ => None,+ };+ sh.psd_raw = None;+}++fn shape_info(s: &Session, id: LayerId) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;+ let LayerContent::Shape(sh) = &l.content else {+ return Err(EngineError::Other(format!("layer {} is a {} layer, not a shape layer", id.0, l.content.kind_name())));+ };+ let bounds = sh.cache.as_ref().map(|c| c.content_bounds()).filter(|r| !r.is_empty()).map(|r| json!([r.x0, r.y0, r.width(), r.height()]));+ Ok(json!({+ "layer": id.0,+ "name": l.name,+ "path": path_json(&sh.path),+ "fill": sh.fill.as_ref().map(fill_json),+ "stroke": sh.stroke.as_ref().map(stroke_json),+ "live": sh.live.as_ref().map(live_json),+ "kind": sh.live.as_ref().map_or("path", live_kind),+ "bounds": bounds,+ }))+}++fn with_shape<R>(s: &mut Session, id: LayerId, label: &str, f: impl FnOnce(&mut ShapeLayer, &mut Layer) -> Result<R>) -> Result<R> {+ s.edit(label, |doc, _| {+ let snapshot = doc.clone();+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ if !matches!(l.content, LayerContent::Shape(_)) {+ return Err(EngineError::Other(format!("layer {} is a {} layer, not a shape layer", id.0, l.content.kind_name())));+ }+ let LayerContent::Shape(mut sh) = std::mem::replace(&mut l.content, LayerContent::Fill(Fill::Solid(Color::BLACK))) else { unreachable!() };+ let r = f(&mut sh, l);+ refresh_shape(&snapshot, &mut sh);+ l.content = LayerContent::Shape(sh);+ r+ })+}++fn default_name(kind: &str) -> &'static str {+ match kind {+ "rect" | "rectangle" => "Rectangle",+ "roundedRect" | "roundRect" => "Rounded Rectangle",+ "ellipse" => "Ellipse",+ "polygon" => "Polygon",+ "star" => "Star",+ "line" => "Line",+ _ => "Shape",+ }+}++fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "shape.create";+ let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect");+ let (path, live) = if kind == "path" {+ let v = p.get("path").ok_or_else(|| bad(CMD, "kind \"path\" needs `path`"))?;+ (parse_path(v).map_err(|e| bad(CMD, e))?, None)+ } else {+ let l = live_from_params(CMD, kind, p, None)?;+ (vector::shapes::live_path(&l), Some(l))+ };+ let fg = s.tools.foreground;+ let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]);+ let fill = match p.get("fill") {+ Some(v) => parse_fill(v).map_err(|e| bad(CMD, e))?,+ None => Some(Fill::Solid(fgc)),+ };+ let stroke = match p.get("stroke") {+ Some(v) => parse_stroke(v, None, fgc).map_err(|e| bad(CMD, e))?,+ None => None,+ };+ // Add to an existing shape layer with a path operation (Shape tool in combine/subtract… mode).+ if let Some(target) = p.get("addTo").and_then(Value::as_u64) {+ let op = p.get("op").and_then(Value::as_str).map_or(Some(PathOp::Combine), op_from).ok_or_else(|| bad(CMD, "unknown `op`"))?;+ let id = LayerId(target);+ with_shape(s, id, "Add Shape", |sh, _| {+ for mut sp in path.subpaths {+ sp.op = op;+ sh.path.subpaths.push(sp);+ }+ sh.live = None;+ sh.psd_raw = None;+ Ok(())+ })?;+ return shape_info(s, id);+ }+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);+ let mut sh = ShapeLayer { path, fill, stroke, live, ..Default::default() };+ let id = s.edit("New Shape Layer", |doc, active| {+ refresh_shape(doc, &mut sh);+ let name = name.unwrap_or_else(|| doc.next_layer_name(default_name(kind)));+ let id = doc.insert_above(*active, Layer::new(name, LayerContent::Shape(sh)));+ *active = Some(id);+ Ok(id)+ })?;+ shape_info(s, id)+}++fn shape_edit(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "shape.edit";+ let id = layer_id(s, p)?;+ let fg = s.tools.foreground;+ let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]);+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);+ with_shape(s, id, "Edit Shape", |sh, layer| {+ if let Some(v) = p.get("path") {+ sh.path = parse_path(v).map_err(|e| bad(CMD, e))?;+ sh.live = None;+ sh.psd_raw = None;+ }+ let geom_keys = ["kind", "rect", "radii", "radius", "sides", "starRatio", "from", "to", "weight"];+ if geom_keys.iter().any(|k| p.get(*k).is_some()) {+ let kind = p.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| sh.live.as_ref().map(|l| live_kind(l).to_string()));+ let kind = kind.ok_or_else(|| bad(CMD, "this shape has no live-shape parameters; pass `kind` or `path`"))?;+ // Explicit radii on a plain rectangle keep it a (now rounded) rectangle.+ let kind = if kind == "rect" && radii(p).is_some_and(|r| r.iter().any(|v| *v > 0.0)) { "roundedRect".to_string() } else { kind };+ let l = live_from_params(CMD, &kind, p, sh.live.as_ref())?;+ sh.path = vector::shapes::live_path(&l);+ sh.live = Some(l);+ sh.psd_raw = None;+ }+ if let Some(m) = nums::<6>(p, "transform") {+ transform_shape(sh, &Affine { m });+ }+ if let Some([dx, dy]) = nums::<2>(p, "move") {+ transform_shape(sh, &Affine::translate(dx, dy));+ }+ if let Some(op) = p.get("op").and_then(Value::as_str) {+ // Operation of the selected subpath(s) (`subpath`: index, default all but the first).+ let op = op_from(op).ok_or_else(|| bad(CMD, format!("unknown op `{op}`")))?;+ match p.get("subpath").and_then(Value::as_u64) {+ Some(i) => sh.path.subpaths.get_mut(i as usize).ok_or_else(|| bad(CMD, "no such subpath"))?.op = op,+ None => sh.path.subpaths.iter_mut().skip(1).for_each(|sp| sp.op = op),+ }+ sh.live = None;+ }+ if let Some(r) = p.get("fillRule").and_then(Value::as_str) {+ sh.path.fill_rule = if r.eq_ignore_ascii_case("evenodd") { FillRule::EvenOdd } else { FillRule::NonZero };+ }+ if let Some(v) = p.get("fill") {+ sh.fill = parse_fill(v).map_err(|e| bad(CMD, e))?;+ }+ if let Some(v) = p.get("stroke") {+ sh.stroke = parse_stroke(v, sh.stroke.clone(), fgc).map_err(|e| bad(CMD, e))?;+ }+ if let Some(n) = name {+ layer.name = n;+ }+ Ok(())+ })?;+ shape_info(s, id)+}++fn shape_rasterize(s: &mut Session, p: &Value) -> Result<Value> {+ let id = layer_id(s, p)?;+ s.edit("Rasterize Shape", |doc, _| {+ let snapshot = doc.clone();+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ let LayerContent::Shape(sh) = &mut l.content else {+ return Err(EngineError::Other(format!("layer {} is not a shape layer", id.0)));+ };+ if sh.cache.is_none() {+ refresh_shape(&snapshot, sh);+ }+ let fmt = snapshot.pixel_format();+ let surface = sh.cache.take().unwrap_or_else(|| photocraft_raster::Surface::new(fmt));+ let surface = if surface.format() == fmt { surface } else { surface.convert(fmt) };+ l.content = LayerContent::Raster(surface);+ l.psd_blocks.retain(|(k, _)| !SHAPE_BLOCKS.contains(&k));+ Ok(())+ })?;+ Ok(json!({ "layer": id.0 }))+}++// ---------------------------------------------------------------------------+// Document paths+// ---------------------------------------------------------------------------++fn is_work(name: Option<&str>) -> bool {+ name.is_none_or(|n| n.is_empty() || n.eq_ignore_ascii_case("work") || n == "Work Path")+}++/// The path a command targets: `"work"`/absent → the work path (falling back to the active+/// layer's shape path or vector mask when there is none), `"layer"` → the active layer's,+/// otherwise a saved path by name.+fn resolve_path(s: &Session, name: Option<&str>) -> Result<Path> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let layer_path = || -> Option<Path> {+ let l = d.doc.layer(d.active_layer?)?;+ match &l.content {+ LayerContent::Shape(sh) => Some(sh.path.clone()),+ _ => l.vector_mask.as_ref().map(|v| v.path.clone()),+ }+ };+ if name == Some("layer") {+ return layer_path().ok_or_else(|| EngineError::Other("active layer has no shape path or vector mask".into()));+ }+ if is_work(name) {+ return d.doc.work_path.clone().or_else(layer_path).ok_or_else(|| EngineError::Other("no work path".into()));+ }+ let n = name.unwrap_or_default();+ d.doc.paths.iter().find(|p| p.name == n).map(|p| p.path.clone()).ok_or_else(|| EngineError::Other(format!("no path named \"{n}\"")))+}++fn paths_list(s: &Session) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let doc = &d.doc;+ let knots = |p: &Path| p.subpaths.iter().map(|s| s.knots.len()).sum::<usize>();+ let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| match &l.content {+ LayerContent::Shape(sh) => Some(json!({ "kind": "shape", "layer": l.id.0, "name": format!("{} Shape Path", l.name), "knots": knots(&sh.path) })),+ _ => l.vector_mask.as_ref().map(|v| json!({ "kind": "vectorMask", "layer": l.id.0, "name": format!("{} Vector Mask", l.name), "knots": knots(&v.path) })),+ });+ Ok(json!({+ "paths": doc.paths.iter().map(|p| json!({ "name": p.name, "knots": knots(&p.path), "subpaths": p.path.subpaths.len() })).collect::<Vec<_>>(),+ "workPath": doc.work_path.as_ref().map(|p| json!({ "knots": knots(p), "subpaths": p.subpaths.len() })),+ "clippingPath": doc.clipping_path.as_ref().map(|c| json!({ "name": c.name, "flatness": c.flatness })),+ "layerPath": layer,+ }))+}++fn path_set(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "path.set";+ let path = parse_path(p.get("path").ok_or_else(|| bad(CMD, "missing `path`"))?).map_err(|e| bad(CMD, e))?;+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);+ let append = p.get("op").and_then(Value::as_str).map(|o| op_from(o).ok_or_else(|| bad(CMD, format!("unknown op `{o}`")))).transpose()?;+ s.edit(if is_work(name.as_deref()) { "Work Path" } else { "Save Path" }, |doc, _| {+ let merge = |old: Option<&Path>, new: Path| match (old, append) {+ (Some(o), Some(op)) => {+ let mut o = o.clone();+ o.subpaths.extend(new.subpaths.into_iter().map(|mut sp| {+ sp.op = op;+ sp+ }));+ o+ }+ _ => new,+ };+ if is_work(name.as_deref()) {+ doc.work_path = Some(merge(doc.work_path.as_ref(), path));+ } else {+ let n = name.clone().unwrap_or_default();+ match doc.paths.iter_mut().find(|q| q.name == n) {+ Some(q) => {+ q.path = merge(Some(&q.path), path);+ }+ None => doc.paths.push(NamedPath { name: n, path, psd_raw: None }),+ }+ }+ Ok(())+ })?;+ let path = resolve_path(s, name.as_deref())?;+ Ok(json!({ "name": name.unwrap_or_else(|| "work".into()), "path": path_json(&path) }))+}++fn path_delete(s: &mut Session, p: &Value) -> Result<Value> {+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);+ s.edit("Delete Path", |doc, _| {+ if is_work(name.as_deref()) {+ return doc.work_path.take().map(|_| ()).ok_or_else(|| EngineError::Other("no work path".into()));+ }+ let n = name.clone().unwrap_or_default();+ let before = doc.paths.len();+ doc.paths.retain(|q| q.name != n);+ if doc.paths.len() == before {+ return Err(EngineError::Other(format!("no path named \"{n}\"")));+ }+ if doc.clipping_path.as_ref().is_some_and(|c| c.name == n) {+ doc.clipping_path = None;+ }+ Ok(())+ })?;+ Ok(Value::Null)+}++fn path_rename(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "path.rename";+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);+ let to = p.get("to").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| bad(CMD, "missing `to`"))?.to_string();+ if is_work(Some(&to)) {+ return Err(bad(CMD, "`to` cannot name the work path"));+ }+ s.edit(if is_work(name.as_deref()) { "Save Path" } else { "Rename Path" }, |doc, _| {+ if doc.paths.iter().any(|q| q.name == to) {+ return Err(EngineError::Other(format!("a path named \"{to}\" already exists")));+ }+ if is_work(name.as_deref()) {+ // Photoshop: saving the work path turns it into a named path.+ let path = doc.work_path.take().ok_or_else(|| EngineError::Other("no work path".into()))?;+ doc.paths.push(NamedPath { name: to.clone(), path, psd_raw: None });+ return Ok(());+ }+ let n = name.clone().unwrap_or_default();+ let q = doc.paths.iter_mut().find(|q| q.name == n).ok_or_else(|| EngineError::Other(format!("no path named \"{n}\"")))?;+ q.name = to.clone();+ if let Some(c) = doc.clipping_path.as_mut()+ && c.name == n+ {+ c.name = to.clone();+ }+ Ok(())+ })?;+ Ok(json!({ "name": to }))+}++fn path_to_selection(s: &mut Session, p: &Value) -> Result<Value> {+ let path = resolve_path(s, p.get("name").and_then(Value::as_str))?;+ let feather = f64p(p, "feather").unwrap_or(0.0) as f32;+ let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true);+ let mode = SelectionMode::parse(p.get("mode").and_then(Value::as_str).unwrap_or("replace"));+ let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds();+ let mut mask = vector::fill_rasterizer(&path, vector::DEFAULT_TOLERANCE).render(area);+ if !aa {+ for v in &mut mask {+ *v = if *v >= 0.5 { 1.0 } else { 0.0 };+ }+ }+ if feather > 0.0 {+ mask = sel::feather(&mask, area.width() as usize, area.height() as usize, feather);+ }+ let selected = s.edit("Make Selection", |doc, _| {+ doc.selection = sel::combine(doc.selection.as_ref(), &mask, area, mode);+ Ok(doc.selection.is_some())+ })?;+ Ok(json!({ "selected": selected }))+}++fn select_to_work_path(s: &mut Session, p: &Value) -> Result<Value> {+ let tol = f64p(p, "tolerance").unwrap_or(2.0).clamp(0.5, 10.0);+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let area = d.doc.bounds();+ let sel_surface = d.doc.selection.as_ref().ok_or_else(|| EngineError::Other("no selection".into()))?;+ let mask = sel::mask_from_surface(Some(sel_surface), area);+ let path = vector::trace::trace_mask(&mask, area, 0.0, tol);+ let knots: usize = path.subpaths.iter().map(|s| s.knots.len()).sum();+ let subpaths = path.subpaths.len();+ s.edit("Make Work Path", |doc, _| {+ doc.work_path = Some(path);+ Ok(())+ })?;+ Ok(json!({ "subpaths": subpaths, "knots": knots }))+}++fn path_fill(s: &mut Session, p: &Value) -> Result<Value> {+ let path = resolve_path(s, p.get("name").and_then(Value::as_str))?;+ let fg = s.tools.foreground;+ let c = p.get("color").and_then(color).unwrap_or(Color::rgba(fg[0], fg[1], fg[2], fg[3]));+ let rgb = c.to_rgb();+ let src = [rgb[0], rgb[1], rgb[2], c.alpha];+ let opacity = (f64p(p, "opacity").unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32;+ let mode = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(BlendMode::Normal);+ let feather = f64p(p, "feather").unwrap_or(0.0) as f32;+ let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true);+ let id = layer_id(s, p)?;+ s.edit("Fill Path", |doc, _| {+ let area = doc.bounds();+ let r = vector::fill_rasterizer(&path, vector::DEFAULT_TOLERANCE);+ let area = r.pixel_bounds().map_or(area, |b| b.inflate(feather.ceil() as i32 * 2).intersect(&area));+ if area.is_empty() {+ return Ok(());+ }+ let mut cov = r.render(area);+ if !aa {+ cov.iter_mut().for_each(|v| *v = if *v >= 0.5 { 1.0 } else { 0.0 });+ }+ if feather > 0.0 {+ cov = sel::feather(&cov, area.width() as usize, area.height() as usize, feather);+ }+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ let lock = l.locks.transparency;+ let surf = l.surface_mut().ok_or_else(|| EngineError::Other("Fill Path needs a pixel layer".into()))?;+ paint_coverage(surf, area, &cov, src, opacity, mode, lock);+ Ok(())+ })?;+ Ok(Value::Null)+}++/// Composites `src` × coverage onto a surface over `area` (any pixel format).+fn paint_coverage(surf: &mut photocraft_raster::Surface, area: Rect, cov: &[f32], src: [f32; 4], opacity: f32, mode: BlendMode, lock_alpha: bool) {+ let fmt = surf.format();+ let ch = fmt.channels();+ let mut vals = surf.read_region(area);+ for (px, c) in vals.chunks_exact_mut(ch).zip(cov) {+ if *c <= 0.0 {+ continue;+ }+ let dst = photocraft_raster::to_rgba(&fmt, px);+ let mut out = photocraft_compose::psblend::composite(mode, dst, [src[0], src[1], src[2], src[3] * c], opacity);+ if lock_alpha {+ out[3] = dst[3];+ }+ photocraft_raster::from_rgba_into(&fmt, out, px);+ }+ surf.write_region(area, &vals);+ surf.prune();+}++fn path_stroke(s: &mut Session, p: &Value) -> Result<Value> {+ let path = resolve_path(s, p.get("name").and_then(Value::as_str))?;+ let tool = p.get("tool").and_then(Value::as_str).unwrap_or("brush");+ let base = s.tools.brush.clone();+ let fg = s.tools.foreground;+ let mut brush = photocraft_paint::BrushSettings {+ size: f64p(p, "size").map_or(base.size, |v| v as f32),+ hardness: f64p(p, "hardness").map_or(base.hardness, |v| v as f32),+ opacity: f64p(p, "opacity").map_or(base.opacity, |v| (v / 100.0) as f32),+ color: p.get("color").and_then(color).map_or(fg, |c| {+ let v = c.to_rgb();+ [v[0], v[1], v[2], c.alpha]+ }),+ erase: tool == "eraser",+ ..base+ };+ match tool {+ "pencil" => brush.hardness = 1.0,+ "brush" | "eraser" => {}+ o => return Err(bad("path.stroke", format!("unknown tool `{o}` (brush|pencil|eraser)"))),+ }+ let lines = vector::flatten_path(&path, 0.1);+ let id = layer_id(s, p)?;+ let dmg = s.edit("Stroke Path", |doc, _| {+ let sel = doc.selection.clone();+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ let lock = l.locks.transparency;+ let surf = l.surface_mut().ok_or_else(|| EngineError::Other("Stroke Path needs a pixel layer".into()))?;+ let mut dmg = Rect::EMPTY;+ for pl in &lines {+ let mut pts: Vec<photocraft_paint::StrokePoint> = pl.pts.iter().map(|&(x, y)| photocraft_paint::StrokePoint { x, y, pressure: 1.0 }).collect();+ if pl.closed && let Some(first) = pts.first().copied() {+ pts.push(first);+ }+ if pts.is_empty() {+ continue;+ }+ let r = photocraft_paint::apply_stroke(surf, &photocraft_paint::Stroke { brush: brush.clone(), points: pts }, sel.as_ref(), lock);+ dmg = if dmg.is_empty() { r } else { dmg.union(&r) };+ }+ Ok(dmg)+ })?;+ Ok(json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] }))+}++// ---------------------------------------------------------------------------+// Vector masks+// ---------------------------------------------------------------------------++fn vector_mask_info(s: &Session, id: LayerId) -> Result<Value> {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;+ Ok(match &l.vector_mask {+ Some(v) => json!({ "layer": id.0, "path": path_json(&v.path), "enabled": v.enabled, "linked": v.linked, "density": v.density * 100.0, "feather": v.feather }),+ None => json!({ "layer": id.0, "vectorMask": null }),+ })+}++fn vector_mask_add(s: &mut Session, p: &Value, from_path: bool) -> Result<Value> {+ const CMD: &str = "layer.vectorMask.add";+ let id = layer_id(s, p)?;+ let mut path = match p.get("path") {+ Some(v) => parse_path(v).map_err(|e| bad(CMD, e))?,+ None if from_path || p.get("name").is_some() => {+ let name = p.get("name").and_then(Value::as_str);+ // Never fall back to the layer's own path here.+ if is_work(name) {+ s.active().and_then(|d| d.doc.work_path.clone()).ok_or_else(|| EngineError::Other("no work path".into()))?+ } else {+ resolve_path(s, name)?+ }+ }+ None => Path::default(),+ };+ if p.get("hide").and_then(Value::as_bool).unwrap_or(false) {+ path.inverted = !path.inverted;+ }+ s.edit("Add Vector Mask", |doc, _| {+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ if matches!(l.content, LayerContent::Shape(_)) {+ return Err(EngineError::Other("a shape layer's path is already its vector mask".into()));+ }+ if l.locks.all {+ return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));+ }+ l.vector_mask = Some(VectorMask::new(path));+ Ok(())+ })?;+ vector_mask_info(s, id)+}++fn vector_mask_edit(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "layer.vectorMask.edit";+ let id = layer_id(s, p)?;+ let path = p.get("path").map(parse_path).transpose().map_err(|e| bad(CMD, e))?;+ s.edit("Edit Vector Mask", |doc, _| {+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ let vm = l.vector_mask.as_mut().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?;+ if let Some(pth) = path {+ vm.path = pth;+ }+ if let Some(b) = p.get("enabled").and_then(Value::as_bool) {+ vm.enabled = b;+ }+ if let Some(b) = p.get("linked").and_then(Value::as_bool) {+ vm.linked = b;+ }+ if let Some(d) = f64p(p, "density") {+ vm.density = (d / 100.0).clamp(0.0, 1.0) as f32;+ }+ if let Some(f) = f64p(p, "feather") {+ vm.feather = f.max(0.0) as f32;+ }+ if let Some(b) = p.get("invert").and_then(Value::as_bool)+ && b+ {+ vm.path.inverted = !vm.path.inverted;+ }+ Ok(())+ })?;+ vector_mask_info(s, id)+}++fn vector_mask_delete(s: &mut Session, p: &Value) -> Result<Value> {+ let id = layer_id(s, p)?;+ s.edit("Delete Vector Mask", |doc, _| {+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ l.vector_mask.take().map(|_| ()).ok_or_else(|| EngineError::Other("layer has no vector mask".into()))+ })?;+ Ok(Value::Null)+}++/// Layer › Rasterize › Vector Mask: multiplies the vector mask into the pixel mask.+fn vector_mask_rasterize(s: &mut Session, p: &Value) -> Result<Value> {+ let id = layer_id(s, p)?;+ s.edit("Rasterize Vector Mask", |doc, _| {+ let area = doc.bounds();+ let depth = doc.depth;+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ let vm = l.vector_mask.take().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?;+ let vals = vector::vector_mask_values(&vm, area);+ let mut mask = l.mask.take().unwrap_or_else(|| {+ let mut m = photocraft_doc::LayerMask::reveal_all();+ m.surface = photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Grayscale, depth, false), &[1.0]);+ m+ });+ // Outside the canvas the vector mask is 0 unless it is empty/inverted; keep the old default there.+ let old = mask.surface.read_region(area);+ let merged: Vec<f32> = old.iter().zip(&vals).map(|(a, b)| a * b).collect();+ mask.surface.write_region(area, &merged);+ mask.surface.prune();+ l.mask = Some(mask);+ Ok(())+ })?;+ Ok(json!({ "layer": id.0 }))+}++/// `p` with `key` set (for alias commands).+fn with(p: &Value, key: &str, v: Value) -> Value {+ let mut o = if p.is_object() { p.clone() } else { json!({}) };+ o[key] = v;+ o+}++fn toggle_vector_mask(s: &mut Session, p: &Value, key: &str) -> Result<Value> {+ let id = layer_id(s, p)?;+ let cur = {+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let vm = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?.vector_mask.as_ref().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?;+ if key == "enabled" { vm.enabled } else { vm.linked }+ };+ let v = p.get(key).and_then(Value::as_bool).unwrap_or(!cur);+ vector_mask_edit(s, &json!({ "layer": id.0, key: v }))+}++/// Traces the exact coverage of the shape's path back into plain outlines.+fn merge_components(s: &mut Session, p: &Value) -> Result<Value> {+ let id = layer_id(s, p)?;+ let tol = f64p(p, "tolerance").unwrap_or(0.1).clamp(0.05, 10.0);+ with_shape(s, id, "Merge Shape Components", |sh, _| {+ // Trace at 4× resolution so the fitted outline follows the anti-aliased edge closely.+ const K: f64 = 4.0;+ let up = sh.path.transform(&Affine::scale(K));+ let r = vector::fill_rasterizer(&up, vector::DEFAULT_TOLERANCE);+ let Some(b) = r.pixel_bounds() else {+ sh.path.subpaths.clear();+ return Ok(());+ };+ let b = b.inflate(2);+ if u64::from(b.width()) * u64::from(b.height()) > 400_000_000 {+ return Err(EngineError::Other("shape too large to merge".into()));+ }+ let cov = r.render(b);+ let traced = vector::trace::trace_mask(&cov, b, 0.0, tol * K);+ sh.path = traced.transform(&Affine::scale(1.0 / K));+ sh.live = None;+ sh.psd_raw = None;+ Ok(())+ })?;+ shape_info(s, id)+}++fn selection_to_shape(s: &mut Session, p: &Value) -> Result<Value> {+ let tol = f64p(p, "tolerance").unwrap_or(2.0).clamp(0.5, 10.0);+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let area = d.doc.bounds();+ let mask = sel::mask_from_surface(d.doc.selection.as_ref(), area);+ let path = vector::trace::trace_mask(&mask, area, 0.0, tol);+ let mut q = json!({ "kind": "path", "path": path_json(&path) });+ for k in ["fill", "name", "stroke"] {+ if let Some(v) = p.get(k) {+ q[k] = v.clone();+ }+ }+ shape_create(s, &q)+}++// ---------------------------------------------------------------------------+// Specs+// ---------------------------------------------------------------------------++const PATH_FORM: &str = r##"path: {"subpaths":[{"closed":bool=true,"op":"combine|subtract|intersect|exclude","knots":[[x,y] | {"anchor":[x,y],"in":[x,y],"out":[x,y],"smooth":bool}]}],"fillRule":"nonzero|evenodd","inverted":bool}"##;++macro_rules! spec {+ ($id:literal, $label:literal, [$($m:literal),*], $params:expr, $en:expr, $run:expr) => {+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true }+ };+}++fn leak(s: String) -> &'static str {+ Box::leak(s.into_boxed_str())+}++pub fn specs() -> Vec<CommandSpec> {+ let stroke = r##""stroke":{"width":px,"color":"#rrggbb"|fill,"opacity":0..100,"align":"inside|center|outside","cap":"butt|round|square","join":"miter|round|bevel","miterLimit":n,"dashes":[multiples of width],"dashOffset":n}|null"##;+ let fill = r##""fill":"#rrggbb"|[r,g,b,a]|{"gradient":{"stops":[[t,"#hex"]],"angle":deg,"scale":%,"style":"linear|radial|angle|reflected|diamond","reverse":bool}}|{"pattern":name}|null (no fill)"##;+ vec![+ spec!(+ "shape.create",+ "New Shape Layer",+ ["Layer", "New"],+ leak(format!(+ r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"from":[x,y],"to":[x,y],"weight":px=1 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"##+ )),+ has_doc,+ shape_create+ ),+ spec!(+ "shape.edit",+ "Edit Shape",+ [],+ leak(format!(+ r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"##+ )),+ has_layer,+ shape_edit+ ),+ CommandSpec {+ id: "shape.info",+ label: "Shape Layer Info",+ menu: &[],+ shortcut: None,+ params: r##"{"layer":id?} → {layer,name,kind,path,fill,stroke,live,bounds:[x,y,w,h]}"##,+ enabled: has_layer,+ run: |s, p| {+ let id = layer_id(s, p)?;+ shape_info(s, id)+ },+ journal: false,+ },+ spec!("shape.rasterize", "Rasterize Shape", ["Layer", "Rasterize"], r##"{"layer":id?}"##, has_layer, shape_rasterize),+ CommandSpec {+ id: "path.list",+ label: "List Paths",+ menu: &[],+ shortcut: None,+ params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask)}"##,+ enabled: has_doc,+ run: |s, _| paths_list(s),+ journal: false,+ },+ CommandSpec {+ id: "path.info",+ label: "Path Info",+ menu: &[],+ shortcut: None,+ params: r##"{"name":str|"work"|"layer"="work"} → {name,path}"##,+ enabled: has_doc,+ run: |s, p| {+ let name = p.get("name").and_then(Value::as_str);+ let path = resolve_path(s, name)?;+ Ok(json!({ "name": name.unwrap_or("work"), "path": path_json(&path) }))+ },+ journal: false,+ },+ spec!(+ "path.set",+ "Set Path",+ [],+ leak(format!(r##"{{"name":str|"work"="work","path":{{…}},"op":"combine|subtract|intersect|exclude"? (append to the existing path with this op instead of replacing)}}. {PATH_FORM}"##)),+ has_doc,+ path_set+ ),+ spec!("path.delete", "Delete Path", [], r##"{"name":str|"work"="work"}"##, has_doc, path_delete),+ spec!("path.rename", "Rename Path", [], r##"{"name":str|"work"="work","to":str} (renaming the work path saves it)"##, has_doc, path_rename),+ spec!(+ "path.toSelection",+ "Make Selection from Path",+ [],+ r##"{"name":str|"work"|"layer"="work","feather":px=0,"antiAlias":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##,+ has_doc,+ path_to_selection+ ),+ spec!("select.toWorkPath", "Make Work Path", [], r##"{"tolerance":0.5..10 px=2} → {subpaths,knots}"##, has_selection, select_to_work_path),+ spec!(+ "path.fill",+ "Fill Path",+ [],+ r##"{"name":str|"work"|"layer"="work","layer":id? (pixel layer, default active),"color":"#rrggbb"=foreground,"opacity":0..100=100,"mode":"normal|multiply|…"="normal","feather":px=0,"antiAlias":bool=true}"##,+ has_layer,+ path_fill+ ),+ spec!(+ "path.stroke",+ "Stroke Path",+ [],+ r##"{"name":str|"work"|"layer"="work","layer":id? (pixel layer),"tool":"brush|pencil|eraser"="brush","size":px?,"hardness":0..1?,"opacity":0..100?,"color":"#rrggbb"=foreground} (current brush settings otherwise)"##,+ has_layer,+ path_stroke+ ),+ spec!(+ "layer.vectorMask.add",+ "Add Vector Mask",+ ["Layer", "Vector Mask"],+ r##"{"layer":id?,"path":{…}? | "name":str|"work"? (copy a document path),"hide":bool=false (Hide All = inverted)} → vector mask info. Without a path the mask reveals all."##,+ has_layer,+ |s, p| vector_mask_add(s, p, false)+ ),+ spec!(+ "layer.vectorMask.fromPath",+ "Vector Mask from Current Path",+ ["Layer", "Vector Mask"],+ r##"{"layer":id?,"name":str|"work"="work"}"##,+ has_layer,+ |s, p| vector_mask_add(s, p, true)+ ),+ spec!(+ "layer.vectorMask.edit",+ "Edit Vector Mask",+ [],+ leak(format!(r##"{{"layer":id?,"path":{{…}}?,"enabled":bool?,"linked":bool?,"density":0..100?,"feather":px?,"invert":true?}}. {PATH_FORM}"##)),+ has_layer,+ vector_mask_edit+ ),+ spec!("layer.vectorMask.delete", "Delete Vector Mask", ["Layer", "Vector Mask"], r##"{"layer":id?}"##, has_layer, vector_mask_delete),+ spec!("layer.rasterize.vectorMask", "Rasterize Vector Mask", [], r##"{"layer":id?} (multiplied into the layer mask)"##, has_layer, vector_mask_rasterize),+ // Menu ids of Photoshop's Layer › Vector Mask / Rasterize / Combine Shapes.+ spec!("layer.vectorMask.revealAll", "Vector Mask: Reveal All", [], r##"{"layer":id?}"##, has_layer, |s, p| vector_mask_add(s, &with(p, "hide", json!(false)), false)),+ spec!("layer.vectorMask.hideAll", "Vector Mask: Hide All", [], r##"{"layer":id?}"##, has_layer, |s, p| vector_mask_add(s, &with(p, "hide", json!(true)), false)),+ spec!("layer.vectorMask.currentPath", "Vector Mask: Current Path", [], r##"{"layer":id?,"name":str|"work"="work"}"##, has_layer, |s, p| vector_mask_add(s, p, true)),+ spec!("layer.vectorMask.enabled", "Enable Vector Mask", [], r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, has_layer, |s, p| toggle_vector_mask(s, p, "enabled")),+ spec!("layer.vectorMask.linked", "Link Vector Mask", [], r##"{"layer":id?,"linked":bool? (default: toggle)}"##, has_layer, |s, p| toggle_vector_mask(s, p, "linked")),+ spec!("layer.rasterize.shape", "Rasterize Shape", [], r##"{"layer":id?}"##, has_layer, shape_rasterize),+ spec!("layer.combineShapes.unite", "Unite Shapes", [], r##"{"layer":id?,"subpath":index? (default all but the first)}"##, has_layer, |s, p| shape_edit(s, &with(p, "op", json!("combine")))),+ spec!("layer.combineShapes.subtractFrontShape", "Subtract Front Shape", [], r##"{"layer":id?,"subpath":index?}"##, has_layer, |s, p| shape_edit(s, &with(p, "op", json!("subtract")))),+ spec!("layer.combineShapes.intersectShapeAreas", "Intersect Shape Areas", [], r##"{"layer":id?,"subpath":index?}"##, has_layer, |s, p| shape_edit(s, &with(p, "op", json!("intersect")))),+ spec!("layer.combineShapes.excludeOverlappingShapes", "Exclude Overlapping Shapes", [], r##"{"layer":id?,"subpath":index?}"##, has_layer, |s, p| shape_edit(s, &with(p, "op", json!("exclude")))),+ spec!(+ "layer.combineShapes.mergeShapeComponents",+ "Merge Shape Components",+ [],+ r##"{"layer":id?,"tolerance":px=0.1} (bakes the path operations into plain combined outlines, traced from the exact coverage)"##,+ has_layer,+ merge_components+ ),+ spec!(+ "select.convertToShape",+ "Convert Selection to Shape",+ [],+ r##"{"tolerance":px=2,"fill":"#rrggbb"=foreground,"name":str?} → shape.info"##,+ has_selection,+ selection_to_shape+ ),+ CommandSpec {+ id: "layer.vectorMask.info",+ label: "Vector Mask Info",+ menu: &[],+ shortcut: None,+ params: r##"{"layer":id?} → {layer,path,enabled,linked,density,feather}"##,+ enabled: has_layer,+ run: |s, p| {+ let id = layer_id(s, p)?;+ vector_mask_info(s, id)+ },+ journal: false,+ },+ ]+}++#[cfg(test)]+mod tests;diff --git a/crates/engine/src/vector_cmds/tests.rs b/crates/engine/src/vector_cmds/tests.rsnew file mode 100644index 000000000..78f6cdec4--- /dev/null+++ b/crates/engine/src/vector_cmds/tests.rs@@ -0,0 +1,366 @@+use serde_json::json;++use super::*;++fn session(w: u32, h: u32, depth: u32) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": w, "height": h, "background": "white", "depth": depth})).unwrap();+ s+}++fn doc(s: &Session) -> &Document {+ &s.active().unwrap().doc+}++fn shape(s: &Session, id: u64) -> ShapeLayer {+ match &doc(s).layer(LayerId(id)).unwrap().content {+ LayerContent::Shape(sh) => sh.clone(),+ other => panic!("not a shape: {}", other.kind_name()),+ }+}++fn alpha_sum(sh: &ShapeLayer) -> f64 {+ let c = sh.cache.as_ref().unwrap();+ let r = c.content_bounds();+ let fmt = c.format();+ c.read_region(r).chunks_exact(fmt.channels()).map(|p| f64::from(photocraft_raster::to_rgba(&fmt, p)[3])).sum()+}++fn selection_mask(s: &Session) -> Vec<f32> {+ let d = doc(s);+ sel::mask_from_surface(d.selection.as_ref(), d.bounds())+}++#[test]+fn shape_create_every_kind_and_undo() {+ for depth in [8, 16, 32] {+ let mut s = session(200, 150, depth);+ let cases = [+ (json!({"kind": "rect", "rect": [10, 10, 50, 40]}), 2000.0),+ (json!({"kind": "roundedRect", "rect": [10, 10, 50, 40], "radii": 10}), 2000.0 - (4.0 - std::f64::consts::PI) * 100.0),+ (json!({"kind": "ellipse", "rect": [20, 20, 100, 60]}), std::f64::consts::PI * 50.0 * 30.0),+ (json!({"kind": "polygon", "rect": [0, 0, 100, 100], "sides": 6}), 1.5 * 3f64.sqrt() * 2500.0),+ (json!({"kind": "star", "rect": [0, 0, 100, 100], "sides": 5, "starRatio": 0.5}), 0.0),+ (json!({"kind": "line", "from": [10, 100], "to": [110, 100], "weight": 4}), 400.0),+ (json!({"kind": "path", "path": {"subpaths": [{"closed": true, "knots": [[0, 0], [60, 0], [0, 60]]}]}}), 1800.0),+ ];+ let before = doc(&s).layer_count();+ for (i, (p, area)) in cases.iter().enumerate() {+ let r = s.execute("shape.create", p.clone()).unwrap();+ let id = r["layer"].as_u64().unwrap();+ let sh = shape(&s, id);+ assert_eq!(sh.cache.as_ref().unwrap().format(), doc(&s).pixel_format());+ let a = alpha_sum(&sh);+ if *area > 0.0 {+ assert!((a - area).abs() / area < 0.01, "case {i} depth {depth}: {a} vs {area}");+ } else {+ assert!(a > 1000.0);+ }+ assert_eq!(r["kind"], p["kind"], "{r}");+ assert_eq!(s.active().unwrap().active_layer, Some(LayerId(id)));+ }+ assert_eq!(doc(&s).layer_count(), before + cases.len());+ for _ in 0..cases.len() {+ assert!(s.undo());+ }+ assert_eq!(doc(&s).layer_count(), before);+ assert!(s.redo());+ assert_eq!(doc(&s).layer_count(), before + 1);+ }+}++#[test]+fn shape_create_fill_stroke_and_composite() {+ let mut s = session(100, 100, 8);+ let r = s+ .execute("shape.create", json!({"kind": "rect", "rect": [20, 20, 60, 60], "fill": "#ff0000", "stroke": {"width": 4, "color": "#0000ff", "align": "outside"}}))+ .unwrap();+ assert_eq!(r["fill"], "#ff0000");+ assert_eq!(r["stroke"]["align"], "outside");+ assert_eq!(r["bounds"], json!([16, 16, 68, 68]));+ let f = photocraft_compose::flatten(doc(&s));+ let px = |x: i32, y: i32| f.get(x, y);+ assert!(px(50, 50)[0] > 0.99 && px(50, 50)[2] < 0.01);+ assert!(px(18, 50)[2] > 0.99 && px(18, 50)[0] < 0.01);+ assert!(px(10, 10)[1] > 0.99);+ // No fill: only the stroke.+ let r = s.execute("shape.create", json!({"kind": "ellipse", "rect": [5, 5, 40, 40], "fill": null, "stroke": {"width": 2}})).unwrap();+ let sh = shape(&s, r["layer"].as_u64().unwrap());+ assert!(sh.fill.is_none());+ assert!((alpha_sum(&sh) - std::f64::consts::PI * 40.0 * 2.0).abs() < 3.0, "{}", alpha_sum(&sh));+ assert!(s.execute("shape.create", json!({"kind": "rect"})).is_err());+ assert!(s.execute("shape.create", json!({"kind": "blob", "rect": [0, 0, 1, 1]})).is_err());+}++#[test]+fn shape_edit_live_params_and_undo() {+ let mut s = session(200, 200, 8);+ let id = s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 50, 50]})).unwrap()["layer"].as_u64().unwrap();+ let r = s.execute("shape.edit", json!({"layer": id, "rect": [10, 10, 100, 50]})).unwrap();+ assert_eq!(r["bounds"], json!([10, 10, 100, 50]));+ assert!((alpha_sum(&shape(&s, id)) - 5000.0).abs() < 1.0);+ // Radii turn it into a rounded rectangle.+ let r = s.execute("shape.edit", json!({"layer": id, "radii": [20, 0, 20, 0]})).unwrap();+ assert_eq!(r["kind"], "roundedRect");+ assert_eq!(r["live"]["radii"], json!([20.0, 0.0, 20.0, 0.0]));+ // Move keeps the live shape; a rotation drops it.+ let r = s.execute("shape.edit", json!({"layer": id, "move": [5, 7]})).unwrap();+ assert_eq!(r["live"]["rect"], json!([15.0, 17.0, 100.0, 50.0]));+ let r = s.execute("shape.edit", json!({"layer": id, "transform": [0.0, 1.0, -1.0, 0.0, 150.0, 0.0]})).unwrap();+ assert_eq!(r["kind"], "path");+ // Fill/stroke edits merge.+ s.execute("shape.edit", json!({"layer": id, "stroke": {"width": 3}})).unwrap();+ let r = s.execute("shape.edit", json!({"layer": id, "stroke": {"cap": "round", "dashes": [2, 1]}, "fill": {"gradient": {"stops": [[0, "#000000"], [1, "#ffffff"]], "angle": 0}}})).unwrap();+ assert_eq!(r["stroke"]["width"], 3.0);+ assert_eq!(r["stroke"]["cap"], "round");+ assert!(r["fill"]["gradient"].is_object());+ s.execute("shape.edit", json!({"layer": id, "stroke": null, "name": "Box"})).unwrap();+ assert!(shape(&s, id).stroke.is_none());+ assert_eq!(doc(&s).layer(LayerId(id)).unwrap().name, "Box");+ // Undo walks back one edit at a time.+ s.undo();+ assert!(shape(&s, id).stroke.is_some());+ // Editing a non-shape layer fails.+ let bg = doc(&s).layers[0].id.0;+ assert!(s.execute("shape.edit", json!({"layer": bg, "fill": "#000000"})).is_err());+}++#[test]+fn shape_add_to_with_path_ops() {+ let mut s = session(100, 100, 8);+ let id = s.execute("shape.create", json!({"kind": "rect", "rect": [0, 0, 60, 60]})).unwrap()["layer"].as_u64().unwrap();+ let r = s.execute("shape.create", json!({"kind": "rect", "rect": [30, 30, 60, 60], "addTo": id, "op": "subtract"})).unwrap();+ assert_eq!(r["path"]["subpaths"][1]["op"], "subtract");+ assert!((alpha_sum(&shape(&s, id)) - (3600.0 - 900.0)).abs() < 1.0);+ s.execute("layer.combineShapes.intersectShapeAreas", json!({"layer": id})).unwrap();+ assert!((alpha_sum(&shape(&s, id)) - 900.0).abs() < 1.0);+ s.execute("layer.combineShapes.excludeOverlappingShapes", json!({"layer": id})).unwrap();+ assert!((alpha_sum(&shape(&s, id)) - 5400.0).abs() < 1.0);+ // Merge bakes the xor into plain outlines with the same area.+ let r = s.execute("layer.combineShapes.mergeShapeComponents", json!({"layer": id})).unwrap();+ let merged = shape(&s, id);+ assert!(merged.path.subpaths.len() >= 2, "{r}");+ assert!((alpha_sum(&merged) - 5400.0).abs() < 20.0, "{}", alpha_sum(&merged));+}++#[test]+fn shape_rasterize_keeps_pixels() {+ let mut s = session(64, 64, 16);+ let id = s.execute("shape.create", json!({"kind": "ellipse", "rect": [4, 4, 40, 30]})).unwrap()["layer"].as_u64().unwrap();+ let before = shape(&s, id).cache.unwrap();+ let flat = photocraft_compose::flatten(doc(&s));+ s.execute("layer.rasterize.shape", json!({"layer": id})).unwrap();+ let l = doc(&s).layer(LayerId(id)).unwrap();+ assert!(matches!(l.content, LayerContent::Raster(_)));+ assert_eq!(l.surface().unwrap(), &before);+ assert_eq!(photocraft_compose::flatten(doc(&s)).px, flat.px);+ assert!(s.execute("shape.rasterize", json!({"layer": id})).is_err());+}++#[test]+fn paths_set_rename_delete_list() {+ let mut s = session(100, 100, 8);+ let tri = json!({"subpaths": [{"knots": [[10, 10], [90, 10], [50, 90]]}]});+ s.execute("path.set", json!({"path": tri})).unwrap();+ assert!(doc(&s).work_path.is_some());+ // Saving the work path (rename) moves it into the saved paths.+ s.execute("path.rename", json!({"to": "Triangle"})).unwrap();+ assert!(doc(&s).work_path.is_none());+ assert_eq!(doc(&s).paths[0].name, "Triangle");+ s.execute("path.set", json!({"name": "Triangle", "op": "subtract", "path": {"subpaths": [{"knots": [[40, 20], [60, 20], [60, 40], [40, 40]]}]}})).unwrap();+ assert_eq!(doc(&s).paths[0].path.subpaths.len(), 2);+ assert_eq!(doc(&s).paths[0].path.subpaths[1].op, PathOp::Subtract);+ let l = s.execute("path.list", json!({})).unwrap();+ assert_eq!(l["paths"][0]["knots"], 7);+ let info = s.execute("path.info", json!({"name": "Triangle"})).unwrap();+ assert_eq!(info["path"]["subpaths"][1]["op"], "subtract");+ s.execute("path.rename", json!({"name": "Triangle", "to": "Tri"})).unwrap();+ assert!(s.execute("path.delete", json!({"name": "Triangle"})).is_err());+ s.execute("path.delete", json!({"name": "Tri"})).unwrap();+ assert!(doc(&s).paths.is_empty());+ s.undo();+ assert_eq!(doc(&s).paths[0].name, "Tri");+ assert!(s.execute("path.set", json!({"path": {"subpaths": [{"knots": [[0, 0], [1]]}]}})).is_err());+}++#[test]+fn path_to_selection_matches_analytic_shape() {+ let mut s = session(200, 200, 8);+ // Circle of radius 60 at (100, 100) as a work path.+ let c = vector::shapes::ellipse(40.0, 40.0, 120.0, 120.0);+ s.execute("path.set", json!({"path": path_json(&c)})).unwrap();+ s.execute("path.toSelection", json!({})).unwrap();+ let m = selection_mask(&s);+ let area: f64 = m.iter().map(|v| f64::from(*v)).sum();+ let want = std::f64::consts::PI * 3600.0;+ assert!((area - want).abs() / want < 0.005, "{area} vs {want}");+ // Pixel-level: centres well inside/outside are exact; edge pixels match the analytic coverage.+ let at = |x: usize, y: usize| m[y * 200 + x];+ assert_eq!(at(100, 100), 1.0);+ assert_eq!(at(10, 10), 0.0);+ for (x, y) in [(160usize, 100usize), (100, 40), (142, 142)] {+ let d = ((x as f64 + 0.5 - 100.0).powi(2) + (y as f64 + 0.5 - 100.0).powi(2)).sqrt();+ let analytic = (60.0 - d + 0.5).clamp(0.0, 1.0);+ assert!((f64::from(at(x, y)) - analytic).abs() < 0.2, "({x},{y}): {} vs {analytic}", at(x, y));+ }+ // Modes: subtract a square, then intersect.+ s.execute("path.set", json!({"name": "Sq", "path": {"subpaths": [{"knots": [[100, 0], [200, 0], [200, 200], [100, 200]]}]}})).unwrap();+ s.execute("path.toSelection", json!({"name": "Sq", "mode": "subtract"})).unwrap();+ let half: f64 = selection_mask(&s).iter().map(|v| f64::from(*v)).sum();+ assert!((half - want / 2.0).abs() / want < 0.005);+ // Non-anti-aliased selections are binary; feather softens.+ s.execute("path.toSelection", json!({"antiAlias": false})).unwrap();+ assert!(selection_mask(&s).iter().all(|v| *v == 0.0 || *v == 1.0));+ s.execute("path.toSelection", json!({"feather": 8})).unwrap();+ let m = selection_mask(&s);+ assert!(m[100 * 200 + 160] > 0.2 && m[100 * 200 + 160] < 0.8);+}++#[test]+fn selection_to_work_path_roundtrip_iou() {+ let mut s = session(240, 180, 8);+ // An anti-aliased donut plus a rectangle, from a path, as the selection.+ let mut p = vector::shapes::ellipse(20.0, 20.0, 140.0, 140.0);+ p.subpaths.push(vector::shapes::ellipse(60.0, 60.0, 60.0, 60.0).subpaths.remove(0).with_op(PathOp::Subtract));+ p.subpaths.push(vector::shapes::rect(170.0, 30.0, 50.0, 120.0).subpaths.remove(0));+ s.execute("path.set", json!({"name": "src", "path": path_json(&p)})).unwrap();+ s.execute("path.toSelection", json!({"name": "src"})).unwrap();+ let before = selection_mask(&s);+ for tol in [1.0, 2.0] {+ let r = s.execute("select.toWorkPath", json!({"tolerance": tol})).unwrap();+ assert_eq!(r["subpaths"], 3);+ s.execute("path.toSelection", json!({})).unwrap();+ let after = selection_mask(&s);+ let (mut i, mut u) = (0.0f64, 0.0f64);+ for (a, b) in before.iter().zip(&after) {+ i += f64::from(a.min(*b));+ u += f64::from(a.max(*b));+ }+ assert!(i / u > 0.98, "tolerance {tol}: IoU {}", i / u);+ // Restore the original selection for the next tolerance.+ s.execute("path.toSelection", json!({"name": "src"})).unwrap();+ }+ // Selection → shape layer.+ let r = s.execute("select.convertToShape", json!({"fill": "#00ff00"})).unwrap();+ assert_eq!(r["fill"], "#00ff00");+ assert_eq!(r["path"]["subpaths"].as_array().unwrap().len(), 3);+}++#[test]+fn fill_and_stroke_path_on_pixel_layer() {+ let mut s = session(100, 100, 16);+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("path.set", json!({"path": {"subpaths": [{"knots": [[10, 10], [60, 10], [60, 60], [10, 60]]}]}})).unwrap();+ s.execute("path.fill", json!({"color": "#ff0000", "opacity": 50})).unwrap();+ let d = doc(&s);+ let l = d.layer(s.active().unwrap().active_layer.unwrap()).unwrap();+ let px = l.surface().unwrap().rgba(30, 30);+ assert!((px[0] - 1.0).abs() < 1e-3 && (px[3] - 0.5).abs() < 0.01, "{px:?}");+ assert_eq!(l.surface().unwrap().rgba(80, 80)[3], 0.0);+ // Stroke with a hard 4 px pencil along the square outline.+ s.execute("path.stroke", json!({"tool": "pencil", "size": 4, "color": "#0000ff", "opacity": 100})).unwrap();+ let d = doc(&s);+ let surf = d.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().clone();+ assert!(surf.rgba(10, 35)[2] > 0.9);+ assert!(surf.rgba(60, 35)[2] > 0.9);+ assert!(surf.rgba(35, 35)[2] < 0.1);+ assert!(s.execute("path.stroke", json!({"tool": "airbrush"})).is_err());+ // Filling needs a pixel layer.+ s.execute("shape.create", json!({"kind": "rect", "rect": [0, 0, 5, 5]})).unwrap();+ assert!(s.execute("path.fill", json!({})).is_err());+}++#[test]+fn vector_mask_commands_and_compositing() {+ let mut s = session(100, 100, 8);+ s.execute("layer.new.layer", json!({})).unwrap();+ let id = s.active().unwrap().active_layer.unwrap().0;+ // Fill the layer black via a full-canvas path fill (works regardless of edit.fill).+ s.execute("path.set", json!({"name": "all", "path": {"subpaths": [{"knots": [[0, 0], [100, 0], [100, 100], [0, 100]]}]}})).unwrap();+ s.execute("path.fill", json!({"name": "all", "color": "#000000"})).unwrap();+ // Reveal All: nothing hidden.+ s.execute("layer.vectorMask.revealAll", json!({})).unwrap();+ let f = photocraft_compose::flatten(doc(&s));+ assert!(f.get(80, 80)[0] < 0.01);+ // Current path → only the left half shows the black layer.+ s.execute("path.set", json!({"path": {"subpaths": [{"knots": [[0, 0], [50, 0], [50, 100], [0, 100]]}]}})).unwrap();+ s.execute("layer.vectorMask.currentPath", json!({})).unwrap();+ let f = photocraft_compose::flatten(doc(&s));+ assert!(f.get(20, 50)[0] < 0.01 && f.get(80, 50)[0] > 0.99);+ // Disable → all black again; toggling re-enables.+ s.execute("layer.vectorMask.enabled", json!({})).unwrap();+ assert!(photocraft_compose::flatten(doc(&s)).get(80, 50)[0] < 0.01);+ s.execute("layer.vectorMask.enabled", json!({})).unwrap();+ // Density 50%: the hidden half shows half grey.+ let r = s.execute("layer.vectorMask.edit", json!({"density": 50})).unwrap();+ assert_eq!(r["density"], 50.0);+ assert!((photocraft_compose::flatten(doc(&s)).get(80, 50)[0] - 0.5).abs() < 0.01);+ s.execute("layer.vectorMask.edit", json!({"density": 100})).unwrap();+ // Hide All.+ s.execute("layer.vectorMask.hideAll", json!({})).unwrap();+ assert!(photocraft_compose::flatten(doc(&s)).get(20, 50)[0] > 0.99);+ // Rasterize into the pixel mask: same composite, no vector mask left.+ s.execute("layer.vectorMask.currentPath", json!({})).unwrap();+ let before = photocraft_compose::flatten(doc(&s));+ s.execute("layer.rasterize.vectorMask", json!({})).unwrap();+ let l = doc(&s).layer(LayerId(id)).unwrap();+ assert!(l.vector_mask.is_none() && l.mask.is_some());+ assert_eq!(photocraft_compose::flatten(doc(&s)).px, before.px);+ // Delete / undo.+ s.undo();+ s.execute("layer.vectorMask.delete", json!({})).unwrap();+ assert!(doc(&s).layer(LayerId(id)).unwrap().vector_mask.is_none());+ assert!(s.execute("layer.vectorMask.delete", json!({})).is_err());+ s.undo();+ assert!(doc(&s).layer(LayerId(id)).unwrap().vector_mask.is_some());+ // Shape layers cannot take a separate vector mask.+ s.execute("shape.create", json!({"kind": "rect", "rect": [0, 0, 10, 10]})).unwrap();+ assert!(s.execute("layer.vectorMask.revealAll", json!({})).is_err());+}++#[test]+fn translate_vectors_moves_shapes_and_masks() {+ let mut s = session(100, 100, 8);+ let id = s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 20, 20]})).unwrap()["layer"].as_u64().unwrap();+ s.edit("Move", |d, _| {+ let snap = d.clone();+ let l = d.layer_mut(LayerId(id)).unwrap();+ translate_vectors(&snap, l, 5.0, 0.0);+ Ok(())+ })+ .unwrap();+ let sh = shape(&s, id);+ assert_eq!(sh.cache.unwrap().content_bounds(), Rect::new(15, 10, 35, 30));+ assert_eq!(sh.live, Some(LiveShape::Rect { rect: [15.0, 10.0, 20.0, 20.0], radii: [0.0; 4] }));+}++#[test]+fn all_vector_commands_are_registered() {+ for id in [+ "shape.create",+ "shape.edit",+ "shape.info",+ "shape.rasterize",+ "path.set",+ "path.delete",+ "path.rename",+ "path.list",+ "path.info",+ "path.toSelection",+ "select.toWorkPath",+ "path.fill",+ "path.stroke",+ "layer.vectorMask.add",+ "layer.vectorMask.fromPath",+ "layer.vectorMask.delete",+ "layer.vectorMask.edit",+ "layer.rasterize.vectorMask",+ ] {+ assert!(crate::commands::find(id).is_some(), "{id}");+ }+ let mut ids: Vec<&str> = crate::command_specs().iter().map(|c| c.id).collect();+ let n = ids.len();+ ids.sort_unstable();+ ids.dedup();+ assert_eq!(ids.len(), n, "duplicate command ids");+}diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.tomlnew file mode 100644index 000000000..a3108b40c--- /dev/null+++ b/crates/format/Cargo.toml@@ -0,0 +1,26 @@+[package]+name = "photocraft-format"+description = "Native .pcraft document bundle: manifest + content-addressed zstd tiles"+version.workspace = true+edition.workspace = true+license.workspace = true+rust-version.workspace = true++[lints]+workspace = true++[dependencies]+photocraft-geom = { workspace = true }+photocraft-color = { workspace = true }+photocraft-raster = { workspace = true }+photocraft-doc = { workspace = true }+photocraft-codecs = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+thiserror = { workspace = true }+flate2 = { workspace = true }+blake3 = { version = "1.8", default-features = false, features = ["pure"] }+ruzstd = "0.9"++[dev-dependencies]+proptest = { workspace = true }diff --git a/crates/format/fuzz/.gitignore b/crates/format/fuzz/.gitignorenew file mode 100644index 000000000..d932d310f--- /dev/null+++ b/crates/format/fuzz/.gitignore@@ -0,0 +1,4 @@+target/+corpus/+artifacts/+Cargo.lockdiff --git a/crates/format/fuzz/Cargo.toml b/crates/format/fuzz/Cargo.tomlnew file mode 100644index 000000000..5eaf8748d--- /dev/null+++ b/crates/format/fuzz/Cargo.toml@@ -0,0 +1,21 @@+[package]+name = "photocraft-format-fuzz"+version = "0.0.0"+publish = false+edition = "2024"++[package.metadata]+cargo-fuzz = true++[workspace]++[dependencies]+libfuzzer-sys = "0.4"+photocraft-format = { path = ".." }++[[bin]]+name = "load"+path = "fuzz_targets/load.rs"+test = false+doc = false+bench = falsediff --git a/crates/format/fuzz/fuzz_targets/load.rs b/crates/format/fuzz/fuzz_targets/load.rsnew file mode 100644index 000000000..037d70cb5--- /dev/null+++ b/crates/format/fuzz/fuzz_targets/load.rs@@ -0,0 +1,11 @@+#![no_main]+//! Load arbitrary bytes as a .pcraft bundle with tight limits.++use libfuzzer_sys::fuzz_target;+use photocraft_format::{LoadOptions, load_from_bytes_with, read_manifest};++fuzz_target!(|data: &[u8]| {+ let opts = LoadOptions { max_manifest_bytes: 1 << 20, max_blob_bytes: 16 << 20, max_total_bytes: 64 << 20, preserve_ids: false };+ let _ = load_from_bytes_with(data, &opts);+ let _ = read_manifest(data);+});diff --git a/crates/format/src/autosave.rs b/crates/format/src/autosave.rsnew file mode 100644index 000000000..b93d84d19--- /dev/null+++ b/crates/format/src/autosave.rs@@ -0,0 +1,228 @@+//! Autosave and crash recovery (architecture §9): the same incremental writer+//! saves a document *snapshot* into a recovery directory on a background+//! thread, so the UI never blocks.+//!+//! Layout: `<recovery_dir>/<key>.pcraft/` (directory bundles, so repeated+//! autosaves write only changed tiles) plus `<key>.json` with+//! [`RecoveryInfo`]. Native targets only (threads and a filesystem).++use std::path::{Path, PathBuf};+use std::sync::mpsc::{self, Receiver, Sender};+use std::sync::{Arc, Mutex};+use std::thread::JoinHandle;+use std::time::{SystemTime, UNIX_EPOCH};++use photocraft_doc::Document;+use serde::{Deserialize, Serialize};++use crate::store::write_atomic;+use crate::{PcraftWriter, Result, SaveOptions, SaveStats};++/// Sidecar describing an autosave.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct RecoveryInfo {+ pub key: String,+ pub document_name: String,+ /// Where the user last saved the document, if anywhere.+ pub original_path: Option<String>,+ /// Seconds since the Unix epoch.+ pub saved_at: u64,+ pub revision: u64,+}++/// One recoverable document found by [`list_recovery`].+#[derive(Debug, Clone, PartialEq)]+pub struct RecoveryEntry {+ pub info: RecoveryInfo,+ pub bundle: PathBuf,+}++struct Job {+ snapshot: Arc<Document>,+ info: RecoveryInfo,+ opts: SaveOptions,+}++/// Background autosaver for one document. Requests are coalesced: if saves+/// arrive faster than they complete, only the newest snapshot is written.+pub struct Autosaver {+ dir: PathBuf,+ key: String,+ tx: Option<Sender<Job>>,+ handle: Option<JoinHandle<()>>,+ last: Arc<Mutex<Option<Result<SaveStats>>>>,+}++fn sanitize(key: &str) -> String {+ let s: String = key+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {+ c+ } else {+ '_'+ }+ })+ .collect();+ if s.is_empty() { "untitled".into() } else { s }+}++impl Autosaver {+ /// `key` identifies the document across autosaves (e.g. its DocId).+ pub fn new(recovery_dir: impl Into<PathBuf>, key: &str) -> Self {+ let dir = recovery_dir.into();+ let key = sanitize(key);+ let (tx, rx) = mpsc::channel::<Job>();+ let last = Arc::new(Mutex::new(None));+ let bundle = dir.join(format!("{key}.pcraft"));+ let sidecar = dir.join(format!("{key}.json"));+ let last2 = last.clone();+ let handle = std::thread::Builder::new()+ .name(format!("autosave-{key}"))+ .spawn(move || worker(rx, bundle, sidecar, last2))+ .ok();+ Autosaver {+ dir,+ key,+ tx: Some(tx),+ handle,+ last,+ }+ }++ pub fn bundle_path(&self) -> PathBuf {+ self.dir.join(format!("{}.pcraft", self.key))+ }++ /// Queue a snapshot for saving (returns immediately).+ pub fn request(+ &self,+ snapshot: Arc<Document>,+ revision: u64,+ original_path: Option<String>,+ opts: SaveOptions,+ ) {+ let info = RecoveryInfo {+ key: self.key.clone(),+ document_name: snapshot.name.clone(),+ original_path,+ saved_at: SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0),+ revision,+ };+ if let Some(tx) = &self.tx {+ let _ = tx.send(Job {+ snapshot,+ info,+ opts,+ });+ }+ }++ /// Result of the most recent completed save.+ pub fn last_result(&self) -> Option<std::result::Result<SaveStats, String>> {+ let g = self.last.lock().ok()?;+ g.as_ref()+ .map(|r| r.as_ref().map(|s| *s).map_err(|e| e.to_string()))+ }++ /// Finish pending saves and stop the thread.+ pub fn flush(mut self) -> Option<std::result::Result<SaveStats, String>> {+ self.shutdown();+ self.last_result()+ }++ /// The document was saved normally or closed: drop its recovery data.+ pub fn discard(mut self) -> Result<()> {+ self.shutdown();+ remove_entry(&self.dir, &self.key)+ }++ fn shutdown(&mut self) {+ self.tx.take();+ if let Some(h) = self.handle.take() {+ let _ = h.join();+ }+ }+}++impl Drop for Autosaver {+ fn drop(&mut self) {+ self.shutdown();+ }+}++fn worker(+ rx: Receiver<Job>,+ bundle: PathBuf,+ sidecar: PathBuf,+ last: Arc<Mutex<Option<Result<SaveStats>>>>,+) {+ let mut writer = PcraftWriter::new();+ while let Ok(mut job) = rx.recv() {+ // Coalesce: skip to the newest queued snapshot.+ while let Ok(newer) = rx.try_recv() {+ job = newer;+ }+ let r = (|| {+ std::fs::create_dir_all(&bundle)?;+ let stats = writer.save_dir(&job.snapshot, &bundle, &job.opts)?;+ write_atomic(&sidecar, &serde_json::to_vec_pretty(&job.info)?)?;+ Ok(stats)+ })();+ if let Ok(mut g) = last.lock() {+ *g = Some(r);+ }+ }+}++/// Recoverable documents in `recovery_dir`, newest first.+pub fn list_recovery(recovery_dir: &Path) -> Vec<RecoveryEntry> {+ let mut out = Vec::new();+ let Ok(rd) = std::fs::read_dir(recovery_dir) else {+ return out;+ };+ for e in rd.flatten() {+ let p = e.path();+ if p.extension().is_some_and(|x| x == "json")+ && let Ok(bytes) = std::fs::read(&p)+ && let Ok(info) = serde_json::from_slice::<RecoveryInfo>(&bytes)+ {+ let bundle = recovery_dir.join(format!("{}.pcraft", info.key));+ if bundle.join(crate::store::MANIFEST).is_file() {+ out.push(RecoveryEntry { info, bundle });+ }+ }+ }+ out.sort_by(|a, b| {+ b.info+ .saved_at+ .cmp(&a.info.saved_at)+ .then(a.info.key.cmp(&b.info.key))+ });+ out+}++/// Load a recovered document.+pub fn recover(entry: &RecoveryEntry) -> Result<Document> {+ crate::load_path(&entry.bundle)+}++/// Delete a recovery entry.+pub fn discard_recovery(recovery_dir: &Path, entry: &RecoveryEntry) -> Result<()> {+ remove_entry(recovery_dir, &entry.info.key)+}++fn remove_entry(dir: &Path, key: &str) -> Result<()> {+ let bundle = dir.join(format!("{key}.pcraft"));+ if bundle.exists() {+ std::fs::remove_dir_all(bundle)?;+ }+ let sidecar = dir.join(format!("{key}.json"));+ if sidecar.exists() {+ std::fs::remove_file(sidecar)?;+ }+ Ok(())+}diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rsnew file mode 100644index 000000000..1992e60d2--- /dev/null+++ b/crates/format/src/convert.rs@@ -0,0 +1,501 @@+//! Document ⇄ manifest conversion. Binary data is routed through a+//! [`Sink`] (save) or [`Fetch`] (load) keyed by BLAKE3 hash.++use std::sync::Arc;++use photocraft_color::{PixelFormat, SampleType};+use photocraft_doc::{+ AlphaChannel, DocId, Document, Effects, FillCache, Group, Layer, LayerContent, LayerId,+ LayerMask, Metadata, NamedPath, ShapeLayer, SmartObject, SmartSource, TextLayer,+};+use photocraft_geom::{TILE_SIZE, TileCoord};+use photocraft_raster::{Surface, Tile, decode_pixel, encode_pixel};++use crate::manifest::*;+use crate::{FormatError, Result};++pub(crate) trait Sink {+ /// Register a tile, returning its hash.+ fn tile(&mut self, format: PixelFormat, tile: &Arc<Tile>) -> Hash;+ fn blob(&mut self, data: &Arc<Vec<u8>>) -> Hash;+}++pub(crate) trait Fetch {+ /// Canonical (little-endian) tile bytes of the given expected length.+ fn tile(&mut self, hash: &str, len: usize) -> Result<Vec<u8>>;+ fn blob(&mut self, hash: &str) -> Result<Arc<Vec<u8>>>;+}++pub(crate) fn hex(bytes: &[u8]) -> String {+ const H: &[u8; 16] = b"0123456789abcdef";+ let mut s = String::with_capacity(bytes.len() * 2);+ for b in bytes {+ s.push(H[(b >> 4) as usize] as char);+ s.push(H[(b & 15) as usize] as char);+ }+ s+}++pub(crate) fn unhex(s: &str) -> Result<Vec<u8>> {+ if !s.len().is_multiple_of(2) {+ return Err(FormatError::corrupt(format!("bad hex `{s}`")));+ }+ (0..s.len())+ .step_by(2)+ .map(|i| {+ u8::from_str_radix(s.get(i..i + 2).unwrap_or("x"), 16)+ .map_err(|_| FormatError::corrupt(format!("bad hex `{s}`")))+ })+ .collect()+}++fn key4(s: &str) -> Result<[u8; 4]> {+ unhex(s)?+ .try_into()+ .map_err(|_| FormatError::corrupt(format!("bad 4-byte key `{s}`")))+}++pub(crate) fn is_valid_hash(h: &str) -> bool {+ h.len() == 64+ && h.bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+}++/// Convert native-endian sample bytes to little-endian in place (and back:+/// the swap is an involution).+pub(crate) fn swap_to_le(bytes: &mut [u8], sample: SampleType) {+ if cfg!(target_endian = "big") {+ match sample {+ SampleType::U8 => {}+ SampleType::U16 => bytes.chunks_exact_mut(2).for_each(|c| c.reverse()),+ SampleType::F32 => bytes.chunks_exact_mut(4).for_each(|c| c.reverse()),+ }+ }+}++pub(crate) fn tile_len(format: &PixelFormat) -> usize {+ (TILE_SIZE * TILE_SIZE) as usize * format.bytes_per_pixel()+}++// ---------------------------------------------------------------------------+// Save+// ---------------------------------------------------------------------------++fn surface_m(s: &Surface, sink: &mut dyn Sink) -> SurfaceM {+ let f = s.format();+ let mut dp = vec![0u8; f.bytes_per_pixel()];+ encode_pixel(&f, &s.default_pixel(), &mut dp);+ swap_to_le(&mut dp, f.sample);+ SurfaceM {+ format: f,+ default: hex(&dp),+ tiles: s+ .tiles()+ .map(|(c, t)| TileRef {+ tx: c.tx,+ ty: c.ty,+ hash: sink.tile(f, t),+ })+ .collect(),+ }+}++fn opt_blob(b: &Option<Arc<Vec<u8>>>, sink: &mut dyn Sink) -> Option<Hash> {+ b.as_ref().map(|b| sink.blob(b))+}++fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {+ let content = match &l.content {+ LayerContent::Raster(s) => ContentM::Raster {+ surface: surface_m(s, sink),+ },+ LayerContent::Group(g) => ContentM::Group {+ children: g.children.iter().map(|c| layer_m(c, sink)).collect(),+ expanded: g.expanded,+ },+ LayerContent::Adjustment(a) => ContentM::Adjustment {+ adjustment: a.clone(),+ },+ LayerContent::Fill(f) => ContentM::Fill { fill: f.clone() },+ LayerContent::Text(t) => ContentM::Text {+ text: t.text.clone(),+ font_family: t.font_family.clone(),+ size_pt: t.size_pt,+ color: t.color,+ transform: t.transform,+ cache: t.cache.as_ref().map(|s| surface_m(s, sink)),+ psd_raw: opt_blob(&t.psd_raw, sink),+ runs: t.runs.clone(),+ paragraphs: t.paragraphs.clone(),+ shape: t.shape,+ orientation: t.orientation,+ antialias: t.antialias,+ warp: t.warp.clone(),+ },+ LayerContent::Shape(s) => ContentM::Shape {+ fill: s.fill.clone(),+ cache: s.cache.as_ref().map(|c| surface_m(c, sink)),+ psd_raw: opt_blob(&s.psd_raw, sink),+ path: s.path.clone(),+ stroke: s.stroke.clone(),+ live: s.live.clone(),+ },+ LayerContent::Smart(s) => ContentM::Smart {+ source: match &s.source {+ SmartSource::Embedded { file_name, bytes } => SmartSourceM::Embedded {+ file_name: file_name.clone(),+ blob: sink.blob(bytes),+ },+ SmartSource::Linked { path } => SmartSourceM::Linked { path: path.clone() },+ },+ transform: s.transform,+ smart_filters: s.smart_filters.clone(),+ cache: s.cache.as_ref().map(|c| surface_m(c, sink)),+ psd_raw: opt_blob(&s.psd_raw, sink),+ },+ };+ LayerM {+ id: l.id.0,+ name: l.name.clone(),+ visible: l.visible,+ locks: l.locks,+ blend: l.blend,+ opacity: l.opacity,+ fill_opacity: l.fill_opacity,+ clipped: l.clipped,+ mask: l.mask.as_ref().map(|m| MaskM {+ surface: surface_m(&m.surface, sink),+ enabled: m.enabled,+ linked: m.linked,+ density: m.density,+ feather: m.feather,+ }),+ vector_mask: l.vector_mask.clone(),+ effects: EffectsM {+ enabled: l.effects.enabled,+ items: l.effects.items.clone(),+ psd_raw: opt_blob(&l.effects.psd_raw, sink),+ },+ label: l.label,+ content,+ psd_blocks: l+ .psd_blocks+ .iter()+ .map(|(k, d)| (hex(k), sink.blob(d)))+ .collect(),+ psd_id: l.psd_id,+ fill_cache: l.fill_cache.as_ref().map(|fc| FillCacheM {+ fill: fc.fill.clone(),+ surface: surface_m(&fc.surface, sink),+ }),+ }+}++pub(crate) fn doc_m(d: &Document, sink: &mut dyn Sink) -> DocM {+ DocM {+ id: d.id.0,+ name: d.name.clone(),+ size: d.size,+ resolution_dpi: d.resolution_dpi,+ mode: d.mode,+ depth: d.depth,+ icc_profile: opt_blob(&d.icc_profile, sink),+ layers: d.layers.iter().map(|l| layer_m(l, sink)).collect(),+ channels: d+ .channels+ .iter()+ .map(|c| ChannelM {+ name: c.name.clone(),+ surface: surface_m(&c.surface, sink),+ spot: c.spot,+ })+ .collect(),+ guides: d.guides.clone(),+ selection: d.selection.as_ref().map(|s| surface_m(s, sink)),+ metadata: MetadataM {+ xmp: d.metadata.xmp.clone(),+ exif: opt_blob(&d.metadata.exif, sink),+ psd_resources: d+ .metadata+ .psd_resources+ .iter()+ .map(|(id, n, b)| (*id, n.clone(), sink.blob(b)))+ .collect(),+ psd_global_blocks: d+ .metadata+ .psd_global_blocks+ .iter()+ .map(|(s, k, b)| (hex(s), hex(k), sink.blob(b)))+ .collect(),+ },+ global_light: d.global_light,+ paths: d+ .paths+ .iter()+ .map(|p| NamedPathM {+ name: p.name.clone(),+ path: p.path.clone(),+ psd_raw: opt_blob(&p.psd_raw, sink),+ })+ .collect(),+ work_path: d.work_path.clone(),+ clipping_path: d.clipping_path.clone(),+ }+}++// ---------------------------------------------------------------------------+// Load+// ---------------------------------------------------------------------------++pub(crate) struct Loader<'a> {+ pub fetch: &'a mut dyn Fetch,+ pub preserve_ids: bool,+ pub max_id: u64,+}++impl Loader<'_> {+ fn surface(&mut self, m: &SurfaceM) -> Result<Surface> {+ let f = m.format;+ let mut dp = unhex(&m.default)?;+ if dp.len() != f.bytes_per_pixel() {+ return Err(FormatError::corrupt(+ "default pixel has wrong size for its format",+ ));+ }+ swap_to_le(&mut dp, f.sample);+ let mut s = Surface::with_default(f, &decode_pixel(&f, &dp));+ let len = tile_len(&f);+ for t in &m.tiles {+ let c = TileCoord::new(t.tx, t.ty);+ if s.tile(c).is_some() {+ return Err(FormatError::corrupt(format!(+ "duplicate tile ({}, {})",+ t.tx, t.ty+ )));+ }+ let mut bytes = self.fetch.tile(&t.hash, len)?;+ swap_to_le(&mut bytes, f.sample);+ s.tile_mut(c).bytes_mut().copy_from_slice(&bytes);+ }+ Ok(s)+ }++ fn opt_surface(&mut self, m: &Option<SurfaceM>) -> Result<Option<Surface>> {+ m.as_ref().map(|s| self.surface(s)).transpose()+ }++ fn opt_blob(&mut self, h: &Option<Hash>) -> Result<Option<Arc<Vec<u8>>>> {+ h.as_ref().map(|h| self.fetch.blob(h)).transpose()+ }++ fn id(&mut self, raw: u64) -> LayerId {+ if self.preserve_ids {+ self.max_id = self.max_id.max(raw);+ LayerId(raw)+ } else {+ LayerId::fresh()+ }+ }++ fn layer(&mut self, m: &LayerM, depth: usize) -> Result<Layer> {+ if depth > 256 {+ return Err(FormatError::LimitExceeded(+ "layer groups nested deeper than 256".into(),+ ));+ }+ let content = match &m.content {+ ContentM::Raster { surface } => LayerContent::Raster(self.surface(surface)?),+ ContentM::Group { children, expanded } => LayerContent::Group(Group {+ children: children+ .iter()+ .map(|c| self.layer(c, depth + 1))+ .collect::<Result<_>>()?,+ expanded: *expanded,+ }),+ ContentM::Adjustment { adjustment } => LayerContent::Adjustment(adjustment.clone()),+ ContentM::Fill { fill } => LayerContent::Fill(fill.clone()),+ ContentM::Text {+ text,+ font_family,+ size_pt,+ color,+ transform,+ cache,+ psd_raw,+ runs,+ paragraphs,+ shape,+ orientation,+ antialias,+ warp,+ } => LayerContent::Text(TextLayer {+ text: text.clone(),+ font_family: font_family.clone(),+ size_pt: *size_pt,+ color: *color,+ transform: *transform,+ cache: self.opt_surface(cache)?,+ psd_raw: self.opt_blob(psd_raw)?,+ runs: runs.clone(),+ paragraphs: paragraphs.clone(),+ shape: *shape,+ orientation: *orientation,+ antialias: *antialias,+ warp: warp.clone(),+ }),+ ContentM::Shape {+ fill,+ cache,+ psd_raw,+ path,+ stroke,+ live,+ } => LayerContent::Shape(ShapeLayer {+ path: path.clone(),+ fill: fill.clone(),+ stroke: stroke.clone(),+ live: live.clone(),+ cache: self.opt_surface(cache)?,+ psd_raw: self.opt_blob(psd_raw)?,+ }),+ ContentM::Smart {+ source,+ transform,+ smart_filters,+ cache,+ psd_raw,+ } => LayerContent::Smart(SmartObject {+ source: match source {+ SmartSourceM::Embedded { file_name, blob } => SmartSource::Embedded {+ file_name: file_name.clone(),+ bytes: self.fetch.blob(blob)?,+ },+ SmartSourceM::Linked { path } => SmartSource::Linked { path: path.clone() },+ },+ transform: *transform,+ smart_filters: smart_filters.clone(),+ cache: self.opt_surface(cache)?,+ psd_raw: self.opt_blob(psd_raw)?,+ }),+ };+ let mask = match &m.mask {+ Some(mm) => Some(LayerMask {+ surface: self.surface(&mm.surface)?,+ enabled: mm.enabled,+ linked: mm.linked,+ density: mm.density,+ feather: mm.feather,+ }),+ None => None,+ };+ let fill_cache = match &m.fill_cache {+ Some(fc) => Some(FillCache {+ fill: fc.fill.clone(),+ surface: self.surface(&fc.surface)?,+ }),+ None => None,+ };+ let mut psd_blocks = Vec::with_capacity(m.psd_blocks.len());+ for (k, h) in &m.psd_blocks {+ psd_blocks.push((key4(k)?, self.fetch.blob(h)?));+ }+ Ok(Layer {+ id: self.id(m.id),+ name: m.name.clone(),+ visible: m.visible,+ locks: m.locks,+ blend: m.blend,+ opacity: m.opacity,+ fill_opacity: m.fill_opacity,+ clipped: m.clipped,+ mask,+ vector_mask: m.vector_mask.clone(),+ effects: Effects {+ enabled: m.effects.enabled,+ items: m.effects.items.clone(),+ psd_raw: self.opt_blob(&m.effects.psd_raw)?,+ },+ label: m.label,+ content,+ psd_blocks,+ psd_id: m.psd_id,+ fill_cache,+ })+ }++ pub(crate) fn document(&mut self, m: &DocM) -> Result<Document> {+ let layers = m+ .layers+ .iter()+ .map(|l| self.layer(l, 0))+ .collect::<Result<Vec<_>>>()?;+ let mut channels = Vec::with_capacity(m.channels.len());+ for c in &m.channels {+ channels.push(AlphaChannel {+ name: c.name.clone(),+ surface: self.surface(&c.surface)?,+ spot: c.spot,+ });+ }+ let mut md = Metadata {+ xmp: m.metadata.xmp.clone(),+ exif: self.opt_blob(&m.metadata.exif)?,+ psd_resources: Vec::new(),+ psd_global_blocks: Vec::new(),+ };+ for (id, n, h) in &m.metadata.psd_resources {+ md.psd_resources.push((*id, n.clone(), self.fetch.blob(h)?));+ }+ for (s, k, h) in &m.metadata.psd_global_blocks {+ md.psd_global_blocks+ .push((key4(s)?, key4(k)?, self.fetch.blob(h)?));+ }+ let mut paths = Vec::with_capacity(m.paths.len());+ for p in &m.paths {+ paths.push(NamedPath {+ name: p.name.clone(),+ path: p.path.clone(),+ psd_raw: self.opt_blob(&p.psd_raw)?,+ });+ }+ let id = if self.preserve_ids {+ self.max_id = self.max_id.max(m.id);+ DocId(m.id)+ } else {+ DocId::fresh()+ };+ Ok(Document {+ id,+ name: m.name.clone(),+ size: m.size,+ resolution_dpi: m.resolution_dpi,+ mode: m.mode,+ depth: m.depth,+ icc_profile: self.opt_blob(&m.icc_profile)?,+ layers,+ channels,+ guides: m.guides.clone(),+ selection: self.opt_surface(&m.selection)?,+ metadata: md,+ global_light: m.global_light,+ paths,+ work_path: m.work_path.clone(),+ clipping_path: m.clipping_path.clone(),+ })+ }+}++/// Advance the global id counter past `max` so ids loaded from a file never+/// collide with ids minted later in this process. Returns `false` if `max`+/// is implausibly far ahead (the caller then remaps ids instead).+pub(crate) fn reserve_ids_through(max: u64) -> bool {+ let probe = LayerId::fresh().0;+ if max < probe {+ return true;+ }+ if max - probe > 10_000_000 {+ return false;+ }+ photocraft_doc::ensure_ids_above(max);+ true+}diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rsnew file mode 100644index 000000000..6e66d615d--- /dev/null+++ b/crates/format/src/lib.rs@@ -0,0 +1,158 @@+//! # photocraft-format+//!+//! The native, lossless `.pcraft` document bundle (architecture §9).+//!+//! ```text+//! manifest.json versioned document tree (see [`manifest`])+//! tiles/<blake3>.zst content-addressed 256×256 tiles (zstd, little-endian samples)+//! blobs/<blake3>.zst content-addressed binary data (ICC, EXIF, PSD blocks, smart objects)+//! thumb.png optional thumbnail (caller-rendered)+//! composite/preview.png optional flattened preview (caller-rendered)+//! ```+//!+//! A bundle is either a ZIP archive (STORE entries) or a directory with the+//! same layout. Saving is incremental: [`PcraftWriter`] remembers what it+//! already compressed/wrote, so only new tiles are encoded, and directory+//! saves write only missing files and garbage-collect unreferenced ones.+//!+//! This crate sits at L3 next to the compositor, so it does not render.+//! Callers pass previews in [`SaveOptions`]; `photocraft-io` does that.+#![forbid(unsafe_code)]++pub mod autosave;+mod convert;+pub mod manifest;+mod migrate;+mod store;+pub mod zip;++use std::path::Path;++use photocraft_doc::Document;+use photocraft_raster::Rgba8Image;++pub use autosave::{Autosaver, RecoveryEntry, discard_recovery, list_recovery, recover};+pub use manifest::{FORMAT_VERSION, Manifest};+pub use store::{PcraftWriter, SaveStats};++/// File extension of the native format.+pub const EXTENSION: &str = "pcraft";++#[derive(Debug, thiserror::Error)]+pub enum FormatError {+ #[error("corrupt .pcraft bundle: {0}")]+ Corrupt(String),+ #[error("unsupported .pcraft feature: {0}")]+ Unsupported(String),+ #[error(+ "bundle written by a newer version (format {found}, this build reads up to {supported})"+ )]+ TooNew { found: u32, supported: u32 },+ #[error("limit exceeded: {0}")]+ LimitExceeded(String),+ #[error("I/O: {0}")]+ Io(#[from] std::io::Error),+ #[error("manifest JSON: {0}")]+ Json(#[from] serde_json::Error),+}++impl FormatError {+ pub(crate) fn corrupt(msg: impl Into<String>) -> Self {+ FormatError::Corrupt(msg.into())+ }+}++pub type Result<T> = std::result::Result<T, FormatError>;++/// Previews to embed. The format crate cannot render (it sits beside the+/// compositor), so callers provide them.+#[derive(Debug, Clone, Default)]+pub struct SaveOptions {+ pub thumbnail: Option<Rgba8Image>,+ pub composite: Option<Rgba8Image>,+}++/// Limits applied while loading untrusted bundles.+#[derive(Debug, Clone, Copy)]+pub struct LoadOptions {+ /// Maximum size of `manifest.json`.+ pub max_manifest_bytes: usize,+ /// Maximum size of one decompressed blob.+ pub max_blob_bytes: usize,+ /// Maximum total decompressed tile + blob bytes.+ pub max_total_bytes: u64,+ /// Keep document and layer ids from the file (the id counter is advanced+ /// past them). When `false`, fresh ids are assigned.+ pub preserve_ids: bool,+}++impl Default for LoadOptions {+ fn default() -> Self {+ LoadOptions {+ max_manifest_bytes: 256 << 20,+ max_blob_bytes: 1 << 30,+ max_total_bytes: 16 << 30,+ preserve_ids: true,+ }+ }+}++/// `true` if `bytes` look like a `.pcraft` ZIP bundle (a ZIP whose first+/// entry is `manifest.json`, which is how we write them).+pub fn is_pcraft(bytes: &[u8]) -> bool {+ bytes.len() > 30 && bytes.starts_with(b"PK\x03\x04") && {+ let n = u16::from_le_bytes([bytes[26], bytes[27]]) as usize;+ bytes.get(30..30 + n) == Some(b"manifest.json")+ }+}++/// Save to an in-memory ZIP bundle (one-shot; use [`PcraftWriter`] for+/// incremental saves).+pub fn save_to_bytes(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>> {+ PcraftWriter::new().save_zip(doc, opts).map(|(b, _)| b)+}++/// Load a ZIP bundle from memory.+pub fn load_from_bytes(bytes: &[u8]) -> Result<Document> {+ load_from_bytes_with(bytes, &LoadOptions::default())+}++pub fn load_from_bytes_with(bytes: &[u8], opts: &LoadOptions) -> Result<Document> {+ let src = store::ZipSource::new(bytes)?;+ store::load(&src, opts)+}++/// Load a bundle from a path: a directory bundle or a ZIP file.+pub fn load_path(path: &Path) -> Result<Document> {+ load_path_with(path, &LoadOptions::default())+}++pub fn load_path_with(path: &Path, opts: &LoadOptions) -> Result<Document> {+ if path.is_dir() {+ store::load(+ &store::DirSource {+ root: path.to_path_buf(),+ },+ opts,+ )+ } else {+ let bytes = std::fs::read(path)?;+ load_from_bytes_with(&bytes, opts)+ }+}++/// Read and migrate only the manifest (fast: no tiles are decoded).+pub fn read_manifest(bytes: &[u8]) -> Result<Manifest> {+ let src = store::ZipSource::new(bytes)?;+ store::read_manifest(&src, &LoadOptions::default())+}++/// The embedded thumbnail, if present (PNG bytes).+pub fn read_thumbnail(bytes: &[u8]) -> Result<Option<Vec<u8>>> {+ let src = store::ZipSource::new(bytes)?;+ let m = store::read_manifest(&src, &LoadOptions::default())?;+ match m.thumbnail {+ Some(p) => Ok(Some(store::Source::get(&src, &p, 64 << 20)?)),+ None => Ok(None),+ }+}diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rsnew file mode 100644index 000000000..a4a23f454--- /dev/null+++ b/crates/format/src/manifest.rs@@ -0,0 +1,209 @@+//! `manifest.json` schema. This is a *separate* serde model from+//! `photocraft-doc` on purpose: the on-disk schema is versioned and migrated+//! independently of in-memory refactors.+//!+//! Binary payloads never live in JSON. Surfaces reference tiles+//! (`tiles/<blake3>.zst`) and other binary data references blobs+//! (`blobs/<blake3>.zst`), both by the BLAKE3 hash of their uncompressed+//! bytes (little-endian samples for tiles).++use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};+use photocraft_doc::{+ Adjustment, ClippingPath, Effect, Fill, GlobalLight, Guides, LabelColor, LiveShape, Locks, Path, ShapeStroke,+ SmartFilter, VectorMask, text,+};+use photocraft_geom::{Affine, Size};+use serde::{Deserialize, Serialize};++/// Current manifest version written by this build.+pub const FORMAT_VERSION: u32 = 1;++/// Hex-encoded BLAKE3 hash (64 chars).+pub type Hash = String;++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct Manifest {+ pub format_version: u32,+ /// Free-form writer identification, e.g. `photocraft-format 0.1.0`.+ pub generator: String,+ pub document: DocM,+ /// Optional previews present in the bundle.+ #[serde(default)]+ pub thumbnail: Option<String>,+ #[serde(default)]+ pub composite: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct DocM {+ pub id: u64,+ pub name: String,+ pub size: Size,+ pub resolution_dpi: f32,+ pub mode: ColorMode,+ pub depth: SampleType,+ pub icc_profile: Option<Hash>,+ /// Bottom-to-top.+ pub layers: Vec<LayerM>,+ pub channels: Vec<ChannelM>,+ pub guides: Guides,+ pub selection: Option<SurfaceM>,+ pub metadata: MetadataM,+ pub global_light: GlobalLight,+ /// Saved paths (Paths panel).+ #[serde(default)]+ pub paths: Vec<NamedPathM>,+ #[serde(default)]+ pub work_path: Option<Path>,+ #[serde(default)]+ pub clipping_path: Option<ClippingPath>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct NamedPathM {+ pub name: String,+ pub path: Path,+ #[serde(default)]+ pub psd_raw: Option<Hash>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct TileRef {+ pub tx: i32,+ pub ty: i32,+ pub hash: Hash,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct SurfaceM {+ pub format: PixelFormat,+ /// Default ("untouched") pixel as hex of its little-endian encoded bytes.+ pub default: String,+ /// 256×256 tiles, interleaved little-endian samples.+ pub tiles: Vec<TileRef>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct MaskM {+ pub surface: SurfaceM,+ pub enabled: bool,+ pub linked: bool,+ pub density: f32,+ pub feather: f32,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct EffectsM {+ pub enabled: bool,+ pub items: Vec<Effect>,+ pub psd_raw: Option<Hash>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct FillCacheM {+ pub fill: Fill,+ pub surface: SurfaceM,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct LayerM {+ pub id: u64,+ pub name: String,+ pub visible: bool,+ pub locks: Locks,+ pub blend: BlendMode,+ pub opacity: f32,+ pub fill_opacity: f32,+ pub clipped: bool,+ pub mask: Option<MaskM>,+ #[serde(default)]+ pub vector_mask: Option<VectorMask>,+ pub effects: EffectsM,+ pub label: LabelColor,+ pub content: ContentM,+ /// (4-char key as hex, blob)+ pub psd_blocks: Vec<(String, Hash)>,+ pub psd_id: Option<u32>,+ pub fill_cache: Option<FillCacheM>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum ContentM {+ Raster {+ surface: SurfaceM,+ },+ Group {+ children: Vec<LayerM>,+ expanded: bool,+ },+ Adjustment {+ adjustment: Adjustment,+ },+ Fill {+ fill: Fill,+ },+ Text {+ text: String,+ font_family: String,+ size_pt: f32,+ color: Color,+ transform: Affine,+ cache: Option<SurfaceM>,+ psd_raw: Option<Hash>,+ #[serde(default)]+ runs: Vec<text::TextRun>,+ #[serde(default)]+ paragraphs: Vec<text::ParagraphRun>,+ #[serde(default)]+ shape: text::TextShape,+ #[serde(default)]+ orientation: text::Orientation,+ #[serde(default)]+ antialias: text::AntiAlias,+ #[serde(default)]+ warp: Option<text::TextWarp>,+ },+ Shape {+ fill: Option<Fill>,+ cache: Option<SurfaceM>,+ psd_raw: Option<Hash>,+ #[serde(default)]+ path: Path,+ #[serde(default)]+ stroke: Option<ShapeStroke>,+ #[serde(default)]+ live: Option<LiveShape>,+ },+ Smart {+ source: SmartSourceM,+ transform: Affine,+ smart_filters: Vec<SmartFilter>,+ cache: Option<SurfaceM>,+ psd_raw: Option<Hash>,+ },+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum SmartSourceM {+ Embedded { file_name: String, blob: Hash },+ Linked { path: String },+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct ChannelM {+ pub name: String,+ pub surface: SurfaceM,+ pub spot: Option<(Color, f32)>,+}++#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+pub struct MetadataM {+ pub xmp: Option<String>,+ pub exif: Option<Hash>,+ /// (id, name, blob)+ pub psd_resources: Vec<(u16, String, Hash)>,+ /// (signature hex, key hex, blob)+ pub psd_global_blocks: Vec<(String, String, Hash)>,+}diff --git a/crates/format/src/migrate.rs b/crates/format/src/migrate.rsnew file mode 100644index 000000000..648d3a808--- /dev/null+++ b/crates/format/src/migrate.rs@@ -0,0 +1,96 @@+//! Manifest migrations. Each step upgrades the raw JSON from version `n` to+//! `n + 1`, so old bundles keep loading as the schema evolves.++use serde_json::Value;++use crate::manifest::FORMAT_VERSION;+use crate::{FormatError, Result};++pub(crate) type Step = fn(&mut Value) -> Result<()>;++/// `STEPS[i]` upgrades version `i + 1` to `i + 2`. Empty while version 1 is+/// the only version.+pub(crate) const STEPS: &[Step] = &[];++/// Upgrade `v` in place to `target` using `steps`.+pub(crate) fn migrate_with(v: &mut Value, steps: &[Step], target: u32) -> Result<u32> {+ let found = v+ .get("format_version")+ .and_then(Value::as_u64)+ .ok_or_else(|| FormatError::corrupt("manifest has no format_version"))?;+ let found =+ u32::try_from(found).map_err(|_| FormatError::corrupt("format_version out of range"))?;+ if found == 0 {+ return Err(FormatError::corrupt("format_version 0 is invalid"));+ }+ if found > target {+ return Err(FormatError::TooNew {+ found,+ supported: target,+ });+ }+ for ver in found..target {+ let step = steps+ .get(ver as usize - 1)+ .ok_or_else(|| FormatError::Unsupported(format!("no migration from format {ver}")))?;+ step(v)?;+ v["format_version"] = Value::from(ver + 1);+ }+ Ok(found)+}++pub(crate) fn migrate(v: &mut Value) -> Result<u32> {+ migrate_with(v, STEPS, FORMAT_VERSION)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn rename_title(v: &mut Value) -> Result<()> {+ let t = v["document"]["title"].take();+ v["document"]["name"] = t;+ Ok(())+ }+ fn add_field(v: &mut Value) -> Result<()> {+ v["document"]["added"] = json!(true);+ Ok(())+ }++ #[test]+ fn chained_steps_run_in_order() {+ let mut v = json!({"format_version": 1, "document": {"title": "old"}});+ let found = migrate_with(&mut v, &[rename_title, add_field], 3).unwrap();+ assert_eq!(found, 1);+ assert_eq!(v["format_version"], 3);+ assert_eq!(v["document"]["name"], "old");+ assert_eq!(v["document"]["added"], true);+ }++ #[test]+ fn partial_chain_from_middle() {+ let mut v = json!({"format_version": 2, "document": {}});+ migrate_with(&mut v, &[rename_title, add_field], 3).unwrap();+ assert_eq!(v["document"]["added"], true);+ assert!(v["document"].get("name").is_none());+ }++ #[test]+ fn too_new_and_invalid_versions() {+ let mut v = json!({"format_version": 99});+ assert!(matches!(+ migrate(&mut v),+ Err(FormatError::TooNew { found: 99, .. })+ ));+ assert!(migrate(&mut json!({"format_version": 0})).is_err());+ assert!(migrate(&mut json!({})).is_err());+ assert!(migrate_with(&mut json!({"format_version": 1}), &[], 2).is_err());+ }++ #[test]+ fn current_version_is_noop() {+ let mut v = json!({"format_version": FORMAT_VERSION});+ assert_eq!(migrate(&mut v).unwrap(), FORMAT_VERSION);+ }+}diff --git a/crates/format/src/store.rs b/crates/format/src/store.rsnew file mode 100644index 000000000..e6f47eb74--- /dev/null+++ b/crates/format/src/store.rs@@ -0,0 +1,497 @@+//! Object storage (ZIP or directory), incremental writer and loader.++use std::collections::{BTreeMap, HashMap, HashSet};+use std::io::Read;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Weak};++use photocraft_color::{PixelFormat, SampleType};+use photocraft_doc::Document;+use photocraft_raster::{Rgba8Image, Tile};++use crate::convert::{self, Fetch, Loader, Sink, is_valid_hash, swap_to_le};+use crate::manifest::{FORMAT_VERSION, Hash, Manifest};+use crate::zip::{ZipReader, ZipWriter};+use crate::{FormatError, LoadOptions, Result, SaveOptions};++pub(crate) const MANIFEST: &str = "manifest.json";+pub(crate) const THUMB: &str = "thumb.png";+pub(crate) const COMPOSITE: &str = "composite/preview.png";++fn tile_path(h: &str) -> String {+ format!("tiles/{h}.zst")+}+fn blob_path(h: &str) -> String {+ format!("blobs/{h}.zst")+}++fn compress(data: &[u8]) -> Vec<u8> {+ ruzstd::encoding::compress_to_vec(data, ruzstd::encoding::CompressionLevel::Fastest)+}++fn decompress(data: &[u8], expected: usize, what: &str) -> Result<Vec<u8>> {+ let mut dec = ruzstd::decoding::StreamingDecoder::new(data)+ .map_err(|e| FormatError::corrupt(format!("{what}: zstd: {e}")))?;+ let mut out = Vec::with_capacity(expected.min(64 << 20));+ (&mut dec)+ .take(expected as u64 + 1)+ .read_to_end(&mut out)+ .map_err(|e| FormatError::corrupt(format!("{what}: zstd: {e}")))?;+ if out.len() != expected {+ return Err(FormatError::corrupt(format!(+ "{what}: expected {expected} bytes, got {}",+ out.len()+ )));+ }+ Ok(out)+}++fn hash_bytes(b: &[u8]) -> Hash {+ blake3::hash(b).to_hex().to_string()+}++fn png(img: &Rgba8Image) -> Result<Vec<u8>> {+ let image = photocraft_codecs::Image::from_u8(+ img.width,+ img.height,+ photocraft_codecs::ChannelLayout::Rgba,+ img.pixels.clone(),+ )+ .map_err(|e| FormatError::Unsupported(format!("preview: {e}")))?;+ photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default())+ .map_err(|e| FormatError::Unsupported(format!("preview: {e}")))+}++// ---------------------------------------------------------------------------+// Sources+// ---------------------------------------------------------------------------++pub(crate) trait Source {+ fn get(&self, path: &str, max: usize) -> Result<Vec<u8>>;+}++pub(crate) struct ZipSource<'a> {+ zip: ZipReader<'a>,+}++impl<'a> ZipSource<'a> {+ pub fn new(bytes: &'a [u8]) -> Result<Self> {+ Ok(ZipSource {+ zip: ZipReader::new(bytes)?,+ })+ }+}++impl Source for ZipSource<'_> {+ fn get(&self, path: &str, max: usize) -> Result<Vec<u8>> {+ self.zip.read_by_name(path, max)+ }+}++pub(crate) struct DirSource {+ pub root: PathBuf,+}++impl Source for DirSource {+ fn get(&self, path: &str, max: usize) -> Result<Vec<u8>> {+ let p = self.root.join(path);+ let len = std::fs::metadata(&p)+ .map_err(|_| FormatError::corrupt(format!("missing `{path}`")))?+ .len();+ if len > max as u64 {+ return Err(FormatError::LimitExceeded(format!(+ "`{path}` is {len} bytes (max {max})"+ )));+ }+ Ok(std::fs::read(p)?)+ }+}++// ---------------------------------------------------------------------------+// Loading+// ---------------------------------------------------------------------------++pub(crate) fn read_manifest(src: &dyn Source, opts: &LoadOptions) -> Result<Manifest> {+ let raw = src.get(MANIFEST, opts.max_manifest_bytes)?;+ let mut v: serde_json::Value = serde_json::from_slice(&raw)?;+ crate::migrate::migrate(&mut v)?;+ Ok(serde_json::from_value(v)?)+}++struct LoadFetch<'a> {+ src: &'a dyn Source,+ opts: LoadOptions,+ total: u64,+ blobs: HashMap<String, Arc<Vec<u8>>>,+}++impl LoadFetch<'_> {+ fn account(&mut self, n: usize) -> Result<()> {+ self.total += n as u64;+ if self.total > self.opts.max_total_bytes {+ return Err(FormatError::LimitExceeded(format!(+ "bundle expands beyond {} bytes",+ self.opts.max_total_bytes+ )));+ }+ Ok(())+ }+}++impl Fetch for LoadFetch<'_> {+ fn tile(&mut self, hash: &str, len: usize) -> Result<Vec<u8>> {+ if !is_valid_hash(hash) {+ return Err(FormatError::corrupt(format!("invalid tile hash `{hash}`")));+ }+ self.account(len)?;+ let path = tile_path(hash);+ let z = self.src.get(&path, len + len / 8 + 4096)?;+ let data = decompress(&z, len, &path)?;+ if hash_bytes(&data) != hash {+ return Err(FormatError::corrupt(format!(+ "{path}: content does not match its hash"+ )));+ }+ Ok(data)+ }++ fn blob(&mut self, hash: &str) -> Result<Arc<Vec<u8>>> {+ if let Some(b) = self.blobs.get(hash) {+ return Ok(b.clone());+ }+ if !is_valid_hash(hash) {+ return Err(FormatError::corrupt(format!("invalid blob hash `{hash}`")));+ }+ let path = blob_path(hash);+ let z = self.src.get(&path, self.opts.max_blob_bytes)?;+ // Blob length is not in the manifest; the frame header bounds it and+ // we cap at max_blob_bytes.+ let mut dec = ruzstd::decoding::StreamingDecoder::new(&z[..])+ .map_err(|e| FormatError::corrupt(format!("{path}: zstd: {e}")))?;+ let mut data = Vec::new();+ (&mut dec)+ .take(self.opts.max_blob_bytes as u64 + 1)+ .read_to_end(&mut data)+ .map_err(|e| FormatError::corrupt(format!("{path}: zstd: {e}")))?;+ if data.len() > self.opts.max_blob_bytes {+ return Err(FormatError::LimitExceeded(format!(+ "{path} exceeds max_blob_bytes"+ )));+ }+ self.account(data.len())?;+ if hash_bytes(&data) != hash {+ return Err(FormatError::corrupt(format!(+ "{path}: content does not match its hash"+ )));+ }+ let data = Arc::new(data);+ self.blobs.insert(hash.to_owned(), data.clone());+ Ok(data)+ }+}++pub(crate) fn load(src: &dyn Source, opts: &LoadOptions) -> Result<Document> {+ let m = read_manifest(src, opts)?;+ let mut fetch = LoadFetch {+ src,+ opts: *opts,+ total: 0,+ blobs: HashMap::new(),+ };+ let mut loader = Loader {+ fetch: &mut fetch,+ preserve_ids: opts.preserve_ids,+ max_id: 0,+ };+ let doc = loader.document(&m.document)?;+ if opts.preserve_ids && !convert::reserve_ids_through(loader.max_id) {+ // Ids far beyond our counter: remap instead of risking collisions.+ let fresh = LoadOptions {+ preserve_ids: false,+ ..*opts+ };+ return load(src, &fresh);+ }+ Ok(doc)+}++// ---------------------------------------------------------------------------+// Saving+// ---------------------------------------------------------------------------++/// What a save did.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct SaveStats {+ /// Distinct tiles referenced by the document.+ pub tiles_total: usize,+ /// Tiles that had to be compressed (ZIP) or written (directory).+ pub tiles_written: usize,+ /// Tiles reused from the previous save.+ pub tiles_reused: usize,+ pub blobs_total: usize,+ pub blobs_written: usize,+ /// Unreferenced objects removed (directory bundles).+ pub objects_removed: usize,+ /// Bytes of the manifest.+ pub manifest_bytes: usize,+}++#[derive(Default)]+struct Collect<'c> {+ tiles: BTreeMap<Hash, (Arc<Tile>, SampleType)>,+ blobs: BTreeMap<Hash, Arc<Vec<u8>>>,+ hash_cache: Option<&'c mut HashMap<usize, (Weak<Tile>, Hash)>>,+}++impl Sink for Collect<'_> {+ fn tile(&mut self, format: PixelFormat, tile: &Arc<Tile>) -> Hash {+ let key = Arc::as_ptr(tile) as usize;+ if let Some(cache) = self.hash_cache.as_deref_mut()+ && let Some((w, h)) = cache.get(&key)+ && w.upgrade().is_some_and(|t| Arc::ptr_eq(&t, tile))+ {+ let h = h.clone();+ self.tiles+ .entry(h.clone())+ .or_insert_with(|| (tile.clone(), format.sample));+ return h;+ }+ let h = if cfg!(target_endian = "big") {+ let mut b = tile.bytes().to_vec();+ swap_to_le(&mut b, format.sample);+ hash_bytes(&b)+ } else {+ hash_bytes(tile.bytes())+ };+ if let Some(cache) = self.hash_cache.as_deref_mut() {+ cache.insert(key, (Arc::downgrade(tile), h.clone()));+ }+ self.tiles+ .entry(h.clone())+ .or_insert_with(|| (tile.clone(), format.sample));+ h+ }++ fn blob(&mut self, data: &Arc<Vec<u8>>) -> Hash {+ let h = hash_bytes(data);+ self.blobs.entry(h.clone()).or_insert_with(|| data.clone());+ h+ }+}++fn tile_le(t: &Tile, sample: SampleType) -> std::borrow::Cow<'_, [u8]> {+ if cfg!(target_endian = "big") {+ let mut b = t.bytes().to_vec();+ swap_to_le(&mut b, sample);+ std::borrow::Cow::Owned(b)+ } else {+ std::borrow::Cow::Borrowed(t.bytes())+ }+}++/// Incremental `.pcraft` writer. Keep one per open document: it remembers+/// tile hashes (by `Arc` identity) and compressed objects, so re-saving only+/// hashes and compresses tiles that changed.+#[derive(Default)]+pub struct PcraftWriter {+ hash_cache: HashMap<usize, (Weak<Tile>, Hash)>,+ /// Compressed objects by bundle path (ZIP mode).+ compressed: HashMap<String, Arc<Vec<u8>>>,+}++struct Prepared {+ manifest: Vec<u8>,+ objects: BTreeMap<String, Object>,+ previews: Vec<(&'static str, Vec<u8>)>,+ stats: SaveStats,+}++enum Object {+ Tile(Arc<Tile>, SampleType),+ Blob(Arc<Vec<u8>>),+}++impl Object {+ fn compressed(&self) -> Vec<u8> {+ match self {+ Object::Tile(t, s) => compress(&tile_le(t, *s)),+ Object::Blob(b) => compress(b),+ }+ }+}++impl PcraftWriter {+ pub fn new() -> Self {+ Self::default()+ }++ fn prepare(&mut self, doc: &Document, opts: &SaveOptions) -> Result<Prepared> {+ self.hash_cache.retain(|_, (w, _)| w.strong_count() > 0);+ let mut c = Collect {+ hash_cache: Some(&mut self.hash_cache),+ ..Default::default()+ };+ let document = convert::doc_m(doc, &mut c);+ let mut previews = Vec::new();+ if let Some(t) = &opts.thumbnail {+ previews.push((THUMB, png(t)?));+ }+ if let Some(t) = &opts.composite {+ previews.push((COMPOSITE, png(t)?));+ }+ let manifest = Manifest {+ format_version: FORMAT_VERSION,+ generator: format!("photocraft-format {}", env!("CARGO_PKG_VERSION")),+ document,+ thumbnail: opts.thumbnail.as_ref().map(|_| THUMB.to_owned()),+ composite: opts.composite.as_ref().map(|_| COMPOSITE.to_owned()),+ };+ let manifest = serde_json::to_vec_pretty(&manifest)?;+ let stats = SaveStats {+ tiles_total: c.tiles.len(),+ blobs_total: c.blobs.len(),+ manifest_bytes: manifest.len(),+ ..Default::default()+ };+ let mut objects = BTreeMap::new();+ for (h, (t, s)) in c.tiles {+ objects.insert(tile_path(&h), Object::Tile(t, s));+ }+ for (h, b) in c.blobs {+ objects.insert(blob_path(&h), Object::Blob(b));+ }+ Ok(Prepared {+ manifest,+ objects,+ previews,+ stats,+ })+ }++ /// Save as a ZIP bundle in memory.+ pub fn save_zip(&mut self, doc: &Document, opts: &SaveOptions) -> Result<(Vec<u8>, SaveStats)> {+ let p = self.prepare(doc, opts)?;+ let mut stats = p.stats;+ let mut z = ZipWriter::new();+ z.add(MANIFEST, &p.manifest)?;+ for (name, data) in &p.previews {+ z.add(name, data)?;+ }+ let mut next = HashMap::with_capacity(p.objects.len());+ for (path, obj) in &p.objects {+ let data = match self.compressed.get(path) {+ Some(d) => {+ if matches!(obj, Object::Tile(..)) {+ stats.tiles_reused += 1;+ }+ d.clone()+ }+ None => {+ match obj {+ Object::Tile(..) => stats.tiles_written += 1,+ Object::Blob(_) => stats.blobs_written += 1,+ }+ Arc::new(obj.compressed())+ }+ };+ z.add(path, &data)?;+ next.insert(path.clone(), data);+ }+ self.compressed = next;+ Ok((z.finish()?, stats))+ }++ /// Save into a directory bundle: writes only missing objects, then the+ /// manifest (atomically), then removes unreferenced objects.+ pub fn save_dir(+ &mut self,+ doc: &Document,+ dir: &Path,+ opts: &SaveOptions,+ ) -> Result<SaveStats> {+ let p = self.prepare(doc, opts)?;+ let mut stats = p.stats;+ for sub in ["tiles", "blobs", "composite"] {+ std::fs::create_dir_all(dir.join(sub))?;+ }+ let existing = list_objects(dir)?;+ for (path, obj) in &p.objects {+ if existing.contains(path) {+ if matches!(obj, Object::Tile(..)) {+ stats.tiles_reused += 1;+ }+ continue;+ }+ match obj {+ Object::Tile(..) => stats.tiles_written += 1,+ Object::Blob(_) => stats.blobs_written += 1,+ }+ write_atomic(&dir.join(path), &obj.compressed())?;+ }+ for (name, data) in &p.previews {+ write_atomic(&dir.join(name), data)?;+ }+ for stale in [THUMB, COMPOSITE] {+ if !p.previews.iter().any(|(n, _)| *n == stale) {+ let _ = std::fs::remove_file(dir.join(stale));+ }+ }+ write_atomic(&dir.join(MANIFEST), &p.manifest)?;+ for path in existing {+ if !p.objects.contains_key(&path) {+ std::fs::remove_file(dir.join(&path))?;+ stats.objects_removed += 1;+ }+ }+ Ok(stats)+ }++ /// Save to `path`: a directory bundle if `path` is an existing directory+ /// or ends with a path separator, otherwise a ZIP file (written atomically).+ pub fn save_path(+ &mut self,+ doc: &Document,+ path: &Path,+ opts: &SaveOptions,+ ) -> Result<SaveStats> {+ let s = path.to_string_lossy();+ if path.is_dir() || s.ends_with('/') || s.ends_with('\\') {+ self.save_dir(doc, path, opts)+ } else {+ let (bytes, stats) = self.save_zip(doc, opts)?;+ write_atomic(path, &bytes)?;+ Ok(stats)+ }+ }+}++fn list_objects(dir: &Path) -> Result<HashSet<String>> {+ let mut out = HashSet::new();+ for sub in ["tiles", "blobs"] {+ let Ok(rd) = std::fs::read_dir(dir.join(sub)) else {+ continue;+ };+ for e in rd.flatten() {+ let name = e.file_name().to_string_lossy().into_owned();+ if name.ends_with(".zst") {+ out.insert(format!("{sub}/{name}"));+ }+ }+ }+ Ok(out)+}++pub(crate) fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ let tmp = path.with_extension(format!(+ "{}tmp",+ path.extension()+ .map(|e| format!("{}.", e.to_string_lossy()))+ .unwrap_or_default()+ ));+ std::fs::write(&tmp, data)?;+ std::fs::rename(&tmp, path)?;+ Ok(())+}diff --git a/crates/format/src/zip.rs b/crates/format/src/zip.rsnew file mode 100644index 000000000..4f7de6752--- /dev/null+++ b/crates/format/src/zip.rs@@ -0,0 +1,311 @@+//! Minimal ZIP container: we write STORE entries (the payloads are already+//! zstd-compressed) and read STORE or DEFLATE entries (so a bundle that was+//! unzipped and re-zipped by another tool still loads). No ZIP64, no+//! encryption, no multi-disk archives.++use std::io::Read;++use crate::FormatError;++const LOCAL_SIG: u32 = 0x0403_4b50;+const CENTRAL_SIG: u32 = 0x0201_4b50;+const EOCD_SIG: u32 = 0x0605_4b50;++/// CRC-32 (IEEE), table-driven.+pub fn crc32(data: &[u8]) -> u32 {+ static TABLE: std::sync::OnceLock<[u32; 256]> = std::sync::OnceLock::new();+ let t = TABLE.get_or_init(|| {+ let mut t = [0u32; 256];+ for (i, e) in t.iter_mut().enumerate() {+ let mut c = i as u32;+ for _ in 0..8 {+ c = if c & 1 != 0 {+ 0xEDB8_8320 ^ (c >> 1)+ } else {+ c >> 1+ };+ }+ *e = c;+ }+ t+ });+ let mut c = 0xFFFF_FFFFu32;+ for &b in data {+ c = t[((c ^ b as u32) & 0xFF) as usize] ^ (c >> 8);+ }+ !c+}++/// Streaming writer for STORE entries.+pub struct ZipWriter {+ out: Vec<u8>,+ central: Vec<u8>,+ count: u16,+}++impl Default for ZipWriter {+ fn default() -> Self {+ Self::new()+ }+}++impl ZipWriter {+ pub fn new() -> Self {+ ZipWriter {+ out: Vec::new(),+ central: Vec::new(),+ count: 0,+ }+ }++ pub fn add(&mut self, name: &str, data: &[u8]) -> Result<(), FormatError> {+ if self.count == u16::MAX {+ return Err(FormatError::Unsupported(+ "more than 65535 zip entries (ZIP64 not supported)".into(),+ ));+ }+ let size = u32::try_from(data.len())+ .map_err(|_| FormatError::Unsupported("zip entry over 4 GiB".into()))?;+ let offset = u32::try_from(self.out.len())+ .map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?;+ let crc = crc32(data);+ let name_b = name.as_bytes();+ // Local file header.+ let o = &mut self.out;+ o.extend_from_slice(&LOCAL_SIG.to_le_bytes());+ o.extend_from_slice(&20u16.to_le_bytes()); // version needed+ o.extend_from_slice(&0x0800u16.to_le_bytes()); // flags: UTF-8 names+ o.extend_from_slice(&0u16.to_le_bytes()); // method: store+ o.extend_from_slice(&0u16.to_le_bytes()); // time+ o.extend_from_slice(&0x21u16.to_le_bytes()); // date: 1980-01-01+ o.extend_from_slice(&crc.to_le_bytes());+ o.extend_from_slice(&size.to_le_bytes());+ o.extend_from_slice(&size.to_le_bytes());+ o.extend_from_slice(&(name_b.len() as u16).to_le_bytes());+ o.extend_from_slice(&0u16.to_le_bytes());+ o.extend_from_slice(name_b);+ o.extend_from_slice(data);+ // Central directory entry.+ let c = &mut self.central;+ c.extend_from_slice(&CENTRAL_SIG.to_le_bytes());+ c.extend_from_slice(&20u16.to_le_bytes()); // made by+ c.extend_from_slice(&20u16.to_le_bytes()); // needed+ c.extend_from_slice(&0x0800u16.to_le_bytes());+ c.extend_from_slice(&0u16.to_le_bytes());+ c.extend_from_slice(&0u16.to_le_bytes());+ c.extend_from_slice(&0x21u16.to_le_bytes());+ c.extend_from_slice(&crc.to_le_bytes());+ c.extend_from_slice(&size.to_le_bytes());+ c.extend_from_slice(&size.to_le_bytes());+ c.extend_from_slice(&(name_b.len() as u16).to_le_bytes());+ c.extend_from_slice(&[0; 8]); // extra len, comment len, disk, internal attrs+ c.extend_from_slice(&0u32.to_le_bytes()); // external attrs+ c.extend_from_slice(&offset.to_le_bytes());+ c.extend_from_slice(name_b);+ self.count += 1;+ Ok(())+ }++ pub fn finish(mut self) -> Result<Vec<u8>, FormatError> {+ let cd_offset = u32::try_from(self.out.len())+ .map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?;+ let cd_size = self.central.len() as u32;+ self.out.extend_from_slice(&self.central);+ self.out.extend_from_slice(&EOCD_SIG.to_le_bytes());+ self.out.extend_from_slice(&[0; 4]); // disk numbers+ self.out.extend_from_slice(&self.count.to_le_bytes());+ self.out.extend_from_slice(&self.count.to_le_bytes());+ self.out.extend_from_slice(&cd_size.to_le_bytes());+ self.out.extend_from_slice(&cd_offset.to_le_bytes());+ self.out.extend_from_slice(&0u16.to_le_bytes());+ Ok(self.out)+ }+}++#[derive(Debug, Clone)]+pub struct Entry {+ pub name: String,+ method: u16,+ crc: u32,+ compressed: usize,+ uncompressed: usize,+ data_offset: usize,+}++/// Read-only view of an archive in memory.+pub struct ZipReader<'a> {+ bytes: &'a [u8],+ pub entries: Vec<Entry>,+}++fn u16_at(b: &[u8], o: usize) -> Result<u16, FormatError> {+ b.get(o..o + 2)+ .map(|s| u16::from_le_bytes([s[0], s[1]]))+ .ok_or_else(|| FormatError::corrupt("truncated zip"))+}+fn u32_at(b: &[u8], o: usize) -> Result<u32, FormatError> {+ b.get(o..o + 4)+ .map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))+ .ok_or_else(|| FormatError::corrupt("truncated zip"))+}++impl<'a> ZipReader<'a> {+ pub fn new(bytes: &'a [u8]) -> Result<Self, FormatError> {+ if bytes.len() < 22 {+ return Err(FormatError::corrupt("not a zip archive (too short)"));+ }+ // End of central directory: scan back over a possible comment.+ let min = bytes.len().saturating_sub(22 + 65535);+ let eocd = (min..=bytes.len() - 22)+ .rev()+ .find(|&i| u32_at(bytes, i).ok() == Some(EOCD_SIG))+ .ok_or_else(|| FormatError::corrupt("zip end-of-central-directory not found"))?;+ let count = u16_at(bytes, eocd + 10)? as usize;+ let cd_size = u32_at(bytes, eocd + 12)? as usize;+ let cd_off = u32_at(bytes, eocd + 16)? as usize;+ if cd_off.checked_add(cd_size).is_none_or(|e| e > eocd) {+ return Err(FormatError::corrupt("zip central directory out of range"));+ }+ let mut entries = Vec::with_capacity(count.min(bytes.len() / 46));+ let mut p = cd_off;+ for _ in 0..count {+ if u32_at(bytes, p)? != CENTRAL_SIG {+ return Err(FormatError::corrupt("bad zip central directory entry"));+ }+ let flags = u16_at(bytes, p + 8)?;+ let method = u16_at(bytes, p + 10)?;+ let crc = u32_at(bytes, p + 16)?;+ let compressed = u32_at(bytes, p + 20)? as usize;+ let uncompressed = u32_at(bytes, p + 24)? as usize;+ let nlen = u16_at(bytes, p + 28)? as usize;+ let elen = u16_at(bytes, p + 30)? as usize;+ let clen = u16_at(bytes, p + 32)? as usize;+ let local = u32_at(bytes, p + 42)? as usize;+ let name = bytes+ .get(p + 46..p + 46 + nlen)+ .ok_or_else(|| FormatError::corrupt("truncated zip name"))?;+ let name = String::from_utf8_lossy(name).into_owned();+ if flags & 1 != 0 {+ return Err(FormatError::Unsupported("encrypted zip entries".into()));+ }+ // Local header gives the real data offset.+ if u32_at(bytes, local)? != LOCAL_SIG {+ return Err(FormatError::corrupt("bad zip local header"));+ }+ let lnlen = u16_at(bytes, local + 26)? as usize;+ let lelen = u16_at(bytes, local + 28)? as usize;+ let data_offset = local + 30 + lnlen + lelen;+ if data_offset+ .checked_add(compressed)+ .is_none_or(|e| e > bytes.len())+ {+ return Err(FormatError::corrupt(format!(+ "zip entry `{name}` out of range"+ )));+ }+ entries.push(Entry {+ name,+ method,+ crc,+ compressed,+ uncompressed,+ data_offset,+ });+ p += 46 + nlen + elen + clen;+ }+ Ok(ZipReader { bytes, entries })+ }++ pub fn find(&self, name: &str) -> Option<&Entry> {+ self.entries.iter().find(|e| e.name == name)+ }++ /// Entry payload (decompressed), at most `max` bytes, CRC-checked.+ pub fn read(&self, e: &Entry, max: usize) -> Result<Vec<u8>, FormatError> {+ if e.uncompressed > max {+ return Err(FormatError::LimitExceeded(format!(+ "zip entry `{}` is {} bytes (max {max})",+ e.name, e.uncompressed+ )));+ }+ let raw = &self.bytes[e.data_offset..e.data_offset + e.compressed];+ let data = match e.method {+ 0 => raw.to_vec(),+ 8 => {+ let mut out = Vec::with_capacity(e.uncompressed);+ flate2::read::DeflateDecoder::new(raw)+ .take(max as u64 + 1)+ .read_to_end(&mut out)+ .map_err(|err| {+ FormatError::corrupt(format!("zip entry `{}`: {err}", e.name))+ })?;+ out+ }+ m => {+ return Err(FormatError::Unsupported(format!(+ "zip compression method {m} for `{}`",+ e.name+ )));+ }+ };+ if data.len() != e.uncompressed || data.len() > max {+ return Err(FormatError::corrupt(format!(+ "zip entry `{}` has wrong size",+ e.name+ )));+ }+ if crc32(&data) != e.crc {+ return Err(FormatError::corrupt(format!(+ "zip entry `{}` failed its CRC check",+ e.name+ )));+ }+ Ok(data)+ }++ pub fn read_by_name(&self, name: &str, max: usize) -> Result<Vec<u8>, FormatError> {+ let e = self+ .find(name)+ .ok_or_else(|| FormatError::corrupt(format!("missing `{name}`")))?;+ self.read(e, max)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn crc_known_value() {+ assert_eq!(crc32(b"123456789"), 0xCBF4_3926);+ }++ #[test]+ fn roundtrip() {+ let mut w = ZipWriter::new();+ w.add("a.txt", b"hello").unwrap();+ w.add("dir/b.bin", &[0, 1, 2, 3]).unwrap();+ w.add("empty", &[]).unwrap();+ let bytes = w.finish().unwrap();+ let r = ZipReader::new(&bytes).unwrap();+ assert_eq!(r.entries.len(), 3);+ assert_eq!(r.read_by_name("a.txt", 100).unwrap(), b"hello");+ assert_eq!(r.read_by_name("dir/b.bin", 100).unwrap(), [0, 1, 2, 3]);+ assert!(r.read_by_name("empty", 0).unwrap().is_empty());+ assert!(matches!(+ r.read_by_name("a.txt", 3),+ Err(FormatError::LimitExceeded(_))+ ));+ }++ #[test]+ fn crc_mismatch_detected() {+ let mut w = ZipWriter::new();+ w.add("a", b"hello").unwrap();+ let mut bytes = w.finish().unwrap();+ let pos = bytes.windows(5).position(|x| x == b"hello").unwrap();+ bytes[pos] = b'j';+ let r = ZipReader::new(&bytes).unwrap();+ assert!(r.read_by_name("a", 100).is_err());+ }+}diff --git a/crates/format/tests/autosave.rs b/crates/format/tests/autosave.rsnew file mode 100644index 000000000..be6d8f40b--- /dev/null+++ b/crates/format/tests/autosave.rs@@ -0,0 +1,95 @@+//! Background autosave and crash recovery.++mod common;+use std::sync::Arc;++use common::*;+use photocraft_color::{ColorMode, SampleType};+use photocraft_format::*;++#[test]+fn autosave_then_recover() {+ let dir = temp_dir("recovery");+ let doc = Arc::new(rich_doc(ColorMode::Rgb, SampleType::U16));+ let saver = Autosaver::new(&dir, "doc-1");+ saver.request(+ doc.clone(),+ 7,+ Some("/work/a.pcraft".into()),+ SaveOptions::default(),+ );+ let r = saver.flush().expect("a save ran");+ let stats = r.unwrap();+ assert!(stats.tiles_written > 0);+ let entries = list_recovery(&dir);+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].info.revision, 7);+ assert_eq!(+ entries[0].info.original_path.as_deref(),+ Some("/work/a.pcraft")+ );+ assert_eq!(entries[0].info.document_name, "Rich");+ assert_eq!(recover(&entries[0]).unwrap(), *doc);+ discard_recovery(&dir, &entries[0]).unwrap();+ assert!(list_recovery(&dir).is_empty());+ std::fs::remove_dir_all(dir).unwrap();+}++#[test]+fn repeated_autosaves_are_incremental_and_coalesced() {+ let dir = temp_dir("coalesce");+ let saver = Autosaver::new(&dir, "k");+ let mut doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ for i in 0..5 {+ let id = doc.layers[1].id;+ doc.layer_mut(id)+ .unwrap()+ .surface_mut()+ .unwrap()+ .write_pixel(i, 0, &[1.0, 0.0, 0.0, 1.0]);+ saver.request(+ Arc::new(doc.clone()),+ i as u64,+ None,+ SaveOptions::default(),+ );+ }+ saver.flush().unwrap().unwrap();+ let e = list_recovery(&dir);+ assert_eq!(e[0].info.revision, 4, "newest snapshot wins");+ assert_eq!(recover(&e[0]).unwrap(), doc);+ std::fs::remove_dir_all(dir).unwrap();+}++#[test]+fn discard_removes_everything() {+ let dir = temp_dir("discard");+ let saver = Autosaver::new(&dir, "x y/z");+ saver.request(+ Arc::new(rich_doc(ColorMode::Grayscale, SampleType::U8)),+ 1,+ None,+ SaveOptions::default(),+ );+ let path = saver.bundle_path();+ assert!(+ path.file_name()+ .unwrap()+ .to_string_lossy()+ .starts_with("x_y_z")+ );+ saver.discard().unwrap();+ assert!(list_recovery(&dir).is_empty());+ assert!(!path.exists());+ std::fs::remove_dir_all(dir).unwrap();+}++#[test]+fn list_ignores_junk() {+ let dir = temp_dir("junk");+ std::fs::write(dir.join("bogus.json"), b"{}").unwrap();+ std::fs::write(dir.join("other.txt"), b"x").unwrap();+ assert!(list_recovery(&dir).is_empty());+ assert!(list_recovery(&dir.join("missing")).is_empty());+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/crates/format/tests/common/mod.rs b/crates/format/tests/common/mod.rsnew file mode 100644index 000000000..d1d2aaee0--- /dev/null+++ b/crates/format/tests/common/mod.rs@@ -0,0 +1,297 @@+//! Synthetic documents exercising every part of the model.+#![allow(dead_code)]++use std::sync::Arc;++use photocraft_color::{BlendMode, Color, ColorMode, SampleType};+use photocraft_doc::text::{CharStyle, ParagraphRun, ParagraphStyle, TextRun, TextShape, TextWarp};+use photocraft_doc::*;+use serde_json::json;++pub struct Rng(u64);+impl Rng {+ pub fn new(s: u64) -> Self {+ Rng(s)+ }+ pub fn next(&mut self) -> u64 {+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);+ let mut z = self.0;+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+ }+ pub fn f(&mut self) -> f32 {+ (self.next() >> 40) as f32 / (1u64 << 24) as f32+ }+}++/// Scribble deterministic pixels into a surface, including negative+/// coordinates and far-away tiles. Float surfaces get HDR values.+pub fn scribble(s: &mut Surface, seed: u64, hdr: bool) {+ let mut r = Rng::new(seed);+ let ch = s.channels();+ for &(x0, y0) in &[(-12, -7), (0, 0), (250, 250), (600, 30)] {+ for dy in 0..9 {+ for dx in 0..11 {+ let px: Vec<f32> = (0..ch)+ .map(|_| if hdr { r.f() * 4.0 - 1.0 } else { r.f() })+ .collect();+ s.write_pixel(x0 + dx, y0 + dy, &px);+ }+ }+ }+}++pub fn blob(seed: u8, n: usize) -> Arc<Vec<u8>> {+ Arc::new(+ (0..n)+ .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))+ .collect(),+ )+}++pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {+ let hdr = depth == SampleType::F32;+ let mut d = Document::with_background("Rich", Size::new(300, 280), mode, depth, Color::WHITE);+ d.resolution_dpi = 300.0;+ d.icc_profile = Some(blob(1, 500));+ let pf = d.pixel_format();++ let mut paint = Layer::raster("Paint", pf);+ scribble(paint.surface_mut().unwrap(), 1, hdr);+ paint.blend = BlendMode::Multiply;+ paint.opacity = 0.75;+ paint.fill_opacity = 0.5;+ paint.clipped = true;+ paint.label = LabelColor::Violet;+ paint.locks.pixels = true;+ let mut mask = LayerMask::hide_all();+ scribble(&mut mask.surface, 2, false);+ mask.density = 0.8;+ mask.feather = 3.5;+ mask.linked = false;+ paint.mask = Some(mask);+ paint.effects.items.push(Effect::ColorOverlay {+ common: FxCommon::new(BlendMode::Normal, 0.8),+ color: Color::rgb(1.0, 0.2, 0.1),+ });+ paint.effects.items.push(Effect::GradientOverlay {+ common: FxCommon::new(BlendMode::Normal, 0.8),+ gradient: Gradient::default(),+ dither: true,+ });+ paint.effects.psd_raw = Some(blob(3, 64));+ paint.psd_blocks.push((*b"vmsk", blob(4, 40)));+ paint.psd_blocks.push((*b"lnsr", blob(5, 4)));+ paint.psd_id = Some(42);++ let mut inner = Layer::raster("Inner", pf);+ scribble(inner.surface_mut().unwrap(), 6, hdr);+ let nested = Layer::group("Nested", vec![inner]);+ let mut adj = Layer::new(+ "Hue/Sat",+ LayerContent::Adjustment(Adjustment::HueSaturation {+ hue: 30.0,+ saturation: -10.0,+ lightness: 5.0,+ colorize: false,+ }),+ );+ adj.visible = false;+ let mut group = Layer::group("Group", vec![nested, adj]);+ if let LayerContent::Group(g) = &mut group.content {+ g.expanded = false;+ }++ let mut fill = Layer::new(+ "Fill",+ LayerContent::Fill(Fill::Solid(Color::rgba(0.1, 0.2, 0.3, 0.9))),+ );+ let mut fc = Surface::new(pf);+ scribble(&mut fc, 7, false);+ fill.fill_cache = Some(FillCache {+ fill: Fill::Solid(Color::rgba(0.1, 0.2, 0.3, 0.9)),+ surface: fc,+ });+ let grad = Layer::new(+ "Gradient",+ LayerContent::Fill(Fill::Gradient {+ stops: vec![(0.0, Color::BLACK), (1.0, Color::WHITE)],+ angle: 45.0,+ scale: 1.5,+ style: GradientStyle::default(),+ reverse: true,+ }),+ );++ let mut cache = Surface::new(pf);+ scribble(&mut cache, 8, false);+ let text = Layer::new(+ "Type",+ LayerContent::Text(TextLayer {+ text: "Hello ✓ world".into(),+ font_family: "Inter".into(),+ size_pt: 24.0,+ color: Color::rgb(0.2, 0.4, 0.6),+ transform: Affine::translate(10.5, 20.25),+ cache: Some(cache.clone()),+ psd_raw: Some(blob(9, 100)),+ runs: vec![+ TextRun {+ len: 6,+ style: CharStyle::default(),+ },+ TextRun {+ len: 9,+ style: CharStyle::default(),+ },+ ],+ paragraphs: vec![ParagraphRun {+ len: 15,+ style: ParagraphStyle::default(),+ }],+ shape: TextShape::Box {+ x: 1.0,+ y: 2.0,+ width: 100.0,+ height: 50.0,+ },+ orientation: text::Orientation::Vertical,+ antialias: text::AntiAlias::Crisp,+ warp: Some(TextWarp {+ style: "warpArc".into(),+ value: 25.0,+ ..Default::default()+ }),+ }),+ );+ let mut shape = Layer::new(+ "Shape",+ LayerContent::Shape(ShapeLayer {+ path: vector_path(),+ fill: Some(Fill::Solid(Color::BLACK)),+ stroke: Some(ShapeStroke {+ width: 2.5,+ paint: Fill::Solid(Color::rgb(0.0, 0.5, 1.0)),+ opacity: 0.75,+ align: StrokeAlign::Outside,+ cap: LineCap::Round,+ join: LineJoin::Bevel,+ miter_limit: 4.0,+ dashes: vec![2.0, 1.0],+ dash_offset: 0.5,+ }),+ live: Some(LiveShape::Rect { rect: [1.0, 2.0, 30.0, 40.0], radii: [4.0, 0.0, 4.0, 0.0] }),+ cache: Some(cache.clone()),+ psd_raw: Some(blob(10, 30)),+ }),+ );+ shape.label = LabelColor::Green;+ let mut vm = VectorMask::new(vector_path());+ vm.enabled = false;+ vm.density = 0.4;+ vm.feather = 3.0;+ vm.path.inverted = true;+ paint.vector_mask = Some(vm);+ let smart = Layer::new(+ "Smart",+ LayerContent::Smart(SmartObject {+ source: SmartSource::Embedded {+ file_name: "inner.png".into(),+ bytes: blob(11, 2000),+ },+ transform: Affine::scale(0.5),+ smart_filters: vec![SmartFilter {+ command: "filter.blur.gaussian".into(),+ params: json!({"radius": 2.5, "nested": {"a": [1, 2, 3]}}),+ blend: BlendMode::Screen,+ opacity: 0.6,+ visible: true,+ }],+ cache: Some(cache),+ psd_raw: None,+ }),+ );+ let linked = Layer::new(+ "Linked",+ LayerContent::Smart(SmartObject {+ source: SmartSource::Linked {+ path: "/tmp/linked.psd".into(),+ },+ transform: Affine::IDENTITY,+ smart_filters: vec![],+ cache: None,+ psd_raw: Some(blob(12, 8)),+ }),+ );+ d.layers+ .extend([paint, group, fill, grad, text, shape, smart, linked]);++ let mut ch = Surface::new(PixelFormat::GRAY8.with_sample(depth));+ scribble(&mut ch, 13, false);+ d.channels.push(AlphaChannel {+ name: "Alpha 1".into(),+ surface: ch.clone(),+ spot: None,+ });+ d.channels.push(AlphaChannel {+ name: "Spot".into(),+ surface: ch,+ spot: Some((Color::rgb(1.0, 0.0, 0.5), 0.7)),+ });+ d.guides = Guides {+ horizontal: vec![10.0, 20.5],+ vertical: vec![100.25],+ };+ let mut sel = Surface::new(PixelFormat::GRAY8);+ scribble(&mut sel, 14, false);+ d.selection = Some(sel);+ d.metadata.xmp = Some("<x:xmpmeta/>".into());+ d.metadata.exif = Some(blob(15, 64));+ d.metadata+ .psd_resources+ .push((1036, "thumb".into(), blob(16, 20)));+ d.metadata+ .psd_global_blocks+ .push((*b"8BIM", *b"Patt", blob(17, 50)));+ d.global_light = GlobalLight {+ angle: 120.0,+ altitude: 30.0,+ };+ d.paths.push(NamedPath { name: "Path 1".into(), path: vector_path(), psd_raw: Some(blob(18, 52)) });+ d.paths.push(NamedPath { name: "Empty".into(), path: Path::default(), psd_raw: None });+ let mut wp = vector_path();+ wp.fill_rule = FillRule::EvenOdd;+ d.work_path = Some(wp);+ d.clipping_path = Some(ClippingPath { name: "Path 1".into(), flatness: 2.0 });+ d+}++/// A path using every knot kind and path operation.+pub fn vector_path() -> Path {+ Path::new(vec![+ Subpath {+ closed: true,+ op: PathOp::Combine,+ knots: vec![+ Knot::corner(1.5, 2.25),+ Knot::smooth(photocraft_geom::Point::new(40.0, 5.0), photocraft_geom::Point::new(30.0, 0.0), photocraft_geom::Point::new(50.0, 10.0)),+ Knot::corner(10.0, 60.0),+ ],+ },+ Subpath::polygon(&[(5.0, 5.0), (9.0, 5.0), (9.0, 9.0)]).with_op(PathOp::Subtract),+ Subpath::polyline(&[(0.0, 0.0), (3.0, 4.0)]).with_op(PathOp::Exclude),+ Subpath::polygon(&[(0.0, 0.0), (3.0, 4.0), (3.0, 0.0)]).with_op(PathOp::Intersect),+ ])+}++/// A fresh, empty directory under the system temp dir, unique per test process and call.+pub fn temp_dir(tag: &str) -> std::path::PathBuf {+ use std::sync::atomic::{AtomicU32, Ordering};+ static N: AtomicU32 = AtomicU32::new(0);+ let n = N.fetch_add(1, Ordering::Relaxed);+ let dir = std::env::temp_dir().join(format!("photocraft-format-{tag}-{}-{n}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).expect("create temp dir");+ dir+}diff --git a/crates/format/tests/corruption.rs b/crates/format/tests/corruption.rsnew file mode 100644index 000000000..c8aa23152--- /dev/null+++ b/crates/format/tests/corruption.rs@@ -0,0 +1,255 @@+//! Damaged or hostile bundles must fail cleanly, never panic.++mod common;+use common::*;+use photocraft_color::{ColorMode, SampleType};+use photocraft_format::*;+use proptest::prelude::*;++fn sample() -> Vec<u8> {+ save_to_bytes(+ &rich_doc(ColorMode::Rgb, SampleType::U8),+ &SaveOptions::default(),+ )+ .unwrap()+}++fn rebuild(bytes: &[u8], f: impl Fn(&str, Vec<u8>) -> Option<Vec<u8>>) -> Vec<u8> {+ let r = zip::ZipReader::new(bytes).unwrap();+ let mut z = zip::ZipWriter::new();+ for e in &r.entries {+ if let Some(d) = f(&e.name, r.read(e, usize::MAX).unwrap()) {+ z.add(&e.name, &d).unwrap();+ }+ }+ z.finish().unwrap()+}++#[test]+fn truncation_never_panics_and_fails() {+ let b = sample();+ let step = (b.len() / 200).max(1);+ for cut in (0..b.len()).step_by(step) {+ assert!(load_from_bytes(&b[..cut]).is_err(), "cut at {cut}");+ }+}++#[test]+fn byte_flips_detected() {+ let b = sample();+ let mut rng = common::Rng::new(9);+ let mut failures = 0;+ for _ in 0..300 {+ let mut c = b.clone();+ let i = (rng.next() as usize) % c.len();+ c[i] ^= 0x20;+ if load_from_bytes(&c).is_err() {+ failures += 1;+ }+ }+ // Some flips hit unused header fields; most must be caught (CRC + hashes).+ assert!(failures > 200, "{failures}");+}++#[test]+fn missing_tile_is_error() {+ let b = rebuild(&sample(), |n, d| (!n.starts_with("tiles/")).then_some(d));+ assert!(matches!(load_from_bytes(&b), Err(FormatError::Corrupt(_))));+}++#[test]+fn missing_manifest_is_error() {+ let b = rebuild(&sample(), |n, d| (n != "manifest.json").then_some(d));+ assert!(load_from_bytes(&b).is_err());+}++#[test]+fn swapped_tile_content_fails_hash_check() {+ let b = sample();+ let r = zip::ZipReader::new(&b).unwrap();+ let tiles: Vec<_> = r+ .entries+ .iter()+ .filter(|e| e.name.starts_with("tiles/"))+ .map(|e| e.name.clone())+ .collect();+ let other = r.read_by_name(&tiles[1], usize::MAX).unwrap();+ let first = tiles[0].clone();+ let b2 = rebuild(&b, |n, d| Some(if n == first { other.clone() } else { d }));+ let e = load_from_bytes(&b2).unwrap_err();+ assert!(e.to_string().contains("hash"), "{e}");+}++#[test]+fn bad_manifest_json() {+ let b = rebuild(&sample(), |n, d| {+ Some(if n == "manifest.json" {+ b"{not json".to_vec()+ } else {+ d+ })+ });+ assert!(matches!(load_from_bytes(&b), Err(FormatError::Json(_))));+}++#[test]+fn too_new_version_rejected() {+ let b = rebuild(&sample(), |n, d| {+ Some(if n == "manifest.json" {+ let mut v: serde_json::Value = serde_json::from_slice(&d).unwrap();+ v["format_version"] = 999.into();+ serde_json::to_vec(&v).unwrap()+ } else {+ d+ })+ });+ assert!(matches!(+ load_from_bytes(&b),+ Err(FormatError::TooNew { found: 999, .. })+ ));+}++#[test]+fn invalid_hash_strings_rejected() {+ let b = rebuild(&sample(), |n, d| {+ Some(if n == "manifest.json" {+ let s = String::from_utf8(d).unwrap();+ let i = s.find("\"hash\": \"").unwrap() + 9;+ let mut s = s.into_bytes();+ s[i] = b'/';+ s+ } else {+ d+ })+ });+ assert!(load_from_bytes(&b).is_err());+}++#[test]+fn manifest_size_limit() {+ let b = sample();+ let opts = LoadOptions {+ max_manifest_bytes: 100,+ ..Default::default()+ };+ assert!(matches!(+ load_from_bytes_with(&b, &opts),+ Err(FormatError::LimitExceeded(_))+ ));+}++#[test]+fn total_size_limit() {+ let b = sample();+ let opts = LoadOptions {+ max_total_bytes: 1000,+ ..Default::default()+ };+ assert!(matches!(+ load_from_bytes_with(&b, &opts),+ Err(FormatError::LimitExceeded(_))+ ));+}++#[test]+fn directory_bundle_tampered_tile() {+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ let dir = temp_dir("tamper");+ PcraftWriter::new()+ .save_dir(&doc, &dir, &SaveOptions::default())+ .unwrap();+ let tile = std::fs::read_dir(dir.join("tiles"))+ .unwrap()+ .next()+ .unwrap()+ .unwrap()+ .path();+ std::fs::write(&tile, b"garbage").unwrap();+ assert!(load_path(&dir).is_err());+ std::fs::remove_dir_all(dir).unwrap();+}++#[test]+fn deflated_zip_entries_are_readable() {+ // Re-zip with DEFLATE (as a user's zip tool might) — must still load.+ use std::io::Write;+ let b = sample();+ let r = zip::ZipReader::new(&b).unwrap();+ let mut out = Vec::new();+ let mut central = Vec::new();+ for e in &r.entries {+ let data = r.read(e, usize::MAX).unwrap();+ let mut enc =+ flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());+ enc.write_all(&data).unwrap();+ let comp = enc.finish().unwrap();+ let crc = zip::crc32(&data);+ let off = out.len() as u32;+ let name = e.name.as_bytes();+ out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());+ out.extend_from_slice(&[20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]);+ out.extend_from_slice(&crc.to_le_bytes());+ out.extend_from_slice(&(comp.len() as u32).to_le_bytes());+ out.extend_from_slice(&(data.len() as u32).to_le_bytes());+ out.extend_from_slice(&(name.len() as u16).to_le_bytes());+ out.extend_from_slice(&[0, 0]);+ out.extend_from_slice(name);+ out.extend_from_slice(&comp);+ central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());+ central.extend_from_slice(&[20, 0, 20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]);+ central.extend_from_slice(&crc.to_le_bytes());+ central.extend_from_slice(&(comp.len() as u32).to_le_bytes());+ central.extend_from_slice(&(data.len() as u32).to_le_bytes());+ central.extend_from_slice(&(name.len() as u16).to_le_bytes());+ central.extend_from_slice(&[0; 12]);+ central.extend_from_slice(&off.to_le_bytes());+ central.extend_from_slice(name);+ }+ let cd_off = out.len() as u32;+ let n = r.entries.len() as u16;+ out.extend_from_slice(¢ral);+ out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());+ out.extend_from_slice(&[0; 4]);+ out.extend_from_slice(&n.to_le_bytes());+ out.extend_from_slice(&n.to_le_bytes());+ out.extend_from_slice(&(central.len() as u32).to_le_bytes());+ out.extend_from_slice(&cd_off.to_le_bytes());+ out.extend_from_slice(&[0, 0]);+ assert_eq!(load_from_bytes(&out).unwrap(), rich_doc_ids_from(&b));+}++fn rich_doc_ids_from(b: &[u8]) -> photocraft_doc::Document {+ load_from_bytes(b).unwrap()+}++proptest! {+ #![proptest_config(ProptestConfig { cases: 300, .. ProptestConfig::default() })]++ #[test]+ fn random_bytes_never_panic(data in proptest::collection::vec(any::<u8>(), 0..4096)) {+ let _ = load_from_bytes(&data);+ let _ = read_manifest(&data);+ }++ #[test]+ fn random_manifest_never_panics(json in "\\PC{0,300}") {+ let mut z = zip::ZipWriter::new();+ z.add("manifest.json", json.as_bytes()).unwrap();+ let _ = load_from_bytes(&z.finish().unwrap());+ }++ #[test]+ fn random_tile_payload_never_panics(data in proptest::collection::vec(any::<u8>(), 0..512), which in 0usize..8) {+ let b = sample_cached();+ let r = zip::ZipReader::new(b).unwrap();+ let tiles: Vec<String> = r.entries.iter().filter(|e| e.name.starts_with("tiles/")).map(|e| e.name.clone()).collect();+ let target = tiles[which % tiles.len()].clone();+ let b2 = rebuild(b, |n, d| Some(if n == target { data.clone() } else { d }));+ prop_assert!(load_from_bytes(&b2).is_err());+ }+}++fn sample_cached() -> &'static [u8] {+ static S: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();+ S.get_or_init(sample)+}diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/roundtrip.rsnew file mode 100644index 000000000..16f3cbe5f--- /dev/null+++ b/crates/format/tests/roundtrip.rs@@ -0,0 +1,287 @@+//! doc → .pcraft → doc equality, incremental saves, ids, previews.++mod common;+use common::*;+use photocraft_color::{ColorMode, SampleType};+use photocraft_doc::{Document, Layer, LayerId};+use photocraft_format::*;+use photocraft_raster::Rgba8Image;++const MODES: [ColorMode; 4] = [+ ColorMode::Rgb,+ ColorMode::Grayscale,+ ColorMode::Cmyk,+ ColorMode::Lab,+];++fn check_zip(mode: ColorMode, depth: SampleType) {+ let doc = rich_doc(mode, depth);+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();+ assert!(is_pcraft(&bytes));+ let back = load_from_bytes(&bytes).unwrap();+ assert_eq!(back, doc, "{mode:?} {depth:?}");+}++macro_rules! zip_cases {+ ($($name:ident: $m:ident, $d:ident;)*) => {$(+ #[test]+ fn $name() {+ check_zip(ColorMode::$m, SampleType::$d);+ }+ )*};+}++zip_cases! {+ rgb_u8: Rgb, U8; rgb_u16: Rgb, U16; rgb_f32: Rgb, F32;+ gray_u8: Grayscale, U8; gray_u16: Grayscale, U16; gray_f32: Grayscale, F32;+ cmyk_u8: Cmyk, U8; cmyk_u16: Cmyk, U16; cmyk_f32: Cmyk, F32;+ lab_u8: Lab, U8; lab_u16: Lab, U16; lab_f32: Lab, F32;+}++#[test]+fn directory_bundle_roundtrip_all_modes() {+ for mode in MODES {+ for depth in SampleType::ALL {+ let doc = rich_doc(mode, depth);+ let dir = temp_dir("dir");+ PcraftWriter::new()+ .save_dir(&doc, &dir, &SaveOptions::default())+ .unwrap();+ assert!(dir.join("manifest.json").is_file());+ assert_eq!(load_path(&dir).unwrap(), doc, "{mode:?} {depth:?}");+ std::fs::remove_dir_all(dir).unwrap();+ }+ }+}++#[test]+fn save_path_zip_file() {+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ let dir = temp_dir("file");+ let path = dir.join("a.pcraft");+ PcraftWriter::new()+ .save_path(&doc, &path, &SaveOptions::default())+ .unwrap();+ assert!(path.is_file());+ assert_eq!(load_path(&path).unwrap(), doc);+ std::fs::remove_dir_all(dir).unwrap();+}++#[test]+fn empty_document_roundtrips() {+ let doc = Document::new(+ "empty",+ photocraft_doc::Size::new(1, 1),+ ColorMode::Rgb,+ SampleType::U8,+ );+ assert_eq!(+ load_from_bytes(&save_to_bytes(&doc, &SaveOptions::default()).unwrap()).unwrap(),+ doc+ );+}++#[test]+fn zip_incremental_only_new_tiles() {+ let mut doc = rich_doc(ColorMode::Rgb, SampleType::U16);+ let mut w = PcraftWriter::new();+ let (_, s1) = w.save_zip(&doc, &SaveOptions::default()).unwrap();+ assert!(s1.tiles_total > 5);+ assert_eq!(s1.tiles_written, s1.tiles_total);+ let (_, s2) = w.save_zip(&doc, &SaveOptions::default()).unwrap();+ assert_eq!(s2.tiles_written, 0);+ assert_eq!(s2.tiles_reused, s2.tiles_total);+ assert_eq!(s2.blobs_written, 0);+ // Touch one pixel of one layer: exactly one tile is new.+ let id = doc.layers[1].id;+ doc.layer_mut(id)+ .unwrap()+ .surface_mut()+ .unwrap()+ .write_pixel(3, 3, &[0.5, 0.5, 0.5, 1.0]);+ let (bytes, s3) = w.save_zip(&doc, &SaveOptions::default()).unwrap();+ assert_eq!(s3.tiles_written, 1);+ assert_eq!(load_from_bytes(&bytes).unwrap(), doc);+}++#[test]+fn directory_incremental_and_gc() {+ let mut doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ let dir = temp_dir("gc");+ let mut w = PcraftWriter::new();+ let s1 = w.save_dir(&doc, &dir, &SaveOptions::default()).unwrap();+ assert_eq!(s1.tiles_written, s1.tiles_total);+ // A fresh writer still skips files already on disk.+ let s2 = PcraftWriter::new()+ .save_dir(&doc, &dir, &SaveOptions::default())+ .unwrap();+ assert_eq!(s2.tiles_written, 0);+ assert_eq!(s2.objects_removed, 0);+ // Delete a layer: its unique tiles get garbage-collected.+ let paint = doc.layers[1].id;+ doc.remove(paint);+ let s3 = w.save_dir(&doc, &dir, &SaveOptions::default()).unwrap();+ assert!(s3.objects_removed > 0, "{s3:?}");+ assert_eq!(load_path(&dir).unwrap(), doc);+ let files = std::fs::read_dir(dir.join("tiles")).unwrap().count();+ assert_eq!(files, s3.tiles_total);+ std::fs::remove_dir_all(dir).unwrap();+}++#[test]+fn identical_tiles_are_stored_once() {+ let mut doc = Document::new(+ "d",+ photocraft_doc::Size::new(10, 10),+ ColorMode::Rgb,+ SampleType::U8,+ );+ let mut a = Layer::raster("a", doc.pixel_format());+ scribble(a.surface_mut().unwrap(), 5, false);+ let b = a.duplicate();+ doc.layers.push(a);+ doc.layers.push(b);+ let (_, s) = PcraftWriter::new()+ .save_zip(&doc, &SaveOptions::default())+ .unwrap();+ let per_layer = doc.layers[0].surface().unwrap().tile_count();+ assert_eq!(s.tiles_total, per_layer);+}++#[test]+fn ids_preserved_and_counter_advanced() {+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();+ // Simulate a file written with much larger ids.+ let mut m = read_manifest(&bytes).unwrap();+ m.document.layers[0].id = LayerId::fresh().0 + 5000;+ let big = m.document.layers[0].id;+ let text = serde_json::to_vec(&m).unwrap();+ let mut z = zip::ZipWriter::new();+ z.add("manifest.json", &text).unwrap();+ let r = zip::ZipReader::new(&bytes).unwrap();+ for e in r.entries.iter().filter(|e| e.name != "manifest.json") {+ z.add(&e.name, &r.read(e, usize::MAX).unwrap()).unwrap();+ }+ let back = load_from_bytes(&z.finish().unwrap()).unwrap();+ assert_eq!(back.layers[0].id.0, big);+ assert!(+ LayerId::fresh().0 > big,+ "fresh ids must not collide with loaded ids"+ );+}++#[test]+fn fresh_ids_option() {+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();+ let back = load_from_bytes_with(+ &bytes,+ &LoadOptions {+ preserve_ids: false,+ ..Default::default()+ },+ )+ .unwrap();+ assert_ne!(back.id, doc.id);+ assert_ne!(back.layers[0].id, doc.layers[0].id);+ assert_eq!(back.layers.len(), doc.layers.len());+ assert_eq!(back.layers[1].surface(), doc.layers[1].surface());+}++#[test]+fn previews_embedded_and_readable() {+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ let mut thumb = Rgba8Image::new(4, 3);+ thumb+ .pixels+ .iter_mut()+ .enumerate()+ .for_each(|(i, p)| *p = i as u8);+ let opts = SaveOptions {+ thumbnail: Some(thumb.clone()),+ composite: Some(thumb.clone()),+ };+ let bytes = save_to_bytes(&doc, &opts).unwrap();+ let png = read_thumbnail(&bytes).unwrap().unwrap();+ let img = photocraft_codecs::decode(&png).unwrap();+ assert_eq!(img.dimensions(), (4, 3));+ assert_eq!(img.to_rgba8(), thumb.pixels);+ let m = read_manifest(&bytes).unwrap();+ assert_eq!(m.composite.as_deref(), Some("composite/preview.png"));+ assert_eq!(m.format_version, FORMAT_VERSION);+ assert!(+ read_thumbnail(&save_to_bytes(&doc, &SaveOptions::default()).unwrap())+ .unwrap()+ .is_none()+ );+}++#[test]+fn manifest_is_human_readable_json() {+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();+ let r = zip::ZipReader::new(&bytes).unwrap();+ assert_eq!(r.entries[0].name, "manifest.json");+ let text = String::from_utf8(r.read_by_name("manifest.json", usize::MAX).unwrap()).unwrap();+ assert!(text.contains("\"format_version\": 1"));+ assert!(text.contains("\"Hue/Sat\""));+ assert!(text.contains("filter.blur.gaussian"));+ assert!(+ r.entries+ .iter()+ .any(|e| e.name.starts_with("tiles/") && e.name.ends_with(".zst"))+ );+ assert!(r.entries.iter().any(|e| e.name.starts_with("blobs/")));+}++#[test]+fn save_is_deterministic() {+ let doc = rich_doc(ColorMode::Cmyk, SampleType::U16);+ let a = save_to_bytes(&doc, &SaveOptions::default()).unwrap();+ let b = save_to_bytes(&doc, &SaveOptions::default()).unwrap();+ assert_eq!(a, b);+}++#[test]+fn not_pcraft() {+ assert!(!is_pcraft(b""));+ assert!(!is_pcraft(b"8BPS...."));+ let mut z = zip::ZipWriter::new();+ z.add("other.txt", b"x").unwrap();+ assert!(!is_pcraft(&z.finish().unwrap()));+}++#[test]+fn vector_fields_roundtrip_and_default_when_absent() {+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);+ let back = load_from_bytes(&save_to_bytes(&doc, &SaveOptions::default()).unwrap()).unwrap();+ assert_eq!(back.paths, doc.paths);+ assert_eq!(back.work_path, doc.work_path);+ assert_eq!(back.clipping_path, doc.clipping_path);+ let vm = |d: &Document| d.walk().into_iter().find_map(|(_, _, l)| l.vector_mask.clone());+ assert!(vm(&back).is_some());+ assert_eq!(vm(&back), vm(&doc));+ // Manifests written before the vector fields existed still load (serde defaults).+ let m = read_manifest(&save_to_bytes(&doc, &SaveOptions::default()).unwrap()).unwrap();+ let mut v = serde_json::to_value(&m.document).unwrap();+ for k in ["paths", "work_path", "clipping_path"] {+ v.as_object_mut().unwrap().remove(k);+ }+ fn strip(layers: &mut serde_json::Value) {+ for l in layers.as_array_mut().unwrap() {+ l.as_object_mut().unwrap().remove("vector_mask");+ let c = l["content"].as_object_mut().unwrap();+ for k in ["path", "stroke", "live"] {+ c.remove(k);+ }+ if let Some(ch) = c.get_mut("children") {+ strip(ch);+ }+ }+ }+ strip(&mut v["layers"]);+ let old: photocraft_format::manifest::DocM = serde_json::from_value(v).unwrap();+ assert!(old.paths.is_empty() && old.work_path.is_none());+ assert!(old.layers.iter().all(|l| l.vector_mask.is_none()));+}diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rsindex e26ed3c65..be86c72e9 100644--- a/crates/geom/src/lib.rs+++ b/crates/geom/src/lib.rs@@ -60,6 +60,10 @@ impl Rect {pub fn is_empty(&self) -> bool {self.x1 <= self.x0 || self.y1 <= self.y0}+ /// `other` lies entirely inside `self` (an empty `other` is contained in anything).+ pub fn contains_rect(&self, other: &Rect) -> bool {+ other.is_empty() || (other.x0 >= self.x0 && other.y0 >= self.y0 && other.x1 <= self.x1 && other.y1 <= self.y1)+ }pub fn contains(&self, x: i32, y: i32) -> bool {x >= self.x0 && x < self.x1 && y >= self.y0 && y < self.y1}diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.tomlnew file mode 100644index 000000000..307546ac0--- /dev/null+++ b/crates/gpu/Cargo.toml@@ -0,0 +1,22 @@+[package]+name = "photocraft-gpu"+version.workspace = true+edition.workspace = true+license.workspace = true++[lints]+workspace = true++[dependencies]+photocraft-geom = { workspace = true }+photocraft-color = { workspace = true }+photocraft-raster = { workspace = true }+photocraft-doc = { workspace = true }+photocraft-compose = { workspace = true }+# Same major version as eframe's wgpu so the app's device can be shared.+wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] }+log = { workspace = true }++[dev-dependencies]+wgpu = { version = "30" }+pollster = "1"diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgslnew file mode 100644index 000000000..42a58ce6c--- /dev/null+++ b/crates/gpu/src/compose.wgsl@@ -0,0 +1,494 @@+// Photocraft GPU compositor kernels.+//+// Every pass renders one chunk of the canvas into a straight-alpha RGBA16F accumulator, reading+// its inputs with `textureLoad` at the same pixel. The functions mirror `photocraft-compose`+// (the CPU reference) operation for operation; keep them in sync.++struct Chunk {+ origin: vec2<i32>,+ size: vec2<i32>,+};++struct Op {+ mode: i32,+ kind: i32,+ flags: u32,+ _pad0: u32,+ opacity: f32,+ mask_density: f32,+ mask_default: f32,+ _pad1: f32,+ tex_origin: vec2<i32>,+ tex_size: vec2<i32>,+ mask_origin: vec2<i32>,+ mask_size: vec2<i32>,+ color: vec4<f32>,+ p0: vec4<f32>,+ p1: vec4<f32>,+ p2: vec4<f32>,+ p3: vec4<f32>,+};++const F_MASK: u32 = 1u; // layer has an enabled mask+const F_MASK_TEX: u32 = 2u; // mask pixels live in `mask_tex`+const F_TEX: u32 = 4u; // layer pixels live in `layer_tex`+const F_GRADIENT: u32 = 8u; // gradient fill (stops in `lut_tex`)++@group(0) @binding(0) var<uniform> chunk: Chunk;+@group(0) @binding(1) var<uniform> op: Op;+@group(1) @binding(0) var tex_a: texture_2d<f32>;+@group(1) @binding(1) var tex_b: texture_2d<f32>;+@group(1) @binding(2) var layer_tex: texture_2d<f32>;+@group(1) @binding(3) var mask_tex: texture_2d<f32>;+@group(1) @binding(4) var lut_tex: texture_2d<f32>;++struct VOut { @builtin(position) pos: vec4<f32> };++@vertex+fn vs(@builtin(vertex_index) vi: u32) -> VOut {+ let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u));+ return VOut(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0));+}++fn local(pos: vec4<f32>) -> vec2<i32> { return vec2<i32>(floor(pos.xy)); }+fn doc_px(p: vec2<i32>) -> vec2<i32> { return chunk.origin + p; }++fn inside(p: vec2<i32>, size: vec2<i32>) -> bool {+ return p.x >= 0 && p.y >= 0 && p.x < size.x && p.y < size.y;+}++// Rust's f32::round (half away from zero) for non-negative inputs.+fn round_half_up(x: f32) -> f32 { return floor(x + 0.5); }+fn rem_euclid(x: f32, m: f32) -> f32 { return x - floor(x / m) * m; }++fn mask_value(d: vec2<i32>) -> f32 {+ if ((op.flags & F_MASK) == 0u) {+ return 1.0;+ }+ var v = op.mask_default;+ if ((op.flags & F_MASK_TEX) != 0u) {+ let m = d - op.mask_origin;+ if (inside(m, op.mask_size)) {+ v = textureLoad(mask_tex, m, 0).r;+ }+ }+ return 1.0 - op.mask_density * (1.0 - v);+}++fn lut(row: i32, v: f32) -> f32 {+ let x = clamp(v, 0.0, 1.0) * 4095.0;+ let i = i32(floor(x));+ let j = min(i + 1, 4095);+ let f = x - f32(i);+ return textureLoad(lut_tex, vec2(i, row), 0).r * (1.0 - f) + textureLoad(lut_tex, vec2(j, row), 0).r * f;+}++fn gray(c: vec3<f32>) -> f32 { return 0.299 * c.r + 0.587 * c.g + 0.114 * c.b; }++// ---- blend modes (photocraft_color::blend + compose::psblend) ------------------------------++const M_NORMAL: i32 = 1;+const M_DISSOLVE: i32 = 2;++fn color_burn(cb: f32, cs: f32) -> f32 {+ if (cb >= 1.0) { return 1.0; }+ if (cs <= 0.0) { return 0.0; }+ return 1.0 - min((1.0 - cb) / cs, 1.0);+}+fn color_dodge(cb: f32, cs: f32) -> f32 {+ if (cb <= 0.0) { return 0.0; }+ if (cs >= 1.0) { return 1.0; }+ return min(cb / (1.0 - cs), 1.0);+}+fn hard_light(cb: f32, cs: f32) -> f32 {+ if (cs <= 0.5) { return cb * 2.0 * cs; }+ let s = 2.0 * cs - 1.0;+ return cb + s - cb * s;+}+fn soft_light_ps(cb: f32, cs: f32) -> f32 {+ if (cs <= 0.5) { return 2.0 * cb * cs + cb * cb * (1.0 - 2.0 * cs); }+ return 2.0 * cb * (1.0 - cs) + sqrt(max(cb, 0.0)) * (2.0 * cs - 1.0);+}+fn vivid_light_ps(cb: f32, cs: f32) -> f32 {+ if (cs <= 0.5) {+ if (cs <= 0.0) { return 0.0; }+ return 1.0 - min((1.0 - cb) / (2.0 * cs), 1.0);+ }+ if (cs >= 1.0) { return 1.0; }+ return min(cb / (2.0 * (1.0 - cs)), 1.0);+}+fn vivid_light_generic(cb: f32, cs: f32) -> f32 {+ if (cs <= 0.5) {+ if (cb >= 1.0) { return 1.0; }+ if (cs <= 0.0) { return 0.0; }+ return 1.0 - min((1.0 - cb) / (2.0 * cs), 1.0);+ }+ if (cb <= 0.0) { return 0.0; }+ if (cs >= 1.0) { return 1.0; }+ return min(cb / (2.0 * (1.0 - cs)), 1.0);+}++fn blend_channel(mode: i32, cb: f32, cs: f32) -> f32 {+ switch mode {+ case 3: { return min(cb, cs); } // Darken+ case 4: { return cb * cs; } // Multiply+ case 5: { return color_burn(cb, cs); } // ColorBurn+ case 6: { return max(cb + cs - 1.0, 0.0); } // LinearBurn+ case 8: { return max(cb, cs); } // Lighten+ case 9: { return cb + cs - cb * cs; } // Screen+ case 10: { return color_dodge(cb, cs); } // ColorDodge+ case 11: { return min(cb + cs, 1.0); } // LinearDodge+ case 13: { return hard_light(cs, cb); } // Overlay+ case 14: { return soft_light_ps(cb, cs); } // SoftLight+ case 15: { return hard_light(cb, cs); } // HardLight+ case 16: { return vivid_light_ps(cb, cs); } // VividLight (Photoshop)+ case 17: { return clamp(cb + 2.0 * cs - 1.0, 0.0, 1.0); } // LinearLight+ case 18: { // PinLight+ if (cs <= 0.5) { return min(cb, 2.0 * cs); }+ return max(cb, 2.0 * cs - 1.0);+ }+ case 19: { // HardMix (Photoshop)+ return select(0.0, 1.0, vivid_light_generic(cb, cs) >= 0.5 - 1e-6);+ }+ case 20: { return abs(cb - cs); } // Difference+ case 21: { return cb + cs - 2.0 * cb * cs; } // Exclusion+ case 22: { return max(cb - cs, 0.0); } // Subtract+ case 23: { // Divide+ if (cs <= 0.0) { return select(1.0, 0.0, cb <= 0.0); }+ return min(cb / cs, 1.0);+ }+ default: { return cs; } // Normal, Dissolve, PassThrough+ }+}++fn lum(c: vec3<f32>) -> f32 { return 0.3 * c.r + 0.59 * c.g + 0.11 * c.b; }++fn clip_color(c: vec3<f32>) -> vec3<f32> {+ let l = lum(c);+ let n = min(min(c.r, c.g), c.b);+ let x = max(max(c.r, c.g), c.b);+ var out = c;+ if (n < 0.0) {+ let d = l - n;+ if (abs(d) < 1e-12) { out = vec3(l); } else { out = l + (out - l) * l / d; }+ }+ if (x > 1.0) {+ let d = x - l;+ if (abs(d) < 1e-12) { out = vec3(l); } else { out = l + (out - l) * (1.0 - l) / d; }+ }+ return out;+}+fn set_lum(c: vec3<f32>, l: f32) -> vec3<f32> { return clip_color(c + (l - lum(c))); }+fn sat(c: vec3<f32>) -> f32 { return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b); }+fn set_sat(c: vec3<f32>, s: f32) -> vec3<f32> {+ let mx = max(max(c.r, c.g), c.b);+ let mn = min(min(c.r, c.g), c.b);+ if (mx > mn) { return (c - mn) * s / (mx - mn); }+ return vec3(0.0);+}++fn blend_rgb(mode: i32, cb: vec3<f32>, cs: vec3<f32>) -> vec3<f32> {+ switch mode {+ case 24: { return set_lum(set_sat(cs, sat(cb)), lum(cb)); } // Hue+ case 25: { return set_lum(set_sat(cb, sat(cs)), lum(cb)); } // Saturation+ case 26: { return set_lum(cs, lum(cb)); } // Color+ case 27: { return set_lum(cb, lum(cs)); } // Luminosity+ case 7: { return select(cb, cs, lum(cs) < lum(cb)); } // DarkerColor+ case 12: { return select(cb, cs, lum(cs) > lum(cb)); } // LighterColor+ default: {+ return vec3(blend_channel(mode, cb.r, cs.r), blend_channel(mode, cb.g, cs.g), blend_channel(mode, cb.b, cs.b));+ }+ }+}++fn composite(mode: i32, b: vec4<f32>, s: vec4<f32>, opacity: f32) -> vec4<f32> {+ let ab = b.a;+ let as_ = s.a * opacity;+ if (as_ <= 0.0) { return b; }+ let bl = blend_rgb(mode, b.rgb, s.rgb);+ let ao = as_ + ab * (1.0 - as_);+ if (ao <= 0.0) { return vec4(0.0); }+ let rgb = ((1.0 - as_) * ab * b.rgb + (1.0 - ab) * as_ * s.rgb + as_ * ab * bl) / ao;+ return vec4(rgb, ao);+}++fn dissolve_noise(d: vec2<i32>) -> f32 {+ var h = (bitcast<u32>(d.x) * 0x8da6b343u) ^ (bitcast<u32>(d.y) * 0xd8163841u) ^ 0x9e3779b9u;+ h = h ^ (h >> 15u);+ h = h * 0x2c1b3c6du;+ h = h ^ (h >> 12u);+ return f32(h & 0xffffu) / 65536.0;+}++// ---- adjustments (compose::adjust) ----------------------------------------------------------++fn srgb_to_linear(v: f32) -> f32 {+ if (v <= 0.04045) { return v / 12.92; }+ return pow((v + 0.055) / 1.055, 2.4);+}+fn linear_to_srgb(v: f32) -> f32 {+ if (v <= 0.0031308) { return v * 12.92; }+ return 1.055 * pow(v, 1.0 / 2.4) - 0.055;+}+fn t_decode(v: f32, g: f32) -> f32 {+ if (g <= 0.0) { return srgb_to_linear(max(v, 0.0)); }+ return pow(max(v, 0.0), g);+}+fn t_encode(v: f32, g: f32) -> f32 {+ if (g <= 0.0) { return linear_to_srgb(max(v, 0.0)); }+ return pow(max(v, 0.0), 1.0 / g);+}++fn rgb_to_hsl(c: vec3<f32>) -> vec3<f32> {+ let mx = max(max(c.r, c.g), c.b);+ let mn = min(min(c.r, c.g), c.b);+ let l = (mx + mn) / 2.0;+ if (abs(mx - mn) < 1e-7) { return vec3(0.0, 0.0, l); }+ let d = mx - mn;+ var s: f32;+ if (l > 0.5) { s = d / (2.0 - mx - mn); } else { s = d / (mx + mn); }+ var h: f32;+ if (mx == c.r) {+ h = rem_euclid((c.g - c.b) / d, 6.0);+ } else if (mx == c.g) {+ h = (c.b - c.r) / d + 2.0;+ } else {+ h = (c.r - c.g) / d + 4.0;+ }+ return vec3(h / 6.0, s, l);+}+fn hue_ch(p: f32, q: f32, t0: f32) -> f32 {+ let t = rem_euclid(t0, 1.0);+ if (t < 1.0 / 6.0) { return p + (q - p) * 6.0 * t; }+ if (t < 0.5) { return q; }+ if (t < 2.0 / 3.0) { return p + (q - p) * (2.0 / 3.0 - t) * 6.0; }+ return p;+}+fn hsl_to_rgb(h: f32, s: f32, l: f32) -> vec3<f32> {+ if (s <= 0.0) { return vec3(l); }+ var q: f32;+ if (l < 0.5) { q = l * (1.0 + s); } else { q = l + s - l * s; }+ let p = 2.0 * l - q;+ return vec3(hue_ch(p, q, h + 1.0 / 3.0), hue_ch(p, q, h), hue_ch(p, q, h - 1.0 / 3.0));+}++fn posterize(v: f32, n: f32) -> f32 {+ let x = round_half_up(clamp(v, 0.0, 1.0) * 255.0);+ let bin = min(floor(x * n / 256.0), n - 1.0);+ return floor(bin * 255.0 / (n - 1.0)) / 255.0;+}++fn adjust(c: vec3<f32>) -> vec3<f32> {+ let p0 = op.p0;+ let p1 = op.p1;+ let p2 = op.p2;+ let p3 = op.p3;+ switch op.kind {+ case 1: { return 1.0 - c; } // Invert+ case 2: { // Threshold (p0.x = 8-bit level)+ return vec3(select(0.0, 1.0, round_half_up(gray(c) * 255.0) >= p0.x));+ }+ case 3: { return vec3(posterize(c.r, p0.x), posterize(c.g, p0.x), posterize(c.b, p0.x)); }+ case 4: { return clamp((c - 0.5) * p0.y + 0.5 + p0.x, vec3(0.0), vec3(1.0)); } // B/C legacy+ case 5: { return clamp((c + p0.x - 0.5) * p0.y + 0.5, vec3(0.0), vec3(1.0)); } // B/C+ case 6: { // Exposure+ var o: vec3<f32>;+ for (var i = 0; i < 3; i++) {+ let lin = pow(max(t_decode(c[i], p0.w) * p0.x + p0.y, 0.0), 1.0 / p0.z);+ o[i] = clamp(t_encode(lin, p0.w), 0.0, 1.0);+ }+ return o;+ }+ case 7: { return vec3(lut(0, c.r), lut(1, c.g), lut(2, c.b)); } // Levels / Curves+ case 8: { // Hue/Saturation+ let hsl = rgb_to_hsl(c);+ var hh: f32;+ var ss: f32;+ if (p0.w > 0.5) {+ hh = rem_euclid(p0.x, 360.0) / 360.0;+ ss = max(abs(p0.y), 0.25);+ } else {+ hh = rem_euclid(hsl.x + p0.x / 360.0, 1.0);+ ss = clamp(hsl.y * (1.0 + p0.y), 0.0, 1.0);+ }+ var rgb = hsl_to_rgb(hh, ss, hsl.z);+ if (p0.z > 0.0) {+ rgb = rgb + (1.0 - rgb) * p0.z;+ } else if (p0.z < 0.0) {+ rgb = rgb * (1.0 + p0.z);+ }+ return rgb;+ }+ case 9: { // Vibrance+ let hsl = rgb_to_hsl(c);+ let boost = p0.x * (1.0 - hsl.y);+ let ns = clamp(hsl.y * (1.0 + p0.y) + boost * max(hsl.y, 0.1), 0.0, 1.0);+ return hsl_to_rgb(hsl.x, ns, hsl.z);+ }+ case 10: { // Channel mixer+ let r = clamp(dot(p0.xyz, c) + p0.w, 0.0, 1.0);+ if (p3.x > 0.5) { return vec3(r); }+ return vec3(r, clamp(dot(p1.xyz, c) + p1.w, 0.0, 1.0), clamp(dot(p2.xyz, c) + p2.w, 0.0, 1.0));+ }+ case 11: { // Photo filter+ let f = c * (1.0 - p0.w) + c * p0.rgb * p0.w;+ if (p1.x > 0.5) {+ let l0 = gray(c);+ let l1 = max(gray(f), 1e-6);+ return clamp(f * l0 / l1, vec3(0.0), vec3(1.0));+ }+ return f;+ }+ case 12: { // Black & White+ let hsl = rgb_to_hsl(c);+ let base = gray(c);+ let sector = hsl.x * 6.0;+ let i0 = u32(floor(sector)) % 6u;+ let i1 = (i0 + 1u) % 6u;+ let f = sector - trunc(sector);+ var w = array<f32, 6>(p0.x - 40.0, p0.y - 60.0, p0.z - 40.0, p0.w - 60.0, p1.x - 20.0, p1.y - 80.0);+ let wt = w[i0] * (1.0 - f) + w[i1] * f;+ let g = clamp(base + hsl.y * wt / 100.0 * 0.5, 0.0, 1.0);+ if (p1.z > 0.5) {+ return clamp(g * p2.rgb * 2.0, vec3(0.0), vec3(1.0)) * 0.5 + g * 0.5;+ }+ return vec3(g);+ }+ case 13: { // Gradient map+ var t = gray(c);+ if (p0.x > 0.5) { t = 1.0 - t; }+ return vec3(lut(0, t), lut(1, t), lut(2, t));+ }+ case 14: { // Color balance+ let l = gray(c);+ let ws = clamp(1.0 - l * 2.0, 0.0, 1.0);+ let wh = clamp(l * 2.0 - 1.0, 0.0, 1.0);+ let wm = 1.0 - ws - wh;+ let o = clamp(c + (p0.rgb * ws + p1.rgb * wm + p2.rgb * wh) / 100.0 * 0.5, vec3(0.0), vec3(1.0));+ if (p3.x > 0.5) {+ let l1 = max(gray(o), 1e-6);+ return clamp(o * l / l1, vec3(0.0), vec3(1.0));+ }+ return o;+ }+ default: { return c; }+ }+}++// ---- fills ----------------------------------------------------------------------------------++fn gradient_t(d: vec2<i32>) -> f32 {+ // p0 = (angle°, scale, reverse, style), p1 = canvas (x0, y0, w, h)+ let w = max(op.p1.z, 1.0);+ let h = max(op.p1.w, 1.0);+ let cx = op.p1.x + w / 2.0;+ let cy = op.p1.y + h / 2.0;+ let a = radians(op.p0.x);+ let s = sin(a);+ let c = cos(a);+ let dx = f32(d.x) + 0.5 - cx;+ let dy = f32(d.y) + 0.5 - cy;+ let along = dx * c - dy * s;+ let across = dx * s + dy * c;+ let len = max(sqrt((c * w) * (c * w) + (s * h) * (s * h)), 1.0) * max(op.p0.y, 1e-3);+ var t: f32;+ switch i32(op.p0.w) {+ case 1: { t = sqrt(dx * dx + dy * dy) / (len / 2.0); } // Radial+ case 2: { t = rem_euclid((a - atan2(-dy, dx)) / 6.28318530718, 1.0); } // Angle+ case 3: { t = abs(along / (len / 2.0)); } // Reflected+ case 4: { t = (abs(along) + abs(across)) / (len / 2.0); } // Diamond+ default: { t = along / len + 0.5; } // Linear+ }+ t = clamp(t, 0.0, 1.0);+ if (op.p0.z > 0.5) { t = 1.0 - t; }+ return t;+}++fn layer_texel(d: vec2<i32>) -> vec4<f32> {+ if ((op.flags & F_GRADIENT) != 0u) {+ let t = gradient_t(d);+ return vec4(lut(0, t), lut(1, t), lut(2, t), lut(3, t));+ }+ if ((op.flags & F_TEX) != 0u) {+ let q = d - op.tex_origin;+ if (inside(q, op.tex_size)) {+ return textureLoad(layer_tex, q, 0);+ }+ }+ return op.color;+}++// ---- passes ---------------------------------------------------------------------------------++// A layer's own pixels (raster / fill), times its mask.+@fragment+fn fs_content(in: VOut) -> @location(0) vec4<f32> {+ let d = doc_px(local(in.pos));+ var c = layer_texel(d);+ c.a = c.a * mask_value(d);+ return c;+}++// Multiply alpha of A by the mask (isolated group content).+@fragment+fn fs_mask(in: VOut) -> @location(0) vec4<f32> {+ let p = local(in.pos);+ var c = textureLoad(tex_a, p, 0);+ c.a = c.a * mask_value(doc_px(p));+ return c;+}++// blend_into(backdrop = A, src = B, mode, opacity), including Dissolve.+@fragment+fn fs_blend(in: VOut) -> @location(0) vec4<f32> {+ let p = local(in.pos);+ let b = textureLoad(tex_a, p, 0);+ var s = textureLoad(tex_b, p, 0);+ if (s.a <= 0.0) { return b; }+ if (op.mode == M_DISSOLVE) {+ s.a = select(0.0, 1.0, dissolve_noise(doc_px(p)) < s.a * op.opacity);+ return composite(M_NORMAL, b, s, 1.0);+ }+ return composite(op.mode, b, s, op.opacity);+}++// composite_atop(base = A, src = B): blend as if the base were opaque, keep its alpha.+@fragment+fn fs_atop(in: VOut) -> @location(0) vec4<f32> {+ let p = local(in.pos);+ let base = textureLoad(tex_a, p, 0);+ if (base.a <= 0.0) { return base; }+ let s = textureLoad(tex_b, p, 0);+ let r = composite(op.mode, vec4(base.rgb, 1.0), s, op.opacity);+ return vec4(r.rgb, base.a);+}++// Adjustment applied to A (transparent pixels untouched).+@fragment+fn fs_adjust(in: VOut) -> @location(0) vec4<f32> {+ let c = textureLoad(tex_a, local(in.pos), 0);+ if (c.a <= 0.0) { return c; }+ return vec4(adjust(c.rgb), c.a);+}++// Mix an adjusted result B back over the original A with blend mode, opacity and mask.+@fragment+fn fs_adjmix(in: VOut) -> @location(0) vec4<f32> {+ let p = local(in.pos);+ let b = textureLoad(tex_a, p, 0);+ let k = op.opacity * mask_value(doc_px(p));+ if (k <= 0.0) { return b; }+ let a = textureLoad(tex_b, p, 0);+ let bl = blend_rgb(op.mode, b.rgb, a.rgb);+ return vec4(b.rgb + (bl - b.rgb) * k, b.a);+}++// Pass-through group opacity/mask: lerp(A, B, opacity × mask) on all channels.+@fragment+fn fs_lerp(in: VOut) -> @location(0) vec4<f32> {+ let p = local(in.pos);+ let a = textureLoad(tex_a, p, 0);+ let b = textureLoad(tex_b, p, 0);+ let k = op.opacity * mask_value(doc_px(p));+ return a + (b - a) * k;+}diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rsnew file mode 100644index 000000000..77ea8caea--- /dev/null+++ b/crates/gpu/src/lib.rs@@ -0,0 +1,648 @@+//! GPU compositor (architecture §7.2, milestone M5).+//!+//! Renders a [`Document`] with wgpu, producing the same straight-alpha composite as the CPU+//! reference (`photocraft-compose`) within ~1/255:+//!+//! - **Residency.** Layer and mask surfaces live on the GPU as dense textures covering their+//! allocated tiles. Surfaces are copy-on-write `Arc` tiles, so a tile is re-uploaded only when+//! its `Arc` changed (a brush stroke uploads just the touched 256² tiles; undo swaps pointers+//! back and uploads only what differs). RGBA8 tiles upload with zero conversion.+//! - **Planner** ([`plan`]). The layer tree becomes a linear list of passes over abstract+//! chunk-sized buffers (blend with every Photoshop mode, opacity × fill, masks, clipping groups,+//! pass-through vs isolated groups, adjustments, solid / gradient fills).+//! - **Execution.** The canvas is processed in chunks (1024² RGBA32F accumulators, reused), and+//! each finished chunk is handed to a caller-supplied sink, e.g. to encode it straight into a+//! display texture — no readback.+//!+//! Anything the planner can't express (layer effects, layers clipped to pass-through groups,+//! documents larger than the device's texture limit) returns [`Unsupported`]; callers fall back to+//! the CPU compositor.+#![forbid(unsafe_code)]++pub mod plan;++use std::collections::HashMap;+use std::num::NonZeroU64;+use std::sync::Arc;++use photocraft_color::{PixelFormat, SampleType};+use photocraft_doc::{DocId, Document, LayerId};+use photocraft_geom::{Rect, TILE_SIZE, TileCoord};+use photocraft_raster::{Surface, Tile};++pub use plan::{Kernel, Plan, Role, Unsupported, plan};++/// Accumulator format for intermediate buffers. Full float: discontinuous operations+/// (Posterize, Threshold, Hard Mix, Dissolve) must land on the same side of their thresholds as+/// the CPU reference, and Color Burn/Dodge amplify input error.+pub const ACC_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;+/// Side of the square chunks the canvas is processed in.+pub const CHUNK: u32 = 1024;+const STRIDE: u64 = 256;+const CHUNK_UNIFORM: u64 = 16;+const OP_UNIFORM: u64 = 144;++/// A finished chunk: straight-alpha RGBA32F pixels of `rect` (document coordinates) at the+/// texture's origin.+pub struct ChunkOut<'a> {+ pub rect: Rect,+ pub texture: &'a wgpu::Texture,+ pub view: &'a wgpu::TextureView,+}++/// What a render did (for profiling and tests).+#[derive(Clone, Copy, Debug, Default)]+pub struct Stats {+ pub passes: usize,+ pub chunks: usize,+ pub slots: u32,+ pub tiles_uploaded: usize,+ pub bytes_uploaded: usize,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum TexKind {+ /// RGBA8 tiles copied verbatim.+ Rgba8Direct,+ /// Other 8-bit formats converted to RGBA8.+ Rgba8,+ /// 16/32-bit formats converted to RGBA16F.+ Rgba16F,+ /// GRAY8 masks copied verbatim.+ R8Direct,+ /// Other masks as R32F.+ R32F,+}++impl TexKind {+ fn for_surface(role: Role, f: PixelFormat) -> Self {+ match role {+ Role::Content if f == PixelFormat::RGBA8 => TexKind::Rgba8Direct,+ Role::Content if f.sample == SampleType::U8 => TexKind::Rgba8,+ Role::Content => TexKind::Rgba16F,+ Role::Mask if f == PixelFormat::GRAY8 => TexKind::R8Direct,+ Role::Mask => TexKind::R32F,+ }+ }+ fn format(self) -> wgpu::TextureFormat {+ match self {+ TexKind::Rgba8Direct | TexKind::Rgba8 => wgpu::TextureFormat::Rgba8Unorm,+ TexKind::Rgba16F => wgpu::TextureFormat::Rgba16Float,+ TexKind::R8Direct => wgpu::TextureFormat::R8Unorm,+ TexKind::R32F => wgpu::TextureFormat::R32Float,+ }+ }+ fn bytes_per_pixel(self) -> usize {+ match self {+ TexKind::Rgba8Direct | TexKind::Rgba8 => 4,+ TexKind::Rgba16F => 8,+ TexKind::R8Direct => 1,+ TexKind::R32F => 4,+ }+ }+}++/// Index into the render's resident key list, and the texture's region (x, y, w, h).+type ResidentRef = (usize, [i32; 4]);++struct Resident {+ texture: wgpu::Texture,+ view: wgpu::TextureView,+ /// Document-pixel rect covered (tile aligned).+ region: Rect,+ kind: TexKind,+ format: PixelFormat,+ tiles: HashMap<TileCoord, Arc<Tile>>,+ default_nonzero: bool,+ doc: DocId,+ last_used: u64,+}++/// GPU compositor. Create once per device; call [`Compositor::render`] per refresh.+pub struct Compositor {+ pipelines: HashMap<Kernel, wgpu::RenderPipeline>,+ bgl0: wgpu::BindGroupLayout,+ bgl1: wgpu::BindGroupLayout,+ dummy: wgpu::TextureView,+ pool: Vec<(wgpu::Texture, wgpu::TextureView)>,+ residents: HashMap<(LayerId, Role), Resident>,+ max_dim: u32,+ frame: u64,+}++fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {+ wgpu::BindGroupLayoutEntry {+ binding,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture { multisampled: false, sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension: wgpu::TextureViewDimension::D2 },+ count: None,+ }+}++fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEntry {+ wgpu::BindGroupLayoutEntry {+ binding,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: NonZeroU64::new(size) },+ count: None,+ }+}++/// The compositor's WGSL source (exposed for validation in tests).+pub const SHADER: &str = include_str!("compose.wgsl");++impl Compositor {+ pub fn new(device: &wgpu::Device) -> Self {+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) });+ let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_compose_uniforms"), entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)] });+ let bgl1 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_compose_textures"), entries: &[tex_entry(0), tex_entry(1), tex_entry(2), tex_entry(3), tex_entry(4)] });+ let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_compose"), bind_group_layouts: &[Some(&bgl0), Some(&bgl1)], immediate_size: 0 });+ let mut pipelines = HashMap::new();+ for (k, entry) in [+ (Kernel::Content, "fs_content"),+ (Kernel::Mask, "fs_mask"),+ (Kernel::Blend, "fs_blend"),+ (Kernel::Atop, "fs_atop"),+ (Kernel::Adjust, "fs_adjust"),+ (Kernel::AdjMix, "fs_adjmix"),+ (Kernel::Lerp, "fs_lerp"),+ ] {+ let p = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some(entry),+ layout: Some(&layout),+ vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(entry), targets: &[Some(wgpu::ColorTargetState { format: ACC_FORMAT, blend: None, write_mask: wgpu::ColorWrites::ALL })], compilation_options: Default::default() }),+ multiview_mask: None,+ cache: None,+ });+ pipelines.insert(k, p);+ }+ let dummy = device+ .create_texture(&wgpu::TextureDescriptor {+ label: Some("pc_compose_dummy"),+ size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rgba8Unorm,+ usage: wgpu::TextureUsages::TEXTURE_BINDING,+ view_formats: &[],+ })+ .create_view(&Default::default());+ Self { pipelines, bgl0, bgl1, dummy, pool: Vec::new(), residents: HashMap::new(), max_dim: device.limits().max_texture_dimension_2d, frame: 0 }+ }++ /// Whether `doc` can be composited on the GPU.+ pub fn supports(&self, doc: &Document) -> Result<(), Unsupported> {+ let b = doc.bounds();+ if b.width() > self.max_dim || b.height() > self.max_dim {+ return Err(Unsupported(format!("document larger than the GPU texture limit ({})", self.max_dim)));+ }+ plan(doc).map(|_| ())+ }++ /// Drop GPU textures of a closed document.+ pub fn forget_doc(&mut self, doc: DocId) {+ self.residents.retain(|_, r| r.doc != doc);+ }++ /// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is+ /// still open; the chunk texture is reused afterwards, so the sink must record any copies+ /// or passes that read it into the given encoder. Submits the work before returning.+ pub fn render(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, doc: &Document, region: Rect, mut sink: impl FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>)) -> Result<Stats, Unsupported> {+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") });+ let stats = self.encode(device, queue, &mut encoder, doc, region, &mut sink)?;+ queue.submit([encoder.finish()]);+ Ok(stats)+ }++ /// Like [`Self::render`] but records into `encoder` without submitting.+ pub fn encode(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, doc: &Document, region: Rect, sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>)) -> Result<Stats, Unsupported> {+ let canvas = doc.bounds();+ if canvas.width() > self.max_dim || canvas.height() > self.max_dim {+ return Err(Unsupported(format!("document larger than the GPU texture limit ({})", self.max_dim)));+ }+ let region = region.intersect(&canvas);+ let plan = plan(doc)?;+ let mut stats = Stats { passes: plan.passes.len(), slots: plan.slots, ..Default::default() };+ if region.is_empty() {+ return Ok(stats);+ }+ self.frame += 1;++ // Residency: bring every surface the plan samples up to date.+ let grid = tile_grid(canvas);+ let mut views: Vec<(Option<ResidentRef>, Option<ResidentRef>)> = Vec::with_capacity(plan.passes.len());+ let mut keys: Vec<(LayerId, Role)> = Vec::new();+ for p in &plan.passes {+ let tex = p.tex.and_then(|t| self.sync(device, queue, doc.id, t.layer, t.role, t.surface, grid, &mut stats)).map(|(k, r)| {+ keys.push(k);+ (keys.len() - 1, r)+ });+ let mask = p.mask.and_then(|m| self.sync(device, queue, doc.id, m.layer, Role::Mask, m.surface, grid, &mut stats)).map(|(k, r)| {+ keys.push(k);+ (keys.len() - 1, r)+ });+ views.push((tex, mask));+ }+ // Evict this document's textures whose layers are gone (hidden layers stay resident so+ // toggling visibility costs no upload).+ let frame = self.frame;+ let live: std::collections::HashSet<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();+ self.residents.retain(|(id, _), r| r.doc != doc.id || r.last_used == frame || live.contains(id));++ // Chunk pool.+ while self.pool.len() < plan.slots as usize {+ let t = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("pc_compose_chunk"),+ size: wgpu::Extent3d { width: CHUNK, height: CHUNK, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: ACC_FORMAT,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let v = t.create_view(&Default::default());+ self.pool.push((t, v));+ }++ // Chunks.+ let mut chunks = Vec::new();+ let mut y = region.y0;+ while y < region.y1 {+ let mut x = region.x0;+ while x < region.x1 {+ chunks.push(Rect::new(x, y, (x + CHUNK as i32).min(region.x1), (y + CHUNK as i32).min(region.y1)));+ x += CHUNK as i32;+ }+ y += CHUNK as i32;+ }+ stats.chunks = chunks.len();++ // Uniforms: chunk records, then one record per pass.+ let op_base = chunks.len() as u64 * STRIDE;+ let mut data = vec![0u8; (op_base + plan.passes.len() as u64 * STRIDE) as usize];+ for (i, c) in chunks.iter().enumerate() {+ let w = words(&[I(c.x0), I(c.y0), I(c.width() as i32), I(c.height() as i32)]);+ data[i * STRIDE as usize..][..w.len()].copy_from_slice(&w);+ }+ for (i, (p, (tex, mask))) in plan.passes.iter().zip(&views).enumerate() {+ let mut flags = 0u32;+ let (mut to, mut ts, mut mo, mut ms) = ([0; 2], [0; 2], [0; 2], [0; 2]);+ if let Some((_, r)) = tex {+ flags |= 4;+ to = [r[0], r[1]];+ ts = [r[2], r[3]];+ }+ let (mut density, mut mdefault) = (0.0, 1.0);+ if let Some(m) = &p.mask {+ flags |= 1;+ density = m.density;+ mdefault = m.default;+ if let Some((_, r)) = mask {+ flags |= 2;+ mo = [r[0], r[1]];+ ms = [r[2], r[3]];+ }+ }+ if p.gradient {+ flags |= 8;+ }+ let mut v = vec![I(plan::mode_index(p.mode)), I(p.adjust_kind), U(flags), U(0), F(p.opacity), F(density), F(mdefault), F(0.0), I(to[0]), I(to[1]), I(ts[0]), I(ts[1]), I(mo[0]), I(mo[1]), I(ms[0]), I(ms[1])];+ v.extend(p.color.iter().map(|f| F(*f)));+ for row in &p.params {+ v.extend(row.iter().map(|f| F(*f)));+ }+ let w = words(&v);+ let off = (op_base + i as u64 * STRIDE) as usize;+ data[off..][..w.len()].copy_from_slice(&w);+ }+ let ubuf = device.create_buffer(&wgpu::BufferDescriptor { label: Some("pc_compose_uniforms"), size: data.len() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ queue.write_buffer(&ubuf, 0, &data);+ let bg0 = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("pc_compose_uniforms"),+ layout: &self.bgl0,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &ubuf, offset: 0, size: NonZeroU64::new(CHUNK_UNIFORM) }) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &ubuf, offset: 0, size: NonZeroU64::new(OP_UNIFORM) }) },+ ],+ });++ // Per-pass texture bind groups (chunk-independent: pool slots are reused per chunk).+ let resident_views: Vec<&wgpu::TextureView> = keys.iter().map(|k| &self.residents[k].view).collect();+ let mut luts = Vec::new();+ for p in &plan.passes {+ luts.push(p.lut.as_ref().map(|rows| lut_texture(device, queue, rows)));+ }+ let mut bg1 = Vec::with_capacity(plan.passes.len());+ for (i, p) in plan.passes.iter().enumerate() {+ if p.kernel == Kernel::Clear {+ bg1.push(None);+ continue;+ }+ let slot = |s: Option<u32>| s.map_or(&self.dummy, |s| &self.pool[s as usize].1);+ let (tex, mask) = &views[i];+ let tv = tex.map_or(&self.dummy, |(k, _)| resident_views[k]);+ let mv = mask.map_or(&self.dummy, |(k, _)| resident_views[k]);+ let lv = luts[i].as_ref().map_or(&self.dummy, |(_, v)| v);+ let entries = [slot(p.a), slot(p.b), tv, mv, lv];+ let e: Vec<wgpu::BindGroupEntry> = entries.iter().enumerate().map(|(b, v)| wgpu::BindGroupEntry { binding: b as u32, resource: wgpu::BindingResource::TextureView(v) }).collect();+ bg1.push(Some(device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_compose_pass"), layout: &self.bgl1, entries: &e })));+ }++ for (ci, c) in chunks.iter().enumerate() {+ for (i, p) in plan.passes.iter().enumerate() {+ let target = &self.pool[p.dst as usize].1;+ let clear = p.kernel == Kernel::Clear;+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("pc_compose_pass"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: target,+ resolve_target: None,+ depth_slice: None,+ ops: wgpu::Operations { load: if clear { wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT) } else { wgpu::LoadOp::Load }, store: wgpu::StoreOp::Store },+ })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ });+ if clear {+ continue;+ }+ pass.set_pipeline(&self.pipelines[&p.kernel]);+ pass.set_scissor_rect(0, 0, c.width(), c.height());+ pass.set_bind_group(0, &bg0, &[(ci as u64 * STRIDE) as u32, (op_base + i as u64 * STRIDE) as u32]);+ pass.set_bind_group(1, bg1[i].as_ref(), &[]);+ pass.draw(0..3, 0..1);+ }+ let (t, v) = &self.pool[plan.root as usize];+ sink(encoder, ChunkOut { rect: *c, texture: t, view: v });+ }+ Ok(stats)+ }++ /// Upload changed tiles of `surface`; returns the resident key and its region (x, y, w, h).+ #[allow(clippy::too_many_arguments)]+ fn sync(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, doc: DocId, layer: LayerId, role: Role, surface: &Surface, grid: Rect, stats: &mut Stats) -> Option<((LayerId, Role), [i32; 4])> {+ let region = surface.tile_bounds().intersect(&grid);+ if region.is_empty() {+ return None;+ }+ let format = surface.format();+ let kind = TexKind::for_surface(role, format);+ let key = (layer, role);+ let stale = self.residents.get(&key).is_none_or(|r| r.region != region || r.kind != kind || r.format != format);+ if stale {+ let texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("pc_compose_layer"),+ size: wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: kind.format(),+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ });+ let view = texture.create_view(&Default::default());+ let default_nonzero = surface.default_pixel().iter().any(|v| *v != 0.0);+ let r = Resident { texture, view, region, kind, format, tiles: HashMap::new(), default_nonzero, doc, last_used: 0 };+ if default_nonzero {+ // Missing tiles read as the default pixel: initialise them.+ let bytes = convert_tile(surface, None, kind, TileCoord::new(0, 0));+ for c in region.tiles() {+ if surface.tile(c).is_none() {+ write_tile(queue, &r, c, &bytes);+ }+ }+ }+ self.residents.insert(key, r);+ }+ let r = self.residents.get_mut(&key).expect("inserted");+ r.last_used = self.frame;+ r.doc = doc;+ for (c, t) in surface.tiles() {+ if region.intersect(&c.rect()) != c.rect() {+ continue;+ }+ if r.tiles.get(c).is_some_and(|old| Arc::ptr_eq(old, t)) {+ continue;+ }+ let bytes = convert_tile(surface, Some(t), kind, *c);+ write_tile(queue, r, *c, &bytes);+ stats.tiles_uploaded += 1;+ stats.bytes_uploaded += bytes.len();+ r.tiles.insert(*c, t.clone());+ }+ let gone: Vec<TileCoord> = r.tiles.keys().filter(|c| surface.tile(**c).is_none()).copied().collect();+ if !gone.is_empty() {+ let bytes = if r.default_nonzero { convert_tile(surface, None, kind, TileCoord::new(0, 0)) } else { vec![0u8; (TILE_SIZE * TILE_SIZE) as usize * kind.bytes_per_pixel()] };+ for c in gone {+ write_tile(queue, r, c, &bytes);+ r.tiles.remove(&c);+ }+ }+ Some((key, [region.x0, region.y0, region.width() as i32, region.height() as i32]))+ }+}++/// Canvas rounded out to whole tiles.+fn tile_grid(canvas: Rect) -> Rect {+ let t = TILE_SIZE;+ Rect::new(canvas.x0.div_euclid(t) * t, canvas.y0.div_euclid(t) * t, (canvas.x1 + t - 1).div_euclid(t) * t, (canvas.y1 + t - 1).div_euclid(t) * t)+}++fn write_tile(queue: &wgpu::Queue, r: &Resident, c: TileCoord, bytes: &[u8]) {+ let tr = c.rect();+ let bpp = r.kind.bytes_per_pixel() as u32;+ queue.write_texture(+ wgpu::TexelCopyTextureInfo { texture: &r.texture, mip_level: 0, origin: wgpu::Origin3d { x: (tr.x0 - r.region.x0) as u32, y: (tr.y0 - r.region.y0) as u32, z: 0 }, aspect: wgpu::TextureAspect::All },+ bytes,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(TILE_SIZE as u32 * bpp), rows_per_image: Some(TILE_SIZE as u32) },+ wgpu::Extent3d { width: TILE_SIZE as u32, height: TILE_SIZE as u32, depth_or_array_layers: 1 },+ );+}++/// Tile pixels in the texture's format. `tile = None` gives the default pixel everywhere.+fn convert_tile(surface: &Surface, tile: Option<&Arc<Tile>>, kind: TexKind, c: TileCoord) -> Vec<u8> {+ if let (Some(t), TexKind::Rgba8Direct | TexKind::R8Direct) = (tile, kind) {+ return t.bytes().to_vec();+ }+ let n = (TILE_SIZE * TILE_SIZE) as usize;+ let fmt = surface.format();+ let ch = fmt.channels();+ let raw: Vec<f32> = match tile {+ Some(_) => surface.read_region(c.rect()),+ None => surface.default_pixel().repeat(n),+ };+ let mut out = Vec::with_capacity(n * kind.bytes_per_pixel());+ for px in raw.chunks_exact(ch) {+ match kind {+ TexKind::Rgba8Direct | TexKind::Rgba8 => {+ let v = photocraft_raster::to_rgba(&fmt, px);+ out.extend(v.map(|x| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8));+ }+ TexKind::Rgba16F => {+ let v = photocraft_raster::to_rgba(&fmt, px);+ for x in v {+ out.extend(f32_to_f16(x).to_le_bytes());+ }+ }+ TexKind::R8Direct => out.push((px[0].clamp(0.0, 1.0) * 255.0 + 0.5) as u8),+ TexKind::R32F => out.extend(px[0].to_le_bytes()),+ }+ }+ out+}++fn lut_texture(device: &wgpu::Device, queue: &wgpu::Queue, rows: &[[f32; 4096]]) -> (wgpu::Texture, wgpu::TextureView) {+ let t = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("pc_compose_lut"),+ size: wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::R32Float,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ });+ let bytes: Vec<u8> = rows.iter().flat_map(|r| r.iter().flat_map(|v| v.to_le_bytes())).collect();+ queue.write_texture(+ wgpu::TexelCopyTextureInfo { texture: &t, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },+ &bytes,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4096 * 4), rows_per_image: Some(rows.len() as u32) },+ wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 },+ );+ let v = t.create_view(&Default::default());+ (t, v)+}++#[derive(Clone, Copy)]+enum W {+ I(i32),+ U(u32),+ F(f32),+}+use W::{F, I, U};++fn words(v: &[W]) -> Vec<u8> {+ v.iter()+ .flat_map(|w| match w {+ I(i) => i.to_le_bytes(),+ U(u) => u.to_le_bytes(),+ F(f) => f.to_le_bytes(),+ })+ .collect()+}++/// IEEE half from f32 (round to nearest even; overflow → inf).+pub fn f32_to_f16(x: f32) -> u16 {+ let b = x.to_bits();+ let sign = ((b >> 16) & 0x8000) as u16;+ let exp = ((b >> 23) & 0xff) as i32;+ let man = b & 0x7f_ffff;+ if exp == 0xff {+ return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 };+ }+ let e = exp - 127 + 15;+ if e >= 0x1f {+ return sign | 0x7c00;+ }+ if e <= 0 {+ if e < -10 {+ return sign;+ }+ let m = man | 0x80_0000;+ let shift = (14 - e) as u32;+ let half = 1u32 << (shift - 1);+ let rounded = (m + half - 1 + ((m >> shift) & 1)) >> shift;+ return sign | rounded as u16;+ }+ let mut h = ((e as u32) << 10) | (man >> 13);+ let rest = man & 0x1fff;+ if rest > 0x1000 || (rest == 0x1000 && (h & 1) == 1) {+ h += 1;+ }+ sign | h as u16+}++/// f32 from IEEE half.+pub fn f16_to_f32(h: u16) -> f32 {+ let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 };+ let exp = ((h >> 10) & 0x1f) as i32;+ let man = (h & 0x3ff) as f32;+ match exp {+ 0 => sign * man * 2f32.powi(-24),+ 0x1f => {+ if man == 0.0 {+ sign * f32::INFINITY+ } else {+ f32::NAN+ }+ }+ e => sign * (1.0 + man / 1024.0) * 2f32.powi(e - 15),+ }+}++/// Blocking readback of a composite (native tests and tools).+#[cfg(not(target_arch = "wasm32"))]+pub fn render_to_vec(comp: &mut Compositor, device: &wgpu::Device, queue: &wgpu::Queue, doc: &Document, rect: Rect) -> Result<Vec<[f32; 4]>, Unsupported> {+ let rect = rect.intersect(&doc.bounds());+ let mut staging: Vec<(Rect, wgpu::Buffer, u32)> = Vec::new();+ comp.render(device, queue, doc, rect, |enc, out| {+ let row = (out.rect.width() * 16).div_ceil(256) * 256;+ let buf = device.create_buffer(&wgpu::BufferDescriptor { label: Some("pc_readback"), size: (row * out.rect.height()) as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });+ enc.copy_texture_to_buffer(+ wgpu::TexelCopyTextureInfo { texture: out.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },+ wgpu::TexelCopyBufferInfo { buffer: &buf, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(out.rect.height()) } },+ wgpu::Extent3d { width: out.rect.width(), height: out.rect.height(), depth_or_array_layers: 1 },+ );+ staging.push((out.rect, buf, row));+ })?;+ for (_, b, _) in &staging {+ b.slice(..).map_async(wgpu::MapMode::Read, |_| {});+ }+ let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });+ let w = rect.width() as usize;+ let mut out = vec![[0.0f32; 4]; w * rect.height() as usize];+ for (r, b, row) in &staging {+ let data = b.slice(..).get_mapped_range().expect("mapped readback buffer");+ for y in 0..r.height() as usize {+ for x in 0..r.width() as usize {+ let o = y * *row as usize + x * 16;+ let px: [f32; 4] = std::array::from_fn(|i| f32::from_le_bytes(data[o + i * 4..o + i * 4 + 4].try_into().expect("4 bytes")));+ let (dx, dy) = ((r.x0 - rect.x0) as usize + x, (r.y0 - rect.y0) as usize + y);+ out[dy * w + dx] = px;+ }+ }+ }+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn half_roundtrip() {+ for v in [0.0f32, 1.0, 0.5, 0.25, 1.0 / 255.0, 0.333, 65504.0, -2.5, 1e-6] {+ let r = f16_to_f32(f32_to_f16(v));+ assert!((r - v).abs() <= v.abs() / 1024.0 + 1e-7, "{v} -> {r}");+ }+ }++ #[test]+ fn shader_validates() {+ let module = wgpu::naga::front::wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(SHADER)));+ wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty()).validate(&module).unwrap_or_else(|e| panic!("{e:?}"));+ }++ #[test]+ fn grid_rounds_out() {+ assert_eq!(tile_grid(Rect::new(0, 0, 300, 256)), Rect::new(0, 0, 512, 256));+ }+}diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rsnew file mode 100644index 000000000..4a3906105--- /dev/null+++ b/crates/gpu/src/plan.rs@@ -0,0 +1,554 @@+//! Planner: walks the layer tree into a linear list of GPU passes over abstract buffer slots.+//!+//! The structure mirrors `photocraft_compose::composite_stack` / `composite_layer` /+//! `composite_atop` one to one, so both backends share Photoshop semantics (pass-through vs+//! isolated groups, clipping, masks, opacity × fill, adjustments). Every pass reads slots and+//! writes a fresh slot; slots are recycled as soon as nothing refers to them.++use photocraft_color::BlendMode;+use photocraft_compose::adjust::{self, Transfer};+use photocraft_compose::effects::has_effects;+use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, LayerId};+use photocraft_geom::Rect;+use photocraft_raster::Surface;++/// Index of a chunk-sized accumulator texture.+pub type Slot = u32;++/// Pipeline (fragment entry point) of a pass.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Kernel {+ /// Transparent fill (no draw).+ Clear,+ Content,+ Mask,+ Blend,+ Atop,+ Adjust,+ AdjMix,+ Lerp,+}++/// Which resident texture a pass samples.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Role {+ Content,+ Mask,+}++/// A surface the pass needs on the GPU.+#[derive(Clone, Copy, Debug)]+pub struct TexUse<'a> {+ pub layer: LayerId,+ pub role: Role,+ pub surface: &'a Surface,+}++#[derive(Clone, Debug)]+pub struct Pass<'a> {+ pub kernel: Kernel,+ pub dst: Slot,+ pub a: Option<Slot>,+ pub b: Option<Slot>,+ pub mode: BlendMode,+ pub opacity: f32,+ /// Layer pixels (raster / text / shape / smart cache / fill cache).+ pub tex: Option<TexUse<'a>>,+ /// Colour outside `tex` (the surface's default pixel), or the solid fill colour.+ pub color: [f32; 4],+ pub mask: Option<MaskUse<'a>>,+ /// Adjustment kind (see `adjust` in compose.wgsl) and parameters.+ pub adjust_kind: i32,+ pub params: [[f32; 4]; 4],+ /// 4096-entry LUT rows (Levels / Curves / Gradient map / gradient fill stops).+ pub lut: Option<Vec<[f32; 4096]>>,+ pub gradient: bool,+}++#[derive(Clone, Copy, Debug)]+pub struct MaskUse<'a> {+ pub layer: LayerId,+ pub surface: &'a Surface,+ pub density: f32,+ pub default: f32,+}++impl<'a> Pass<'a> {+ fn new(kernel: Kernel, dst: Slot) -> Self {+ Pass { kernel, dst, a: None, b: None, mode: BlendMode::Normal, opacity: 1.0, tex: None, color: [0.0; 4], mask: None, adjust_kind: 0, params: [[0.0; 4]; 4], lut: None, gradient: false }+ }+}++/// Why a document can't be composited on the GPU (the caller falls back to the CPU compositor).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Unsupported(pub String);++impl std::fmt::Display for Unsupported {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "GPU compositor: {}", self.0)+ }+}++impl std::error::Error for Unsupported {}++#[derive(Debug)]+pub struct Plan<'a> {+ pub passes: Vec<Pass<'a>>,+ pub slots: u32,+ pub root: Slot,+}++/// Build the pass list for `doc`.+pub fn plan(doc: &Document) -> Result<Plan<'_>, Unsupported> {+ let mut p = Planner { passes: Vec::new(), free: Vec::new(), refs: Vec::new(), canvas: doc.bounds(), transfer: Transfer::for_mode(doc.mode) };+ let root = p.clear();+ let root = p.stack(&doc.layers, root)?;+ Ok(Plan { passes: p.passes, slots: p.refs.len() as u32, root })+}++struct Planner<'a> {+ passes: Vec<Pass<'a>>,+ free: Vec<Slot>,+ refs: Vec<u32>,+ canvas: Rect,+ transfer: Transfer,+}++fn mask_use(layer: &Layer) -> Option<MaskUse<'_>> {+ let m = layer.mask.as_ref()?;+ if !m.enabled {+ return None;+ }+ Some(MaskUse { layer: layer.id, surface: &m.surface, density: m.density, default: m.surface.default_pixel().first().copied().unwrap_or(1.0) })+}++impl<'a> Planner<'a> {+ fn alloc(&mut self) -> Slot {+ if let Some(s) = self.free.pop() {+ self.refs[s as usize] = 1;+ return s;+ }+ self.refs.push(1);+ (self.refs.len() - 1) as Slot+ }+ fn retain(&mut self, s: Slot) -> Slot {+ self.refs[s as usize] += 1;+ s+ }+ fn release(&mut self, s: Slot) {+ let r = &mut self.refs[s as usize];+ *r -= 1;+ if *r == 0 {+ self.free.push(s);+ }+ }+ /// Emit `pass` into a fresh slot, releasing its inputs.+ fn emit(&mut self, mut pass: Pass<'a>) -> Slot {+ let dst = self.alloc();+ pass.dst = dst;+ let (a, b) = (pass.a, pass.b);+ self.passes.push(pass);+ if let Some(a) = a {+ self.release(a);+ }+ if let Some(b) = b {+ self.release(b);+ }+ dst+ }+ fn clear(&mut self) -> Slot {+ self.emit(Pass::new(Kernel::Clear, 0))+ }++ /// composite_stack: returns the new backdrop (consumes `backdrop`).+ fn stack(&mut self, layers: &'a [Layer], mut backdrop: Slot) -> Result<Slot, Unsupported> {+ let mut i = 0;+ while i < layers.len() {+ let base = &layers[i];+ let mut j = i + 1;+ while j < layers.len() && layers[j].clipped && !base.clipped {+ j += 1;+ }+ let clipped = &layers[i + 1..j];+ if base.visible {+ backdrop = self.layer(base, clipped, backdrop)?;+ }+ i = j.max(i + 1);+ }+ Ok(backdrop)+ }++ fn check(&self, layer: &Layer) -> Result<(), Unsupported> {+ if has_effects(layer) {+ return Err(Unsupported(format!("layer effects on `{}`", layer.name)));+ }+ if layer.vector_mask.is_some() {+ return Err(Unsupported(format!("vector mask on `{}`", layer.name)));+ }+ Ok(())+ }++ /// composite_layer+ fn layer(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result<Slot, Unsupported> {+ self.check(layer)?;+ let opacity = layer.opacity * layer.fill_opacity;+ let visible_clipped: Vec<&'a Layer> = clipped.iter().filter(|c| c.visible).collect();++ if let LayerContent::Group(g) = &layer.content+ && layer.blend == BlendMode::PassThrough+ {+ if !visible_clipped.is_empty() {+ return Err(Unsupported(format!("layers clipped to pass-through group `{}`", layer.name)));+ }+ let before = self.retain(backdrop);+ let after = self.stack(&g.children, backdrop)?;+ if opacity < 1.0 || layer.mask.is_some() {+ let mut p = Pass::new(Kernel::Lerp, 0);+ p.a = Some(before);+ p.b = Some(after);+ p.opacity = opacity;+ p.mask = mask_use(layer);+ return Ok(self.emit(p));+ }+ self.release(before);+ return Ok(after);+ }++ if let LayerContent::Adjustment(adj) = &layer.content {+ let before = self.retain(backdrop);+ let mut adjusted = self.adjust(adj, backdrop);+ for c in visible_clipped {+ adjusted = self.atop(c, adjusted)?;+ }+ let mut p = Pass::new(Kernel::AdjMix, 0);+ p.a = Some(before);+ p.b = Some(adjusted);+ p.mode = layer.blend;+ p.opacity = opacity;+ p.mask = mask_use(layer);+ return Ok(self.emit(p));+ }++ let mut content = self.content(layer)?;+ for c in visible_clipped {+ content = self.atop(c, content)?;+ }+ let mut p = Pass::new(Kernel::Blend, 0);+ p.a = Some(backdrop);+ p.b = Some(content);+ p.mode = layer.blend;+ p.opacity = opacity;+ Ok(self.emit(p))+ }++ /// render_content for non-adjustment layers.+ fn content(&mut self, layer: &'a Layer) -> Result<Slot, Unsupported> {+ match &layer.content {+ LayerContent::Group(g) => {+ let empty = self.clear();+ let s = self.stack(&g.children, empty)?;+ if layer.mask.is_some() {+ let mut p = Pass::new(Kernel::Mask, 0);+ p.a = Some(s);+ p.mask = mask_use(layer);+ return Ok(self.emit(p));+ }+ Ok(s)+ }+ LayerContent::Adjustment(_) => unreachable!("adjustments handled by the caller"),+ LayerContent::Fill(f) => {+ let mut p = Pass::new(Kernel::Content, 0);+ p.mask = mask_use(layer);+ match &layer.fill_cache {+ Some(c) if c.fill == *f => self.surface_tex(&mut p, layer.id, &c.surface),+ _ => self.fill(&mut p, f),+ }+ Ok(self.emit(p))+ }+ _ => {+ let mut p = Pass::new(Kernel::Content, 0);+ p.mask = mask_use(layer);+ if let Some(s) = layer.surface() {+ self.surface_tex(&mut p, layer.id, s);+ }+ Ok(self.emit(p))+ }+ }+ }++ fn surface_tex(&self, p: &mut Pass<'a>, id: LayerId, s: &'a Surface) {+ let dp = s.default_pixel();+ p.color = photocraft_raster::to_rgba(&s.format(), &dp);+ if s.tile_count() > 0 {+ p.tex = Some(TexUse { layer: id, role: Role::Content, surface: s });+ }+ }++ fn fill(&self, p: &mut Pass<'a>, f: &Fill) {+ match f {+ Fill::Solid(c) => {+ let rgb = c.to_rgb();+ p.color = [rgb[0], rgb[1], rgb[2], c.alpha];+ }+ Fill::Gradient { stops, angle, scale, style, reverse } => {+ p.gradient = true;+ let style_i = match style {+ photocraft_doc::GradientStyle::Linear => 0.0,+ photocraft_doc::GradientStyle::Radial => 1.0,+ photocraft_doc::GradientStyle::Angle => 2.0,+ photocraft_doc::GradientStyle::Reflected => 3.0,+ photocraft_doc::GradientStyle::Diamond => 4.0,+ };+ p.params[0] = [*angle, *scale, if *reverse { 1.0 } else { 0.0 }, style_i];+ let c = self.canvas;+ p.params[1] = [c.x0 as f32, c.y0 as f32, c.width() as f32, c.height() as f32];+ let conv: Vec<(f32, [f32; 4])> = stops+ .iter()+ .map(|(t, c)| {+ let r = c.to_rgb();+ (*t, [r[0], r[1], r[2], c.alpha])+ })+ .collect();+ let mut rows = vec![[0.0f32; 4096]; 4];+ for k in 0..4096 {+ let v = sample_stops4(&conv, k as f32 / 4095.0);+ for (ch, row) in rows.iter_mut().enumerate() {+ row[k] = v[ch];+ }+ }+ p.lut = Some(rows);+ }+ // Patterns render once the pattern library lands; transparent until then (as on CPU).+ Fill::Pattern { .. } => {}+ }+ }++ /// composite_atop: `layer` onto `base`, restricted to the base's alpha.+ fn atop(&mut self, layer: &'a Layer, base: Slot) -> Result<Slot, Unsupported> {+ self.check(layer)?;+ let opacity = layer.opacity * layer.fill_opacity;+ if let LayerContent::Adjustment(adj) = &layer.content {+ let before = self.retain(base);+ let adjusted = self.adjust(adj, base);+ let mut p = Pass::new(Kernel::AdjMix, 0);+ p.a = Some(before);+ p.b = Some(adjusted);+ p.mode = layer.blend;+ p.opacity = opacity;+ p.mask = mask_use(layer);+ return Ok(self.emit(p));+ }+ let content = self.content(layer)?;+ let mut p = Pass::new(Kernel::Atop, 0);+ p.a = Some(base);+ p.b = Some(content);+ p.mode = layer.blend;+ p.opacity = opacity;+ Ok(self.emit(p))+ }++ /// adjust::apply_with on a slot (consumes it).+ fn adjust(&mut self, adj: &Adjustment, src: Slot) -> Slot {+ let mut p = Pass::new(Kernel::Adjust, 0);+ p.a = Some(src);+ let (kind, params, lut) = adjustment_program(adj, self.transfer);+ p.adjust_kind = kind;+ p.params = params;+ p.lut = lut;+ self.emit(p)+ }+}++fn sample_stops4(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] {+ match stops {+ [] => [0.0; 4],+ [only] => only.1,+ _ => {+ if t <= stops[0].0 {+ return stops[0].1;+ }+ for w in stops.windows(2) {+ let (a, b) = (&w[0], &w[1]);+ if t <= b.0 {+ let k = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 };+ return std::array::from_fn(|i| a.1[i] + (b.1[i] - a.1[i]) * k);+ }+ }+ stops[stops.len() - 1].1+ }+ }+}++fn lut_rows(f: impl Fn(usize, f32) -> f32, rows: usize) -> Vec<[f32; 4096]> {+ (0..rows)+ .map(|r| {+ let mut row = [0.0f32; 4096];+ for (k, v) in row.iter_mut().enumerate() {+ *v = f(r, k as f32 / 4095.0);+ }+ row+ })+ .collect()+}++type Program = (i32, [[f32; 4]; 4], Option<Vec<[f32; 4096]>>);++/// Adjustment → (kernel kind, parameters, LUT rows). Kinds are the `switch` in `adjust()`.+pub fn adjustment_program(adj: &Adjustment, transfer: Transfer) -> Program {+ let mut p = [[0.0f32; 4]; 4];+ match adj {+ Adjustment::Invert => (1, p, None),+ Adjustment::Threshold { level } => {+ p[0][0] = (level * 255.0).round();+ (2, p, None)+ }+ Adjustment::Posterize { levels } => {+ p[0][0] = (*levels).clamp(2, 255) as f32;+ (3, p, None)+ }+ Adjustment::BrightnessContrast { brightness, contrast, legacy: true } => {+ let c = contrast.clamp(-100.0, 99.0);+ let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 };+ p[0] = [brightness / 255.0, k, 0.0, 0.0];+ (4, p, None)+ }+ Adjustment::BrightnessContrast { brightness, contrast, .. } => {+ let k = if *contrast >= 0.0 { 1.0 + contrast / 50.0 } else { 1.0 + contrast / 100.0 };+ p[0] = [brightness / 255.0, k, 0.0, 0.0];+ (5, p, None)+ }+ Adjustment::Exposure { exposure, offset, gamma } => {+ let g = match transfer {+ Transfer::Srgb => 0.0,+ Transfer::Gamma(g) => g,+ };+ p[0] = [2f32.powf(*exposure), *offset, gamma.max(0.01), g];+ (6, p, None)+ }+ Adjustment::Levels { master, per_channel } => (7, p, Some(lut_rows(|i, v| adjust::levels(&per_channel[i], adjust::levels(master, v)), 3))),+ Adjustment::Curves { master, per_channel } => {+ let m = adjust::curve_lut(master);+ let chans: Vec<Vec<f32>> = per_channel.iter().map(|c| adjust::curve_lut(c)).collect();+ let lut = |t: &[f32], v: f32| {+ let x = v.clamp(0.0, 1.0) * (t.len() - 1) as f32;+ let i = x.floor() as usize;+ let j = (i + 1).min(t.len() - 1);+ let f = x - i as f32;+ t[i] * (1.0 - f) + t[j] * f+ };+ // The CPU LUT is `m(ch[k])` per entry; entries are on the same 4096 grid.+ let rows = (0..3)+ .map(|r| {+ let mut row = [0.0f32; 4096];+ for (k, v) in row.iter_mut().enumerate() {+ *v = lut(&m, chans[r][k.min(chans[r].len() - 1)]);+ }+ row+ })+ .collect();+ (7, p, Some(rows))+ }+ Adjustment::HueSaturation { hue, saturation, lightness, colorize } => {+ p[0] = [*hue, saturation / 100.0, lightness / 100.0, if *colorize { 1.0 } else { 0.0 }];+ (8, p, None)+ }+ Adjustment::Vibrance { vibrance, saturation } => {+ p[0] = [vibrance / 100.0, saturation / 100.0, 0.0, 0.0];+ (9, p, None)+ }+ Adjustment::ChannelMixer { matrix, monochrome } => {+ p[0] = matrix[0];+ p[1] = matrix[1];+ p[2] = matrix[2];+ p[3][0] = if *monochrome { 1.0 } else { 0.0 };+ (10, p, None)+ }+ Adjustment::PhotoFilter { color, density, preserve_luminosity } => {+ p[0] = [color[0], color[1], color[2], *density];+ p[1][0] = if *preserve_luminosity { 1.0 } else { 0.0 };+ (11, p, None)+ }+ Adjustment::BlackWhite { weights, tint } => {+ p[0] = [weights[0], weights[1], weights[2], weights[3]];+ p[1] = [weights[4], weights[5], if tint.is_some() { 1.0 } else { 0.0 }, 0.0];+ if let Some(t) = tint {+ p[2] = [t[0], t[1], t[2], 0.0];+ }+ (12, p, None)+ }+ Adjustment::GradientMap { stops, reverse } => {+ p[0][0] = if *reverse { 1.0 } else { 0.0 };+ let s4: Vec<(f32, [f32; 4])> = stops.iter().map(|(t, c)| (*t, [c[0], c[1], c[2], 1.0])).collect();+ let rows = lut_rows(|r, t| if s4.is_empty() { t } else { sample_stops4(&s4, t)[r] }, 3);+ (13, p, Some(rows))+ }+ Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => {+ p[0] = [shadows[0], shadows[1], shadows[2], 0.0];+ p[1] = [midtones[0], midtones[1], midtones[2], 0.0];+ p[2] = [highlights[0], highlights[1], highlights[2], 0.0];+ p[3][0] = if *preserve_luminosity { 1.0 } else { 0.0 };+ (14, p, None)+ }+ // Identity on the CPU too (not yet evaluated there).+ Adjustment::SelectiveColor { .. } | Adjustment::ColorLookup { .. } | Adjustment::Unsupported { .. } => (0, p, None),+ }+}++/// Mode index used by the shader (declaration order of [`BlendMode`]).+pub fn mode_index(m: BlendMode) -> i32 {+ match m {+ BlendMode::PassThrough => 0,+ BlendMode::Normal => 1,+ BlendMode::Dissolve => 2,+ BlendMode::Darken => 3,+ BlendMode::Multiply => 4,+ BlendMode::ColorBurn => 5,+ BlendMode::LinearBurn => 6,+ BlendMode::DarkerColor => 7,+ BlendMode::Lighten => 8,+ BlendMode::Screen => 9,+ BlendMode::ColorDodge => 10,+ BlendMode::LinearDodge => 11,+ BlendMode::LighterColor => 12,+ BlendMode::Overlay => 13,+ BlendMode::SoftLight => 14,+ BlendMode::HardLight => 15,+ BlendMode::VividLight => 16,+ BlendMode::LinearLight => 17,+ BlendMode::PinLight => 18,+ BlendMode::HardMix => 19,+ BlendMode::Difference => 20,+ BlendMode::Exclusion => 21,+ BlendMode::Subtract => 22,+ BlendMode::Divide => 23,+ BlendMode::Hue => 24,+ BlendMode::Saturation => 25,+ BlendMode::Color => 26,+ BlendMode::Luminosity => 27,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_color::{Color, ColorMode, SampleType};+ use photocraft_geom::Size;++ #[test]+ fn slots_are_recycled() {+ let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE);+ for i in 0..10 {+ d.layers.push(Layer::raster(format!("l{i}"), d.pixel_format()));+ }+ let p = plan(&d).unwrap();+ assert!(p.slots <= 3, "{} slots", p.slots);+ assert_eq!(p.passes.len(), 1 + 11 * 2);+ }++ #[test]+ fn effects_are_unsupported() {+ let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE);+ d.layers[0].effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE });+ assert!(plan(&d).is_err());+ }+}diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rsnew file mode 100644index 000000000..7cd8a9869--- /dev/null+++ b/crates/gpu/tests/parity.rs@@ -0,0 +1,277 @@+//! GPU vs CPU parity: every blend mode, adjustment, group/clip/mask/fill combination must match+//! the reference compositor within 2/255 (premultiplied). Skips when no GPU adapter exists.++use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};+use photocraft_doc::adjust::{CurvePoint, LevelsChannel};+use photocraft_doc::{Adjustment, Document, Fill, GradientStyle, Layer, LayerContent, LayerMask};+use photocraft_geom::{Rect, Size};+use photocraft_gpu::{Compositor, render_to_vec};++const TOL: f32 = 1.0 / 255.0;++struct Gpu {+ device: wgpu::Device,+ queue: wgpu::Queue,+ comp: Compositor,+}++fn gpu() -> Option<Gpu> {+ let instance = wgpu::Instance::default();+ let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) {+ Ok(a) => a,+ Err(e) => {+ eprintln!("skipping GPU parity tests: no adapter ({e})");+ return None;+ }+ };+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()?;+ let comp = Compositor::new(&device);+ Some(Gpu { device, queue, comp })+}++/// Deterministic pseudo-random values in 0..1.+fn rnd(seed: u32, i: u32) -> f32 {+ let mut h = seed.wrapping_mul(0x9e37_79b9) ^ i.wrapping_mul(0x85eb_ca6b);+ h ^= h >> 13;+ h = h.wrapping_mul(0xc2b2_ae35);+ h ^= h >> 16;+ (h & 0xffff) as f32 / 65535.0+}++fn noise_layer(name: &str, fmt: PixelFormat, rect: Rect, seed: u32, min_alpha: f32) -> Layer {+ let mut l = Layer::raster(name, fmt);+ let n = rect.width() as usize * rect.height() as usize;+ let ch = fmt.channels();+ let mut data = Vec::with_capacity(n * ch);+ for i in 0..n as u32 {+ for c in 0..ch {+ let v = rnd(seed + c as u32 * 7919, i);+ let is_alpha = fmt.alpha && c == ch - 1;+ data.push(if is_alpha { min_alpha + (1.0 - min_alpha) * v } else { v });+ }+ }+ l.surface_mut().unwrap().write_region(rect, &data);+ l+}++fn mask(rect: Rect, seed: u32, default: f32) -> LayerMask {+ let mut m = LayerMask::reveal_all();+ m.surface = photocraft_raster::Surface::with_default(PixelFormat::GRAY8, &[default]);+ let data: Vec<f32> = (0..rect.width() * rect.height()).map(|i| rnd(seed, i)).collect();+ m.surface.write_region(rect, &data);+ m.density = 0.8;+ m+}++fn base_doc(w: u32, h: u32) -> Document {+ let mut d = Document::new("t", Size::new(w, h), ColorMode::Rgb, SampleType::U8);+ d.layers.push(noise_layer("bg", PixelFormat::RGBA8, Rect::from_xywh(0, 0, w, h), 1, 0.3));+ d+}++fn check(g: &mut Gpu, doc: &Document, what: &str) {+ let cpu = photocraft_compose::flatten(doc);+ let out = render_to_vec(&mut g.comp, &g.device, &g.queue, doc, doc.bounds()).unwrap_or_else(|e| panic!("{what}: {e}"));+ let mut worst = (0.0f32, 0usize);+ for (i, (c, o)) in cpu.px.iter().zip(&out).enumerate() {+ let pc = [c[0] * c[3], c[1] * c[3], c[2] * c[3], c[3]];+ let po = [o[0] * o[3], o[1] * o[3], o[2] * o[3], o[3]];+ for k in 0..4 {+ let d = (pc[k] - po[k]).abs();+ if d.is_nan() || d > worst.0 {+ worst = (if d.is_nan() { 9.0 } else { d }, i);+ }+ }+ }+ let w = doc.size.width as usize;+ let (x, y) = (worst.1 % w, worst.1 / w);+ assert!(worst.0 <= TOL, "{what}: max diff {:.2}/255 at ({x},{y}): cpu {:?} gpu {:?}", worst.0 * 255.0, cpu.px[worst.1], out[worst.1]);+}++#[test]+fn blend_modes() {+ let Some(mut g) = gpu() else { return };+ for mode in BlendMode::LAYER_MODES {+ let mut d = base_doc(64, 48);+ let mut l = noise_layer("top", PixelFormat::RGBA8, Rect::new(4, 3, 60, 45), 2, 0.0);+ l.blend = mode;+ l.opacity = 0.8;+ l.fill_opacity = 0.9;+ d.layers.push(l);+ check(&mut g, &d, &format!("{mode:?}"));+ // Over an opaque backdrop too (the common case).+ d.layers[0] = noise_layer("bg", PixelFormat::RGBA8, Rect::from_xywh(0, 0, 64, 48), 5, 1.0);+ check(&mut g, &d, &format!("{mode:?} opaque"));+ }+}++fn adjustments() -> Vec<Adjustment> {+ let lc = |a: f32, b: f32, g: f32| LevelsChannel { in_black: a, in_white: b, gamma: g, out_black: 0.05, out_white: 0.95 };+ let pts = |v: &[(f32, f32)]| v.iter().map(|&(input, output)| CurvePoint { input, output }).collect::<Vec<_>>();+ vec![+ Adjustment::Invert,+ Adjustment::Threshold { level: 0.5 },+ Adjustment::Posterize { levels: 5 },+ Adjustment::BrightnessContrast { brightness: 30.0, contrast: 40.0, legacy: false },+ Adjustment::BrightnessContrast { brightness: -20.0, contrast: -30.0, legacy: true },+ Adjustment::Exposure { exposure: 0.7, offset: 0.02, gamma: 1.2 },+ Adjustment::Levels { master: lc(0.1, 0.9, 1.3), per_channel: [lc(0.0, 1.0, 0.8), LevelsChannel::default(), lc(0.2, 0.8, 1.0)] },+ Adjustment::Curves { master: pts(&[(0.0, 0.1), (0.4, 0.6), (1.0, 0.9)]), per_channel: [pts(&[(0.0, 0.0), (0.5, 0.3), (1.0, 1.0)]), pts(&[(0.0, 0.0), (1.0, 1.0)]), pts(&[(0.0, 0.2), (1.0, 1.0)])] },+ Adjustment::HueSaturation { hue: 40.0, saturation: 30.0, lightness: -10.0, colorize: false },+ Adjustment::HueSaturation { hue: 200.0, saturation: 50.0, lightness: 20.0, colorize: true },+ Adjustment::Vibrance { vibrance: 50.0, saturation: -20.0 },+ Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false },+ Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0; 4], [0.0; 4]], monochrome: true },+ Adjustment::PhotoFilter { color: [0.9, 0.6, 0.2], density: 0.4, preserve_luminosity: true },+ Adjustment::PhotoFilter { color: [0.2, 0.6, 0.9], density: 0.3, preserve_luminosity: false },+ Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None },+ Adjustment::BlackWhite { weights: [70.0, 20.0, 50.0, 10.0, 90.0, 30.0], tint: Some([0.9, 0.7, 0.5]) },+ Adjustment::GradientMap { stops: vec![(0.0, [0.1, 0.0, 0.3]), (0.5, [0.9, 0.3, 0.1]), (1.0, [1.0, 1.0, 0.8])], reverse: false },+ Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: true },+ Adjustment::ColorBalance { shadows: [20.0, -10.0, 5.0], midtones: [-15.0, 10.0, 30.0], highlights: [0.0, 5.0, -20.0], preserve_luminosity: true },+ Adjustment::ColorBalance { shadows: [10.0, 0.0, 0.0], midtones: [0.0, 0.0, 0.0], highlights: [0.0, 0.0, 10.0], preserve_luminosity: false },+ ]+}++#[test]+fn adjustment_layers() {+ let Some(mut g) = gpu() else { return };+ for adj in adjustments() {+ for (mode, opacity, masked) in [(BlendMode::Normal, 1.0, false), (BlendMode::Multiply, 0.7, true)] {+ let mut d = base_doc(48, 40);+ d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(8, 8, 40, 32), 3, 0.5));+ let mut a = Layer::new("adj", LayerContent::Adjustment(adj.clone()));+ a.blend = mode;+ a.opacity = opacity;+ if masked {+ a.mask = Some(mask(Rect::new(0, 0, 48, 20), 9, 0.3));+ }+ d.layers.push(a);+ check(&mut g, &d, &format!("{} {mode:?}", adj.label()));+ }+ }+}++#[test]+fn groups_masks_and_clipping() {+ let Some(mut g) = gpu() else { return };+ let child = |seed, mode| {+ let mut l = noise_layer("c", PixelFormat::RGBA8, Rect::new(5, 5, 50, 40), seed, 0.0);+ l.blend = mode;+ l+ };+ for isolated in [false, true] {+ let mut d = base_doc(56, 44);+ let mut grp = Layer::group("g", vec![child(11, BlendMode::Normal), child(12, BlendMode::Screen), child(13, BlendMode::Multiply)]);+ if isolated {+ grp.blend = BlendMode::Overlay;+ }+ grp.opacity = 0.7;+ grp.mask = Some(mask(Rect::new(10, 0, 40, 44), 21, 1.0));+ d.layers.push(grp);+ check(&mut g, &d, &format!("group isolated={isolated}"));+ }+ // Nested groups with an adjustment inside a pass-through group.+ let mut d = base_doc(56, 44);+ let inner = Layer::group("inner", vec![child(14, BlendMode::Normal), Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]);+ let mut outer = Layer::group("outer", vec![inner, child(15, BlendMode::Difference)]);+ outer.blend = BlendMode::Normal;+ d.layers.push(outer);+ check(&mut g, &d, "nested groups");++ // Clipping: raster + adjustment clipped to a base, a masked base, and a hidden base.+ for hidden in [false, true] {+ let mut d = base_doc(56, 44);+ let mut base = noise_layer("base", PixelFormat::RGBA8, Rect::new(10, 6, 46, 38), 16, 0.0);+ base.mask = Some(mask(Rect::new(0, 0, 56, 44), 22, 1.0));+ base.visible = !hidden;+ let mut c1 = child(17, BlendMode::Multiply);+ c1.clipped = true;+ c1.opacity = 0.6;+ let mut c2 = Layer::new("hs", LayerContent::Adjustment(Adjustment::HueSaturation { hue: 90.0, saturation: 20.0, lightness: 0.0, colorize: false }));+ c2.clipped = true;+ d.layers.extend([base, c1, c2]);+ check(&mut g, &d, &format!("clipping hidden={hidden}"));+ }+ // Clipped group base (isolated) with a clipped layer.+ let mut d = base_doc(56, 44);+ let mut gb = Layer::group("gb", vec![child(18, BlendMode::Normal)]);+ gb.blend = BlendMode::Normal;+ let mut c = child(19, BlendMode::Screen);+ c.clipped = true;+ d.layers.extend([gb, c]);+ check(&mut g, &d, "clipped to isolated group");+}++#[test]+fn fills_and_dissolve() {+ let Some(mut g) = gpu() else { return };+ let mut d = base_doc(64, 48);+ let mut solid = Layer::new("solid", LayerContent::Fill(Fill::Solid(Color::rgb(0.2, 0.5, 0.8))));+ solid.mask = Some(mask(Rect::new(0, 0, 32, 48), 31, 0.0));+ solid.blend = BlendMode::HardLight;+ d.layers.push(solid);+ check(&mut g, &d, "solid fill");+ for style in [GradientStyle::Linear, GradientStyle::Radial, GradientStyle::Angle, GradientStyle::Reflected, GradientStyle::Diamond] {+ let mut d = base_doc(64, 48);+ let stops = vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.6, Color::rgb(0.0, 1.0, 0.2)), (1.0, Color::rgb(0.1, 0.1, 0.9))];+ let mut l = Layer::new("grad", LayerContent::Fill(Fill::Gradient { stops, angle: 30.0, scale: 0.8, style, reverse: style == GradientStyle::Radial }));+ l.opacity = 0.9;+ d.layers.push(l);+ check(&mut g, &d, &format!("gradient {style:?}"));+ }+ let mut d = base_doc(64, 48);+ let mut l = noise_layer("dis", PixelFormat::RGBA8, Rect::new(0, 0, 64, 48), 41, 0.2);+ l.blend = BlendMode::Dissolve;+ l.opacity = 0.6;+ d.layers.push(l);+ check(&mut g, &d, "dissolve");+}++#[test]+fn formats_offsets_and_chunks() {+ let Some(mut g) = gpu() else { return };+ // 16-bit and float layers, and a layer extending off-canvas at negative coordinates.+ let mut d = Document::new("t", Size::new(300, 70), ColorMode::Rgb, SampleType::U16);+ d.layers.push(noise_layer("bg16", PixelFormat::RGBA16, Rect::new(0, 0, 300, 70), 51, 1.0));+ let mut f = noise_layer("f32", PixelFormat::RGBA32F, Rect::new(-40, -10, 200, 60), 52, 0.0);+ f.blend = BlendMode::SoftLight;+ d.layers.push(f);+ check(&mut g, &d, "16-bit / float / offsets");++ // Grayscale and CMYK documents.+ let mut d = Document::new("g", Size::new(40, 30), ColorMode::Grayscale, SampleType::U8);+ d.layers.push(noise_layer("g", PixelFormat::GRAYA8, Rect::new(0, 0, 40, 30), 53, 0.5));+ check(&mut g, &d, "grayscale");+ let mut d = Document::new("c", Size::new(40, 30), ColorMode::Cmyk, SampleType::U8);+ d.layers.push(noise_layer("c", PixelFormat::CMYKA8, Rect::new(0, 0, 40, 30), 54, 1.0));+ check(&mut g, &d, "cmyk");++ // Wider than one chunk.+ let w = photocraft_gpu::CHUNK + 100;+ let mut d = base_doc(w, 24);+ let mut l = noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, w as i32, 24), 55, 0.0);+ l.blend = BlendMode::Color;+ d.layers.push(l);+ check(&mut g, &d, "multi-chunk");+}++#[test]+fn incremental_updates_follow_the_document() {+ let Some(mut g) = gpu() else { return };+ let mut d = base_doc(600, 300);+ d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 600, 300), 61, 0.0));+ check(&mut g, &d, "initial");+ // Paint into one tile of the top layer: only that tile uploads.+ let top = d.layers[1].surface_mut().unwrap();+ top.fill_rect(Rect::new(10, 10, 60, 60), &[1.0, 0.0, 0.0, 1.0]);+ let before = photocraft_gpu::render_to_vec(&mut g.comp, &g.device, &g.queue, &d, Rect::new(0, 0, 1, 1)).unwrap();+ assert_eq!(before.len(), 1);+ check(&mut g, &d, "after paint");+ // Remove all tiles of the top layer, hide nothing: the GPU must clear them.+ d.layers[1] = Layer::raster("empty", PixelFormat::RGBA8);+ check(&mut g, &d, "after clearing");+ // Visibility and opacity changes need no uploads.+ d.layers[0].opacity = 0.5;+ check(&mut g, &d, "opacity");+}diff --git a/crates/gpu/tests/vector_mask.rs b/crates/gpu/tests/vector_mask.rsnew file mode 100644index 000000000..48a9d6797--- /dev/null+++ b/crates/gpu/tests/vector_mask.rs@@ -0,0 +1,16 @@+//! Layers with vector masks are not planned on the GPU yet: the planner reports `Unsupported`+//! so callers fall back to the CPU compositor (which rasterizes the mask).++use photocraft_color::{Color, ColorMode, SampleType};+use photocraft_doc::{Document, Layer, Path, Size, Subpath, VectorMask};++#[test]+fn vector_mask_falls_back_to_cpu() {+ let mut d = Document::with_background("v", Size::new(16, 16), ColorMode::Rgb, SampleType::U8, Color::WHITE);+ assert!(photocraft_gpu::plan(&d).is_ok());+ let mut l = Layer::raster("masked", d.pixel_format());+ l.vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (8.0, 0.0), (8.0, 16.0)])])));+ d.layers.push(Layer::group("g", vec![l]));+ let Err(err) = photocraft_gpu::plan(&d) else { panic!("vector masks are CPU-only") };+ assert!(err.0.contains("vector mask"), "{err}");+}diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.tomlindex 82d7f76cf..970026270 100644--- a/crates/io/Cargo.toml+++ b/crates/io/Cargo.toml@@ -17,8 +17,11 @@ photocraft-doc = { workspace = true }photocraft-compose = { workspace = true }photocraft-psd = { workspace = true }photocraft-codecs = { workspace = true }+photocraft-text = { workspace = true }+photocraft-format = { path = "../format" }thiserror = { workspace = true }[dev-dependencies]photocraft-psd = { workspace = true, features = ["testgen"] }proptest = { workspace = true }+photocraft-vector = { workspace = true }diff --git a/crates/io/examples/dbg_corpus.rs b/crates/io/examples/dbg_corpus.rsnew file mode 100644index 000000000..3ab92c7c5--- /dev/null+++ b/crates/io/examples/dbg_corpus.rs@@ -0,0 +1,30 @@+// Temporary debugging aid: print our flatten vs Photoshop's merged image for a PSD.+fn main() {+ let path = std::env::args().nth(1).expect("path");+ let bytes = std::fs::read(&path).unwrap();+ let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap();+ let imp = photocraft_io::import(&path, &bytes).unwrap();+ let doc = &imp.document;+ println!("mode {:?} depth {:?} layers {} warnings {:?}", doc.mode, doc.depth, doc.layer_count(), imp.warnings);+ for l in doc.walk() {+ let l = l.2;+ println!(" layer {:?} {:?} blend {:?} op {} fill {} fill_cache {}", l.name, l.content.kind_name(), l.blend, l.opacity, l.fill_opacity, l.fill_cache.is_some());+ if let photocraft_doc::LayerContent::Fill(f) = &l.content {+ println!(" {f:?}");+ }+ for (k, v) in &l.psd_blocks {+ if k == b"GdFl" {+ // Skip the 4-byte version before the descriptor.+ if let Ok((d, _)) = photocraft_psd::descriptor::Descriptor::parse_prefix(&v[4..]) {+ println!(" GdFl keys: {:?}", d.items.iter().map(|(k, v)| format!("{k}={v:?}")).filter(|s| !s.starts_with("Grad")).collect::<Vec<_>>());+ }+ }+ }+ }+ let ours = photocraft_compose::flatten(doc).px;+ let merged = photocraft_io::merged_composite(&file).unwrap();+ let n = std::env::args().nth(2).and_then(|s| s.parse().ok()).unwrap_or(8usize);+ for (i, (a, b)) in ours.iter().zip(&merged).enumerate().take(n) {+ println!("{i:4}: ours {:?}\n ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0));+ }+}diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rsindex 4cb2e413d..714c7d5b9 100644--- a/crates/io/src/blocks.rs+++ b/crates/io/src/blocks.rs@@ -210,19 +210,25 @@ pub(crate) fn gradient_desc(stops: &[(f32, Color)], opacity: &[(f32, f32)]) -> Dpub fn parse_fill(key: &[u8; 4], data: &[u8]) -> Option<Fill> {// Block data may carry trailing padding after the descriptor.let d = parse_prefix_versioned(data)?;+ fill_from_desc(key, &d)+}++/// A fill from its descriptor (`SoCo`/`GdFl`/`PtFl` layout; also the `solidColorLayer`,+/// `gradientLayer` and `patternLayer` contents of shape strokes).+pub fn fill_from_desc(key: &[u8; 4], d: &Descriptor) -> Option<Fill> {match key {- b"SoCo" => Some(Fill::Solid(color_from_desc(get_desc(&d, "Clr ")?)?)),+ b"SoCo" => Some(Fill::Solid(color_from_desc(get_desc(d, "Clr ")?)?)),b"GdFl" => {let angle = num(d.get("Angl")).unwrap_or(90.0) as f32;let scale = num(d.get("Scl ")).map_or(1.0, |v| v as f32 / 100.0);- let (mut stops, _) = get_desc(&d, "Grad").map(gradient_stops).unwrap_or_default();+ let (mut stops, _) = get_desc(d, "Grad").map(gradient_stops).unwrap_or_default();if stops.is_empty() {stops = vec![(0.0, Color::BLACK), (1.0, Color::WHITE)];}- Some(Fill::Gradient { stops, angle, scale, style: gradient_style(&d), reverse: bool_of(&d, "Rvrs") })+ Some(Fill::Gradient { stops, angle, scale, style: gradient_style(d), reverse: bool_of(d, "Rvrs") })}b"PtFl" => {- let name = get_desc(&d, "Ptrn")+ let name = get_desc(d, "Ptrn").and_then(|p| match p.get("Nm ") {Some(Value::Text(t)) => Some(t.to_string_lossy()),_ => None,@@ -237,11 +243,14 @@ pub fn parse_fill(key: &[u8; 4], data: &[u8]) -> Option<Fill> {/// Serializes a fill to its block.pub fn write_fill(f: &Fill) -> ([u8; 4], Vec<u8>) {+ let (k, d) = fill_to_desc(f);+ (k, VersionedDescriptor::new(d).to_bytes())+}++/// A fill as (block key, descriptor with class `null`).+pub fn fill_to_desc(f: &Fill) -> ([u8; 4], Descriptor) {match f {- Fill::Solid(c) => {- let d = Descriptor::new("null").with("Clr ", Value::Descriptor(color_to_desc(c)));- (*b"SoCo", VersionedDescriptor::new(d).to_bytes())- }+ Fill::Solid(c) => (*b"SoCo", Descriptor::new("null").with("Clr ", Value::Descriptor(color_to_desc(c)))),Fill::Gradient { stops, angle, scale, style, reverse } => {let mut d = Descriptor::new("null").with("Angl", Value::UnitFloat { unit: *b"#Ang", value: f64::from(*angle) })@@ -251,14 +260,16 @@ pub fn write_fill(f: &Fill) -> ([u8; 4], Vec<u8>) {if *reverse {d = d.with("Rvrs", Value::Boolean(true));}- (*b"GdFl", VersionedDescriptor::new(d).to_bytes())+ (*b"GdFl", d)}Fill::Pattern { name, scale } => {let p = Descriptor::new("Ptrn").with("Nm ", Value::Text(UnicodeString::new_nul(name)));- let d = Descriptor::new("null")- .with("Scl ", Value::UnitFloat { unit: *b"#Prc", value: f64::from(scale * 100.0) })- .with("Ptrn", Value::Descriptor(p));- (*b"PtFl", VersionedDescriptor::new(d).to_bytes())+ (+ *b"PtFl",+ Descriptor::new("null")+ .with("Scl ", Value::UnitFloat { unit: *b"#Prc", value: f64::from(scale * 100.0) })+ .with("Ptrn", Value::Descriptor(p)),+ )}}}@@ -280,7 +291,7 @@ pub fn parse_tysh(data: &[u8]) -> Option<(String, Affine)> {}/// Parses a version-16 descriptor at the start of `data` (trailing bytes allowed).-fn parse_prefix_versioned(data: &[u8]) -> Option<Descriptor> {+pub(crate) fn parse_prefix_versioned(data: &[u8]) -> Option<Descriptor> {VersionedDescriptor::parse_prefix(data).ok().map(|(v, _)| v.descriptor)}diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex 0a2635194..132272324 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -24,6 +24,7 @@ mod flat;mod pixels;mod psd_export;mod psd_import;+pub mod vector_map;use photocraft_codecs::{CodecError, EncodeOptions};use photocraft_doc::Document;@@ -49,6 +50,9 @@ pub enum IoError {/// The requested conversion is not possible.#[error("unsupported: {0}")]Unsupported(String),+ /// Native `.pcraft` bundle failure.+ #[error("pcraft: {0}")]+ Pcraft(#[from] photocraft_format::FormatError),}/// Result of [`import`].@@ -86,6 +90,9 @@ pub fn is_psd(bytes: &[u8]) -> bool {/// Imports a file. PSD/PSB are detected by magic; everything else is decoded/// with `photocraft-codecs`.pub fn import(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {+ if photocraft_format::is_pcraft(bytes) {+ return Ok(ImportResult { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new() });+ }if is_psd(bytes) {let file = PsdFile::from_bytes(bytes)?;let (mut document, warnings) = psd_to_document(&file);@@ -103,6 +110,13 @@ fn extension(name_or_ext: &str) -> String {/// bare extension).pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result<ExportResult, IoError> {let ext = extension(name_or_ext);+ if ext == photocraft_format::EXTENSION {+ let previews = photocraft_format::SaveOptions {+ thumbnail: Some(photocraft_compose::thumbnail(doc, 256)),+ composite: Some(photocraft_compose::thumbnail(doc, 1024)),+ };+ return Ok(ExportResult { bytes: photocraft_format::save_to_bytes(doc, &previews)?, warnings: Vec::new() });+ }if ext == "psd" || ext == "psb" {let o = PsdExportOptions { force_psb: opts.force_psb || ext == "psb" };let (file, warnings) = document_to_psd_with(doc, &o);diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 007556d49..04932f665 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -26,6 +26,8 @@ pub struct PsdExportOptions {struct Ex {fmt: PixelFormat,+ /// Document resolution (for generated type-layer data).+ dpi: f32,mask_fmt: PixelFormat,cc: usize,cmyk: bool,@@ -250,10 +252,13 @@ impl Ex {if let Some(f) = &sh.fill {fill_rule(&mut raw, &mut regenerated, f);}- set_principal(&mut raw, &[b"vsms", b"vmsk"], sh.psd_raw.as_ref());+ let (w, h) = (self.canvas.width(), self.canvas.height());+ crate::vector_map::shape_blocks(sh, &mut raw, w, h, self.dpi);}LayerContent::Text(t) => {- set_principal(&mut raw, &[b"TySh"], t.psd_raw.as_ref());+ // Text layers without PSD data (created here) get a generated TySh.+ let generated = t.psd_raw.is_none().then(|| std::sync::Arc::new(photocraft_text::psd::build_tysh(t, self.dpi, None)));+ set_principal(&mut raw, &[b"TySh"], t.psd_raw.as_ref().or(generated.as_ref()));if !raw.iter().any(|(k, _)| k == b"TySh") {self.warnings.push(format!("layer \"{}\": text layer written as pixels (no TySh data)", l.name));}@@ -266,9 +271,35 @@ impl Ex {}LayerContent::Raster(_) | LayerContent::Group(_) => {}}+ if !matches!(l.content, LayerContent::Shape(_)) {+ self.vector_mask_block(l, &mut raw);+ }regenerated.into_iter().chain(raw).map(|(k, d)| TaggedBlock::new(k, d)).collect()}+ /// Keeps, regenerates or removes the `vmsk`/`vsms` block of a non-shape layer.+ fn vector_mask_block(&mut self, l: &Layer, raw: &mut Vec<([u8; 4], Vec<u8>)>) {+ let (w, h) = (self.canvas.width(), self.canvas.height());+ let pos = raw.iter().position(|(k, _)| k == b"vsms" || k == b"vmsk");+ match (&l.vector_mask, pos) {+ (None, Some(_)) => raw.retain(|(k, _)| k != b"vsms" && k != b"vmsk"),+ (None, None) => {}+ (Some(vm), Some(i)) if crate::vector_map::vector_mask_block_matches(&raw[i].1, vm, w, h) => {}+ (Some(vm), pos) => {+ let data = crate::vector_map::vector_mask_bytes(vm, w, h);+ match pos {+ Some(i) => raw[i].1 = data,+ None => raw.push((*b"vmsk", data)),+ }+ }+ }+ if let Some(vm) = &l.vector_mask+ && (vm.density < 1.0 || vm.feather != 0.0)+ {+ self.warnings.push(format!("layer \"{}\": vector mask density/feather are not written to PSD", l.name));+ }+ }+/// Pixels for a fill layer: Photoshop's cached rendering while valid,/// otherwise our own rendering of the fill over the canvas.fn fill_pixels(&self, l: &Layer, f: &photocraft_doc::Fill) -> Surface {@@ -406,6 +437,7 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFilelet version = if opts.force_psb || big { Version::Psb } else { Version::Psd };let mut ex = Ex {fmt,+ dpi: doc.resolution_dpi,mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false),cc,cmyk: fmt.mode == ColorMode::Cmyk,@@ -505,6 +537,43 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFileresources.push(ImageResource::new(1006, pascal_names_resource(&names)));resources.push(ImageResource::new(1045, unicode_names_resource(&names)));}+ // Paths: saved paths (2000+), the work path (1025), the clipping path name (2999).+ {+ use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records};+ let (w, h) = (doc.size.width, doc.size.height);+ let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize;+ if doc.paths.len() > max {+ ex.warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped"));+ }+ for (i, p) in doc.paths.iter().take(max).enumerate() {+ let data = match &p.psd_raw {+ Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(),+ _ => path_to_records(&p.path, w, h).to_bytes(),+ };+ let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data);+ r.name = legacy_name(&p.name);+ resources.push(r);+ }+ if let Some(wp) = &doc.work_path {+ resources.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes()));+ }+ let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH);+ let raw_name = raw_clip.map(|(_, _, d)| {+ let n = usize::from(d.first().copied().unwrap_or(0));+ d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default()+ });+ if let Some(c) = &doc.clipping_path+ && raw_name.as_deref() != Some(c.name.as_str())+ {+ // Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs).+ let mut data = vec![0u8];+ let name = legacy_name(&c.name);+ data[0] = name.len() as u8;+ data.extend_from_slice(&name);+ data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes());+ resources.push(ImageResource::new(CLIPPING_PATH, data));+ }+ }if let Some(x) = &doc.metadata.xmp {resources.push(ImageResource::new(ids::XMP, x.as_bytes().to_vec()));}@@ -518,6 +587,14 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFileglobal_blocks.push(tb);}for (id, name, data) in &doc.metadata.psd_resources {+ // A preserved clipping-path resource is only valid while it names the current one.+ if *id == crate::vector_map::CLIPPING_PATH {+ let n = usize::from(data.first().copied().unwrap_or(0));+ let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();+ if doc.clipping_path.as_ref().is_none_or(|c| c.name != raw_name) {+ continue;+ }+ }let mut r = ImageResource::new(*id, data.to_vec());r.name = legacy_name(name);resources.push(r);diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex 783102252..66d591f45 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -48,6 +48,8 @@ pub(crate) struct Ctx<'a> {pub cc: usize,pub cmyk: bool,pub warnings: Vec<String>,+ /// Document resolution (type sizes are converted to points with it).+ pub dpi: f32,}fn doc_mode(m: PsdMode) -> Option<ColorMode> {@@ -198,16 +200,15 @@ impl Ctx<'_> {_ => adjust_map::Channels::Other,}))} else if rec.block(b"TySh").is_some() {- let (text, transform) = rec.block(b"TySh").and_then(|b| blocks::parse_tysh(&b.data)).unwrap_or_default();- LayerContent::Text(TextLayer {- text,- font_family: String::new(),- size_pt: 0.0,- color: photocraft_color::Color::BLACK,- transform,- cache: Some(self.record_surface(rec, &name)),- psd_raw: principal(b"TySh"),- })+ // Typed model from TySh/EngineData (photocraft-text); Photoshop's pixels stay the cache.+ let data = rec.block(b"TySh").map(|b| b.data.clone()).unwrap_or_default();+ let mut t = photocraft_text::psd::text_layer_from_tysh(&data, self.dpi).unwrap_or_else(|| {+ let (text, transform) = blocks::parse_tysh(&data).unwrap_or_default();+ TextLayer { text, transform, ..Default::default() }+ });+ t.cache = Some(self.record_surface(rec, &name));+ t.psd_raw = principal(b"TySh");+ LayerContent::Text(t)} else if let Some(k) = smart_key {let (id, transform) = rec.block(k).map(|b| blocks::parse_smart(k, &b.data)).unwrap_or_default();LayerContent::Smart(SmartObject {@@ -217,13 +218,12 @@ impl Ctx<'_> {cache: Some(self.record_surface(rec, &name)),psd_raw: principal(k),})- } else if (vector_key.is_some() && fill_key.is_some()) || rec.block(b"vscg").is_some() {+ } else if (vector_key.is_some() && (fill_key.is_some() || rec.block(b"vstk").is_some())) || rec.block(b"vscg").is_some() {let fill = fill_key.and_then(|k| rec.block(k).and_then(|b| blocks::parse_fill(k, &b.data)));- LayerContent::Shape(ShapeLayer {- fill,- cache: Some(self.record_surface(rec, &name)),- psd_raw: vector_key.and_then(principal),- })+ let mut sh = ShapeLayer { fill, cache: Some(self.record_surface(rec, &name)), psd_raw: vector_key.and_then(principal), ..Default::default() };+ let lookup = |k: &[u8; 4]| rec.block(k).map(|b| b.data.clone());+ crate::vector_map::shape_from_blocks(&mut sh, &lookup, self.file.header.width, self.file.header.height, self.dpi);+ LayerContent::Shape(sh)} else if let Some(k) = fill_key {match rec.block(k).and_then(|b| blocks::parse_fill(k, &b.data)) {Some(f) => {@@ -252,9 +252,30 @@ impl Ctx<'_> {if rendered && rec.layer_mask().is_some_and(|m| m.flags & 8 != 0) {l.mask = None;}+ if !matches!(l.content, LayerContent::Shape(_)) {+ self.apply_vector_mask(&mut l, rec);+ }l}+ /// Typed vector mask from `vsms`/`vmsk` (non-shape layers). A user mask that Photoshop+ /// rendered from the vector data (flag bit 3, no separate real mask) is dropped: the+ /// compositor rasterizes the vector mask itself.+ fn apply_vector_mask(&mut self, l: &mut Layer, rec: &LayerRecord) {+ let Some(b) = rec.block(b"vsms").or_else(|| rec.block(b"vmsk")) else { return };+ let Some(mut vm) = crate::vector_map::vector_mask_from_block(&b.data, self.file.header.width, self.file.header.height) else { return };+ if let Some(m) = rec.layer_mask() {+ if let Some(p) = m.parameters {+ vm.density = p.vector_density.map_or(1.0, |d| f32::from(d) / 255.0);+ vm.feather = p.vector_feather.map_or(0.0, |f| f as f32);+ }+ if m.flags & 8 != 0 && m.real.is_none() {+ l.mask = None;+ }+ }+ l.vector_mask = Some(vm);+ }+fn build(&mut self, nodes: &[LayerNode]) -> Vec<Layer> {let layers = self.file.layers();nodes@@ -269,6 +290,7 @@ impl Ctx<'_> {let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded }));l.psd_blocks = preserved_blocks(rec);self.apply_common(&mut l, rec, sd.and_then(|s| s.blend_mode));+ self.apply_vector_mask(&mut l, rec);l}})@@ -348,6 +370,26 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {}}}+ id if crate::vector_map::SAVED_PATHS.contains(&id) => {+ match crate::vector_map::path_from_resource(&r.data, h.width, h.height) {+ Some(path) => doc.paths.push(photocraft_doc::NamedPath {+ name: String::from_utf8_lossy(&r.name).into_owned(),+ path,+ psd_raw: Some(Arc::new(r.data.clone())),+ }),+ None => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone()))),+ }+ }+ crate::vector_map::WORK_PATH => {+ doc.work_path = crate::vector_map::path_from_resource(&r.data, h.width, h.height);+ }+ crate::vector_map::CLIPPING_PATH => {+ // Kept raw (layout beyond the name is not modelled); the name is exposed.+ let n = usize::from(r.data.first().copied().unwrap_or(0));+ let name = r.data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();+ doc.clipping_path = Some(photocraft_doc::ClippingPath { name, flatness: 0.0 });+ doc.metadata.psd_resources.push((r.id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone())));+ }id if MAPPED_RESOURCES.contains(&id) => {}id => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone()))),}@@ -365,6 +407,7 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {cc,cmyk: fmt.mode == ColorMode::Cmyk,warnings,+ dpi: doc.resolution_dpi,};let (w, hh) = (h.width as usize, h.height as usize);diff --git a/crates/io/src/vector_map.rs b/crates/io/src/vector_map.rsnew file mode 100644index 000000000..5e5953629--- /dev/null+++ b/crates/io/src/vector_map.rs@@ -0,0 +1,599 @@+//! Vector data ⇄ PSD: path records (vector masks `vmsk`/`vsms`, saved paths 2000–2997, the+//! work path 1025), live-shape origination (`vogk`), shape fill content (`vscg`) and shape+//! strokes (`vstk`).+//!+//! Export follows the "keep verbatim while unchanged" rule used for fills and adjustments:+//! a preserved block is written back byte-identical while it still decodes to the layer's+//! current model; otherwise it is regenerated from the model.++use photocraft_doc::{+ Fill, FillRule, Knot, LineCap, LineJoin, LiveShape, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath, VectorMask,+};+use photocraft_geom::Point;+use photocraft_psd::descriptor::{Descriptor, Id, Value, VersionedDescriptor};+use photocraft_psd::path::{PathData, PsdKnot, PsdSubpath, VectorMaskBlock};++use crate::blocks::{bool_of, enum_of, fill_from_desc, fill_to_desc, get_desc, num, parse_prefix_versioned};++/// Saved path resource ids (Adobe spec: 2000–2997).+pub const SAVED_PATHS: std::ops::RangeInclusive<u16> = 2000..=2997;+/// Work path resource id.+pub const WORK_PATH: u16 = 1025;+/// Clipping path name resource id.+pub const CLIPPING_PATH: u16 = 2999;++fn op_from_psd(v: i16) -> PathOp {+ match v {+ 0 => PathOp::Exclude,+ 2 => PathOp::Subtract,+ 3 => PathOp::Intersect,+ _ => PathOp::Combine,+ }+}++fn op_to_psd(op: PathOp) -> i16 {+ match op {+ PathOp::Combine => 1,+ PathOp::Subtract => 2,+ PathOp::Intersect => 3,+ PathOp::Exclude => 0,+ }+}++/// Path records → model path in document pixels (`w`×`h` canvas).+pub fn path_from_records(p: &PathData, w: u32, h: u32) -> Path {+ let (w, h) = (f64::from(w), f64::from(h));+ let pt = |q: (f64, f64)| Point::new(q.0 * w, q.1 * h);+ let subpaths = p+ .subpaths()+ .into_iter()+ .map(|s| Subpath {+ closed: s.closed,+ op: op_from_psd(s.operation),+ knots: s.knots.iter().map(|k| Knot { anchor: pt(k.anchor), in_ctrl: pt(k.pre), out_ctrl: pt(k.post), smooth: k.linked }).collect(),+ })+ .collect();+ Path { subpaths, fill_rule: FillRule::NonZero, inverted: p.initial_fill() }+}++/// Model path → path records.+pub fn path_to_records(p: &Path, w: u32, h: u32) -> PathData {+ let (w, h) = (f64::from(w.max(1)), f64::from(h.max(1)));+ let fr = |q: Point| (q.x / w, q.y / h);+ let subs: Vec<PsdSubpath> = p+ .subpaths+ .iter()+ .map(|s| PsdSubpath {+ closed: s.closed,+ operation: op_to_psd(s.op),+ knots: s.knots.iter().map(|k| PsdKnot { linked: k.smooth, pre: fr(k.in_ctrl), anchor: fr(k.anchor), post: fr(k.out_ctrl) }).collect(),+ })+ .collect();+ PathData::from_subpaths(&subs, p.inverted)+}++/// Path from a saved-path / work-path resource.+pub fn path_from_resource(data: &[u8], w: u32, h: u32) -> Option<Path> {+ PathData::from_bytes(data).ok().map(|p| path_from_records(&p, w, h))+}++/// A `vmsk`/`vsms` block → (path with the invert flag applied, flags).+pub fn path_from_vmsk(data: &[u8], w: u32, h: u32) -> Option<(Path, u32)> {+ let b = VectorMaskBlock::from_bytes(data).ok()?;+ let mut p = path_from_records(&b.path, w, h);+ if b.flags & VectorMaskBlock::FLAG_INVERT != 0 {+ p.inverted = !p.inverted;+ }+ Some((p, b.flags))+}++/// A `vmsk` block for `path` with extra flags (not linked / disabled).+pub fn vmsk_bytes(path: &Path, flags: u32, w: u32, h: u32) -> Vec<u8> {+ let mut p = path.clone();+ let mut flags = flags & !VectorMaskBlock::FLAG_INVERT;+ if p.inverted {+ flags |= VectorMaskBlock::FLAG_INVERT;+ p.inverted = false;+ }+ VectorMaskBlock { version: 3, flags, path: path_to_records(&p, w, h) }.to_bytes()+}++/// A layer's vector mask from its `vmsk`/`vsms` block.+pub fn vector_mask_from_block(data: &[u8], w: u32, h: u32) -> Option<VectorMask> {+ let (path, flags) = path_from_vmsk(data, w, h)?;+ Some(VectorMask {+ path,+ enabled: flags & VectorMaskBlock::FLAG_DISABLED == 0,+ linked: flags & VectorMaskBlock::FLAG_NOT_LINKED == 0,+ density: 1.0,+ feather: 0.0,+ })+}++/// `vmsk` data for a vector mask.+pub fn vector_mask_bytes(m: &VectorMask, w: u32, h: u32) -> Vec<u8> {+ let mut flags = 0;+ if !m.enabled {+ flags |= VectorMaskBlock::FLAG_DISABLED;+ }+ if !m.linked {+ flags |= VectorMaskBlock::FLAG_NOT_LINKED;+ }+ vmsk_bytes(&m.path, flags, w, h)+}++/// Compares the parts of a vector mask stored in the block (density/feather live elsewhere).+pub fn vector_mask_block_matches(data: &[u8], m: &VectorMask, w: u32, h: u32) -> bool {+ vector_mask_from_block(data, w, h).is_some_and(|b| b.path == m.path && b.enabled == m.enabled && b.linked == m.linked)+}++// ---------------------------------------------------------------------------+// vscg (shape fill content)+// ---------------------------------------------------------------------------++/// `vscg`: content key (`SoCo`/`GdFl`/`PtFl`) + version-16 descriptor.+pub fn fill_from_vscg(data: &[u8]) -> Option<Fill> {+ let key: [u8; 4] = data.get(..4)?.try_into().ok()?;+ let d = parse_prefix_versioned(data.get(4..)?)?;+ fill_from_desc(&key, &d)+}++pub fn vscg_bytes(f: &Fill) -> Vec<u8> {+ let (k, d) = fill_to_desc(f);+ let mut out = k.to_vec();+ out.extend(VersionedDescriptor::new(d).to_bytes());+ out+}++// ---------------------------------------------------------------------------+// vstk (shape stroke)+// ---------------------------------------------------------------------------++/// Decoded `vstk`: the stroke (None when disabled) and whether the fill is enabled.+#[derive(Clone, Debug, PartialEq)]+pub struct VstkInfo {+ pub stroke: Option<ShapeStroke>,+ pub fill_enabled: bool,+}++fn content_fill(d: &Descriptor) -> Option<Fill> {+ let key = match d.class_id.as_bytes() {+ b"solidColorLayer" => b"SoCo",+ b"gradientLayer" => b"GdFl",+ b"patternLayer" => b"PtFl",+ _ if d.get("Clr ").is_some() => b"SoCo",+ _ if d.get("Grad").is_some() => b"GdFl",+ _ => b"PtFl",+ };+ fill_from_desc(key, d)+}++fn unit_px(v: Option<&Value>, dpi: f32) -> Option<f64> {+ match v? {+ Value::UnitFloat { unit: [b'#', b'P', b'n', b't'], value } => Some(value * f64::from(dpi) / 72.0),+ Value::UnitFloat { unit: [b'#', b'M', b'l', b'm'], value } => Some(value * f64::from(dpi) / 25.4),+ other => num(Some(other)),+ }+}++pub fn parse_vstk(data: &[u8], dpi: f32) -> Option<VstkInfo> {+ let d = parse_prefix_versioned(data)?;+ let fill_enabled = !matches!(d.get("fillEnabled"), Some(Value::Boolean(false)));+ if !bool_of(&d, "strokeEnabled") {+ return Some(VstkInfo { stroke: None, fill_enabled });+ }+ let e = |k: &str| enum_of(&d, k).map(<[u8]>::to_vec).unwrap_or_default();+ let cap = match &e("strokeStyleLineCapType")[..] {+ b"strokeStyleRoundCap" => LineCap::Round,+ b"strokeStyleSquareCap" => LineCap::Square,+ _ => LineCap::Butt,+ };+ let join = match &e("strokeStyleLineJoinType")[..] {+ b"strokeStyleRoundJoin" => LineJoin::Round,+ b"strokeStyleBevelJoin" => LineJoin::Bevel,+ _ => LineJoin::Miter,+ };+ let align = match &e("strokeStyleLineAlignment")[..] {+ b"strokeStyleAlignInside" => StrokeAlign::Inside,+ b"strokeStyleAlignOutside" => StrokeAlign::Outside,+ _ => StrokeAlign::Center,+ };+ let dashes = match d.get("strokeStyleLineDashSet") {+ Some(Value::List(l)) => l.iter().filter_map(|v| num(Some(v))).map(|v| v as f32).collect(),+ _ => Vec::new(),+ };+ let paint = get_desc(&d, "strokeStyleContent").and_then(content_fill).unwrap_or(Fill::Solid(photocraft_color::Color::BLACK));+ let stroke = ShapeStroke {+ width: unit_px(d.get("strokeStyleLineWidth"), dpi).unwrap_or(1.0) as f32,+ paint,+ opacity: num(d.get("strokeStyleOpacity")).map_or(1.0, |v| v as f32 / 100.0),+ align,+ cap,+ join,+ miter_limit: num(d.get("strokeStyleMiterLimit")).unwrap_or(100.0) as f32,+ dashes,+ dash_offset: num(d.get("strokeStyleLineDashOffset")).unwrap_or(0.0) as f32,+ };+ Some(VstkInfo { stroke: Some(stroke), fill_enabled })+}++fn en(ty: &str, v: &str) -> Value {+ Value::Enumerated { type_id: Id::new(ty), value: Id::new(v) }+}++pub fn vstk_bytes(stroke: Option<&ShapeStroke>, fill_enabled: bool, dpi: f32) -> Vec<u8> {+ let default = ShapeStroke::default();+ let s = stroke.unwrap_or(&default);+ let (_, content) = fill_to_desc(&s.paint);+ let class = match s.paint {+ Fill::Solid(_) => "solidColorLayer",+ Fill::Gradient { .. } => "gradientLayer",+ Fill::Pattern { .. } => "patternLayer",+ };+ let content = Descriptor { class_id: Id::new(class), ..content };+ let d = Descriptor::new("strokeStyle")+ .with("strokeStyleVersion", Value::Integer(2))+ .with("strokeEnabled", Value::Boolean(stroke.is_some()))+ .with("fillEnabled", Value::Boolean(fill_enabled))+ .with("strokeStyleLineWidth", Value::UnitFloat { unit: *b"#Pxl", value: f64::from(s.width) })+ .with("strokeStyleLineDashOffset", Value::UnitFloat { unit: *b"#Pnt", value: f64::from(s.dash_offset) })+ .with("strokeStyleMiterLimit", Value::Double(f64::from(s.miter_limit)))+ .with(+ "strokeStyleLineCapType",+ en("strokeStyleLineCapType", match s.cap {+ LineCap::Butt => "strokeStyleButtCap",+ LineCap::Round => "strokeStyleRoundCap",+ LineCap::Square => "strokeStyleSquareCap",+ }),+ )+ .with(+ "strokeStyleLineJoinType",+ en("strokeStyleLineJoinType", match s.join {+ LineJoin::Miter => "strokeStyleMiterJoin",+ LineJoin::Round => "strokeStyleRoundJoin",+ LineJoin::Bevel => "strokeStyleBevelJoin",+ }),+ )+ .with(+ "strokeStyleLineAlignment",+ en("strokeStyleLineAlignment", match s.align {+ StrokeAlign::Inside => "strokeStyleAlignInside",+ StrokeAlign::Center => "strokeStyleAlignCenter",+ StrokeAlign::Outside => "strokeStyleAlignOutside",+ }),+ )+ .with("strokeStyleScaleLock", Value::Boolean(false))+ .with("strokeStyleStrokeAdjust", Value::Boolean(false))+ .with(+ "strokeStyleLineDashSet",+ Value::List(s.dashes.iter().map(|v| Value::UnitFloat { unit: *b"#Nne", value: f64::from(*v) }).collect()),+ )+ .with("strokeStyleBlendMode", en("BlnM", "Nrml"))+ .with("strokeStyleOpacity", Value::UnitFloat { unit: *b"#Prc", value: f64::from(s.opacity * 100.0) })+ .with("strokeStyleContent", Value::Descriptor(content))+ .with("strokeStyleResolution", Value::Double(f64::from(dpi)));+ VersionedDescriptor::new(d).to_bytes()+}++// ---------------------------------------------------------------------------+// vogk (live shape origination)+// ---------------------------------------------------------------------------++fn rect_of(d: &Descriptor) -> Option<[f64; 4]> {+ let b = get_desc(d, "keyOriginShapeBBox")?;+ let (t, l, bt, r) = (num(b.get("Top "))?, num(b.get("Left"))?, num(b.get("Btom"))?, num(b.get("Rght"))?);+ Some([l, t, r - l, bt - t])+}++fn point_of(d: &Descriptor, key: &str) -> Option<[f64; 2]> {+ let p = get_desc(d, key)?;+ Some([num(p.get("Hrzn"))?, num(p.get("Vrtc"))?])+}++/// Live shape from `vogk` (version 1 + versioned descriptor). Only a single, valid,+/// untransformed origination maps to a [`LiveShape`].+pub fn live_from_vogk(data: &[u8]) -> Option<LiveShape> {+ let d = parse_prefix_versioned(data.get(4..)?)?;+ let Some(Value::List(list)) = d.get("keyDescriptorList") else { return None };+ let [Value::Descriptor(o)] = &list[..] else { return None };+ if bool_of(o, "keyShapeInvalidated") {+ return None;+ }+ if let Some(t) = get_desc(o, "Trnf") {+ let g = |k: &str, dv: f64| num(t.get(k)).unwrap_or(dv);+ let ident = [("xx", 1.0), ("xy", 0.0), ("yx", 0.0), ("yy", 1.0), ("tx", 0.0), ("ty", 0.0)].iter().all(|(k, v)| (g(k, *v) - v).abs() < 1e-9);+ if !ident {+ return None;+ }+ }+ let ty = match o.get("keyOriginType") {+ Some(Value::Integer(i)) => *i,+ _ => return None,+ };+ match ty {+ 1 => Some(LiveShape::Rect { rect: rect_of(o)?, radii: [0.0; 4] }),+ 2 => {+ let r = get_desc(o, "keyOriginRRectRadii")?;+ let g = |k: &str| num(r.get(k)).unwrap_or(0.0);+ Some(LiveShape::Rect { rect: rect_of(o)?, radii: [g("topLeft"), g("topRight"), g("bottomRight"), g("bottomLeft")] })+ }+ 5 => Some(LiveShape::Ellipse { rect: rect_of(o)? }),+ 4 => Some(LiveShape::Line {+ from: point_of(o, "keyOriginLineStart")?,+ to: point_of(o, "keyOriginLineEnd")?,+ weight: num(o.get("keyOriginLineWeight")).unwrap_or(1.0),+ }),+ _ => None,+ }+}++fn px(v: f64) -> Value {+ Value::UnitFloat { unit: *b"#Pxl", value: v }+}++/// `vogk` for a live shape (None for kinds Photoshop has no origination type for here).+pub fn vogk_bytes(s: &LiveShape, dpi: f32) -> Option<Vec<u8>> {+ let bbox = |r: [f64; 4]| {+ Value::Descriptor(+ Descriptor::new("unitRect")+ .with("unitValueQuadVersion", Value::Integer(1))+ .with("Top ", px(r[1]))+ .with("Left", px(r[0]))+ .with("Btom", px(r[1] + r[3]))+ .with("Rght", px(r[0] + r[2])),+ )+ };+ let base = |ty: i32| Descriptor::new("null").with("keyOriginType", Value::Integer(ty)).with("keyOriginResolution", Value::Double(f64::from(dpi)));+ let o = match s {+ LiveShape::Rect { rect, radii } if radii.iter().all(|r| *r == 0.0) => base(1).with("keyOriginShapeBBox", bbox(*rect)),+ LiveShape::Rect { rect, radii } => base(2)+ .with(+ "keyOriginRRectRadii",+ Value::Descriptor(+ Descriptor::new("radii")+ .with("unitValueQuadVersion", Value::Integer(1))+ .with("topRight", px(radii[1]))+ .with("topLeft", px(radii[0]))+ .with("bottomLeft", px(radii[3]))+ .with("bottomRight", px(radii[2])),+ ),+ )+ .with("keyOriginShapeBBox", bbox(*rect)),+ LiveShape::Ellipse { rect } => base(5).with("keyOriginShapeBBox", bbox(*rect)),+ LiveShape::Line { from, to, weight } => {+ let pnt = |p: [f64; 2]| Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(p[0])).with("Vrtc", Value::Double(p[1])));+ let r = [from[0].min(to[0]), from[1].min(to[1]), (from[0] - to[0]).abs(), (from[1] - to[1]).abs()];+ base(4)+ .with("keyOriginShapeBBox", bbox(r))+ .with("keyOriginLineEnd", pnt(*to))+ .with("keyOriginLineStart", pnt(*from))+ .with("keyOriginLineWeight", Value::Double(*weight))+ .with("keyOriginLineArrowSt", Value::Boolean(false))+ .with("keyOriginLineArrowEnd", Value::Boolean(false))+ .with("keyOriginLineArrWdth", Value::Double(0.0))+ .with("keyOriginLineArrLngth", Value::Double(0.0))+ .with("keyOriginLineArrConc", Value::Integer(0))+ }+ LiveShape::Polygon { .. } => return None,+ };+ let o = o.with("keyOriginIndex", Value::Integer(0));+ let d = Descriptor::new("null").with("keyDescriptorList", Value::List(vec![Value::Descriptor(o)]));+ let mut out = 1u32.to_be_bytes().to_vec();+ out.extend(VersionedDescriptor::new(d).to_bytes());+ Some(out)+}++// ---------------------------------------------------------------------------+// Shape layers+// ---------------------------------------------------------------------------++/// Fills the typed parts of a shape layer from its PSD blocks.+pub fn shape_from_blocks(sh: &mut ShapeLayer, block: &dyn Fn(&[u8; 4]) -> Option<Vec<u8>>, w: u32, h: u32, dpi: f32) {+ if let Some(d) = block(b"vsms").or_else(|| block(b"vmsk"))+ && let Some((p, _)) = path_from_vmsk(&d, w, h)+ {+ sh.path = p;+ }+ if let Some(f) = block(b"vscg").and_then(|d| fill_from_vscg(&d)) {+ sh.fill = Some(f);+ }+ if let Some(v) = block(b"vstk").and_then(|d| parse_vstk(&d, dpi)) {+ sh.stroke = v.stroke;+ if !v.fill_enabled {+ sh.fill = None;+ }+ }+ sh.live = block(b"vogk").and_then(|d| live_from_vogk(&d));+}++fn has_fill_block(raw: &[([u8; 4], Vec<u8>)]) -> bool {+ raw.iter().any(|(k, d)| match k {+ b"vscg" => fill_from_vscg(d).is_some(),+ b"SoCo" | b"GdFl" | b"PtFl" => crate::blocks::parse_fill(k, d).is_some(),+ _ => false,+ })+}++/// Rewrites the vector blocks of a shape layer in `raw` (key, data) to match the model:+/// blocks that still decode to the model are kept byte-identical.+pub fn shape_blocks(sh: &ShapeLayer, raw: &mut Vec<([u8; 4], Vec<u8>)>, w: u32, h: u32, dpi: f32) {+ let find = |raw: &Vec<([u8; 4], Vec<u8>)>, k: &[u8; 4]| raw.iter().position(|(key, _)| key == k);+ // Path.+ let pos = find(raw, b"vsms").or_else(|| find(raw, b"vmsk"));+ let from_raw = |d: &[u8]| path_from_vmsk(d, w, h).map(|(p, _)| p);+ let keep = |d: &[u8]| from_raw(d).as_ref() == Some(&sh.path);+ match pos {+ Some(i) if keep(&raw[i].1) => {}+ _ => {+ // The layer's own raw copy may still be valid (psd_raw is the principal block).+ let data = match &sh.psd_raw {+ Some(r) if keep(r) => r.to_vec(),+ _ => vmsk_bytes(&sh.path, 0, w, h),+ };+ match pos {+ Some(i) => raw[i].1 = data,+ None => raw.push((*b"vmsk", data)),+ }+ }+ }+ // Fill content.+ if let Some(f) = &sh.fill {+ match find(raw, b"vscg") {+ Some(i) if fill_from_vscg(&raw[i].1).as_ref() == Some(f) => {}+ Some(i) => raw[i].1 = vscg_bytes(f),+ None => {}+ }+ }+ // Photoshop shapes always carry fill content, even with the fill turned off.+ let present = raw.iter().any(|(k, _)| matches!(k, b"vscg" | b"SoCo" | b"GdFl" | b"PtFl"));+ if sh.fill.is_none() && !present {+ raw.push((*b"vscg", vscg_bytes(&Fill::Solid(photocraft_color::Color::BLACK))));+ }+ // Stroke (+ fill enabled flag). A fill we could not decode counts as unchanged.+ let undecodable_fill = sh.fill.is_none() && present && !has_fill_block(raw);+ let same = |v: &VstkInfo| v.stroke == sh.stroke && (v.fill_enabled == sh.fill.is_some() || (v.fill_enabled && undecodable_fill));+ match find(raw, b"vstk") {+ Some(i) if parse_vstk(&raw[i].1, dpi).as_ref().is_some_and(same) => {}+ Some(i) => raw[i].1 = vstk_bytes(sh.stroke.as_ref(), sh.fill.is_some(), dpi),+ // "No fill" needs a vstk only when a fill block would otherwise paint.+ None if sh.stroke.is_some() || (sh.fill.is_none() && has_fill_block(raw)) => {+ raw.push((*b"vstk", vstk_bytes(sh.stroke.as_ref(), sh.fill.is_some(), dpi)));+ }+ None => {}+ }+ // Live shape origination.+ let pos = find(raw, b"vogk");+ let current = pos.and_then(|i| live_from_vogk(&raw[i].1));+ if current != sh.live || (pos.is_none() && sh.live.is_some()) {+ let generated = sh.live.as_ref().and_then(|l| vogk_bytes(l, dpi));+ match (pos, generated) {+ (Some(i), Some(g)) => raw[i].1 = g,+ (Some(i), None) => {+ raw.remove(i);+ }+ (None, Some(g)) => raw.push((*b"vogk", g)),+ (None, None) => {}+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_color::Color;++ fn sample_path() -> Path {+ let mut p = Path::new(vec![+ Subpath {+ closed: true,+ op: PathOp::Combine,+ knots: vec![+ Knot::corner(10.0, 10.0),+ Knot::smooth(Point::new(50.0, 20.0), Point::new(40.0, 10.0), Point::new(60.0, 30.0)),+ Knot::corner(20.0, 40.0),+ ],+ },+ Subpath::polyline(&[(1.0, 2.0), (3.0, 4.0)]).with_op(PathOp::Subtract),+ ]);+ p.inverted = false;+ p+ }++ #[test]+ fn path_records_roundtrip() {+ let p = sample_path();+ let rec = path_to_records(&p, 64, 64);+ let back = path_from_records(&rec, 64, 64);+ assert_eq!(back, p);+ for op in [PathOp::Combine, PathOp::Subtract, PathOp::Intersect, PathOp::Exclude] {+ assert_eq!(op_from_psd(op_to_psd(op)), op);+ }+ assert_eq!(op_from_psd(-1), PathOp::Combine);+ }++ #[test]+ fn vector_mask_roundtrip_with_flags() {+ let mut m = VectorMask::new(sample_path());+ m.enabled = false;+ m.linked = false;+ m.path.inverted = true;+ let b = vector_mask_bytes(&m, 64, 64);+ let back = vector_mask_from_block(&b, 64, 64).unwrap();+ assert_eq!(back, m);+ assert!(vector_mask_block_matches(&b, &m, 64, 64));+ }++ #[test]+ fn vstk_roundtrip() {+ let s = ShapeStroke {+ width: 4.5,+ paint: Fill::Solid(Color::rgb(1.0, 0.0, 0.0)),+ opacity: 0.5,+ align: StrokeAlign::Outside,+ cap: LineCap::Round,+ join: LineJoin::Bevel,+ miter_limit: 10.0,+ dashes: vec![2.0, 1.0],+ dash_offset: 0.5,+ };+ let b = vstk_bytes(Some(&s), false, 72.0);+ let v = parse_vstk(&b, 72.0).unwrap();+ assert!(!v.fill_enabled);+ let got = v.stroke.unwrap();+ assert_eq!(got.width, s.width);+ assert_eq!((got.cap, got.join, got.align), (s.cap, s.join, s.align));+ assert_eq!(got.dashes, s.dashes);+ match got.paint {+ Fill::Solid(c) => assert!((c.to_rgb()[0] - 1.0).abs() < 1e-3),+ other => panic!("{other:?}"),+ }+ let off = parse_vstk(&vstk_bytes(None, true, 72.0), 72.0).unwrap();+ assert!(off.stroke.is_none() && off.fill_enabled);+ }++ #[test]+ fn vogk_roundtrip() {+ for s in [+ LiveShape::Rect { rect: [1.0, 2.0, 30.0, 40.0], radii: [0.0; 4] },+ LiveShape::Rect { rect: [1.0, 2.0, 30.0, 40.0], radii: [1.0, 2.0, 3.0, 4.0] },+ LiveShape::Ellipse { rect: [5.0, 6.0, 7.0, 8.0] },+ LiveShape::Line { from: [0.0, 10.0], to: [20.0, 0.0], weight: 3.0 },+ ] {+ let b = vogk_bytes(&s, 72.0).unwrap();+ assert_eq!(live_from_vogk(&b), Some(s));+ }+ assert!(vogk_bytes(&LiveShape::Polygon { rect: [0.0; 4], sides: 5, star_ratio: 1.0 }, 72.0).is_none());+ }++ #[test]+ fn shape_blocks_keep_unchanged_and_regenerate_changed() {+ let sh = ShapeLayer {+ path: sample_path(),+ fill: Some(Fill::Solid(Color::rgb(0.0, 1.0, 0.0))),+ stroke: Some(ShapeStroke::default()),+ live: Some(LiveShape::Ellipse { rect: [0.0, 0.0, 10.0, 10.0] }),+ ..Default::default()+ };+ let mut raw = Vec::new();+ shape_blocks(&sh, &mut raw, 64, 64, 72.0);+ let keys: Vec<&[u8; 4]> = raw.iter().map(|(k, _)| k).collect();+ assert_eq!(keys, [b"vmsk", b"vstk", b"vogk"]);+ let before = raw.clone();+ shape_blocks(&sh, &mut raw, 64, 64, 72.0);+ assert_eq!(raw, before);+ let mut back = ShapeLayer::default();+ let lookup = |k: &[u8; 4]| raw.iter().find(|(key, _)| key == k).map(|(_, d)| d.clone());+ shape_from_blocks(&mut back, &lookup, 64, 64, 72.0);+ assert_eq!(back.path, sh.path);+ assert_eq!(back.stroke, sh.stroke);+ assert_eq!(back.live, sh.live);+ // Edit: path changes → vmsk regenerated, live dropped when polygon.+ let mut edited = sh.clone();+ edited.path.subpaths.pop();+ edited.live = Some(LiveShape::Polygon { rect: [0.0; 4], sides: 3, star_ratio: 1.0 });+ shape_blocks(&edited, &mut raw, 64, 64, 72.0);+ assert!(!raw.iter().any(|(k, _)| k == b"vogk"));+ let (p, _) = path_from_vmsk(&raw[0].1, 64, 64).unwrap();+ assert_eq!(p, edited.path);+ }+}diff --git a/crates/io/tests/psd_structure.rs b/crates/io/tests/psd_structure.rsindex 09c21f63e..6d3fc62fe 100644--- a/crates/io/tests/psd_structure.rs+++ b/crates/io/tests/psd_structure.rs@@ -162,8 +162,8 @@ fn testgen_import_details() {assert!(d.icc_profile.is_some());assert!((d.resolution_dpi - 72.0).abs() < 1e-3);assert!(d.metadata.xmp.is_some());- // Unmapped named resource preserved.- assert!(d.metadata.psd_resources.iter().any(|r| r.0 == 2000 && r.1 == "Path 1"));+ // Named saved-path resource (2000) becomes a document path, raw bytes kept for export.+ assert!(d.paths.iter().any(|p| p.name == "Path 1" && p.psd_raw.as_deref() == Some(&vec![1u8, 2, 3])));// Global blocks preserved.assert!(d.metadata.psd_global_blocks.iter().any(|b| &b.1 == b"Patt"));// lfx2 kept on effects.diff --git a/crates/io/tests/roundtrip.rs b/crates/io/tests/roundtrip.rsindex dfbf8abb4..9013c8ecf 100644--- a/crates/io/tests/roundtrip.rs+++ b/crates/io/tests/roundtrip.rs@@ -107,9 +107,14 @@ fn text_shape_smart_raw_blocks_survive() {}),);smart.psd_blocks = vec![(*b"PlLd", Arc::new(vec![0; 4])), (*b"vmsk", Arc::new(vec![5; 8])), (*b"luni", Arc::new(vec![0; 8]))];+ // The typed vector mask (as import produces it) keeps the raw block while unchanged.+ smart.vector_mask = photocraft_io::vector_map::vector_mask_from_block(&[5; 8], d.size.width, d.size.height);d.layers.push(smart);- let mut shape = Layer::new("Shape", LayerContent::Shape(ShapeLayer { fill: None, cache: Some(cache.clone()), psd_raw: None }));+ let mut shape = Layer::new("Shape", LayerContent::Shape(ShapeLayer { fill: None, cache: Some(cache.clone()), psd_raw: None, ..Default::default() }));shape.psd_blocks = vec![(*b"vscg", Arc::new(vec![1, 2, 3, 4])), (*b"vmsk", Arc::new(vec![7; 8]))];+ if let LayerContent::Shape(s) = &mut shape.content {+ s.path = photocraft_io::vector_map::path_from_vmsk(&[7; 8], d.size.width, d.size.height).unwrap().0;+ }d.layers.push(shape);let back = roundtrip(&d);let n = back.layers.len();@@ -134,8 +139,10 @@ fn raster_layer_blocks_preserved() {let mut d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS);let blocks = vec![(*b"vmsk", std::sync::Arc::new(vec![0u8; 12])), (*b"clbl", std::sync::Arc::new(vec![0u8, 0, 0, 0])), (*b"Zzzz", std::sync::Arc::new(vec![1u8]))];d.layers[1].psd_blocks = blocks.clone();+ d.layers[1].vector_mask = photocraft_io::vector_map::vector_mask_from_block(&[0; 12], d.size.width, d.size.height);let back = roundtrip(&d);assert_eq!(back.layers[1].psd_blocks, blocks);+ assert_eq!(back.layers[1].vector_mask, d.layers[1].vector_mask);}#[test]@@ -209,6 +216,7 @@ fn text_layer_roundtrip_with_tysh() {transform: photocraft_geom::Affine { m: [1.0, 0.0, 0.0, 1.0, 3.0, 4.0] },cache: Some(pattern(fmt, photocraft_geom::Rect::new(3, 4, 9, 8), 5, true)),psd_raw: Some(std::sync::Arc::new(tysh)),+ ..Default::default()}),));let back = roundtrip(&d);diff --git a/crates/io/tests/text_corpus.rs b/crates/io/tests/text_corpus.rsnew file mode 100644index 000000000..4eb273537--- /dev/null+++ b/crates/io/tests/text_corpus.rs@@ -0,0 +1,265 @@+//! Type layers in the optional real-file corpus (`corpus/psd`, gitignored; skips if absent).+//!+//! For every text layer: the TySh/EngineData model must parse (text, fonts, sizes, colours,+//! runs), the `TySh` must survive a PSD round trip byte-for-byte, and our engine's re-render is+//! compared with Photoshop's cached pixels. The fonts usually differ, so the comparison checks+//! geometry (ink bounds and alpha overlap) and is reported; the assertions are loose.++use std::path::{Path, PathBuf};++use photocraft_doc::{Layer, LayerContent};+use photocraft_geom::Rect;+use photocraft_raster::Surface;++fn collect(dir: &Path, out: &mut Vec<PathBuf>) {+ let Ok(rd) = std::fs::read_dir(dir) else {+ return;+ };+ for e in rd.flatten() {+ let p = e.path();+ if p.is_dir() {+ collect(&p, out);+ } else if p+ .extension()+ .and_then(|e| e.to_str())+ .is_some_and(|e| e.eq_ignore_ascii_case("psd") || e.eq_ignore_ascii_case("psb"))+ {+ out.push(p);+ }+ }+}++fn walk<'a>(layers: &'a [Layer], out: &mut Vec<&'a Layer>) {+ for l in layers {+ out.push(l);+ if let Some(ch) = l.children() {+ walk(ch, out);+ }+ }+}++fn alpha(s: &Surface, r: Rect) -> Vec<f32> {+ let n = s.channels();+ s.read_region(r).chunks_exact(n).map(|p| p[n - 1]).collect()+}++#[test]+fn corpus_text_layers() {+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd");+ if !root.is_dir() {+ return;+ }+ let mut files = Vec::new();+ collect(&root, &mut files);+ files.sort();+ let mut engine = photocraft_text::TextEngine::with_system_fonts();+ let (mut n, mut good_geometry) = (0, 0);+ for f in files {+ let bytes = std::fs::read(&f).unwrap();+ if !bytes.windows(4).any(|w| w == b"TySh") {+ continue;+ }+ let name = f.file_name().unwrap().to_string_lossy().to_string();+ let Ok(imp) = photocraft_io::import(&name, &bytes) else {+ continue;+ };+ let doc = imp.document;+ let mut all = Vec::new();+ walk(&doc.layers, &mut all);+ for l in all {+ let LayerContent::Text(t) = &l.content else {+ continue;+ };+ n += 1;+ assert!(t.psd_raw.is_some());+ assert!(+ !t.runs.is_empty(),+ "{name}/{}: no style runs parsed",+ l.name+ );+ assert_eq!(+ t.runs+ .iter()+ .map(|r| r.len)+ .sum::<usize>()+ .min(t.text.len()),+ t.text.len(),+ "{name}/{}: runs cover text",+ l.name+ );+ let st = &t.runs[0].style;+ assert!(+ st.size_pt > 0.0 && st.postscript_name.is_some(),+ "{name}/{}: {st:?}",+ l.name+ );+ // Round trip of the model through our own TySh writer.+ let rebuilt = photocraft_text::psd::build_tysh(t, doc.resolution_dpi, None);+ let back =+ photocraft_text::psd::text_layer_from_tysh(&rebuilt, doc.resolution_dpi).unwrap();+ assert_eq!(back.text, t.text);+ assert_eq!(back.char_runs(), t.char_runs(), "{name}/{}", l.name);+ assert_eq!(+ back.paragraph_runs(),+ t.paragraph_runs(),+ "{name}/{}",+ l.name+ );+ assert_eq!(back.shape, t.shape);++ // Geometry vs Photoshop's pixels.+ let Some(ps) = &t.cache else { continue };+ let ps_rect = ps.content_bounds();+ let (_, ours) = engine.render(t, doc.resolution_dpi, doc.pixel_format());+ let our_rect = ours.surface.content_bounds();+ let u = Rect::new(+ ps_rect.x0.min(our_rect.x0),+ ps_rect.y0.min(our_rect.y0),+ ps_rect.x1.max(our_rect.x1),+ ps_rect.y1.max(our_rect.y1),+ );+ let (a, b) = (alpha(ps, u), alpha(&ours.surface, u));+ let inter: f32 = a.iter().zip(&b).map(|(x, y)| x.min(*y)).sum();+ let union: f32 = a.iter().zip(&b).map(|(x, y)| x.max(*y)).sum();+ let iou = if union > 0.0 { inter / union } else { 1.0 };+ let h = ps_rect.height().max(1) as f32;+ let dy = ((ps_rect.y0 + ps_rect.y1) - (our_rect.y0 + our_rect.y1)) as f32 / 2.0;+ let dx0 = (ps_rect.x0 - our_rect.x0) as f32;+ let dh = our_rect.height() as f32 / h;+ let ok = dy.abs() <= 0.25 * h && dx0.abs() <= 0.5 * h && (0.6..1.6).contains(&dh);+ good_geometry += usize::from(ok);+ println!(+ "{name:40} {:12} {:24} {:>6.1}pt {:?} ps={:?} ours={:?} iou={iou:.2} dy={dy:+.1} dx0={dx0:+.1} h×{dh:.2} {}",+ l.name,+ st.postscript_name.as_deref().unwrap_or(""),+ st.size_pt,+ t.shape,+ (ps_rect.x0, ps_rect.y0, ps_rect.width(), ps_rect.height()),+ (+ our_rect.x0,+ our_rect.y0,+ our_rect.width(),+ our_rect.height()+ ),+ if ok { "ok" } else { "GEOMETRY OFF" }+ );+ }+ }+ println!("text layers: {n}, geometry within tolerance: {good_geometry}");+ if n > 0 {+ assert!(+ good_geometry * 2 >= n,+ "most text layers should land where Photoshop drew them"+ );+ }+}++/// Unedited text layers are written back byte-for-byte.+#[test]+fn corpus_tysh_lossless() {+ let root = Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../corpus/psd/ag-psd/read-write/text/src.psd");+ let Ok(bytes) = std::fs::read(&root) else {+ return;+ };+ let doc = photocraft_io::import("src.psd", &bytes).unwrap().document;+ let out = photocraft_io::export(&doc, "out.psd", &Default::default())+ .unwrap()+ .bytes;+ let find = |b: &[u8]| {+ let i = b.windows(8).position(|w| w == b"8BIMTySh").unwrap();+ let len = u32::from_be_bytes(b[i + 8..i + 12].try_into().unwrap()) as usize;+ b[i + 12..i + 12 + len].to_vec()+ };+ assert_eq!(find(&bytes), find(&out));+}++/// A text layer created in Photocraft (no PSD data) exports as an editable type layer and+/// imports back with the same model.+#[test]+fn created_text_layer_roundtrips_through_psd() {+ use photocraft_color::{Color, ColorMode, SampleType};+ use photocraft_doc::text::{+ CharStyle, ParagraphRun, ParagraphStyle, TextAlign, TextRun, TextShape,+ };+ use photocraft_doc::{Document, Size, TextLayer};+ let mut doc = Document::new("t", Size::new(120, 80), ColorMode::Rgb, SampleType::U8);+ doc.resolution_dpi = 144.0;+ let a = CharStyle {+ font_family: "Inter".into(),+ size_pt: 10.0,+ color: Color::rgb(0.2, 0.4, 0.6),+ ..Default::default()+ };+ let b = CharStyle {+ faux_bold: true,+ underline: true,+ tracking: 50.0,+ leading_pt: Some(14.0),+ ..a.clone()+ };+ let mut t = TextLayer {+ text: "Größe\nzwei".into(),+ runs: vec![TextRun { len: 3, style: a }, TextRun { len: 9, style: b }],+ paragraphs: vec![+ ParagraphRun {+ len: 7,+ style: ParagraphStyle {+ align: TextAlign::Center,+ space_after_pt: 3.0,+ ..Default::default()+ },+ },+ ParagraphRun {+ len: 5,+ style: ParagraphStyle {+ align: TextAlign::JustifyAll,+ ..Default::default()+ },+ },+ ],+ shape: TextShape::Box {+ x: 0.0,+ y: 0.0,+ width: 100.0,+ height: 60.0,+ },+ transform: photocraft_geom::Affine::translate(8.0, 6.0),+ ..Default::default()+ };+ t.sync_summary();+ photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format());+ doc.layers.push(photocraft_doc::Layer::new(+ "t",+ LayerContent::Text(t.clone()),+ ));+ let out = photocraft_io::export(&doc, "t.psd", &Default::default()).unwrap();+ assert!(+ !out.warnings.iter().any(|w| w.contains("text layer")),+ "{:?}",+ out.warnings+ );+ let back = photocraft_io::import("t.psd", &out.bytes).unwrap().document;+ let LayerContent::Text(bt) = &back.layers[0].content else {+ panic!("not text")+ };+ let strip = |v: Vec<photocraft_doc::text::TextRun>| {+ v.into_iter()+ .map(|mut r| {+ r.style.postscript_name = None;+ r.style.color.c = r.style.color.c.map(|c| (c * 1000.0).round() / 1000.0);+ r+ })+ .collect::<Vec<_>>()+ };+ assert_eq!(bt.text, t.text);+ assert_eq!(strip(bt.char_runs()), strip(t.char_runs()));+ assert_eq!(bt.paragraph_runs(), t.paragraph_runs());+ assert_eq!(bt.shape, t.shape);+ assert_eq!(bt.transform, t.transform);+ assert!(+ bt.cache+ .as_ref()+ .is_some_and(|c| c.content_bounds().width() > 10)+ );+}diff --git a/crates/io/tests/vector.rs b/crates/io/tests/vector.rsnew file mode 100644index 000000000..fce237880--- /dev/null+++ b/crates/io/tests/vector.rs@@ -0,0 +1,264 @@+//! Vector data ⇄ PSD: synthetic round trips of paths, shape layers and vector masks, plus an+//! optional corpus check (`corpus/psd`, skipped when absent) that compares our rasterization+//! of every plain shape layer with the pixels Photoshop stored for it.++use std::path::{Path as FsPath, PathBuf};+use std::sync::Arc;++use photocraft_color::{Color, ColorMode, SampleType};+use photocraft_doc::{+ Document, Fill, Knot, Layer, LayerContent, LineCap, LineJoin, LiveShape, NamedPath, Path, PathOp, ShapeLayer, ShapeStroke,+ Size, StrokeAlign, Subpath, VectorMask,+};+use photocraft_geom::{Point, Rect};+use photocraft_io::*;+use photocraft_psd::PsdFile;++fn roundtrip(d: &Document) -> Document {+ let r = export(d, "x.psd", &ExportOptions::default()).unwrap();+ import("x.psd", &r.bytes).unwrap().document+}++/// Coordinates on a 64-px grid are exact in PSD's 8.24 fixed point for a 256-px canvas.+fn path() -> Path {+ Path::new(vec![+ Subpath {+ closed: true,+ op: PathOp::Combine,+ knots: vec![+ Knot::corner(16.0, 16.0),+ Knot::smooth(Point::new(128.0, 32.0), Point::new(96.0, 16.0), Point::new(160.0, 48.0)),+ Knot::corner(64.0, 192.0),+ ],+ },+ Subpath::polygon(&[(32.0, 32.0), (64.0, 32.0), (64.0, 64.0)]).with_op(PathOp::Subtract),+ Subpath::polyline(&[(200.0, 10.0), (250.0, 60.0)]).with_op(PathOp::Exclude),+ ])+}++fn doc() -> Document {+ Document::with_background("v", Size::new(256, 256), ColorMode::Rgb, SampleType::U8, Color::WHITE)+}++fn shape_layer(sh: ShapeLayer) -> Layer {+ let mut sh = sh;+ sh.cache = Some(photocraft_vector::render_shape(&sh, photocraft_color::PixelFormat::RGBA8, Rect::new(0, 0, 256, 256)));+ Layer::new("Shape", LayerContent::Shape(sh))+}++#[test]+fn saved_paths_work_path_and_clipping_roundtrip() {+ let mut d = doc();+ d.paths.push(NamedPath { name: "Outline".into(), path: path(), psd_raw: None });+ let mut inv = path();+ inv.inverted = true;+ d.paths.push(NamedPath { name: "Inverted".into(), path: inv, psd_raw: None });+ d.work_path = Some(Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (128.0, 0.0), (128.0, 128.0)])]));+ d.clipping_path = Some(photocraft_doc::ClippingPath { name: "Outline".into(), flatness: 0.0 });+ let b = roundtrip(&d);+ assert_eq!(b.paths.len(), 2);+ assert_eq!(b.paths[0].name, "Outline");+ assert_eq!(b.paths[0].path, d.paths[0].path);+ assert_eq!(b.paths[1].path, d.paths[1].path);+ assert_eq!(b.work_path, d.work_path);+ assert_eq!(b.clipping_path.as_ref().map(|c| c.name.as_str()), Some("Outline"));+ // Unedited paths are written back byte-identical; edited ones are regenerated.+ let raw0 = b.paths[0].psd_raw.clone().unwrap();+ let mut b2 = b.clone();+ b2.paths[1].path.subpaths.pop();+ let c = roundtrip(&b2);+ assert_eq!(c.paths[0].psd_raw.as_deref(), Some(&*raw0));+ assert_eq!(c.paths[1].path, b2.paths[1].path);+ // Removing the clipping path drops the preserved resource.+ let mut b3 = c.clone();+ b3.clipping_path = None;+ assert!(roundtrip(&b3).clipping_path.is_none());+}++#[test]+fn shape_layer_typed_roundtrip() {+ let mut d = doc();+ let sh = ShapeLayer {+ path: path(),+ fill: Some(Fill::Solid(Color::rgb(1.0, 0.0, 0.0))),+ stroke: Some(ShapeStroke {+ width: 4.0,+ paint: Fill::Solid(Color::rgb(0.0, 0.0, 1.0)),+ opacity: 0.5,+ align: StrokeAlign::Inside,+ cap: LineCap::Round,+ join: LineJoin::Round,+ miter_limit: 100.0,+ dashes: vec![2.0, 1.0],+ dash_offset: 0.0,+ }),+ live: None,+ ..Default::default()+ };+ d.layers.push(shape_layer(sh.clone()));+ let mut ell = ShapeLayer {+ path: photocraft_vector::shapes::ellipse(64.0, 64.0, 128.0, 64.0),+ fill: None,+ stroke: Some(ShapeStroke::default()),+ live: Some(LiveShape::Ellipse { rect: [64.0, 64.0, 128.0, 64.0] }),+ ..Default::default()+ };+ ell.path.subpaths[0].op = PathOp::Combine;+ d.layers.push(shape_layer(ell.clone()));+ let b = roundtrip(&d);+ let LayerContent::Shape(s) = &b.layers[1].content else { panic!("not a shape") };+ assert_eq!(s.path, sh.path);+ assert_eq!(s.fill, sh.fill);+ let st = s.stroke.as_ref().unwrap();+ let want = sh.stroke.as_ref().unwrap();+ assert_eq!((st.width, st.align, st.cap, st.join, &st.dashes), (want.width, want.align, want.cap, want.join, &want.dashes));+ assert!((st.opacity - 0.5).abs() < 1e-6);+ assert!(s.cache.is_some());+ let LayerContent::Shape(e) = &b.layers[2].content else { panic!() };+ assert_eq!(e.fill, None);+ assert_eq!(e.live, ell.live);+ // Kappa handles are quantized to PSD's 8.24 fixed point (1/65536 of 256 px).+ let pts = |p: &Path| p.subpaths.iter().flat_map(|s| s.knots.iter().flat_map(|k| [k.anchor, k.in_ctrl, k.out_ctrl])).collect::<Vec<_>>();+ for (a, b) in pts(&e.path).iter().zip(pts(&ell.path)) {+ assert!((a.x - b.x).abs() < 1e-4 && (a.y - b.y).abs() < 1e-4);+ }+ // A second round trip keeps every vector block byte-identical.+ let c = roundtrip(&b);+ for i in 1..3 {+ let keys = |l: &Layer| l.psd_blocks.iter().filter(|(k, _)| matches!(k, b"vmsk" | b"vsms" | b"vstk" | b"vogk" | b"vscg" | b"SoCo")).cloned().collect::<Vec<_>>();+ assert_eq!(keys(&c.layers[i]), keys(&b.layers[i]), "layer {i}");+ }+}++#[test]+fn vector_mask_roundtrip_and_removal() {+ let mut d = doc();+ let mut l = Layer::raster("pix", d.pixel_format());+ l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 256, 256), &[0.0, 0.0, 0.0, 1.0]);+ let mut vm = VectorMask::new(Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (128.0, 0.0), (128.0, 256.0), (0.0, 256.0)])]));+ vm.linked = false;+ l.vector_mask = Some(vm.clone());+ d.layers.push(l);+ let b = roundtrip(&d);+ assert_eq!(b.layers[1].vector_mask.as_ref(), Some(&vm));+ assert!(b.layers[1].psd_blocks.iter().any(|(k, _)| k == b"vmsk"));+ // The composite honours it (left half black, right half white).+ let f = photocraft_compose::flatten(&b);+ assert!(f.get(10, 10)[0] < 0.01 && f.get(200, 10)[0] > 0.99);+ // Removing the vector mask removes the block.+ let mut c = b.clone();+ c.layers[1].vector_mask = None;+ let e = roundtrip(&c);+ assert!(e.layers[1].vector_mask.is_none());+ assert!(!e.layers[1].psd_blocks.iter().any(|(k, _)| k == b"vmsk" || k == b"vsms"));+ // Groups carry vector masks too.+ let mut g = doc();+ let mut grp = Layer::group("G", vec![Layer::raster("in", g.pixel_format())]);+ grp.vector_mask = Some(vm);+ g.layers.push(grp);+ assert!(roundtrip(&g).layers[1].vector_mask.is_some());+}++fn collect(dir: &FsPath, out: &mut Vec<PathBuf>) {+ let Ok(rd) = std::fs::read_dir(dir) else { return };+ for e in rd.flatten() {+ let p = e.path();+ if p.is_dir() {+ collect(&p, out);+ } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("psd") || e.eq_ignore_ascii_case("psb")) {+ out.push(p);+ }+ }+}++/// Every plain shape layer in the corpus (solid fill, no stroke, no effects, visible fill):+/// our fill coverage vs the alpha of Photoshop's pixels. Reported; asserted loosely.+#[test]+fn corpus_shape_coverage_matches_photoshop() {+ let root = FsPath::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd");+ if !root.is_dir() {+ return;+ }+ let mut files = Vec::new();+ collect(&root, &mut files);+ files.sort();+ let (mut n, mut good) = (0, 0);+ for p in &files {+ let name = p.strip_prefix(&root).unwrap_or(p).display().to_string();+ let bytes = std::fs::read(p).unwrap_or_default();+ let Ok(file) = PsdFile::from_bytes(&bytes) else { continue };+ let (d, _) = psd_to_document(&file);+ for (_, _, l) in d.walk() {+ let LayerContent::Shape(sh) = &l.content else { continue };+ let Some(cache) = &sh.cache else { continue };+ if sh.stroke.is_some() || !matches!(sh.fill, Some(Fill::Solid(_))) || !l.effects.items.is_empty() || sh.path.is_empty() {+ continue;+ }+ let r = cache.content_bounds().union(&photocraft_vector::fill_rasterizer(&sh.path, 0.01).pixel_bounds().unwrap_or(Rect::EMPTY)).intersect(&d.bounds());+ if r.is_empty() {+ continue;+ }+ let ours = photocraft_vector::path_coverage(&sh.path, r);+ let mut theirs = vec![[0.0f32; 4]; ours.len()];+ cache.read_rgba_into(r, &mut theirs);+ let (mut inter, mut uni, mut max) = (0.0f64, 0.0f64, 0.0f32);+ for (a, b) in ours.iter().zip(&theirs) {+ inter += f64::from(a.min(b[3]));+ uni += f64::from(a.max(b[3]));+ max = max.max((a - b[3]).abs());+ }+ let iou = inter / uni.max(1e-9);+ n += 1;+ if iou > 0.97 {+ good += 1;+ }+ eprintln!("{name:<55} {:<20} IoU {iou:.4} max {max:.3} subpaths {}", l.name.chars().take(20).collect::<String>(), sh.path.subpaths.len());+ }+ }+ eprintln!("vector corpus: {good}/{n} plain shape layers with IoU > 0.97");+ assert!(n == 0 || good * 10 >= n * 9, "{good}/{n}");+}++/// (layer name, block key, data).+type NamedBlock = (String, [u8; 4], Arc<Vec<u8>>);++/// Unedited corpus shapes and vector masks export with byte-identical vector blocks.+#[test]+fn corpus_vector_blocks_survive_roundtrip() {+ let root = FsPath::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd");+ if !root.is_dir() {+ return;+ }+ let mut files = Vec::new();+ collect(&root, &mut files);+ files.sort();+ let keys: [&[u8; 4]; 6] = [b"vmsk", b"vsms", b"vogk", b"vstk", b"vscg", b"SoCo"];+ let mut checked = 0;+ for p in &files {+ let bytes = std::fs::read(p).unwrap_or_default();+ let Ok(file) = PsdFile::from_bytes(&bytes) else { continue };+ let (d, _) = psd_to_document(&file);+ let Ok(out) = export(&d, "x.psd", &ExportOptions::default()) else { continue };+ let back = PsdFile::from_bytes(&out.bytes).unwrap();+ let blocks = |f: &PsdFile| -> Vec<NamedBlock> {+ f.layers()+ .iter()+ .flat_map(|l| {+ let n = l.name();+ l.blocks.iter().filter(|b| keys.contains(&&b.key)).map(move |b| (n.clone(), b.key, Arc::new(b.data.clone())))+ })+ .collect()+ };+ let (a, b) = (blocks(&file), blocks(&back));+ checked += a.len();+ let summary = |v: &[NamedBlock]| v.iter().map(|(n, k, d)| format!("{n}/{}:{}", String::from_utf8_lossy(k), d.len())).collect::<Vec<_>>();+ for x in &a {+ assert!(b.contains(x), "{}: {}/{} changed or missing; before {:?} after {:?}", p.display(), x.0, String::from_utf8_lossy(&x.1), summary(&a), summary(&b));+ }+ // Saved paths too.+ for r in file.resources.iter().filter(|r| (2000..=2997).contains(&r.id)) {+ assert!(back.resources.iter().any(|q| q.id == r.id && q.data == r.data), "{}: path resource {}", p.display(), r.id);+ }+ }+ eprintln!("vector corpus: {checked} vector blocks byte-identical after round trip");+}diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rsindex 7ac110183..328803175 100644--- a/crates/ops/src/lib.rs+++ b/crates/ops/src/lib.rs@@ -84,6 +84,17 @@ impl History {self.undo.iter().map(|s| s.label.clone()).chain(std::iter::once(self.current_label.clone())).collect()}+ /// Document of past entry `i`, indexed like [`History::entries`] (0 = oldest). The last entry is+ /// the current document, which the history does not hold, so it (and any index past it) is `None`.+ pub fn state(&self, i: usize) -> Option<Arc<Document>> {+ self.undo.get(i).map(|s| s.doc.clone())+ }++ /// Number of past states (entries before the current one).+ pub fn past_len(&self) -> usize {+ self.undo.len()+ }+pub fn clear(&mut self) {self.undo.clear();self.redo.clear();@@ -149,6 +160,19 @@ mod tests {assert!(h.redo(cur.clone()).is_none());}+ #[test]+ fn state_accessor_matches_entries() {+ let mut h = History::default();+ let mut cur = Arc::new(base());+ let open = cur.clone();+ edit(&mut h, &mut cur, "A", |d| d.name = "a".into());+ edit(&mut h, &mut cur, "B", |d| d.name = "b".into());+ assert_eq!(h.entries().len(), h.past_len() + 1);+ assert!(Arc::ptr_eq(&h.state(0).unwrap(), &open));+ assert_eq!(h.state(1).unwrap().name, "a");+ assert!(h.state(2).is_none(), "the current document is not held");+ }+#[test]fn new_edit_clears_redo() {let mut h = History::default();diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rsindex 1caef9d70..45ca276cd 100644--- a/crates/paint/src/lib.rs+++ b/crates/paint/src/lib.rs@@ -7,9 +7,11 @@#![forbid(unsafe_code)]use photocraft_geom::{Point, Rect};-use photocraft_raster::{Surface, from_rgba, to_rgba};+use photocraft_raster::{Surface, to_rgba};use serde::{Deserialize, Serialize};+pub mod retouch;+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]pub struct StrokePoint {pub x: f64,@@ -128,40 +130,19 @@ pub fn dab_coverage(d: f32, radius: f32, hardness: f32) -> f32 {/// Returns the damaged rectangle.pub fn apply_stroke(target: &mut Surface, stroke: &Stroke, selection: Option<&Surface>, lock_transparency: bool) -> Rect {let b = &stroke.brush;- let ds = dabs(stroke);- if ds.is_empty() {+ if stroke.points.is_empty() {return Rect::EMPTY;}- let bounds = ds.iter().fold(Rect::EMPTY, |r, d| {- let rr = d.radius.ceil() as i32 + 1;- r.union(&Rect::new(d.center.x as i32 - rr, d.center.y as i32 - rr, d.center.x as i32 + rr + 1, d.center.y as i32 + rr + 1))- });- // Accumulate stroke coverage (max-combined dabs × flow), then composite once at stroke opacity.+ // Accumulate stroke coverage (dabs × flow build up), then composite once at stroke opacity.+ let (bounds, cov) = retouch::stroke_coverage(stroke);let w = bounds.width() as usize;- let mut cov = vec![0.0f32; w * bounds.height() as usize];- for d in &ds {- let rr = d.radius.ceil() as i32 + 1;- let (cx, cy) = (d.center.x as f32, d.center.y as f32);- for y in (d.center.y as i32 - rr)..=(d.center.y as i32 + rr) {- for x in (d.center.x as i32 - rr)..=(d.center.x as i32 + rr) {- if !bounds.contains(x, y) {- continue;- }- let dist = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();- let c = dab_coverage(dist, d.radius, b.hardness) * d.alpha;- let i = (y - bounds.y0) as usize * w + (x - bounds.x0) as usize;- // flow build-up within the stroke, capped at 1- cov[i] = cov[i] + c * (1.0 - cov[i]);- }- }- }let fmt = target.format();let mut region = target.read_region(bounds);let n = fmt.channels();for (i, c) in cov.iter().enumerate() {let x = bounds.x0 + (i % w) as i32;let y = bounds.y0 + (i / w) as i32;- let sel = selection.map_or(1.0, |s| s.pixel(x, y)[0]);+ let sel = selection.map_or(1.0, |s| s.sample_channel(x, y, 0));let k = (c * b.opacity * sel).min(1.0);if k <= 0.0 {continue;@@ -185,7 +166,8 @@ pub fn apply_stroke(target: &mut Surface, stroke: &Stroke, selection: Option<&Su}o};- let enc = from_rgba(&fmt, out);+ let mut enc = [0.0f32; 8];+ photocraft_raster::from_rgba_into(&fmt, out, &mut enc);px.copy_from_slice(&enc[..n]);}target.write_region(bounds, ®ion);diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rsnew file mode 100644index 000000000..e5b5807e1--- /dev/null+++ b/crates/paint/src/retouch.rs@@ -0,0 +1,435 @@+//! Generic dab-driven stroke machinery for the retouching tools (Clone Stamp, Healing Brush, Spot+//! Healing, Dodge/Burn/Sponge, Blur/Sharpen, Smudge, History Brush).+//!+//! Two stroke shapes cover every retouching tool:+//!+//! * **Accumulate, then composite** ([`stroke_coverage`] + [`apply_coverage`]): the stroke's dabs build+//! up one coverage map (flow builds up, capped at 1), and a *paint image* computed once from the+//! pre-stroke state (a cloned source, a healed patch, an earlier history state…) is composited+//! through it at the stroke's opacity. Pixels painted earlier in the same stroke are never re-sampled.+//! * **Sequential dabs** ([`apply_dab_stroke`]): each dab edits a working copy in place (so dab *n*+//! sees the result of dab *n − 1*, as Dodge, Blur or Smudge need), and the finished working copy is+//! mixed back at the stroke's opacity.+//!+//! All pixel data here is the surface's *native* channels as normalised `f32` (any depth, any colour+//! model); colour-space-specific work happens in the callbacks.++use photocraft_color::{BlendMode, PixelFormat};+use photocraft_geom::Rect;+use photocraft_raster::{Surface, from_rgba_into, to_rgba};++use crate::{Dab, Stroke, dab_coverage, dabs};++/// A rectangle of native-channel pixels (`rect.width() × rect.height() × ch` floats, row-major).+#[derive(Clone, Debug, PartialEq)]+pub struct Region {+ pub rect: Rect,+ pub ch: usize,+ pub data: Vec<f32>,+}++impl Region {+ /// A zeroed region.+ pub fn new(rect: Rect, ch: usize) -> Self {+ Self { rect, ch, data: vec![0.0; rect.width() as usize * rect.height() as usize * ch] }+ }+ /// Read `rect` from a surface.+ pub fn read(s: &Surface, rect: Rect) -> Self {+ Self { rect, ch: s.channels(), data: s.read_region(rect) }+ }+ pub fn width(&self) -> usize {+ self.rect.width() as usize+ }+ pub fn height(&self) -> usize {+ self.rect.height() as usize+ }+ /// Pixel index of document coordinate `(x, y)` (must lie inside `rect`).+ #[inline]+ pub fn index(&self, x: i32, y: i32) -> usize {+ (y - self.rect.y0) as usize * self.width() + (x - self.rect.x0) as usize+ }+ #[inline]+ pub fn px(&self, x: i32, y: i32) -> &[f32] {+ let i = self.index(x, y) * self.ch;+ &self.data[i..i + self.ch]+ }+ #[inline]+ pub fn px_mut(&mut self, x: i32, y: i32) -> &mut [f32] {+ let i = self.index(x, y) * self.ch;+ let n = self.ch;+ &mut self.data[i..i + n]+ }+ /// Copy of the sub-rectangle `r` (clipped to this region).+ pub fn crop(&self, r: Rect) -> Region {+ let r = r.intersect(&self.rect);+ let mut out = Region::new(r, self.ch);+ let (w, n) = (r.width() as usize, self.ch);+ for y in r.y0..r.y1 {+ let s = self.index(r.x0, y) * n;+ let d = (y - r.y0) as usize * w * n;+ out.data[d..d + w * n].copy_from_slice(&self.data[s..s + w * n]);+ }+ out+ }+ /// Write this region into a surface.+ pub fn write(&self, s: &mut Surface) {+ s.write_region(self.rect, &self.data);+ }+}++/// One dab's footprint: coverage (hardness falloff × dab alpha) over its bounding rectangle.+#[derive(Clone, Debug, PartialEq)]+pub struct Footprint {+ pub dab: Dab,+ /// Position of the dab in the stroke (0 = first).+ pub index: usize,+ pub rect: Rect,+ /// `rect.width() × rect.height()` coverage values in 0..1 (already multiplied by flow/pressure).+ pub cov: Vec<f32>,+}++impl Footprint {+ #[inline]+ pub fn at(&self, x: i32, y: i32) -> f32 {+ self.cov[(y - self.rect.y0) as usize * self.rect.width() as usize + (x - self.rect.x0) as usize]+ }+}++/// Bounding rectangle of a dab (1 px of anti-aliasing slack included).+pub fn dab_rect(d: &Dab) -> Rect {+ let rr = d.radius.ceil() as i32 + 1;+ let (cx, cy) = (d.center.x.floor() as i32, d.center.y.floor() as i32);+ Rect::new(cx - rr, cy - rr, cx + rr + 1, cy + rr + 1)+}++/// Rasterize one dab's coverage.+pub fn footprint(d: &Dab, index: usize, hardness: f32) -> Footprint {+ let rect = dab_rect(d);+ let (cx, cy) = (d.center.x as f32, d.center.y as f32);+ let mut cov = Vec::with_capacity(rect.width() as usize * rect.height() as usize);+ for y in rect.y0..rect.y1 {+ for x in rect.x0..rect.x1 {+ let dist = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();+ cov.push(dab_coverage(dist, d.radius, hardness) * d.alpha);+ }+ }+ Footprint { dab: *d, index, rect, cov }+}++/// Union of the dabs' rectangles.+pub fn stroke_bounds(ds: &[Dab]) -> Rect {+ ds.iter().fold(Rect::EMPTY, |r, d| r.union(&dab_rect(d)))+}++/// Accumulated coverage of a whole stroke: dabs build up (`c ← c + d·(1 − c)`, "flow"), capped at 1.+/// Returns the stroke bounds and `width × height` coverage values.+pub fn stroke_coverage(stroke: &Stroke) -> (Rect, Vec<f32>) {+ let ds = dabs(stroke);+ let bounds = stroke_bounds(&ds);+ let w = bounds.width() as usize;+ let mut cov = vec![0.0f32; w * bounds.height() as usize];+ for (i, d) in ds.iter().enumerate() {+ let fp = footprint(d, i, stroke.brush.hardness);+ let fw = fp.rect.width() as usize;+ for y in fp.rect.y0..fp.rect.y1 {+ for x in fp.rect.x0..fp.rect.x1 {+ let c = fp.cov[(y - fp.rect.y0) as usize * fw + (x - fp.rect.x0) as usize];+ let o = &mut cov[(y - bounds.y0) as usize * w + (x - bounds.x0) as usize];+ *o += c * (1.0 - *o);+ }+ }+ }+ (bounds, cov)+}++/// Index of the alpha channel, if the format has one.+#[inline]+pub fn alpha_index(fmt: &PixelFormat) -> Option<usize> {+ fmt.alpha.then(|| fmt.mode.color_channels())+}++/// Normal-mode "source over destination" at coverage `k`, in native channels (colour channels are+/// channel-agnostic, so this works for RGB, Gray, CMYK, Lab… at any depth).+#[inline]+pub fn over_native(fmt: &PixelFormat, dst: &mut [f32], src: &[f32], k: f32, lock_transparency: bool) {+ match alpha_index(fmt) {+ Some(a) => {+ let (da, sa) = (dst[a], src[a] * k);+ let oa = sa + da * (1.0 - sa);+ if oa > 0.0 {+ for c in 0..a {+ dst[c] = (src[c] * sa + dst[c] * da * (1.0 - sa)) / oa;+ }+ }+ if !lock_transparency {+ dst[a] = oa;+ }+ }+ None => {+ for c in 0..dst.len() {+ dst[c] += (src[c] - dst[c]) * k;+ }+ }+ }+}++/// Composite a paint image through a coverage map onto `target`.+///+/// `paint` must cover `rect`; `cov` has one value per pixel of `rect`. The per-pixel weight is+/// `cov × opacity × selection`. Non-normal blend modes composite in straight RGBA (W3C formula).+#[allow(clippy::too_many_arguments)]+pub fn apply_coverage(+ target: &mut Surface,+ rect: Rect,+ cov: &[f32],+ opacity: f32,+ selection: Option<&Surface>,+ lock_transparency: bool,+ paint: &Region,+ blend: BlendMode,+) -> Rect {+ if rect.is_empty() {+ return Rect::EMPTY;+ }+ let fmt = target.format();+ let n = fmt.channels();+ let mut region = target.read_region(rect);+ let w = rect.width() as usize;+ let a = alpha_index(&fmt);+ for (i, c) in cov.iter().enumerate() {+ let x = rect.x0 + (i % w) as i32;+ let y = rect.y0 + (i / w) as i32;+ let sel = selection.map_or(1.0, |s| s.sample_channel(x, y, 0));+ let k = (c * opacity * sel).min(1.0);+ if k <= 0.0 {+ continue;+ }+ let px = &mut region[i * n..(i + 1) * n];+ if lock_transparency && a.is_some_and(|a| px[a] <= 0.0) {+ continue;+ }+ let src = paint.px(x, y);+ if blend == BlendMode::Normal {+ over_native(&fmt, px, src, k, lock_transparency);+ } else {+ let d = to_rgba(&fmt, px);+ let s = to_rgba(&fmt, src);+ let mut o = photocraft_color::blend::composite(blend, d, s, k);+ if lock_transparency {+ o[3] = d[3];+ }+ let mut enc = [0.0f32; 8];+ from_rgba_into(&fmt, o, &mut enc);+ px.copy_from_slice(&enc[..n]);+ }+ }+ target.write_region(rect, ®ion);+ rect+}++/// Run a sequential-dab stroke: `effect(work, footprint)` edits the working copy for each dab in+/// order; the result is mixed back at `stroke.brush.opacity × selection`.+///+/// The working copy covers the stroke bounds grown by `halo` pixels so neighbourhood effects (blur,+/// sharpen) can read around each dab; only the stroke bounds are written back. With+/// `lock_transparency`, alpha is preserved. Returns the damaged rectangle.+pub fn apply_dab_stroke(+ target: &mut Surface,+ stroke: &Stroke,+ selection: Option<&Surface>,+ lock_transparency: bool,+ halo: i32,+ mut effect: impl FnMut(&mut Region, &Footprint),+) -> Rect {+ let ds = dabs(stroke);+ if ds.is_empty() {+ return Rect::EMPTY;+ }+ let bounds = stroke_bounds(&ds);+ let outer = Rect::new(bounds.x0 - halo, bounds.y0 - halo, bounds.x1 + halo, bounds.y1 + halo);+ let orig = Region::read(target, outer);+ let mut work = orig.clone();+ for (i, d) in ds.iter().enumerate() {+ effect(&mut work, &footprint(d, i, stroke.brush.hardness));+ }+ let fmt = target.format();+ let a = alpha_index(&fmt);+ let mut out = orig.crop(bounds);+ let n = out.ch;+ let opacity = stroke.brush.opacity.clamp(0.0, 1.0);+ for y in bounds.y0..bounds.y1 {+ for x in bounds.x0..bounds.x1 {+ let k = opacity * selection.map_or(1.0, |s| s.sample_channel(x, y, 0));+ if k <= 0.0 {+ continue;+ }+ let wv = work.px(x, y);+ let i = out.index(x, y) * n;+ let o = &mut out.data[i..i + n];+ for c in 0..n {+ if lock_transparency && Some(c) == a {+ continue;+ }+ o[c] += (wv[c] - o[c]) * k;+ }+ }+ }+ out.write(target);+ bounds+}++/// Smudge state: a colour buffer carried from dab to dab (centred on the dab), which is laid down at+/// `strength` and then re-picks-up the pixels under the dab. Use with [`apply_dab_stroke`].+#[derive(Clone, Debug)]+pub struct Smudge {+ /// 0..1: how much carried colour each dab lays down (and keeps).+ pub strength: f32,+ /// Finger painting: start the stroke with this native-channel colour instead of the pixels under+ /// the first dab.+ pub finger: Option<Vec<f32>>,+ radius: i32,+ carry: Option<Vec<f32>>,+}++impl Smudge {+ pub fn new(strength: f32, finger: Option<Vec<f32>>, max_brush_size: f32) -> Self {+ Self { strength: strength.clamp(0.0, 1.0), finger, radius: (max_brush_size / 2.0).ceil() as i32 + 2, carry: None }+ }++ /// Apply one dab to the working copy.+ pub fn dab(&mut self, work: &mut Region, fp: &Footprint) {+ let (r, n) = (self.radius, work.ch);+ let side = (2 * r + 1) as usize;+ let (cx, cy) = (fp.dab.center.x.floor() as i32, fp.dab.center.y.floor() as i32);+ let wr = work.rect;+ let clamp_px = |work: &Region, x: i32, y: i32| -> Vec<f32> { work.px(x.clamp(wr.x0, wr.x1 - 1), y.clamp(wr.y0, wr.y1 - 1)).to_vec() };+ let carry = self.carry.get_or_insert_with(|| {+ let mut c = vec![0.0f32; side * side * n];+ for qy in 0..side {+ for qx in 0..side {+ let v = match &self.finger {+ Some(f) => f.clone(),+ None => clamp_px(work, cx + qx as i32 - r, cy + qy as i32 - r),+ };+ c[(qy * side + qx) * n..(qy * side + qx + 1) * n].copy_from_slice(&v[..n]);+ }+ }+ c+ });+ // Lay down the carried colour.+ for y in fp.rect.y0.max(wr.y0)..fp.rect.y1.min(wr.y1) {+ for x in fp.rect.x0.max(wr.x0)..fp.rect.x1.min(wr.x1) {+ let k = fp.at(x, y) * self.strength;+ let (qx, qy) = (x - cx + r, y - cy + r);+ if k <= 0.0 || qx < 0 || qy < 0 || qx >= side as i32 || qy >= side as i32 {+ continue;+ }+ let q = (qy as usize * side + qx as usize) * n;+ let px = work.px_mut(x, y);+ for c in 0..n {+ px[c] += (carry[q + c] - px[c]) * k;+ }+ }+ }+ // Pick up: the carried colour keeps `strength` of itself.+ let keep = self.strength;+ for qy in 0..side {+ for qx in 0..side {+ let (x, y) = (cx + qx as i32 - r, cy + qy as i32 - r);+ if !wr.contains(x, y) {+ continue;+ }+ let q = (qy * side + qx) * n;+ let px = work.px(x, y);+ for c in 0..n {+ carry[q + c] = carry[q + c] * keep + px[c] * (1.0 - keep);+ }+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{BrushSettings, StrokePoint};++ fn stroke(points: &[(f64, f64)], size: f32, hardness: f32) -> Stroke {+ Stroke {+ brush: BrushSettings { size, hardness, spacing: 0.25, pressure_size: false, ..Default::default() },+ points: points.iter().map(|&(x, y)| StrokePoint { x, y, pressure: 1.0 }).collect(),+ }+ }++ #[test]+ fn coverage_matches_apply_stroke_bounds() {+ let st = stroke(&[(10.0, 10.0), (40.0, 12.0)], 8.0, 1.0);+ let (r, cov) = stroke_coverage(&st);+ assert!(r.contains(10, 10) && r.contains(40, 12));+ let w = r.width() as usize;+ assert!((cov[(10 - r.y0) as usize * w + (25 - r.x0) as usize] - 1.0).abs() < 1e-6);+ assert!(cov.iter().all(|c| (0.0..=1.0).contains(c)));+ }++ #[test]+ fn coverage_composite_copies_exactly_at_full_hardness() {+ for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::CMYKA8, PixelFormat::GRAYA8] {+ let mut s = Surface::new(fmt);+ s.fill_rect(Rect::new(0, 0, 64, 64), &vec![0.2; fmt.channels()].iter().enumerate().map(|(i, v)| if i + 1 == fmt.channels() { 1.0 } else { *v }).collect::<Vec<_>>());+ let st = stroke(&[(20.0, 20.0)], 10.0, 1.0);+ let (r, cov) = stroke_coverage(&st);+ let mut paint = Region::new(r, fmt.channels());+ let n = fmt.channels();+ paint.data.iter_mut().enumerate().for_each(|(i, v)| *v = if fmt.alpha && i % n == n - 1 { 1.0 } else { 0.8 });+ apply_coverage(&mut s, r, &cov, 1.0, None, false, &paint, BlendMode::Normal);+ let p = s.pixel(20, 20);+ assert!(p[..n - 1].iter().all(|v| (v - 0.8).abs() < 1e-2) && p[n - 1] == 1.0, "{fmt:?} {p:?}");+ assert!((s.pixel(40, 40)[0] - 0.2).abs() < 1e-2);+ }+ }++ #[test]+ fn dab_stroke_runs_sequentially_and_respects_selection() {+ let mut s = Surface::new(PixelFormat::GRAY8);+ let mut sel = Surface::new(PixelFormat::GRAY8);+ sel.fill_rect(Rect::new(0, 0, 30, 100), &[1.0]);+ let st = stroke(&[(10.0, 10.0), (50.0, 10.0)], 6.0, 1.0);+ let mut seen = Vec::new();+ apply_dab_stroke(&mut s, &st, Some(&sel), false, 2, |work, fp| {+ seen.push(fp.index);+ for y in fp.rect.y0..fp.rect.y1 {+ for x in fp.rect.x0..fp.rect.x1 {+ if fp.at(x, y) > 0.5 {+ work.px_mut(x, y)[0] += 0.1;+ }+ }+ }+ });+ assert!(seen.windows(2).all(|w| w[1] == w[0] + 1));+ assert!(s.pixel(20, 10)[0] > 0.1, "dabs accumulate");+ assert_eq!(s.pixel(40, 10)[0], 0.0, "outside the selection untouched");+ }++ #[test]+ fn smudge_drags_colour_along_the_stroke() {+ for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] {+ let mut s = Surface::new(fmt);+ s.fill_rect(Rect::new(0, 0, 100, 40), &[1.0, 1.0, 1.0, 1.0]);+ s.fill_rect(Rect::new(0, 0, 30, 40), &[1.0, 0.0, 0.0, 1.0]);+ let st = stroke(&[(20.0, 20.0), (70.0, 20.0)], 12.0, 1.0);+ let mut sm = Smudge::new(0.8, None, 12.0);+ apply_dab_stroke(&mut s, &st, None, false, 0, |w, fp| sm.dab(w, fp));+ // Red dragged to the right of the edge, fading with distance.+ let g = |x| s.pixel(x, 20)[1];+ assert!(g(35) < 0.5, "{fmt:?} {}", g(35));+ assert!(g(35) < g(60), "{fmt:?}");+ assert_eq!(s.pixel(35, 35)[1], 1.0, "off-stroke untouched");+ // Finger painting starts with the given colour.+ let mut s2 = Surface::new(fmt);+ s2.fill_rect(Rect::new(0, 0, 100, 40), &[1.0, 1.0, 1.0, 1.0]);+ let mut fg = Smudge::new(0.8, Some(vec![0.0, 0.0, 1.0, 1.0]), 12.0);+ apply_dab_stroke(&mut s2, &st, None, false, 0, |w, fp| fg.dab(w, fp));+ assert!(s2.pixel(22, 20)[0] < 0.5);+ }+ }+}diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rsindex 7fcd0ce0e..ddc7baa61 100644--- a/crates/psd/src/lib.rs+++ b/crates/psd/src/lib.rs@@ -49,6 +49,7 @@ pub mod header;pub mod image_data;mod io;pub mod layer;+pub mod path;pub mod pixels;pub mod resources;pub mod tagged;diff --git a/crates/psd/src/path.rs b/crates/psd/src/path.rsnew file mode 100644index 000000000..1ed24ade3--- /dev/null+++ b/crates/psd/src/path.rs@@ -0,0 +1,308 @@+//! Path records: saved paths (image resources 2000–2997), the work path+//! (resource 1025) and vector masks (`vmsk` / `vsms` layer blocks).+//!+//! Implemented from the public Adobe "Photoshop File Formats Specification",+//! section "Path resource format": a path is a list of 26-byte records, each a+//! 2-byte selector followed by 24 bytes of data. Knot coordinates are signed+//! 8.24 fixed-point fractions of the document height (vertical) and width+//! (horizontal), stored vertical first.+//!+//! Undocumented detail (as documented by the MIT-licensed psd-tools): bytes+//! 2–3 of a subpath length record's data (after the knot count) hold the+//! *path operation* of the subpath (`-1` or `1` combine/or, `2` subtract,+//! `3` intersect, `0` exclude/xor). Everything else is kept raw, so parsing+//! and writing a record list is byte-exact.++use crate::error::{PsdError, Result};++/// Length of one path record in bytes (selector + data).+pub const RECORD_LEN: usize = 26;++/// Record selectors (spec table "Path data record types").+pub mod selector {+ /// Closed subpath length record.+ pub const CLOSED_LENGTH: u16 = 0;+ /// Closed subpath Bézier knot, linked.+ pub const CLOSED_KNOT_LINKED: u16 = 1;+ /// Closed subpath Bézier knot, unlinked.+ pub const CLOSED_KNOT_UNLINKED: u16 = 2;+ /// Open subpath length record.+ pub const OPEN_LENGTH: u16 = 3;+ /// Open subpath Bézier knot, linked.+ pub const OPEN_KNOT_LINKED: u16 = 4;+ /// Open subpath Bézier knot, unlinked.+ pub const OPEN_KNOT_UNLINKED: u16 = 5;+ /// Path fill rule record.+ pub const FILL_RULE: u16 = 6;+ /// Clipboard record.+ pub const CLIPBOARD: u16 = 7;+ /// Initial fill rule record.+ pub const INITIAL_FILL: u16 = 8;+}++/// One 26-byte path record, kept raw.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct PathRecord {+ /// Record type (see [`selector`]).+ pub selector: u16,+ /// The 24 data bytes.+ pub data: [u8; 24],+}++impl PathRecord {+ fn u16_at(&self, at: usize) -> u16 {+ u16::from_be_bytes([self.data[at], self.data[at + 1]])+ }+ fn i32_at(&self, at: usize) -> i32 {+ i32::from_be_bytes([self.data[at], self.data[at + 1], self.data[at + 2], self.data[at + 3]])+ }+ /// Whether this is a (closed or open) subpath length record.+ pub fn is_length(&self) -> bool {+ matches!(self.selector, selector::CLOSED_LENGTH | selector::OPEN_LENGTH)+ }+ /// Whether this is a Bézier knot record.+ pub fn is_knot(&self) -> bool {+ matches!(self.selector, 1 | 2 | 4 | 5)+ }+}++/// A Bézier knot as fractions of the document size: `(x, y)` pairs.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PsdKnot {+ /// Linked (smooth) knot: the control points move together.+ pub linked: bool,+ /// Control point preceding the anchor (`(x, y)` fractions).+ pub pre: (f64, f64),+ /// Anchor point.+ pub anchor: (f64, f64),+ /// Control point leaving the anchor.+ pub post: (f64, f64),+}++/// A subpath: its knots, closed flag and path operation.+#[derive(Clone, Debug, PartialEq)]+pub struct PsdSubpath {+ /// Closed subpath.+ pub closed: bool,+ /// Path operation (bytes 2–3 of the length record data): `-1`/`1`+ /// combine, `2` subtract, `3` intersect, `0` exclude.+ pub operation: i16,+ /// Knots in order.+ pub knots: Vec<PsdKnot>,+}++/// Fixed 8.24 → fraction.+pub fn fixed_to_f64(v: i32) -> f64 {+ f64::from(v) / 16_777_216.0+}++/// Fraction → fixed 8.24 (rounded, saturating).+pub fn f64_to_fixed(v: f64) -> i32 {+ (v * 16_777_216.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32+}++/// A parsed path record list.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct PathData {+ /// Records in file order.+ pub records: Vec<PathRecord>,+}++impl PathData {+ /// Parses path records. Trailing bytes shorter than a record are ignored.+ pub fn from_bytes(data: &[u8]) -> Result<Self> {+ if data.len() / RECORD_LEN > 4_000_000 {+ return Err(PsdError::LimitExceeded("path records"));+ }+ let records = data+ .chunks_exact(RECORD_LEN)+ .map(|c| {+ let mut d = [0u8; 24];+ d.copy_from_slice(&c[2..]);+ PathRecord { selector: u16::from_be_bytes([c[0], c[1]]), data: d }+ })+ .collect();+ Ok(PathData { records })+ }++ /// Serializes the records.+ pub fn to_bytes(&self) -> Vec<u8> {+ let mut out = Vec::with_capacity(self.records.len() * RECORD_LEN);+ for r in &self.records {+ out.extend_from_slice(&r.selector.to_be_bytes());+ out.extend_from_slice(&r.data);+ }+ out+ }++ /// Initial fill rule: `true` when the path starts with all pixels filled+ /// (inverted path).+ pub fn initial_fill(&self) -> bool {+ self.records.iter().find(|r| r.selector == selector::INITIAL_FILL).is_some_and(|r| r.u16_at(0) != 0)+ }++ /// Subpaths with their knots. Knot records not preceded by a length+ /// record, or beyond a length record's count, start/extend a subpath+ /// leniently instead of failing.+ pub fn subpaths(&self) -> Vec<PsdSubpath> {+ let mut out: Vec<PsdSubpath> = Vec::new();+ let mut remaining = 0usize;+ for r in &self.records {+ if r.is_length() {+ remaining = usize::from(r.u16_at(0));+ out.push(PsdSubpath {+ closed: r.selector == selector::CLOSED_LENGTH,+ operation: r.u16_at(2) as i16,+ knots: Vec::with_capacity(remaining.min(4096)),+ });+ } else if r.is_knot() {+ let closed = r.selector <= 2;+ if remaining == 0 && out.last().is_none_or(|s| s.closed != closed) {+ out.push(PsdSubpath { closed, operation: -1, knots: Vec::new() });+ }+ remaining = remaining.saturating_sub(1);+ let pt = |i: usize| (fixed_to_f64(r.i32_at(i * 8 + 4)), fixed_to_f64(r.i32_at(i * 8)));+ if let Some(s) = out.last_mut() {+ s.knots.push(PsdKnot {+ linked: matches!(r.selector, 1 | 4),+ pre: pt(0),+ anchor: pt(1),+ post: pt(2),+ });+ }+ }+ }+ out+ }++ /// Builds a record list: a fill rule record, an initial fill record,+ /// then each subpath's length record and knots.+ pub fn from_subpaths(subpaths: &[PsdSubpath], initial_fill: bool) -> Self {+ let mut records = vec![+ PathRecord { selector: selector::FILL_RULE, data: [0; 24] },+ PathRecord { selector: selector::INITIAL_FILL, data: [0; 24] },+ ];+ records[1].data[..2].copy_from_slice(&u16::from(initial_fill).to_be_bytes());+ for s in subpaths {+ let mut data = [0u8; 24];+ data[..2].copy_from_slice(&(s.knots.len().min(u16::MAX as usize) as u16).to_be_bytes());+ data[2..4].copy_from_slice(&s.operation.to_be_bytes());+ // Photoshop writes 1 here (psd-tools default); meaning unknown.+ data[4..6].copy_from_slice(&1u16.to_be_bytes());+ records.push(PathRecord { selector: if s.closed { selector::CLOSED_LENGTH } else { selector::OPEN_LENGTH }, data });+ for k in s.knots.iter().take(u16::MAX as usize) {+ let sel = match (s.closed, k.linked) {+ (true, true) => selector::CLOSED_KNOT_LINKED,+ (true, false) => selector::CLOSED_KNOT_UNLINKED,+ (false, true) => selector::OPEN_KNOT_LINKED,+ (false, false) => selector::OPEN_KNOT_UNLINKED,+ };+ let mut d = [0u8; 24];+ for (i, p) in [k.pre, k.anchor, k.post].iter().enumerate() {+ d[i * 8..i * 8 + 4].copy_from_slice(&f64_to_fixed(p.1).to_be_bytes());+ d[i * 8 + 4..i * 8 + 8].copy_from_slice(&f64_to_fixed(p.0).to_be_bytes());+ }+ records.push(PathRecord { selector: sel, data: d });+ }+ }+ PathData { records }+ }+}++/// A vector mask block (`vmsk` / `vsms`): version, flags and path records.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct VectorMaskBlock {+ /// Version (3).+ pub version: u32,+ /// Flags: bit 0 invert, bit 1 not linked, bit 2 disabled.+ pub flags: u32,+ /// The path.+ pub path: PathData,+}++impl VectorMaskBlock {+ /// Invert flag.+ pub const FLAG_INVERT: u32 = 1;+ /// Not-linked flag.+ pub const FLAG_NOT_LINKED: u32 = 2;+ /// Disabled flag.+ pub const FLAG_DISABLED: u32 = 4;++ /// Parses the block data.+ pub fn from_bytes(data: &[u8]) -> Result<Self> {+ if data.len() < 8 {+ return Err(PsdError::UnexpectedEof { offset: 0, needed: 8 - data.len() });+ }+ let version = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);+ let flags = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);+ Ok(VectorMaskBlock { version, flags, path: PathData::from_bytes(&data[8..])? })+ }++ /// Serializes the block data.+ pub fn to_bytes(&self) -> Vec<u8> {+ let mut out = Vec::with_capacity(8 + self.path.records.len() * RECORD_LEN);+ out.extend_from_slice(&self.version.to_be_bytes());+ out.extend_from_slice(&self.flags.to_be_bytes());+ out.extend_from_slice(&self.path.to_bytes());+ out+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sample() -> Vec<PsdSubpath> {+ vec![+ PsdSubpath {+ closed: true,+ operation: 1,+ knots: vec![+ PsdKnot { linked: false, pre: (0.25, 0.25), anchor: (0.25, 0.25), post: (0.25, 0.25) },+ PsdKnot { linked: true, pre: (0.625, 0.125), anchor: (0.75, 0.25), post: (0.875, 0.375) },+ PsdKnot { linked: false, pre: (0.5, 0.75), anchor: (0.5, 0.75), post: (0.5, 0.75) },+ ],+ },+ PsdSubpath {+ closed: false,+ operation: 2,+ knots: vec![PsdKnot { linked: false, pre: (-0.5, 1.5), anchor: (0.0, 1.0), post: (0.0625, 0.9375) }],+ },+ ]+ }++ #[test]+ fn subpaths_roundtrip_and_bytes_are_stable() {+ let p = PathData::from_subpaths(&sample(), true);+ let bytes = p.to_bytes();+ assert_eq!(bytes.len(), (2 + 2 + 4) * RECORD_LEN);+ let q = PathData::from_bytes(&bytes).unwrap();+ assert_eq!(q.to_bytes(), bytes);+ assert_eq!(q.subpaths(), sample());+ assert!(q.initial_fill());+ }++ #[test]+ fn vector_mask_block_roundtrip() {+ let b = VectorMaskBlock { version: 3, flags: VectorMaskBlock::FLAG_INVERT, path: PathData::from_subpaths(&sample(), false) };+ let bytes = b.to_bytes();+ assert_eq!(VectorMaskBlock::from_bytes(&bytes).unwrap(), b);+ assert!(VectorMaskBlock::from_bytes(&[0; 4]).is_err());+ }++ #[test]+ fn fixed_point_conversion() {+ assert_eq!(f64_to_fixed(1.0), 1 << 24);+ assert_eq!(fixed_to_f64(-(1 << 23)), -0.5);+ assert_eq!(f64_to_fixed(1e12), i32::MAX);+ }++ #[test]+ fn lenient_knots_without_length_record() {+ let mut p = PathData::from_subpaths(&sample(), false);+ p.records.retain(|r| !r.is_length());+ let s = p.subpaths();+ assert_eq!(s.len(), 2);+ assert_eq!(s[0].knots.len(), 3);+ }+}diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rsindex 731dc2db7..349e1ae07 100644--- a/crates/raster/src/lib.rs+++ b/crates/raster/src/lib.rs@@ -98,22 +98,37 @@ impl Surface {/// Exact bounds of pixels that differ from the default pixel.pub fn content_bounds(&self) -> Rect {let bpp = self.format.bytes_per_pixel();+ if self.tiles.is_empty() {+ return Rect::EMPTY;+ }+ // Scan tiles from the outside of the tile grid inwards; a tile lying entirely inside the+ // bounds found so far cannot extend them and is skipped (so a full-canvas selection scans+ // roughly its outer ring of tiles instead of every pixel).+ let (mut gx0, mut gy0, mut gx1, mut gy1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);+ for c in self.tiles.keys() {+ (gx0, gy0, gx1, gy1) = (gx0.min(c.tx), gy0.min(c.ty), gx1.max(c.tx), gy1.max(c.ty));+ }+ let mut order: Vec<(&TileCoord, &Arc<Tile>)> = self.tiles.iter().collect();+ order.sort_by_key(|(c, _)| (c.tx - gx0).min(gx1 - c.tx).min(c.ty - gy0).min(gy1 - c.ty));+ let dp = &*self.default_pixel;+ let ts = TILE_SIZE as usize;let mut out = Rect::EMPTY;- for (c, t) in &self.tiles {+ for (c, t) in order {let origin = c.rect();- let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);- for (i, px) in t.data.chunks_exact(bpp).enumerate() {- if px != &*self.default_pixel {- let x = (i as i32) % TILE_SIZE;- let y = (i as i32) / TILE_SIZE;- x0 = x0.min(x);- y0 = y0.min(y);- x1 = x1.max(x + 1);- y1 = y1.max(y + 1);- }+ if !out.is_empty() && out.contains_rect(&origin) {+ continue;}- if x0 <= x1 && x0 != i32::MAX {- out = out.union(&Rect::new(x0, y0, x1, y1).translate(origin.x0, origin.y0));+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize);+ for (y, row) in t.data.chunks_exact(ts * bpp).enumerate() {+ let Some(first) = row.chunks_exact(bpp).position(|px| px != dp) else { continue };+ let last = ts - 1 - row.chunks_exact(bpp).rev().position(|px| px != dp).unwrap_or(0);+ x0 = x0.min(first);+ x1 = x1.max(last + 1);+ y0 = y0.min(y);+ y1 = y + 1;+ }+ if x0 != usize::MAX {+ out = out.union(&Rect::new(x0 as i32, y0 as i32, x1 as i32, y1 as i32).translate(origin.x0, origin.y0));}}out@@ -168,6 +183,169 @@ impl Surface {}}+ /// One channel of one pixel, without allocating.+ #[inline]+ pub fn sample_channel(&self, x: i32, y: i32, c: usize) -> f32 {+ let (tc, base) = self.locate(x, y);+ match self.tiles.get(&tc) {+ Some(t) => read_sample(&t.data, self.format.sample, base + c),+ None => read_sample(&self.default_pixel, self.format.sample, c),+ }+ }++ /// Channel `c` at `(x0 + i·step, y)` for `i in 0..out.len()`, looking each tile up once per run+ /// (much faster than per-sample [`Surface::sample_channel`] for strided scans).+ pub fn sample_row_strided(&self, y: i32, x0: i32, step: i32, c: usize, out: &mut [f32]) {+ let step = step.max(1);+ let dp = read_sample(&self.default_pixel, self.format.sample, c);+ let n = self.format.channels();+ let ty = y.div_euclid(TILE_SIZE);+ let ly = y.rem_euclid(TILE_SIZE) as usize;+ let mut i = 0;+ while i < out.len() {+ let x = x0 + i as i32 * step;+ let tx = x.div_euclid(TILE_SIZE);+ // Samples that fall in this tile.+ let tile_end = (tx + 1) * TILE_SIZE;+ let count = (((tile_end - x) + step - 1) / step).max(1) as usize;+ let end = (i + count).min(out.len());+ match self.tiles.get(&TileCoord { tx, ty }) {+ None => out[i..end].fill(dp),+ Some(t) => {+ for (k, o) in out[i..end].iter_mut().enumerate() {+ let lx = (x + k as i32 * step - tx * TILE_SIZE) as usize;+ *o = read_sample(&t.data, self.format.sample, (ly * TILE_SIZE as usize + lx) * n + c);+ }+ }+ }+ i = end;+ }+ }++ /// [`Surface::read_region`] into a reusable buffer (resized to fit).+ pub fn read_region_into(&self, r: Rect, out: &mut Vec<f32>) {+ let n = self.channels();+ let w = r.width() as usize;+ out.clear();+ out.resize(w * r.height() as usize * n, 0.0);+ let dp = self.default_pixel();+ for tc in r.tiles() {+ let tr = tc.rect().intersect(&r);+ let tile = self.tiles.get(&tc);+ for y in tr.y0..tr.y1 {+ let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n;+ let span = tr.width() as usize * n;+ let dst = &mut out[o..o + span];+ match tile {+ Some(t) => {+ let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n;+ for (i, d) in dst.iter_mut().enumerate() {+ *d = read_sample(&t.data, self.format.sample, base + i);+ }+ }+ None => {+ for px in dst.chunks_exact_mut(n) {+ px.copy_from_slice(&dp);+ }+ }+ }+ }+ }+ }++ /// Reads `r` as straight RGBA floats (converting from the surface's+ /// model) into `out` (`w*h` entries), without per-pixel allocation.+ /// Fast paths for RGB(A) and gray(A) at 8/16/32 bits read tile bytes+ /// directly; missing tiles are filled with the default pixel.+ pub fn read_rgba_into(&self, r: Rect, out: &mut [[f32; 4]]) {+ let w = r.width() as usize;+ debug_assert_eq!(out.len(), w * r.height() as usize);+ let fmt = self.format;+ let n = fmt.channels();+ let dp = to_rgba(&fmt, &self.default_pixel());+ for tc in r.tiles() {+ let tr = tc.rect().intersect(&r);+ let tile = self.tiles.get(&tc);+ for y in tr.y0..tr.y1 {+ let o = ((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize;+ let dst = &mut out[o..o + tr.width() as usize];+ let Some(t) = tile else {+ dst.fill(dp);+ continue;+ };+ let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n;+ match (fmt.mode, fmt.sample, fmt.alpha) {+ (ColorMode::Rgb, SampleType::U8, true) => {+ let src = &t.data[base..base + dst.len() * 4];+ for (d, s) in dst.iter_mut().zip(src.chunks_exact(4)) {+ *d = [s[0] as f32 / 255.0, s[1] as f32 / 255.0, s[2] as f32 / 255.0, s[3] as f32 / 255.0];+ }+ }+ (ColorMode::Grayscale, SampleType::U8, true) => {+ let src = &t.data[base..base + dst.len() * 2];+ for (d, s) in dst.iter_mut().zip(src.chunks_exact(2)) {+ let g = s[0] as f32 / 255.0;+ *d = [g, g, g, s[1] as f32 / 255.0];+ }+ }+ _ => {+ let mut px = [0.0f32; 8];+ for (i, d) in dst.iter_mut().enumerate() {+ for (c, v) in px.iter_mut().enumerate().take(n) {+ *v = read_sample(&t.data, fmt.sample, base + i * n + c);+ }+ *d = to_rgba(&fmt, &px[..n]);+ }+ }+ }+ }+ }+ }++ /// Reads `r` as straight 8-bit RGBA into `out` (`w*h` entries). RGBA8 surfaces copy tile bytes+ /// directly; other formats convert through [`Surface::read_rgba_into`] one tile row at a time.+ pub fn read_rgba8_into(&self, r: Rect, out: &mut [[u8; 4]]) {+ let w = r.width() as usize;+ debug_assert_eq!(out.len(), w * r.height() as usize);+ let fmt = self.format;+ let rgba8 = matches!((fmt.mode, fmt.sample, fmt.alpha), (ColorMode::Rgb, SampleType::U8, true));+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;+ let dp = to_rgba(&fmt, &self.default_pixel());+ let dp8 = [q(dp[0]), q(dp[1]), q(dp[2]), q(dp[3])];+ let mut row = Vec::new();+ for tc in r.tiles() {+ let tr = tc.rect().intersect(&r);+ let tile = self.tiles.get(&tc);+ for y in tr.y0..tr.y1 {+ let o = ((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize;+ let dst = &mut out[o..o + tr.width() as usize];+ match tile {+ None => dst.fill(dp8),+ Some(t) if rgba8 => {+ let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * 4;+ let len = dst.len();+ for (d, s) in dst.iter_mut().zip(t.data[base..base + len * 4].chunks_exact(4)) {+ *d = [s[0], s[1], s[2], s[3]];+ }+ }+ Some(_) => {+ row.resize(dst.len(), [0.0f32; 4]);+ self.read_rgba_into(Rect::new(tr.x0, y, tr.x1, y + 1), &mut row);+ for (d, p) in dst.iter_mut().zip(&row) {+ *d = [q(p[0]), q(p[1]), q(p[2]), q(p[3])];+ }+ }+ }+ }+ }+ }++ /// `true` if any allocated tile intersects `r` (else `r` reads as the+ /// default pixel everywhere).+ pub fn has_tiles_in(&self, r: Rect) -> bool {+ r.tiles().any(|tc| self.tiles.contains_key(&tc))+ }+/// Read a rectangle as interleaved normalised floats (`w*h*channels`).pub fn read_region(&self, r: Rect) -> Vec<f32> {let n = self.channels();@@ -369,6 +547,38 @@ pub fn from_rgba(format: &PixelFormat, rgba: [f32; 4]) -> Vec<f32> {out}+/// [`from_rgba`] without allocating: writes `format.channels()` values into+/// `out` and returns how many were written.+#[inline]+pub fn from_rgba_into(format: &PixelFormat, rgba: [f32; 4], out: &mut [f32]) -> usize {+ let rgb = [rgba[0], rgba[1], rgba[2]];+ let n = match format.mode {+ ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => {+ out[0] = photocraft_color::convert::rgb_to_gray(rgb);+ 1+ }+ ColorMode::Cmyk => {+ out[..4].copy_from_slice(&photocraft_color::convert::rgb_to_cmyk_naive(rgb));+ 4+ }+ ColorMode::Lab => {+ let l = photocraft_color::convert::srgb_to_lab(rgb);+ out[..3].copy_from_slice(&[l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0]);+ 3+ }+ _ => {+ out[..3].copy_from_slice(&rgb);+ 3+ }+ };+ if format.alpha {+ out[n] = rgba[3];+ n + 1+ } else {+ n+ }+}+/// A simple owned RGBA8 image, used for display and thumbnails.#[derive(Clone, Debug, PartialEq, Eq)]pub struct Rgba8Image {@@ -394,6 +604,44 @@ mod tests {use photocraft_color::PixelFormat;use proptest::prelude::*;+ #[test]+ fn from_rgba_into_matches_from_rgba() {+ for fmt in [PixelFormat::RGBA8, PixelFormat::GRAY8, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::new(ColorMode::Lab, SampleType::F32, true)] {+ let mut buf = [0.0f32; 8];+ let n = from_rgba_into(&fmt, [0.2, 0.5, 0.7, 0.4], &mut buf);+ assert_eq!(&buf[..n], &from_rgba(&fmt, [0.2, 0.5, 0.7, 0.4])[..]);+ }+ }++ #[test]+ fn zero_alloc_accessors_match_read_region() {+ for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::GRAY8] {+ let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]);+ let r = Rect::new(-300, -20, 300, 40);+ for (i, (x, y)) in [(-299, -19), (0, 0), (255, 39), (256, 10), (299, 0)].into_iter().enumerate() {+ let px: Vec<f32> = (0..fmt.channels()).map(|c| ((i * 3 + c) % 5) as f32 / 4.0).collect();+ s.write_pixel(x, y, &px);+ }+ let region = s.read_region(r);+ let mut into = vec![9.0; 3];+ s.read_region_into(r, &mut into);+ assert_eq!(region, into);+ let mut rgba = vec![[0.0; 4]; (r.width() * r.height()) as usize];+ s.read_rgba_into(r, &mut rgba);+ let n = fmt.channels();+ for (i, p) in region.chunks_exact(n).enumerate() {+ let want = to_rgba(&fmt, p);+ for c in 0..4 {+ assert!((rgba[i][c] - want[c]).abs() < 1e-6, "{fmt:?} px {i}");+ }+ let (x, y) = (r.x0 + (i % r.width() as usize) as i32, r.y0 + (i / r.width() as usize) as i32);+ assert_eq!(s.sample_channel(x, y, 0), p[0]);+ }+ assert!(s.has_tiles_in(Rect::new(0, 0, 1, 1)));+ assert!(!s.has_tiles_in(Rect::new(1000, 1000, 1001, 1001)));+ }+ }+#[test]fn empty_surface_reads_default() {let s = Surface::new(PixelFormat::RGBA8);@@ -513,4 +761,32 @@ mod tests {}}}++ #[test]+ fn strided_row_sampling_matches_sample_channel() {+ let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]);+ s.fill_rect(Rect::new(-300, 10, 200, 40), &[1.0]);+ s.fill_rect(Rect::new(250, 10, 700, 20), &[0.5]);+ for (y, x0, step) in [(15, -520, 7), (15, -1, 1), (30, 3, 64), (500, 0, 9)] {+ let mut out = vec![0.0; 120];+ s.sample_row_strided(y, x0, step, 0, &mut out);+ for (i, v) in out.iter().enumerate() {+ assert_eq!(*v, s.sample_channel(x0 + i as i32 * step, y, 0), "y={y} x0={x0} step={step} i={i}");+ }+ }+ }++ #[test]+ fn content_bounds_with_tile_skipping() {+ // Interior content only; ring tiles present but all-default (unpruned).+ let mut s = Surface::new(PixelFormat::GRAY8);+ s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.0]);+ s.fill_rect(Rect::new(300, 310, 700, 720), &[1.0]);+ assert_eq!(s.content_bounds(), Rect::new(300, 310, 700, 720));+ // Full-canvas content plus a far-away speck.+ let mut s = Surface::new(PixelFormat::GRAY8);+ s.fill_rect(Rect::new(0, 0, 2000, 1500), &[1.0]);+ s.fill_rect(Rect::new(-700, 4000, -699, 4001), &[0.5]);+ assert_eq!(s.content_bounds(), Rect::new(-700, 0, 2000, 4001));+ }}diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.tomlnew file mode 100644index 000000000..301e38395--- /dev/null+++ b/crates/text/Cargo.toml@@ -0,0 +1,21 @@+[package]+name = "photocraft-text"+description = "Font database, text shaping/layout (parley) and text-layer rasterization"+version.workspace = true+edition.workspace = true+license.workspace = true+rust-version.workspace = true++[lints]+workspace = true++[dependencies]+photocraft-geom = { workspace = true }+photocraft-color = { workspace = true }+photocraft-raster = { workspace = true }+photocraft-doc = { workspace = true }+photocraft-psd = { workspace = true }+# No `system` feature: fontique's system backend links fontconfig on Linux. We scan font+# directories ourselves (native) and always register the bundled fonts (native + web).+parley = { version = "0.11", default-features = false, features = ["std"] }+skrifa = "0.44"diff --git a/crates/text/src/engine_data.rs b/crates/text/src/engine_data.rsnew file mode 100644index 000000000..72df9d1e3--- /dev/null+++ b/crates/text/src/engine_data.rs@@ -0,0 +1,415 @@+//! Photoshop's `EngineData`: the PostScript-like text engine document stored in `TySh`.+//!+//! Syntax (from observation of real files and public notes): dictionaries `<< /Key value … >>`,+//! arrays `[ … ]`, strings `( … )` holding UTF-16BE with a `FE FF` byte-order mark and `\`+//! escapes, numbers (`12`, `-1.5`, `.5`), `true`/`false`, and `/Name` values.++use std::fmt::Write as _;++#[derive(Clone, Debug, PartialEq)]+pub enum Value {+ Dict(Vec<(String, Value)>),+ Array(Vec<Value>),+ String(String),+ Int(i64),+ Real(f64),+ Bool(bool),+ Name(String),+}++impl Value {+ pub fn get(&self, key: &str) -> Option<&Value> {+ match self {+ Value::Dict(items) => items.iter().find(|(k, _)| k == key).map(|(_, v)| v),+ _ => None,+ }+ }+ /// Follows a path of dictionary keys.+ pub fn path(&self, keys: &[&str]) -> Option<&Value> {+ keys.iter().try_fold(self, |v, k| v.get(k))+ }+ pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {+ match self {+ Value::Dict(items) => items.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v),+ _ => None,+ }+ }+ /// Sets (or appends) a dictionary entry.+ pub fn set(&mut self, key: &str, v: Value) {+ if let Value::Dict(items) = self {+ match items.iter_mut().find(|(k, _)| k == key) {+ Some(e) => e.1 = v,+ None => items.push((key.to_string(), v)),+ }+ }+ }+ pub fn as_f64(&self) -> Option<f64> {+ match self {+ Value::Int(i) => Some(*i as f64),+ Value::Real(r) => Some(*r),+ _ => None,+ }+ }+ pub fn as_i64(&self) -> Option<i64> {+ match self {+ Value::Int(i) => Some(*i),+ Value::Real(r) => Some(*r as i64),+ _ => None,+ }+ }+ pub fn as_bool(&self) -> Option<bool> {+ match self {+ Value::Bool(b) => Some(*b),+ Value::Int(i) => Some(*i != 0),+ _ => None,+ }+ }+ pub fn as_str(&self) -> Option<&str> {+ match self {+ Value::String(s) | Value::Name(s) => Some(s),+ _ => None,+ }+ }+ pub fn as_array(&self) -> Option<&[Value]> {+ match self {+ Value::Array(a) => Some(a),+ _ => None,+ }+ }+ pub fn dict() -> Value {+ Value::Dict(Vec::new())+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ParseError(pub String);++impl std::fmt::Display for ParseError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "EngineData: {}", self.0)+ }+}+impl std::error::Error for ParseError {}++const MAX_DEPTH: usize = 64;++struct Parser<'a> {+ b: &'a [u8],+ i: usize,+}++impl Parser<'_> {+ fn ws(&mut self) {+ while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\t' | b'\r' | b'\n' | 0) {+ self.i += 1;+ }+ }+ fn err<T>(&self, m: &str) -> Result<T, ParseError> {+ Err(ParseError(format!("{m} at byte {}", self.i)))+ }+ fn value(&mut self, depth: usize) -> Result<Value, ParseError> {+ if depth > MAX_DEPTH {+ return self.err("nesting too deep");+ }+ self.ws();+ let b = self.b;+ match b.get(self.i) {+ None => self.err("unexpected end"),+ Some(b'<') if b.get(self.i + 1) == Some(&b'<') => {+ self.i += 2;+ let mut items = Vec::new();+ loop {+ self.ws();+ match b.get(self.i) {+ Some(b'>') if b.get(self.i + 1) == Some(&b'>') => {+ self.i += 2;+ return Ok(Value::Dict(items));+ }+ Some(b'/') => {+ let k = self.name();+ let v = self.value(depth + 1)?;+ items.push((k, v));+ }+ None => return self.err("unterminated dictionary"),+ _ => return self.err("expected key"),+ }+ }+ }+ Some(b'[') => {+ self.i += 1;+ let mut items = Vec::new();+ loop {+ self.ws();+ match b.get(self.i) {+ Some(b']') => {+ self.i += 1;+ return Ok(Value::Array(items));+ }+ None => return self.err("unterminated array"),+ _ => items.push(self.value(depth + 1)?),+ }+ }+ }+ Some(b'(') => {+ self.i += 1;+ let mut raw = Vec::new();+ loop {+ match b.get(self.i) {+ None => return self.err("unterminated string"),+ Some(b'\\') => {+ if let Some(&c) = b.get(self.i + 1) {+ raw.push(c);+ }+ self.i += 2;+ }+ Some(b')') => {+ self.i += 1;+ break;+ }+ Some(&c) => {+ raw.push(c);+ self.i += 1;+ }+ }+ }+ Ok(Value::String(decode_string(&raw)))+ }+ Some(b'/') => Ok(Value::Name(self.name())),+ Some(_) => {+ let start = self.i;+ while self.i < b.len()+ && !matches!(+ b[self.i],+ b' ' | b'\t' | b'\r' | b'\n' | b'[' | b']' | b'<' | b'>' | b'(' | b'/'+ )+ {+ self.i += 1;+ }+ let tok = std::str::from_utf8(&b[start..self.i]).unwrap_or("");+ match tok {+ "true" => Ok(Value::Bool(true)),+ "false" => Ok(Value::Bool(false)),+ "" => {+ self.i += 1;+ self.err("unexpected byte")+ }+ t if t.contains('.') || t.contains('e') || t.contains('E') => t+ .parse()+ .map(Value::Real)+ .or_else(|_| self.err("bad number")),+ t => t.parse().map(Value::Int).or_else(|_| {+ t.parse()+ .map(Value::Real)+ .or_else(|_| self.err("bad token"))+ }),+ }+ }+ }+ }+ fn name(&mut self) -> String {+ self.i += 1; // '/'+ let start = self.i;+ while self.i < self.b.len()+ && !matches!(+ self.b[self.i],+ b' ' | b'\t' | b'\r' | b'\n' | b'[' | b']' | b'<' | b'>' | b'(' | b'/'+ )+ {+ self.i += 1;+ }+ String::from_utf8_lossy(&self.b[start..self.i]).into_owned()+ }+}++fn decode_string(raw: &[u8]) -> String {+ if raw.len() >= 2 && raw[0] == 0xFE && raw[1] == 0xFF {+ let u: Vec<u16> = raw[2..]+ .chunks_exact(2)+ .map(|c| u16::from_be_bytes([c[0], c[1]]))+ .collect();+ String::from_utf16_lossy(&u)+ } else {+ raw.iter().map(|&c| c as char).collect()+ }+}++/// Parses an EngineData document (the top-level dictionary).+pub fn parse(data: &[u8]) -> Result<Value, ParseError> {+ let mut p = Parser { b: data, i: 0 };+ p.value(0)+}++/// Serializes in Photoshop's layout (tab-indented, one key per line).+pub fn write(v: &Value) -> Vec<u8> {+ let mut out = b"\n\n".to_vec();+ write_value(v, 0, &mut out);+ out.push(b'\n');+ out+}++fn indent(out: &mut Vec<u8>, n: usize) {+ out.extend(std::iter::repeat_n(b'\t', n));+}++fn is_container(v: &Value) -> bool {+ matches!(v, Value::Dict(_))+ || matches!(v, Value::Array(a) if a.iter().any(|x| matches!(x, Value::Dict(_) | Value::Array(_))))+}++fn write_value(v: &Value, depth: usize, out: &mut Vec<u8>) {+ match v {+ Value::Dict(items) => {+ out.extend_from_slice(b"<<\n");+ for (k, v) in items {+ indent(out, depth + 1);+ out.push(b'/');+ out.extend_from_slice(k.as_bytes());+ if is_container(v) {+ out.push(b'\n');+ indent(out, depth + 1);+ } else {+ out.push(b' ');+ }+ write_value(v, depth + 1, out);+ out.push(b'\n');+ }+ indent(out, depth);+ out.extend_from_slice(b">>");+ }+ Value::Array(items) if is_container(v) => {+ out.extend_from_slice(b"[\n");+ for x in items {+ indent(out, depth);+ write_value(x, depth, out);+ out.push(b'\n');+ }+ indent(out, depth);+ out.push(b']');+ }+ Value::Array(items) => {+ out.push(b'[');+ for x in items {+ out.push(b' ');+ write_value(x, depth, out);+ }+ out.extend_from_slice(b" ]");+ }+ Value::String(s) => {+ out.push(b'(');+ let mut raw = vec![0xFE, 0xFF];+ for u in s.encode_utf16() {+ raw.extend_from_slice(&u.to_be_bytes());+ }+ for c in raw {+ if matches!(c, b'(' | b')' | b'\\') {+ out.push(b'\\');+ }+ out.push(c);+ }+ out.push(b')');+ }+ Value::Int(i) => {+ let _ = write!(Wrap(out), "{i}");+ }+ Value::Real(r) => out.extend_from_slice(format_real(*r).as_bytes()),+ Value::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),+ Value::Name(n) => {+ out.push(b'/');+ out.extend_from_slice(n.as_bytes());+ }+ }+}++struct Wrap<'a>(&'a mut Vec<u8>);+impl std::fmt::Write for Wrap<'_> {+ fn write_str(&mut self, s: &str) -> std::fmt::Result {+ self.0.extend_from_slice(s.as_bytes());+ Ok(())+ }+}++/// Photoshop style: `1.0`, `.5`, `-.25`.+fn format_real(r: f64) -> String {+ if !r.is_finite() {+ return "0.0".into();+ }+ if r.fract() == 0.0 && r.abs() < 1e15 {+ return format!("{r:.1}");+ }+ let mut s = format!("{r:.5}");+ while s.ends_with('0') {+ s.pop();+ }+ if let Some(rest) = s.strip_prefix("0.") {+ s = format!(".{rest}");+ } else if let Some(rest) = s.strip_prefix("-0.") {+ s = format!("-.{rest}");+ }+ s+}++#[cfg(test)]+mod tests {+ use super::*;++ const SAMPLE: &[u8] = b"\n\n<<\n\t/EngineDict\n\t<<\n\t\t/Editor\n\t\t<<\n\t\t\t/Text (\xFE\xFF\x00H\x00i\x00\\)\x00\r)\n\t\t>>\n\t\t/Nums [ 1.0 .5 -2 0 ]\n\t\t/Flag true\n\t\t/Kind /Roman\n\t\t/Runs [\n\t\t<<\n\t\t\t/A 1\n\t\t>>\n\t\t]\n\t>>\n>>";++ #[test]+ fn parses_sample() {+ let v = parse(SAMPLE).unwrap();+ assert_eq!(+ v.path(&["EngineDict", "Editor", "Text"])+ .and_then(Value::as_str),+ Some("Hi)\r")+ );+ let nums: Vec<f64> = v+ .path(&["EngineDict", "Nums"])+ .unwrap()+ .as_array()+ .unwrap()+ .iter()+ .filter_map(Value::as_f64)+ .collect();+ assert_eq!(nums, [1.0, 0.5, -2.0, 0.0]);+ assert_eq!(+ v.path(&["EngineDict", "Flag"]).and_then(Value::as_bool),+ Some(true)+ );+ assert_eq!(+ v.path(&["EngineDict", "Kind"]),+ Some(&Value::Name("Roman".into()))+ );+ assert_eq!(+ v.path(&["EngineDict", "Runs"]).unwrap().as_array().unwrap()[0]+ .get("A")+ .and_then(Value::as_i64),+ Some(1)+ );+ }++ #[test]+ fn write_parse_roundtrip() {+ let v = parse(SAMPLE).unwrap();+ let bytes = write(&v);+ assert_eq!(parse(&bytes).unwrap(), v);+ // Stable: writing twice gives identical bytes.+ assert_eq!(write(&parse(&bytes).unwrap()), bytes);+ }++ #[test]+ fn reals_format_like_photoshop() {+ assert_eq!(format_real(1.0), "1.0");+ assert_eq!(format_real(0.5), ".5");+ assert_eq!(format_real(-0.25), "-.25");+ assert_eq!(format_real(12.125), "12.125");+ }++ #[test]+ fn malformed_input_never_panics() {+ for cut in 0..SAMPLE.len() {+ let _ = parse(&SAMPLE[..cut]);+ }+ assert!(parse(b"<< /A").is_err());+ assert!(parse(&[b'['; 200]).is_err());+ }+}diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rsnew file mode 100644index 000000000..3d387bb4a--- /dev/null+++ b/crates/text/src/fonts.rs@@ -0,0 +1,420 @@+//! Font database: bundled fonts (always available, also on the web), optional system fonts found+//! by scanning the platform font directories (no fontconfig), user-registered font data, and+//! PostScript-name lookup for PSD import.++use std::collections::HashMap;+use std::sync::Arc;++use parley::FontContext;+use parley::fontique::{+ Blob, Collection, CollectionOptions, FontStyle, GenericFamily, SourceCache,+};+use skrifa::raw::FileRef;+use skrifa::{MetadataProvider, string::StringId};++/// Family used when a style names no family or an unknown one.+pub const DEFAULT_FAMILY: &str = "Inter";+/// Bundled monospace family.+pub const MONO_FAMILY: &str = "JetBrains Mono";++/// Fonts shipped with Photocraft (OFL; licences in `assets/fonts`).+pub const BUNDLED: &[(&str, &[u8])] = &[+ (+ "Inter-Regular.ttf",+ include_bytes!("../../../assets/fonts/Inter-Regular.ttf"),+ ),+ (+ "Inter-Medium.ttf",+ include_bytes!("../../../assets/fonts/Inter-Medium.ttf"),+ ),+ (+ "Inter-SemiBold.ttf",+ include_bytes!("../../../assets/fonts/Inter-SemiBold.ttf"),+ ),+ (+ "JetBrainsMono-Regular.ttf",+ include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"),+ ),+];++/// Families tried (if installed) after the requested one, for missing glyphs.+const FALLBACK_CANDIDATES: &[&str] = &[+ "Noto Sans",+ "Arial Unicode MS",+ "Segoe UI",+ "DejaVu Sans",+ "Geeza Pro",+ "Arial Hebrew",+ "Noto Sans Arabic",+ "Noto Sans Hebrew",+ "Noto Sans CJK SC",+ "PingFang SC",+ "Hiragino Sans",+ "Apple Color Emoji",+ "Segoe UI Emoji",+ "Noto Color Emoji",+];++/// One face in the database (for font menus).+#[derive(Clone, Debug, PartialEq)]+pub struct FaceInfo {+ pub family: String,+ /// CSS weight (100–900); variable fonts report their default.+ pub weight: f32,+ pub italic: bool,+ /// Variation axes: (tag, min, default, max).+ pub axes: Vec<(String, f32, f32, f32)>,+}++/// Result of a PostScript-name lookup.+#[derive(Clone, Debug, PartialEq)]+pub struct ResolvedFont {+ pub family: String,+ pub weight: u16,+ pub italic: bool,+ /// True when the exact face was found; false for a heuristic family guess.+ pub exact: bool,+}++pub struct FontDb {+ pub(crate) fcx: FontContext,+ system_loaded: bool,+ /// PostScript name → (family, weight, italic), filled lazily.+ ps_cache: HashMap<String, Option<ResolvedFont>>,+ fallbacks: Vec<String>,+}++impl Default for FontDb {+ fn default() -> Self {+ Self::new()+ }+}++impl FontDb {+ /// Bundled fonts only (deterministic: used by tests and the web build).+ pub fn new() -> Self {+ let collection = Collection::new(CollectionOptions {+ shared: false,+ system_fonts: false,+ });+ let mut db = FontDb {+ fcx: FontContext {+ collection,+ source_cache: SourceCache::default(),+ },+ system_loaded: false,+ ps_cache: HashMap::new(),+ fallbacks: Vec::new(),+ };+ for (_, bytes) in BUNDLED {+ db.register_font_data(bytes.to_vec());+ }+ db.refresh_generics();+ db+ }++ /// Bundled fonts plus the fonts installed on this machine (no-op on the web).+ pub fn with_system_fonts() -> Self {+ let mut db = Self::new();+ db.load_system_fonts();+ db+ }++ /// Scans the platform font directories (once). Font files are memory-mapped lazily by+ /// fontique when a face is first used.+ pub fn load_system_fonts(&mut self) {+ if self.system_loaded {+ return;+ }+ self.system_loaded = true;+ #[cfg(not(target_arch = "wasm32"))]+ {+ // One call per file: fontique's directory scan is much slower on large folders.+ let mut files = Vec::new();+ for d in system_font_dirs() {+ collect_font_files(&d, 0, &mut files);+ }+ for f in files {+ self.fcx.collection.load_fonts_from_paths([f]);+ }+ self.ps_cache.clear();+ self.refresh_generics();+ }+ }++ /// Registers font data (TTF/OTF, or every face of a TTC/OTC). Returns the family names added.+ pub fn register_font_data(&mut self, bytes: Vec<u8>) -> Vec<String> {+ let added = self+ .fcx+ .collection+ .register_fonts(Blob::new(Arc::new(bytes)), None);+ let mut names = Vec::new();+ for (id, _) in added {+ if let Some(n) = self.fcx.collection.family_name(id)+ && !names.iter().any(|x: &String| x == n)+ {+ names.push(n.to_string());+ }+ }+ self.ps_cache.clear();+ self.refresh_generics();+ names+ }++ fn refresh_generics(&mut self) {+ let c = &mut self.fcx.collection;+ if let Some(inter) = c.family_id(DEFAULT_FAMILY) {+ for g in [+ GenericFamily::SansSerif,+ GenericFamily::Serif,+ GenericFamily::SystemUi,+ GenericFamily::UiSansSerif,+ ] {+ if c.generic_families(g).next().is_none() {+ c.set_generic_families(g, std::iter::once(inter));+ }+ }+ }+ if let Some(mono) = c.family_id(MONO_FAMILY) {+ for g in [GenericFamily::Monospace, GenericFamily::UiMonospace] {+ if c.generic_families(g).next().is_none() {+ c.set_generic_families(g, std::iter::once(mono));+ }+ }+ }+ self.fallbacks = FALLBACK_CANDIDATES+ .iter()+ .filter(|f| c.family_id(f).is_some())+ .map(|s| s.to_string())+ .collect();+ }++ /// Families available after the requested one (bundled default + installed coverage fonts).+ pub(crate) fn fallback_stack(&self) -> impl Iterator<Item = &str> {+ std::iter::once(DEFAULT_FAMILY).chain(self.fallbacks.iter().map(String::as_str))+ }++ /// All family names, sorted.+ pub fn families(&mut self) -> Vec<String> {+ let mut v: Vec<String> = self+ .fcx+ .collection+ .family_names()+ .map(str::to_string)+ .collect();+ v.sort_by_key(|s| s.to_lowercase());+ v.dedup();+ v+ }++ pub fn has_family(&mut self, name: &str) -> bool {+ self.fcx.collection.family_id(name).is_some()+ }++ /// Faces of a family (weights, italics, variation axes).+ pub fn faces(&mut self, family: &str) -> Vec<FaceInfo> {+ let Some(info) = self.fcx.collection.family_by_name(family) else {+ return Vec::new();+ };+ info.fonts()+ .iter()+ .map(|f| FaceInfo {+ family: info.name().to_string(),+ weight: f.weight().value(),+ italic: !matches!(f.style(), FontStyle::Normal),+ axes: f+ .axes()+ .iter()+ .map(|a| (a.tag.to_string(), a.min, a.default, a.max))+ .collect(),+ })+ .collect()+ }++ /// Finds a face by PostScript name (as stored in PSD files): exact match by reading the+ /// `name` table of candidate faces, else a heuristic split (`Arial-BoldMT` → Arial, 700).+ pub fn resolve_postscript(&mut self, ps: &str) -> ResolvedFont {+ if let Some(Some(r)) = self.ps_cache.get(ps) {+ return r.clone();+ }+ let guess = guess_from_postscript(ps);+ let exact = self.find_exact(ps, &guess.family);+ let r = exact.unwrap_or_else(|| {+ // Keep the guessed family only if we have it; otherwise let fallback pick.+ let mut g = guess.clone();+ if !self.has_family(&g.family)+ && let Some(f) = self.families().into_iter().find(|f| {+ f.replace(' ', "")+ .eq_ignore_ascii_case(&g.family.replace(' ', ""))+ })+ {+ g.family = f;+ }+ g+ });+ self.ps_cache.insert(ps.to_string(), Some(r.clone()));+ r+ }++ fn find_exact(&mut self, ps: &str, family_guess: &str) -> Option<ResolvedFont> {+ let first_word = family_guess+ .split(' ')+ .next()+ .unwrap_or(family_guess)+ .to_lowercase();+ let candidates: Vec<String> = self+ .families()+ .into_iter()+ .filter(|f| f.to_lowercase().replace(' ', "").starts_with(&first_word))+ .collect();+ for fam in candidates {+ let Some(info) = self.fcx.collection.family_by_name(&fam) else {+ continue;+ };+ for font in info.fonts() {+ let Some(blob) = font.load(Some(&mut self.fcx.source_cache)) else {+ continue;+ };+ let Ok(fr) = skrifa::FontRef::from_index(blob.as_ref(), font.index()) else {+ continue;+ };+ let name = fr+ .localized_strings(StringId::POSTSCRIPT_NAME)+ .english_or_first()+ .map(|s| s.to_string());+ if name.as_deref() == Some(ps) {+ return Some(ResolvedFont {+ family: info.name().to_string(),+ weight: font.weight().value().round() as u16,+ italic: !matches!(font.style(), FontStyle::Normal),+ exact: true,+ });+ }+ }+ }+ None+ }+}++/// Number of faces in a font file (1 for TTF/OTF, n for TTC/OTC, 0 if unreadable).+pub fn face_count(bytes: &[u8]) -> usize {+ match FileRef::new(bytes) {+ Ok(FileRef::Font(_)) => 1,+ Ok(FileRef::Collection(c)) => c.len() as usize,+ Err(_) => 0,+ }+}++/// Heuristic PostScript-name split: `MyriadPro-BoldIt` → ("Myriad Pro", 700, italic).+pub fn guess_from_postscript(ps: &str) -> ResolvedFont {+ let (fam, style) = ps.split_once('-').unwrap_or((ps, ""));+ let fam = fam+ .trim_end_matches("MT")+ .trim_end_matches("PS")+ .trim_end_matches("Std")+ .trim_end_matches("Pro");+ let pro = ps.split_once('-').map_or(ps, |p| p.0);+ let suffix = if pro.ends_with("Pro") {+ " Pro"+ } else if pro.ends_with("Std") {+ " Std"+ } else {+ ""+ };+ // Split camel case: "TimesNewRoman" → "Times New Roman".+ let mut family = String::new();+ let chars: Vec<char> = fam.chars().collect();+ for (i, &c) in chars.iter().enumerate() {+ if i > 0+ && c.is_uppercase()+ && (chars[i - 1].is_lowercase()+ || chars.get(i + 1).is_some_and(|n| n.is_lowercase())+ && chars[i - 1].is_uppercase())+ {+ family.push(' ');+ }+ family.push(c);+ }+ family.push_str(suffix);+ let s = style.to_lowercase();+ let weight = if s.contains("thin") || s.contains("hairline") {+ 100+ } else if s.contains("extralight") || s.contains("ultralight") {+ 200+ } else if s.contains("light") {+ 300+ } else if s.contains("medium") {+ 500+ } else if s.contains("semibold") || s.contains("demibold") || s.contains("demi") {+ 600+ } else if s.contains("extrabold") || s.contains("ultrabold") || s.contains("heavy") {+ 800+ } else if s.contains("black") {+ 900+ } else if s.contains("bold") {+ 700+ } else {+ 400+ };+ let italic = s.contains("italic") || s.ends_with("it") || s.contains("oblique");+ ResolvedFont {+ family: family.trim().to_string(),+ weight,+ italic,+ exact: false,+ }+}++#[cfg(not(target_arch = "wasm32"))]+fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec<std::path::PathBuf>) {+ let Ok(rd) = std::fs::read_dir(dir) else {+ return;+ };+ for e in rd.flatten() {+ let p = e.path();+ if p.is_dir() {+ if depth < 8 {+ collect_font_files(&p, depth + 1, out);+ }+ } else if p.extension().and_then(|x| x.to_str()).is_some_and(|x| {+ matches!(+ x.to_ascii_lowercase().as_str(),+ "ttf" | "otf" | "ttc" | "otc"+ )+ }) {+ out.push(p);+ }+ }+}++#[cfg(not(target_arch = "wasm32"))]+fn system_font_dirs() -> Vec<std::path::PathBuf> {+ use std::path::PathBuf;+ let home = std::env::var_os("HOME").map(PathBuf::from);+ let mut v = Vec::new();+ if cfg!(target_os = "macos") {+ v.push(PathBuf::from("/System/Library/Fonts"));+ v.push(PathBuf::from("/Library/Fonts"));+ if let Some(h) = &home {+ v.push(h.join("Library/Fonts"));+ }+ } else if cfg!(target_os = "windows") {+ let windir =+ std::env::var_os("WINDIR").map_or_else(|| PathBuf::from("C:\\Windows"), PathBuf::from);+ v.push(windir.join("Fonts"));+ if let Some(l) = std::env::var_os("LOCALAPPDATA") {+ v.push(PathBuf::from(l).join("Microsoft\\Windows\\Fonts"));+ }+ } else {+ v.push(PathBuf::from("/usr/share/fonts"));+ v.push(PathBuf::from("/usr/local/share/fonts"));+ if let Some(d) = std::env::var_os("XDG_DATA_HOME") {+ v.push(PathBuf::from(d).join("fonts"));+ }+ if let Some(h) = &home {+ v.push(h.join(".local/share/fonts"));+ v.push(h.join(".fonts"));+ }+ }+ v+}diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rsnew file mode 100644index 000000000..004a055c6--- /dev/null+++ b/crates/text/src/layout.rs@@ -0,0 +1,639 @@+//! Shaping and layout of a text layer's model into positioned glyphs (text-space pixels, y down,+//! first baseline of point text at y = 0).+//!+//! Each paragraph is shaped and line-broken by parley (HarfRust shaping, Unicode bidi and line+//! breaking); paragraphs are then stacked with Photoshop's rules: baseline-to-baseline distance =+//! the largest leading on the line (auto leading = paragraph factor × size), space before/after,+//! indents, and point-text alignment around the anchor.++use std::borrow::Cow;+use std::ops::Range;++use parley::{+ Alignment, AlignmentOptions, FontData, FontFamily, FontFeatures, FontStyle, FontVariations,+ FontWeight, IndentOptions, Layout, LayoutContext, PositionedLayoutItem, StyleProperty,+};+use photocraft_doc::TextLayer;+use photocraft_doc::text::{Caps, CharStyle, Kerning, TextAlign, TextDirection, TextShape};++use crate::fonts::FontDb;++/// Index of the character run whose style a glyph uses.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct RunBrush(pub u32);++/// A font instance used by some glyphs.+#[derive(Clone, Debug)]+pub struct GlyphFace {+ pub font: FontData,+ /// Normalised variation coordinates (F2Dot14 bits).+ pub coords: Vec<i16>,+ pub size_px: f32,+ /// Synthetic bold requested by font matching (face lacks the weight).+ pub embolden: bool,+ /// Synthetic oblique angle in degrees (face lacks italics).+ pub skew_deg: f32,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PlacedGlyph {+ pub face: u32,+ pub id: u32,+ /// Pen position (text space px): x along the baseline, y = baseline (before baseline shift).+ pub x: f32,+ pub y: f32,+ /// Character run index (into [`TextLayout::styles`]).+ pub style: u32,+}++/// Underline/strikethrough rectangle (text space px).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct DecorationRect {+ pub x0: f32,+ pub y0: f32,+ pub x1: f32,+ pub y1: f32,+ pub style: u32,+}++#[derive(Clone, Debug, PartialEq)]+pub struct LineInfo {+ /// Byte range in the layer text (without the paragraph break).+ pub range: Range<usize>,+ pub baseline: f32,+ /// Visual extent along the baseline.+ pub x0: f32,+ pub x1: f32,+ pub ascent: f32,+ pub descent: f32,+ pub paragraph: usize,+}++/// A grapheme cluster (caret stops, hit testing, selection).+#[derive(Clone, Debug, PartialEq)]+pub struct ClusterInfo {+ pub range: Range<usize>,+ pub x: f32,+ pub advance: f32,+ pub line: usize,+ pub rtl: bool,+}++/// Result of laying out a text layer.+#[derive(Clone, Debug, Default)]+pub struct TextLayout {+ pub faces: Vec<GlyphFace>,+ pub glyphs: Vec<PlacedGlyph>,+ pub decorations: Vec<DecorationRect>,+ pub lines: Vec<LineInfo>,+ pub clusters: Vec<ClusterInfo>,+ /// Resolved character styles (one per run of the layer).+ pub styles: Vec<CharStyle>,+ /// Pixels per point used (dpi / 72).+ pub px_per_pt: f32,+}++impl TextLayout {+ /// Logical bounds (x0, y0, x1, y1) of all lines, text space.+ pub fn bounds(&self) -> Option<[f32; 4]> {+ self.lines.iter().fold(None, |acc, l| {+ let r = [l.x0, l.baseline - l.ascent, l.x1, l.baseline + l.descent];+ Some(match acc {+ None => r,+ Some(a) => [+ a[0].min(r[0]),+ a[1].min(r[1]),+ a[2].max(r[2]),+ a[3].max(r[3]),+ ],+ })+ })+ }++ /// Byte offset of the caret nearest to a text-space point.+ pub fn hit_test(&self, x: f32, y: f32) -> usize {+ let Some((li, line)) = self.lines.iter().enumerate().min_by(|a, b| {+ let d = |l: &LineInfo| {+ if y < l.baseline - l.ascent {+ l.baseline - l.ascent - y+ } else if y > l.baseline + l.descent {+ y - l.baseline - l.descent+ } else {+ 0.0+ }+ };+ d(a.1).total_cmp(&d(b.1))+ }) else {+ return 0;+ };+ let mut best = (f32::MAX, line.range.end);+ for c in self.clusters.iter().filter(|c| c.line == li) {+ let mid = c.x + c.advance / 2.0;+ let (before, after) = if c.rtl {+ (c.range.end, c.range.start)+ } else {+ (c.range.start, c.range.end)+ };+ let (dist, off) = if x < mid {+ ((x - c.x).abs(), before)+ } else {+ ((x - c.x - c.advance).abs(), after)+ };+ if dist < best.0 {+ best = (dist, off);+ }+ }+ best.1+ }++ /// Caret geometry for a byte offset: (x, top, bottom) in text space.+ pub fn caret(&self, offset: usize) -> (f32, f32, f32) {+ for c in &self.clusters {+ if c.range.start == offset {+ let l = &self.lines[c.line];+ let x = if c.rtl { c.x + c.advance } else { c.x };+ return (x, l.baseline - l.ascent, l.baseline + l.descent);+ }+ }+ // End of a line (or empty line): after the last cluster of the line containing it.+ let li = self+ .lines+ .iter()+ .position(|l| offset >= l.range.start && offset <= l.range.end)+ .unwrap_or(self.lines.len().saturating_sub(1));+ match self.lines.get(li) {+ Some(l) => {+ let x = self+ .clusters+ .iter()+ .filter(|c| c.line == li && c.range.end == offset)+ .map(|c| if c.rtl { c.x } else { c.x + c.advance })+ .next()+ .unwrap_or(l.x1);+ (x, l.baseline - l.ascent, l.baseline + l.descent)+ }+ None => (0.0, 0.0, 0.0),+ }+ }+}++const LRM: &str = "\u{200E}";+const RLM: &str = "\u{200F}";++pub(crate) struct Layouter {+ lcx: LayoutContext<RunBrush>,+}++impl Layouter {+ pub fn new() -> Self {+ Self {+ lcx: LayoutContext::new(),+ }+ }++ pub fn layout(&mut self, fonts: &mut FontDb, t: &TextLayer, dpi: f32) -> TextLayout {+ let k = if dpi > 0.0 { dpi / 72.0 } else { 1.0 };+ let runs = t.char_runs();+ let paras = t.paragraph_runs();+ let mut out = TextLayout {+ px_per_pt: k,+ ..Default::default()+ };+ // Resolve families (PostScript names from PSDs, unknown families).+ for r in &runs {+ let mut s = r.style.clone();+ if let Some(ps) = s.postscript_name.clone() {+ let f = fonts.resolve_postscript(&ps);+ // An exact face match wins; a guessed family only fills a missing family.+ if f.exact || (!fonts.has_family(&s.font_family) && fonts.has_family(&f.family)) {+ s.font_family = f.family;+ s.weight = f.weight;+ s.italic = f.italic;+ }+ }+ out.styles.push(s);+ }+ let run_starts: Vec<usize> = runs+ .iter()+ .scan(0, |a, r| {+ let s = *a;+ *a += r.len;+ Some(s)+ })+ .collect();+ let style_at = |off: usize| run_starts.iter().rposition(|&s| s <= off).unwrap_or(0);+ let para_starts: Vec<usize> = paras+ .iter()+ .scan(0, |a, r| {+ let s = *a;+ *a += r.len;+ Some(s)+ })+ .collect();+ let para_style_at =+ |off: usize| ¶s[para_starts.iter().rposition(|&s| s <= off).unwrap_or(0)].style;++ let text = &t.text;+ let (box_rect, is_box) = match t.shape {+ TextShape::Box {+ x,+ y,+ width,+ height,+ } => ((x, y, width, height), true),+ TextShape::Point => ((0.0, 0.0, 0.0, 0.0), false),+ };+ let mut prev_baseline: Option<f32> = None;+ let mut pending_space = 0.0f32;+ let mut stop = false;+ for (pi, prange) in split_paragraphs(text).into_iter().enumerate() {+ if stop {+ break;+ }+ let ps = para_style_at(prange.start).clone();+ let content_end = strip_break(text, &prange);+ let content = &text[prange.start..content_end];+ let prefix = match ps.direction {+ TextDirection::Auto => "",+ TextDirection::Ltr => LRM,+ TextDirection::Rtl => RLM,+ };+ let mut ptext = String::with_capacity(prefix.len() + content.len());+ ptext.push_str(prefix);+ for (i, ch) in content.char_indices() {+ let caps = out.styles[style_at(prange.start + i)].caps;+ if caps == Caps::AllCaps {+ let up: String = ch.to_uppercase().collect();+ if up.len() == ch.len_utf8() {+ ptext.push_str(&up);+ continue;+ }+ }+ ptext.push(ch);+ }+ let first_style = &out.styles[style_at(prange.start)];+ let first_px = first_style.size_pt * k;+ let fallback: Vec<String> = fonts.fallback_stack().map(str::to_string).collect();+ let mut layout: Layout<RunBrush> = {+ let mut b = self.lcx.ranged_builder(&mut fonts.fcx, &ptext, 1.0, false);+ // Paragraph-start style as the default (covers the direction mark and empty+ // paragraphs), then every run piece intersecting this paragraph.+ let si0 = style_at(prange.start);+ for p in style_props(&out.styles[si0], k, &fallback, si0 as u32) {+ b.push_default(p);+ }+ for (ri, st) in out.styles.iter().enumerate() {+ let rs = run_starts[ri];+ let (a, z) = (rs.max(prange.start), (rs + runs[ri].len).min(content_end));+ if a >= z {+ continue;+ }+ let range =+ (a - prange.start + prefix.len())..(z - prange.start + prefix.len());+ for p in style_props(st, k, &fallback, ri as u32) {+ b.push(p, range.clone());+ }+ }+ b.build(&ptext)+ };+ let indent_start = ps.start_indent_pt * k;+ let indent_end = ps.end_indent_pt * k;+ if ps.first_line_indent_pt != 0.0 {+ layout.set_text_indent(ps.first_line_indent_pt * k, IndentOptions::default());+ }+ let avail = if is_box {+ Some((box_rect.2 - indent_start - indent_end).max(1.0))+ } else {+ None+ };+ layout.break_all_lines(avail);+ let alignment = if is_box {+ match ps.align {+ TextAlign::Left => Alignment::Left,+ TextAlign::Center => Alignment::Center,+ TextAlign::Right => Alignment::Right,+ _ => Alignment::Justify,+ }+ } else {+ Alignment::Left+ };+ layout.align(+ alignment,+ AlignmentOptions {+ align_when_overflowing: !is_box,+ },+ );++ // Stack lines.+ if prev_baseline.is_some() {+ pending_space += ps.space_before_pt * k;+ }+ let nlines = layout.len();+ for (li, line) in layout.lines().enumerate() {+ let m = *line.metrics();+ // Largest leading among the glyph runs of the line.+ let mut leading = 0.0f32;+ for item in line.items() {+ if let PositionedLayoutItem::GlyphRun(gr) = item {+ let st = &out.styles[gr.style().brush.0 as usize];+ let px = gr.run().font_size();+ leading =+ leading.max(st.leading_pt.map_or(ps.auto_leading * px, |l| l * k));+ }+ }+ if leading == 0.0 {+ let st = &out.styles[style_at(prange.start)];+ leading = st+ .leading_pt+ .map_or(ps.auto_leading * st.size_pt * k, |l| l * k);+ }+ let (ascent, descent) = if m.ascent > 0.0 || m.descent > 0.0 {+ (m.ascent, m.descent)+ } else {+ (first_px * 0.8, first_px * 0.2)+ };+ let baseline = match prev_baseline {+ // Photoshop's "first baseline: ascent": the top of the tallest ascender+ // (height of 'd') touches the box top, not the font's hhea ascent.+ None if is_box => box_rect.1 + first_ascent(&line).unwrap_or(ascent),+ None => 0.0,+ Some(b) => b + leading + pending_space,+ };+ pending_space = 0.0;+ if is_box && baseline + descent > box_rect.1 + box_rect.3 + 0.5 {+ stop = true;+ break;+ }+ prev_baseline = Some(baseline);+ let last_line = li + 1 == nlines;+ let adv = m.advance - m.trailing_whitespace;+ let dx = if is_box {+ let base = box_rect.0 + indent_start;+ let slack = avail.unwrap_or(0.0) - adv;+ base + if last_line {+ match ps.align {+ TextAlign::JustifyCenter => slack * 0.5 - m.offset,+ TextAlign::JustifyRight => slack - m.offset,+ _ => 0.0,+ }+ } else {+ 0.0+ }+ } else {+ let target = match ps.align {+ TextAlign::Center | TextAlign::JustifyCenter => -adv / 2.0,+ TextAlign::Right | TextAlign::JustifyRight => -adv,+ _ => indent_start,+ };+ target - m.offset+ };+ let justify_all = is_box && last_line && ps.align == TextAlign::JustifyAll;+ let line_index = out.lines.len();+ let map =+ |o: usize| (prange.start + o.saturating_sub(prefix.len())).min(content_end);+ let lr = line.text_range();+ let g0 = out.glyphs.len();+ let c0 = out.clusters.len();+ let mut extra = 0.0f32; // horizontal-scale growth along the line+ let mut seen_runs: Vec<usize> = Vec::new();+ for item in line.items() {+ let PositionedLayoutItem::GlyphRun(gr) = item else {+ continue;+ };+ let run = gr.run();+ let si = gr.style().brush.0;+ let st = &out.styles[si as usize];+ let hs = if st.horizontal_scale > 0.0 {+ st.horizontal_scale+ } else {+ 1.0+ };+ let synth = run.synthesis();+ let face = out.faces.len() as u32;+ out.faces.push(GlyphFace {+ font: run.font().clone(),+ coords: run.normalized_coords().to_vec(),+ size_px: run.font_size(),+ embolden: synth.embolden(),+ skew_deg: synth.skew().unwrap_or(0.0),+ });+ let run_x0 = dx + gr.offset() + extra;+ if !seen_runs.contains(&run.index()) {+ seen_runs.push(run.index());+ let mut cx = run_x0;+ for c in run.visual_clusters() {+ let a = c.advance() * hs;+ let r = c.text_range();+ if r.end > prefix.len() || prefix.is_empty() {+ out.clusters.push(ClusterInfo {+ range: map(r.start)..map(r.end),+ x: cx,+ advance: a,+ line: line_index,+ rtl: c.is_rtl(),+ });+ }+ cx += a;+ }+ }+ let mut pen = gr.offset();+ for g in gr.glyphs() {+ out.glyphs.push(PlacedGlyph {+ face,+ id: g.id,+ x: dx + pen + g.x + extra,+ y: baseline + g.y,+ style: si,+ });+ extra += g.advance * (hs - 1.0);+ pen += g.advance;+ }+ let run_x1 = dx + gr.offset() + gr.advance() + extra;+ let rm = run.metrics();+ let shift = st.baseline_shift_pt * k;+ if gr.style().underline.is_some() {+ let y0 = baseline - rm.underline_offset - shift;+ out.decorations.push(DecorationRect {+ x0: run_x0,+ y0,+ x1: run_x1,+ y1: y0 + rm.underline_size.max(1.0),+ style: si,+ });+ }+ if gr.style().strikethrough.is_some() {+ let y0 = baseline - rm.strikethrough_offset - shift;+ out.decorations.push(DecorationRect {+ x0: run_x0,+ y0,+ x1: run_x1,+ y1: y0 + rm.strikethrough_size.max(1.0),+ style: si,+ });+ }+ }+ if justify_all {+ let slack = avail.unwrap_or(0.0) - (adv + extra);+ let n = out.clusters.len() - c0;+ if n > 1 && slack > 0.0 {+ let step = slack / (n - 1) as f32;+ let starts: Vec<f32> = out.clusters[c0..].iter().map(|c| c.x).collect();+ for (i, c) in out.clusters[c0..].iter_mut().enumerate() {+ c.x += step * i as f32;+ }+ for g in &mut out.glyphs[g0..] {+ let i = starts.iter().rposition(|&s| s <= g.x + 1e-3).unwrap_or(0);+ g.x += step * i as f32;+ }+ extra += slack;+ }+ }+ let x0 = dx + m.offset;+ out.lines.push(LineInfo {+ range: map(lr.start)..map(lr.end).min(content_end),+ baseline,+ x0,+ x1: x0 + adv + extra,+ ascent,+ descent,+ paragraph: pi,+ });+ }+ pending_space += ps.space_after_pt * k;+ }+ out+ }+}++/// Byte ranges of paragraphs (each including its `\r`, `\n` or `\r\n` terminator). Text ending+/// with a break yields a final empty paragraph, like Photoshop's trailing empty line.+pub fn split_paragraphs(text: &str) -> Vec<Range<usize>> {+ let b = text.as_bytes();+ let mut v = Vec::new();+ let mut start = 0;+ let mut i = 0;+ while i < b.len() {+ match b[i] {+ b'\r' => {+ let end = if b.get(i + 1) == Some(&b'\n') {+ i + 2+ } else {+ i + 1+ };+ v.push(start..end);+ start = end;+ i = end;+ }+ b'\n' => {+ v.push(start..i + 1);+ start = i + 1;+ i += 1;+ }+ _ => i += 1,+ }+ }+ v.push(start..b.len());+ v+}++fn strip_break(text: &str, r: &Range<usize>) -> usize {+ let s = &text[r.clone()];+ r.start + s.trim_end_matches(['\r', '\n']).len()+}++fn quote(s: &str) -> String {+ format!("\"{}\"", s.replace(['\\', '"'], ""))+}++fn style_props(+ st: &CharStyle,+ k: f32,+ fallback: &[String],+ idx: u32,+) -> Vec<StyleProperty<'static, RunBrush>> {+ let px = (st.size_pt * k).max(0.01);+ let mut fam: Vec<String> = Vec::new();+ if !st.font_family.is_empty() {+ fam.push(quote(&st.font_family));+ }+ fam.extend(fallback.iter().map(|f| quote(f)));+ fam.push("sans-serif".into());+ let mut feats: Vec<String> = Vec::new();+ if st.kerning == Kerning::Off {+ feats.push("\"kern\" 0".into());+ }+ if !st.ligatures {+ feats.push("\"liga\" 0".into());+ feats.push("\"clig\" 0".into());+ }+ if st.discretionary_ligatures {+ feats.push("\"dlig\" 1".into());+ }+ if st.caps == Caps::SmallCaps {+ feats.push("\"smcp\" 1".into());+ }+ for f in &st.features {+ if f.tag.len() == 4 && f.tag.is_ascii() {+ feats.push(format!("\"{}\" {}", f.tag, f.value));+ }+ }+ let vars: Vec<String> = st+ .variations+ .iter()+ .filter(|v| v.axis.len() == 4 && v.axis.is_ascii())+ .map(|v| format!("\"{}\" {}", v.axis, v.value))+ .collect();+ vec![+ StyleProperty::FontFamily(FontFamily::Source(Cow::Owned(fam.join(", ")))),+ StyleProperty::FontSize(px),+ StyleProperty::FontWeight(FontWeight::new(st.weight.clamp(1, 1000) as f32)),+ StyleProperty::FontStyle(if st.italic {+ FontStyle::Italic+ } else {+ FontStyle::Normal+ }),+ StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))),+ StyleProperty::FontVariations(FontVariations::Source(Cow::Owned(vars.join(", ")))),+ StyleProperty::LetterSpacing(st.tracking / 1000.0 * px),+ StyleProperty::Underline(st.underline),+ StyleProperty::Strikethrough(st.strikethrough),+ StyleProperty::Brush(RunBrush(idx)),+ StyleProperty::Locale(+ st.language+ .as_deref()+ .and_then(|l| parley::fontique::Language::parse(l).ok()),+ ),+ ]+}++/// Height of the lowercase ascender ('d') of the tallest run on the line.+fn first_ascent(line: &parley::Line<'_, RunBrush>) -> Option<f32> {+ use skrifa::MetadataProvider;+ let mut best: Option<f32> = None;+ for run in line.runs() {+ let fd = run.font();+ let Ok(font) = skrifa::FontRef::from_index(fd.data.as_ref(), fd.index) else {+ continue;+ };+ let coords: Vec<skrifa::instance::NormalizedCoord> = run+ .normalized_coords()+ .iter()+ .map(|&c| skrifa::instance::NormalizedCoord::from_bits(c))+ .collect();+ let loc = skrifa::instance::LocationRef::new(&coords);+ let size = skrifa::instance::Size::new(run.font_size());+ let h = font+ .charmap()+ .map('d')+ .and_then(|g| font.glyph_metrics(size, loc).bounds(g))+ .map(|b| b.y_max)+ .or_else(|| {+ let m = font.metrics(size, loc);+ m.cap_height.or(Some(m.ascent * 0.75))+ });+ if let Some(h) = h {+ best = Some(best.map_or(h, |b: f32| b.max(h)));+ }+ }+ best+}diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rsnew file mode 100644index 000000000..59f171f11--- /dev/null+++ b/crates/text/src/lib.rs@@ -0,0 +1,106 @@+//! Photocraft's type engine.+//!+//! * [`fonts::FontDb`]: bundled fonts (Inter, JetBrains Mono; always available, including on the+//! web), optional system fonts from a directory scan (no fontconfig), user font data, TrueType+//! collections, PostScript-name lookup.+//! * [`layout`]: shaping and line layout with [parley] (HarfRust shaping, bidi, line breaking),+//! point and paragraph (box) text, per-run styles, Photoshop leading/indent/spacing rules.+//! * [`render`]: anti-aliased rasterization (exact-area accumulation, f32 coverage) into a+//! [`photocraft_raster::Surface`] at any depth and colour model.+//! * [`psd`]: the PSD `TySh` block and its `EngineData` (text, fonts, runs, paragraphs, box).+//!+//! The usual entry point is [`TextEngine::render_layer`], which refreshes a+//! [`photocraft_doc::TextLayer`]'s cache from its style model.+#![forbid(unsafe_code)]++pub mod engine_data;+pub mod fonts;+pub mod layout;+pub mod psd;+pub mod raster;+pub mod render;++use photocraft_color::PixelFormat;+use photocraft_doc::TextLayer;++pub use fonts::{FaceInfo, FontDb, ResolvedFont};+pub use layout::{ClusterInfo, LineInfo, PlacedGlyph, TextLayout};+pub use render::Rendered;++/// Font database + layout context. Create once and reuse (font loading and shaping caches).+pub struct TextEngine {+ pub fonts: FontDb,+ layouter: layout::Layouter,+}++impl Default for TextEngine {+ fn default() -> Self {+ Self::new()+ }+}++impl TextEngine {+ /// Bundled fonts only: deterministic output (tests, web).+ pub fn new() -> Self {+ Self {+ fonts: FontDb::new(),+ layouter: layout::Layouter::new(),+ }+ }++ /// Bundled plus installed system fonts (native desktop).+ pub fn with_system_fonts() -> Self {+ Self {+ fonts: FontDb::with_system_fonts(),+ layouter: layout::Layouter::new(),+ }+ }++ /// Lays out a text layer (text space: pixels, before `layer.transform`).+ pub fn layout(&mut self, layer: &TextLayer, dpi: f32) -> TextLayout {+ self.layouter.layout(&mut self.fonts, layer, dpi)+ }++ /// Lays out and rasterizes a text layer into document space.+ pub fn render(+ &mut self,+ layer: &TextLayer,+ dpi: f32,+ format: PixelFormat,+ ) -> (TextLayout, Rendered) {+ let l = self.layout(layer, dpi);+ let r = render::rasterize(&l, &layer.transform, format, layer.antialias);+ (l, r)+ }++ /// Re-renders `layer.cache` from its model. Returns the document-space rectangle drawn.+ pub fn render_layer(+ &mut self,+ layer: &mut TextLayer,+ dpi: f32,+ format: PixelFormat,+ ) -> photocraft_geom::Rect {+ let (_, r) = self.render(layer, dpi, format);+ layer.cache = Some(r.surface);+ r.rect+ }+}++/// A process-wide engine for callers without their own (bundled fonts only on the web; bundled+/// plus system fonts elsewhere). Locking is cheap relative to layout.+pub fn shared() -> &'static std::sync::Mutex<TextEngine> {+ static ENGINE: std::sync::OnceLock<std::sync::Mutex<TextEngine>> = std::sync::OnceLock::new();+ ENGINE.get_or_init(|| {+ let use_system = cfg!(not(target_arch = "wasm32"))+ && !cfg!(test)+ && std::env::var_os("PHOTOCRAFT_NO_SYSTEM_FONTS").is_none();+ std::sync::Mutex::new(if use_system {+ TextEngine::with_system_fonts()+ } else {+ TextEngine::new()+ })+ })+}++#[cfg(test)]+mod tests;diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rsnew file mode 100644index 000000000..fb4a71c3e--- /dev/null+++ b/crates/text/src/psd.rs@@ -0,0 +1,860 @@+//! PSD type layers: the `TySh` block (transform + text descriptor with `EngineData` + warp) ⇄ the+//! typed [`TextLayer`] model.+//!+//! Units: EngineData sizes are in text-space units, which the `TySh` transform maps to document+//! pixels; Photoshop shows them as points at the document resolution, so+//! `size_pt = FontSize × 72 / dpi` (and likewise leading, tracking-independent lengths, indents).+//! Box bounds stay in text-space pixels.+//!+//! Writing starts from the layer's original `TySh` (when present) and patches only the text, runs,+//! paragraphs, fonts, shape and transform, so Photoshop-only settings survive an edit.++use photocraft_color::{Color, ColorMode};+use photocraft_doc::TextLayer;+use photocraft_doc::text::{+ AntiAlias, Caps, CharStyle, Kerning, Orientation, ParagraphRun, ParagraphStyle, TextAlign,+ TextRun, TextShape, TextWarp,+};+use photocraft_geom::Affine;+use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D, VersionedDescriptor};++use crate::engine_data::{self as ed, Value as E};+use crate::fonts::guess_from_postscript;++/// Parsed `TySh` contents.+#[derive(Clone, Debug, PartialEq)]+pub struct TySh {+ pub transform: Affine,+ pub text: Descriptor,+ pub warp: Option<Descriptor>,+ /// The four trailing i32 values (left, top, right, bottom).+ pub bounds: [i32; 4],+}++/// Parses a `TySh` block.+pub fn parse_tysh(data: &[u8]) -> Option<TySh> {+ let f = |at: usize| {+ data.get(at..at + 8)+ .map(|b| f64::from_be_bytes(b.try_into().unwrap_or([0; 8])))+ };+ let mut m = [0.0; 6];+ for (i, v) in m.iter_mut().enumerate() {+ *v = f(2 + i * 8)?;+ }+ let (text, used) = VersionedDescriptor::parse_prefix(data.get(52..)?).ok()?;+ let rest = data.get(52 + used..).unwrap_or(&[]);+ let (warp, wused) = match rest+ .get(2..)+ .and_then(|r| VersionedDescriptor::parse_prefix(r).ok())+ {+ Some((w, n)) => (Some(w.descriptor), n + 2),+ None => (None, 0),+ };+ let tail = rest.get(wused..).unwrap_or(&[]);+ let mut bounds = [0i32; 4];+ for (i, b) in bounds.iter_mut().enumerate() {+ if let Some(x) = tail.get(i * 4..i * 4 + 4) {+ *b = i32::from_be_bytes(x.try_into().unwrap_or([0; 4]));+ }+ }+ Some(TySh {+ transform: Affine { m },+ text: text.descriptor,+ warp,+ bounds,+ })+}++/// Serializes a `TySh` block.+pub fn write_tysh(t: &TySh) -> Vec<u8> {+ let mut v = 1u16.to_be_bytes().to_vec();+ for x in t.transform.m {+ v.extend_from_slice(&x.to_be_bytes());+ }+ v.extend_from_slice(&50u16.to_be_bytes());+ v.extend(VersionedDescriptor::new(t.text.clone()).to_bytes());+ v.extend_from_slice(&1u16.to_be_bytes());+ v.extend(VersionedDescriptor::new(t.warp.clone().unwrap_or_else(default_warp)).to_bytes());+ for b in t.bounds {+ v.extend_from_slice(&b.to_be_bytes());+ }+ v+}++fn default_warp() -> Descriptor {+ Descriptor::new("warp")+ .with("warpStyle", enumv("warpStyle", "warpNone"))+ .with("warpValue", D::Double(0.0))+ .with("warpPerspective", D::Double(0.0))+ .with("warpPerspectiveOther", D::Double(0.0))+ .with("warpRotate", enumv("Ornt", "Hrzn"))+}++fn enumv(t: &str, v: &str) -> D {+ D::Enumerated {+ type_id: Id::new(t),+ value: Id::new(v),+ }+}++fn enum_value(d: &Descriptor, key: &str) -> Option<String> {+ match d.get(key) {+ Some(D::Enumerated { value, .. }) => {+ Some(String::from_utf8_lossy(value.as_bytes()).into_owned())+ }+ _ => None,+ }+}++fn dnum(v: Option<&D>) -> Option<f64> {+ match v {+ Some(D::Double(x)) => Some(*x),+ Some(D::UnitFloat { value, .. }) => Some(*value),+ Some(D::Integer(i)) => Some(f64::from(*i)),+ _ => None,+ }+}++/// The EngineData of a text descriptor.+pub fn engine_data(text: &Descriptor) -> Option<E> {+ match text.get("EngineData") {+ Some(D::RawData(b)) => ed::parse(b).ok(),+ _ => None,+ }+}++/// Builds a [`TextLayer`] (model, text and transform; no cache, no `psd_raw`) from `TySh` data.+pub fn text_layer_from_tysh(data: &[u8], dpi: f32) -> Option<TextLayer> {+ let t = parse_tysh(data)?;+ let mut layer = TextLayer {+ transform: t.transform,+ ..Default::default()+ };+ let txt = match t.text.get("Txt ") {+ Some(D::Text(s)) => Some(s.to_string_lossy().trim_end_matches('\0').to_string()),+ _ => None,+ };+ layer.orientation = if enum_value(&t.text, "Ornt").as_deref() == Some("Vrtc") {+ Orientation::Vertical+ } else {+ Orientation::Horizontal+ };+ layer.antialias = match enum_value(&t.text, "AntA").as_deref() {+ Some("Anno") => AntiAlias::None,+ Some("antiAliasSharp" | "AnSh") => AntiAlias::Sharp,+ Some("AnCr") => AntiAlias::Crisp,+ Some("AnSt") => AntiAlias::Strong,+ _ => AntiAlias::Smooth,+ };+ if let Some(w) = &t.warp {+ let style = enum_value(w, "warpStyle").unwrap_or_else(|| "warpNone".into());+ if style != "warpNone" {+ layer.warp = Some(TextWarp {+ style,+ value: dnum(w.get("warpValue")).unwrap_or(0.0) as f32,+ horizontal_distortion: dnum(w.get("warpPerspective")).unwrap_or(0.0) as f32,+ vertical_distortion: dnum(w.get("warpPerspectiveOther")).unwrap_or(0.0) as f32,+ horizontal: enum_value(w, "warpRotate").as_deref() != Some("Vrtc"),+ });+ }+ }+ let k = 72.0 / if dpi > 0.0 { dpi } else { 72.0 };+ if let Some(e) = engine_data(&t.text) {+ apply_engine_data(&mut layer, &e, txt.as_deref(), k);+ } else {+ layer.text = txt.unwrap_or_default().replace('\r', "\n");+ }+ layer.sync_summary();+ Some(layer)+}++fn arr_f(v: Option<&E>) -> Vec<f64> {+ v.and_then(E::as_array)+ .map(|a| a.iter().filter_map(E::as_f64).collect())+ .unwrap_or_default()+}++/// Converts UTF-16 run lengths over `text` into UTF-8 byte lengths.+fn utf16_to_byte_lengths(text: &str, lens: &[f64]) -> Vec<usize> {+ let mut out = Vec::with_capacity(lens.len());+ let mut chars = text.chars().peekable();+ for &l in lens {+ let mut units = l.max(0.0) as usize;+ let mut bytes = 0;+ while units > 0 {+ match chars.next() {+ Some(c) => {+ units = units.saturating_sub(c.len_utf16());+ bytes += c.len_utf8();+ }+ None => break,+ }+ }+ out.push(bytes);+ }+ out+}++fn apply_engine_data(layer: &mut TextLayer, e: &E, txt: Option<&str>, k: f32) {+ let ed_text = e+ .path(&["EngineDict", "Editor", "Text"])+ .and_then(E::as_str)+ .unwrap_or("")+ .to_string();+ // Photoshop always ends the engine text with a paragraph break; the descriptor text doesn't.+ let text = txt+ .map(str::to_string)+ .unwrap_or_else(|| ed_text.strip_suffix('\r').unwrap_or(&ed_text).to_string());+ layer.text = text.replace('\r', "\n");+ let res = e.get("ResourceDict").or_else(|| e.get("DocumentResources"));+ let fonts: Vec<String> = res+ .and_then(|r| r.get("FontSet"))+ .and_then(E::as_array)+ .map(|a| {+ a.iter()+ .map(|f| f.get("Name").and_then(E::as_str).unwrap_or("").to_string())+ .collect()+ })+ .unwrap_or_default();+ let default_sheet = res+ .and_then(|r| r.get("TheNormalStyleSheet"))+ .and_then(E::as_i64)+ .unwrap_or(0) as usize;+ let base_style = res+ .and_then(|r| r.get("StyleSheetSet"))+ .and_then(E::as_array)+ .and_then(|a| a.get(default_sheet).or(a.first()))+ .and_then(|s| s.get("StyleSheetData"));+ let default_para_sheet = res+ .and_then(|r| r.get("TheNormalParagraphSheet"))+ .and_then(E::as_i64)+ .unwrap_or(0) as usize;+ let base_para = res+ .and_then(|r| r.get("ParagraphSheetSet"))+ .and_then(E::as_array)+ .and_then(|a| a.get(default_para_sheet).or(a.first()))+ .and_then(|s| s.get("Properties"));++ // Character runs.+ let srun = e.path(&["EngineDict", "StyleRun"]);+ let sdata: Vec<&E> = srun+ .and_then(|r| r.get("RunArray"))+ .and_then(E::as_array)+ .map(|a| {+ a.iter()+ .filter_map(|x| x.path(&["StyleSheet", "StyleSheetData"]))+ .collect()+ })+ .unwrap_or_default();+ let slens = utf16_to_byte_lengths(&ed_text, &arr_f(srun.and_then(|r| r.get("RunLengthArray"))));+ layer.runs = sdata+ .iter()+ .zip(slens)+ .map(|(d, len)| TextRun {+ len,+ style: char_style(base_style, d, &fonts, k),+ })+ .collect();++ // Paragraph runs.+ let prun = e.path(&["EngineDict", "ParagraphRun"]);+ let pdata: Vec<&E> = prun+ .and_then(|r| r.get("RunArray"))+ .and_then(E::as_array)+ .map(|a| {+ a.iter()+ .filter_map(|x| x.path(&["ParagraphSheet", "Properties"]))+ .collect()+ })+ .unwrap_or_default();+ let plens = utf16_to_byte_lengths(&ed_text, &arr_f(prun.and_then(|r| r.get("RunLengthArray"))));+ layer.paragraphs = pdata+ .iter()+ .zip(plens)+ .map(|(d, len)| ParagraphRun {+ len,+ style: para_style(base_para, d, k),+ })+ .collect();++ // Shape.+ let shape = e+ .path(&["EngineDict", "Rendered", "Shapes", "Children"])+ .and_then(E::as_array)+ .and_then(|a| a.first());+ if let Some(sh) = shape+ && sh.get("ShapeType").and_then(E::as_i64) == Some(1)+ {+ let b = arr_f(sh.path(&["Cookie", "Photoshop", "BoxBounds"]));+ if b.len() == 4 {+ layer.shape = TextShape::Box {+ x: b[0] as f32,+ y: b[1] as f32,+ width: (b[2] - b[0]) as f32,+ height: (b[3] - b[1]) as f32,+ };+ }+ }+}++fn lookup<'a>(run: &'a E, base: Option<&'a E>, key: &str) -> Option<&'a E> {+ run.get(key).or_else(|| base.and_then(|b| b.get(key)))+}++fn char_style(base: Option<&E>, d: &E, fonts: &[String], k: f32) -> CharStyle {+ let g = |key: &str| lookup(d, base, key);+ let num = |key: &str| g(key).and_then(E::as_f64);+ let flag = |key: &str| g(key).and_then(E::as_bool);+ let mut s = CharStyle::default();+ if let Some(ps) = g("Font")+ .and_then(E::as_i64)+ .and_then(|i| fonts.get(i as usize))+ {+ let r = guess_from_postscript(ps);+ s.font_family = r.family;+ s.weight = r.weight;+ s.italic = r.italic;+ s.postscript_name = Some(ps.clone());+ }+ if let Some(v) = num("FontSize") {+ s.size_pt = v as f32 * k;+ }+ if flag("AutoLeading") == Some(false)+ && let Some(v) = num("Leading")+ {+ s.leading_pt = Some(v as f32 * k);+ }+ s.tracking = num("Tracking").unwrap_or(0.0) as f32;+ s.baseline_shift_pt = num("BaselineShift").unwrap_or(0.0) as f32 * k;+ s.horizontal_scale = num("HorizontalScale").unwrap_or(1.0) as f32;+ s.vertical_scale = num("VerticalScale").unwrap_or(1.0) as f32;+ s.faux_bold = flag("FauxBold").unwrap_or(false);+ s.faux_italic = flag("FauxItalic").unwrap_or(false);+ s.underline = flag("Underline").unwrap_or(false);+ s.strikethrough = flag("Strikethrough").unwrap_or(false);+ s.ligatures = flag("Ligatures").unwrap_or(true);+ s.discretionary_ligatures = flag("DLigatures").unwrap_or(false);+ s.kerning = if flag("AutoKerning") == Some(false) {+ Kerning::Off+ } else {+ Kerning::Metrics+ };+ s.caps = match g("FontCaps").and_then(E::as_i64) {+ Some(1) => Caps::SmallCaps,+ Some(2) => Caps::AllCaps,+ _ => Caps::Normal,+ };+ if let Some(c) = g("FillColor") {+ let v = arr_f(c.get("Values"));+ let a = v.first().copied().unwrap_or(1.0) as f32;+ s.color = match v.len() {+ 5 => Color {+ mode: ColorMode::Cmyk,+ c: [v[1] as f32, v[2] as f32, v[3] as f32, v[4] as f32],+ alpha: a,+ },+ 2 => Color {+ mode: ColorMode::Grayscale,+ c: [v[1] as f32, 0.0, 0.0, 0.0],+ alpha: a,+ },+ 4 => Color::rgba(v[1] as f32, v[2] as f32, v[3] as f32, a),+ _ => Color::BLACK,+ };+ }+ s+}++fn para_style(base: Option<&E>, d: &E, k: f32) -> ParagraphStyle {+ let num = |key: &str| lookup(d, base, key).and_then(E::as_f64);+ ParagraphStyle {+ align: match num("Justification").map(|v| v as i64) {+ Some(1) => TextAlign::Right,+ Some(2) => TextAlign::Center,+ Some(3) => TextAlign::JustifyLeft,+ Some(4) => TextAlign::JustifyRight,+ Some(5) => TextAlign::JustifyCenter,+ Some(6) => TextAlign::JustifyAll,+ _ => TextAlign::Left,+ },+ first_line_indent_pt: num("FirstLineIndent").unwrap_or(0.0) as f32 * k,+ start_indent_pt: num("StartIndent").unwrap_or(0.0) as f32 * k,+ end_indent_pt: num("EndIndent").unwrap_or(0.0) as f32 * k,+ space_before_pt: num("SpaceBefore").unwrap_or(0.0) as f32 * k,+ space_after_pt: num("SpaceAfter").unwrap_or(0.0) as f32 * k,+ auto_leading: num("AutoLeading").unwrap_or(1.2) as f32,+ hyphenate: lookup(d, base, "AutoHyphenate")+ .and_then(E::as_bool)+ .unwrap_or(false),+ ..Default::default()+ }+}++// ---------- writing ----------++fn real(v: f32) -> E {+ E::Real(f64::from(v))+}++/// PostScript name for a style (the PSD `FontSet` stores these).+fn postscript_for(s: &CharStyle) -> String {+ if let Some(ps) = &s.postscript_name {+ return ps.clone();+ }+ let fam = if s.font_family.is_empty() {+ crate::fonts::DEFAULT_FAMILY+ } else {+ &s.font_family+ };+ let w = match s.weight {+ 0..=150 => "Thin",+ 151..=250 => "ExtraLight",+ 251..=350 => "Light",+ 351..=450 => "Regular",+ 451..=550 => "Medium",+ 551..=650 => "SemiBold",+ 651..=750 => "Bold",+ 751..=850 => "ExtraBold",+ _ => "Black",+ };+ let style = match (w, s.italic) {+ ("Regular", true) => "Italic".to_string(),+ (w, true) => format!("{w}Italic"),+ (w, false) => w.to_string(),+ };+ format!("{}-{style}", fam.replace(' ', ""))+}++fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E {+ let c = &s.color;+ let values = match c.mode {+ ColorMode::Cmyk => vec![+ real(c.alpha),+ real(c.c[0]),+ real(c.c[1]),+ real(c.c[2]),+ real(c.c[3]),+ ],+ ColorMode::Grayscale => vec![real(c.alpha), real(c.c[0])],+ _ => {+ let [r, g, b] = c.to_rgb();+ vec![real(c.alpha), real(r), real(g), real(b)]+ }+ };+ let color_type = match c.mode {+ ColorMode::Cmyk => 2,+ ColorMode::Grayscale => 0,+ _ => 1,+ };+ E::Dict(vec![+ ("Font".into(), E::Int(font as i64)),+ ("FontSize".into(), real(s.size_pt / k)),+ ("FauxBold".into(), E::Bool(s.faux_bold)),+ ("FauxItalic".into(), E::Bool(s.faux_italic)),+ ("AutoLeading".into(), E::Bool(s.leading_pt.is_none())),+ ("Leading".into(), real(s.leading_pt.unwrap_or(0.0) / k)),+ ("HorizontalScale".into(), real(s.horizontal_scale)),+ ("VerticalScale".into(), real(s.vertical_scale)),+ ("Tracking".into(), E::Int(s.tracking.round() as i64)),+ ("AutoKerning".into(), E::Bool(s.kerning != Kerning::Off)),+ ("Kerning".into(), E::Int(0)),+ ("BaselineShift".into(), real(s.baseline_shift_pt / k)),+ (+ "FontCaps".into(),+ E::Int(match s.caps {+ Caps::Normal => 0,+ Caps::SmallCaps => 1,+ Caps::AllCaps => 2,+ }),+ ),+ ("Underline".into(), E::Bool(s.underline)),+ ("Strikethrough".into(), E::Bool(s.strikethrough)),+ ("Ligatures".into(), E::Bool(s.ligatures)),+ ("DLigatures".into(), E::Bool(s.discretionary_ligatures)),+ (+ "FillColor".into(),+ E::Dict(vec![+ ("Type".into(), E::Int(color_type)),+ ("Values".into(), E::Array(values)),+ ]),+ ),+ ])+}++fn paragraph_properties(p: &ParagraphStyle, k: f32) -> E {+ let j = match p.align {+ TextAlign::Left => 0,+ TextAlign::Right => 1,+ TextAlign::Center => 2,+ TextAlign::JustifyLeft => 3,+ TextAlign::JustifyRight => 4,+ TextAlign::JustifyCenter => 5,+ TextAlign::JustifyAll => 6,+ };+ E::Dict(vec![+ ("Justification".into(), E::Int(j)),+ ("FirstLineIndent".into(), real(p.first_line_indent_pt / k)),+ ("StartIndent".into(), real(p.start_indent_pt / k)),+ ("EndIndent".into(), real(p.end_indent_pt / k)),+ ("SpaceBefore".into(), real(p.space_before_pt / k)),+ ("SpaceAfter".into(), real(p.space_after_pt / k)),+ ("AutoHyphenate".into(), E::Bool(p.hyphenate)),+ ("AutoLeading".into(), real(p.auto_leading)),+ ("LeadingType".into(), E::Int(0)),+ ])+}++fn utf16_len(s: &str) -> i64 {+ s.encode_utf16().count() as i64+}++fn font_entry(name: &str) -> E {+ E::Dict(vec![+ ("Name".into(), E::String(name.into())),+ ("Script".into(), E::Int(0)),+ ("FontType".into(), E::Int(1)),+ ("Synthetic".into(), E::Int(0)),+ ])+}++/// Updates (or creates) an EngineData tree for `layer`.+pub fn build_engine_data(layer: &TextLayer, template: Option<E>, dpi: f32) -> E {+ let k = 72.0 / if dpi > 0.0 { dpi } else { 72.0 };+ let mut e = template.unwrap_or_else(|| {+ E::Dict(vec![+ ("EngineDict".into(), E::dict()),+ ("ResourceDict".into(), E::dict()),+ ])+ });+ let runs = layer.char_runs();+ let paras = layer.paragraph_runs();+ let text = layer.text.replace('\n', "\r");+ let ed_text = format!("{text}\r");++ // Fonts: keep the template's font list and append new PostScript names.+ let mut fonts: Vec<String> = e+ .path(&["ResourceDict", "FontSet"])+ .and_then(E::as_array)+ .map(|a| {+ a.iter()+ .map(|f| f.get("Name").and_then(E::as_str).unwrap_or("").to_string())+ .collect()+ })+ .unwrap_or_default();+ let mut font_index = |ps: String| match fonts.iter().position(|f| *f == ps) {+ Some(i) => i,+ None => {+ fonts.push(ps);+ fonts.len() - 1+ }+ };+ let mut sruns = Vec::new();+ let mut slens = Vec::new();+ let mut at = 0usize;+ for (i, r) in runs.iter().enumerate() {+ let piece = &text[at..at + r.len];+ at += r.len;+ let mut n = utf16_len(piece);+ if i + 1 == runs.len() {+ n += 1; // trailing paragraph break+ }+ let fi = font_index(postscript_for(&r.style));+ sruns.push(E::Dict(vec![(+ "StyleSheet".into(),+ E::Dict(vec![(+ "StyleSheetData".into(),+ style_sheet_data(&r.style, fi, k),+ )]),+ )]));+ slens.push(E::Int(n));+ }+ let mut pruns = Vec::new();+ let mut plens = Vec::new();+ let mut at = 0usize;+ for (i, p) in paras.iter().enumerate() {+ let piece = &text[at..at + p.len];+ at += p.len;+ let mut n = utf16_len(piece);+ if i + 1 == paras.len() {+ n += 1;+ }+ pruns.push(E::Dict(vec![(+ "ParagraphSheet".into(),+ E::Dict(vec![+ ("DefaultStyleSheet".into(), E::Int(0)),+ ("Properties".into(), paragraph_properties(&p.style, k)),+ ]),+ )]));+ plens.push(E::Int(n));+ }+ let fontset = E::Array(fonts.iter().map(|f| font_entry(f)).collect());++ let dict = e.get_mut("EngineDict").expect("EngineDict");+ let mut editor = dict.get("Editor").cloned().unwrap_or_else(E::dict);+ editor.set("Text", E::String(ed_text));+ dict.set("Editor", editor);+ let mut pr = dict.get("ParagraphRun").cloned().unwrap_or_else(E::dict);+ pr.set("RunArray", E::Array(pruns));+ pr.set("RunLengthArray", E::Array(plens));+ if pr.get("IsJoinable").is_none() {+ pr.set("IsJoinable", E::Int(1));+ }+ dict.set("ParagraphRun", pr);+ let mut sr = dict.get("StyleRun").cloned().unwrap_or_else(E::dict);+ sr.set("RunArray", E::Array(sruns));+ sr.set("RunLengthArray", E::Array(slens));+ if sr.get("IsJoinable").is_none() {+ sr.set("IsJoinable", E::Int(2));+ }+ dict.set("StyleRun", sr);+ dict.set(+ "AntiAlias",+ E::Int(match layer.antialias {+ AntiAlias::None => 0,+ AntiAlias::Sharp => 1,+ AntiAlias::Crisp => 2,+ AntiAlias::Strong => 3,+ AntiAlias::Smooth => 4,+ }),+ );+ if dict.get("UseFractionalGlyphWidths").is_none() {+ dict.set("UseFractionalGlyphWidths", E::Bool(true));+ }+ let (shape_type, box_bounds) = match layer.shape {+ TextShape::Point => (0, None),+ TextShape::Box {+ x,+ y,+ width,+ height,+ } => (1, Some([x, y, x + width, y + height])),+ };+ let mut photoshop = E::Dict(vec![("ShapeType".into(), E::Int(shape_type))]);+ match box_bounds {+ None => photoshop.set("PointBase", E::Array(vec![real(0.0), real(0.0)])),+ Some(b) => photoshop.set("BoxBounds", E::Array(b.iter().map(|v| real(*v)).collect())),+ }+ photoshop.set(+ "Base",+ E::Dict(vec![+ ("ShapeType".into(), E::Int(shape_type)),+ (+ "TransformPoint0".into(),+ E::Array(vec![real(1.0), real(0.0)]),+ ),+ (+ "TransformPoint1".into(),+ E::Array(vec![real(0.0), real(1.0)]),+ ),+ (+ "TransformPoint2".into(),+ E::Array(vec![real(0.0), real(0.0)]),+ ),+ ]),+ );+ let child = E::Dict(vec![+ ("ShapeType".into(), E::Int(shape_type)),+ ("Procession".into(), E::Int(0)),+ (+ "Lines".into(),+ E::Dict(vec![+ ("WritingDirection".into(), E::Int(0)),+ ("Children".into(), E::Array(vec![])),+ ]),+ ),+ (+ "Cookie".into(),+ E::Dict(vec![("Photoshop".into(), photoshop)]),+ ),+ ]);+ dict.set(+ "Rendered",+ E::Dict(vec![+ ("Version".into(), E::Int(1)),+ (+ "Shapes".into(),+ E::Dict(vec![+ ("WritingDirection".into(), E::Int(0)),+ ("Children".into(), E::Array(vec![child])),+ ]),+ ),+ ]),+ );++ for key in ["ResourceDict", "DocumentResources"] {+ if key == "DocumentResources" && e.get(key).is_none() {+ let rd = e.get("ResourceDict").cloned().unwrap_or_else(E::dict);+ e.set(key, rd);+ continue;+ }+ let Some(rd) = e.get_mut(key) else { continue };+ rd.set("FontSet", fontset.clone());+ if rd.get("StyleSheetSet").is_none() {+ let base = runs.first().map(|r| r.style.clone()).unwrap_or_default();+ rd.set(+ "StyleSheetSet",+ E::Array(vec![E::Dict(vec![+ ("Name".into(), E::String("Normal RGB".into())),+ ("StyleSheetData".into(), style_sheet_data(&base, 0, k)),+ ])]),+ );+ }+ if rd.get("ParagraphSheetSet").is_none() {+ rd.set(+ "ParagraphSheetSet",+ E::Array(vec![E::Dict(vec![+ ("Name".into(), E::String("Normal RGB".into())),+ ("DefaultStyleSheet".into(), E::Int(0)),+ (+ "Properties".into(),+ paragraph_properties(&ParagraphStyle::default(), k),+ ),+ ])]),+ );+ }+ for (k2, v) in [("TheNormalStyleSheet", 0), ("TheNormalParagraphSheet", 0)] {+ if rd.get(k2).is_none() {+ rd.set(k2, E::Int(v));+ }+ }+ }+ e+}++/// Builds the `TySh` block for `layer`, patching its current `psd_raw` when present.+/// `ink` is the layer's rendered bounds in text space (for `bounds`/`boundingBox`).+pub fn build_tysh(layer: &TextLayer, dpi: f32, ink: Option<[f32; 4]>) -> Vec<u8> {+ let old = layer.psd_raw.as_deref().and_then(|d| parse_tysh(d));+ let template = old.as_ref().and_then(|t| engine_data(&t.text));+ let e = build_engine_data(layer, template, dpi);+ let mut text = old+ .as_ref()+ .map(|t| t.text.clone())+ .unwrap_or_else(|| Descriptor::new("TxLr"));+ let set =+ |d: &mut Descriptor, key: &str, v: D| match d.items.iter_mut().find(|(k, _)| k.is(key)) {+ Some(e) => e.1 = v,+ None => d.items.push((Id::new(key), v)),+ };+ set(+ &mut text,+ "Txt ",+ D::Text(UnicodeString::new_nul(&layer.text.replace('\n', "\r"))),+ );+ if text.get("textGridding").is_none() {+ set(&mut text, "textGridding", enumv("textGridding", "None"));+ }+ set(+ &mut text,+ "Ornt",+ enumv(+ "Ornt",+ if layer.orientation == Orientation::Vertical {+ "Vrtc"+ } else {+ "Hrzn"+ },+ ),+ );+ set(+ &mut text,+ "AntA",+ enumv(+ "Annt",+ match layer.antialias {+ AntiAlias::None => "Anno",+ AntiAlias::Sharp => "antiAliasSharp",+ AntiAlias::Crisp => "AnCr",+ AntiAlias::Strong => "AnSt",+ AntiAlias::Smooth => "AnSm",+ },+ ),+ );+ let [l, t, r, b] = match (layer.shape, ink) {+ (+ TextShape::Box {+ x,+ y,+ width,+ height,+ },+ _,+ ) => [x, y, x + width, y + height],+ (_, Some(i)) => i,+ _ => [0.0; 4],+ };+ let rect = |cls: &str| {+ D::Descriptor(+ Descriptor::new(cls)+ .with(+ "Left",+ D::UnitFloat {+ unit: *b"#Pnt",+ value: f64::from(l),+ },+ )+ .with(+ "Top ",+ D::UnitFloat {+ unit: *b"#Pnt",+ value: f64::from(t),+ },+ )+ .with(+ "Rght",+ D::UnitFloat {+ unit: *b"#Pnt",+ value: f64::from(r),+ },+ )+ .with(+ "Btom",+ D::UnitFloat {+ unit: *b"#Pnt",+ value: f64::from(b),+ },+ ),+ )+ };+ set(&mut text, "bounds", rect("bounds"));+ set(&mut text, "boundingBox", rect("boundingBox"));+ if text.get("TextIndex").is_none() {+ set(&mut text, "TextIndex", D::Integer(0));+ }+ set(&mut text, "EngineData", D::RawData(ed::write(&e)));+ let warp = match (&layer.warp, old.as_ref().and_then(|o| o.warp.clone())) {+ (Some(w), _) => Some(+ Descriptor::new("warp")+ .with("warpStyle", enumv("warpStyle", &w.style))+ .with("warpValue", D::Double(f64::from(w.value)))+ .with(+ "warpPerspective",+ D::Double(f64::from(w.horizontal_distortion)),+ )+ .with(+ "warpPerspectiveOther",+ D::Double(f64::from(w.vertical_distortion)),+ )+ .with(+ "warpRotate",+ enumv("Ornt", if w.horizontal { "Hrzn" } else { "Vrtc" }),+ ),+ ),+ (None, Some(old)) if enum_value(&old, "warpStyle").as_deref() == Some("warpNone") => {+ Some(old)+ }+ _ => None,+ };+ let bounds = [+ l.floor() as i32,+ t.floor() as i32,+ r.ceil() as i32,+ b.ceil() as i32,+ ];+ write_tysh(&TySh {+ transform: layer.transform,+ text,+ warp,+ bounds,+ })+}diff --git a/crates/text/src/raster.rs b/crates/text/src/raster.rsnew file mode 100644index 000000000..5a8482d5a--- /dev/null+++ b/crates/text/src/raster.rs@@ -0,0 +1,315 @@+//! Anti-aliased path rasterizer: exact signed-area accumulation (the "font-rs" technique), f32+//! coverage, nonzero-ish fill (|winding| clamped to 1). Curves are flattened to lines.++/// A 2D affine map `[a c e; b d f]`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Xform(pub [f64; 6]);++impl Xform {+ pub const IDENTITY: Xform = Xform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);+ pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {+ let [a, b, c, d, e, f] = self.0;+ (a * x + c * y + e, b * x + d * y + f)+ }+ /// `self ∘ o` (apply `o` first).+ pub fn mul(&self, o: &Xform) -> Xform {+ let [a, b, c, d, e, f] = self.0;+ let [oa, ob, oc, od, oe, of] = o.0;+ Xform([+ a * oa + c * ob,+ b * oa + d * ob,+ a * oc + c * od,+ b * oc + d * od,+ a * oe + c * of + e,+ b * oe + d * of + f,+ ])+ }+ /// Largest scale factor (for flattening tolerance).+ pub fn max_scale(&self) -> f64 {+ let [a, b, c, d, ..] = self.0;+ (a * a + b * b).sqrt().max((c * c + d * d).sqrt())+ }+}++/// Receives flattened line segments.+pub trait LineSink {+ fn line(&mut self, p0: (f64, f64), p1: (f64, f64));+}++/// Collects the bounding box of everything drawn.+#[derive(Clone, Copy, Debug, Default)]+pub struct Bounds {+ pub rect: Option<[f64; 4]>,+}++impl Bounds {+ pub fn add(&mut self, p: (f64, f64)) {+ if !(p.0.is_finite() && p.1.is_finite()) {+ return;+ }+ self.rect = Some(match self.rect {+ None => [p.0, p.1, p.0, p.1],+ Some(r) => [r[0].min(p.0), r[1].min(p.1), r[2].max(p.0), r[3].max(p.1)],+ });+ }+}++impl LineSink for Bounds {+ fn line(&mut self, p0: (f64, f64), p1: (f64, f64)) {+ self.add(p0);+ self.add(p1);+ }+}++impl LineSink for Coverage {+ fn line(&mut self, p0: (f64, f64), p1: (f64, f64)) {+ Coverage::line(self, p0, p1);+ }+}++/// Adds a transformed axis-aligned rectangle.+pub fn rect_to(sink: &mut impl LineSink, xf: &Xform, x0: f64, y0: f64, x1: f64, y1: f64) {+ let p = [+ xf.apply(x0, y0),+ xf.apply(x1, y0),+ xf.apply(x1, y1),+ xf.apply(x0, y1),+ ];+ for i in 0..4 {+ sink.line(p[i], p[(i + 1) % 4]);+ }+}++/// Coverage accumulation buffer of `width × height` pixels.+pub struct Coverage {+ pub width: usize,+ pub height: usize,+ acc: Vec<f32>,+}++impl Coverage {+ pub fn new(width: usize, height: usize) -> Self {+ Self {+ width,+ height,+ acc: vec![0.0; width * height + 2],+ }+ }++ /// Adds a line segment (pixel coordinates, y down).+ pub fn line(&mut self, p0: (f64, f64), p1: (f64, f64)) {+ let (w, h) = (self.width as f32, self.height as f32);+ if p0.1 == p1.1+ || !(p0.0.is_finite() && p0.1.is_finite() && p1.0.is_finite() && p1.1.is_finite())+ {+ return;+ }+ let (dir, (x0, y0), (x1, y1)) = if p0.1 < p1.1 {+ (1.0f32, p0, p1)+ } else {+ (-1.0f32, p1, p0)+ };+ let (x0, y0, x1, y1) = (x0 as f32, y0 as f32, x1 as f32, y1 as f32);+ if y1 <= 0.0 || y0 >= h {+ return;+ }+ let dxdy = (x1 - x0) / (y1 - y0);+ let mut x = x0;+ let ys = y0.max(0.0);+ if y0 < 0.0 {+ x -= y0 * dxdy;+ }+ let ye = y1.min(h);+ let stride = self.width;+ let mut y = ys;+ let mut row = ys.floor() as usize;+ while y < ye {+ let ynext = ((row + 1) as f32).min(ye);+ let dy = ynext - y;+ let xnext = x + dxdy * dy;+ let d = dy * dir;+ let (xa, xb) = if x < xnext { (x, xnext) } else { (xnext, x) };+ let (xa, xb) = (xa.clamp(0.0, w), xb.clamp(0.0, w));+ let ls = row * stride;+ let x0f = xa.floor();+ let x0i = x0f as usize;+ let x1c = xb.ceil();+ let x1i = x1c as usize;+ if x1i <= x0i + 1 {+ let xmf = 0.5 * (xa + xb) - x0f;+ self.acc[ls + x0i] += d - d * xmf;+ self.acc[ls + x0i + 1] += d * xmf;+ } else {+ let s = 1.0 / (xb - xa);+ let x0frac = xa - x0f;+ let a0 = 0.5 * s * (1.0 - x0frac) * (1.0 - x0frac);+ let x1frac = xb - x1c + 1.0;+ let am = 0.5 * s * x1frac * x1frac;+ self.acc[ls + x0i] += d * a0;+ if x1i == x0i + 2 {+ self.acc[ls + x0i + 1] += d * (1.0 - a0 - am);+ } else {+ let a1 = s * (1.5 - x0frac);+ self.acc[ls + x0i + 1] += d * (a1 - a0);+ for xi in x0i + 2..x1i - 1 {+ self.acc[ls + xi] += d * s;+ }+ let a2 = a1 + (x1i - x0i - 3) as f32 * s;+ self.acc[ls + x1i - 1] += d * (1.0 - a2 - am);+ }+ self.acc[ls + x1i] += d * am;+ }+ x = xnext;+ y = ynext;+ row += 1;+ }+ }++ /// Resolves the accumulation into per-pixel coverage in 0..=1.+ pub fn finish(self) -> Vec<f32> {+ let n = self.width * self.height;+ let mut out = Vec::with_capacity(n);+ let mut sum = 0.0f32;+ for v in &self.acc[..n] {+ sum += v;+ out.push(sum.abs().min(1.0));+ }+ out+ }+}++/// Outline pen that transforms font-space points (y up) and flattens curves into a [`Coverage`].+pub struct Pen<'a, S: LineSink> {+ pub cov: &'a mut S,+ pub xf: Xform,+ start: (f64, f64),+ last: (f64, f64),+ /// Flattening tolerance in output pixels.+ tol: f64,+}++impl<'a, S: LineSink> Pen<'a, S> {+ pub fn new(cov: &'a mut S, xf: Xform) -> Self {+ Pen {+ cov,+ xf,+ start: (0.0, 0.0),+ last: (0.0, 0.0),+ tol: 0.03,+ }+ }+ fn to(&mut self, p: (f64, f64)) {+ self.cov.line(self.last, p);+ self.last = p;+ }+ fn segments(&self, a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> usize {+ // Deviation of the control polygon from the chord bounds the flattening error.+ let dd = ((a.0 - 2.0 * b.0 + c.0).powi(2) + (a.1 - 2.0 * b.1 + c.1).powi(2)).sqrt();+ ((0.75 * dd / self.tol).sqrt().ceil() as usize).clamp(1, 100)+ }+}++impl<S: LineSink> skrifa::outline::OutlinePen for Pen<'_, S> {+ fn move_to(&mut self, x: f32, y: f32) {+ self.close();+ let p = self.xf.apply(x as f64, y as f64);+ self.start = p;+ self.last = p;+ }+ fn line_to(&mut self, x: f32, y: f32) {+ let p = self.xf.apply(x as f64, y as f64);+ self.to(p);+ }+ fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {+ let a = self.last;+ let b = self.xf.apply(cx0 as f64, cy0 as f64);+ let c = self.xf.apply(x as f64, y as f64);+ let n = self.segments(a, b, c);+ for i in 1..=n {+ let t = i as f64 / n as f64;+ let mt = 1.0 - t;+ let p = (+ mt * mt * a.0 + 2.0 * mt * t * b.0 + t * t * c.0,+ mt * mt * a.1 + 2.0 * mt * t * b.1 + t * t * c.1,+ );+ self.to(p);+ }+ }+ fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {+ let a = self.last;+ let b = self.xf.apply(cx0 as f64, cy0 as f64);+ let c = self.xf.apply(cx1 as f64, cy1 as f64);+ let d = self.xf.apply(x as f64, y as f64);+ let n = self.segments(a, b, c).max(self.segments(b, c, d));+ for i in 1..=n {+ let t = i as f64 / n as f64;+ let mt = 1.0 - t;+ let (k0, k1, k2, k3) = (mt * mt * mt, 3.0 * mt * mt * t, 3.0 * mt * t * t, t * t * t);+ let p = (+ k0 * a.0 + k1 * b.0 + k2 * c.0 + k3 * d.0,+ k0 * a.1 + k1 * b.1 + k2 * c.1 + k3 * d.1,+ );+ self.to(p);+ }+ }+ fn close(&mut self) {+ if self.last != self.start {+ let s = self.start;+ self.to(s);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sum(v: &[f32]) -> f32 {+ v.iter().sum()+ }++ #[test]+ fn square_area_exact() {+ let mut c = Coverage::new(10, 10);+ rect_to(&mut c, &Xform::IDENTITY, 2.25, 3.5, 6.75, 8.0);+ let v = c.finish();+ assert!((sum(&v) - 4.5 * 4.5).abs() < 1e-3, "{}", sum(&v));+ assert_eq!(v[5 * 10 + 4], 1.0);+ assert_eq!(v[0], 0.0);+ }++ #[test]+ fn triangle_area_and_clipping() {+ let mut c = Coverage::new(8, 8);+ // Right triangle partly outside on the left and bottom.+ let pts = [(-4.0, 2.0), (6.0, 2.0), (-4.0, 12.0)];+ for i in 0..3 {+ c.line(pts[i], pts[(i + 1) % 3]);+ }+ let v = c.finish();+ // Visible part: region x in [0,6], y in [2,8] under the hypotenuse x + y <= 8.+ // Area = ∫_{y=2}^{8} (8 - y) dy = 18.+ assert!((sum(&v) - 18.0).abs() < 1e-3, "{}", sum(&v));+ assert!(v.iter().all(|x| (0.0..=1.0).contains(x)));+ }++ #[test]+ fn circle_area_via_pen() {+ use skrifa::outline::OutlinePen;+ let mut c = Coverage::new(40, 40);+ {+ let mut p = Pen::new(&mut c, Xform([1.0, 0.0, 0.0, -1.0, 20.0, 20.0]));+ // Cubic circle approximation, r = 15.+ let (r, k) = (15.0f32, 0.552_284_8f32 * 15.0);+ p.move_to(r, 0.0);+ p.curve_to(r, k, k, r, 0.0, r);+ p.curve_to(-k, r, -r, k, -r, 0.0);+ p.curve_to(-r, -k, -k, -r, 0.0, -r);+ p.curve_to(k, -r, r, -k, r, 0.0);+ p.close();+ }+ let a = sum(&c.finish());+ let exact = std::f32::consts::PI * 225.0;+ assert!((a - exact).abs() / exact < 0.005, "{a} vs {exact}");+ }+}diff --git a/crates/text/src/render.rs b/crates/text/src/render.rsnew file mode 100644index 000000000..cbfc72b3f--- /dev/null+++ b/crates/text/src/render.rs@@ -0,0 +1,212 @@+//! Rasterizes a [`TextLayout`] into a document-space [`Surface`] of any pixel format.++use photocraft_color::{Color, PixelFormat};+use photocraft_doc::text::AntiAlias;+use photocraft_geom::{Affine, Rect};+use photocraft_raster::Surface;+use skrifa::instance::{LocationRef, NormalizedCoord, Size};+use skrifa::outline::DrawSettings;+use skrifa::{GlyphId, MetadataProvider};++use crate::layout::TextLayout;+use crate::raster::{Bounds, Coverage, LineSink, Pen, Xform, rect_to};++/// Faux-italic slant in degrees (Photoshop-like).+pub const FAUX_ITALIC_DEG: f32 = 12.0;+/// Faux-bold dilation radius as a fraction of the font size.+pub const FAUX_BOLD_RADIUS: f32 = 0.018;+/// Largest raster we produce (pixels), as a guard against absurd sizes.+const MAX_PIXELS: u64 = 256 * 1024 * 1024;++/// Rendered text: pixels in document space plus the covered rectangle.+pub struct Rendered {+ pub surface: Surface,+ pub rect: Rect,+}++/// Draws every glyph and decoration of `layout` whose style colour is `color` (or all of them+/// when `color` is `None`) into `sink`, through `transform` (text space → sink space).+fn draw(+ layout: &TextLayout,+ transform: &Xform,+ sink: &mut impl LineSink,+ only_color: Option<&Color>,+) {+ for g in &layout.glyphs {+ let st = &layout.styles[g.style as usize];+ if only_color.is_some_and(|c| c != &st.color) {+ continue;+ }+ let face = &layout.faces[g.face as usize];+ let Ok(font) = skrifa::FontRef::from_index(face.font.data.as_ref(), face.font.index) else {+ continue;+ };+ let Some(outline) = font.outline_glyphs().get(GlyphId::new(g.id)) else {+ continue;+ };+ let coords: Vec<NormalizedCoord> = face+ .coords+ .iter()+ .map(|&c| NormalizedCoord::from_bits(c))+ .collect();+ let hs = if st.horizontal_scale > 0.0 {+ st.horizontal_scale+ } else {+ 1.0+ } as f64;+ let vs = if st.vertical_scale > 0.0 {+ st.vertical_scale+ } else {+ 1.0+ } as f64;+ let skew_deg = if st.faux_italic { FAUX_ITALIC_DEG } else { 0.0 } + face.skew_deg;+ let skew = (skew_deg as f64).to_radians().tan() * vs;+ let shift = (st.baseline_shift_pt * layout.px_per_pt) as f64;+ let glyph = Xform([hs, 0.0, skew, -vs, g.x as f64, g.y as f64 - shift]);+ let bold = st.faux_bold || face.embolden;+ let r = (face.size_px * FAUX_BOLD_RADIUS) as f64;+ let offsets: &[(f64, f64)] = if bold {+ &[+ (-1.0, 0.0),+ (1.0, 0.0),+ (0.0, -1.0),+ (0.0, 1.0),+ (0.7, 0.7),+ (-0.7, -0.7),+ (0.7, -0.7),+ (-0.7, 0.7),+ ]+ } else {+ &[(0.0, 0.0)]+ };+ for &(ox, oy) in offsets {+ let xf = transform+ .mul(&Xform([1.0, 0.0, 0.0, 1.0, ox * r, oy * r]))+ .mul(&glyph);+ let mut pen = Pen::new(sink, xf);+ let settings =+ DrawSettings::unhinted(Size::new(face.size_px), LocationRef::new(&coords));+ if outline.draw(settings, &mut pen).is_ok() {+ skrifa::outline::OutlinePen::close(&mut pen);+ }+ }+ }+ for d in &layout.decorations {+ let st = &layout.styles[d.style as usize];+ if only_color.is_some_and(|c| c != &st.color) {+ continue;+ }+ rect_to(+ sink,+ transform,+ d.x0 as f64,+ d.y0 as f64,+ d.x1 as f64,+ d.y1 as f64,+ );+ }+}++/// Colour components in `format`'s model (without alpha).+fn color_in(format: &PixelFormat, c: &Color) -> Vec<f32> {+ let n = format.mode.color_channels();+ if c.mode == format.mode {+ c.c[..n].to_vec()+ } else {+ let [r, g, b] = c.to_rgb();+ let mut v = photocraft_raster::from_rgba(+ &PixelFormat {+ alpha: false,+ ..*format+ },+ [r, g, b, 1.0],+ );+ v.truncate(n);+ v+ }+}++/// Document-space bounds of the drawn text (integer pixel rectangle).+pub fn ink_rect(layout: &TextLayout, transform: &Affine) -> Rect {+ let mut b = Bounds::default();+ draw(layout, &Xform(transform.m), &mut b, None);+ match b.rect {+ Some([x0, y0, x1, y1]) => Rect::new(+ x0.floor() as i32 - 1,+ y0.floor() as i32 - 1,+ x1.ceil() as i32 + 1,+ y1.ceil() as i32 + 1,+ ),+ None => Rect::new(0, 0, 0, 0),+ }+}++/// Rasterizes `layout` through `transform` (text space → document pixels). The result always+/// has an alpha channel; colour is written in `format`'s colour model and sample depth.+pub fn rasterize(+ layout: &TextLayout,+ transform: &Affine,+ format: PixelFormat,+ antialias: AntiAlias,+) -> Rendered {+ let format = PixelFormat {+ alpha: true,+ ..format+ };+ let rect = ink_rect(layout, transform);+ let (w, h) = (rect.width() as usize, rect.height() as usize);+ let mut surface = Surface::new(format);+ if w == 0 || h == 0 || (w as u64) * (h as u64) > MAX_PIXELS {+ return Rendered {+ surface,+ rect: Rect::new(0, 0, 0, 0),+ };+ }+ let n = format.mode.color_channels();+ let stride = n + 1;+ // Premultiplied accumulation.+ let mut acc = vec![0.0f32; w * h * stride];+ let xf = Xform([1.0, 0.0, 0.0, 1.0, -rect.x0 as f64, -rect.y0 as f64]).mul(&Xform(transform.m));+ let mut colors: Vec<Color> = Vec::new();+ for st in &layout.styles {+ if !colors.contains(&st.color) {+ colors.push(st.color);+ }+ }+ for c in &colors {+ let mut cov = Coverage::new(w, h);+ draw(layout, &xf, &mut cov, Some(c));+ let cov = cov.finish();+ let comps = color_in(&format, c);+ let a = c.alpha.clamp(0.0, 1.0);+ for (i, &cv) in cov.iter().enumerate() {+ let cv = if antialias == AntiAlias::None {+ if cv >= 0.5 { 1.0 } else { 0.0 }+ } else {+ cv+ };+ let s = cv * a;+ if s <= 0.0 {+ continue;+ }+ let px = &mut acc[i * stride..(i + 1) * stride];+ let keep = 1.0 - s;+ for j in 0..n {+ px[j] = comps[j] * s + px[j] * keep;+ }+ px[n] = s + px[n] * keep;+ }+ }+ // Unpremultiply.+ for px in acc.chunks_exact_mut(stride) {+ let a = px[n];+ if a > 0.0 {+ for v in &mut px[..n] {+ *v = (*v / a).clamp(0.0, 1.0);+ }+ }+ }+ surface.write_region(rect, &acc);+ surface.prune();+ Rendered { surface, rect }+}diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rsnew file mode 100644index 000000000..96b55ed4f--- /dev/null+++ b/crates/text/src/tests.rs@@ -0,0 +1,750 @@+use photocraft_color::{Color, PixelFormat, SampleType};+use photocraft_doc::TextLayer;+use photocraft_doc::text::{+ CharStyle, FontFeature, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun,+ TextShape,+};+use photocraft_geom::Affine;++use crate::{TextEngine, fonts};++fn point(text: &str, size_pt: f32) -> TextLayer {+ TextLayer {+ text: text.into(),+ font_family: "Inter".into(),+ size_pt,+ ..Default::default()+ }+}++fn styled(text: &str, style: CharStyle) -> TextLayer {+ TextLayer {+ text: text.into(),+ runs: vec![TextRun {+ len: text.len(),+ style,+ }],+ ..Default::default()+ }+}++fn with_para(mut t: TextLayer, p: ParagraphStyle) -> TextLayer {+ t.paragraphs = vec![ParagraphRun {+ len: t.text.len(),+ style: p,+ }];+ t+}++fn width(l: &crate::TextLayout) -> f32 {+ l.lines.iter().map(|l| l.x1 - l.x0).fold(0.0, f32::max)+}++fn alpha_sum(s: &photocraft_raster::Surface, r: photocraft_geom::Rect) -> f64 {+ let n = s.channels();+ s.read_region(r)+ .chunks_exact(n)+ .map(|p| f64::from(p[n - 1]))+ .sum()+}++#[test]+fn bundled_fonts_cover_latin() {+ let mut e = TextEngine::new();+ let fams = e.fonts.families();+ assert!(fams.iter().any(|f| f == "Inter"), "{fams:?}");+ assert!(fams.iter().any(|f| f == "JetBrains Mono"), "{fams:?}");+ let l = e.layout(&point("Hello, Wörld! 0123", 12.0), 72.0);+ assert_eq!(l.glyphs.len(), "Hello, Wörld! 0123".chars().count());+ assert!(l.glyphs.iter().all(|g| g.id != 0), "no .notdef");+ assert_eq!(e.fonts.faces("Inter").len(), 3);+}++#[test]+fn metrics_are_stable_and_scale_with_dpi() {+ let mut e = TextEngine::new();+ let a = e.layout(&point("Hamburgefonstiv", 12.0), 72.0);+ let w = width(&a);+ // Inter 12 px: stable to a tenth of a pixel across runs.+ let again = width(&e.layout(&point("Hamburgefonstiv", 12.0), 72.0));+ assert_eq!(w, again);+ assert!((80.0..110.0).contains(&w), "{w}");+ let b = e.layout(&point("Hamburgefonstiv", 12.0), 144.0);+ assert!(+ (width(&b) - 2.0 * w).abs() < 0.05,+ "{} vs {}",+ width(&b),+ 2.0 * w+ );+ // Point text: first baseline at the anchor.+ assert_eq!(a.lines[0].baseline, 0.0);+ assert!(a.lines[0].ascent > 8.0 && a.lines[0].ascent < 13.0);+}++#[test]+fn auto_and_explicit_leading() {+ let mut e = TextEngine::new();+ let l = e.layout(&point("one\ntwo\rthree", 10.0), 72.0);+ assert_eq!(l.lines.len(), 3);+ assert!(+ (l.lines[1].baseline - 12.0).abs() < 1e-3,+ "auto leading = 1.2 × size"+ );+ assert!((l.lines[2].baseline - 24.0).abs() < 1e-3);+ assert_eq!(&"one\ntwo\rthree"[l.lines[2].range.clone()], "three");+ let t = styled(+ "a\nb",+ CharStyle {+ size_pt: 10.0,+ leading_pt: Some(30.0),+ ..Default::default()+ },+ );+ let l = e.layout(&t, 144.0);+ assert!(+ (l.lines[1].baseline - 60.0).abs() < 1e-3,+ "{}",+ l.lines[1].baseline+ );+ // Space before/after in points.+ let t = with_para(+ point("a\nb", 10.0),+ ParagraphStyle {+ space_after_pt: 5.0,+ ..Default::default()+ },+ );+ let l = e.layout(&t, 72.0);+ assert!(+ (l.lines[1].baseline - 17.0).abs() < 1e-3,+ "{}",+ l.lines[1].baseline+ );+}++#[test]+fn box_text_wraps_inside_width() {+ let mut e = TextEngine::new();+ let mut t = point(+ "The quick brown fox jumps over the lazy dog again and again",+ 12.0,+ );+ t.shape = TextShape::Box {+ x: 10.0,+ y: 20.0,+ width: 100.0,+ height: 1000.0,+ };+ let l = e.layout(&t, 72.0);+ assert!(l.lines.len() >= 3, "{}", l.lines.len());+ for line in &l.lines {+ assert!(+ line.x0 >= 10.0 - 1e-3 && line.x1 <= 110.0 + 1e-3,+ "{line:?}"+ );+ }+ // First baseline = top + ascender height ('d'), a bit less than the hhea ascent.+ let drop = l.lines[0].baseline - 20.0;+ assert!(drop > 0.65 * 12.0 && drop < l.lines[0].ascent, "{drop}");+ // Lines cover the text in order.+ assert_eq!(l.lines[0].range.start, 0);+ for w in l.lines.windows(2) {+ assert!(w[1].range.start >= w[0].range.end);+ }+ // Overflowing lines are hidden, like Photoshop.+ t.shape = TextShape::Box {+ x: 0.0,+ y: 0.0,+ width: 100.0,+ height: 30.0,+ };+ let l2 = e.layout(&t, 72.0);+ assert_eq!(l2.lines.len(), 2);+}++#[test]+fn alignment_point_and_box() {+ let mut e = TextEngine::new();+ let c = e.layout(+ &with_para(+ point("Centered", 20.0),+ ParagraphStyle {+ align: TextAlign::Center,+ ..Default::default()+ },+ ),+ 72.0,+ );+ let ln = &c.lines[0];+ assert!((ln.x0 + ln.x1).abs() < 0.01, "centered on anchor: {ln:?}");+ let r = e.layout(+ &with_para(+ point("Right", 20.0),+ ParagraphStyle {+ align: TextAlign::Right,+ ..Default::default()+ },+ ),+ 72.0,+ );+ assert!(r.lines[0].x1.abs() < 0.01 && r.lines[0].x0 < -10.0);++ let mut t = point("aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk", 12.0);+ t.shape = TextShape::Box {+ x: 0.0,+ y: 0.0,+ width: 120.0,+ height: 500.0,+ };+ let t = with_para(+ t,+ ParagraphStyle {+ align: TextAlign::JustifyLeft,+ ..Default::default()+ },+ );+ let l = e.layout(&t, 72.0);+ assert!(l.lines.len() > 1);+ let first = &l.lines[0];+ // Justified line: last glyph ends at the right edge (within a pixel).+ let last_glyph_x = l+ .glyphs+ .iter()+ .filter(|g| (g.y - first.baseline).abs() < 1e-3)+ .map(|g| g.x)+ .fold(f32::MIN, f32::max);+ assert!(last_glyph_x > 110.0, "{last_glyph_x}");+ let right = with_para(+ TextLayer {+ shape: TextShape::Box {+ x: 0.0,+ y: 0.0,+ width: 200.0,+ height: 100.0,+ },+ ..point("end", 12.0)+ },+ ParagraphStyle {+ align: TextAlign::Right,+ ..Default::default()+ },+ );+ let l = e.layout(&right, 72.0);+ assert!((l.lines[0].x1 - 200.0).abs() < 0.5, "{:?}", l.lines[0]);+}++#[test]+fn rtl_text_is_reordered() {+ let mut e = TextEngine::new();+ // Hebrew isn't in the bundled fonts, but bidi still resolves (glyphs may be .notdef).+ let text = "abc שלום def";+ let l = e.layout(&point(text, 12.0), 72.0);+ let heb: Vec<_> = l+ .clusters+ .iter()+ .filter(|c| {+ text[c.range.clone()]+ .chars()+ .all(|ch| ('\u{0590}'..='\u{05FF}').contains(&ch))+ })+ .collect();+ assert_eq!(heb.len(), 4);+ assert!(heb.iter().all(|c| c.rtl));+ // Visual order: the first logical Hebrew letter is rightmost among them.+ let first = heb.iter().min_by_key(|c| c.range.start).unwrap();+ assert!(heb.iter().all(|c| c.x <= first.x + 1e-3));+ // Forced RTL paragraph: the Latin run ends up to the right of the Hebrew.+ let t = with_para(+ point("שלום abc", 12.0),+ ParagraphStyle {+ direction: TextDirection::Rtl,+ ..Default::default()+ },+ );+ let l = e.layout(&t, 72.0);+ let a = l+ .clusters+ .iter()+ .find(|c| &"שלום abc"[c.range.clone()] == "a")+ .unwrap();+ let shin = l.clusters.iter().find(|c| c.range.start == 0).unwrap();+ assert!(a.x < shin.x, "abc left of the Hebrew in an RTL paragraph");+ assert!(l.clusters.iter().all(|c| c.range.end <= "שלום abc".len()));+}++/// Builds a TrueType collection from standalone fonts (table offsets rebased).+fn make_ttc(fonts: &[&[u8]]) -> Vec<u8> {+ let header_len = 12 + 4 * fonts.len();+ let mut out = Vec::new();+ out.extend_from_slice(b"ttcf");+ out.extend_from_slice(&0x0001_0000u32.to_be_bytes());+ out.extend_from_slice(&(fonts.len() as u32).to_be_bytes());+ let mut offsets = Vec::new();+ let mut body: Vec<u8> = Vec::new();+ for f in fonts {+ while !(header_len + body.len()).is_multiple_of(4) {+ body.push(0);+ }+ let base = (header_len + body.len()) as u32;+ offsets.push(base);+ let mut copy = f.to_vec();+ let n = u16::from_be_bytes([copy[4], copy[5]]) as usize;+ for i in 0..n {+ let at = 12 + i * 16 + 8;+ let off = u32::from_be_bytes(copy[at..at + 4].try_into().unwrap());+ copy[at..at + 4].copy_from_slice(&(off + base).to_be_bytes());+ }+ body.extend(copy);+ }+ for o in offsets {+ out.extend_from_slice(&o.to_be_bytes());+ }+ out.extend(body);+ out+}++#[test]+fn truetype_collections_load() {+ let ttc = make_ttc(&[fonts::BUNDLED[0].1, fonts::BUNDLED[3].1]);+ assert_eq!(fonts::face_count(&ttc), 2);+ let mut db = fonts::FontDb::new();+ // A fresh DB without the bundled mono font would miss it; register the collection anyway+ // and check both faces are indexed (families already present gain faces).+ let before = db.faces("JetBrains Mono").len();+ let names = db.register_font_data(ttc);+ assert!(+ names.iter().any(|n| n == "Inter") && names.iter().any(|n| n == "JetBrains Mono"),+ "{names:?}"+ );+ assert_eq!(db.faces("JetBrains Mono").len(), before + 1);+ // Layout with the TTC-backed face works.+ let mut e = TextEngine {+ fonts: db,+ layouter: crate::layout::Layouter::new(),+ };+ let t = styled(+ "mono",+ CharStyle {+ font_family: "JetBrains Mono".into(),+ ..Default::default()+ },+ );+ let l = e.layout(&t, 72.0);+ assert!(l.glyphs.iter().all(|g| g.id != 0));+}++#[test]+fn opentype_features_and_tracking() {+ let mut e = TextEngine::new();+ let ids = |e: &mut TextEngine, feats: Vec<FontFeature>, lig: bool| {+ let t = styled(+ "a0",+ CharStyle {+ features: feats,+ ligatures: lig,+ ..Default::default()+ },+ );+ e.layout(&t, 72.0)+ .glyphs+ .iter()+ .map(|g| g.id)+ .collect::<Vec<_>>()+ };+ let plain = ids(&mut e, vec![], true);+ let alt = ids(+ &mut e,+ vec![FontFeature {+ tag: "zero".into(),+ value: 1,+ }],+ true,+ );+ assert_ne!(+ plain, alt,+ "Inter's `zero` feature selects the slashed zero"+ );+ let a = width(&e.layout(&styled("tracking", CharStyle::default()), 72.0));+ let b = width(&e.layout(+ &styled(+ "tracking",+ CharStyle {+ tracking: 100.0,+ ..Default::default()+ },+ ),+ 72.0,+ ));+ // 100/1000 em at 12 px per letter (8 letters; trailing spacing counts too).+ assert!((b - a - 8.0 * 1.2).abs() < 1.3, "{a} → {b}");+}++#[test]+fn raster_coverage_scales_and_depths_agree() {+ let mut e = TextEngine::new();+ let t = |size: f32| TextLayer {+ transform: Affine::translate(10.0, 50.0),+ ..point("Ink", size)+ };+ let (_, r12) = e.render(&t(12.0), 72.0, PixelFormat::RGBA8);+ let (_, r24) = e.render(&t(24.0), 72.0, PixelFormat::RGBA8);+ let s12 = alpha_sum(&r12.surface, r12.rect);+ let s24 = alpha_sum(&r24.surface, r24.rect);+ assert!(s12 > 20.0, "{s12}");+ let ratio = s24 / s12;+ assert!((3.6..4.4).contains(&ratio), "ink ∝ size²: {ratio}");+ // Placement: anchored at (10, 50) baseline.+ assert!(+ r12.rect.x0 >= 8 && r12.rect.x0 <= 11 && r12.rect.y1 <= 53 && r12.rect.y1 >= 50,+ "{:?}",+ r12.rect+ );+ for fmt in [+ PixelFormat::RGBA16,+ PixelFormat::RGBA32F,+ PixelFormat::GRAYA8,+ PixelFormat::CMYKA8,+ ] {+ let (_, r) = e.render(&t(12.0), 72.0, fmt);+ assert_eq!(r.rect, r12.rect);+ let s = alpha_sum(&r.surface, r.rect);+ assert!((s - s12).abs() / s12 < 0.01, "{fmt:?}: {s} vs {s12}");+ }+ // Deterministic.+ let (_, again) = e.render(&t(12.0), 72.0, PixelFormat::RGBA8);+ assert_eq!(again.surface, r12.surface);+ // Golden-ish total ink for "Ink" in Inter 12 px (±3%).+ assert!(+ (s12 - GOLDEN_INK_12).abs() / GOLDEN_INK_12 < 0.03,+ "ink sum {s12}"+ );+}++/// Sum of alpha for "Ink", Inter Regular 12 px (measured once; guards rasterizer regressions).+const GOLDEN_INK_12: f64 = 44.4;++#[test]+fn styles_change_pixels() {+ let mut e = TextEngine::new();+ let base = CharStyle {+ size_pt: 30.0,+ ..Default::default()+ };+ let ink = |e: &mut TextEngine, s: CharStyle| {+ let (_, r) = e.render(+ &TextLayer {+ transform: Affine::translate(5.0, 40.0),+ ..styled("Hi", s)+ },+ 72.0,+ PixelFormat::RGBA8,+ );+ (alpha_sum(&r.surface, r.rect), r.rect)+ };+ let (plain, prect) = ink(&mut e, base.clone());+ let (bold, _) = ink(+ &mut e,+ CharStyle {+ faux_bold: true,+ ..base.clone()+ },+ );+ assert!(bold > plain * 1.1, "{plain} → {bold}");+ let (under, urect) = ink(+ &mut e,+ CharStyle {+ underline: true,+ ..base.clone()+ },+ );+ assert!(under > plain && urect.y1 > prect.y1);+ let (_, irect) = ink(+ &mut e,+ CharStyle {+ faux_italic: true,+ ..base.clone()+ },+ );+ assert!(irect.x1 > prect.x1, "slanted top extends right");+ let (_, srect) = ink(+ &mut e,+ CharStyle {+ baseline_shift_pt: 10.0,+ ..base.clone()+ },+ );+ assert_eq!(srect.y0, prect.y0 - 10);+ let (_, hrect) = ink(+ &mut e,+ CharStyle {+ horizontal_scale: 2.0,+ ..base.clone()+ },+ );+ assert!(hrect.width() as f32 > prect.width() as f32 * 1.7);+}++#[test]+fn multicolor_runs() {+ let mut e = TextEngine::new();+ let red = CharStyle {+ size_pt: 40.0,+ color: Color::rgb(1.0, 0.0, 0.0),+ ..Default::default()+ };+ let blue = CharStyle {+ color: Color::rgb(0.0, 0.0, 1.0),+ ..red.clone()+ };+ let t = TextLayer {+ text: "HH".into(),+ runs: vec![+ TextRun { len: 1, style: red },+ TextRun {+ len: 1,+ style: blue,+ },+ ],+ transform: Affine::translate(0.0, 40.0),+ ..Default::default()+ };+ let (l, r) = e.render(&t, 72.0, PixelFormat::RGBA8);+ assert_eq!(l.glyphs.len(), 2);+ let px = r.surface.read_region(r.rect);+ let opaque: Vec<&[f32]> = px.chunks_exact(4).filter(|p| p[3] > 0.99).collect();+ assert!(opaque.iter().any(|p| p[0] > 0.99 && p[2] < 0.01));+ assert!(opaque.iter().any(|p| p[2] > 0.99 && p[0] < 0.01));+ // CMYK target keeps colour in the document model.+ let (_, rc) = e.render(&t, 72.0, PixelFormat::CMYKA8);+ assert!(+ rc.surface+ .read_region(rc.rect)+ .chunks_exact(5)+ .any(|p| p[4] > 0.99 && p[1] > 0.9 && p[2] > 0.9)+ );+}++#[test]+fn hit_test_and_caret() {+ let mut e = TextEngine::new();+ let l = e.layout(&point("abc\ndef", 20.0), 72.0);+ assert_eq!(l.hit_test(-5.0, -5.0), 0);+ assert_eq!(l.hit_test(1000.0, -5.0), 3);+ assert_eq!(l.hit_test(-5.0, 24.0), 4);+ let (x, top, bottom) = l.caret(1);+ assert!(x > 0.0 && top < 0.0 && bottom > 0.0);+ let (x2, ..) = l.caret(2);+ assert!(x2 > x);+ assert_eq!(l.caret(3).0, l.lines[0].x1);+}++#[test]+fn empty_text_and_empty_lines() {+ let mut e = TextEngine::new();+ let l = e.layout(&point("", 12.0), 72.0);+ assert_eq!(l.lines.len(), 1);+ assert!(l.glyphs.is_empty());+ let l = e.layout(&point("a\n\nb", 12.0), 72.0);+ assert_eq!(l.lines.len(), 3);+ assert!((l.lines[2].baseline - 2.0 * 14.4).abs() < 1e-3);+ let (_, r) = e.render(&point("", 12.0), 72.0, PixelFormat::RGBA8);+ assert_eq!(r.rect.width(), 0);+}++#[test]+fn postscript_names() {+ let g = fonts::guess_from_postscript("MyriadPro-BoldIt");+ assert_eq!(+ (g.family.as_str(), g.weight, g.italic),+ ("Myriad Pro", 700, true)+ );+ let g = fonts::guess_from_postscript("TimesNewRomanPSMT");+ assert_eq!(+ (g.family.as_str(), g.weight, g.italic),+ ("Times New Roman", 400, false)+ );+ let g = fonts::guess_from_postscript("Arial-BoldMT");+ assert_eq!((g.family.as_str(), g.weight), ("Arial", 700));+ let mut db = fonts::FontDb::new();+ let r = db.resolve_postscript("Inter-SemiBold");+ assert_eq!((r.family.as_str(), r.weight, r.exact), ("Inter", 600, true));+ // Unknown fonts fall back gracefully in layout.+ let mut e = TextEngine::new();+ let t = styled(+ "x",+ CharStyle {+ font_family: "Nonexistent Sans".into(),+ postscript_name: Some("Nope-Bold".into()),+ ..Default::default()+ },+ );+ assert!(e.layout(&t, 72.0).glyphs[0].id != 0);+}++#[test]+fn depth_is_respected() {+ let mut e = TextEngine::new();+ let (_, r) = e.render(+ &TextLayer {+ transform: Affine::translate(2.0, 20.0),+ ..point("a", 20.0)+ },+ 72.0,+ PixelFormat::RGBA16,+ );+ assert_eq!(r.surface.format().sample, SampleType::U16);+ assert!(r.surface.format().alpha);+}++/// Visual check: `PHOTOCRAFT_TEXT_DUMP=/tmp/t.ppm cargo test -p photocraft-text dump -- --ignored`.+#[test]+#[ignore]+fn dump_sample() {+ use photocraft_doc::text::{Caps, TextAlign};+ let Some(path) = std::env::var_os("PHOTOCRAFT_TEXT_DUMP") else {+ return;+ };+ let mut e = if std::env::var_os("PHOTOCRAFT_TEXT_SYSTEM").is_some() {+ TextEngine::with_system_fonts()+ } else {+ TextEngine::new()+ };+ let s = CharStyle {+ size_pt: 28.0,+ ..Default::default()+ };+ let text = "Photocraft Type\nBold faux, italic faux, underline\nשלום عربي mixed ✓\nJustified paragraph text wraps inside the box nicely and evenly across lines.";+ let runs = vec![+ TextRun {+ len: 16,+ style: CharStyle {+ size_pt: 40.0,+ color: Color::rgb(0.1, 0.3, 0.9),+ caps: Caps::Normal,+ ..s.clone()+ },+ },+ TextRun {+ len: 5,+ style: CharStyle {+ faux_bold: true,+ ..s.clone()+ },+ },+ TextRun {+ len: 13,+ style: CharStyle {+ faux_italic: true,+ color: Color::rgb(0.8, 0.1, 0.1),+ ..s.clone()+ },+ },+ TextRun {+ len: 11,+ style: CharStyle {+ underline: true,+ strikethrough: false,+ ..s.clone()+ },+ },+ TextRun {+ len: 1000,+ style: CharStyle {+ size_pt: 20.0,+ tracking: 20.0,+ ..s.clone()+ },+ },+ ];+ let t = TextLayer {+ text: text.into(),+ runs,+ paragraphs: vec![+ ParagraphRun {+ len: 45,+ style: ParagraphStyle {+ align: TextAlign::Left,+ ..Default::default()+ },+ },+ ParagraphRun {+ len: 1000,+ style: ParagraphStyle {+ align: TextAlign::JustifyLeft,+ space_before_pt: 6.0,+ ..Default::default()+ },+ },+ ],+ shape: TextShape::Box {+ x: 0.0,+ y: 0.0,+ width: 560.0,+ height: 400.0,+ },+ transform: Affine::translate(20.0, 20.0),+ ..Default::default()+ };+ let (_, r) = e.render(&t, 72.0, PixelFormat::RGBA8);+ let (w, h) = (600u32, 360u32);+ let mut out = format!("P6 {w} {h} 255\n").into_bytes();+ for y in 0..h as i32 {+ for x in 0..w as i32 {+ let p = r.surface.pixel(x, y);+ let a = p[3];+ for c in &p[..3] {+ out.push(((c * a + (1.0 - a)) * 255.0).round() as u8);+ }+ }+ }+ std::fs::write(path, out).unwrap();+}++/// Variable-font axes reach the outlines (uses a system variable font when one is present).+#[test]+fn variable_font_axes() {+ let candidates = [+ "/System/Library/Fonts/SFNS.ttf",+ "/usr/share/fonts/truetype/noto/NotoSans-VariableFont_wdth,wght.ttf",+ "C:\\Windows\\Fonts\\bahnschrift.ttf",+ ];+ let Some(bytes) = candidates.iter().find_map(|p| std::fs::read(p).ok()) else {+ return;+ };+ let mut e = TextEngine::new();+ let fams = e.fonts.register_font_data(bytes);+ let Some(fam) = fams.first().cloned() else {+ return;+ };+ if !e+ .fonts+ .faces(&fam)+ .iter()+ .any(|f| f.axes.iter().any(|a| a.0 == "wght"))+ {+ return;+ }+ let ink = |e: &mut TextEngine, w: f32| {+ let s = CharStyle {+ font_family: fam.clone(),+ size_pt: 40.0,+ variations: vec![photocraft_doc::text::FontVariation {+ axis: "wght".into(),+ value: w,+ }],+ ..Default::default()+ };+ let (_, r) = e.render(+ &TextLayer {+ transform: Affine::translate(0.0, 50.0),+ ..styled("Weight", s)+ },+ 72.0,+ PixelFormat::RGBA8,+ );+ alpha_sum(&r.surface, r.rect)+ };+ let light = ink(&mut e, 200.0);+ let heavy = ink(&mut e, 800.0);+ assert!(heavy > light * 1.5, "{light} → {heavy}");+}diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.tomlindex 69e42631e..f0e1ab251 100644--- a/crates/ui-egui/Cargo.toml+++ b/crates/ui-egui/Cargo.toml@@ -13,7 +13,10 @@ photocraft-color = { workspace = true }photocraft-raster = { workspace = true }photocraft-doc = { workspace = true }photocraft-compose = { workspace = true }+photocraft-gpu = { workspace = true }photocraft-engine = { workspace = true }+photocraft-algo = { workspace = true }+photocraft-text = { workspace = true }egui = { workspace = true }egui_extras = { version = "0.36", default-features = false, features = ["svg"] }eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }@@ -21,5 +24,10 @@ serde = { workspace = true }serde_json = { workspace = true }log = { workspace = true }+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+rayon = { workspace = true }+[dev-dependencies]egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] }+# Only for examples/snapshot.rs (offscreen UI renders of real files).+photocraft-io = { workspace = true }diff --git a/crates/ui-egui/examples/snapshot.rs b/crates/ui-egui/examples/snapshot.rsnew file mode 100644index 000000000..193d6f3cd--- /dev/null+++ b/crates/ui-egui/examples/snapshot.rs@@ -0,0 +1,90 @@+//! Render the full Photocraft UI offscreen (no window, no focus stealing) and save a PNG.+//!+//! ```sh+//! cargo run --release -p photocraft-ui-egui --example snapshot -- \+//! --out ui.png --size 1440x900 --scale 2 --open photo.jpg \+//! --script '[["ui.set", {"tool": "type"}], ["ui.menu.invoke", {"id": "image.imageSize"}]]'+//! ```+//!+//! `--script` is a JSON array of `[method, params]` control-protocol calls (see+//! docs/control-protocol.md), applied in order with a few frames between them.++use photocraft_ui_egui::control::{ControlRequest, Outcome, handle};+use photocraft_ui_egui::{PhotocraftApp, Services};+use serde_json::Value;++fn arg(args: &[String], name: &str) -> Option<String> {+ args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())+}++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let out = arg(&args, "--out").unwrap_or_else(|| "snapshot.png".into());+ let (w, h) = arg(&args, "--size")+ .and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.parse::<f32>().ok()?, b.parse::<f32>().ok()?))))+ .unwrap_or((1440.0, 900.0));+ let scale: f32 = arg(&args, "--scale").and_then(|s| s.parse().ok()).unwrap_or(2.0);+ let script: Vec<(String, Value)> = arg(&args, "--script")+ .map(|s| serde_json::from_str::<Vec<(String, Value)>>(&s).expect("--script must be [[method, params], …]"))+ .unwrap_or_default();++ let services = Services {+ import: Some(Box::new(|name: &str, bytes: &[u8]| photocraft_io::import(name, bytes).map(|r| r.document).map_err(|e| e.to_string()))),+ export: Some(Box::new(|doc: &photocraft_doc::Document, path: &str, settings: &photocraft_ui_egui::ExportSettings| {+ let mut opts = photocraft_io::ExportOptions::default();+ if let Some(q) = settings.jpeg_quality {+ opts.encode.jpeg_quality = q;+ }+ photocraft_io::export(doc, path, &opts).map(|r| r.bytes).map_err(|e| e.to_string())+ })),+ ..Default::default()+ };+ let open = arg(&args, "--open");+ let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(w, h)).with_pixels_per_point(scale).with_max_steps(64).wgpu().build_eframe(move |cc| {+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);+ if let Some(rs) = cc.wgpu_render_state.as_ref() {+ app.set_wgpu(rs.clone());+ }+ if let Some(path) = &open {+ let bytes = std::fs::read(path).expect("read --open file");+ let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();+ app.open_bytes(&name, &bytes).expect("open file");+ }+ app+ });+ harness.run_steps(4);+ let ctx = harness.ctx.clone();+ for (method, params) in script {+ let (req, _rx) = ControlRequest::new(&method, params);+ let outcome = handle(harness.state_mut(), &ctx, &req);+ if let Outcome::Done(v) = &outcome+ && v.get("ok") == Some(&Value::Bool(false))+ {+ eprintln!("{method}: {v}");+ }+ // The harness doesn't call raw_input_hook: feed queued synthetic input step by step.+ loop {+ let step = harness.state_mut().take_synthetic_step();+ if step.is_empty() {+ break;+ }+ for e in step {+ harness.event(e);+ }+ harness.step();+ }+ harness.run_steps(4);+ }+ // Let fade animations settle.+ for _ in 0..12 {+ harness.step();+ }+ let (req, _rx) = ControlRequest::new("ui.inspect", Value::Null);+ if let Outcome::Done(v) = handle(harness.state_mut(), &ctx, &req) {+ println!("perf: {}", v["result"]["perf"]["timings"]);+ }+ let img = harness.render().expect("render");+ img.save(&out).expect("save png");+ println!("wrote {out} ({}×{})", img.width(), img.height());+}diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rsnew file mode 100644index 000000000..99aac0396--- /dev/null+++ b/crates/ui-egui/src/actions.rs@@ -0,0 +1,181 @@+//! Actions panel: record and replay command sequences.+//!+//! Every edit is an engine command appended to `Session::journal`, so recording is just remembering+//! where the journal was when ● was pressed, and ▶ replays those exact commands (strokes, transforms,+//! type edits included) on whatever document is active.++use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};+use serde::{Deserialize, Serialize};+use serde_json::Value;++use crate::PhotocraftApp;+use crate::theme::Tokens;++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Action {+ pub name: String,+ pub steps: Vec<(String, Value)>,+ #[serde(default)]+ pub expanded: bool,+}++/// Actions and recording state (persisted with the UI state).+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Actions {+ pub list: Vec<Action>,+ pub selected: Option<usize>,+ /// Journal length when recording started, and the action being recorded into.+ pub recording: Option<(usize, usize)>,+}++/// Commands that are queries or UI plumbing, not worth replaying.+fn replayable(id: &str) -> bool {+ !matches!(id, "document.pixel" | "document.inspect" | "session.inspect" | "command.list" | "type.info" | "type.fonts" | "edit.undo" | "edit.redo")+}++pub fn start_recording(app: &mut PhotocraftApp) {+ let n = app.ui.actions.list.len();+ app.ui.actions.list.push(Action { name: format!("Action {}", n + 1), steps: Vec::new(), expanded: true });+ app.ui.actions.selected = Some(n);+ app.ui.actions.recording = Some((app.session.journal.len(), n));+}++/// Stop recording: move the new journal entries into the action.+pub fn stop_recording(app: &mut PhotocraftApp) {+ let Some((from, idx)) = app.ui.actions.recording.take() else { return };+ let steps: Vec<(String, Value)> = app.session.journal.iter().skip(from).filter(|(id, _)| replayable(id)).cloned().collect();+ if let Some(a) = app.ui.actions.list.get_mut(idx) {+ a.steps.extend(steps);+ }+}++/// Replay an action; stops at the first failing step and reports it.+pub fn play(app: &mut PhotocraftApp, idx: usize) -> Result<usize, String> {+ let steps = app.ui.actions.list.get(idx).map(|a| a.steps.clone()).ok_or("no such action")?;+ for (i, (id, p)) in steps.iter().enumerate() {+ app.run(id, p.clone()).map_err(|e| format!("Step {} ({id}) failed: {e}", i + 1))?;+ }+ Ok(steps.len())+}++fn label_of(id: &str) -> String {+ photocraft_engine::commands::find(id).map(|c| c.label.trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string())+}++pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ let live = app.ui.actions.recording.map(|(from, _)| app.session.journal.len().saturating_sub(from)).unwrap_or(0);+ let max_h = (ui.available_height() - 70.0).clamp(80.0, 320.0);+ let mut play_idx = None;+ egui::ScrollArea::vertical().id_salt("actions-rows").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| {+ if app.ui.actions.list.is_empty() {+ ui.label(egui::RichText::new("Record ● a sequence of edits, then play ▶ it on any document.").color(t.text_faint).size(11.5));+ }+ let n = app.ui.actions.list.len();+ for i in 0..n {+ let a = app.ui.actions.list[i].clone();+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click());+ let sel = app.ui.actions.selected == Some(i);+ if sel {+ ui.painter().rect_filled(rect, 0.0, t.row_selected);+ } else if resp.hovered() {+ ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5));+ }+ // Expander triangle.+ let tri = Rect::from_center_size(pos2(rect.left() + 12.0, rect.center().y), vec2(8.0, 8.0));+ let pts = if a.expanded { vec![tri.left_top(), tri.right_top(), tri.center_bottom()] } else { vec![tri.left_top(), tri.right_center(), tri.left_bottom()] };+ ui.painter().add(egui::Shape::convex_polygon(pts, t.text_dim, Stroke::NONE));+ crate::icons::paint(ui, Rect::from_center_size(pos2(rect.left() + 30.0, rect.center().y), vec2(16.0, 16.0)), "play", 11.0, t.icon);+ let recording_this = app.ui.actions.recording.is_some_and(|(_, r)| r == i);+ let steps = a.steps.len() + if recording_this { live } else { 0 };+ ui.painter().text(pos2(rect.left() + 44.0, rect.center().y), Align2::LEFT_CENTER, &a.name, egui::FontId::proportional(12.0), t.text);+ ui.painter().text(pos2(rect.right() - 8.0, rect.center().y), Align2::RIGHT_CENTER, format!("{steps} steps"), egui::FontId::proportional(11.0), t.text_faint);+ if recording_this {+ ui.painter().circle_filled(pos2(rect.right() - 64.0, rect.center().y), 4.0, Color32::from_rgb(230, 60, 60));+ }+ if resp.clicked() {+ app.ui.actions.selected = Some(i);+ if resp.interact_pointer_pos().is_some_and(|p| p.x < rect.left() + 20.0) {+ app.ui.actions.list[i].expanded = !a.expanded;+ }+ }+ if resp.double_clicked() {+ play_idx = Some(i);+ }+ if a.expanded {+ for (id, _) in &a.steps {+ let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::hover());+ ui.painter().text(pos2(r.left() + 44.0, r.center().y), Align2::LEFT_CENTER, label_of(id), egui::FontId::proportional(11.5), t.text_dim);+ }+ }+ }+ });+ // Footer: stop, record, play, new, delete (Photoshop's order).+ ui.add_space(4.0);+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 2.0;+ let recording = app.ui.actions.recording.is_some();+ if crate::icons::button(ui, "square", 24.0, false, "Stop playing/recording").clicked() {+ stop_recording(app);+ }+ let (r, rec) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click());+ if rec.hovered() {+ ui.painter().rect_filled(r, 3.0, t.hover);+ }+ ui.painter().circle_filled(r.center(), 5.5, if recording { Color32::from_rgb(230, 60, 60) } else { t.icon });+ if rec.on_hover_text("Begin recording").clicked() && !recording {+ start_recording(app);+ }+ if crate::icons::button(ui, "play", 24.0, false, "Play selection").clicked() {+ play_idx = app.ui.actions.selected;+ }+ if crate::icons::button(ui, "plus", 24.0, false, "Create new action").clicked() && !recording {+ start_recording(app);+ }+ if crate::icons::button(ui, "trash", 24.0, false, "Delete").clicked()+ && !recording+ && let Some(i) = app.ui.actions.selected.take()+ && i < app.ui.actions.list.len()+ {+ app.ui.actions.list.remove(i);+ }+ });+ if let Some(i) = play_idx {+ match play(app, i) {+ Ok(n) => app.ui.status = format!("Played {n} steps"),+ Err(e) => {+ app.ui.status = e;+ app.ui.status_error = true;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn record_and_replay_on_another_document() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 40, "height": 40})).unwrap();+ app.sync_views();+ start_recording(&mut app);+ app.run("layer.new.layer", json!({})).unwrap();+ app.run("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();+ let _ = app.run("document.pixel", json!({"x": 1, "y": 1}));+ stop_recording(&mut app);+ let a = &app.ui.actions.list[0];+ assert_eq!(a.steps.iter().map(|s| s.0.as_str()).collect::<Vec<_>>(), ["layer.new.layer", "select.rect", "edit.fill"]);+ // Replay on a second document.+ app.run("file.new", json!({"width": 40, "height": 40})).unwrap();+ app.sync_views();+ assert_eq!(play(&mut app, 0).unwrap(), 3);+ let d = &app.session.active().unwrap().doc;+ assert_eq!(d.layers.len(), 2);+ assert_eq!(d.layers[1].surface().unwrap().pixel(5, 5), vec![1.0, 0.0, 0.0, 1.0]);+ }+}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 945e3c69d..f4130c60b 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -132,6 +132,12 @@ fn downsample(buf: &photocraft_compose::Buffer, factor: u32) -> photocraft_compo/// The document to render: the committed one, or a clone with the live adjustment preview applied.fn display_doc(app: &PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>, u64) {let st = &app.session.documents()[idx];+ if let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview)+ && app.session.active_index() == Some(idx)+ && st.doc.layer(photocraft_doc::LayerId(t.layer)).is_some()+ {+ return (pv.doc.clone(), (1 << 40) + pv.session);+ }if let Some((layer, params)) = &app.live_adjust&& let Some(l) = st.doc.layer(*layer)&& let LayerContent::Adjustment(a) = &l.content@@ -204,7 +210,24 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize) -> bool {let t0 = crate::gpu_canvas::now_ms();let partial = present && cache.preview_key == preview_key && cache.revision + 1 == revision && last_damage.is_some();let mut done = false;- if partial {+ // Preferred: the wgpu compositor renders straight into the display texture (damage rect for+ // strokes, everything otherwise). Falls back to the CPU compositor below when unsupported.+ let region = if partial { last_damage.unwrap_or(doc.bounds()).intersect(&doc.bounds()) } else { doc.bounds() };+ match gpu.composite(&doc, region) {+ Ok(stats) => {+ done = true;+ let kind = if partial { "gpu-rect" } else { "gpu-full" };+ app.perf.record(kind, region.width() as u64 * region.height() as u64, crate::gpu_canvas::now_ms() - t0, 0.0);+ app.perf.gpu_uploads = stats.tiles_uploaded as u64;+ }+ Err(e) => {+ if app.perf.gpu_fallback.as_deref() != Some(e.0.as_str()) {+ log::info!("{e}; using the CPU compositor");+ }+ app.perf.gpu_fallback = Some(e.0);+ }+ }+ if partial && !done {let r = last_damage.unwrap().intersect(&doc.bounds());if r.is_empty() {done = true;@@ -216,8 +239,8 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize) -> bool {}}if !done {- // TODO(M5): render only the visible region at display resolution when zoomed out; the- // wgpu compositor will make this CPU flatten go away entirely.+ // CPU fallback (documents the GPU compositor doesn't cover yet, e.g. layer effects).+ // TODO: render only the visible region at display resolution when zoomed out.let full = photocraft_compose::flatten(&doc);let t1 = crate::gpu_canvas::now_ms();gpu.upload_buffer_full(id.0, &full);@@ -231,6 +254,36 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize) -> bool {true}+/// Live preview for an open filter dialog: run the filter on the proxy and upload it.+fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u64)> {+ let d = app.ui.dialogs.iter().find(|d| d.fields.contains_key("__filter"))?;+ if d.fields.get("__preview").and_then(serde_json::Value::as_bool) != Some(true) {+ return None;+ }+ let cmd = d.fields.get("__command")?.as_str()?.to_string();+ let params = crate::filter_dialog::params_of(&d.fields);+ let (doc_id, revision, doc, active) = {+ let st = app.session.documents().get(idx)?;+ (st.doc.id, st.revision, st.doc.clone(), st.active_layer)+ };+ let k = crate::proxy::factor(&doc);+ let hash = format!("{cmd}{params}").bytes().fold(k as u64 ^ revision.wrapping_mul(0x9e37), |h, b| h.wrapping_mul(31).wrapping_add(b as u64));+ let key = doc_id.0 ^ (1u64 << 61);+ let fresh = matches!(&app.filter_preview, Some(p) if p.doc == doc_id && p.hash == hash);+ if !fresh {+ let t0 = crate::gpu_canvas::now_ms();+ let result = crate::filter_dialog::preview_document(&doc, active, &cmd, ¶ms, k).map(std::sync::Arc::new);+ if let Some(r) = &result {+ let buf = photocraft_compose::flatten(r);+ let t1 = crate::gpu_canvas::now_ms();+ app.gpu.as_ref()?.upload_buffer_full(key, &buf);+ app.perf.record("filter-preview", r.size.area(), t1 - t0, crate::gpu_canvas::now_ms() - t1);+ }+ app.filter_preview = Some(crate::filter_dialog::FilterPreview { doc: doc_id, revision, hash, k, result });+ }+ app.filter_preview.as_ref().filter(|p| p.result.is_some()).map(|p| (p.k, key))+}+/// If a live adjustment preview is active on a large document, composite it on the proxy and upload/// it under its own GPU key. Returns (factor, gpu key) when the proxy should be drawn.fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u64)> {@@ -275,7 +328,9 @@ fn buf_image(buf: &photocraft_compose::Buffer) -> egui::ColorImage {/// Tabs + canvas for the active document, or the start screen.pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {if let Some(gpu) = &app.gpu {- let live: Vec<u64> = app.session.documents().iter().map(|st| st.doc.id.0).collect();+ // Keep each document's texture plus its preview textures (filter preview, adjustment proxy);+ // retaining only document ids freed the previews every frame (blank canvas while previewing).+ let live: Vec<u64> = app.session.documents().iter().flat_map(|st| [st.doc.id.0, st.doc.id.0 ^ (1u64 << 61), st.doc.id.0 ^ (1u64 << 62)]).collect();gpu.retain(&live);}if app.session.documents().is_empty() {@@ -351,7 +406,14 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let mut x = strip.left();for (i, st) in app.session.documents().iter().enumerate() {let zoom = app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0);- let title = format!("{} @ {}% ({}/{}){}", st.doc.name, fmt_zoom(zoom), mode_label(&st.doc), st.doc.depth.bits(), if st.is_dirty() { "*" } else { "" });+ // Photoshop: "name @ 50% (Layer 1, RGB/8)", "(Layer 1, Layer Mask/8)" when the mask is targeted;+ // the Background layer's name is omitted.+ let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !(l.name == "Background" && l.locks.transparency));+ let is_active_doc = app.session.active_index() == Some(i);+ let mask = is_active_doc && app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some());+ let model = if mask { "Layer Mask".to_string() } else { mode_label(&st.doc).to_string() };+ let layer = active_layer.map(|l| format!("{}, ", l.name)).unwrap_or_default();+ let title = format!("{} @ {}% ({layer}{model}/{}){}", st.doc.name, fmt_zoom(zoom), st.doc.depth.bits(), if st.is_dirty() { "*" } else { "" });let g = ui.painter().layout_no_wrap(title, egui::FontId::proportional(11.5), t.text);let r = Rect::from_min_size(egui::pos2(x, strip.top()), egui::vec2(g.size().x + 42.0, strip.height()));let resp = ui.interact(r, ui.id().with(("ptab", i)), Sense::click());@@ -475,7 +537,17 @@ fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) {/// Draw one canvas view and handle its input. `primary` = main window (tools active).pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: Rect, mut view: View, primary: bool) -> View {let ctx = ui.ctx().clone();+ let full = rect;+ let rect = if primary { crate::rulers::content_rect(app, rect) } else { rect };let doc = app.session.documents()[idx].doc.clone();+ let size = [doc.size.width, doc.size.height];+ if view.doc_size != size {+ // Like Photoshop: keep the zoom level, re-centre the resized document.+ if view.doc_size != [0, 0] {+ view.center = [size[0] as f32 / 2.0, size[1] as f32 / 2.0];+ }+ view.doc_size = size;+ }if view.fit_pending && rect.width() > 50.0 {fit_view(&mut view, &doc, rect.size());}@@ -489,7 +561,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:// Live adjustment previews on big documents use a downsampled proxy (see proxy.rs).let mut on_gpu = false;if app.gpu.is_some()- && let Some((k, key)) = ensure_proxy_preview(app, idx)+ && let Some((k, key)) = ensure_filter_preview(app, idx).or_else(|| ensure_proxy_preview(app, idx)){on_gpu = true;let params = crate::gpu_canvas::ViewParams {@@ -546,17 +618,26 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:// Selection outline: true boundary, animated marching ants (cached per revision).if let Some(sel) = &doc.selection {- let rev = app.session.documents()[idx].revision;- let fresh = matches!(&app.outline_cache, Some((d, r, _)) if *d == doc.id && *r == rev);+ // Trace at display resolution over the visible part only; key by the mask's tile identity+ // (not the document revision) so unrelated edits don't re-trace it.+ let step = (1.0 / view.zoom.max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32;+ let tl = xf.to_doc(rect.min);+ let br = xf.to_doc(rect.max);+ let q = 256 * step as i32; // quantise the region so small pans reuse the cache+ let vis = photocraft_geom::Rect::new(+ (tl[0].floor() as i32).div_euclid(q) * q - q,+ (tl[1].floor() as i32).div_euclid(q) * q - q,+ ((br[0].ceil() as i32).div_euclid(q) + 2) * q,+ ((br[1].ceil() as i32).div_euclid(q) + 2) * q,+ );+ let key = crate::surface_fingerprint(sel) ^ (step as u64) << 56 ^ doc.id.0.rotate_left(17) ^ (vis.x0 as u64) << 8 ^ (vis.y0 as u64) << 24 ^ (vis.x1 as u64) << 36 ^ (vis.y1 as u64) << 48;+ let fresh = matches!(&app.outline_cache, Some((d, k, _)) if *d == doc.id && *k == key);if !fresh {- let b = app.cached_bounds(u64::MAX - doc.id.0, sel);- // Very large selections: fall back to the bounding box until the GPU path lands.- let segs = if b.width() as u64 * b.height() as u64 > 40_000_000 {- vec![([b.x0, b.y0], [b.x1, b.y0]), ([b.x1, b.y0], [b.x1, b.y1]), ([b.x1, b.y1], [b.x0, b.y1]), ([b.x0, b.y1], [b.x0, b.y0])]- } else {- crate::outline::outline(sel, b)- };- app.outline_cache = Some((doc.id, rev, std::sync::Arc::new(segs)));+ let t0 = crate::gpu_canvas::now_ms();+ let b = app.cached_bounds(u64::MAX - doc.id.0, sel).intersect(&vis);+ let segs = crate::outline::outline_scaled(sel, b, step);+ app.perf.span("outline", crate::gpu_canvas::now_ms() - t0);+ app.outline_cache = Some((doc.id, key, std::sync::Arc::new(segs)));}if let Some((_, _, segs)) = &app.outline_cache {let time = ui.input(|i| i.time);@@ -622,16 +703,64 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:}}}+ if app.ui.transform.is_some() && response.double_clicked() {+ crate::transform_tool::commit(app);+ }+ if tool == Tool::Type && response.double_clicked() {+ crate::type_tool::select_word(app);+ }+ if app.ui.extras.grid {+ crate::rulers::draw_grid(&painter, &xf, &doc);+ }+ crate::rulers::draw_guides(app, &painter, &xf, &doc);draw_drag_preview(app, &painter, &xf);- // Brush cursor.- if matches!(app.ui.tool, Tool::Brush | Tool::Eraser)- && let Some(p) = response.hover_pos()- {- let r = app.session.tools.brush.size / 2.0 * view.zoom;- painter.circle_stroke(p, r.max(1.0), Stroke::new(1.0, Color32::from_white_alpha(200)));- painter.circle_stroke(p, r.max(1.0) + 1.0, Stroke::new(1.0, Color32::from_black_alpha(120)));+ crate::type_tool::draw_overlay(app, &painter, &xf);+ crate::transform_tool::draw_overlay(app, &painter, &xf);+ crate::retouch_ui::draw_source_marker(app, &painter, &xf);+ crate::vector_ui::draw_overlay(app, &painter, &xf, &doc);+ // Tool cursors (Photoshop-style).+ let guide_hover = response.hover_pos().filter(|_| tool == Tool::Move).and_then(|p| {+ let d = xf.to_doc(p);+ crate::rulers::guide_at(app, d[0], d[1])+ });+ if let Some((vertical, _)) = guide_hover {+ ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });+ } else if let Some(c) = response.hover_pos().and_then(|p| crate::transform_tool::cursor(app, xf.to_doc(p))) {+ ui.ctx().set_cursor_icon(c);+ } else if let Some(p) = response.hover_pos() {+ let alt = ui.input(|i| i.modifiers.alt);+ let icon = match tool {+ t if t.is_brushlike() || t == Tool::QuickSelection => {+ // Brush tip outline with a small centre crosshair; hide the OS cursor.+ let r = (app.session.tools.brush.size / 2.0 * view.zoom).max(1.0);+ painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140)));+ painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220)));+ if r > 6.0 {+ let c = Stroke::new(1.0, Color32::from_white_alpha(200));+ painter.line_segment([p - vec2(3.0, 0.0), p + vec2(3.0, 0.0)], c);+ painter.line_segment([p - vec2(0.0, 3.0), p + vec2(0.0, 3.0)], c);+ }+ egui::CursorIcon::None+ }+ Tool::Move => egui::CursorIcon::Move,+ Tool::Hand => {+ if response.dragged() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab }+ }+ Tool::Zoom => {+ if alt { egui::CursorIcon::ZoomOut } else { egui::CursorIcon::ZoomIn }+ }+ Tool::Type => egui::CursorIcon::Text,+ _ => egui::CursorIcon::Crosshair,+ };+ ui.ctx().set_cursor_icon(icon);}}+ if primary {+ app.hover_doc = response.hover_pos().map(|p| xf.to_doc(p));+ }+ if primary && app.ui.extras.rulers {+ crate::rulers::draw_rulers(app, ui, full, &xf);+ }if primary {app.ui.views[idx] = view.clone();}@@ -702,7 +831,57 @@ fn marching_ants(painter: &egui::Painter, r: Rect, time: f64) {}}+/// Photoshop crop overlay: dimmed outside, bright frame, rule-of-thirds grid, corner handles.+fn crop_overlay(painter: &egui::Painter, r: Rect) {+ let clip = painter.clip_rect();+ let dim = Color32::from_black_alpha(130);+ for band in [+ Rect::from_min_max(clip.min, egui::pos2(clip.max.x, r.min.y)),+ Rect::from_min_max(egui::pos2(clip.min.x, r.max.y), clip.max),+ Rect::from_min_max(egui::pos2(clip.min.x, r.min.y), egui::pos2(r.min.x, r.max.y)),+ Rect::from_min_max(egui::pos2(r.max.x, r.min.y), egui::pos2(clip.max.x, r.max.y)),+ ] {+ painter.rect_filled(band, 0.0, dim);+ }+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Middle);+ let thin = Stroke::new(1.0, Color32::from_white_alpha(90));+ for i in 1..3 {+ let fx = r.left() + r.width() * i as f32 / 3.0;+ let fy = r.top() + r.height() * i as f32 / 3.0;+ painter.line_segment([egui::pos2(fx, r.top()), egui::pos2(fx, r.bottom())], thin);+ painter.line_segment([egui::pos2(r.left(), fy), egui::pos2(r.right(), fy)], thin);+ }+ let h = Stroke::new(3.0, Color32::WHITE);+ let l = 14.0f32.min(r.width() / 3.0).min(r.height() / 3.0);+ for (c, dx, dy) in [(r.left_top(), 1.0, 1.0), (r.right_top(), -1.0, 1.0), (r.left_bottom(), 1.0, -1.0), (r.right_bottom(), -1.0, -1.0)] {+ painter.line_segment([c, c + vec2(l * dx, 0.0)], h);+ painter.line_segment([c, c + vec2(0.0, l * dy)], h);+ }+}++/// Overlays that persist between gestures: polygonal lasso in progress, pending crop box.+fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: Option<Pos2>) {+ if !app.ui.polygon.is_empty() {+ let mut pts: Vec<Pos2> = app.ui.polygon.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect();+ if let Some(h) = hover {+ pts.push(h);+ }+ painter.add(egui::Shape::line(pts.clone(), Stroke::new(1.0, Color32::WHITE)));+ painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, Color32::BLACK), 4.0, 4.0));+ for p in &pts[..app.ui.polygon.len()] {+ painter.rect_filled(Rect::from_center_size(*p, vec2(5.0, 5.0)), 0.0, Color32::WHITE);+ }+ }+ if let Some(c) = app.ui.crop_rect+ && app.drag.is_none()+ {+ let r = Rect::from_two_pos(xf.to_screen(c[0] as f32, c[1] as f32), xf.to_screen(c[2] as f32, c[3] as f32));+ crop_overlay(painter, r);+ }+}+fn draw_drag_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {+ draw_tool_state(app, painter, xf, painter.ctx().input(|i| i.pointer.hover_pos()));let Some(d) = &app.drag else { return };let last = d.points.last().map(|p| [p[0], p[1]]).unwrap_or(d.start);match d.tool {@@ -717,14 +896,53 @@ fn draw_drag_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXforpainter.add(egui::Shape::line(pts, Stroke::new(w, color)));}}- Tool::RectMarquee | Tool::EllipseMarquee => {+ t if t.is_brushlike() || t == Tool::QuickSelection => {+ // Retouching strokes preview as a translucent trail of the brush footprint.+ let pts: Vec<Pos2> = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect();+ let w = (app.session.tools.brush.size * xf.zoom).max(1.0);+ let col = Color32::from_white_alpha(if t == Tool::QuickSelection { 40 } else { 60 });+ if pts.len() == 1 {+ painter.circle_filled(pts[0], w / 2.0, col);+ } else {+ painter.add(egui::Shape::line(pts, Stroke::new(w, col)));+ }+ }+ Tool::Line => {+ painter.line_segment([xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32)], Stroke::new(1.0, crate::theme::Tokens::get(painter.ctx()).accent));+ }+ Tool::RectMarquee | Tool::EllipseMarquee | Tool::ObjectSelection | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon => {let r = Rect::from_two_pos(xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32));- if d.tool == Tool::EllipseMarquee {+ if matches!(d.tool, Tool::EllipseMarquee | Tool::EllipseShape) {painter.add(egui::Shape::ellipse_stroke(r.center(), r.size() / 2.0, Stroke::new(1.0, Color32::WHITE)));} else {painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Middle);}}+ Tool::Lasso => {+ let pts: Vec<Pos2> = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect();+ if pts.len() > 1 {+ painter.add(egui::Shape::line(pts.clone(), Stroke::new(1.0, Color32::WHITE)));+ painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, Color32::BLACK), 4.0, 4.0));+ }+ }+ Tool::Gradient => {+ let a = xf.to_screen(d.start[0] as f32, d.start[1] as f32);+ let b = xf.to_screen(last[0] as f32, last[1] as f32);+ painter.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(140)));+ painter.line_segment([a, b], Stroke::new(1.0, Color32::WHITE));+ painter.circle_filled(a, 3.0, Color32::WHITE);+ painter.circle_filled(b, 3.0, Color32::WHITE);+ }+ Tool::Crop => {+ let r = Rect::from_two_pos(xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32));+ crop_overlay(painter, r);+ }+ Tool::Type => {+ let r = Rect::from_two_pos(xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32));+ let pts = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()];+ painter.add(egui::Shape::line(pts.to_vec(), Stroke::new(1.0, Color32::WHITE)));+ painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, Color32::BLACK), 3.0, 3.0));+ }Tool::Move => {let off = vec2(((last[0] - d.start[0]) as f32) * xf.zoom, ((last[1] - d.start[1]) as f32) * xf.zoom);painter.arrow(xf.to_screen(d.start[0] as f32, d.start[1] as f32), off, Stroke::new(2.0, crate::theme::Tokens::get(painter.ctx()).accent));@@ -735,7 +953,34 @@ fn draw_drag_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXfor/// Tool state machine. Shared by mouse input and automation.pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) {+ if crate::transform_tool::pointer(app, ev, mods) {+ return;+ }let tool = app.ui.tool;+ // Move tool over a guide drags the guide (off the canvas deletes it).+ match ev {+ ToolEvent::Down { x, y, .. } if tool == Tool::Move => {+ if let Some((vertical, i)) = crate::rulers::guide_at(app, x, y) {+ app.guide_drag = Some(crate::rulers::GuideDrag { vertical, index: Some(i), pos: if vertical { x } else { y } });+ return;+ }+ }+ ToolEvent::Move { x, y, .. } => {+ if let Some(d) = app.guide_drag.as_mut().filter(|d| d.index.is_some()) {+ d.pos = if d.vertical { x } else { y };+ return;+ }+ }+ ToolEvent::Up { x, y } => {+ if let Some(mut d) = app.guide_drag.filter(|d| d.index.is_some()) {+ app.guide_drag = None;+ d.pos = if d.vertical { x } else { y };+ crate::rulers::finish_drag(app, d);+ return;+ }+ }+ _ => {}+ }match ev {ToolEvent::Down { x, y, pressure } => {if tool == Tool::Eyedropper {@@ -748,9 +993,48 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)}return;}+ match tool {+ Tool::Pen => {+ crate::vector_ui::pen_down(app, x, y);+ return;+ }+ Tool::CloneStamp | Tool::Healing if mods.alt => {+ crate::retouch_ui::set_source(app, x, y);+ return;+ }+ Tool::MagicWand => {+ let o = app.ui.tool_options.clone();+ let mode = selection_mode(app, mods);+ let _ = app.run("select.magicWand", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all_layers, "mode": mode}));+ return;+ }+ Tool::PaintBucket => {+ let o = app.ui.tool_options.clone();+ let _ = app.run("paint.bucket", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "opacity": o.fill_opacity, "target": paint_target(app)}));+ return;+ }+ Tool::PolygonLasso => {+ // Click adds a vertex; clicking near the first vertex closes the polygon.+ let close = app.ui.polygon.first().is_some_and(|p0| app.ui.polygon.len() >= 3 && ((p0[0] - x).powi(2) + (p0[1] - y).powi(2)).sqrt() < 8.0 / app.current_zoom().max(0.01) as f64);+ if close {+ commit_polygon(app, mods);+ } else {+ app.ui.polygon.push([x, y]);+ }+ return;+ }+ Tool::Type if crate::type_tool::pointer_down(app, x, y, mods.shift) => return,+ _ => {}+ }app.drag = Some(Drag { tool, start: [x, y], points: vec![[x, y, pressure as f64]], modifiers: mods });}ToolEvent::Move { x, y, pressure } => {+ if tool == Tool::Type && app.drag.is_none() {+ crate::type_tool::pointer_move(app, x, y);+ }+ if tool == Tool::Pen {+ crate::vector_ui::pen_move(app, x, y);+ }if let Some(d) = &mut app.drag&& d.points.last().is_none_or(|p| (p[0] - x).abs() + (p[1] - y).abs() > 0.25){@@ -758,6 +1042,14 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)}}ToolEvent::Up { x, y } => {+ if tool == Tool::Type+ && let Some(e) = app.ui.text_edit.as_mut()+ {+ e.dragging = false;+ }+ if tool == Tool::Pen {+ crate::vector_ui::pen_up(app);+ }let Some(mut d) = app.drag.take() else { return };if d.points.last().is_none_or(|p| p[0] != x || p[1] != y) {d.points.push([x, y, d.points.last().map_or(1.0, |p| p[2])]);@@ -769,10 +1061,17 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {let end = d.points.last().copied().unwrap_or([d.start[0], d.start[1], 1.0]);+ if crate::retouch_ui::finish_stroke(app, d.tool, &d.points, d.modifiers) {+ return;+ }match d.tool {+ Tool::ObjectSelection => crate::retouch_ui::finish_object_selection(app, d.start, [end[0], end[1]], d.modifiers),+ t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.modifiers),+ Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]),+ Tool::Type => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]),Tool::Brush | Tool::Eraser => {let pts: Vec<[f64; 3]> = d.points.clone();- let _ = app.run("paint.stroke", json!({ "points": pts, "erase": d.tool == Tool::Eraser, "smoothing": 0.3 }));+ let _ = app.run("paint.stroke", json!({ "points": pts, "erase": d.tool == Tool::Eraser, "smoothing": 0.3, "target": paint_target(app) }));}Tool::RectMarquee | Tool::EllipseMarquee => {let (x0, y0) = (d.start[0].min(end[0]).floor(), d.start[1].min(end[1]).floor());@@ -797,6 +1096,32 @@ fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {};let _ = app.run("select.rect", json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0, "mode": mode, "ellipse": d.tool == Tool::EllipseMarquee}));}+ Tool::Lasso => {+ let pts: Vec<[f64; 2]> = d.points.iter().map(|p| [p[0], p[1]]).collect();+ if pts.len() >= 3 {+ let mode = selection_mode(app, d.modifiers);+ let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": app.ui.tool_options.anti_alias}));+ } else if app.session.is_enabled("select.deselect") {+ let _ = app.run("select.deselect", json!({}));+ }+ }+ Tool::Gradient => {+ if (end[0] - d.start[0]).abs() + (end[1] - d.start[1]).abs() >= 2.0 {+ let o = app.ui.tool_options.clone();+ let fg = app.session.tools.foreground;+ let bg = app.session.tools.background;+ let _ = app.run(+ "paint.gradient",+ json!({"from": [d.start[0], d.start[1]], "to": [end[0], end[1]], "style": o.gradient_style, "reverse": o.gradient_reverse, "colors": [hex(fg), hex(bg)], "opacity": o.fill_opacity, "target": paint_target(app)}),+ );+ }+ }+ Tool::Crop => {+ let r = [d.start[0].min(end[0]), d.start[1].min(end[1]), d.start[0].max(end[0]), d.start[1].max(end[1])];+ if r[2] - r[0] >= 2.0 && r[3] - r[1] >= 2.0 {+ app.ui.crop_rect = Some(r);+ }+ }Tool::Move => {let (dx, dy) = ((end[0] - d.start[0]).round(), (end[1] - d.start[1]).round());if dx != 0.0 || dy != 0.0 {@@ -836,6 +1161,52 @@ pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) {app.ui.windows.retain(|w| w.open);}+/// Selection mode from the options bar, overridden by modifier keys (⇧ add, ⌥ subtract, ⇧⌥ intersect).+fn selection_mode(app: &PhotocraftApp, m: egui::Modifiers) -> &'static str {+ if m.shift && m.alt {+ "intersect"+ } else if m.shift {+ "add"+ } else if m.alt {+ "subtract"+ } else {+ ["replace", "add", "subtract", "intersect"][app.ui.selection_mode.min(3) as usize]+ }+}++/// Close the polygonal lasso and make the selection.+pub fn commit_polygon(app: &mut PhotocraftApp, mods: egui::Modifiers) {+ let pts = std::mem::take(&mut app.ui.polygon);+ if pts.len() >= 3 {+ let mode = selection_mode(app, mods);+ let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": app.ui.tool_options.anti_alias}));+ }+}++/// Apply the crop tool's rectangle.+pub fn commit_crop(app: &mut PhotocraftApp) {+ let Some(r) = app.ui.crop_rect.take() else { return };+ let (x, y) = (r[0].round(), r[1].round());+ let (w, h) = ((r[2] - r[0]).round().max(1.0), (r[3] - r[1]).round().max(1.0));+ if app.run("image.crop", json!({"x": x, "y": y, "width": w, "height": h})).is_ok()+ && let Some(i) = app.session.active_index()+ {+ app.ui.views[i].fit_pending = true;+ }+}++/// "mask" when the Layers panel targets the active layer's mask, else "pixels".+pub fn paint_target(app: &PhotocraftApp) -> &'static str {+ let has_mask = app.session.active().and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))).is_some_and(|l| l.mask.is_some());+ if app.ui.mask_target && has_mask { "mask" } else { "pixels" }+}++/// `#rrggbb` for an sRGB colour (the engine's colour parameter notation).+fn hex(c: [f32; 4]) -> String {+ let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2]))+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 16e7b8f54..2fe364f4c 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -12,6 +12,8 @@//! - `ui.dialog.open {kind, fields?}` / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`//! - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows//! - `ui.pointer {events: [{kind: down|move|up, x, y, pressure?}], modifiers?}`: drive the active tool in document coordinates+//! - `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points+//! - `ui.key {key, command?, shift?, alt?, ctrl?}` / `ui.type {text}`: synthetic keyboard input//! - `ui.resize {width, height}`: resize the main window//! - `ui.screenshot {path?, focus?}`: capture the main window (PNG). Raises the window first (default)//! because occluded macOS windows stop rendering@@ -45,6 +47,9 @@ impl ControlRequest {pub enum Outcome {Done(Value),Screenshot { token: u64, path: Option<String> },+ /// Synthetic input queued: reply once the app has processed all of it (so a following+ /// `ui.inspect`/`engine.execute` observes the effect).+ AfterInput,}fn ok(v: Value) -> Outcome {@@ -92,6 +97,21 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequestErr(e) => return err(e),}}+ if let Some(m) = p.get("maskTarget").and_then(Value::as_bool) {+ app.ui.mask_target = m;+ }+ if let Some(tabs) = p.get("dockTabs") {+ let mut cur = serde_json::to_value(app.ui.dock_tabs).unwrap_or_default();+ if let (Some(c), Some(n)) = (cur.as_object_mut(), tabs.as_object()) {+ for (k, v) in n {+ c.insert(k.clone(), v.clone());+ }+ }+ match serde_json::from_value(cur) {+ Ok(v) => app.ui.dock_tabs = v,+ Err(e) => return err(e),+ }+ }if let Some(i) = app.session.active_index() {if let Some(z) = p.get("zoom").and_then(Value::as_f64) {app.ui.views[i].zoom = (z as f32).clamp(0.01, 64.0);@@ -174,15 +194,12 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest}"ui.pointer" => {let Some(events) = p.get("events").and_then(Value::as_array) else { return err("missing `events`") };- let mods = egui::Modifiers {- shift: p.get("shift").and_then(Value::as_bool).unwrap_or(false),- alt: p.get("alt").and_then(Value::as_bool).unwrap_or(false),- ..Default::default()- };- if let Some(t) = s("tool") {- if let Some(t) = Tool::from_name(t) {- app.ui.tool = t;- }+ // Modifier flags may be top-level or grouped under "modifiers".+ let m = p.get("modifiers").unwrap_or(p);+ let flag = |k: &str| m.get(k).and_then(Value::as_bool).unwrap_or(false);+ let mods = egui::Modifiers { shift: flag("shift"), alt: flag("alt"), command: flag("command"), mac_cmd: cfg!(target_os = "macos") && flag("command"), ctrl: flag("ctrl") };+ if let Some(t) = s("tool").and_then(Tool::from_name) {+ app.ui.tool = t;}for e in events {let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.0);@@ -197,6 +214,45 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest}ok(json!({"status": app.ui.status}))}+ "ui.click" | "ui.move" => {+ // Screen coordinates in points (as reported by ui.inspect window size).+ let x = p.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32;+ let y = p.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32;+ let pos = egui::pos2(x, y);+ let button = match s("button").unwrap_or("left") {+ "right" | "secondary" => egui::PointerButton::Secondary,+ "middle" => egui::PointerButton::Middle,+ _ => egui::PointerButton::Primary,+ };+ app.synthetic.push(egui::Event::PointerMoved(pos));+ if req.method == "ui.click" {+ let clicks = p.get("count").and_then(Value::as_u64).unwrap_or(1);+ for _ in 0..clicks {+ app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: true, modifiers: Default::default() });+ app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: false, modifiers: Default::default() });+ }+ }+ ctx.request_repaint();+ Outcome::AfterInput+ }+ "ui.key" => {+ let Some(name) = s("key") else { return err("missing `key`") };+ let Some(key) = egui::Key::from_name(name) else { return err(format!("unknown key `{name}`")) };+ // Modifier flags may be top-level or grouped under "modifiers".+ let m = p.get("modifiers").unwrap_or(p);+ let flag = |k: &str| m.get(k).and_then(Value::as_bool).unwrap_or(false);+ let modifiers = egui::Modifiers { command: flag("command"), mac_cmd: cfg!(target_os = "macos") && flag("command"), shift: flag("shift"), alt: flag("alt"), ctrl: flag("ctrl") };+ app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers });+ app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers });+ ctx.request_repaint();+ Outcome::AfterInput+ }+ "ui.type" => {+ let Some(text) = s("text") else { return err("missing `text`") };+ app.synthetic.push(egui::Event::Text(text.to_string()));+ ctx.request_repaint();+ Outcome::AfterInput+ }"ui.resize" => {let (w, h) = (p.get("width").and_then(Value::as_f64).unwrap_or(1280.0), p.get("height").and_then(Value::as_f64).unwrap_or(800.0));ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w as f32, h as f32)));@@ -214,8 +270,9 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequestif p.get("focus").and_then(Value::as_bool).unwrap_or(true) {ctx.send_viewport_cmd(egui::ViewportCommand::Focus);}+ // The capture itself is issued by `PhotocraftApp::issue_screenshots` once open/close+ // animations (modals, popups) have settled.let token = app.ui.alloc_id();- ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(token)));ctx.request_repaint();Outcome::Screenshot { token, path: s("path").map(str::to_string) }}@@ -244,6 +301,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {json!({"window": {"width": screen.width(), "height": screen.height(), "pixelsPerPoint": ctx.pixels_per_point()},"tool": app.ui.tool,+ "textEdit": app.ui.text_edit,"panels": app.ui.panels,"views": app.ui.views,"dialogs": dialogs,diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex bc9d2ae51..7c1df6da9 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -14,7 +14,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {let title = title(&d);let modal = egui::Modal::new(egui::Id::new(("dialog", d.id))).show(ctx, |ui| {ui.set_min_width(380.0);- ui.set_max_width(if d.kind == DialogKind::LayerStyle { 600.0 } else { 440.0 });+ ui.set_max_width(if d.kind == DialogKind::LayerStyle || d.fields.contains_key("__export") { 600.0 } else { 440.0 });ui.label(egui::RichText::new(&title).font(crate::theme::semibold(15.0)));ui.add_space(4.0);crate::widgets::hairline(ui);@@ -26,6 +26,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {ui.label(format!("Version {}", env!("CARGO_PKG_VERSION")));ui.weak("egui · wgpu · photocraft-engine");}+ DialogKind::Command if fields.contains_key("__export") => crate::export_dialog::body(app, ui, &mut fields),+ DialogKind::Command if fields.contains_key("__sizing") => crate::sizing::body(ui, &mut fields),+ DialogKind::Command if fields.contains_key("__filter") => crate::filter_dialog::body(ui, &mut fields),DialogKind::Command => command_fields(ui, &mut fields),DialogKind::LayerStyle => crate::layer_style::body(ui, &mut fields),DialogKind::Error => {@@ -40,7 +43,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {outcome = Some(false);}} else {- let ok_label = if d.kind == DialogKind::NewDocument { "Create" } else { "OK" };+ let ok_label = if d.kind == DialogKind::NewDocument {+ "Create"+ } else if d.fields.contains_key("__export") {+ "Export"+ } else {+ "OK"+ };if crate::widgets::primary_button(ui, ok_label, 84.0).clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {outcome = Some(true);}@@ -62,6 +71,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {}Some(false) => {app.ui.close_dialog(d.id);+ app.filter_preview = None;}None => {}}@@ -89,12 +99,11 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {}r}+ DialogKind::Command if d.fields.contains_key("__export") => crate::export_dialog::confirm(app, &d.fields),DialogKind::Command => {- let mut fields = d.fields;- let cmd = fields.remove("__command").and_then(|v| v.as_str().map(str::to_string)).ok_or("dialog has no command")?;- fields.remove("__label");- fields.remove("__kind");- app.run(&cmd, Value::Object(fields))+ app.filter_preview = None;+ let cmd = d.fields.get("__command").and_then(|v| v.as_str().map(str::to_string)).ok_or("dialog has no command")?;+ app.run(&cmd, crate::filter_dialog::params_of(&d.fields))}DialogKind::LayerStyle => crate::layer_style::confirm(app, &d.fields),DialogKind::About | DialogKind::Error => Ok(Value::Null),diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rsnew file mode 100644index 000000000..858dc1fb2--- /dev/null+++ b/crates/ui-egui/src/export_dialog.rs@@ -0,0 +1,191 @@+//! File › Export › Export As… (and Quick Export as PNG): format, quality, transparency and scale,+//! with a preview and an estimated file size. The estimate encodes a small proxy and scales by+//! pixel count, so the dialog stays instant on 36 MP documents.++use std::sync::Arc;++use photocraft_doc::Document;+use serde_json::{Map, Value, json};++use crate::state::DialogKind;+use crate::theme::Tokens;+use crate::{ExportSettings, PhotocraftApp};++const FORMATS: [(&str, &str); 4] = [("png", "PNG"), ("jpg", "JPG"), ("webp", "WebP (lossless)"), ("tif", "TIFF")];++pub fn open(app: &mut PhotocraftApp) -> Result<u64, String> {+ let st = app.session.active().ok_or("no document")?;+ let mut f = Map::new();+ f.insert("__export".into(), json!(true));+ f.insert("__label".into(), json!("Export As"));+ f.insert("format".into(), json!("png"));+ f.insert("quality".into(), json!(85));+ f.insert("transparency".into(), json!(true));+ f.insert("scale".into(), json!(100));+ f.insert("__w".into(), json!(st.doc.size.width));+ f.insert("__h".into(), json!(st.doc.size.height));+ Ok(app.ui.open_dialog(DialogKind::Command, f))+}++fn s(f: &Map<String, Value>, k: &str) -> String {+ f.get(k).and_then(Value::as_str).unwrap_or_default().to_string()+}+fn n(f: &Map<String, Value>, k: &str, d: f64) -> f64 {+ f.get(k).and_then(Value::as_f64).unwrap_or(d)+}++/// The document as exported: scaled (engine Image Size, bicubic) and flattened over white when+/// transparency is off or the format has no alpha.+fn export_document(doc: &Document, f: &Map<String, Value>, max_side: Option<u32>) -> Result<Document, String> {+ let mut s = photocraft_engine::Session::new();+ s.add_document(doc.clone(), None);+ let scale = n(f, "scale", 100.0) / 100.0;+ let mut w = (doc.size.width as f64 * scale).round().max(1.0);+ if let Some(m) = max_side {+ let long = doc.size.width.max(doc.size.height) as f64 * scale;+ if long > m as f64 {+ w = (w * m as f64 / long).round().max(1.0);+ }+ }+ if (w - doc.size.width as f64).abs() >= 1.0 {+ s.execute("image.imageSize", json!({"width": w, "resample": if max_side.is_some() { "bilinear" } else { "bicubic" }})).map_err(|e| e.to_string())?;+ }+ let fmt = s_fmt(f);+ if !f.get("transparency").and_then(Value::as_bool).unwrap_or(true) || fmt == "jpg" {+ s.execute("layer.flattenImage", json!({})).map_err(|e| e.to_string())?;+ }+ s.active().map(|d| (*d.doc).clone()).ok_or_else(|| "export failed".into())+}++fn s_fmt(f: &Map<String, Value>) -> String {+ let v = s(f, "format");+ if v.is_empty() { "png".into() } else { v }+}++fn settings(f: &Map<String, Value>) -> ExportSettings {+ ExportSettings { jpeg_quality: (s_fmt(f) == "jpg").then(|| n(f, "quality", 85.0).clamp(1.0, 100.0) as u8) }+}++/// Estimated size (bytes) from a ≤512 px proxy encode, scaled by pixel count.+fn estimate(app: &PhotocraftApp, doc: &Document, f: &Map<String, Value>) -> Option<u64> {+ let export = app.services.export.as_ref()?;+ let proxy = export_document(doc, f, Some(512)).ok()?;+ let bytes = export(&proxy, &format!("estimate.{}", s_fmt(f)), &settings(f)).ok()?;+ let scale = n(f, "scale", 100.0) / 100.0;+ let full = doc.size.width as f64 * scale * doc.size.height as f64 * scale;+ let small = (proxy.size.width as f64 * proxy.size.height as f64).max(1.0);+ Some((bytes.len() as f64 * full / small) as u64)+}++pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {+ let t = Tokens::get(ui.ctx());+ let Some(doc) = app.session.active().map(|s| s.doc.clone()) else { return };+ ui.horizontal_top(|ui| {+ // Left: settings.+ ui.vertical(|ui| {+ ui.set_width(220.0);+ ui.label(egui::RichText::new("File Settings").font(crate::theme::semibold(12.0)).color(t.text));+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new("Format").color(t.text_dim));+ let mut fmt = s_fmt(f);+ let opts: Vec<(String, &str)> = FORMATS.iter().map(|(k, l)| (k.to_string(), *l)).collect();+ if crate::widgets::dropdown(ui, "export-format", &mut fmt, &opts, 130.0) {+ f.insert("format".into(), json!(fmt));+ }+ });+ let fmt = s_fmt(f);+ if fmt == "jpg" {+ let mut q = n(f, "quality", 85.0) as f32;+ crate::widgets::slider_row(ui, "Quality", &mut q, 1.0..=100.0, "%", None);+ f.insert("quality".into(), json!(q.round()));+ } else {+ let mut tr = f.get("transparency").and_then(Value::as_bool).unwrap_or(true);+ crate::widgets::checkbox(ui, &mut tr, "Transparency");+ f.insert("transparency".into(), json!(tr));+ }+ ui.add_space(8.0);+ ui.label(egui::RichText::new("Image Size").font(crate::theme::semibold(12.0)).color(t.text));+ let mut sc = n(f, "scale", 100.0) as f32;+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new("Scale").color(t.text_dim));+ crate::widgets::value_field(ui, &mut sc, 1.0..=1000.0, "%", 70.0);+ });+ f.insert("scale".into(), json!(sc.round()));+ let (w, h) = ((doc.size.width as f32 * sc / 100.0).round(), (doc.size.height as f32 * sc / 100.0).round());+ ui.label(egui::RichText::new(format!("{w} × {h} px")).color(t.text_dim).size(11.5));+ });+ ui.add_space(12.0);+ // Right: preview + estimated size.+ ui.vertical(|ui| {+ let key = egui::Id::new(("export-preview", doc.id.0, app.session.active().map_or(0, |s| s.revision)));+ let sig = format!("{}{}{}{}", s_fmt(f), n(f, "quality", 85.0), f.get("transparency").map(|v| v.to_string()).unwrap_or_default(), n(f, "scale", 100.0));+ let cached: Option<(String, Option<u64>, Arc<egui::TextureHandle>)> = ui.data(|d| d.get_temp(key));+ let (size, tex) = match cached.filter(|c| c.0 == sig) {+ Some((_, size, tex)) => (size, tex),+ None => {+ let size = estimate(app, &doc, f);+ let img = photocraft_compose::thumbnail(&export_document(&doc, f, Some(360)).unwrap_or_else(|_| (*doc).clone()), 360);+ let color = egui::ColorImage::from_rgba_unmultiplied([img.width as usize, img.height as usize], &img.pixels);+ let tex = Arc::new(ui.ctx().load_texture("export-preview", color, egui::TextureOptions::LINEAR));+ ui.data_mut(|d| d.insert_temp(key, (sig, size, tex.clone())));+ (size, tex)+ }+ };+ let side = 300.0;+ let (r, _) = ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::hover());+ crate::widgets::checker(ui.painter(), r, 8.0);+ let ts = tex.size_vec2();+ let k = (side / ts.x.max(ts.y)).min(1.0e3);+ let ir = egui::Rect::from_center_size(r.center(), ts * k);+ ui.painter().image(tex.id(), ir, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), egui::Color32::WHITE);+ ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Outside);+ let est = size.map_or("—".to_string(), |b| crate::sizing::human_bytes(b as f64));+ ui.label(egui::RichText::new(format!("{} ≈ {est}", s_fmt(f).to_uppercase())).color(t.text_dim).size(11.5));+ });+ });+}++/// Export with the dialog's settings: choose a path, render, encode, write.+pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {+ let st = app.session.active().ok_or("no document")?;+ let doc = st.doc.clone();+ let stem = doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(a, _)| a).to_string();+ let ext = s_fmt(f);+ let suggested = format!("{stem}.{ext}");+ let path = app.services.pick_save.as_mut().and_then(|p| p(&suggested)).ok_or("cancelled")?;+ let out = export_document(&doc, f, None)?;+ let export = app.services.export.as_ref().ok_or("no exporter configured")?;+ let bytes = export(&out, &path, &settings(f))?;+ let write = app.services.write.as_mut().ok_or("no writer configured")?;+ write(&path, &bytes)?;+ app.ui.status = format!("Exported {path} ({})", crate::sizing::human_bytes(bytes.len() as f64));+ Ok(json!({"path": path, "bytes": bytes.len()}))+}++/// File › Export › Quick Export as PNG: current settings-free PNG next to the document.+pub fn quick_export_png(app: &mut PhotocraftApp) -> Result<Value, String> {+ let mut f = Map::new();+ f.insert("format".into(), json!("png"));+ f.insert("transparency".into(), json!(true));+ f.insert("scale".into(), json!(100));+ confirm(app, &f)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn export_document_scales_and_flattens() {+ let doc = Document::with_background("x", photocraft_doc::Size::new(200, 100), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8, photocraft_doc::Color::WHITE);+ let mut f = Map::new();+ f.insert("format".into(), json!("jpg"));+ f.insert("scale".into(), json!(50));+ let out = export_document(&doc, &f, None).unwrap();+ assert_eq!((out.size.width, out.size.height), (100, 50));+ assert_eq!(out.layers.len(), 1);+ let proxy = export_document(&doc, &f, Some(40)).unwrap();+ assert_eq!(proxy.size.width, 40);+ assert_eq!(settings(&f).jpeg_quality, Some(85));+ }+}diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsnew file mode 100644index 000000000..35b6ea9ff--- /dev/null+++ b/crates/ui-egui/src/filter_dialog.rs@@ -0,0 +1,259 @@+//! Filter dialogs generated from engine command parameter specs, with live on-canvas preview.+//!+//! The preview runs the *same engine command* on the downsampled proxy document (pixel-sized+//! parameters scaled by the proxy factor), so what you preview is what you get.++use std::sync::Arc;++use photocraft_doc::Document;+use serde_json::{Map, Value, json};++use crate::PhotocraftApp;+use crate::theme::Tokens;++#[derive(Clone, Debug, PartialEq)]+pub enum Kind {+ Range { min: f32, max: f32, default: f32 },+ Choice(Vec<String>),+ Bool,+ Int { default: i64 },+}++#[derive(Clone, Debug, PartialEq)]+pub struct Param {+ pub key: String,+ pub kind: Kind,+}++/// Parse the registry's parameter notation, e.g.+/// `{"radius":0.1..1000=1,"method":"spin|zoom","monochromatic":bool,"seed":u32=0,"horizontal":px=0}`.+pub fn parse_spec(spec: &str) -> Vec<Param> {+ let inner = spec.trim().trim_start_matches('{').trim_end_matches('}');+ let mut out = Vec::new();+ // Split on commas that start a new `"key":`.+ let mut parts: Vec<String> = Vec::new();+ let mut cur = String::new();+ let mut in_str = false;+ for ch in inner.chars() {+ if ch == '"' {+ in_str = !in_str;+ }+ if ch == ',' && !in_str {+ parts.push(std::mem::take(&mut cur));+ } else {+ cur.push(ch);+ }+ }+ if !cur.trim().is_empty() {+ parts.push(cur);+ }+ for part in parts {+ let Some((k, v)) = part.split_once(':') else { continue };+ let key = k.trim().trim_matches('"').to_string();+ if key.is_empty() || key == "layer" {+ continue;+ }+ let v = v.trim();+ let kind = if let Some(choices) = v.strip_prefix('"') {+ let body = choices.split('"').next().unwrap_or("");+ Kind::Choice(body.split('|').map(str::to_string).collect())+ } else if v.starts_with("bool") {+ Kind::Bool+ } else if let Some((range, default)) = v.split_once('=').map(|(a, b)| (a, b.trim())).or(Some((v, ""))) {+ if let Some((lo, hi)) = range.split_once("..") {+ let min = lo.trim().parse().unwrap_or(0.0);+ let max = hi.trim().parse().unwrap_or(100.0);+ let default = default.parse().unwrap_or(min);+ Kind::Range { min, max, default }+ } else {+ Kind::Int { default: default.parse().unwrap_or(0) }+ }+ } else {+ continue;+ };+ out.push(Param { key, kind });+ }+ out+}++/// Parameter keys measured in pixels (scaled for proxy previews).+fn is_pixel_param(key: &str) -> bool {+ matches!(key, "radius" | "distance" | "cellSize" | "horizontal" | "vertical" | "height" | "wavelengthMin" | "wavelengthMax" | "amplitudeMin" | "amplitudeMax")+}++pub fn has_dialog(command: &str) -> bool {+ (command.starts_with("filter.") || command.starts_with("select.modify.") || matches!(command, "image.trim" | "view.newGuide" | "select.refineEdge")) && photocraft_engine::commands::find(command).is_some_and(|c| !parse_spec(c.params).is_empty())+}++pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {+ let spec = photocraft_engine::commands::find(command)?;+ let mut fields = Map::new();+ fields.insert("__command".into(), json!(command));+ fields.insert("__label".into(), json!(spec.label));+ fields.insert("__filter".into(), json!(true));+ if command.starts_with("filter.") {+ fields.insert("__preview".into(), json!(true));+ }+ for p in parse_spec(spec.params) {+ let v = match &p.kind {+ Kind::Range { default, .. } => json!(default),+ Kind::Choice(c) => json!(c.first().cloned().unwrap_or_default()),+ Kind::Bool => json!(false),+ Kind::Int { default } => json!(default),+ };+ fields.insert(p.key, v);+ }+ let id = app.ui.open_dialog(crate::state::DialogKind::Command, fields);+ Some(id)+}++fn label(key: &str) -> String {+ // camelCase → "Camel Case"+ let mut s = String::new();+ for (i, ch) in key.chars().enumerate() {+ if i == 0 {+ s.extend(ch.to_uppercase());+ } else if ch.is_uppercase() {+ s.push(' ');+ s.push(ch);+ } else {+ s.push(ch);+ }+ }+ s+}++fn choice_label(v: &str) -> String {+ label(v)+}++/// Dialog body for filter commands.+pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {+ let t = Tokens::get(ui.ctx());+ let cmd = f.get("__command").and_then(Value::as_str).unwrap_or_default().to_string();+ let Some(spec) = photocraft_engine::commands::find(&cmd) else { return };+ for p in parse_spec(spec.params) {+ match p.kind {+ Kind::Range { min, max, default } => {+ let mut v = f.get(&p.key).and_then(Value::as_f64).unwrap_or(default as f64) as f32;+ let unit = if is_pixel_param(&p.key) { "px" } else if p.key == "angle" { "°" } else if p.key == "amount" && max <= 500.0 { "%" } else { "" };+ let logarithmic = min > 0.0 && max / min > 500.0;+ if logarithmic {+ // Scrub the value field directly; add a log-scaled slider for huge ranges.+ let mut lv = v.max(min.max(0.1)).ln();+ let r = crate::widgets::slider_row(ui, &label(&p.key), &mut v, min..=max, unit, None);+ let _ = r;+ let r2 = crate::widgets::slider(ui, &mut lv, min.max(0.1).ln()..=max.ln(), None);+ if r2.changed() {+ v = lv.exp();+ }+ } else {+ crate::widgets::slider_row(ui, &label(&p.key), &mut v, min..=max, unit, None);+ }+ f.insert(p.key, json!((v * 10.0).round() / 10.0));+ }+ Kind::Choice(options) => {+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new(label(&p.key)).color(t.text_dim));+ let mut cur = f.get(&p.key).and_then(Value::as_str).unwrap_or(&options[0]).to_string();+ let labels: Vec<String> = options.iter().map(|o| choice_label(o)).collect();+ let opts: Vec<(String, &str)> = options.iter().cloned().zip(labels.iter().map(String::as_str)).collect();+ crate::widgets::dropdown(ui, &format!("flt-{cmd}-{}", p.key), &mut cur, &opts, 170.0);+ f.insert(p.key.clone(), json!(cur));+ });+ }+ Kind::Bool => {+ let mut b = f.get(&p.key).and_then(Value::as_bool).unwrap_or(false);+ crate::widgets::checkbox(ui, &mut b, &label(&p.key));+ f.insert(p.key, json!(b));+ }+ Kind::Int { default } => {+ let mut v = f.get(&p.key).and_then(Value::as_f64).unwrap_or(default as f64) as f32;+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new(label(&p.key)).color(t.text_dim));+ crate::widgets::value_field(ui, &mut v, -30000.0..=30000.0, "", 80.0);+ });+ f.insert(p.key, json!(v.round() as i64));+ }+ }+ }+ if let Some(mut preview) = f.get("__preview").and_then(Value::as_bool) {+ ui.add_space(4.0);+ crate::widgets::checkbox(ui, &mut preview, "Preview");+ f.insert("__preview".into(), json!(preview));+ }+}++/// User-facing params (strip the dialog's private `__` keys).+pub fn params_of(f: &Map<String, Value>) -> Value {+ Value::Object(f.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect())+}++/// Compute a preview document: run `command` with `params` on the proxy (scaled) copy of `doc`.+pub fn preview_document(doc: &Document, active: Option<photocraft_doc::LayerId>, command: &str, params: &Value, k: u32) -> Option<Document> {+ let proxy = crate::proxy::proxy_document(doc, k);+ let mut s = photocraft_engine::Session::new();+ s.add_document(proxy, None);+ if let Some(id) = active {+ s.select_layer(id).ok()?;+ }+ let mut p = params.clone();+ if k > 1+ && let Some(o) = p.as_object_mut()+ {+ for (key, v) in o.iter_mut() {+ if is_pixel_param(key)+ && let Some(x) = v.as_f64()+ {+ *v = json!((x / k as f64).max(if key == "cellSize" { 1.0 } else { 0.1 }));+ }+ }+ }+ s.execute(command, p).ok()?;+ s.active().map(|d| (*d.doc).clone())+}++/// Cached preview state on the app.+pub struct FilterPreview {+ pub doc: photocraft_doc::DocId,+ pub revision: u64,+ pub hash: u64,+ pub k: u32,+ pub result: Option<Arc<Document>>,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_registry_notation() {+ let p = parse_spec(r#"{"radius":0.1..1000=1,"method":"spin|zoom","monochromatic":bool,"seed":u32=0,"horizontal":px=0}"#);+ assert_eq!(p[0], Param { key: "radius".into(), kind: Kind::Range { min: 0.1, max: 1000.0, default: 1.0 } });+ assert_eq!(p[1].kind, Kind::Choice(vec!["spin".into(), "zoom".into()]));+ assert_eq!(p[2].kind, Kind::Bool);+ assert_eq!(p[3].kind, Kind::Int { default: 0 });+ assert_eq!(p[4].kind, Kind::Int { default: 0 });+ assert!(parse_spec("{}").is_empty());+ }++ #[test]+ fn every_filter_command_spec_parses() {+ for c in photocraft_engine::command_specs().iter().filter(|c| c.id.starts_with("filter.")) {+ let _ = parse_spec(c.params);+ }+ assert!(has_dialog("filter.blur.gaussianBlur"));+ assert!(!has_dialog("filter.stylize.findEdges"));+ }++ #[test]+ fn preview_runs_engine_command_on_proxy() {+ let mut doc = Document::with_background("p", photocraft_doc::Size::new(64, 64), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8, photocraft_doc::Color::WHITE);+ let bg = doc.layers[0].id;+ doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 32, 64), &[0.0, 0.0, 0.0, 1.0]);+ let out = preview_document(&doc, Some(bg), "filter.blur.gaussianBlur", &json!({"radius": 4.0}), 1).unwrap();+ let p = out.layers[0].surface().unwrap().pixel(32, 32);+ assert!(p[0] > 0.2 && p[0] < 0.8, "edge blurred: {p:?}");+ assert_eq!(label("wavelengthMin"), "Wavelength Min");+ }+}diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rsindex 6f09e6853..883d94bd5 100644--- a/crates/ui-egui/src/gpu_canvas.rs+++ b/crates/ui-egui/src/gpu_canvas.rs@@ -129,12 +129,87 @@ impl GpuCanvas {self.upload_rect(doc, [r.x0 as u32, r.y0 as u32], [r.width(), r.height()], &premultiply_rgba8(&buf.px))}+ /// Composite `region` of `doc` with the wgpu compositor straight into its display texture+ /// (no CPU pixels, no upload of the composite). Returns `Err` when the document uses features+ /// the GPU compositor doesn't cover yet; the caller then falls back to the CPU compositor.+ pub fn composite(&self, doc: &photocraft_doc::Document, region: photocraft_geom::Rect) -> Result<photocraft_gpu::Stats, photocraft_gpu::Unsupported> {+ let (device, queue) = (&self.rs.device, &self.rs.queue);+ let size = [doc.size.width, doc.size.height];+ if size[0] == 0 || size[1] == 0 {+ return Err(photocraft_gpu::Unsupported("empty document".into()));+ }+ if std::env::var_os("PHOTOCRAFT_CPU_COMPOSE").is_some() {+ return Err(photocraft_gpu::Unsupported("disabled by PHOTOCRAFT_CPU_COMPOSE".into()));+ }+ let mut renderer = self.rs.renderer.write();+ let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return Err(photocraft_gpu::Unsupported("no GPU canvas".into())) };+ let mut comp = res.compositor.take().unwrap_or_else(|| photocraft_gpu::Compositor::new(device));+ let key = doc.id.0;+ let fresh = res.docs.get(&key).is_none_or(|d| d.size != size);+ let region = if fresh { doc.bounds() } else { region.intersect(&doc.bounds()) };+ if let Err(e) = comp.supports(doc) {+ res.compositor = Some(comp);+ return Err(e);+ }+ if fresh {+ let tex = DocTextures::new(device, res, size, self.tile);+ res.docs.insert(key, tex);+ }+ let d = &res.docs[&key];+ let (bgl, pipe) = (&res.encode_bgl, &res.encode_pipeline);+ let result = comp.render(device, queue, doc, region, |enc, out| {+ for t in &d.tiles {+ let [tx, ty, tw, th] = t.rect.map(|v| v as i32);+ let r = out.rect.intersect(&photocraft_geom::Rect::from_xywh(tx, ty, tw as u32, th as u32));+ if r.is_empty() {+ continue;+ }+ let offset = [out.rect.x0 - tx, out.rect.y0 - ty, 0, 0];+ let ubuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("pc_encode"), contents: &offset.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>(), usage: wgpu::BufferUsages::UNIFORM });+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("pc_encode"),+ layout: bgl,+ entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(out.view) }, wgpu::BindGroupEntry { binding: 1, resource: ubuf.as_entire_binding() }],+ });+ let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("pc_encode"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &t.levels[0], resolve_target: None, depth_slice: None, ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store } })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ });+ pass.set_pipeline(pipe);+ pass.set_bind_group(0, &bg, &[]);+ pass.set_scissor_rect((r.x0 - tx) as u32, (r.y0 - ty) as u32, r.width(), r.height());+ pass.draw(0..3, 0..1);+ }+ });+ if result.is_ok() {+ d.regenerate_mips(device, queue, res, [region.x0 as u32, region.y0 as u32, region.x1 as u32, region.y1 as u32]);+ if std::env::var_os("PHOTOCRAFT_GPU_SYNC").is_some() {+ // Benchmarking: wait for the GPU so callers can time the whole refresh.+ let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });+ }+ } else if fresh {+ res.docs.remove(&key);+ }+ res.compositor = Some(comp);+ result+ }+/// Free textures of documents not in `live`.pub fn retain(&self, live: &[u64]) {let mut renderer = self.rs.renderer.write();if let Some(res) = renderer.callback_resources.get_mut::<Resources>()&& res.docs.keys().any(|k| !live.contains(k)){+ let gone: Vec<u64> = res.docs.keys().filter(|k| !live.contains(k)).copied().collect();+ if let Some(c) = res.compositor.as_mut() {+ for k in &gone {+ c.forget_doc(photocraft_doc::DocId(*k));+ }+ }res.docs.retain(|k, _| live.contains(k));}}@@ -157,7 +232,7 @@ pub fn now_ms() -> f64 {}/// UI-thread timings (CPU side), exponentially smoothed.-#[derive(Clone, Copy, Debug, Default, serde::Serialize)]+#[derive(Clone, Debug, Default, serde::Serialize)]#[serde(rename_all = "camelCase")]pub struct Perf {/// Average CPU time building the UI per frame (ms).@@ -174,6 +249,15 @@ pub struct Perf {pub last_refresh_px: u64,/// Whether the GPU canvas path is active.pub gpu: bool,+ /// Layer tiles uploaded by the last GPU composite.+ pub gpu_uploads: u64,+ /// Why the last refresh fell back to the CPU compositor (None = GPU composited).+ pub gpu_fallback: Option<String>,+ /// Last command run through the app and its duration (ms).+ pub last_command: String,+ pub command_ms: f64,+ /// Most recent cost of occasional UI work (outline tracing, thumbnails, …), in ms.+ pub spans: std::collections::BTreeMap<&'static str, f64>,#[serde(skip)]max_decay: f64,}@@ -184,6 +268,14 @@ impl Perf {self.last_refresh_px = px;self.composite_ms = composite_ms;self.upload_ms = upload_ms;+ if !kind.starts_with("gpu") {+ self.gpu_uploads = 0;+ } else {+ self.gpu_fallback = None;+ }+ }+ pub fn span(&mut self, name: &'static str, ms: f64) {+ self.spans.insert(name, (ms * 100.0).round() / 100.0);}pub fn frame(&mut self, ms: f64) {self.ui_ms = if self.ui_ms == 0.0 { ms } else { self.ui_ms * 0.9 + ms * 0.1 };@@ -237,6 +329,10 @@ struct Resources {docs: HashMap<u64, DocTextures>,views: HashMap<u64, ViewGpu>,out_linear: bool,+ /// The wgpu layer compositor (created on first use).+ compositor: Option<photocraft_gpu::Compositor>,+ encode_bgl: wgpu::BindGroupLayout,+ encode_pipeline: wgpu::RenderPipeline,}struct ViewGpu {@@ -325,7 +421,33 @@ impl Resources {let mip_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_mip"), bind_group_layouts: &[Some(&mip_bgl)], immediate_size: 0 });let mip_pipeline = pipeline(device, "pc_mip", &mip_layout, &mip_module, ("vs", "fs"), FORMAT, None);let mip_sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("pc_mip"), mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() });- Self { view_bgl, tile_bgl, shadow_pipeline, tile_pipeline, sampler, mip_bgl, mip_pipeline, mip_sampler, docs: HashMap::new(), views: HashMap::new(), out_linear: target.is_srgb() }+ // Compositor output (straight RGBA32F chunk) -> premultiplied RGBA8 display tile.+ let encode_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_encode"), source: wgpu::ShaderSource::Wgsl(ENCODE_WGSL.into()) });+ let unfilterable = wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture { multisampled: false, sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension: wgpu::TextureViewDimension::D2 },+ count: None,+ };+ let encode_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_encode"), entries: &[unfilterable, uniform_entry(1, 16, wgpu::ShaderStages::FRAGMENT)] });+ let encode_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_encode"), bind_group_layouts: &[Some(&encode_bgl)], immediate_size: 0 });+ let encode_pipeline = pipeline(device, "pc_encode", &encode_layout, &encode_module, ("vs", "fs"), FORMAT, None);+ Self {+ view_bgl,+ tile_bgl,+ shadow_pipeline,+ tile_pipeline,+ sampler,+ mip_bgl,+ mip_pipeline,+ mip_sampler,+ docs: HashMap::new(),+ views: HashMap::new(),+ out_linear: target.is_srgb(),+ compositor: None,+ encode_bgl,+ encode_pipeline,+ }}}@@ -649,6 +771,24 @@ fn fs_tile(in: VOut) -> @location(0) vec4<f32> {}"#;+const ENCODE_WGSL: &str = r#"+@group(0) @binding(0) var acc: texture_2d<f32>;+@group(0) @binding(1) var<uniform> offset: vec4<i32>;++@vertex+fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {+ let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u));+ return vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);+}++@fragment+fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let c = textureLoad(acc, vec2<i32>(floor(pos.xy)) - offset.xy, 0);+ let a = clamp(c.a, 0.0, 1.0);+ return vec4(clamp(c.rgb, vec3(0.0), vec3(1.0)) * a, a);+}+"#;+const MIP_WGSL: &str = r#"@group(0) @binding(0) var src: texture_2d<f32>;@group(0) @binding(1) var samp: sampler;@@ -692,7 +832,7 @@ mod tests {#[test]fn shaders_validate() {use wgpu::naga;- for (name, src) in [("canvas", CANVAS_WGSL), ("mip", MIP_WGSL)] {+ for (name, src) in [("canvas", CANVAS_WGSL), ("mip", MIP_WGSL), ("encode", ENCODE_WGSL)] {let module = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(src)));naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap_or_else(|e| panic!("{name}: {e:?}"));}diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rsindex 9bc6d140e..855026af0 100644--- a/crates/ui-egui/src/icon_data.rs+++ b/crates/ui-egui/src/icon_data.rs@@ -1,9 +1,13 @@-//! Lucide icons (ISC licence, see assets/icons/LICENSE-lucide.txt), embedded and tinted at runtime.-//! Photon Studio uses the same icon family; it is also what gives Photocraft its clean line-art look.+//! Lucide icons (ISC licence), embedded and tinted at runtime.pub static ICONS: &[(&str, &[u8])] = &[+ ("align-center", include_bytes!("../../../assets/icons/align-center.svg")),+ ("align-justify", include_bytes!("../../../assets/icons/align-justify.svg")),+ ("align-left", include_bytes!("../../../assets/icons/align-left.svg")),+ ("align-right", include_bytes!("../../../assets/icons/align-right.svg")),("app-window", include_bytes!("../../../assets/icons/app-window.svg")),("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")),+ ("ban", include_bytes!("../../../assets/icons/ban.svg")),("bandage", include_bytes!("../../../assets/icons/bandage.svg")),("blend", include_bytes!("../../../assets/icons/blend.svg")),("brush-cleaning", include_bytes!("../../../assets/icons/brush-cleaning.svg")),@@ -15,30 +19,37 @@ pub static ICONS: &[(&str, &[u8])] = &[("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")),("circle-dashed", include_bytes!("../../../assets/icons/circle-dashed.svg")),("circle-dot", include_bytes!("../../../assets/icons/circle-dot.svg")),+ ("circle", include_bytes!("../../../assets/icons/circle.svg")),("clock", include_bytes!("../../../assets/icons/clock.svg")),+ ("cloud", include_bytes!("../../../assets/icons/cloud.svg")),("compass", include_bytes!("../../../assets/icons/compass.svg")),("contrast", include_bytes!("../../../assets/icons/contrast.svg")),("copy", include_bytes!("../../../assets/icons/copy.svg")),("crop", include_bytes!("../../../assets/icons/crop.svg")),+ ("diamond", include_bytes!("../../../assets/icons/diamond.svg")),("droplet", include_bytes!("../../../assets/icons/droplet.svg")),("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")),("eraser", include_bytes!("../../../assets/icons/eraser.svg")),("eye-off", include_bytes!("../../../assets/icons/eye-off.svg")),("eye", include_bytes!("../../../assets/icons/eye.svg")),("file-plus", include_bytes!("../../../assets/icons/file-plus.svg")),+ ("flame", include_bytes!("../../../assets/icons/flame.svg")),("folder-open", include_bytes!("../../../assets/icons/folder-open.svg")),("folder-plus", include_bytes!("../../../assets/icons/folder-plus.svg")),("folder", include_bytes!("../../../assets/icons/folder.svg")),("gauge", include_bytes!("../../../assets/icons/gauge.svg")),+ ("grid-2x2", include_bytes!("../../../assets/icons/grid-2x2.svg")),("grid-3x3", include_bytes!("../../../assets/icons/grid-3x3.svg")),("hand", include_bytes!("../../../assets/icons/hand.svg")),("image", include_bytes!("../../../assets/icons/image.svg")),("info", include_bytes!("../../../assets/icons/info.svg")),+ ("lasso-select", include_bytes!("../../../assets/icons/lasso-select.svg")),("lasso", include_bytes!("../../../assets/icons/lasso.svg")),("layers", include_bytes!("../../../assets/icons/layers.svg")),("link", include_bytes!("../../../assets/icons/link.svg")),("lock-open", include_bytes!("../../../assets/icons/lock-open.svg")),("lock", include_bytes!("../../../assets/icons/lock.svg")),+ ("lollipop", include_bytes!("../../../assets/icons/lollipop.svg")),("maximize-2", include_bytes!("../../../assets/icons/maximize-2.svg")),("message-square", include_bytes!("../../../assets/icons/message-square.svg")),("minus", include_bytes!("../../../assets/icons/minus.svg")),@@ -51,25 +62,41 @@ pub static ICONS: &[(&str, &[u8])] = &[("panel-right", include_bytes!("../../../assets/icons/panel-right.svg")),("panels-top-left", include_bytes!("../../../assets/icons/panels-top-left.svg")),("pen-tool", include_bytes!("../../../assets/icons/pen-tool.svg")),+ ("pentagon", include_bytes!("../../../assets/icons/pentagon.svg")),("pipette", include_bytes!("../../../assets/icons/pipette.svg")),+ ("play", include_bytes!("../../../assets/icons/play.svg")),("plus", include_bytes!("../../../assets/icons/plus.svg")),+ ("pointer", include_bytes!("../../../assets/icons/pointer.svg")),+ ("rectangle-horizontal", include_bytes!("../../../assets/icons/rectangle-horizontal.svg")),("redo-2", include_bytes!("../../../assets/icons/redo-2.svg")),+ ("rotate-cw", include_bytes!("../../../assets/icons/rotate-cw.svg")),+ ("scaling", include_bytes!("../../../assets/icons/scaling.svg")),+ ("scan-line", include_bytes!("../../../assets/icons/scan-line.svg")),("scan", include_bytes!("../../../assets/icons/scan.svg")),("scissors", include_bytes!("../../../assets/icons/scissors.svg")),("search", include_bytes!("../../../assets/icons/search.svg")),("settings", include_bytes!("../../../assets/icons/settings.svg")),+ ("slash", include_bytes!("../../../assets/icons/slash.svg")),("sliders-horizontal", include_bytes!("../../../assets/icons/sliders-horizontal.svg")),("sparkles", include_bytes!("../../../assets/icons/sparkles.svg")),+ ("spline", include_bytes!("../../../assets/icons/spline.svg")),+ ("square-dashed-mouse-pointer", include_bytes!("../../../assets/icons/square-dashed-mouse-pointer.svg")),("square-dashed", include_bytes!("../../../assets/icons/square-dashed.svg")),("square", include_bytes!("../../../assets/icons/square.svg")),("squares-subtract", include_bytes!("../../../assets/icons/squares-subtract.svg")),("stamp", include_bytes!("../../../assets/icons/stamp.svg")),("sun", include_bytes!("../../../assets/icons/sun.svg")),("swatch-book", include_bytes!("../../../assets/icons/swatch-book.svg")),+ ("text-cursor", include_bytes!("../../../assets/icons/text-cursor.svg")),("trash", include_bytes!("../../../assets/icons/trash.svg")),+ ("triangle-alert", include_bytes!("../../../assets/icons/triangle-alert.svg")),+ ("triangle-right", include_bytes!("../../../assets/icons/triangle-right.svg")),+ ("triangle", include_bytes!("../../../assets/icons/triangle.svg")),("type", include_bytes!("../../../assets/icons/type.svg")),("undo-2", include_bytes!("../../../assets/icons/undo-2.svg")),+ ("unlink", include_bytes!("../../../assets/icons/unlink.svg")),("wand-sparkles", include_bytes!("../../../assets/icons/wand-sparkles.svg")),+ ("wand", include_bytes!("../../../assets/icons/wand.svg")),("x", include_bytes!("../../../assets/icons/x.svg")),("zoom-in", include_bytes!("../../../assets/icons/zoom-in.svg")),];diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rsindex f373c4c4d..2fa932488 100644--- a/crates/ui-egui/src/icons.rs+++ b/crates/ui-egui/src/icons.rs@@ -50,8 +50,33 @@ pub fn tool_icon(t: Tool) -> &'static str {Tool::Brush => "brush",Tool::Eraser => "eraser",Tool::Eyedropper => "pipette",+ Tool::Lasso => "lasso",+ Tool::PolygonLasso => "pentagon",+ Tool::MagicWand => "wand-sparkles",+ Tool::Crop => "crop",+ Tool::Gradient => "blend",+ Tool::PaintBucket => "paint-bucket",+ Tool::Type => "type",Tool::Hand => "hand",Tool::Zoom => "zoom-in",+ Tool::SpotHealing | Tool::Healing => "bandage",+ Tool::CloneStamp => "stamp",+ Tool::HistoryBrush => "clock",+ Tool::Blur => "droplet",+ Tool::Sharpen => "triangle",+ Tool::Smudge => "pointer",+ Tool::Dodge => "lollipop",+ Tool::Burn => "flame",+ Tool::Sponge => "cloud",+ Tool::QuickSelection => "circle-dashed",+ Tool::ObjectSelection => "square-dashed-mouse-pointer",+ Tool::Pen => "pen-tool",+ Tool::PathSelection => "mouse-pointer-2",+ Tool::Rectangle => "rectangle-horizontal",+ Tool::EllipseShape => "circle",+ Tool::Triangle => "triangle",+ Tool::Polygon => "pentagon",+ Tool::Line => "slash",}}@@ -71,6 +96,21 @@ pub fn button(ui: &mut egui::Ui, name: &str, box_size: f32, selected: bool, toolif tooltip.is_empty() { resp } else { resp.on_hover_text(tooltip) }}+/// Rail toggle: "on" gets a quiet filled background and full-strength icon (no accent).+pub fn rail_button(ui: &mut egui::Ui, name: &str, box_size: f32, on: bool, tooltip: &str) -> Response {+ let t = Tokens::get(ui.ctx());+ let (rect, resp) = ui.allocate_exact_size(Vec2::splat(box_size), Sense::click());+ if on {+ ui.painter().rect_filled(rect, t.radius_sm, t.card);+ ui.painter().rect_stroke(rect, t.radius_sm, egui::Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside);+ } else if resp.hovered() {+ ui.painter().rect_filled(rect, t.radius_sm, t.hover);+ }+ let tint = if on || resp.hovered() { t.text } else { t.text_faint };+ paint(ui, rect, name, (box_size * 0.52).round(), tint);+ resp.on_hover_text(tooltip)+}+#[cfg(test)]mod tests {use super::*;@@ -92,18 +132,3 @@ mod tests {}}}--/// Rail toggle: "on" gets a quiet filled background and full-strength icon (no accent).-pub fn rail_button(ui: &mut egui::Ui, name: &str, box_size: f32, on: bool, tooltip: &str) -> Response {- let t = Tokens::get(ui.ctx());- let (rect, resp) = ui.allocate_exact_size(Vec2::splat(box_size), Sense::click());- if on {- ui.painter().rect_filled(rect, t.radius_sm, t.card);- ui.painter().rect_stroke(rect, t.radius_sm, egui::Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside);- } else if resp.hovered() {- ui.painter().rect_filled(rect, t.radius_sm, t.hover);- }- let tint = if on || resp.hovered() { t.text } else { t.text_faint };- paint(ui, rect, name, (box_size * 0.52).round(), tint);- resp.on_hover_text(tooltip)-}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 652ebfede..d3b3ca161 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -6,20 +6,31 @@//! part of the interface.#![forbid(unsafe_code)]+pub mod actions;pub mod canvas;pub mod control;pub mod dialogs;+pub mod export_dialog;pub mod gpu_canvas;+pub mod filter_dialog;pub mod icons;pub mod layer_style;+pub mod menu_catalog;pub mod menus;pub mod outline;pub mod palette;pub mod proxy;+pub mod retouch_ui;+pub mod rulers;pub mod panels;pub mod shortcuts;+mod sizing;pub mod state;pub mod theme;+pub mod tone;+pub mod transform_tool;+pub mod type_tool;+pub mod vector_ui;pub mod widgets;mod icon_data;@@ -33,24 +44,47 @@ use serde_json::Value;pub use control::{ControlRequest, ControlResponse};pub use state::{Tool, UiState};+pub type ImportFn = Box<dyn Fn(&str, &[u8]) -> Result<Document, String>>;+/// Encoder settings chosen in Export As (the file format comes from the name's extension).+#[derive(Clone, Debug, Default, PartialEq)]+pub struct ExportSettings {+ /// JPEG quality 1–100 (None = codec default).+ pub jpeg_quality: Option<u8>,+}++pub type ExportFn = Box<dyn Fn(&Document, &str, &ExportSettings) -> Result<Vec<u8>, String>>;+pub type PickOpenFn = Box<dyn FnMut() -> Option<(String, Vec<u8>)>>;+pub type PickSaveFn = Box<dyn FnMut(&str) -> Option<String>>;+pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;+pub type EncodePngFn = Box<dyn Fn(u32, u32, &[u8]) -> Result<Vec<u8>, String>>;+/// Put an RGBA8 image (width, height, pixels) on the OS clipboard.+pub type ClipboardSetFn = Box<dyn FnMut(u32, u32, &[u8]) -> Result<(), String>>;+/// Read an RGBA8 image from the OS clipboard.+pub type ClipboardGetFn = Box<dyn FnMut() -> Option<(u32, u32, Vec<u8>)>>;+/// Shared queue of (file name, bytes) delivered asynchronously.+pub type Inbox = std::sync::Arc<std::sync::Mutex<Vec<(String, Vec<u8>)>>>;+/// Platform services injected by the app binary (file dialogs, codecs), keeping this crate free of/// I/O dependencies.#[derive(Default)]pub struct Services {/// Decode a file's bytes into a document (PSD, PNG, JPEG, …).- pub import: Option<Box<dyn Fn(&str, &[u8]) -> Result<Document, String>>>,+ pub import: Option<ImportFn>,/// Encode a document for a file name (format chosen by extension).- pub export: Option<Box<dyn Fn(&Document, &str) -> Result<Vec<u8>, String>>>,+ pub export: Option<ExportFn>,/// Show an "open file" dialog; returns (name, bytes).- pub pick_open: Option<Box<dyn FnMut() -> Option<(String, Vec<u8>)>>>,+ pub pick_open: Option<PickOpenFn>,/// Show a "save file" dialog; returns a path/name to write.- pub pick_save: Option<Box<dyn FnMut(&str) -> Option<String>>>,+ pub pick_save: Option<PickSaveFn>,/// Write bytes to a path (native) or trigger a download (web).- pub write: Option<Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>>,+ pub write: Option<WriteFn>,/// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`).- pub encode_png: Option<Box<dyn Fn(u32, u32, &[u8]) -> Result<Vec<u8>, String>>>,+ pub encode_png: Option<EncodePngFn>,/// Files delivered asynchronously (web file pickers, drag-and-drop): drained every frame.- pub inbox: Option<std::sync::Arc<std::sync::Mutex<Vec<(String, Vec<u8>)>>>>,+ pub inbox: Option<Inbox>,+ /// OS clipboard images: copies go out, screenshots and images from other apps come in.+ pub clipboard_set_image: Option<ClipboardSetFn>,+ pub clipboard_get_image: Option<ClipboardGetFn>,}pub struct PhotocraftApp {@@ -62,6 +96,10 @@ pub struct PhotocraftApp {drag: Option<canvas::Drag>,control_rx: Option<Receiver<ControlRequest>>,pending_screenshots: Vec<(u64, Option<String>, Sender<ControlResponse>)>,+ /// Screenshots not yet requested from the viewport: (token, earliest time in ms, frames seen).+ queued_screenshots: Vec<(u64, f64, u32)>,+ /// Control replies waiting for queued synthetic input to be processed.+ input_waiters: Vec<Sender<ControlResponse>>,/// Live (uncommitted) adjustment edit shown on canvas while a slider is dragged.pub live_adjust: Option<(photocraft_doc::LayerId, Value)>,/// Frames rendered (for tests and the status bar).@@ -83,6 +121,29 @@ pub struct PhotocraftApp {/// Key of the preview currently uploaded to the GPU (doc, params hash).pub(crate) proxy_uploaded: Option<(DocId, u64)>,/// Selection outline cache: (doc, revision, segments).+ /// Live filter preview (proxy document with the filter applied).+ pub(crate) filter_preview: Option<filter_dialog::FilterPreview>,+ /// Synthetic input events queued by automation (`ui.click`, `ui.key`, …), injected next frame.+ pub(crate) synthetic: Vec<egui::Event>,+ /// Levels/Curves histogram cache: (document, adjustment layer, revision it is valid for).+ pub(crate) tone_hist: Option<(DocId, photocraft_doc::LayerId, u64, std::sync::Arc<tone::Histograms>)>,+ /// Histogram panel cache: (document, revision, computed at ms, histograms).+ pub(crate) doc_hist: Option<(DocId, u64, f64, std::sync::Arc<tone::Histograms>)>,+ /// Free Transform preview (document without the moving pixels + their texture).+ pub(crate) transform_preview: Option<transform_tool::TransformPreview>,+ /// Signature of the image we last put on the OS clipboard (to tell ours from other apps').+ os_clip_sig: Option<u64>,+ /// Pointer position over the canvas (document px), for the Info panel and status bar.+ pub(crate) hover_doc: Option<[f64; 2]>,+ /// Info panel sample cache: ((x, y, revision), composite RGBA).+ info_sample: Option<((i32, i32, u64), [f32; 4])>,+ /// Guide being dragged (from a ruler or with the Move tool).+ pub(crate) guide_drag: Option<rulers::GuideDrag>,+ /// Type tool layout cache: ((doc, revision, layer), layout).+ pub(crate) type_layout: Option<((u64, u64, u64), std::sync::Arc<photocraft_text::TextLayout>)>,+ /// Channel thumbnails (composite + per channel) cached per (doc, revision).+ channel_thumbs: Option<(DocId, u64, Vec<egui::TextureHandle>)>,+ /// Selection outline keyed by (document, mask identity × step × visible region).pub(crate) outline_cache: Option<(DocId, u64, std::sync::Arc<Vec<outline::Segment>>)>,/// GPU canvas renderer, when running on the wgpu backend (see [`Self::set_wgpu`]).gpu: Option<gpu_canvas::GpuCanvas>,@@ -103,6 +164,8 @@ impl PhotocraftApp {drag: None,control_rx: None,pending_screenshots: Vec::new(),+ queued_screenshots: Vec::new(),+ input_waiters: Vec::new(),live_adjust: None,frame: 0,styled: false,@@ -116,6 +179,17 @@ impl PhotocraftApp {proxy: None,proxy_uploaded: None,outline_cache: None,+ filter_preview: None,+ synthetic: Vec::new(),+ channel_thumbs: None,+ type_layout: None,+ guide_drag: None,+ hover_doc: None,+ info_sample: None,+ os_clip_sig: None,+ transform_preview: None,+ tone_hist: None,+ doc_hist: None,gpu: None,perf: Default::default(),#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]@@ -137,7 +211,16 @@ impl PhotocraftApp {/// Run an engine command, reporting errors in the status bar.pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {+ let t0 = gpu_canvas::now_ms();+ if matches!(id, "edit.paste" | "edit.pasteSpecial.pasteInPlace") {+ self.import_os_clipboard();+ }let r = self.session.execute(id, params).map_err(|e| e.to_string());+ if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") {+ self.export_os_clipboard();+ }+ self.perf.last_command = id.to_string();+ self.perf.command_ms = gpu_canvas::now_ms() - t0;match &r {Ok(_) => {self.sync_views();@@ -187,7 +270,7 @@ impl PhotocraftApp {None => self.services.pick_save.as_mut().and_then(|f| f(&suggested)).ok_or("cancelled")?,};let export = self.services.export.as_ref().ok_or("no exporter configured")?;- let bytes = export(&st.doc, &path)?;+ let bytes = export(&st.doc, &path, &ExportSettings::default())?;let write = self.services.write.as_mut().ok_or("no writer configured")?;write(&path, &bytes)?;if let Some(st) = self.session.active_mut() {@@ -206,12 +289,31 @@ impl PhotocraftApp {control::Outcome::Done(v) => {let _ = reply.send(v);}- control::Outcome::Screenshot { token, path } => self.pending_screenshots.push((token, path, reply)),+ control::Outcome::AfterInput => self.input_waiters.push(reply),+ control::Outcome::Screenshot { token, path } => {+ // Wait out egui's fade animations (~83 ms) and a few rendered frames first.+ let settle = ctx.global_style().animation_time as f64 * 2000.0 + 60.0;+ self.queued_screenshots.push((token, gpu_canvas::now_ms() + settle, 0));+ self.pending_screenshots.push((token, path, reply));+ }}}self.control_rx = Some(rx);}+ fn issue_screenshots(&mut self, ctx: &egui::Context) {+ let now = gpu_canvas::now_ms();+ self.queued_screenshots.retain_mut(|(token, at, frames)| {+ *frames += 1;+ if now >= *at && *frames >= 3 {+ ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(*token)));+ false+ } else {+ true+ }+ });+ }+fn collect_screenshots(&mut self, ctx: &egui::Context) {if self.pending_screenshots.is_empty() {return;@@ -260,7 +362,20 @@ impl eframe::App for PhotocraftApp {self.checker = None;}self.drain_control(ctx);+ if self.ui.text_edit.is_some() && self.ui.tool != state::Tool::Type {+ type_tool::commit(self);+ }+ if self.ui.pen.is_some() && self.ui.tool != state::Tool::Pen {+ vector_ui::pen_commit(self, false);+ }+ // A transform whose layer or document went away (undo, close) ends silently.+ if let Some(t) = &self.ui.transform+ && self.session.active().and_then(|s| s.doc.layer(photocraft_doc::LayerId(t.layer))).is_none()+ {+ transform_tool::cancel(self);+ }self.collect_screenshots(ctx);+ self.issue_screenshots(ctx);shortcuts::handle(self, ctx);let arrived: Vec<(String, Vec<u8>)> = self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default();for (name, bytes) in arrived {@@ -282,11 +397,17 @@ impl eframe::App for PhotocraftApp {Err(e) => self.ui.status = format!("Couldn't read {name}: {e}"),}}- if self.control_rx.is_some() || !self.pending_screenshots.is_empty() {- ctx.request_repaint_after(std::time::Duration::from_millis(50));+ // The control transport wakes the UI on arrival (ctx.request_repaint); only poll while a+ // screenshot is pending. (Polling every 50 ms here made idle apps render at 20 fps.)+ if !self.pending_screenshots.is_empty() {+ ctx.request_repaint_after(std::time::Duration::from_millis(16));}}+ fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {+ raw_input.events.extend(self.take_synthetic_step());+ }+fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {let ctx = ui.ctx().clone();// Fonts registered via set_fonts only take effect next frame; named families would panic now.@@ -315,6 +436,15 @@ impl eframe::App for PhotocraftApp {dialogs::show(self, &ctx);canvas::extra_windows(self, &ctx);self.perf.frame(gpu_canvas::now_ms() - t0);+ // Synthetic input is injected one press/release step per frame: keep frames coming until+ // the queue is empty, then release control replies waiting on it.+ if !self.synthetic.is_empty() {+ ctx.request_repaint();+ } else if !self.input_waiters.is_empty() {+ for w in self.input_waiters.drain(..) {+ let _ = w.send(serde_json::json!({"ok": true, "result": null}));+ }+ }}}@@ -338,28 +468,37 @@ impl PhotocraftApp {/// Cached 64px thumbnail of a pixel-ish layer, laid out in document space.pub fn layer_thumb(&mut self, ctx: &egui::Context, doc: &Document, layer: &photocraft_doc::Layer) -> egui::TextureId {- let rev = self.session.active().map_or(0, |d| d.revision);+ // Key by content, not document revision: COW tiles change pointer only when their pixels+ // change, so unrelated edits (e.g. painting another layer) don't rebuild this thumbnail.+ let rev = layer.surface().map_or(0, surface_fingerprint) ^ (doc.size.width as u64) << 40;let key = (layer.id, false);if let Some((r, tex)) = self.thumbs.get(&key)&& *r == rev{return tex.id();}- let img = thumb_image(doc, 64, |x, y| layer.surface().map_or([0.0; 4], |s| s.rgba(x, y)));+ let mut px = [0.0f32; 8];+ let img = thumb_image(doc, 64, |x, y| {+ let Some(s) = layer.surface() else { return [0.0; 4] };+ let n = s.channels();+ s.read_pixel(x, y, &mut px[..n]);+ photocraft_raster::to_rgba(&s.format(), &px[..n])+ });self.store_thumb(ctx, key, rev, img)}pub fn mask_thumb(&mut self, ctx: &egui::Context, doc: &Document, id: photocraft_doc::LayerId, mask: &photocraft_doc::LayerMask) -> egui::TextureId {- let rev = self.session.active().map_or(0, |d| d.revision);+ let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40;let key = (id, true);if let Some((r, tex)) = self.thumbs.get(&key)&& *r == rev{return tex.id();}+ let mut v = [0.0f32; 1];let img = thumb_image(doc, 64, |x, y| {- let v = mask.surface.pixel(x, y)[0];- [v, v, v, 1.0]+ mask.surface.read_pixel(x, y, &mut v);+ [v[0], v[0], v[0], 1.0]});self.store_thumb(ctx, key, rev, img)}@@ -381,8 +520,18 @@ impl PhotocraftApp {}}+/// Cheap identity of a surface's pixels: tile coordinates and `Arc` pointers.+pub fn surface_fingerprint(s: &photocraft_raster::Surface) -> u64 {+ let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ s.tile_count() as u64;+ for (c, t) in s.tiles() {+ let p = std::sync::Arc::as_ptr(t) as usize as u64;+ h = (h ^ p ^ ((c.tx as u64) << 32 | c.ty as u32 as u64)).wrapping_mul(0x100_0000_01b3);+ }+ h+}+/// Square thumbnail of the canvas area, letterboxed, sampling `f(x, y)` in document space.-fn thumb_image(doc: &Document, side: usize, f: impl Fn(i32, i32) -> [f32; 4]) -> egui::ColorImage {+fn thumb_image(doc: &Document, side: usize, mut f: impl FnMut(i32, i32) -> [f32; 4]) -> egui::ColorImage {let (w, h) = (doc.size.width.max(1) as f32, doc.size.height.max(1) as f32);let scale = w.max(h) / side as f32;let (ox, oy) = ((side as f32 - w / scale) / 2.0, (side as f32 - h / scale) / 2.0);@@ -403,6 +552,14 @@ fn thumb_image(doc: &Document, side: usize, f: impl Fn(i32, i32) -> [f32; 4]) ->}impl PhotocraftApp {+ /// Next step of queued synthetic input (automation): events up to and including the first+ /// release, so egui sees press and release in separate frames. Hosts that don't call+ /// `raw_input_hook` (offscreen harnesses) feed these to their input themselves.+ pub fn take_synthetic_step(&mut self) -> Vec<egui::Event> {+ let n = self.synthetic.iter().position(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. } | egui::Event::Key { pressed: false, .. })).map_or(self.synthetic.len(), |i| i + 1);+ self.synthetic.drain(..n).collect()+ }+/// Install fonts, image loaders and the theme. Call from the app creator when possible so the/// very first frame renders; otherwise `logic` does it and the first frame is skipped.pub fn setup_context(ctx: &egui::Context, kind: theme::ThemeKind) {@@ -413,9 +570,9 @@ impl PhotocraftApp {}impl PhotocraftApp {- /// Cached `Surface::content_bounds` keyed by an id and the active document revision.+ /// Cached `Surface::content_bounds` keyed by an id and the surface's tile identity.pub fn cached_bounds(&mut self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect {- let rev = self.session.active().map_or(0, |d| d.revision);+ let rev = surface_fingerprint(surface);if let Some((r, b)) = self.bounds_cache.get(&key)&& *r == rev{@@ -429,3 +586,124 @@ impl PhotocraftApp {b}}++impl PhotocraftApp {+ /// Zoom of the active document's main view (screen points per document pixel).+ pub fn current_zoom(&self) -> f32 {+ self.session.active_index().and_then(|i| self.ui.views.get(i)).map_or(1.0, |v| v.zoom)+ }+}++impl PhotocraftApp {+ /// Composite + per-channel grayscale thumbnails of the active document (cached per revision).+ pub fn channel_thumbs(&mut self, ctx: &egui::Context) -> Vec<egui::TextureId> {+ let Some(st) = self.session.active() else { return Vec::new() };+ let (id, rev, doc) = (st.doc.id, st.revision, st.doc.clone());+ if !matches!(&self.channel_thumbs, Some((d, r, _)) if *d == id && *r == rev) {+ let comp = photocraft_compose::thumbnail(&doc, 56);+ let (w, h) = (comp.width as usize, comp.height as usize);+ let side = w.max(h);+ let make = |f: &dyn Fn(&[u8]) -> egui::Color32, name: &str| {+ let mut px = vec![egui::Color32::TRANSPARENT; side * side];+ let (ox, oy) = ((side - w) / 2, (side - h) / 2);+ for y in 0..h {+ for x in 0..w {+ let o = (y * w + x) * 4;+ px[(y + oy) * side + x + ox] = f(&comp.pixels[o..o + 4]);+ }+ }+ ctx.load_texture(format!("chan-{name}"), egui::ColorImage::new([side, side], px), egui::TextureOptions::LINEAR)+ };+ let texs = vec![+ make(&|p| egui::Color32::from_rgb(p[0], p[1], p[2]), "rgb"),+ make(&|p| egui::Color32::from_gray(p[0]), "r"),+ make(&|p| egui::Color32::from_gray(p[1]), "g"),+ make(&|p| egui::Color32::from_gray(p[2]), "b"),+ ];+ self.channel_thumbs = Some((id, rev, texs));+ }+ self.channel_thumbs.as_ref().map(|(_, _, t)| t.iter().map(|t| t.id()).collect()).unwrap_or_default()+ }+}++fn clip_signature(w: u32, h: u32, px: &[u8]) -> u64 {+ let mut sig = (w as u64) << 32 | h as u64;+ for b in px.iter().step_by(997) {+ sig = sig.rotate_left(5) ^ *b as u64;+ }+ sig+}++impl PhotocraftApp {+ /// Mirror the session clipboard onto the OS clipboard (RGBA8).+ fn export_os_clipboard(&mut self) {+ let (Some(set), Some(clip)) = (self.services.clipboard_set_image.as_mut(), self.session.clipboard.as_ref()) else { return };+ let b = clip.bounds;+ if b.is_empty() {+ return;+ }+ let mut px = vec![[0u8; 4]; b.width() as usize * b.height() as usize];+ clip.surface.read_rgba8_into(b, &mut px);+ let bytes: Vec<u8> = px.into_iter().flatten().collect();+ if set(b.width(), b.height(), &bytes).is_ok() {+ self.os_clip_sig = Some(clip_signature(b.width(), b.height(), &bytes));+ }+ }++ /// If the OS clipboard holds an image that isn't the one we put there, make it the session+ /// clipboard (so ⌘V pastes screenshots and images copied in other apps, like Photoshop).+ /// Returns true when a new external image was imported.+ pub(crate) fn import_os_clipboard(&mut self) -> bool {+ let Some(get) = self.services.clipboard_get_image.as_mut() else { return false };+ let Some((w, h, bytes)) = get() else { return false };+ if w == 0 || h == 0 || bytes.len() != w as usize * h as usize * 4 {+ return false;+ }+ let sig = clip_signature(w, h, &bytes);+ if self.os_clip_sig == Some(sig) && self.session.clipboard.is_some() {+ return false;+ }+ let r = photocraft_geom::Rect::new(0, 0, w as i32, h as i32);+ let mut surface = photocraft_raster::Surface::from_interleaved(photocraft_color::PixelFormat::RGBA8, r, &bytes);+ surface.prune();+ self.session.clipboard = Some(photocraft_engine::edit_cmds::Clip { surface, bounds: r });+ self.os_clip_sig = Some(sig);+ true+ }+}++#[cfg(test)]+mod clipboard_tests {+ use super::*;+ use std::sync::{Arc, Mutex};++ #[test]+ fn os_clipboard_bridge() {+ type OsClip = Arc<Mutex<Option<(u32, u32, Vec<u8>)>>>;+ let os: OsClip = Arc::default();+ let (a, b) = (os.clone(), os.clone());+ let services = Services {+ clipboard_set_image: Some(Box::new(move |w: u32, h: u32, px: &[u8]| {+ *a.lock().unwrap() = Some((w, h, px.to_vec()));+ Ok(())+ })),+ clipboard_get_image: Some(Box::new(move || b.lock().unwrap().clone())),+ ..Default::default()+ };+ let mut app = PhotocraftApp::new(Session::new(), services);+ app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap();+ app.sync_views();+ app.run("select.rect", serde_json::json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap();+ app.run("edit.copy", serde_json::json!({})).unwrap();+ let (w, h, px) = os.lock().unwrap().clone().unwrap();+ assert_eq!((w, h, px.len()), (8, 4, 8 * 4 * 4));+ // Our own image comes back unchanged (no re-import, keeps the original position).+ assert!(!app.import_os_clipboard());+ // Another app puts a 3×2 red image on the clipboard: ⌘V pastes it.+ *os.lock().unwrap() = Some((3, 2, [255u8, 0, 0, 255].repeat(6)));+ app.run("edit.paste", serde_json::json!({})).unwrap();+ let st = app.session.active().unwrap();+ let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();+ assert_eq!(surf.content_bounds().width(), 3);+ }+}diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rsnew file mode 100644index 000000000..218eec3a0--- /dev/null+++ b/crates/ui-egui/src/menu_catalog.rs@@ -0,0 +1,770 @@+//! Photoshop menu structure (standard public command names) used to present the full, familiar+//! menu tree, in order, with separators ("---"). Items whose id matches an engine or UI command are+//! live; others render disabled until implemented. Generated from the recorded menu structure.++/// (menu path, label or "---", default shortcut, command id)+pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[+ (&["File"], "New…", Some("Cmd+N"), "file.new"),+ (&["File"], "Open…", Some("Cmd+O"), "file.open"),+ (&["File"], "Open As…", Some("Cmd+Alt+Shift+O"), "file.openAs"),+ (&["File"], "---", None, "---"),+ (&["File"], "Close", Some("Cmd+W"), "file.close"),+ (&["File"], "Close All", Some("Cmd+Alt+W"), "file.closeAll"),+ (&["File"], "Close Others", Some("Cmd+Alt+P"), "file.closeOthers"),+ (&["File"], "---", None, "---"),+ (&["File"], "Save", Some("Cmd+S"), "file.save"),+ (&["File"], "Save As…", Some("Cmd+Shift+S"), "file.saveAs"),+ (&["File"], "Save a Copy…", Some("Cmd+Alt+S"), "file.saveACopy"),+ (&["File"], "Revert", Some("F12"), "file.revert"),+ (&["File"], "---", None, "---"),+ (&["File", "Export"], "Quick Export as PNG", None, "file.export.quickExportAsPng"),+ (&["File", "Export"], "Export As…", Some("Cmd+Alt+Shift+W"), "file.export.exportAs"),+ (&["File", "Export"], "Export Preferences…", None, "file.export.exportPreferences"),+ (&["File", "Export"], "---", None, "---"),+ (&["File", "Export"], "Save for Web (Legacy)…", Some("Cmd+Alt+Shift+S"), "file.export.saveForWebLegacy"),+ (&["File", "Export"], "---", None, "---"),+ (&["File", "Export"], "Artboards to Files…", None, "file.export.artboardsToFiles"),+ (&["File", "Export"], "Artboards to PDF…", None, "file.export.artboardsToPdf"),+ (&["File", "Export"], "Layers to Files…", None, "file.export.layersToFiles"),+ (&["File", "Export"], "Layer Comps to Files…", None, "file.export.layerCompsToFiles"),+ (&["File", "Export"], "---", None, "---"),+ (&["File", "Export"], "Color Lookup Tables…", None, "file.export.colorLookupTables"),+ (&["File", "Export"], "Data Sets as Files…", None, "file.export.dataSetsAsFiles"),+ (&["File", "Export"], "Paths to Illustrator…", None, "file.export.pathsToIllustrator"),+ (&["File", "Export"], "Render Video…", None, "file.export.renderVideo"),+ (&["File", "Generate"], "Image Assets", None, "file.generate.imageAssets"),+ (&["File"], "---", None, "---"),+ (&["File"], "Place Embedded…", None, "file.placeEmbedded"),+ (&["File"], "Place Linked…", None, "file.placeLinked"),+ (&["File"], "---", None, "---"),+ (&["File"], "Package…", None, "file.package"),+ (&["File"], "---", None, "---"),+ (&["File", "Automate"], "Batch…", None, "file.automate.batch"),+ (&["File", "Automate"], "Create Droplet…", None, "file.automate.createDroplet"),+ (&["File", "Automate"], "---", None, "---"),+ (&["File", "Automate"], "Crop and Straighten Photos", None, "file.automate.cropAndStraightenPhotos"),+ (&["File", "Automate"], "Contact Sheet II…", None, "file.automate.contactSheetII"),+ (&["File", "Automate"], "Conditional Mode Change…", None, "file.automate.conditionalModeChange"),+ (&["File", "Automate"], "Fit Image…", None, "file.automate.fitImage"),+ (&["File", "Automate"], "Lens Correction…", None, "file.automate.lensCorrection"),+ (&["File", "Automate"], "---", None, "---"),+ (&["File", "Automate"], "Merge to HDR Pro…", None, "file.automate.mergeToHdrPro"),+ (&["File", "Automate"], "Photomerge…", None, "file.automate.photomerge"),+ (&["File", "Scripts"], "Image Processor…", None, "file.scripts.imageProcessor"),+ (&["File", "Scripts"], "---", None, "---"),+ (&["File", "Scripts"], "Delete All Empty Layers", None, "file.scripts.deleteAllEmptyLayers"),+ (&["File", "Scripts"], "Flatten All Layer Effects", None, "file.scripts.flattenAllLayerEffects"),+ (&["File", "Scripts"], "Flatten All Masks", None, "file.scripts.flattenAllMasks"),+ (&["File", "Scripts"], "---", None, "---"),+ (&["File", "Scripts"], "Script Events Manager…", None, "file.scripts.scriptEventsManager"),+ (&["File", "Scripts"], "---", None, "---"),+ (&["File", "Scripts"], "Load Files into Stack…", None, "file.scripts.loadFilesIntoStack"),+ (&["File", "Scripts"], "Statistics…", None, "file.scripts.statistics"),+ (&["File", "Scripts"], "---", None, "---"),+ (&["File", "Scripts"], "Browse…", None, "file.scripts.browse"),+ (&["File", "Import"], "Variable Data Sets…", None, "file.import.variableDataSets"),+ (&["File", "Import"], "Video Frames to Layers…", None, "file.import.videoFramesToLayers"),+ (&["File", "Import"], "Notes…", None, "file.import.notes"),+ (&["File", "Import"], "WIA Support…", None, "file.import.wiaSupport"),+ (&["File"], "---", None, "---"),+ (&["File"], "File Info…", Some("Cmd+Alt+Shift+I"), "file.fileInfo"),+ (&["File"], "---", None, "---"),+ (&["File"], "Print…", Some("Cmd+P"), "file.print"),+ (&["File"], "Print One Copy", Some("Cmd+Alt+Shift+P"), "file.printOneCopy"),+ (&["Edit"], "Undo", None, "edit.undo"),+ (&["Edit"], "Redo", None, "edit.redo"),+ (&["Edit"], "Toggle Last State", Some("Cmd+Alt+Z"), "edit.toggleLastState"),+ (&["Edit"], "Fade…", Some("Cmd+Shift+F"), "edit.fade"),+ (&["Edit"], "---", None, "---"),+ (&["Edit"], "Cut", None, "edit.cut"),+ (&["Edit"], "Copy", None, "edit.copy"),+ (&["Edit"], "Copy Merged", Some("Cmd+Shift+C"), "edit.copyMerged"),+ (&["Edit"], "Paste", None, "edit.paste"),+ (&["Edit", "Paste Special"], "Paste in Place", Some("Cmd+Shift+V"), "edit.pasteSpecial.pasteInPlace"),+ (&["Edit", "Paste Special"], "Paste Into", Some("Cmd+Alt+Shift+V"), "edit.pasteSpecial.pasteInto"),+ (&["Edit", "Paste Special"], "Paste Outside", None, "edit.pasteSpecial.pasteOutside"),+ (&["Edit"], "Clear", None, "edit.clear"),+ (&["Edit"], "---", None, "---"),+ (&["Edit"], "Search…", Some("Cmd+K"), "edit.search"),+ (&["Edit"], "---", None, "---"),+ (&["Edit"], "Check Spelling…", None, "edit.checkSpelling"),+ (&["Edit"], "Find and Replace Text…", None, "edit.findAndReplaceText"),+ (&["Edit"], "---", None, "---"),+ (&["Edit"], "Fill…", Some("Shift+F5"), "edit.fill"),+ (&["Edit"], "Stroke…", None, "edit.stroke"),+ (&["Edit"], "Content-Aware Fill…", None, "edit.contentAwareFill"),+ (&["Edit"], "---", None, "---"),+ (&["Edit"], "Content-Aware Scale", Some("Cmd+Alt+Shift+C"), "edit.contentAwareScale"),+ (&["Edit"], "Puppet Warp", None, "edit.puppetWarp"),+ (&["Edit"], "Perspective Warp", None, "edit.perspectiveWarp"),+ (&["Edit"], "Free Transform", Some("Cmd+T"), "edit.freeTransform"),+ (&["Edit", "Transform"], "Again", Some("Cmd+Shift+T"), "edit.transform.again"),+ (&["Edit", "Transform"], "---", None, "---"),+ (&["Edit", "Transform"], "Scale", None, "edit.transform.scale"),+ (&["Edit", "Transform"], "Rotate", None, "edit.transform.rotate"),+ (&["Edit", "Transform"], "Skew", None, "edit.transform.skew"),+ (&["Edit", "Transform"], "Distort", None, "edit.transform.distort"),+ (&["Edit", "Transform"], "Perspective", None, "edit.transform.perspective"),+ (&["Edit", "Transform"], "Warp", None, "edit.transform.warp"),+ (&["Edit", "Transform"], "---", None, "---"),+ (&["Edit", "Transform"], "Split Warp Horizontally", None, "edit.transform.splitWarpHorizontally"),+ (&["Edit", "Transform"], "Split Warp Vertically", None, "edit.transform.splitWarpVertically"),+ (&["Edit", "Transform"], "Split Warp Crosswise", None, "edit.transform.splitWarpCrosswise"),+ (&["Edit", "Transform"], "Remove Warp Split", None, "edit.transform.removeWarpSplit"),+ (&["Edit", "Transform"], "---", None, "---"),+ (&["Edit", "Transform"], "Rotate 180°", None, "edit.transform.rotate180"),+ (&["Edit", "Transform"], "Rotate 90° Clockwise", None, "edit.transform.rotate90Cw"),+ (&["Edit", "Transform"], "Rotate 90° Counter Clockwise", None, "edit.transform.rotate90Ccw"),+ (&["Edit", "Transform"], "---", None, "---"),+ (&["Edit", "Transform"], "Flip Horizontal", None, "edit.transform.flipHorizontal"),+ (&["Edit", "Transform"], "Flip Vertical", None, "edit.transform.flipVertical"),+ (&["Edit"], "Auto-Align Layers…", None, "edit.autoAlignLayers"),+ (&["Edit"], "Auto-Blend Layers…", None, "edit.autoBlendLayers"),+ (&["Edit"], "---", None, "---"),+ (&["Edit"], "Define Brush Preset…", None, "edit.defineBrushPreset"),+ (&["Edit"], "Define Pattern…", None, "edit.definePattern"),+ (&["Edit"], "Define Custom Shape…", None, "edit.defineCustomShape"),+ (&["Edit"], "---", None, "---"),+ (&["Edit", "Purge"], "Undo", None, "edit.purge.undo"),+ (&["Edit", "Purge"], "Clipboard", None, "edit.purge.clipboard"),+ (&["Edit", "Purge"], "Histories", None, "edit.purge.histories"),+ (&["Edit", "Purge"], "Video Cache", None, "edit.purge.videoCache"),+ (&["Edit", "Purge"], "---", None, "---"),+ (&["Edit", "Purge"], "All", None, "edit.purge.all"),+ (&["Edit"], "---", None, "---"),+ (&["Edit", "Presets"], "Preset Manager…", None, "edit.presets.presetManager"),+ (&["Edit", "Presets"], "---", None, "---"),+ (&["Edit", "Presets"], "Migrate Presets", None, "edit.presets.migratePresets"),+ (&["Edit", "Presets"], "Export/Import Presets…", None, "edit.presets.exportImportPresets"),+ (&["Edit"], "---", None, "---"),+ (&["Edit"], "Color Settings…", Some("Cmd+Shift+K"), "edit.colorSettings"),+ (&["Edit"], "Assign Profile…", None, "edit.assignProfile"),+ (&["Edit"], "Convert to Profile…", None, "edit.convertToProfile"),+ (&["Edit"], "---", None, "---"),+ (&["Edit"], "Keyboard Shortcuts…", Some("Cmd+Alt+Shift+K"), "edit.keyboardShortcuts"),+ (&["Edit"], "Menus…", Some("Cmd+Alt+Shift+M"), "edit.menus"),+ (&["Edit"], "Toolbar…", None, "edit.toolbar"),+ (&["Edit"], "---", None, "---"),+ (&["Edit", "Preferences"], "Settings…", None, "edit.preferences.general"),+ (&["Edit", "Preferences"], "AI Integrations…", None, "edit.preferences.integrations"),+ (&["Edit", "Preferences"], "Interface…", None, "edit.preferences.interface"),+ (&["Edit", "Preferences"], "Workspace…", None, "edit.preferences.workspace"),+ (&["Edit", "Preferences"], "Tools…", None, "edit.preferences.tools"),+ (&["Edit", "Preferences"], "History Log…", None, "edit.preferences.historyLog"),+ (&["Edit", "Preferences"], "File Handling…", None, "edit.preferences.fileHandling"),+ (&["Edit", "Preferences"], "Export…", None, "edit.preferences.export"),+ (&["Edit", "Preferences"], "Performance…", None, "edit.preferences.performance"),+ (&["Edit", "Preferences"], "Scratch Disks…", None, "edit.preferences.scratchDisks"),+ (&["Edit", "Preferences"], "Cursors…", None, "edit.preferences.cursors"),+ (&["Edit", "Preferences"], "Transparency & Gamut…", None, "edit.preferences.transparencyAndGamut"),+ (&["Edit", "Preferences"], "Units & Rulers…", None, "edit.preferences.unitsAndRulers"),+ (&["Edit", "Preferences"], "Guides, Grid & Slices…", None, "edit.preferences.guidesGridAndSlices"),+ (&["Edit", "Preferences"], "Plug-ins…", None, "edit.preferences.plugIns"),+ (&["Edit", "Preferences"], "Type…", None, "edit.preferences.type"),+ (&["Edit", "Preferences"], "Enhanced Controls…", None, "edit.preferences.enhancedControls"),+ (&["Edit", "Preferences"], "Raw Defaults…", None, "edit.preferences.rawDefaults"),+ (&["Image", "Mode"], "Bitmap", None, "image.mode.bitmap"),+ (&["Image", "Mode"], "Grayscale", None, "image.mode.grayscale"),+ (&["Image", "Mode"], "Duotone", None, "image.mode.duotone"),+ (&["Image", "Mode"], "Indexed Color", None, "image.mode.indexedColor"),+ (&["Image", "Mode"], "RGB Color", None, "image.mode.rgb"),+ (&["Image", "Mode"], "CMYK Color", None, "image.mode.cmyk"),+ (&["Image", "Mode"], "Lab Color", None, "image.mode.lab"),+ (&["Image", "Mode"], "Multichannel", None, "image.mode.multichannel"),+ (&["Image", "Mode"], "---", None, "---"),+ (&["Image", "Mode"], "8 Bits/Channel", None, "image.mode.bits8"),+ (&["Image", "Mode"], "16 Bits/Channel", None, "image.mode.bits16"),+ (&["Image", "Mode"], "32 Bits/Channel", None, "image.mode.bits32"),+ (&["Image", "Mode"], "---", None, "---"),+ (&["Image", "Mode"], "Color Table…", None, "image.mode.colorTable"),+ (&["Image"], "---", None, "---"),+ (&["Image", "Adjustments"], "Brightness/Contrast…", None, "image.adjustments.brightnessContrast"),+ (&["Image", "Adjustments"], "Levels…", Some("Cmd+L"), "image.adjustments.levels"),+ (&["Image", "Adjustments"], "Curves…", Some("Cmd+M"), "image.adjustments.curves"),+ (&["Image", "Adjustments"], "Exposure…", None, "image.adjustments.exposure"),+ (&["Image", "Adjustments"], "Vibrance…", None, "image.adjustments.vibrance"),+ (&["Image", "Adjustments"], "Hue/Saturation…", Some("Cmd+U"), "image.adjustments.hueSaturation"),+ (&["Image", "Adjustments"], "Color Balance…", Some("Cmd+B"), "image.adjustments.colorBalance"),+ (&["Image", "Adjustments"], "Black & White…", Some("Cmd+Alt+Shift+B"), "image.adjustments.blackAndWhite"),+ (&["Image", "Adjustments"], "Photo Filter…", None, "image.adjustments.photoFilter"),+ (&["Image", "Adjustments"], "Channel Mixer…", None, "image.adjustments.channelMixer"),+ (&["Image", "Adjustments"], "Color Lookup…", None, "image.adjustments.colorLookup"),+ (&["Image", "Adjustments"], "---", None, "---"),+ (&["Image", "Adjustments"], "Invert", Some("Cmd+I"), "image.adjustments.invert"),+ (&["Image", "Adjustments"], "Posterize…", None, "image.adjustments.posterize"),+ (&["Image", "Adjustments"], "Threshold…", None, "image.adjustments.threshold"),+ (&["Image", "Adjustments"], "Gradient Map…", None, "image.adjustments.gradientMap"),+ (&["Image", "Adjustments"], "Selective Color…", None, "image.adjustments.selectiveColor"),+ (&["Image", "Adjustments"], "---", None, "---"),+ (&["Image", "Adjustments"], "Shadows/Highlights…", None, "image.adjustments.shadowsHighlights"),+ (&["Image", "Adjustments"], "HDR Toning…", None, "image.adjustments.hdrToning"),+ (&["Image", "Adjustments"], "---", None, "---"),+ (&["Image", "Adjustments"], "Desaturate", Some("Cmd+Shift+U"), "image.adjustments.desaturate"),+ (&["Image", "Adjustments"], "Match Color…", None, "image.adjustments.matchColor"),+ (&["Image", "Adjustments"], "Replace Color…", None, "image.adjustments.replaceColor"),+ (&["Image", "Adjustments"], "Equalize", None, "image.adjustments.equalize"),+ (&["Image"], "---", None, "---"),+ (&["Image"], "Auto Tone", Some("Cmd+Shift+L"), "image.autoTone"),+ (&["Image"], "Auto Contrast", Some("Cmd+Alt+Shift+L"), "image.autoContrast"),+ (&["Image"], "Auto Color", Some("Cmd+Shift+B"), "image.autoColor"),+ (&["Image"], "---", None, "---"),+ (&["Image"], "Image Size…", Some("Cmd+Alt+I"), "image.imageSize"),+ (&["Image"], "Canvas Size…", Some("Cmd+Alt+C"), "image.canvasSize"),+ (&["Image", "Image Rotation"], "180°", None, "image.rotation.rotate180"),+ (&["Image", "Image Rotation"], "90° Clockwise", None, "image.rotation.rotate90Cw"),+ (&["Image", "Image Rotation"], "90° Counter Clockwise", None, "image.rotation.rotate90Ccw"),+ (&["Image", "Image Rotation"], "Arbitrary…", None, "image.rotation.arbitrary"),+ (&["Image", "Image Rotation"], "---", None, "---"),+ (&["Image", "Image Rotation"], "Flip Canvas Horizontal", None, "image.rotation.flipCanvasHorizontal"),+ (&["Image", "Image Rotation"], "Flip Canvas Vertical", None, "image.rotation.flipCanvasVertical"),+ (&["Image"], "Crop", None, "image.crop"),+ (&["Image"], "Trim…", None, "image.trim"),+ (&["Image"], "Reveal All", None, "image.revealAll"),+ (&["Image"], "---", None, "---"),+ (&["Image"], "Duplicate…", None, "image.duplicate"),+ (&["Image"], "Apply Image…", None, "image.applyImage"),+ (&["Image"], "Calculations…", None, "image.calculations"),+ (&["Image"], "---", None, "---"),+ (&["Image", "Variables"], "Define…", None, "image.variables.define"),+ (&["Image", "Variables"], "Data Sets…", None, "image.variables.dataSets"),+ (&["Image"], "Apply Data Set…", None, "image.applyDataSet"),+ (&["Image"], "---", None, "---"),+ (&["Image"], "Trap…", None, "image.trap"),+ (&["Image"], "---", None, "---"),+ (&["Image", "Analysis"], "Set Measurement Scale…", None, "image.analysis.setMeasurementScale"),+ (&["Image", "Analysis"], "Select Data Points…", None, "image.analysis.selectDataPoints"),+ (&["Image", "Analysis"], "---", None, "---"),+ (&["Image", "Analysis"], "Record Measurements", None, "image.analysis.recordMeasurements"),+ (&["Image", "Analysis"], "---", None, "---"),+ (&["Image", "Analysis"], "Ruler Tool", None, "image.analysis.rulerTool"),+ (&["Image", "Analysis"], "Count Tool", None, "image.analysis.countTool"),+ (&["Image", "Analysis"], "---", None, "---"),+ (&["Image", "Analysis"], "Place Scale Marker…", None, "image.analysis.placeScaleMarker"),+ (&["Layer", "New"], "Layer…", Some("Cmd+Shift+N"), "layer.new.layer"),+ (&["Layer", "New"], "Layer from Background…", None, "layer.new.layerFromBackground"),+ (&["Layer", "New"], "Group…", None, "layer.new.group"),+ (&["Layer", "New"], "Group from Layers…", None, "layer.new.groupFromLayers"),+ (&["Layer", "New"], "---", None, "---"),+ (&["Layer", "New"], "Artboard…", None, "layer.new.artboard"),+ (&["Layer", "New"], "Artboard from Group…", None, "layer.new.artboardFromGroup"),+ (&["Layer", "New"], "Artboard from Layers…", None, "layer.new.artboardFromLayers"),+ (&["Layer", "New"], "Frame from Layers", None, "layer.new.frameFromLayers"),+ (&["Layer", "New"], "---", None, "---"),+ (&["Layer", "New"], "Layer via Copy", Some("Cmd+J"), "layer.new.layerViaCopy"),+ (&["Layer", "New"], "Layer via Cut", Some("Cmd+Shift+J"), "layer.new.layerViaCut"),+ (&["Layer"], "Duplicate Layer…", None, "layer.duplicateLayer"),+ (&["Layer", "Delete"], "Layer", None, "layer.delete.layer"),+ (&["Layer", "Delete"], "Hidden Layers", None, "layer.delete.hiddenLayers"),+ (&["Layer"], "---", None, "---"),+ (&["Layer"], "Quick Export as PNG", Some("Cmd+Shift+'"), "layer.quickExportAsPng"),+ (&["Layer"], "Export As…", Some("Cmd+Alt+Shift+'"), "layer.exportAs"),+ (&["Layer"], "---", None, "---"),+ (&["Layer"], "Rename Layer", None, "layer.renameLayer"),+ (&["Layer", "Layer Style"], "Blending Options…", None, "layer.layerStyle.blendingOptions"),+ (&["Layer", "Layer Style"], "Bevel & Emboss…", None, "layer.layerStyle.bevelAndEmboss"),+ (&["Layer", "Layer Style"], "Stroke…", None, "layer.layerStyle.stroke"),+ (&["Layer", "Layer Style"], "Inner Shadow…", None, "layer.layerStyle.innerShadow"),+ (&["Layer", "Layer Style"], "Inner Glow…", None, "layer.layerStyle.innerGlow"),+ (&["Layer", "Layer Style"], "Satin…", None, "layer.layerStyle.satin"),+ (&["Layer", "Layer Style"], "Color Overlay…", None, "layer.layerStyle.colorOverlay"),+ (&["Layer", "Layer Style"], "Gradient Overlay…", None, "layer.layerStyle.gradientOverlay"),+ (&["Layer", "Layer Style"], "Pattern Overlay…", None, "layer.layerStyle.patternOverlay"),+ (&["Layer", "Layer Style"], "Outer Glow…", None, "layer.layerStyle.outerGlow"),+ (&["Layer", "Layer Style"], "Drop Shadow…", None, "layer.layerStyle.dropShadow"),+ (&["Layer", "Layer Style"], "---", None, "---"),+ (&["Layer", "Layer Style"], "Copy Layer Style", None, "layer.layerStyle.copyLayerStyle"),+ (&["Layer", "Layer Style"], "Paste Layer Style", None, "layer.layerStyle.pasteLayerStyle"),+ (&["Layer", "Layer Style"], "Clear Layer Style", None, "layer.layerStyle.clear"),+ (&["Layer", "Layer Style"], "---", None, "---"),+ (&["Layer", "Layer Style"], "Global Light…", None, "layer.layerStyle.globalLight"),+ (&["Layer", "Layer Style"], "Create Layer", None, "layer.layerStyle.createLayer"),+ (&["Layer", "Layer Style"], "Hide All Effects", None, "layer.layerStyle.hideAllEffects"),+ (&["Layer", "Layer Style"], "Scale Effects…", None, "layer.layerStyle.scaleEffects"),+ (&["Layer", "Smart Filter"], "Disable Smart Filters", None, "layer.smartFilter.disableSmartFilters"),+ (&["Layer", "Smart Filter"], "---", None, "---"),+ (&["Layer", "Smart Filter"], "Delete Filter Mask", None, "layer.smartFilter.deleteFilterMask"),+ (&["Layer", "Smart Filter"], "Disable Filter Mask", None, "layer.smartFilter.disableFilterMask"),+ (&["Layer", "Smart Filter"], "Blending Options…", None, "layer.smartFilter.blendingOptions"),+ (&["Layer", "Smart Filter"], "---", None, "---"),+ (&["Layer", "Smart Filter"], "Clear Smart Filters", None, "layer.smartFilter.clearSmartFilters"),+ (&["Layer"], "---", None, "---"),+ (&["Layer", "New Fill Layer"], "Solid Color…", None, "layer.newFillLayer.solidColor"),+ (&["Layer", "New Fill Layer"], "Gradient…", None, "layer.newFillLayer.gradient"),+ (&["Layer", "New Fill Layer"], "Pattern…", None, "layer.newFillLayer.pattern"),+ (&["Layer", "New Adjustment Layer"], "Brightness/Contrast…", None, "layer.newAdjustmentLayer.brightnessContrast"),+ (&["Layer", "New Adjustment Layer"], "Levels…", None, "layer.newAdjustmentLayer.levels"),+ (&["Layer", "New Adjustment Layer"], "Curves…", None, "layer.newAdjustmentLayer.curves"),+ (&["Layer", "New Adjustment Layer"], "Exposure…", None, "layer.newAdjustmentLayer.exposure"),+ (&["Layer", "New Adjustment Layer"], "Vibrance…", None, "layer.newAdjustmentLayer.vibrance"),+ (&["Layer", "New Adjustment Layer"], "Hue/Saturation…", None, "layer.newAdjustmentLayer.hueSaturation"),+ (&["Layer", "New Adjustment Layer"], "Color Balance…", None, "layer.newAdjustmentLayer.colorBalance"),+ (&["Layer", "New Adjustment Layer"], "Black & White…", None, "layer.newAdjustmentLayer.blackAndWhite"),+ (&["Layer", "New Adjustment Layer"], "Photo Filter…", None, "layer.newAdjustmentLayer.photoFilter"),+ (&["Layer", "New Adjustment Layer"], "Channel Mixer…", None, "layer.newAdjustmentLayer.channelMixer"),+ (&["Layer", "New Adjustment Layer"], "Color Lookup…", None, "layer.newAdjustmentLayer.colorLookup"),+ (&["Layer", "New Adjustment Layer"], "---", None, "---"),+ (&["Layer", "New Adjustment Layer"], "Invert…", None, "layer.newAdjustmentLayer.invert"),+ (&["Layer", "New Adjustment Layer"], "Posterize…", None, "layer.newAdjustmentLayer.posterize"),+ (&["Layer", "New Adjustment Layer"], "Threshold…", None, "layer.newAdjustmentLayer.threshold"),+ (&["Layer", "New Adjustment Layer"], "Gradient Map…", None, "layer.newAdjustmentLayer.gradientMap"),+ (&["Layer", "New Adjustment Layer"], "Selective Color…", None, "layer.newAdjustmentLayer.selectiveColor"),+ (&["Layer"], "Layer Content Options…", None, "layer.layerContentOptions"),+ (&["Layer"], "---", None, "---"),+ (&["Layer", "Layer Mask"], "Reveal All", None, "layer.layerMask.revealAll"),+ (&["Layer", "Layer Mask"], "Hide All", None, "layer.layerMask.hideAll"),+ (&["Layer", "Layer Mask"], "---", None, "---"),+ (&["Layer", "Layer Mask"], "Reveal Selection", None, "layer.layerMask.revealSelection"),+ (&["Layer", "Layer Mask"], "Hide Selection", None, "layer.layerMask.hideSelection"),+ (&["Layer", "Layer Mask"], "From Transparency", None, "layer.layerMask.fromTransparency"),+ (&["Layer", "Layer Mask"], "---", None, "---"),+ (&["Layer", "Layer Mask"], "Delete", None, "layer.layerMask.delete"),+ (&["Layer", "Layer Mask"], "Apply", None, "layer.layerMask.apply"),+ (&["Layer", "Layer Mask"], "---", None, "---"),+ (&["Layer", "Layer Mask"], "Enable Layer Mask", None, "layer.layerMask.enabled"),+ (&["Layer", "Layer Mask"], "Link Layer Mask", None, "layer.layerMask.linked"),+ (&["Layer"], "Mask All Objects", None, "layer.maskAllObjects"),+ (&["Layer", "Vector Mask"], "Reveal All", None, "layer.vectorMask.revealAll"),+ (&["Layer", "Vector Mask"], "Hide All", None, "layer.vectorMask.hideAll"),+ (&["Layer", "Vector Mask"], "Current Path", None, "layer.vectorMask.currentPath"),+ (&["Layer", "Vector Mask"], "---", None, "---"),+ (&["Layer", "Vector Mask"], "Delete", None, "layer.vectorMask.delete"),+ (&["Layer", "Vector Mask"], "---", None, "---"),+ (&["Layer", "Vector Mask"], "Enable Vector Mask", None, "layer.vectorMask.enabled"),+ (&["Layer", "Vector Mask"], "Link Vector Mask", None, "layer.vectorMask.linked"),+ (&["Layer"], "Create Clipping Mask", Some("Cmd+Alt+G"), "layer.createClippingMask"),+ (&["Layer"], "---", None, "---"),+ (&["Layer", "Smart Objects"], "Convert to Smart Object", None, "layer.smartObjects.convertToSmartObject"),+ (&["Layer", "Smart Objects"], "New Smart Object via Copy", None, "layer.smartObjects.newSmartObjectViaCopy"),+ (&["Layer", "Smart Objects"], "---", None, "---"),+ (&["Layer", "Smart Objects"], "Reveal in Finder", None, "layer.smartObjects.revealInFinder"),+ (&["Layer", "Smart Objects"], "---", None, "---"),+ (&["Layer", "Smart Objects"], "Update Modified Content", None, "layer.smartObjects.updateModifiedContent"),+ (&["Layer", "Smart Objects"], "Update All Modified Content", None, "layer.smartObjects.updateAllModifiedContent"),+ (&["Layer", "Smart Objects"], "---", None, "---"),+ (&["Layer", "Smart Objects"], "Edit Contents", None, "layer.smartObjects.editContents"),+ (&["Layer", "Smart Objects"], "Relink to File…", None, "layer.smartObjects.relinkToFile"),+ (&["Layer", "Smart Objects"], "Replace Contents…", None, "layer.smartObjects.replaceContents"),+ (&["Layer", "Smart Objects"], "Export Contents…", None, "layer.smartObjects.exportContents"),+ (&["Layer", "Smart Objects"], "---", None, "---"),+ (&["Layer", "Smart Objects"], "Convert to Linked…", None, "layer.smartObjects.convertToLinked"),+ (&["Layer", "Smart Objects"], "Convert to Embedded", None, "layer.smartObjects.convertToEmbedded"),+ (&["Layer", "Smart Objects"], "---", None, "---"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Entropy", None, "layer.smartObjects.stackMode.entropy"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Kurtosis", None, "layer.smartObjects.stackMode.kurtosis"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Maximum", None, "layer.smartObjects.stackMode.maximum"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Mean", None, "layer.smartObjects.stackMode.mean"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Median", None, "layer.smartObjects.stackMode.median"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Minimum", None, "layer.smartObjects.stackMode.minimum"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Range", None, "layer.smartObjects.stackMode.range"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Skewness", None, "layer.smartObjects.stackMode.skewness"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Standard Deviation", None, "layer.smartObjects.stackMode.standardDeviation"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Summation", None, "layer.smartObjects.stackMode.summation"),+ (&["Layer", "Smart Objects", "Stack Mode"], "Variance", None, "layer.smartObjects.stackMode.variance"),+ (&["Layer", "Smart Objects"], "---", None, "---"),+ (&["Layer", "Smart Objects"], "Rasterize", None, "layer.smartObjects.rasterize"),+ (&["Layer", "Smart Objects"], "---", None, "---"),+ (&["Layer", "Smart Objects"], "Warp", None, "layer.smartObjects.warp"),+ (&["Layer", "Smart Objects"], "Perspective Warp", None, "layer.smartObjects.perspectiveWarp"),+ (&["Layer", "Smart Objects"], "Puppet Warp", None, "layer.smartObjects.puppetWarp"),+ (&["Layer", "Video Layers"], "New Blank Video Layer", None, "layer.videoLayers.newBlankVideoLayer"),+ (&["Layer", "Video Layers"], "New Video Layer from File…", None, "layer.videoLayers.newVideoLayerFromFile"),+ (&["Layer", "Video Layers"], "---", None, "---"),+ (&["Layer", "Video Layers"], "Insert Blank Frame", None, "layer.videoLayers.insertBlankFrame"),+ (&["Layer", "Video Layers"], "Duplicate Frame", None, "layer.videoLayers.duplicateFrame"),+ (&["Layer", "Video Layers"], "Delete Frame", None, "layer.videoLayers.deleteFrame"),+ (&["Layer", "Video Layers"], "---", None, "---"),+ (&["Layer", "Video Layers"], "Replace Footage…", None, "layer.videoLayers.replaceFootage"),+ (&["Layer", "Video Layers"], "Interpret Footage…", None, "layer.videoLayers.interpretFootage"),+ (&["Layer", "Video Layers"], "---", None, "---"),+ (&["Layer", "Video Layers"], "Show Altered Video", None, "layer.videoLayers.showAlteredVideo"),+ (&["Layer", "Video Layers"], "---", None, "---"),+ (&["Layer", "Video Layers"], "Restore Frame", None, "layer.videoLayers.restoreFrame"),+ (&["Layer", "Video Layers"], "Restore All Frames", None, "layer.videoLayers.restoreAllFrames"),+ (&["Layer", "Video Layers"], "Reload Frame", None, "layer.videoLayers.reloadFrame"),+ (&["Layer", "Video Layers"], "---", None, "---"),+ (&["Layer", "Video Layers"], "Rasterize", None, "layer.videoLayers.rasterize"),+ (&["Layer", "Rasterize"], "Type", None, "layer.rasterize.type"),+ (&["Layer", "Rasterize"], "Shape", None, "layer.rasterize.shape"),+ (&["Layer", "Rasterize"], "Fill Content", None, "layer.rasterize.fillContent"),+ (&["Layer", "Rasterize"], "Vector Mask", None, "layer.rasterize.vectorMask"),+ (&["Layer", "Rasterize"], "Smart Object", None, "layer.rasterize.smartObject"),+ (&["Layer", "Rasterize"], "Video", None, "layer.rasterize.video"),+ (&["Layer", "Rasterize"], "---", None, "---"),+ (&["Layer", "Rasterize"], "Layer", None, "layer.rasterize.layer"),+ (&["Layer", "Rasterize"], "All Layers", None, "layer.rasterize.allLayers"),+ (&["Layer"], "---", None, "---"),+ (&["Layer"], "New Layer Based Slice", None, "layer.newLayerBasedSlice"),+ (&["Layer"], "---", None, "---"),+ (&["Layer"], "Group Layers", None, "layer.groupLayers"),+ (&["Layer"], "Ungroup Layers", None, "layer.ungroupLayers"),+ (&["Layer"], "Hide Layers", None, "layer.hideLayers"),+ (&["Layer"], "---", None, "---"),+ (&["Layer", "Arrange"], "Bring to Front", Some("Cmd+Shift+]"), "layer.arrange.bringToFront"),+ (&["Layer", "Arrange"], "Bring Forward", Some("Cmd+]"), "layer.arrange.bringForward"),+ (&["Layer", "Arrange"], "Send Backward", Some("Cmd+["), "layer.arrange.sendBackward"),+ (&["Layer", "Arrange"], "Send to Back", Some("Cmd+Shift+["), "layer.arrange.sendToBack"),+ (&["Layer", "Arrange"], "---", None, "---"),+ (&["Layer", "Arrange"], "Reverse", None, "layer.arrange.reverse"),+ (&["Layer", "Combine Shapes"], "Unite Shapes", None, "layer.combineShapes.unite"),+ (&["Layer", "Combine Shapes"], "Subtract Front Shape", None, "layer.combineShapes.subtractFrontShape"),+ (&["Layer", "Combine Shapes"], "Intersect Shape Areas", None, "layer.combineShapes.intersectShapeAreas"),+ (&["Layer", "Combine Shapes"], "Exclude Overlapping Shapes", None, "layer.combineShapes.excludeOverlappingShapes"),+ (&["Layer", "Combine Shapes"], "---", None, "---"),+ (&["Layer", "Combine Shapes"], "Merge Shape Components", None, "layer.combineShapes.mergeShapeComponents"),+ (&["Layer", "Align"], "Top Edges", None, "layer.align.topEdges"),+ (&["Layer", "Align"], "Vertical Centers", None, "layer.align.verticalCenters"),+ (&["Layer", "Align"], "Bottom Edges", None, "layer.align.bottomEdges"),+ (&["Layer", "Align"], "---", None, "---"),+ (&["Layer", "Align"], "Left Edges", None, "layer.align.leftEdges"),+ (&["Layer", "Align"], "Horizontal Centers", None, "layer.align.horizontalCenters"),+ (&["Layer", "Align"], "Right Edges", None, "layer.align.rightEdges"),+ (&["Layer", "Distribute"], "Top Edges", None, "layer.distribute.topEdges"),+ (&["Layer", "Distribute"], "Vertical Centers", None, "layer.distribute.verticalCenters"),+ (&["Layer", "Distribute"], "Bottom Edges", None, "layer.distribute.bottomEdges"),+ (&["Layer", "Distribute"], "---", None, "---"),+ (&["Layer", "Distribute"], "Left Edges", None, "layer.distribute.leftEdges"),+ (&["Layer", "Distribute"], "Horizontal Centers", None, "layer.distribute.horizontalCenters"),+ (&["Layer", "Distribute"], "Right Edges", None, "layer.distribute.rightEdges"),+ (&["Layer", "Distribute"], "---", None, "---"),+ (&["Layer", "Distribute"], "Horizontally", None, "layer.distribute.horizontally"),+ (&["Layer", "Distribute"], "Vertically", None, "layer.distribute.vertically"),+ (&["Layer"], "---", None, "---"),+ (&["Layer"], "Lock Layers…", None, "layer.lockLayers"),+ (&["Layer"], "---", None, "---"),+ (&["Layer"], "Link Layers", None, "layer.linkLayers"),+ (&["Layer"], "Select Linked Layers", None, "layer.selectLinkedLayers"),+ (&["Layer"], "---", None, "---"),+ (&["Layer"], "Merge Layers", Some("Cmd+E"), "layer.mergeLayers"),+ (&["Layer"], "Merge Visible", Some("Cmd+Shift+E"), "layer.mergeVisible"),+ (&["Layer"], "Flatten Image", None, "layer.flattenImage"),+ (&["Layer"], "---", None, "---"),+ (&["Layer", "Matting"], "Color Decontaminate…", None, "layer.matting.colorDecontaminate"),+ (&["Layer", "Matting"], "Defringe…", None, "layer.matting.defringe"),+ (&["Layer", "Matting"], "Remove Black Matte", None, "layer.matting.removeBlackMatte"),+ (&["Layer", "Matting"], "Remove White Matte", None, "layer.matting.removeWhiteMatte"),+ (&["Type", "Panels"], "Character Panel", None, "type.panels.character"),+ (&["Type", "Panels"], "Paragraph Panel", None, "type.panels.paragraph"),+ (&["Type", "Panels"], "Glyphs Panel", None, "type.panels.glyphs"),+ (&["Type", "Panels"], "Character Styles Panel", None, "type.panels.characterStyles"),+ (&["Type", "Panels"], "Paragraph Styles Panel", None, "type.panels.paragraphStyles"),+ (&["Type"], "---", None, "---"),+ (&["Type", "Anti-Alias"], "Sharp", None, "type.antiAlias.sharp"),+ (&["Type", "Anti-Alias"], "Crisp", None, "type.antiAlias.crisp"),+ (&["Type", "Anti-Alias"], "Strong", None, "type.antiAlias.strong"),+ (&["Type", "Anti-Alias"], "Smooth", None, "type.antiAlias.smooth"),+ (&["Type", "Anti-Alias"], "---", None, "---"),+ (&["Type", "Anti-Alias"], "Windows LCD", None, "type.antiAlias.windowsLcd"),+ (&["Type", "Anti-Alias"], "Windows", None, "type.antiAlias.windows"),+ (&["Type", "Orientation"], "Horizontal", None, "type.orientation.horizontal"),+ (&["Type", "Orientation"], "Vertical", None, "type.orientation.vertical"),+ (&["Type", "OpenType"], "Standard Ligatures", None, "type.openType.standardLigatures"),+ (&["Type", "OpenType"], "Contextual Alternates", None, "type.openType.contextualAlternates"),+ (&["Type", "OpenType"], "Discretionary Ligatures", None, "type.openType.discretionaryLigatures"),+ (&["Type", "OpenType"], "Swash", None, "type.openType.swash"),+ (&["Type", "OpenType"], "Oldstyle", None, "type.openType.oldstyle"),+ (&["Type", "OpenType"], "Stylistic Alternates", None, "type.openType.stylisticAlternates"),+ (&["Type", "OpenType"], "Titling Alternates", None, "type.openType.titlingAlternates"),+ (&["Type", "OpenType"], "Ornaments", None, "type.openType.ornaments"),+ (&["Type", "OpenType"], "Ordinals", None, "type.openType.ordinals"),+ (&["Type", "OpenType"], "Fractions", None, "type.openType.fractions"),+ (&["Type"], "---", None, "---"),+ (&["Type"], "Create Work Path", None, "type.createWorkPath"),+ (&["Type"], "Convert to Shape", None, "type.convertToShape"),+ (&["Type"], "---", None, "---"),+ (&["Type"], "Rasterize Type Layer", None, "type.rasterizeTypeLayer"),+ (&["Type"], "---", None, "---"),+ (&["Type"], "Convert to Paragraph Text", None, "type.convertToParagraphText"),+ (&["Type"], "Convert to Point Text", None, "type.convertToPointText"),+ (&["Type"], "Warp Text…", None, "type.warpText"),+ (&["Type"], "---", None, "---"),+ (&["Type", "Font Preview Size"], "Small", None, "type.fontPreviewSize.small"),+ (&["Type", "Font Preview Size"], "Medium", None, "type.fontPreviewSize.medium"),+ (&["Type", "Font Preview Size"], "Large", None, "type.fontPreviewSize.large"),+ (&["Type", "Font Preview Size"], "Extra Large", None, "type.fontPreviewSize.extraLarge"),+ (&["Type", "Font Preview Size"], "Huge", None, "type.fontPreviewSize.huge"),+ (&["Type", "Language Options"], "Default Features", None, "type.languageOptions.defaultFeatures"),+ (&["Type", "Language Options"], "East Asian Features", None, "type.languageOptions.eastAsianFeatures"),+ (&["Type", "Language Options"], "Middle Eastern Features", None, "type.languageOptions.middleEasternFeatures"),+ (&["Type", "Language Options"], "---", None, "---"),+ (&["Type", "Language Options"], "Middle Eastern & South Asian Composer", None, "type.languageOptions.middleEasternAndSouthAsianComposer"),+ (&["Type"], "---", None, "---"),+ (&["Type"], "Update All Text Layers", None, "type.updateAllTextLayers"),+ (&["Type"], "Replace All Missing Fonts", None, "type.replaceAllMissingFonts"),+ (&["Type"], "Resolve Missing Fonts…", None, "type.resolveMissingFonts"),+ (&["Type"], "---", None, "---"),+ (&["Type"], "Paste Lorem Ipsum", None, "type.pasteLoremIpsum"),+ (&["Type"], "---", None, "---"),+ (&["Type"], "Load Default Type Styles", None, "type.loadDefaultTypeStyles"),+ (&["Type"], "Save Default Type Styles", None, "type.saveDefaultTypeStyles"),+ (&["Select"], "All", Some("Cmd+A"), "select.all"),+ (&["Select"], "Deselect", Some("Cmd+D"), "select.deselect"),+ (&["Select"], "Reselect", Some("Cmd+Shift+D"), "select.reselect"),+ (&["Select"], "Inverse Selection", None, "select.inverse"),+ (&["Select"], "Convert to Shape", None, "select.convertToShape"),+ (&["Select"], "---", None, "---"),+ (&["Select"], "All Layers", Some("Cmd+Alt+A"), "select.allLayers"),+ (&["Select"], "Deselect Layers", None, "select.deselectLayers"),+ (&["Select"], "Find Layers", Some("Cmd+Alt+Shift+F"), "select.findLayers"),+ (&["Select"], "Isolate Layers", None, "select.isolateLayers"),+ (&["Select"], "---", None, "---"),+ (&["Select"], "Color Range…", None, "select.colorRange"),+ (&["Select"], "Focus Area…", None, "select.focusArea"),+ (&["Select"], "Subject", None, "select.subject"),+ (&["Select"], "Sky", None, "select.sky"),+ (&["Select"], "Select and Mask…", None, "select.selectAndMask"),+ (&["Select"], "---", None, "---"),+ (&["Select", "Modify"], "Border…", None, "select.modify.border"),+ (&["Select", "Modify"], "Smooth…", None, "select.modify.smooth"),+ (&["Select", "Modify"], "Expand…", None, "select.modify.expand"),+ (&["Select", "Modify"], "Contract…", None, "select.modify.contract"),+ (&["Select", "Modify"], "Feather…", Some("Shift+F6"), "select.modify.feather"),+ (&["Select"], "---", None, "---"),+ (&["Select"], "Grow", None, "select.grow"),+ (&["Select"], "Similar", None, "select.similar"),+ (&["Select"], "---", None, "---"),+ (&["Select"], "Transform Selection", None, "select.transformSelection"),+ (&["Select"], "---", None, "---"),+ (&["Select"], "Edit in Quick Mask Mode", Some("Q"), "select.editInQuickMaskMode"),+ (&["Select"], "---", None, "---"),+ (&["Select"], "Load Selection…", None, "select.loadSelection"),+ (&["Select"], "Save Selection…", None, "select.saveSelection"),+ (&["Filter"], "Last Filter", Some("Cmd+Alt+F"), "filter.lastFilter"),+ (&["Filter"], "---", None, "---"),+ (&["Filter"], "Convert for Smart Filters", None, "filter.convertForSmartFilters"),+ (&["Filter"], "---", None, "---"),+ (&["Filter"], "Filter Gallery…", None, "filter.filterGallery"),+ (&["Filter"], "Camera Raw Filter…", None, "filter.cameraRaw"),+ (&["Filter"], "Adaptive Wide Angle…", Some("Cmd+Alt+Shift+A"), "filter.adaptiveWideAngle"),+ (&["Filter"], "Lens Correction…", Some("Cmd+Shift+R"), "filter.lensCorrection"),+ (&["Filter"], "Liquify…", Some("Cmd+Shift+X"), "filter.liquify"),+ (&["Filter"], "Vanishing Point…", Some("Cmd+Alt+V"), "filter.vanishingPoint"),+ (&["Filter"], "---", None, "---"),+ (&["Filter", "Blur"], "Average", None, "filter.blur.average"),+ (&["Filter", "Blur"], "Blur", None, "filter.blur.blur"),+ (&["Filter", "Blur"], "Blur More", None, "filter.blur.blurMore"),+ (&["Filter", "Blur"], "Box Blur…", None, "filter.blur.boxBlur"),+ (&["Filter", "Blur"], "Gaussian Blur…", None, "filter.blur.gaussianBlur"),+ (&["Filter", "Blur"], "Lens Blur…", None, "filter.blur.lensBlur"),+ (&["Filter", "Blur"], "Motion Blur…", None, "filter.blur.motionBlur"),+ (&["Filter", "Blur"], "Radial Blur…", None, "filter.blur.radialBlur"),+ (&["Filter", "Blur"], "Shape Blur…", None, "filter.blur.shapeBlur"),+ (&["Filter", "Blur"], "Smart Blur…", None, "filter.blur.smartBlur"),+ (&["Filter", "Blur"], "Surface Blur…", None, "filter.blur.surfaceBlur"),+ (&["Filter", "Blur Gallery"], "Field Blur…", None, "filter.blurGallery.fieldBlur"),+ (&["Filter", "Blur Gallery"], "Iris Blur…", None, "filter.blurGallery.irisBlur"),+ (&["Filter", "Blur Gallery"], "Tilt-Shift…", None, "filter.blurGallery.tiltShift"),+ (&["Filter", "Blur Gallery"], "Path Blur…", None, "filter.blurGallery.pathBlur"),+ (&["Filter", "Blur Gallery"], "Spin Blur…", None, "filter.blurGallery.spinBlur"),+ (&["Filter", "Distort"], "Displace…", None, "filter.distort.displace"),+ (&["Filter", "Distort"], "Pinch…", None, "filter.distort.pinch"),+ (&["Filter", "Distort"], "Polar Coordinates…", None, "filter.distort.polarCoordinates"),+ (&["Filter", "Distort"], "Ripple…", None, "filter.distort.ripple"),+ (&["Filter", "Distort"], "Shear…", None, "filter.distort.shear"),+ (&["Filter", "Distort"], "Spherize…", None, "filter.distort.spherize"),+ (&["Filter", "Distort"], "Twirl…", None, "filter.distort.twirl"),+ (&["Filter", "Distort"], "Wave…", None, "filter.distort.wave"),+ (&["Filter", "Distort"], "ZigZag…", None, "filter.distort.zigZag"),+ (&["Filter", "Noise"], "Add Noise…", None, "filter.noise.addNoise"),+ (&["Filter", "Noise"], "Despeckle", None, "filter.noise.despeckle"),+ (&["Filter", "Noise"], "Dust & Scratches…", None, "filter.noise.dustAndScratches"),+ (&["Filter", "Noise"], "Median…", None, "filter.noise.median"),+ (&["Filter", "Noise"], "Reduce Noise…", None, "filter.noise.reduceNoise"),+ (&["Filter", "Pixelate"], "Color Halftone…", None, "filter.pixelate.colorHalftone"),+ (&["Filter", "Pixelate"], "Crystallize…", None, "filter.pixelate.crystallize"),+ (&["Filter", "Pixelate"], "Facet", None, "filter.pixelate.facet"),+ (&["Filter", "Pixelate"], "Fragment", None, "filter.pixelate.fragment"),+ (&["Filter", "Pixelate"], "Mezzotint…", None, "filter.pixelate.mezzotint"),+ (&["Filter", "Pixelate"], "Mosaic…", None, "filter.pixelate.mosaic"),+ (&["Filter", "Pixelate"], "Pointillize…", None, "filter.pixelate.pointillize"),+ (&["Filter", "Render"], "Flame…", None, "filter.render.flame"),+ (&["Filter", "Render"], "Picture Frame…", None, "filter.render.pictureFrame"),+ (&["Filter", "Render"], "Tree…", None, "filter.render.tree"),+ (&["Filter", "Render"], "---", None, "---"),+ (&["Filter", "Render"], "Clouds", None, "filter.render.clouds"),+ (&["Filter", "Render"], "Difference Clouds", None, "filter.render.differenceClouds"),+ (&["Filter", "Render"], "Fibers…", None, "filter.render.fibers"),+ (&["Filter", "Render"], "Lens Flare…", None, "filter.render.lensFlare"),+ (&["Filter", "Render"], "Lighting Effects…", None, "filter.render.lightingEffects"),+ (&["Filter", "Sharpen"], "Sharpen", None, "filter.sharpen.sharpen"),+ (&["Filter", "Sharpen"], "Sharpen Edges", None, "filter.sharpen.sharpenEdges"),+ (&["Filter", "Sharpen"], "Sharpen More", None, "filter.sharpen.sharpenMore"),+ (&["Filter", "Sharpen"], "Smart Sharpen…", None, "filter.sharpen.smartSharpen"),+ (&["Filter", "Sharpen"], "Unsharp Mask…", None, "filter.sharpen.unsharpMask"),+ (&["Filter", "Stylize"], "Diffuse…", None, "filter.stylize.diffuse"),+ (&["Filter", "Stylize"], "Emboss…", None, "filter.stylize.emboss"),+ (&["Filter", "Stylize"], "Extrude…", None, "filter.stylize.extrude"),+ (&["Filter", "Stylize"], "Find Edges", None, "filter.stylize.findEdges"),+ (&["Filter", "Stylize"], "Oil Paint…", None, "filter.stylize.oilPaint"),+ (&["Filter", "Stylize"], "Solarize", None, "filter.stylize.solarize"),+ (&["Filter", "Stylize"], "Tiles…", None, "filter.stylize.tiles"),+ (&["Filter", "Stylize"], "Trace Contour…", None, "filter.stylize.traceContour"),+ (&["Filter", "Stylize"], "Wind…", None, "filter.stylize.wind"),+ (&["Filter", "Video"], "De-Interlace…", None, "filter.video.deInterlace"),+ (&["Filter", "Video"], "NTSC Colors", None, "filter.video.ntscColors"),+ (&["Filter", "Other…"], "Custom…", None, "filter.other.custom"),+ (&["Filter", "Other…"], "HSB/HSL", None, "filter.other.hsbHsl"),+ (&["Filter", "Other…"], "High Pass…", None, "filter.other.highPass"),+ (&["Filter", "Other…"], "Maximum…", None, "filter.other.maximum"),+ (&["Filter", "Other…"], "Minimum…", None, "filter.other.minimum"),+ (&["Filter", "Other…"], "Offset…", None, "filter.other.offset"),+ (&["View", "Proof Setup"], "Custom…", None, "view.proofSetup.custom"),+ (&["View", "Proof Setup"], "---", None, "---"),+ (&["View", "Proof Setup"], "Working CMYK", None, "view.proofSetup.workingCmyk"),+ (&["View", "Proof Setup"], "Working Cyan Plate", None, "view.proofSetup.workingCyanPlate"),+ (&["View", "Proof Setup"], "Working Magenta Plate", None, "view.proofSetup.workingMagentaPlate"),+ (&["View", "Proof Setup"], "Working Yellow Plate", None, "view.proofSetup.workingYellowPlate"),+ (&["View", "Proof Setup"], "Working Black Plate", None, "view.proofSetup.workingBlackPlate"),+ (&["View", "Proof Setup"], "Working CMY Plate", None, "view.proofSetup.workingCmyPlate"),+ (&["View", "Proof Setup"], "---", None, "---"),+ (&["View", "Proof Setup"], "Legacy Macintosh RGB", None, "view.proofSetup.legacyMacintoshRgb"),+ (&["View", "Proof Setup"], "Internet Standard RGB", None, "view.proofSetup.internetStandardRgb"),+ (&["View", "Proof Setup"], "Monitor RGB", None, "view.proofSetup.monitorRgb"),+ (&["View", "Proof Setup"], "---", None, "---"),+ (&["View", "Proof Setup"], "Color Blindness — Protanopia-type", None, "view.proofSetup.colorBlindnessProtanopia"),+ (&["View", "Proof Setup"], "Color Blindness — Deuteranopia-type", None, "view.proofSetup.colorBlindnessDeuteranopia"),+ (&["View"], "Proof Colors", Some("Cmd+Y"), "view.proofColors"),+ (&["View"], "Gamut Warning", Some("Cmd+Shift+Y"), "view.gamutWarning"),+ (&["View"], "---", None, "---"),+ (&["View", "Pixel Aspect Ratio"], "Custom Pixel Aspect Ratio…", None, "view.pixelAspectRatio.custom"),+ (&["View", "Pixel Aspect Ratio"], "---", None, "---"),+ (&["View", "Pixel Aspect Ratio"], "Square", None, "view.pixelAspectRatio.square"),+ (&["View", "Pixel Aspect Ratio"], "D1/DV NTSC (0.91)", None, "view.pixelAspectRatio.d1DvNtsc"),+ (&["View", "Pixel Aspect Ratio"], "D1/DV PAL (1.09)", None, "view.pixelAspectRatio.d1DvPal"),+ (&["View", "Pixel Aspect Ratio"], "D1/DV NTSC Widescreen (1.21)", None, "view.pixelAspectRatio.d1DvNtscWidescreen"),+ (&["View", "Pixel Aspect Ratio"], "HDV 1080/DVCPRO HD 720 (1.33)", None, "view.pixelAspectRatio.hdv1080"),+ (&["View", "Pixel Aspect Ratio"], "D1/DV PAL Widescreen (1.46)", None, "view.pixelAspectRatio.d1DvPalWidescreen"),+ (&["View", "Pixel Aspect Ratio"], "DVCPRO HD 1080/HDV 1080 (1.5)", None, "view.pixelAspectRatio.dvcproHd1080"),+ (&["View", "Pixel Aspect Ratio"], "Anamorphic 2:1 (2)", None, "view.pixelAspectRatio.anamorphic2To1"),+ (&["View"], "Pixel Aspect Ratio Correction", None, "view.pixelAspectRatioCorrection"),+ (&["View"], "---", None, "---"),+ (&["View"], "32-bit Preview Options…", None, "view.thirtyTwoBitPreviewOptions"),+ (&["View"], "---", None, "---"),+ (&["View"], "Zoom In", Some("Cmd+="), "view.zoomIn"),+ (&["View"], "Zoom Out", Some("Cmd+-"), "view.zoomOut"),+ (&["View"], "Fit on Screen", None, "view.fitOnScreen"),+ (&["View"], "Fit Layer(s) on Screen", None, "view.fitLayersOnScreen"),+ (&["View"], "Fit Artboard on Screen", None, "view.fitArtboardOnScreen"),+ (&["View"], "100%", Some("Cmd+1"), "view.actualPixels"),+ (&["View"], "200%", None, "view.twoHundredPercent"),+ (&["View"], "Print Size", None, "view.printSize"),+ (&["View"], "---", None, "---"),+ (&["View"], "Flip Horizontal", None, "view.flipHorizontal"),+ (&["View", "Screen Mode"], "Standard Screen Mode", None, "view.screenMode.standard"),+ (&["View", "Screen Mode"], "Full Screen Mode With Menu Bar", None, "view.screenMode.fullScreenWithMenuBar"),+ (&["View", "Screen Mode"], "Full Screen Mode", None, "view.screenMode.fullScreen"),+ (&["View"], "---", None, "---"),+ (&["View"], "Extras", Some("Cmd+H"), "view.extras"),+ (&["View", "Show"], "Layer Edges", None, "view.show.layerEdges"),+ (&["View", "Show"], "Selection Edges", None, "view.show.selectionEdges"),+ (&["View", "Show"], "Target Path", Some("Cmd+Shift+H"), "view.show.targetPath"),+ (&["View", "Show"], "Grid", Some("Cmd+'"), "view.show.grid"),+ (&["View", "Show"], "Guides", Some("Cmd+;"), "view.show.guides"),+ (&["View", "Show"], "Canvas Guides", None, "view.show.canvasGuides"),+ (&["View", "Show"], "Artboard Guides", None, "view.show.artboardGuides"),+ (&["View", "Show"], "Count", None, "view.show.count"),+ (&["View", "Show"], "Smart Guides", None, "view.show.smartGuides"),+ (&["View", "Show"], "Slices", None, "view.show.slices"),+ (&["View", "Show"], "Notes", None, "view.show.notes"),+ (&["View", "Show"], "Pixel Grid", None, "view.show.pixelGrid"),+ (&["View", "Show"], "Brush Preview", None, "view.show.brushPreview"),+ (&["View", "Show"], "Mesh", None, "view.show.mesh"),+ (&["View", "Show"], "Edit Pins", None, "view.show.editPins"),+ (&["View", "Show"], "---", None, "---"),+ (&["View", "Show"], "All", None, "view.show.all"),+ (&["View", "Show"], "Show Extras Options…", None, "view.show.showExtrasOptions"),+ (&["View"], "---", None, "---"),+ (&["View"], "Rulers", Some("Cmd+R"), "view.rulers"),+ (&["View"], "---", None, "---"),+ (&["View"], "Snap", Some("Cmd+Shift+;"), "view.snap"),+ (&["View", "Snap To"], "Guides", None, "view.snapTo.guides"),+ (&["View", "Snap To"], "Grid", None, "view.snapTo.grid"),+ (&["View", "Snap To"], "Layers", None, "view.snapTo.layers"),+ (&["View", "Snap To"], "Slices", None, "view.snapTo.slices"),+ (&["View", "Snap To"], "Document Bounds", None, "view.snapTo.documentBounds"),+ (&["View", "Snap To"], "---", None, "---"),+ (&["View", "Snap To"], "All", None, "view.snapTo.all"),+ (&["View"], "---", None, "---"),+ (&["View"], "Lock Guides", Some("Cmd+Alt+;"), "view.lockGuides"),+ (&["View"], "Clear Guides", None, "view.clearGuides"),+ (&["View"], "Clear Selected Artboard Guides", None, "view.clearSelectedArtboardGuides"),+ (&["View"], "Clear Canvas Guides", None, "view.clearCanvasGuides"),+ (&["View"], "New Guide…", None, "view.newGuide"),+ (&["View"], "New Guide Layout…", None, "view.newGuideLayout"),+ (&["View"], "New Guides From Shape", None, "view.newGuidesFromShape"),+ (&["View"], "---", None, "---"),+ (&["View"], "Lock Slices", None, "view.lockSlices"),+ (&["View"], "Clear Slices", None, "view.clearSlices"),+ (&["View"], "---", None, "---"),+ (&["View"], "Pattern Preview", None, "view.patternPreview"),+ (&["View"], "Pixel Art Preview", None, "view.pixelArtPreview"),+ (&["Window", "Arrange"], "Tile All Vertically", None, "window.arrange.tileAllVertically"),+ (&["Window", "Arrange"], "Tile All Horizontally", None, "window.arrange.tileAllHorizontally"),+ (&["Window", "Arrange"], "2-up Vertical", None, "window.arrange.twoUpVertical"),+ (&["Window", "Arrange"], "2-up Horizontal", None, "window.arrange.twoUpHorizontal"),+ (&["Window", "Arrange"], "3-up Vertical", None, "window.arrange.threeUpVertical"),+ (&["Window", "Arrange"], "3-up Horizontal", None, "window.arrange.threeUpHorizontal"),+ (&["Window", "Arrange"], "3-up Stacked", None, "window.arrange.threeUpStacked"),+ (&["Window", "Arrange"], "4-up", None, "window.arrange.fourUp"),+ (&["Window", "Arrange"], "6-up", None, "window.arrange.sixUp"),+ (&["Window", "Arrange"], "---", None, "---"),+ (&["Window", "Arrange"], "Consolidate All to Tabs", None, "window.arrange.consolidateAllToTabs"),+ (&["Window", "Arrange"], "Cascade", None, "window.arrange.cascade"),+ (&["Window", "Arrange"], "Tile", None, "window.arrange.tile"),+ (&["Window", "Arrange"], "---", None, "---"),+ (&["Window", "Arrange"], "Float in Window", None, "window.arrange.floatInWindow"),+ (&["Window", "Arrange"], "Float All in Windows", None, "window.arrange.floatAllInWindows"),+ (&["Window", "Arrange"], "---", None, "---"),+ (&["Window", "Arrange"], "New Window for Document", None, "window.arrange.newWindowForDocument"),+ (&["Window", "Arrange"], "---", None, "---"),+ (&["Window", "Arrange"], "Match Zoom", None, "window.arrange.matchZoom"),+ (&["Window", "Arrange"], "Match Location", None, "window.arrange.matchLocation"),+ (&["Window", "Arrange"], "Match Rotation", None, "window.arrange.matchRotation"),+ (&["Window", "Arrange"], "Match All", None, "window.arrange.matchAll"),+ (&["Window", "Workspace"], "Essentials", None, "window.workspace.essentials"),+ (&["Window", "Workspace"], "Photography", None, "window.workspace.photography"),+ (&["Window", "Workspace"], "Painting", None, "window.workspace.painting"),+ (&["Window", "Workspace"], "Pixel Art", None, "window.workspace.pixelArt"),+ (&["Window", "Workspace"], "Graphic and Web", None, "window.workspace.graphicAndWeb"),+ (&["Window", "Workspace"], "Motion", None, "window.workspace.motion"),+ (&["Window", "Workspace"], "---", None, "---"),+ (&["Window", "Workspace"], "Reset Workspace", None, "window.workspace.resetWorkspace"),+ (&["Window", "Workspace"], "New Workspace…", None, "window.workspace.newWorkspace"),+ (&["Window", "Workspace"], "Delete Workspace…", None, "window.workspace.deleteWorkspace"),+ (&["Window", "Workspace"], "---", None, "---"),+ (&["Window", "Workspace"], "Keyboard Shortcuts…", Some("Cmd+Alt+Shift+K"), "edit.keyboardShortcuts"),+ (&["Window", "Workspace"], "Lock Workspace", None, "window.workspace.lockWorkspace"),+ (&["Window"], "---", None, "---"),+ (&["Window"], "Actions", Some("Alt+F9"), "window.panel.actions"),+ (&["Window"], "Adjustments", None, "window.panel.adjustments"),+ (&["Window"], "Brush Settings", Some("F5"), "window.panel.brushSettings"),+ (&["Window"], "Brushes", None, "window.panel.brushes"),+ (&["Window"], "Channels", None, "window.panel.channels"),+ (&["Window"], "Character", None, "window.panel.character"),+ (&["Window"], "Character Styles", None, "window.panel.characterStyles"),+ (&["Window"], "Clone Source", None, "window.panel.cloneSource"),+ (&["Window"], "Color", Some("F6"), "window.panel.color"),+ (&["Window"], "Glyphs", None, "window.panel.glyphs"),+ (&["Window"], "Gradients", None, "window.panel.gradients"),+ (&["Window"], "Histogram", None, "window.panel.histogram"),+ (&["Window"], "History", None, "window.panel.history"),+ (&["Window"], "Info", Some("F8"), "window.panel.info"),+ (&["Window"], "Layer Comps", None, "window.panel.layerComps"),+ (&["Window"], "Layers", Some("F7"), "window.panel.layers"),+ (&["Window"], "Measurement Log", None, "window.panel.measurementLog"),+ (&["Window"], "Modifier Keys", None, "window.panel.modifierKeys"),+ (&["Window"], "Navigator", None, "window.panel.navigator"),+ (&["Window"], "Notes", None, "window.panel.notes"),+ (&["Window"], "Paragraph", None, "window.panel.paragraph"),+ (&["Window"], "Paragraph Styles", None, "window.panel.paragraphStyles"),+ (&["Window"], "Paths", None, "window.panel.paths"),+ (&["Window"], "Patterns", None, "window.panel.patterns"),+ (&["Window"], "Properties", None, "window.panel.properties"),+ (&["Window"], "Shapes", None, "window.panel.shapes"),+ (&["Window"], "Styles", None, "window.panel.styles"),+ (&["Window"], "Swatches", None, "window.panel.swatches"),+ (&["Window"], "Timeline", None, "window.panel.timeline"),+ (&["Window"], "Tool Presets", None, "window.panel.toolPresets"),+ (&["Window"], "---", None, "---"),+ (&["Window"], "Options", None, "window.panel.options"),+ (&["Window"], "Tools", None, "window.panel.tools"),+];diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 934ce36bf..205f9c7e7 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -6,13 +6,20 @@ use crate::PhotocraftApp;use crate::state::{DialogKind, UiState};/// Top-level menus in Photoshop order.-pub const TOP_MENUS: [&str; 9] = ["File", "Edit", "Image", "Layer", "Select", "Filter", "View", "Window", "Help"];+pub const TOP_MENUS: [&str; 10] = ["File", "Edit", "Image", "Layer", "Type", "Select", "Filter", "View", "Window", "Help"];/// UI-level commands (handled by the shell rather than the engine): id, label, menu, shortcut.pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[("file.open", "Open…", &["File"], Some("Cmd+O")),("file.save", "Save", &["File"], Some("Cmd+S")),("file.saveAs", "Save As…", &["File"], Some("Cmd+Shift+S")),+ ("edit.freeTransform", "Free Transform", &["Edit"], Some("Cmd+T")),+ ("file.export.exportAs", "Export As…", &["File", "Export"], Some("Cmd+Alt+Shift+W")),+ ("view.rulers", "Rulers", &["View"], Some("Cmd+R")),+ ("view.show.grid", "Grid", &["View", "Show"], Some("Cmd+'")),+ ("view.show.guides", "Guides", &["View", "Show"], Some("Cmd+;")),+ ("view.snap", "Snap", &["View"], Some("Cmd+Shift+;")),+ ("view.lockGuides", "Lock Guides", &["View"], Some("Cmd+Alt+;")),("view.zoomIn", "Zoom In", &["View"], Some("Cmd+=")),("view.zoomOut", "Zoom Out", &["View"], Some("Cmd+-")),("view.fitOnScreen", "Fit on Screen", &["View"], Some("Cmd+0")),@@ -87,6 +94,47 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: VaOk(Value::Null)}"help.about" => Ok(json!({"dialog": app.ui.open_dialog(DialogKind::About, Default::default())})),+ "file.export.exportAs" => Ok(json!({"dialog": crate::export_dialog::open(app)?})),+ "file.export.quickExportAsPng" => crate::export_dialog::quick_export_png(app),+ // Photoshop's "Select and Mask…" is the engine's select.refineEdge.+ "select.selectAndMask" => Ok(json!({"dialog": crate::filter_dialog::open(app, "select.refineEdge")})),+ "edit.paste" if params.as_object().is_none_or(|o| o.is_empty()) => {+ // Photoshop: paste in place when the copied area is visible, else centred in the view;+ // images from other apps are always centred.+ let external = app.import_os_clipboard();+ let visible = !external && app.session.active_index().zip(app.session.clipboard.as_ref()).is_some_and(|(i, clip)| {+ let v = &app.ui.views[i];+ let (hw, hh) = (app.last_canvas_rect.width() / 2.0 / v.zoom, app.last_canvas_rect.height() / 2.0 / v.zoom);+ let r = photocraft_geom::Rect::new((v.center[0] - hw) as i32, (v.center[1] - hh) as i32, (v.center[0] + hw) as i32, (v.center[1] + hh) as i32);+ !clip.bounds.intersect(&r).is_empty()+ });+ let p = match app.session.active_index() {+ Some(i) if !visible => json!({"center": app.ui.views[i].center}),+ _ => json!({}),+ };+ app.run("edit.paste", p)+ }+ "view.rulers" | "view.show.grid" | "view.show.guides" | "view.snap" | "view.lockGuides" => {+ let e = &mut app.ui.extras;+ let slot = match id {+ "view.rulers" => &mut e.rulers,+ "view.show.grid" => &mut e.grid,+ "view.show.guides" => &mut e.guides,+ "view.snap" => &mut e.snap,+ _ => &mut e.lock_guides,+ };+ *slot = !*slot;+ Ok(json!(*slot))+ }+ "edit.freeTransform" | "edit.transform.scale" | "edit.transform.rotate" | "edit.transform.skew" | "edit.transform.distort" | "edit.transform.perspective" => {+ crate::transform_tool::begin(app, ctx).map(|_| json!({"transform": app.ui.transform}))+ }+ sz if crate::sizing::is_sizing(sz) && params.as_object().is_none_or(|o| o.is_empty()) => {+ Ok(json!({"dialog": crate::sizing::open(app, sz).ok_or("no document")?}))+ }+ fl if crate::filter_dialog::has_dialog(fl) && params.as_object().is_none_or(|o| o.is_empty()) => {+ Ok(json!({"dialog": crate::filter_dialog::open(app, fl)}))+ }a if a.starts_with("image.adjustments.")&& params.as_object().is_none_or(|o| o.is_empty())&& !crate::panels::adjustment_sliders(a.rsplit('.').next().unwrap_or("")).is_empty() =>@@ -133,15 +181,43 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {match id {"file.open" | "help.about" | "edit.search" => true,i if i.starts_with("window.theme.") => true,- "file.save" | "file.saveAs" => app.session.active().is_some() && app.services.export.is_some(),+ "file.save" | "file.saveAs" | "file.export.exportAs" | "file.export.quickExportAsPng" => app.session.active().is_some() && app.services.export.is_some(),i if i.starts_with("window.toggle.") => true,- i if i.starts_with("view.") || i == "window.newWindowForDocument" => app.session.active().is_some(),+ "view.rulers" | "view.show.grid" | "view.show.guides" | "view.snap" | "view.lockGuides" => true,+ "select.selectAndMask" => app.session.is_enabled("select.refineEdge"),+ i if (i.starts_with("view.zoom") || i == "view.fitOnScreen" || i == "view.actualPixels") || i == "window.newWindowForDocument" => app.session.active().is_some(),+ "edit.freeTransform" | "edit.transform.scale" | "edit.transform.rotate" | "edit.transform.skew" | "edit.transform.distort" | "edit.transform.perspective" => {+ app.ui.transform.is_none() && app.session.active().and_then(|s| s.active_layer).is_some()+ }i => app.session.is_enabled(i),}}/// Is a UI-level panel toggle currently on (for checkmarks)?fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {+ use photocraft_doc::{ColorMode, SampleType};+ if let Some(m) = id.strip_prefix("image.mode.") {+ let d = &app.session.active()?.doc;+ return match m {+ "rgb" => Some(d.mode == ColorMode::Rgb),+ "grayscale" => Some(d.mode == ColorMode::Grayscale),+ "cmyk" => Some(d.mode == ColorMode::Cmyk),+ "lab" => Some(d.mode == ColorMode::Lab),+ "bits8" => Some(d.depth == SampleType::U8),+ "bits16" => Some(d.depth == SampleType::U16),+ "bits32" => Some(d.depth == SampleType::F32),+ _ => None,+ };+ }+ let e = &app.ui.extras;+ match id {+ "view.rulers" => return Some(e.rulers),+ "view.show.grid" => return Some(e.grid),+ "view.show.guides" => return Some(e.guides),+ "view.snap" => return Some(e.snap),+ "view.lockGuides" => return Some(e.lock_guides),+ _ => {}+ }let p = &app.ui.panels;Some(match id {"window.toggle.layers" => p.layers,@@ -167,25 +243,36 @@ pub struct MenuItem {}pub fn menu_items(app: &PhotocraftApp) -> Vec<MenuItem> {- let mut items: Vec<MenuItem> = Vec::new();+ // 1) Photoshop's full menu tree, in Photoshop order; live where we implement the command.+ let known = |id: &str| photocraft_engine::commands::find(id).is_some() || UI_COMMANDS.iter().any(|c| c.0 == id);+ let mut items: Vec<MenuItem> = crate::menu_catalog::CATALOG+ .iter()+ .map(|&(path, label, sc, id)| MenuItem {+ id: id.to_string(),+ label: label.to_string(),+ path: path.iter().map(|s| s.to_string()).collect(),+ shortcut: sc.map(Into::into),+ enabled: known(id) && is_enabled(app, id),+ checked: checked(app, id),+ })+ .collect();+ // 2) Our commands that Photoshop's tree doesn't list (or lists under another id).+ let mut extra: Vec<MenuItem> = Vec::new();for &(id, label, path, sc) in UI_COMMANDS {- items.push(MenuItem { id: id.into(), label: label.into(), path: path.iter().map(|s| s.to_string()).collect(), shortcut: sc.map(Into::into), enabled: is_enabled(app, id), checked: checked(app, id) });+ extra.push(MenuItem { id: id.into(), label: label.into(), path: path.iter().map(|s| s.to_string()).collect(), shortcut: sc.map(Into::into), enabled: is_enabled(app, id), checked: checked(app, id) });}for c in photocraft_engine::command_specs().iter().filter(|c| !c.menu.is_empty()) {- items.push(MenuItem { id: c.id.into(), label: c.label.into(), path: c.menu.iter().map(|s| s.to_string()).collect(), shortcut: c.shortcut.map(Into::into), enabled: is_enabled(app, c.id), checked: None });+ extra.push(MenuItem { id: c.id.into(), label: c.label.into(), path: c.menu.iter().map(|s| s.to_string()).collect(), shortcut: c.shortcut.map(Into::into), enabled: is_enabled(app, c.id), checked: None });}- // Stable, Photoshop-like order: File menu items in a sensible sequence.- let order = |id: &str| -> i32 {- match id {- "file.new" => 0,- "file.open" => 1,- "file.close" => 2,- "file.save" => 3,- "file.saveAs" => 4,- _ => 10,+ for e in extra {+ let dup = items.iter().any(|i| i.id == e.id || (i.path == e.path && i.label.trim_end_matches('…') == e.label.trim_end_matches('…')));+ if !dup {+ // Insert after the last item of the same top-level menu, keeping menus contiguous.+ let top = e.path.first().cloned();+ let at = items.iter().rposition(|i| i.path.first() == top.as_ref()).map_or(items.len(), |p| p + 1);+ items.insert(at, e);}- };- items.sort_by_key(|i| (TOP_MENUS.iter().position(|m| Some(m) == i.path.first().map(|s| s.as_str()).as_ref()).unwrap_or(99), order(&i.id)));+ }items}@@ -231,36 +318,46 @@ fn render_level(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &v.widgets.hovered.corner_radius = egui::CornerRadius::same(3);ui.spacing_mut().button_padding = egui::vec2(10.0, 4.0);}- let mut subs: Vec<String> = Vec::new();- for it in items {- if it.path.len() > depth {- let s = it.path[depth].clone();- if !subs.contains(&s) {- subs.push(s);+ // Walk in Photoshop order: leaves and separators at this depth; a submenu appears at the position+ // of its first child.+ let mut shown_subs: Vec<&str> = Vec::new();+ let mut last_was_sep = true;+ for (i, it) in items.iter().enumerate() {+ if it.path.len() == depth {+ if it.label == "---" {+ if !last_was_sep && i + 1 < items.len() {+ ui.separator();+ last_was_sep = true;+ }+ continue;}+ let mut text = it.label.clone();+ if let Some(c) = it.checked {+ text = format!("{} {}", if c { "✔" } else { " " }, text);+ }+ let mut b = egui::Button::new(text);+ if let Some(sc) = &it.shortcut {+ b = b.shortcut_text(crate::shortcuts::pretty(sc));+ }+ if ui.add_enabled(it.enabled, b).clicked() {+ *clicked = Some(it.id.clone());+ ui.close();+ }+ last_was_sep = false;+ } else if it.path.len() > depth {+ let name = it.path[depth].as_str();+ if shown_subs.contains(&name) {+ continue;+ }+ shown_subs.push(name);+ let child: Vec<&MenuItem> = items.iter().copied().filter(|c| c.path.len() > depth && c.path[depth] == name).collect();+ let any_enabled = child.iter().any(|c| c.enabled && c.label != "---");+ ui.add_enabled_ui(any_enabled || !child.is_empty(), |ui| {+ ui.menu_button(name, |ui| render_level(ui, &child, depth + 1, clicked));+ });+ last_was_sep = false;}}- for it in items.iter().filter(|i| i.path.len() == depth) {- let mut text = it.label.clone();- if let Some(c) = it.checked {- text = format!("{} {}", if c { "✔" } else { " " }, text);- }- let mut b = egui::Button::new(text);- if let Some(sc) = &it.shortcut {- b = b.shortcut_text(crate::shortcuts::pretty(sc));- }- if ui.add_enabled(it.enabled, b).clicked() {- *clicked = Some(it.id.clone());- ui.close();- }- }- if !subs.is_empty() && items.iter().any(|i| i.path.len() == depth) {- ui.separator();- }- for s in subs {- let child: Vec<&MenuItem> = items.iter().copied().filter(|i| i.path.len() > depth && i.path[depth] == s).collect();- ui.menu_button(&s, |ui| render_level(ui, &child, depth + 1, clicked));- }}/// Workspace presets (Window → Workspace): which panels are visible.diff --git a/crates/ui-egui/src/outline.rs b/crates/ui-egui/src/outline.rsindex 691d9408b..9f12e4077 100644--- a/crates/ui-egui/src/outline.rs+++ b/crates/ui-egui/src/outline.rs@@ -1,5 +1,8 @@//! Selection outlines: boundary segments of a coverage mask (threshold 0.5), merged into long runs,-//! computed once per document revision and drawn as animated marching ants.+//! drawn as animated marching ants.+//!+//! The outline is traced at display resolution: `outline_scaled` samples every `step`-th pixel, so+//! a 36 MP selection at 12% zoom costs a ~0.5 MP scan instead of reading the whole mask.use photocraft_geom::Rect;use photocraft_raster::Surface;@@ -9,15 +12,46 @@ pub type Segment = ([i32; 2], [i32; 2]);/// Extract the boundary of `mask` (> 0.5 = selected) as merged horizontal and vertical segments.pub fn outline(mask: &Surface, bounds: Rect) -> Vec<Segment> {+ outline_scaled(mask, bounds, 1)+}++/// Like [`outline`], sampling one pixel per `step`×`step` block (segments stay in document space).+pub fn outline_scaled(mask: &Surface, bounds: Rect, step: u32) -> Vec<Segment> {if bounds.is_empty() {return Vec::new();}- // Pad by one so edges at the bounds are detected.- let r = bounds.inflate(1);- let (w, h) = (r.width() as usize, r.height() as usize);- let data = mask.read_region(r);- let n = mask.channels();- let inside = |x: usize, y: usize| data[(y * w + x) * n] > 0.5;+ let step = step.max(1) as i32;+ // Grid of block samples, padded by one cell so edges at the bounds are detected.+ let gx0 = bounds.x0.div_euclid(step) - 1;+ let gy0 = bounds.y0.div_euclid(step) - 1;+ let gx1 = (bounds.x1 + step - 1).div_euclid(step) + 1;+ let gy1 = (bounds.y1 + step - 1).div_euclid(step) + 1;+ let (w, h) = ((gx1 - gx0) as usize, (gy1 - gy0) as usize);+ let mut grid = vec![false; w * h];+ let half = step / 2;+ let sample_row = |gy: usize, row: &mut [bool]| {+ let y = (gy0 + gy as i32) * step + half;+ if y < bounds.y0 || y >= bounds.y1 {+ return;+ }+ let mut vals = vec![0.0f32; row.len()];+ mask.sample_row_strided(y, gx0 * step + half, step, 0, &mut vals);+ for (gx, (cell, v)) in row.iter_mut().zip(vals).enumerate() {+ let x = (gx0 + gx as i32) * step + half;+ *cell = x >= bounds.x0 && x < bounds.x1 && v > 0.5;+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ grid.par_chunks_mut(w).enumerate().for_each(|(gy, row)| sample_row(gy, row));+ }+ #[cfg(target_arch = "wasm32")]+ grid.chunks_mut(w).enumerate().for_each(|(gy, row)| sample_row(gy, row));+ let inside = |x: usize, y: usize| grid[y * w + x];+ // Grid → document coordinates, clamped so coarse cells never draw outside the selection bounds.+ let r = Rect::new(gx0 * step, gy0 * step, gx1 * step, gy1 * step);+ let (cx, cy) = (|v: i32| v.clamp(bounds.x0, bounds.x1), |v: i32| v.clamp(bounds.y0, bounds.y1));let mut segs = Vec::new();// Horizontal edges between rows y-1 and y, merged along x.for y in 1..h {@@ -27,7 +61,8 @@ pub fn outline(mask: &Surface, bounds: Rect) -> Vec<Segment> {match (edge, run) {(true, None) => run = Some(x),(false, Some(x0)) => {- segs.push(([r.x0 + x0 as i32, r.y0 + y as i32], [r.x0 + x as i32, r.y0 + y as i32]));+ let yy = cy(r.y0 + y as i32 * step);+ segs.push(([cx(r.x0 + x0 as i32 * step), yy], [cx(r.x0 + x as i32 * step), yy]));run = None;}_ => {}@@ -42,7 +77,8 @@ pub fn outline(mask: &Surface, bounds: Rect) -> Vec<Segment> {match (edge, run) {(true, None) => run = Some(y),(false, Some(y0)) => {- segs.push(([r.x0 + x as i32, r.y0 + y0 as i32], [r.x0 + x as i32, r.y0 + y as i32]));+ let xx = cx(r.x0 + x as i32 * step);+ segs.push(([xx, cy(r.y0 + y0 as i32 * step)], [xx, cy(r.y0 + y as i32 * step)]));run = None;}_ => {}@@ -77,6 +113,24 @@ mod tests {assert_eq!(outline(&m, m.content_bounds()).len(), 8);}+ #[test]+ fn scaled_outline_approximates_full_resolution() {+ let mut m = Surface::new(PixelFormat::GRAY8);+ m.fill_rect(Rect::new(8, 8, 72, 40), &[1.0]);+ let s = outline_scaled(&m, m.content_bounds(), 4);+ assert_eq!(s.len(), 4, "{s:?}");+ assert!(s.contains(&([8, 8], [72, 8])));+ assert!(s.contains(&([72, 8], [72, 40])));+ // Unaligned bounds are clamped, never drawn outside the selection.+ let mut m = Surface::new(PixelFormat::GRAY8);+ m.fill_rect(Rect::new(3, 5, 30, 21), &[1.0]);+ for seg in outline_scaled(&m, m.content_bounds(), 8) {+ for p in [seg.0, seg.1] {+ assert!(p[0] >= 3 && p[0] <= 30 && p[1] >= 5 && p[1] <= 21, "{seg:?}");+ }+ }+ }+#[test]fn empty_mask_has_no_outline() {let m = Surface::new(PixelFormat::GRAY8);diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rsindex 447d29eaf..627c2a28a 100644--- a/crates/ui-egui/src/palette.rs+++ b/crates/ui-egui/src/palette.rs@@ -78,7 +78,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {.filter_map(|m| {let path = m.path.join(" › ");let s = fuzzy_score(&q, &format!("{} {}", m.label, path))?;- Some((s, m.id, format!("{}", m.label.trim_end_matches('…')), Some(path).filter(|_| true).map(|p| p + &m.shortcut.map(|s| format!(" {}", crate::shortcuts::pretty(&s))).unwrap_or_default()), m.enabled))+ Some((s, m.id, m.label.trim_end_matches('…').to_string(), Some(path).filter(|_| true).map(|p| p + &m.shortcut.map(|s| format!(" {}", crate::shortcuts::pretty(&s))).unwrap_or_default()), m.enabled))}).collect();for tool in crate::state::Tool::ALL {diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 991f731a7..a2776f81e 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -12,11 +12,43 @@ use crate::{PhotocraftApp, icons, widgets};// ----------------------------------------------------------------------------- toolbar/// Tool groups separated by hairlines, Photoshop order.-const TOOL_GROUPS: &[&[Tool]] = &[&[Tool::Move], &[Tool::RectMarquee, Tool::EllipseMarquee], &[Tool::Eyedropper], &[Tool::Brush, Tool::Eraser], &[Tool::Hand, Tool::Zoom]];+/// Photoshop toolbar: divider-separated sections of slots; each slot is a flyout group whose button+/// shows the group's last-used tool.+const TOOL_SECTIONS: &[&[&[Tool]]] = &[+ &[&[Tool::Move]],+ &[&[Tool::RectMarquee, Tool::EllipseMarquee], &[Tool::Lasso, Tool::PolygonLasso], &[Tool::ObjectSelection, Tool::QuickSelection, Tool::MagicWand], &[Tool::Crop], &[Tool::Eyedropper]],+ &[+ &[Tool::SpotHealing, Tool::Healing],+ &[Tool::Brush],+ &[Tool::CloneStamp],+ &[Tool::HistoryBrush],+ &[Tool::Eraser],+ &[Tool::Gradient, Tool::PaintBucket],+ &[Tool::Blur, Tool::Sharpen, Tool::Smudge],+ &[Tool::Dodge, Tool::Burn, Tool::Sponge],+ ],+ &[&[Tool::Pen], &[Tool::Type], &[Tool::PathSelection], &[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line]],+ &[&[Tool::Hand], &[Tool::Zoom]],+];++/// The tool a slot shows: the current tool if it belongs to the slot, else the last one used.+fn slot_tool(ui: &egui::Ui, current: Tool, slot: &[Tool], key: egui::Id) -> Tool {+ if slot.contains(¤t) {+ ui.data_mut(|d| d.insert_temp(key, current));+ return current;+ }+ ui.data(|d| d.get_temp::<Tool>(key)).filter(|t| slot.contains(t)).unwrap_or(slot[0])+}pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let t = Tokens::get(ui.ctx());- let (w, bx, m) = if t.pro { (40.0, 30.0, 5i8) } else { (50.0, 36.0, 7i8) };+ let (w1, bx, m) = if t.pro { (40.0, 30.0, 5i8) } else { (50.0, 36.0, 7i8) };+ // Photoshop switches to a double-column toolbar when the window is too short.+ let slots: usize = TOOL_SECTIONS.iter().map(|g| g.len()).sum();+ let needed = slots as f32 * (bx + 3.0) + TOOL_SECTIONS.len() as f32 * 9.0 + 190.0;+ let avail_h = ui.ctx().content_rect().height() - 130.0;+ let double = needed > avail_h;+ let w = if double { w1 + bx + 2.0 } else { w1 };egui::Panel::left("toolbar").resizable(false).exact_size(w).frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(m, 8))).show(ui, |ui| {if t.pro {let r = ui.max_rect();@@ -41,26 +73,76 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {mesh.add_triangle(0, 2, 3);ui.painter().add(mesh);}- ui.spacing_mut().item_spacing = vec2(0.0, 3.0);- for (gi, group) in TOOL_GROUPS.iter().enumerate() {- if gi > 0 {+ ui.spacing_mut().item_spacing = vec2(2.0, 3.0);+ let flyout_id = egui::Id::new("tool-flyout");+ let mut slot_index = 0usize;+ for (si, section) in TOOL_SECTIONS.iter().enumerate() {+ if si > 0 {ui.add_space(4.0);- let (r, _) = ui.allocate_exact_size(vec2(bx, 1.0), Sense::hover());+ let (r, _) = ui.allocate_exact_size(vec2(if double { bx * 2.0 + 2.0 } else { bx }, 1.0), Sense::hover());ui.painter().line_segment([r.left_center() + vec2(8.0, 0.0), r.right_center() - vec2(8.0, 0.0)], Stroke::new(1.0, t.separator));ui.add_space(4.0);}- for &tool in *group {- let sel = app.ui.tool == tool;- let resp = icons::button(ui, icons::tool_icon(tool), bx, sel, &format!("{} ({})", tool.label(), tool.key()));- if t.pro && group.len() > 1 {- // Photoshop's little corner triangle marks a tool group.- let r = resp.rect;- let tri = vec![r.right_bottom() + vec2(-2.0, -2.0), r.right_bottom() + vec2(-6.0, -2.0), r.right_bottom() + vec2(-2.0, -6.0)];- ui.painter().add(egui::Shape::convex_polygon(tri, t.text_faint, Stroke::NONE));- }- if resp.clicked() {- app.ui.tool = tool;- }+ let rows: Vec<&[&[Tool]]> = if double { section.chunks(2).collect() } else { section.chunks(1).collect() };+ for row in rows {+ ui.horizontal(|ui| {+ for slot in row.iter() {+ let key = egui::Id::new(("tool-slot", slot_index));+ slot_index += 1;+ let tool = slot_tool(ui, app.ui.tool, slot, key);+ let sel = slot.contains(&app.ui.tool);+ let tip = if tool.key() == '\0' { tool.label().to_string() } else { format!("{} ({})", tool.label(), tool.key()) };+ let resp = icons::button(ui, icons::tool_icon(tool), bx, sel, &tip);+ if slot.len() > 1 {+ let r = resp.rect;+ let tri = vec![r.right_bottom() + vec2(-2.0, -2.0), r.right_bottom() + vec2(-6.0, -2.0), r.right_bottom() + vec2(-2.0, -6.0)];+ ui.painter().add(egui::Shape::convex_polygon(tri, t.text_faint, Stroke::NONE));+ }+ if resp.clicked() {+ app.ui.tool = tool;+ }+ // Right-click or long-press opens the flyout (Photoshop).+ let long_press = resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.press_start_time().is_some_and(|t0| i.time - t0 > 0.35));+ if slot.len() > 1 && (resp.secondary_clicked() || long_press) {+ ui.data_mut(|d| d.insert_temp(flyout_id, (key, resp.rect)));+ }+ if slot.len() > 1 && long_press {+ ui.ctx().request_repaint();+ }+ if let Some((open_key, anchor)) = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id))+ && open_key == key+ {+ let area = egui::Area::new(key.with("flyout")).order(egui::Order::Foreground).fixed_pos(anchor.right_top() + vec2(6.0, 0.0)).show(ui.ctx(), |ui| {+ egui::Frame::popup(ui.style()).show(ui, |ui| {+ let label_w = slot.iter().map(|it| ui.painter().layout_no_wrap(it.label().to_string(), egui::FontId::proportional(12.5), t.text).size().x).fold(0.0f32, f32::max);+ let fw = (label_w + 42.0 + 40.0).max(180.0);+ for &item in slot.iter() {+ let (r, ir) = ui.allocate_exact_size(vec2(fw, 26.0), Sense::click());+ if ir.hovered() {+ ui.painter().rect_filled(r, 3.0, t.hover);+ }+ if item == tool {+ ui.painter().rect_filled(Rect::from_center_size(pos2(r.left() + 8.0, r.center().y), vec2(4.0, 4.0)), 0.0, t.text);+ }+ icons::paint(ui, Rect::from_center_size(pos2(r.left() + 26.0, r.center().y), vec2(18.0, 18.0)), icons::tool_icon(item), 14.0, t.icon);+ ui.painter().text(pos2(r.left() + 42.0, r.center().y), Align2::LEFT_CENTER, item.label(), egui::FontId::proportional(12.5), t.text);+ if item.key() != '\0' {+ ui.painter().text(pos2(r.right() - 8.0, r.center().y), Align2::RIGHT_CENTER, item.key().to_string(), egui::FontId::proportional(12.0), t.text_dim);+ }+ if ir.clicked() {+ app.ui.tool = item;+ ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id));+ }+ }+ });+ });+ let clicked_outside = ui.input(|i| i.pointer.any_click()) && !area.response.hovered() && !resp.hovered();+ if clicked_outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id));+ }+ }+ }+ });}}ui.add_space(14.0);@@ -160,10 +242,22 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {icons::paint(ui, r, "chevron-down", 10.0, t.text_faint);}widgets::vline(ui, 22.0);+ if app.ui.transform.is_some() {+ crate::transform_tool::options_bar(app, ui);+ return;+ }+ let tool = app.ui.tool;+ if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Eraser)) || tool == Tool::QuickSelection {+ brush_preset_chip(ui, &mut app.session.tools.brush);+ widgets::vline(ui, 22.0);+ }+ if crate::retouch_ui::options_bar(app, ui, tool) || crate::vector_ui::options_bar(app, ui, tool) {+ return;+ }let b = &mut app.session.tools.brush;match app.ui.tool {Tool::Brush | Tool::Eraser if t.pro => {- brush_preset_chip(ui, b.size, b.hardness);+ brush_preset_chip(ui, b);widgets::vline(ui, 22.0);opt_label(ui, "Mode");let mut mode = BlendMode::Normal;@@ -235,8 +329,87 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let mut style = 0u8;widgets::dropdown(ui, "marquee-style", &mut style, &[(0u8, "Normal"), (1, "Fixed Ratio"), (2, "Fixed Size")], 96.0);widgets::vline(ui, 22.0);- let _ = widgets::secondary_button(ui, "Select and Mask…", 0.0);+ if widgets::secondary_button(ui, "Select and Mask…", 0.0).clicked() {+ let _ = crate::menus::invoke(app, ui.ctx(), "select.selectAndMask", json!({}));+ }+ }+ Tool::Lasso | Tool::PolygonLasso if t.pro => {+ selection_mode_buttons(app, ui);+ widgets::vline(ui, 22.0);+ opt_label(ui, "Feather");+ widgets::value_field(ui, &mut app.ui.tool_options.feather, 0.0..=1000.0, "px", 62.0);+ widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, "Anti-alias");+ widgets::vline(ui, 22.0);+ if widgets::secondary_button(ui, "Select and Mask…", 0.0).clicked() {+ let _ = crate::menus::invoke(app, ui.ctx(), "select.selectAndMask", json!({}));+ }+ if app.ui.tool == Tool::PolygonLasso && !app.ui.polygon.is_empty() {+ hint(ui, "Click the first point or press ↵ to close · Esc cancels");+ }+ }+ Tool::MagicWand if t.pro => {+ selection_mode_buttons(app, ui);+ widgets::vline(ui, 22.0);+ opt_label(ui, "Tolerance");+ widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0);+ widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, "Anti-alias");+ widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, "Contiguous");+ widgets::checkbox(ui, &mut app.ui.tool_options.sample_all_layers, "Sample All Layers");+ widgets::vline(ui, 22.0);+ if widgets::secondary_button(ui, "Select Subject", 0.0).clicked() {+ let _ = app.run("select.subject", json!({}));+ }+ if widgets::secondary_button(ui, "Select and Mask…", 0.0).clicked() {+ let _ = crate::menus::invoke(app, ui.ctx(), "select.selectAndMask", json!({}));+ }+ }+ Tool::PaintBucket if t.pro => {+ opt_label(ui, "Fill");+ let mut src = 0u8;+ widgets::dropdown(ui, "bucket-src", &mut src, &[(0u8, "Foreground"), (1, "Pattern")], 100.0);+ opt_label(ui, "Opacity");+ widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);+ opt_label(ui, "Tolerance");+ widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0);+ widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, "Anti-alias");+ widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, "Contiguous");+ widgets::checkbox(ui, &mut app.ui.tool_options.sample_all_layers, "All Layers");+ }+ Tool::Gradient if t.pro => {+ gradient_swatch(ui, app.session.tools.foreground, app.session.tools.background);+ widgets::vline(ui, 22.0);+ ui.spacing_mut().item_spacing.x = 2.0;+ for (style, icon, tip) in [("linear", "blend", "Linear Gradient"), ("radial", "circle", "Radial Gradient"), ("angle", "rotate-cw", "Angle Gradient"), ("reflected", "arrow-left-right", "Reflected Gradient"), ("diamond", "diamond", "Diamond Gradient")] {+ if icons::button(ui, icon, 24.0, app.ui.tool_options.gradient_style == style, tip).clicked() {+ app.ui.tool_options.gradient_style = style.into();+ }+ }+ ui.spacing_mut().item_spacing.x = 8.0;+ widgets::vline(ui, 22.0);+ opt_label(ui, "Opacity");+ widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);+ widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, "Reverse");+ let mut dither = true;+ widgets::checkbox(ui, &mut dither, "Dither");+ }+ Tool::Crop if t.pro => {+ let mut ratio = 0u8;+ widgets::dropdown(ui, "crop-ratio", &mut ratio, &[(0u8, "Ratio"), (1, "1 : 1 (Square)"), (2, "4 : 5 (8 : 10)"), (3, "16 : 9"), (4, "Original Ratio")], 120.0);+ widgets::vline(ui, 22.0);+ let _ = widgets::secondary_button(ui, "Clear", 0.0);+ let _ = icons::button(ui, "grid-3x3", 24.0, true, "Overlay: Rule of Thirds");+ let mut del = true;+ widgets::checkbox(ui, &mut del, "Delete Cropped Pixels");+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if icons::button(ui, "check", 26.0, false, "Commit current crop operation (↵)").clicked() {+ crate::canvas::commit_crop(app);+ }+ if icons::button(ui, "ban", 26.0, false, "Cancel current crop operation (Esc)").clicked() {+ app.ui.crop_rect = None;+ }+ });}+ Tool::Type if t.pro => crate::type_tool::options_bar(app, ui),Tool::Move if t.pro => {let mut auto = false;widgets::checkbox(ui, &mut auto, "Auto-Select:");@@ -270,6 +443,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}}Tool::Hand => hint(ui, "Drag to pan · hold Space with any tool"),+ Tool::Lasso | Tool::PolygonLasso => hint(ui, "Drag (lasso) or click points (polygonal) · ⇧ add · ⌥ subtract"),+ Tool::MagicWand => hint(ui, "Click to select similar colours"),+ Tool::Crop => hint(ui, "Drag a crop box · ↵ commits · Esc cancels"),+ Tool::Gradient => hint(ui, "Drag to draw a gradient"),+ Tool::PaintBucket => hint(ui, "Click to fill similar colours"),+ Tool::Type => hint(ui, "Click to add text"),+ // Retouching and smart-selection tools draw their bar in `retouch_ui::options_bar`.+ _ => {}}});});@@ -344,7 +525,7 @@ pub fn right_dock(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}// Narrow icon rail (always visible) that toggles panels.let (rw, rb) = if t.pro { (36.0, 28.0) } else { (44.0, 32.0) };- egui::Panel::right("rail").resizable(false).exact_size(rw).frame(egui::Frame::NONE.fill(if t.pro { t.chrome } else { t.chrome }).inner_margin(egui::Margin::symmetric(4, 8))).show(ui, |ui| {+ egui::Panel::right("rail").resizable(false).exact_size(rw).frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(4, 8))).show(ui, |ui| {let r = ui.max_rect();ui.painter().line_segment([r.left_top() - vec2(6.0, 8.0), r.left_bottom() + vec2(-6.0, 8.0)], Stroke::new(1.0, t.separator));ui.spacing_mut().item_spacing.y = 4.0;@@ -375,7 +556,7 @@ pub fn right_dock(app: &mut PhotocraftApp, ui: &mut egui::Ui) {fn dock_panels(app: &mut PhotocraftApp, ui: &mut egui::Ui, p: &crate::state::Panels, t: &Tokens) {let p = p.clone();- if !(p.layers || p.history || p.color || p.navigator) {+ if !(p.layers || p.history || p.color || p.navigator || (t.pro && p.properties)) {return;}let margin = if t.pro { 2 } else { 8 };@@ -397,23 +578,34 @@ fn dock_panels(app: &mut PhotocraftApp, ui: &mut egui::Ui, p: &crate::state::Pan}if t.pro && p.properties {let mut sel = app.ui.dock_tabs.properties;- widgets::card(ui, "properties", &["Properties", "Adjustments"], &mut sel, |ui, tab| if tab == 0 { properties_body(app, ui) } else { adjustments_grid(app, ui) });+ // Leave Layers at least ~240 px; Properties scrolls within what remains.+ let reserve = if p.layers { 240.0 } else { 40.0 };+ let max_h = (ui.available_height() - reserve - 40.0).max(70.0);+ widgets::card(ui, "properties", &["Properties", "Adjustments"], &mut sel, |ui, tab| {+ egui::ScrollArea::vertical().id_salt("props-scroll").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| if tab == 0 { properties_body(app, ui) } else { adjustments_grid(app, ui) });+ });app.ui.dock_tabs.properties = sel;}if p.navigator {- let mut sel = 0;- widgets::card(ui, "navigator", &["Navigator", "Histogram"], &mut sel, |ui, tab| if tab == 0 { navigator(app, ui) } else { empty(ui, "Histogram arrives with the GPU pipeline (M5)") });+ let mut sel = app.ui.dock_tabs.navigator;+ widgets::card(ui, "navigator", &["Navigator", "Histogram", "Info"], &mut sel, |ui, tab| match tab {+ 0 => navigator(app, ui),+ 1 => crate::tone::histogram_panel(app, ui),+ _ => info_panel(app, ui),+ });+ app.ui.dock_tabs.navigator = sel;}if p.history {- let mut sel = 0;- widgets::card(ui, "history", &["History"], &mut sel, |ui, _| history(app, ui));+ let mut sel = app.ui.dock_tabs.history;+ widgets::card(ui, "history", &["History", "Actions"], &mut sel, |ui, tab| if tab == 0 { history(app, ui) } else { crate::actions::panel(app, ui) });+ app.ui.dock_tabs.history = sel;}if p.layers {let mut sel = app.ui.dock_tabs.layers;widgets::card(ui, "layers", &["Layers", "Channels", "Paths"], &mut sel, |ui, tab| match tab {0 => layers(app, ui),1 => channels(app, ui),- _ => empty(ui, "No paths"),+ _ => crate::vector_ui::paths_panel(app, ui),});app.ui.dock_tabs.layers = sel;}@@ -427,6 +619,62 @@ fn dock_panels(app: &mut PhotocraftApp, ui: &mut egui::Ui, p: &crate::state::Pan});}+/// Photoshop's Info panel: colour under the pointer (RGB and CMYK), position, selection size.+fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ let Some(st) = app.session.active() else {+ empty(ui, "No document");+ return;+ };+ let (rev, size) = (st.revision, st.doc.size);+ let sel = st.doc.selection.as_ref().map(|m| m.content_bounds());+ let pos = app.hover_doc.map(|p| (p[0].floor() as i32, p[1].floor() as i32)).filter(|(x, y)| *x >= 0 && *y >= 0 && *x < size.width as i32 && *y < size.height as i32);+ let rgba = pos.and_then(|(x, y)| {+ if let Some(((cx, cy, cr), v)) = app.info_sample+ && (cx, cy, cr) == (x, y, rev)+ {+ return Some(v);+ }+ let v: Vec<f32> = serde_json::from_value(app.session.execute("document.pixel", json!({"x": x, "y": y})).ok()?).ok()?;+ let v = [v[0], v[1], v[2], v[3]];+ app.info_sample = Some(((x, y, rev), v));+ Some(v)+ });+ let mono = theme::mono(11.5);+ let row = |ui: &mut egui::Ui, k: &str, v: String| {+ ui.horizontal(|ui| {+ ui.add_sized([18.0, 16.0], egui::Label::new(RichText::new(k).color(t.text_dim).size(11.5)));+ ui.label(RichText::new(v).font(mono.clone()).color(t.text));+ });+ };+ ui.columns(2, |cols| {+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32;+ let dash = || "—".to_string();+ row(&mut cols[0], "R:", rgba.map_or_else(dash, |c| q(c[0]).to_string()));+ row(&mut cols[0], "G:", rgba.map_or_else(dash, |c| q(c[1]).to_string()));+ row(&mut cols[0], "B:", rgba.map_or_else(dash, |c| q(c[2]).to_string()));+ // Naive device CMYK (no ICC profile yet), in percent like Photoshop's readout.+ let cmyk = rgba.map(|c| {+ let k = 1.0 - c[0].max(c[1]).max(c[2]);+ let f = |v: f32| if k >= 1.0 { 0.0 } else { (1.0 - v - k) / (1.0 - k) };+ [f(c[0]), f(c[1]), f(c[2]), k].map(|v| (v * 100.0).round() as i32)+ });+ for (i, k) in ["C:", "M:", "Y:", "K:"].iter().enumerate() {+ row(&mut cols[1], k, cmyk.map_or_else(dash, |c| format!("{}%", c[i])));+ }+ });+ widgets::hairline(ui);+ ui.columns(2, |cols| {+ let dash = || "—".to_string();+ row(&mut cols[0], "X:", pos.map_or_else(dash, |p| p.0.to_string()));+ row(&mut cols[0], "Y:", pos.map_or_else(dash, |p| p.1.to_string()));+ row(&mut cols[1], "W:", sel.map_or_else(dash, |r| r.width().to_string()));+ row(&mut cols[1], "H:", sel.map_or_else(dash, |r| r.height().to_string()));+ });+ widgets::hairline(ui);+ ui.label(RichText::new(format!("Doc: {} × {} px", size.width, size.height)).color(t.text_dim).size(11.5));+}+fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let t = Tokens::get(ui.ctx());let Some(idx) = app.session.active_index() else {@@ -577,8 +825,15 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {icons::paint(ui, Rect::from_center_size(r.left_center() + vec2(11.0, 0.0), vec2(14.0, 14.0)), "search", 11.0, t.text_faint);ui.painter().text(r.left_center() + vec2(22.0, 0.0), Align2::LEFT_CENTER, "Kind", egui::FontId::proportional(11.5), t.text_dim);ui.add_space(4.0);- for (icon, tip) in [("image", "Pixel layers"), ("contrast", "Adjustment layers"), ("type", "Type layers"), ("square", "Shape layers"), ("app-window", "Smart objects")] {- let _ = icons::button(ui, icon, 22.0, false, tip);+ for (kind, icon, tip) in [("pixel", "image", "Filter for pixel layers"), ("adjustment", "contrast", "Filter for adjustment layers"), ("type", "type", "Filter for type layers"), ("shape", "square", "Filter for shape layers"), ("smart", "app-window", "Filter for smart objects")] {+ let on = app.ui.layer_filter.iter().any(|k| k == kind);+ if icons::button(ui, icon, 22.0, on, tip).clicked() {+ if on {+ app.ui.layer_filter.retain(|k| k != kind);+ } else {+ app.ui.layer_filter.push(kind.to_string());+ }+ }}});ui.add_space(4.0);@@ -602,14 +857,24 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {label(ui, if t.pro { "Lock:" } else { "Lock" });if t.pro {ui.spacing_mut().item_spacing.x = 0.0;- for (icon, tip) in [("grid-3x3", "Lock transparent pixels"), ("brush", "Lock image pixels"), ("move", "Lock position"), ("scan", "Prevent auto-nesting"), ("lock", "Lock all")] {- let on = icon == "lock" && (l.locks.all || l.locks.transparency || l.locks.position);- let _ = icons::button(ui, icon, 20.0, on, tip);+ let lk = l.locks;+ for (key, icon, tip, on) in [+ ("transparency", "grid-3x3", "Lock transparent pixels", lk.transparency),+ ("pixels", "brush", "Lock image pixels", lk.pixels),+ ("position", "move", "Lock position", lk.position),+ ("artboard", "scan", "Prevent auto-nesting in and out of Artboards and Frames", lk.artboard),+ ("all", "lock", "Lock all", lk.all),+ ] {+ if icons::button(ui, icon, 20.0, on, tip).clicked() {+ actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "locks": { key: !on }})));+ }}}if !t.pro {let locked = l.locks.transparency || l.locks.position || l.locks.all;- let _ = icons::button(ui, if locked { "lock" } else { "lock-open" }, 22.0, locked, "Lock layer");+ if icons::button(ui, if locked { "lock" } else { "lock-open" }, 22.0, locked, "Lock layer").clicked() {+ actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "locks": {"all": !l.locks.all}})));+ }}ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {let mut f = l.fill_opacity * 100.0;@@ -628,7 +893,21 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let fill = t.pro && ui.available_height() > footer + 60.0;let rows_h = if fill { ui.available_height() - footer } else { f32::INFINITY };egui::ScrollArea::vertical().id_salt("layer-rows").max_height(rows_h).min_scrolled_height(if fill { rows_h } else { 0.0 }).auto_shrink([false, !fill]).show(ui, |ui| {+ let filter = app.ui.layer_filter.clone();for (_, depth, l) in rows.iter().rev() {+ if !filter.is_empty() {+ let kind = match &l.content {+ LayerContent::Raster(_) => "pixel",+ LayerContent::Adjustment(_) | LayerContent::Fill(_) => "adjustment",+ LayerContent::Text(_) => "type",+ LayerContent::Shape(_) => "shape",+ LayerContent::Smart(_) => "smart",+ LayerContent::Group(_) => "",+ };+ if !filter.iter().any(|k| k == kind) {+ continue;+ }+ }layer_row(app, &ctx, ui, &doc, l, *depth, active == Some(l.id), &mut actions);if !l.effects.items.is_empty() {effect_rows(app, ui, l, *depth);@@ -700,6 +979,10 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {});});for (id, p) in actions {+ if id == "ui.maskTarget" {+ app.ui.mask_target = p.as_bool().unwrap_or(false);+ continue;+ }let _ = app.run(&id, p);}}@@ -742,12 +1025,27 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, dolet thumb = Rect::from_min_size(pos2(x, rect.center().y - ts / 2.0), vec2(ts, ts));draw_layer_thumb(app, ctx, ui, doc, l, thumb, selected);x += ts + 6.0;+ let mut mask_rect = None;if let Some(m) = &l.mask {- let mr = Rect::from_min_size(pos2(x, rect.center().y - 17.0), vec2(34.0, 34.0));+ let mr = Rect::from_min_size(pos2(x, rect.center().y - ts / 2.0), vec2(ts, ts));let tex = app.mask_thumb(ctx, doc, l.id, m);painter.image(tex, mr, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);- painter.rect_stroke(mr, 4.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);- x += 40.0;+ painter.rect_stroke(mr, if t.pro { 0.0 } else { 4.0 }, Stroke::new(1.0, if t.pro { Color32::from_gray(20) } else { t.field_border }), StrokeKind::Outside);+ mask_rect = Some(mr);+ x += ts + 6.0;+ }+ // Photoshop frames the targeted thumbnail (pixels or mask) of the selected layer with corner brackets.+ if selected {+ let target = if app.ui.mask_target { mask_rect } else { Some(thumb) };+ if let Some(r) = target.filter(|_| l.mask.is_some() || !app.ui.mask_target) {+ let r = r.expand(3.0);+ let k = 6.0;+ let st = Stroke::new(1.5, t.text);+ for (c, dx, dy) in [(r.left_top(), 1.0, 1.0), (r.right_top(), -1.0, 1.0), (r.right_bottom(), -1.0, -1.0), (r.left_bottom(), 1.0, -1.0)] {+ painter.line_segment([c, c + vec2(k * dx, 0.0)], st);+ painter.line_segment([c, c + vec2(0.0, k * dy)], st);+ }+ }}let name_color = if l.visible { t.text } else { t.text_faint };let font = if selected && !t.pro { theme::medium(13.0) } else { egui::FontId::proportional(if t.pro { 12.0 } else { 13.0 }) };@@ -778,6 +1076,16 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do}if resp.clicked() && !eye_resp.clicked() {actions.push(("layer.select".into(), json!({"layer": l.id.0})));+ // Clicking a thumbnail picks what painting targets; adjustment/fill layers target their mask.+ let pos = resp.interact_pointer_pos();+ let on_mask = mask_rect.zip(pos).is_some_and(|(r, p)| r.expand(2.0).contains(p));+ let on_thumb = pos.is_some_and(|p| thumb.expand(2.0).contains(p));+ let content_less = matches!(l.content, LayerContent::Adjustment(_) | LayerContent::Fill(_));+ if on_mask || (content_less && l.mask.is_some()) {+ actions.push(("ui.maskTarget".into(), json!(true)));+ } else if on_thumb || !selected {+ actions.push(("ui.maskTarget".into(), json!(false)));+ }}// Double-click the name to rename in place (Photoshop ergonomics).let rename_id = egui::Id::new(("rename", l.id.0));@@ -848,6 +1156,11 @@ fn draw_layer_thumb(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &egui::Ui,let icon = if l.is_group() { "folder" } else { "contrast" };icons::paint(ui, rect, icon, 18.0, t.icon);}+ LayerContent::Text(_) => {+ // Photoshop: type layers show a "T" tile rather than a pixel thumbnail.+ p.rect_filled(rect, if t.pro { 0.0 } else { 6.0 }, Color32::from_gray(if t.pro { 222 } else { 236 }));+ icons::paint(ui, rect, "type", 20.0, Color32::from_gray(40));+ }LayerContent::Fill(f) => {let c = match f {photocraft_doc::Fill::Solid(c) => c.to_rgba8(),@@ -871,22 +1184,32 @@ fn channels(app: &mut PhotocraftApp, ui: &mut egui::Ui) {empty(ui, "No document");return;};- let names: Vec<&str> = match st.doc.mode {+ let doc = st.doc.clone();+ let names: Vec<&str> = match doc.mode {photocraft_doc::ColorMode::Cmyk => vec!["CMYK", "Cyan", "Magenta", "Yellow", "Black"],photocraft_doc::ColorMode::Grayscale => vec!["Gray"],photocraft_doc::ColorMode::Lab => vec!["Lab", "Lightness", "a", "b"],_ => vec!["RGB", "Red", "Green", "Blue"],};let t = Tokens::get(ui.ctx());+ let ctx = ui.ctx().clone();+ let thumbs = app.channel_thumbs(&ctx);for (i, n) in names.iter().enumerate() {- ui.horizontal(|ui| {- let (r, _) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::hover());- icons::paint(ui, r, "eye", 15.0, t.icon);- ui.label(RichText::new(*n).color(t.text));- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- ui.label(RichText::new(format!("⌘{}", i + 2)).font(theme::mono(11.0)).color(t.text_faint));- });- });+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());+ if i == 0 || resp.hovered() {+ ui.painter().rect_filled(rect, 0.0, if i == 0 { t.row_selected.gamma_multiply(if t.pro { 1.0 } else { 0.0 }) } else { t.hover.gamma_multiply(0.4) });+ }+ icons::paint(ui, Rect::from_min_size(pos2(rect.left() + 6.0, rect.center().y - 9.0), vec2(18.0, 18.0)), "eye", 13.0, t.icon);+ let thumb = Rect::from_min_size(pos2(rect.left() + 34.0, rect.center().y - 14.0), vec2(28.0, 28.0));+ if let Some(tex) = thumbs.get(i.min(thumbs.len().saturating_sub(1))) {+ ui.painter().image(*tex, thumb, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);+ }+ ui.painter().rect_stroke(thumb, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside);+ ui.painter().text(pos2(thumb.right() + 10.0, rect.center().y), Align2::LEFT_CENTER, *n, egui::FontId::proportional(12.0), t.text);+ ui.painter().text(pos2(rect.right() - 8.0, rect.center().y), Align2::RIGHT_CENTER, format!("⌘{}", i + 2), theme::mono(11.0), t.text_faint);+ if t.pro {+ ui.painter().line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator));+ }}}@@ -896,6 +1219,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {empty(ui, "No document");return;};+ let doc = st.doc.clone();let entries = st.history.entries();let current = entries.len() - 1;let redo: Vec<String> = {@@ -911,20 +1235,59 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}v};+ // Snapshot row (Photoshop shows the document's opening state with a thumbnail).+ {+ let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::hover());+ let thumb = Rect::from_min_size(pos2(rect.left() + 28.0, rect.center().y - 14.0), vec2(28.0, 28.0));+ let ctx = ui.ctx().clone();+ if let Some(layer) = doc.layers.first() {+ widgets::checker(ui.painter(), thumb, 4.0);+ let tex = app.layer_thumb(&ctx, &doc, layer);+ ui.painter().image(tex, thumb, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);+ }+ ui.painter().rect_stroke(thumb, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside);+ ui.painter().text(pos2(thumb.right() + 8.0, rect.center().y), Align2::LEFT_CENTER, &doc.name, egui::FontId::proportional(12.0), t.text);+ ui.painter().line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator));+ }let mut target: Option<isize> = None;let all = entries.iter().map(|e| (e.clone(), false)).chain(redo.iter().map(|e| (e.clone(), true)));- for (i, (e, is_redo)) in all.enumerate() {- let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click());- if i == current {- ui.painter().rect_filled(rect, t.radius_sm, t.accent_soft);- } else if resp.hovered() {- ui.painter().rect_filled(rect, t.radius_sm, t.hover);- }- let color = if is_redo { t.text_faint } else { t.text };- ui.painter().text(rect.left_center() + vec2(10.0, 0.0), Align2::LEFT_CENTER, &e, egui::FontId::proportional(12.5), color);- if resp.clicked() {- target = Some(i as isize - current as isize);+ // Leave room for Layers below (the dock gives Layers a height budget).+ let reserve = if app.ui.panels.layers { 250.0 } else { 0.0 };+ let max_h = (ui.available_height() - reserve - 40.0).clamp(60.0, 360.0);+ egui::ScrollArea::vertical().id_salt("history-rows").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| {+ for (i, (e, is_redo)) in all.enumerate() {+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click());+ if i == current {+ ui.painter().rect_filled(rect, if t.pro { 0.0 } else { t.radius_sm }, if t.pro { t.row_selected } else { t.accent_soft });+ } else if resp.hovered() {+ ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5));+ }+ let icon = match e.as_str() {+ s if s.contains("Brush") || s.contains("Eraser") => "brush",+ s if s.contains("Layer") => "layers",+ s if s.contains("Select") || s.contains("Marquee") || s.contains("Deselect") || s.contains("Lasso") => "square-dashed",+ s if s.contains("Fill") => "paint-bucket",+ "Open" => "image",+ _ => "sliders-horizontal",+ };+ let color = if is_redo { t.text_faint } else { t.text };+ icons::paint(ui, Rect::from_center_size(pos2(rect.left() + 42.0, rect.center().y), vec2(16.0, 16.0)), icon, 12.0, if is_redo { t.text_faint } else { t.icon });+ ui.painter().text(pos2(rect.left() + 58.0, rect.center().y), Align2::LEFT_CENTER, &e, egui::FontId::proportional(12.0), color);+ if resp.clicked() {+ target = Some(i as isize - current as isize);+ }}+ });+ if t.pro {+ widgets::hairline(ui);+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 2.0;+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ let _ = icons::button(ui, "trash", 24.0, false, "Delete current state");+ let _ = icons::button(ui, "scan", 24.0, false, "Create new snapshot");+ let _ = icons::button(ui, "file-plus", 24.0, false, "Create new document from current state");+ });+ });}if let Some(delta) = target {let (cmd, n) = if delta < 0 { ("edit.undo", -delta) } else { ("edit.redo", delta) };@@ -1045,7 +1408,13 @@ fn adjustment_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId,let mut commit = false;let mut live = false;let hue = widgets::hue_stops();- for &(key, label, min, max, default) in adjustment_sliders(kind) {+ let tone = matches!(kind, "levels" | "curves");+ if kind == "levels" {+ crate::tone::levels_editor(app, ui, id);+ } else if kind == "curves" {+ crate::tone::curves_editor(app, ui, id);+ }+ for &(key, label, min, max, default) in if tone { &[][..] } else { adjustment_sliders(kind) } {let mut v = values.get(key).and_then(Value::as_f64).unwrap_or(default as f64) as f32;let gradient = if key == "hue" { Some(&hue[..]) } else { None };let unit = match key {@@ -1070,7 +1439,7 @@ fn adjustment_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId,}ui.add_space(4.0);}- if adjustment_sliders(kind).is_empty() && kind != "invert" {+ if adjustment_sliders(kind).is_empty() && !tone && kind != "invert" {ui.label(RichText::new("Detailed controls for this adjustment arrive in milestone M7.").color(t.text_faint));}if live {@@ -1145,6 +1514,8 @@ fn properties_body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {LayerContent::Adjustment(_) => "sliders-horizontal",LayerContent::Group(_) => "folder",LayerContent::Fill(_) => "paint-bucket",+ LayerContent::Text(_) => "type",+ LayerContent::Shape(_) => "pentagon",_ => "image",};let (r, _) = ui.allocate_exact_size(vec2(20.0, 20.0), Sense::hover());@@ -1162,6 +1533,12 @@ fn properties_body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {adjustment_controls(app, ui, id, adj);} else {layer_controls(app, ui, &layer);+ if matches!(layer.content, LayerContent::Text(_)) {+ crate::type_tool::type_properties(app, ui);+ }+ if matches!(layer.content, LayerContent::Shape(_)) {+ crate::vector_ui::shape_properties(app, ui, id);+ }}}@@ -1307,42 +1684,73 @@ fn hsva_srgb(h: egui::ecolor::Hsva) -> [f32; 4] {[r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0]}-#[cfg(test)]-mod color_tests {- use super::*;-- #[test]- fn srgb_hsva_roundtrip() {- for c in [[0.847, 0.271, 0.180, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.2, 0.6, 0.4, 1.0]] {- let back = hsva_srgb(srgb_hsva(c));- for i in 0..3 {- assert!((back[i] - c[i]).abs() <= 1.0 / 255.0, "{c:?} -> {back:?}");- }- }+/// Photoshop's brush preset picker chip: a soft/hard round tip preview with the size underneath.+/// Draw a round brush tip preview (hard core fading to a soft edge).+fn brush_tip(p: &egui::Painter, c: egui::Pos2, rad: f32, hardness: f32, color: Color32) {+ let inner = rad * hardness.clamp(0.05, 1.0);+ let steps = 8;+ for k in (0..=steps).rev() {+ let f = k as f32 / steps as f32;+ let rr = inner + (rad - inner) * f;+ let a = if hardness >= 0.99 { 1.0 } else { (1.0 - f).powf(1.5) };+ p.circle_filled(c, rr, color.gamma_multiply(a));}}-/// Photoshop's brush preset picker chip: a soft/hard round tip preview with the size underneath.-fn brush_preset_chip(ui: &mut egui::Ui, size: f32, hardness: f32) {+/// Options-bar brush chip; opens Photoshop's Brush Preset Picker (size, hardness, preset tips).+fn brush_preset_chip(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings) {let t = Tokens::get(ui.ctx());let (r, resp) = ui.allocate_exact_size(vec2(44.0, 30.0), Sense::click());if resp.hovered() {ui.painter().rect_filled(r, t.radius_sm, t.hover);}let c = pos2(r.left() + 14.0, r.top() + 11.0);- // soft edge: concentric circles fading out- let rad = 7.0;- let inner = rad * hardness.clamp(0.05, 1.0);- let steps = 6;- for k in (0..=steps).rev() {- let f = k as f32 / steps as f32;- let rr = inner + (rad - inner) * f;- let a = if hardness >= 0.99 { 255 } else { (255.0 * (1.0 - f).powf(1.5)) as u8 };- ui.painter().circle_filled(c, rr, Color32::from_white_alpha(a));- }- ui.painter().text(pos2(c.x, r.bottom() - 5.0), Align2::CENTER_CENTER, format!("{}", size.round() as i64), egui::FontId::proportional(9.5), t.text_dim);+ brush_tip(ui.painter(), c, 7.0, b.hardness, Color32::WHITE);+ ui.painter().text(pos2(c.x, r.bottom() - 5.0), Align2::CENTER_CENTER, format!("{}", b.size.round() as i64), egui::FontId::proportional(9.5), t.text_dim);icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, c.y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint);- resp.on_hover_text("Brush preset picker (size and hardness in the options bar and with [ ])");+ let resp = resp.on_hover_text("Brush Preset picker");+ egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {+ ui.set_width(260.0);+ // Size: value field plus a logarithmic slider (small sizes get most of the travel).+ ui.horizontal(|ui| {+ ui.label(RichText::new("Size").color(t.text_dim));+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ let mut size = b.size;+ if widgets::value_field(ui, &mut size, 1.0..=5000.0, "px", 72.0).changed() {+ b.size = size.round().clamp(1.0, 5000.0);+ }+ });+ });+ let mut lv = b.size.max(1.0).ln();+ if widgets::slider(ui, &mut lv, 0.0..=5000f32.ln(), None).changed() {+ b.size = lv.exp().round().clamp(1.0, 5000.0);+ }+ let mut hard = b.hardness * 100.0;+ if widgets::slider_row(ui, "Hardness", &mut hard, 0.0..=100.0, "%", None).changed() {+ b.hardness = (hard / 100.0).clamp(0.0, 1.0);+ }+ ui.add_space(6.0);+ widgets::hairline(ui);+ ui.add_space(6.0);+ ui.label(RichText::new("General Brushes").color(t.text_dim).size(11.5));+ // Photoshop's default round presets: soft and hard at common sizes.+ let presets: [(f32, f32); 12] = [(1.0, 1.0), (3.0, 1.0), (5.0, 1.0), (9.0, 1.0), (13.0, 1.0), (19.0, 1.0), (5.0, 0.0), (9.0, 0.0), (13.0, 0.0), (17.0, 0.0), (45.0, 0.0), (65.0, 0.0)];+ ui.horizontal_wrapped(|ui| {+ ui.spacing_mut().item_spacing = vec2(4.0, 4.0);+ for (sz, hd) in presets {+ let (cell, cr) = ui.allocate_exact_size(vec2(38.0, 44.0), Sense::click());+ let on = (b.size - sz).abs() < 0.5 && (b.hardness - hd).abs() < 0.01;+ ui.painter().rect_filled(cell, 3.0, if on { t.accent_soft } else if cr.hovered() { t.hover } else { t.field });+ let rad = (sz / 2.0).clamp(1.0, 13.0);+ brush_tip(ui.painter(), pos2(cell.center().x, cell.top() + 17.0), rad, hd, t.text);+ ui.painter().text(pos2(cell.center().x, cell.bottom() - 7.0), Align2::CENTER_CENTER, format!("{}", sz as i64), egui::FontId::proportional(9.5), t.text_dim);+ if cr.on_hover_text(format!("{} Round {sz:.0} px", if hd >= 1.0 { "Hard" } else { "Soft" })).clicked() {+ b.size = sz;+ b.hardness = hd;+ }+ }+ });+ });}/// Drag a layer row to reorder: drop on the upper/lower half to place above/below, or on the middle@@ -1427,3 +1835,45 @@ fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usi}}}++/// New / add / subtract / intersect selection buttons (shared by selection tools).+fn selection_mode_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ ui.spacing_mut().item_spacing.x = 2.0;+ for (i, (icon, tip)) in [("square", "New selection"), ("plus", "Add to selection (⇧)"), ("minus", "Subtract from selection (⌥)"), ("squares-subtract", "Intersect with selection (⇧⌥)")].iter().enumerate() {+ if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() {+ app.ui.selection_mode = i as u8;+ }+ }+ ui.spacing_mut().item_spacing.x = 8.0;+}++/// Gradient picker swatch (foreground → background), Photoshop options-bar style.+fn gradient_swatch(ui: &mut egui::Ui, a: [f32; 4], b: [f32; 4]) {+ let t = Tokens::get(ui.ctx());+ let (r, resp) = ui.allocate_exact_size(vec2(96.0, 20.0), Sense::click());+ let mut mesh = egui::Mesh::default();+ mesh.colored_vertex(r.left_top(), c32(a));+ mesh.colored_vertex(r.right_top(), c32(b));+ mesh.colored_vertex(r.right_bottom(), c32(b));+ mesh.colored_vertex(r.left_bottom(), c32(a));+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(0, 2, 3);+ ui.painter().add(mesh);+ ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);+ let _ = resp.on_hover_text("Click to edit the gradient");+}++#[cfg(test)]+mod color_tests {+ use super::*;++ #[test]+ fn srgb_hsva_roundtrip() {+ for c in [[0.847, 0.271, 0.180, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.2, 0.6, 0.4, 1.0]] {+ let back = hsva_srgb(srgb_hsva(c));+ for i in 0..3 {+ assert!((back[i] - c[i]).abs() <= 1.0 / 255.0, "{c:?} -> {back:?}");+ }+ }+ }+}diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rsnew file mode 100644index 000000000..5c75d76ef--- /dev/null+++ b/crates/ui-egui/src/retouch_ui.rs@@ -0,0 +1,181 @@+//! UI for the retouching tools (healing, clone, history brush, blur/sharpen/smudge, dodge/burn/+//! sponge) and the smart selection tools (Quick Selection, Object Selection): gesture → engine+//! command, options bars, and the clone-source marker.++use egui::{Color32, Stroke, vec2};+use serde_json::{Value, json};++use crate::PhotocraftApp;+use crate::canvas::ViewXform;+use crate::state::Tool;+use crate::theme::Tokens;++/// Finish a stroke with a retouching tool. Returns false if `tool` isn't one.+pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], mods: egui::Modifiers) -> bool {+ let o = app.ui.tool_options.clone();+ let pts = json!(points);+ let (cmd, mut p): (&str, Value) = match tool {+ Tool::SpotHealing => ("paint.spotHealing", json!({"type": o.spot_type})),+ Tool::Healing | Tool::CloneStamp => {+ let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample});+ match (app.ui.clone_offset.filter(|_| o.clone_aligned), app.ui.clone_source) {+ (Some(off), _) => p["offset"] = json!(off),+ (None, Some(src)) => p["source"] = json!(src),+ (None, None) => {+ app.ui.status = "Option-click to define a source point to clone from".into();+ app.ui.status_error = true;+ return true;+ }+ }+ (if tool == Tool::Healing { "paint.healingBrush" } else { "paint.cloneStamp" }, p)+ }+ Tool::HistoryBrush => ("paint.historyBrush", json!({})),+ Tool::Blur => ("paint.blur", json!({"strength": o.strength})),+ Tool::Sharpen => ("paint.sharpen", json!({"strength": o.strength, "protectDetail": o.protect_detail})),+ Tool::Smudge => ("paint.smudge", json!({"strength": o.strength, "fingerPainting": o.finger_painting})),+ Tool::Dodge | Tool::Burn => (if tool == Tool::Dodge { "paint.dodge" } else { "paint.burn" }, json!({"range": o.tone_range, "exposure": o.exposure, "protectTones": o.protect_tones})),+ Tool::Sponge => ("paint.sponge", json!({"mode": o.sponge_mode, "vibrance": o.vibrance})),+ Tool::QuickSelection => {+ let size = app.session.tools.brush.size;+ let mode = if mods.alt { "subtract" } else { "add" };+ let xy: Vec<[f64; 2]> = points.iter().map(|q| [q[0], q[1]]).collect();+ let _ = app.run("select.quick", json!({"points": xy, "size": size, "mode": mode, "enhanceEdge": o.enhance_edge, "sampleAllLayers": o.sample_all_layers}));+ return true;+ }+ _ => return false,+ };+ p["points"] = pts;+ match app.run(cmd, p) {+ Ok(r) if matches!(tool, Tool::Healing | Tool::CloneStamp) => {+ // Aligned: keep the offset for later strokes; non-aligned: every stroke restarts at the source.+ app.ui.clone_offset = r.get("offset").and_then(|v| serde_json::from_value(v.clone()).ok()).filter(|_| o.clone_aligned);+ }+ Ok(_) => {}+ Err(e) => {+ app.ui.status = e;+ app.ui.status_error = true;+ }+ }+ true+}++/// Object Selection: the dragged rectangle.+pub fn finish_object_selection(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) {+ let (x, y) = (start[0].min(end[0]), start[1].min(end[1]));+ let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs());+ if w < 2.0 || h < 2.0 {+ return;+ }+ let mode = if mods.alt { "subtract" } else if mods.shift { "add" } else { "replace" };+ let _ = app.run("select.object", json!({"rect": [x.round(), y.round(), w.round(), h.round()], "mode": mode, "sampleAllLayers": app.ui.tool_options.sample_all_layers}));+}++/// ⌥-click with Clone Stamp / Healing Brush sets the source.+pub fn set_source(app: &mut PhotocraftApp, x: f64, y: f64) {+ app.ui.clone_source = Some([x.round(), y.round()]);+ app.ui.clone_offset = None;+ app.ui.status = format!("Clone source set at {:.0}, {:.0}", x, y);+ app.ui.status_error = false;+}++/// Crosshair where the clone source is sampled from for the current pointer position.+pub fn draw_source_marker(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {+ if !matches!(app.ui.tool, Tool::CloneStamp | Tool::Healing) {+ return;+ }+ let src = match (app.ui.clone_offset, app.hover_doc, app.ui.clone_source) {+ (Some(off), Some(h), _) => Some([h[0] + off[0], h[1] + off[1]]),+ (None, _, Some(s)) => Some(s),+ _ => None,+ };+ let Some(s) = src else { return };+ let c = xf.to_screen(s[0] as f32, s[1] as f32);+ for (w, col) in [(3.0, Color32::from_black_alpha(160)), (1.0, Color32::WHITE)] {+ painter.line_segment([c - vec2(7.0, 0.0), c + vec2(7.0, 0.0)], Stroke::new(w, col));+ painter.line_segment([c - vec2(0.0, 7.0), c + vec2(0.0, 7.0)], Stroke::new(w, col));+ }+}++fn opt(ui: &mut egui::Ui, text: &str) {+ let t = Tokens::get(ui.ctx());+ ui.label(egui::RichText::new(text).color(t.text_dim).size(12.0));+}++fn pct(ui: &mut egui::Ui, label: &str, v: &mut f32) {+ opt(ui, label);+ crate::widgets::value_field(ui, v, 1.0..=100.0, "%", 58.0);+}++/// Options bar for the retouching and smart-selection tools. Returns false for other tools.+pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {+ if !tool.is_brushlike() && !matches!(tool, Tool::QuickSelection | Tool::ObjectSelection) || matches!(tool, Tool::Brush | Tool::Eraser) {+ return false;+ }+ let o = &mut app.ui.tool_options;+ match tool {+ Tool::SpotHealing => {+ opt(ui, "Type:");+ for (k, l) in [("contentAware", "Content-Aware"), ("createTexture", "Create Texture"), ("proximityMatch", "Proximity Match")] {+ let mut on = o.spot_type == k;+ if crate::widgets::checkbox(ui, &mut on, l).clicked() {+ o.spot_type = k.into();+ }+ }+ crate::widgets::vline(ui, 22.0);+ crate::widgets::checkbox(ui, &mut o.sample_all_layers, "Sample All Layers");+ }+ Tool::Healing | Tool::CloneStamp => {+ crate::widgets::checkbox(ui, &mut o.clone_aligned, "Aligned");+ opt(ui, "Sample:");+ let opts = [("current".to_string(), "Current Layer"), ("currentAndBelow".to_string(), "Current & Below"), ("all".to_string(), "All Layers")];+ crate::widgets::dropdown(ui, "clone-sample", &mut o.clone_sample, &opts, 130.0);+ if app.ui.clone_source.is_none() {+ crate::widgets::vline(ui, 22.0);+ opt(ui, "⌥-click to set the source");+ }+ }+ Tool::Dodge | Tool::Burn => {+ opt(ui, "Range:");+ let opts = [("shadows".to_string(), "Shadows"), ("midtones".to_string(), "Midtones"), ("highlights".to_string(), "Highlights")];+ crate::widgets::dropdown(ui, "tone-range", &mut o.tone_range, &opts, 100.0);+ pct(ui, "Exposure:", &mut o.exposure);+ crate::widgets::checkbox(ui, &mut o.protect_tones, "Protect Tones");+ }+ Tool::Sponge => {+ opt(ui, "Mode:");+ let opts = [("desaturate".to_string(), "Desaturate"), ("saturate".to_string(), "Saturate")];+ crate::widgets::dropdown(ui, "sponge-mode", &mut o.sponge_mode, &opts, 110.0);+ crate::widgets::checkbox(ui, &mut o.vibrance, "Vibrance");+ }+ Tool::Blur | Tool::Sharpen | Tool::Smudge => {+ pct(ui, "Strength:", &mut o.strength);+ crate::widgets::checkbox(ui, &mut o.sample_all_layers, "Sample All Layers");+ if tool == Tool::Sharpen {+ crate::widgets::checkbox(ui, &mut o.protect_detail, "Protect Detail");+ }+ if tool == Tool::Smudge {+ crate::widgets::checkbox(ui, &mut o.finger_painting, "Finger Painting");+ }+ }+ Tool::HistoryBrush => opt(ui, "Paints from the document's opening state"),+ Tool::QuickSelection => {+ crate::widgets::checkbox(ui, &mut o.sample_all_layers, "Sample All Layers");+ crate::widgets::checkbox(ui, &mut o.enhance_edge, "Enhance Edge");+ opt(ui, "⌥ to subtract");+ crate::widgets::vline(ui, 22.0);+ if crate::widgets::secondary_button(ui, "Select Subject", 0.0).clicked() {+ let _ = app.run("select.subject", json!({}));+ }+ }+ Tool::ObjectSelection => {+ crate::widgets::checkbox(ui, &mut o.sample_all_layers, "Sample All Layers");+ opt(ui, "Drag a rectangle around the object");+ crate::widgets::vline(ui, 22.0);+ if crate::widgets::secondary_button(ui, "Select Subject", 0.0).clicked() {+ let _ = app.run("select.subject", json!({}));+ }+ }+ _ => {}+ }+ true+}diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/rulers.rsnew file mode 100644index 000000000..04ab3e57e--- /dev/null+++ b/crates/ui-egui/src/rulers.rs@@ -0,0 +1,234 @@+//! View extras: rulers (⌘R), grid (⌘'), guides (⌘;). Guides are dragged out of the rulers and+//! moved with the Move tool (drag one off the canvas to delete it), all through undoable engine+//! commands (`view.newGuide` / `view.moveGuide` / `view.deleteGuide`).++use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, pos2, vec2};+use photocraft_doc::Document;+use serde_json::json;++use crate::PhotocraftApp;+use crate::canvas::ViewXform;+use crate::theme::Tokens;++pub const RULER: f32 = 16.0;+/// Photoshop's default guide colour (cyan) and grid colour (grey).+const GUIDE: Color32 = Color32::from_rgb(74, 255, 255);++/// A guide being dragged: from a ruler (new) or an existing one (index).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct GuideDrag {+ pub vertical: bool,+ pub index: Option<usize>,+ pub pos: f64,+}++/// Canvas area left after the rulers.+pub fn content_rect(app: &PhotocraftApp, rect: Rect) -> Rect {+ if app.ui.extras.rulers { Rect::from_min_max(rect.min + vec2(RULER, RULER), rect.max) } else { rect }+}++/// Tick step (document px) so major ticks are at least ~60 screen px apart: 1, 2, 5, 10, 20, 50…+fn tick_step(zoom: f32) -> f64 {+ let min = 60.0 / zoom.max(1e-4) as f64;+ let mut step = 1.0;+ loop {+ for m in [1.0, 2.0, 5.0] {+ if step * m >= min {+ return step * m;+ }+ }+ step *= 10.0;+ }+}++pub fn draw_grid(painter: &egui::Painter, xf: &ViewXform, doc: &Document) {+ // Photoshop default: a gridline every inch with 4 subdivisions.+ let major = doc.resolution_dpi.max(1.0) as f64;+ let minor = major / 4.0;+ let (w, h) = (doc.size.width as f64, doc.size.height as f64);+ for (step, alpha) in [(minor, 60u8), (major, 130u8)] {+ if step * (xf.zoom as f64) < 6.0 {+ continue;+ }+ let st = Stroke::new(1.0, Color32::from_rgba_unmultiplied(128, 128, 128, alpha));+ let mut x = step;+ while x < w {+ painter.line_segment([xf.to_screen(x as f32, 0.0), xf.to_screen(x as f32, h as f32)], st);+ x += step;+ }+ let mut y = step;+ while y < h {+ painter.line_segment([xf.to_screen(0.0, y as f32), xf.to_screen(w as f32, y as f32)], st);+ y += step;+ }+ }+}++pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) {+ let clip = painter.clip_rect();+ let drag = app.guide_drag;+ let line = |vertical: bool, pos: f64, color: Color32| {+ if vertical {+ let x = xf.to_screen(pos as f32, 0.0).x;+ painter.line_segment([pos2(x, clip.top()), pos2(x, clip.bottom())], Stroke::new(1.0, color));+ } else {+ let y = xf.to_screen(0.0, pos as f32).y;+ painter.line_segment([pos2(clip.left(), y), pos2(clip.right(), y)], Stroke::new(1.0, color));+ }+ };+ if app.ui.extras.guides {+ for (vertical, list) in [(true, &doc.guides.vertical), (false, &doc.guides.horizontal)] {+ for (i, p) in list.iter().enumerate() {+ if drag.is_some_and(|d| d.vertical == vertical && d.index == Some(i)) {+ continue;+ }+ line(vertical, *p as f64, GUIDE);+ }+ }+ }+ if let Some(d) = drag {+ line(d.vertical, d.pos, GUIDE);+ }+}++/// Existing guide under a document point (within 4 screen px).+pub fn guide_at(app: &PhotocraftApp, x: f64, y: f64) -> Option<(bool, usize)> {+ if !app.ui.extras.guides || app.ui.extras.lock_guides {+ return None;+ }+ let doc = &app.session.active()?.doc;+ let tol = 4.0 / app.current_zoom().max(0.01) as f64;+ for (i, g) in doc.guides.vertical.iter().enumerate() {+ if (*g as f64 - x).abs() <= tol {+ return Some((true, i));+ }+ }+ for (i, g) in doc.guides.horizontal.iter().enumerate() {+ if (*g as f64 - y).abs() <= tol {+ return Some((false, i));+ }+ }+ None+}++/// Finish a guide drag: create, move, or delete (dropped outside the canvas).+pub fn finish_drag(app: &mut PhotocraftApp, d: GuideDrag) {+ let Some(size) = app.session.active().map(|s| s.doc.size) else { return };+ let extent = if d.vertical { size.width } else { size.height } as f64;+ let orientation = if d.vertical { "vertical" } else { "horizontal" };+ let inside = d.pos >= 0.0 && d.pos <= extent;+ let pos = (d.pos * 1000.0).round() / 1000.0;+ let _ = match (d.index, inside) {+ (None, true) => app.run("view.newGuide", json!({"orientation": orientation, "position": pos})),+ (Some(i), true) => app.run("view.moveGuide", json!({"orientation": orientation, "index": i, "position": pos})),+ (Some(i), false) => app.run("view.deleteGuide", json!({"orientation": orientation, "index": i})),+ (None, false) => Ok(serde_json::Value::Null),+ };+ if d.index.is_none() && inside {+ app.ui.extras.guides = true;+ }+}++/// Rulers along the top and left of `full` (the canvas rect before `content_rect`), with the+/// pointer position marked; dragging out of a ruler creates a guide.+pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &ViewXform) {+ let t = Tokens::get(ui.ctx());+ let top = Rect::from_min_max(pos2(full.left() + RULER, full.top()), pos2(full.right(), full.top() + RULER));+ let left = Rect::from_min_max(pos2(full.left(), full.top() + RULER), pos2(full.left() + RULER, full.bottom()));+ let corner = Rect::from_min_size(full.min, vec2(RULER, RULER));+ let p = ui.painter_at(full);+ let bg = t.chrome;+ for r in [top, left, corner] {+ p.rect_filled(r, 0.0, bg);+ }+ p.line_segment([top.left_bottom(), top.right_bottom()], Stroke::new(1.0, t.separator));+ p.line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.separator));+ let step = tick_step(xf.zoom);+ let font = egui::FontId::proportional(9.0);+ let tick = Stroke::new(1.0, t.text_faint);+ // Horizontal ruler.+ let (d0, d1) = (xf.to_doc(top.left_top())[0], xf.to_doc(top.right_top())[0]);+ let mut v = (d0 / step).floor() * step;+ while v <= d1 {+ let x = xf.to_screen(v as f32, 0.0).x;+ p.line_segment([pos2(x, top.bottom() - RULER), pos2(x, top.bottom())], tick);+ p.text(pos2(x + 2.0, top.top() + 1.0), Align2::LEFT_TOP, format!("{}", v as i64), font.clone(), t.text_dim);+ for k in 1..10 {+ let xm = xf.to_screen((v + step * k as f64 / 10.0) as f32, 0.0).x;+ let len = if k == 5 { 6.0 } else { 3.0 };+ p.line_segment([pos2(xm, top.bottom() - len), pos2(xm, top.bottom())], tick);+ }+ v += step;+ }+ // Vertical ruler (labels stacked, as in Photoshop).+ let (d0, d1) = (xf.to_doc(left.left_top())[1], xf.to_doc(left.left_bottom())[1]);+ let mut v = (d0 / step).floor() * step;+ while v <= d1 {+ let y = xf.to_screen(0.0, v as f32).y;+ p.line_segment([pos2(left.right() - RULER, y), pos2(left.right(), y)], tick);+ for (i, ch) in format!("{}", v as i64).chars().enumerate() {+ p.text(pos2(left.left() + 3.0, y + 2.0 + i as f32 * 8.5), Align2::LEFT_TOP, ch, font.clone(), t.text_dim);+ }+ for k in 1..10 {+ let ym = xf.to_screen(0.0, (v + step * k as f64 / 10.0) as f32).y;+ let len = if k == 5 { 6.0 } else { 3.0 };+ p.line_segment([pos2(left.right() - len, ym), pos2(left.right(), ym)], tick);+ }+ v += step;+ }+ // Pointer position markers.+ if let Some(h) = ui.ctx().pointer_hover_pos().filter(|h| full.contains(*h)) {+ let m = Stroke::new(1.0, t.text);+ p.line_segment([pos2(h.x, top.top()), pos2(h.x, top.bottom())], m);+ p.line_segment([pos2(left.left(), h.y), pos2(left.right(), h.y)], m);+ }+ // Drag a new guide out of a ruler.+ for (r, vertical, salt) in [(top, false, "ruler-top"), (left, true, "ruler-left")] {+ let resp = ui.interact(r, ui.id().with(salt), Sense::drag());+ if resp.hovered() {+ ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });+ }+ if let Some(pos) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.drag_started()) {+ let d = xf.to_doc(pos);+ app.guide_drag = Some(GuideDrag { vertical, index: None, pos: if vertical { d[0] } else { d[1] } });+ }+ if resp.drag_stopped()+ && let Some(d) = app.guide_drag.take()+ {+ finish_drag(app, d);+ }+ }+ let _ = Pos2::ZERO;+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ticks_follow_1_2_5_series() {+ assert_eq!(tick_step(1.0), 100.0);+ assert_eq!(tick_step(0.1), 1000.0);+ assert_eq!(tick_step(4.0), 20.0);+ assert_eq!(tick_step(64.0), 1.0);+ assert_eq!(tick_step(0.25), 500.0);+ }++ #[test]+ fn guide_drags_create_move_and_delete() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap();+ app.sync_views();+ finish_drag(&mut app, GuideDrag { vertical: true, index: None, pos: 50.0 });+ finish_drag(&mut app, GuideDrag { vertical: false, index: None, pos: 500.0 }); // off canvas: ignored+ assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![50.0]);+ assert!(app.session.active().unwrap().doc.guides.horizontal.is_empty());+ assert_eq!(guide_at(&app, 51.0, 10.0), Some((true, 0)));+ finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: 120.0 });+ assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![120.0]);+ finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: -30.0 });+ assert!(app.session.active().unwrap().doc.guides.vertical.is_empty());+ app.ui.extras.lock_guides = true;+ assert_eq!(guide_at(&app, 0.0, 0.0), None);+ }+}diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rsindex 4cee696d0..155c26ff2 100644--- a/crates/ui-egui/src/shortcuts.rs+++ b/crates/ui-egui/src/shortcuts.rs@@ -12,15 +12,17 @@ pub fn parse(s: &str) -> Option<KeyboardShortcut> {let mut key = None;for part in s.split('+') {match part {- "Cmd" => mods = mods | Modifiers::COMMAND,- "Shift" => mods = mods | Modifiers::SHIFT,- "Alt" => mods = mods | Modifiers::ALT,- "Ctrl" => mods = mods | Modifiers::CTRL,+ "Cmd" => mods |= Modifiers::COMMAND,+ "Shift" => mods |= Modifiers::SHIFT,+ "Alt" => mods |= Modifiers::ALT,+ "Ctrl" => mods |= Modifiers::CTRL,"" => key = Some(Key::Plus),k => key = Key::from_name(k).or(match k {"=" => Some(Key::Equals),"-" => Some(Key::Minus),"[" => Some(Key::OpenBracket),+ ";" => Some(Key::Semicolon),+ "'" => Some(Key::Quote),"]" => Some(Key::CloseBracket),_ => None,}),@@ -48,6 +50,30 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {if ctx.egui_wants_keyboard_input() || !app.ui.dialogs.is_empty() {return;}+ // Free Transform: ↩ commits, Esc cancels.+ if app.ui.transform.is_some() {+ if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) {+ crate::transform_tool::commit(app);+ return;+ }+ if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {+ crate::transform_tool::cancel(app);+ return;+ }+ }+ // Pen path in progress: ↩ finishes (open path), Esc cancels.+ if app.ui.pen.is_some() {+ if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) {+ crate::vector_ui::pen_commit(app, false);+ return;+ }+ if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {+ app.ui.pen = None;+ return;+ }+ }+ // Inline type editing eats text and navigation keys; ⌘-shortcuts still reach the menus.+ let editing = crate::type_tool::handle_keys(app, ctx);// Registry + UI command shortcuts, most-modifiers first so ⇧⌘Z wins over ⌘Z.let mut all: Vec<(String, KeyboardShortcut)> = crate::menus::UI_COMMANDS.iter()@@ -57,6 +83,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {.collect();all.sort_by_key(|(_, sc)| std::cmp::Reverse(sc.modifiers.shift as u8 + sc.modifiers.alt as u8 + sc.modifiers.command as u8));for (id, sc) in all {+ // While typing, clipboard/select-all shortcuts belong to the text, not the pixels.+ if editing && matches!(id.as_str(), "edit.copy" | "edit.cut" | "edit.paste" | "edit.copyMerged" | "select.all" | "edit.pasteSpecial.pasteInPlace") {+ continue;+ }if ctx.input_mut(|i| i.consume_shortcut(&sc)) {if crate::menus::is_enabled(app, &id) {let r = if id.starts_with("image.adjustments.") && !crate::panels::adjustment_sliders(id.rsplit('.').next().unwrap_or("")).is_empty() {@@ -73,15 +103,36 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {return;}}+ if editing {+ return;+ }// Single-key tools and colours (no modifiers).let pressed = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k));+ // Enter / Escape commit or cancel in-progress tool state (polygonal lasso, crop).+ if !app.ui.polygon.is_empty() || app.ui.crop_rect.is_some() {+ if pressed(Key::Enter) {+ if !app.ui.polygon.is_empty() {+ crate::canvas::commit_polygon(app, Modifiers::NONE);+ } else {+ crate::canvas::commit_crop(app);+ }+ return;+ }+ if pressed(Key::Escape) {+ app.ui.polygon.clear();+ app.ui.crop_rect = None;+ return;+ }+ }+ // Tool keys; pressing the key of the current group cycles within it (Photoshop's Shift+key cycle).for t in Tool::ALL {- let k = Key::from_name(&t.key().to_string());- if let Some(k) = k- && pressed(k)- {- // M toggles between marquee shapes like Photoshop's Shift+M cycling.- app.ui.tool = if t.key() == 'M' && app.ui.tool == Tool::RectMarquee { Tool::EllipseMarquee } else if t.key() == 'M' { Tool::RectMarquee } else { t };+ let Some(k) = Key::from_name(&t.key().to_string()) else { continue };+ if pressed(k) {+ let group: Vec<Tool> = Tool::ALL.iter().copied().filter(|x| x.key() == t.key()).collect();+ app.ui.tool = match group.iter().position(|x| *x == app.ui.tool) {+ Some(i) => group[(i + 1) % group.len()],+ None => group[0],+ };return;}}diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rsnew file mode 100644index 000000000..53d22764d--- /dev/null+++ b/crates/ui-egui/src/sizing.rs@@ -0,0 +1,358 @@+//! Photoshop-style Image Size and Canvas Size dialogs.+//!+//! Field values are stored in pixels (plus a display unit), so automation can set `width`/`height`+//! directly and the dialog maps them to `image.imageSize` / `image.canvasSize` unchanged.++use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};+use serde_json::{Map, Value, json};++use crate::PhotocraftApp;+use crate::state::DialogKind;+use crate::theme::Tokens;++const UNITS: [(&str, &str); 4] = [("px", "Pixels"), ("percent", "Percent"), ("in", "Inches"), ("cm", "Centimeters")];+const ANCHORS: [&str; 9] = ["topLeft", "top", "topRight", "left", "center", "right", "bottomLeft", "bottom", "bottomRight"];++pub fn is_sizing(command: &str) -> bool {+ matches!(command, "image.imageSize" | "image.canvasSize")+}++pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {+ let d = &app.session.active()?.doc;+ let (w, h, res) = (d.size.width as f64, d.size.height as f64, d.resolution_dpi as f64);+ let label = photocraft_engine::commands::find(command).map(|c| c.label).unwrap_or("Image Size…");+ let mut f = Map::new();+ f.insert("__command".into(), json!(command));+ f.insert("__label".into(), json!(label));+ f.insert("__sizing".into(), json!(true));+ f.insert("__origW".into(), json!(w));+ f.insert("__origH".into(), json!(h));+ f.insert("__origRes".into(), json!(res));+ f.insert("__unit".into(), json!("px"));+ f.insert("__bytesPerPixel".into(), json!(d.layers.first().and_then(|l| l.surface()).map_or(4, |s| s.format().bytes_per_pixel())));+ f.insert("width".into(), json!(w));+ f.insert("height".into(), json!(h));+ if command == "image.imageSize" {+ f.insert("__constrain".into(), json!(true));+ f.insert("resolution".into(), json!(res));+ f.insert("resample".into(), json!("bicubic"));+ } else {+ f.insert("relative".into(), json!(false));+ f.insert("anchor".into(), json!("center"));+ f.insert("extensionColor".into(), json!("background"));+ }+ Some(app.ui.open_dialog(DialogKind::Command, f))+}++fn num(f: &Map<String, Value>, k: &str) -> f64 {+ f.get(k).and_then(Value::as_f64).unwrap_or(0.0)+}++/// Pixels → display unit.+fn to_unit(px: f64, unit: &str, orig: f64, res: f64) -> f64 {+ match unit {+ "percent" => px / orig.max(1.0) * 100.0,+ "in" => px / res.max(1.0),+ "cm" => px / res.max(1.0) * 2.54,+ _ => px,+ }+}++fn from_unit(v: f64, unit: &str, orig: f64, res: f64) -> f64 {+ match unit {+ "percent" => v * orig / 100.0,+ "in" => v * res,+ "cm" => v / 2.54 * res,+ _ => v,+ }+}++pub fn human_bytes(b: f64) -> String {+ if b >= 1024.0 * 1024.0 * 1024.0 {+ format!("{:.2}G", b / (1024.0 * 1024.0 * 1024.0))+ } else if b >= 1024.0 * 1024.0 {+ format!("{:.1}M", b / (1024.0 * 1024.0))+ } else {+ format!("{:.0}K", (b / 1024.0).max(1.0))+ }+}++pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {+ if f.get("__command").and_then(Value::as_str) == Some("image.canvasSize") {+ canvas_size(ui, f);+ } else {+ image_size(ui, f);+ }+}++fn label(ui: &mut egui::Ui, text: &str, width: f32) {+ let t = Tokens::get(ui.ctx());+ let (r, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover());+ ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim);+}++fn info_row(ui: &mut egui::Ui, k: &str, v: String) {+ let t = Tokens::get(ui.ctx());+ ui.horizontal(|ui| {+ label(ui, k, 90.0);+ ui.label(egui::RichText::new(v).color(t.text).size(12.0));+ });+}++/// Width / height field in the current unit, writing back pixels. Returns true when edited.+fn dim_field(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, orig_key: &str, id: &str) -> bool {+ let unit = f.get("__unit").and_then(Value::as_str).unwrap_or("px").to_string();+ let res = f.get("resolution").and_then(Value::as_f64).unwrap_or(num(f, "__origRes"));+ let orig = num(f, orig_key);+ let px = num(f, key);+ let mut v = to_unit(px, &unit, orig, res) as f32;+ let range = if unit == "px" { -300000.0..=300000.0 } else { -30000.0..=30000.0 };+ let changed = crate::widgets::value_field(ui, &mut v, range, "", 90.0).changed();+ if changed {+ let px = from_unit(v as f64, &unit, orig, res);+ f.insert(key.into(), json!(if unit == "px" { px.round() } else { px }));+ }+ let _ = id;+ changed+}++fn unit_dropdown(ui: &mut egui::Ui, f: &mut Map<String, Value>, id: &str) {+ let mut unit = f.get("__unit").and_then(Value::as_str).unwrap_or("px").to_string();+ let opts: Vec<(String, &str)> = UNITS.iter().map(|(k, l)| (k.to_string(), *l)).collect();+ if crate::widgets::dropdown(ui, id, &mut unit, &opts, 110.0) {+ f.insert("__unit".into(), json!(unit));+ }+}++fn image_size(ui: &mut egui::Ui, f: &mut Map<String, Value>) {+ let t = Tokens::get(ui.ctx());+ let (ow, oh) = (num(f, "__origW"), num(f, "__origH"));+ let bpp = num(f, "__bytesPerPixel").max(1.0);+ let resample = f.get("resample").and_then(Value::as_str).unwrap_or("bicubic").to_string();+ let resampling = resample != "none";+ let (w, h) = (num(f, "width").round(), num(f, "height").round());+ info_row(ui, "Image Size:", format!("{} (was {})", human_bytes(w * h * bpp), human_bytes(ow * oh * bpp)));+ info_row(ui, "Dimensions:", format!("{} px × {} px", w as i64, h as i64));+ ui.add_space(6.0);+ let mut constrain = f.get("__constrain").and_then(Value::as_bool).unwrap_or(true);+ let w_row = ui.horizontal(|ui| {+ label(ui, "Width:", 90.0);+ let c = dim_field(ui, f, "width", "__origW", "is-w");+ unit_dropdown(ui, f, "is-unit-w");+ c+ });+ let h_row = ui.horizontal(|ui| {+ label(ui, "Height:", 90.0);+ let c = dim_field(ui, f, "height", "__origH", "is-h");+ unit_dropdown(ui, f, "is-unit-h");+ c+ });+ let (w_changed, h_changed) = (w_row.inner, h_row.inner);+ // Photoshop's chain bracket linking width and height (right of the unit dropdowns).+ let x0 = w_row.response.rect.right().max(h_row.response.rect.right()) + 4.0;+ let bracket = Rect::from_min_max(pos2(x0, w_row.response.rect.center().y), pos2(x0 + 14.0, h_row.response.rect.center().y));+ let link = ui.interact(bracket.expand(2.0), ui.id().with("constrain"), Sense::click());+ let col = if constrain { t.text } else { t.text_faint };+ if constrain {+ let p = ui.painter();+ let x = bracket.left() + 8.0;+ p.line_segment([pos2(bracket.left(), bracket.top()), pos2(x, bracket.top())], Stroke::new(1.0, col));+ p.line_segment([pos2(x, bracket.top()), pos2(x, bracket.center().y - 8.0)], Stroke::new(1.0, col));+ p.line_segment([pos2(x, bracket.center().y + 8.0), pos2(x, bracket.bottom())], Stroke::new(1.0, col));+ p.line_segment([pos2(x, bracket.bottom()), pos2(bracket.left(), bracket.bottom())], Stroke::new(1.0, col));+ }+ let chain = Rect::from_center_size(pos2(bracket.left() + 8.0, bracket.center().y), vec2(14.0, 14.0));+ ui.painter().rect_filled(chain, 2.0, if link.hovered() { t.hover } else { Color32::TRANSPARENT });+ crate::icons::paint(ui, chain, if constrain { "link" } else { "unlink" }, 11.0, col);+ if link.on_hover_text("Constrain proportions").clicked() {+ constrain = !constrain;+ f.insert("__constrain".into(), json!(constrain));+ }+ if constrain && resampling {+ if w_changed {+ f.insert("height".into(), json!((num(f, "width") * oh / ow.max(1.0)).round().max(1.0)));+ } else if h_changed {+ f.insert("width".into(), json!((num(f, "height") * ow / oh.max(1.0)).round().max(1.0)));+ }+ }+ ui.horizontal(|ui| {+ label(ui, "Resolution:", 90.0);+ let mut r = f.get("resolution").and_then(Value::as_f64).unwrap_or(72.0) as f32;+ if crate::widgets::value_field(ui, &mut r, 1.0..=30000.0, "", 90.0).changed() {+ let r = r.max(1.0) as f64;+ if !resampling {+ // Without resampling the pixel count is fixed: physical size follows resolution.+ f.insert("width".into(), json!(ow));+ f.insert("height".into(), json!(oh));+ }+ f.insert("resolution".into(), json!(r));+ }+ ui.label(egui::RichText::new("Pixels/Inch").color(t.text_dim).size(12.0));+ });+ ui.add_space(4.0);+ ui.horizontal(|ui| {+ label(ui, "", 90.0);+ let mut on = resampling;+ if crate::widgets::checkbox(ui, &mut on, "Resample").changed() {+ f.insert("resample".into(), json!(if on { "bicubic" } else { "none" }));+ if !on {+ f.insert("width".into(), json!(ow));+ f.insert("height".into(), json!(oh));+ }+ }+ if resampling {+ let mut cur = resample.clone();+ let opts = [+ ("preserveDetails".to_string(), "Preserve Details"),+ ("bicubic".to_string(), "Bicubic (smooth gradients)"),+ ("lanczos".to_string(), "Lanczos (sharp)"),+ ("bilinear".to_string(), "Bilinear"),+ ("nearest".to_string(), "Nearest Neighbor (hard edges)"),+ ];+ if crate::widgets::dropdown(ui, "is-resample", &mut cur, &opts, 200.0) {+ f.insert("resample".into(), json!(cur));+ }+ }+ });+}++fn canvas_size(ui: &mut egui::Ui, f: &mut Map<String, Value>) {+ let t = Tokens::get(ui.ctx());+ let (ow, oh) = (num(f, "__origW"), num(f, "__origH"));+ let bpp = num(f, "__bytesPerPixel").max(1.0);+ let relative = f.get("relative").and_then(Value::as_bool).unwrap_or(false);+ ui.label(egui::RichText::new("Current Size").font(crate::theme::semibold(12.0)).color(t.text));+ info_row(ui, "Size:", human_bytes(ow * oh * bpp));+ info_row(ui, "Width:", format!("{} px", ow as i64));+ info_row(ui, "Height:", format!("{} px", oh as i64));+ ui.add_space(6.0);+ crate::widgets::hairline(ui);+ ui.add_space(6.0);+ let (nw, nh) = if relative { (ow + num(f, "width"), oh + num(f, "height")) } else { (num(f, "width"), num(f, "height")) };+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new("New Size").font(crate::theme::semibold(12.0)).color(t.text));+ ui.label(egui::RichText::new(human_bytes(nw.max(0.0) * nh.max(0.0) * bpp)).color(t.text_dim).size(12.0));+ });+ ui.horizontal(|ui| {+ label(ui, "Width:", 90.0);+ dim_field(ui, f, "width", "__origW", "cs-w");+ unit_dropdown(ui, f, "cs-unit-w");+ });+ ui.horizontal(|ui| {+ label(ui, "Height:", 90.0);+ dim_field(ui, f, "height", "__origH", "cs-h");+ unit_dropdown(ui, f, "cs-unit-h");+ });+ ui.horizontal(|ui| {+ label(ui, "", 90.0);+ let mut rel = relative;+ if crate::widgets::checkbox(ui, &mut rel, "Relative").changed() {+ // Convert between absolute and delta so the resulting canvas is unchanged.+ let (w, h) = (num(f, "width"), num(f, "height"));+ let (w, h) = if rel { (w - ow, h - oh) } else { (w + ow, h + oh) };+ f.insert("width".into(), json!(w));+ f.insert("height".into(), json!(h));+ f.insert("relative".into(), json!(rel));+ }+ });+ ui.horizontal(|ui| {+ label(ui, "Anchor:", 90.0);+ let cur = f.get("anchor").and_then(Value::as_str).unwrap_or("center").to_string();+ if let Some(a) = anchor_grid(ui, &cur, nw - ow, nh - oh) {+ f.insert("anchor".into(), json!(a));+ }+ });+ ui.add_space(4.0);+ ui.horizontal(|ui| {+ label(ui, "Canvas extension color:", 150.0);+ let mut cur = f.get("extensionColor").and_then(Value::as_str).unwrap_or("background").to_string();+ let opts = [+ ("foreground".to_string(), "Foreground"),+ ("background".to_string(), "Background"),+ ("white".to_string(), "White"),+ ("black".to_string(), "Black"),+ ("transparent".to_string(), "Transparent"),+ ];+ if crate::widgets::dropdown(ui, "cs-ext", &mut cur, &opts, 140.0) {+ f.insert("extensionColor".into(), json!(cur));+ }+ });+}++/// 3×3 anchor picker; arrows point away from the anchor in the directions the canvas grows.+fn anchor_grid(ui: &mut egui::Ui, current: &str, dw: f64, dh: f64) -> Option<&'static str> {+ let t = Tokens::get(ui.ctx());+ let cell = 24.0;+ let (rect, _) = ui.allocate_exact_size(vec2(cell * 3.0, cell * 3.0), Sense::hover());+ let ci = ANCHORS.iter().position(|a| *a == current).unwrap_or(4) as i32;+ let (ax, ay) = (ci % 3, ci / 3);+ let mut picked = None;+ for (i, a) in ANCHORS.iter().enumerate() {+ let (x, y) = (i as i32 % 3, i as i32 / 3);+ let r = Rect::from_min_size(rect.min + vec2(x as f32 * cell, y as f32 * cell), vec2(cell, cell)).shrink(1.0);+ let resp = ui.interact(r, ui.id().with(("anchor", i)), Sense::click());+ let selected = i as i32 == ci;+ ui.painter().rect_filled(r, 2.0, if selected { t.field.gamma_multiply(1.6) } else if resp.hovered() { t.hover } else { t.field });+ ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);+ if selected {+ ui.painter().rect_filled(Rect::from_center_size(r.center(), vec2(8.0, 8.0)), 1.0, t.text);+ } else {+ let (dx, dy) = (x - ax, y - ay);+ // Only neighbouring cells show arrows (Photoshop behaviour); direction flips when shrinking.+ if dx.abs() <= 1 && dy.abs() <= 1 {+ let sx = if dw < 0.0 { -1.0 } else { 1.0 };+ let sy = if dh < 0.0 { -1.0 } else { 1.0 };+ let dir = vec2(dx as f32 * sx, dy as f32 * sy);+ if dir != egui::Vec2::ZERO {+ let dir = dir.normalized();+ let c = r.center();+ let tip = c + dir * 6.0;+ let tail = c - dir * 5.0;+ let side = vec2(-dir.y, dir.x) * 3.5;+ let col = t.text_dim;+ ui.painter().line_segment([tail, tip], Stroke::new(1.3, col));+ ui.painter().add(egui::Shape::convex_polygon(vec![tip + dir * 1.5, tip - dir * 3.5 + side, tip - dir * 3.5 - side], col, Stroke::NONE));+ }+ }+ }+ if resp.clicked() {+ picked = Some(*a);+ }+ }+ let _ = Color32::WHITE;+ picked+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn unit_conversions_round_trip() {+ for unit in ["px", "percent", "in", "cm"] {+ let v = to_unit(1500.0, unit, 3000.0, 300.0);+ assert!((from_unit(v, unit, 3000.0, 300.0) - 1500.0).abs() < 1e-9, "{unit}");+ }+ assert_eq!(to_unit(1500.0, "percent", 3000.0, 300.0), 50.0);+ assert_eq!(to_unit(600.0, "in", 3000.0, 300.0), 2.0);+ assert_eq!(human_bytes(6016.0 * 6016.0 * 4.0), "138.1M");+ }++ #[test]+ fn dialog_maps_to_engine_command() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap();+ let id = open(&mut app, "image.imageSize").unwrap();+ let d = app.ui.dialog_mut(id).unwrap();+ d.fields.insert("width".into(), json!(100));+ d.fields.insert("height".into(), json!(50));+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(100, 50));+ let id = open(&mut app, "image.canvasSize").unwrap();+ let d = app.ui.dialog_mut(id).unwrap();+ d.fields.insert("width".into(), json!(120));+ d.fields.insert("anchor".into(), json!("topLeft"));+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(120, 50));+ }+}diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 668b693f0..72d53e02a 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -8,15 +8,76 @@ pub enum Tool {Move,RectMarquee,EllipseMarquee,+ Lasso,+ PolygonLasso,+ MagicWand,+ Crop,+ Eyedropper,Brush,Eraser,- Eyedropper,+ Gradient,+ PaintBucket,+ Type,Hand,Zoom,+ SpotHealing,+ Healing,+ CloneStamp,+ HistoryBrush,+ Blur,+ Sharpen,+ Smudge,+ Dodge,+ Burn,+ Sponge,+ QuickSelection,+ ObjectSelection,+ Pen,+ PathSelection,+ Rectangle,+ EllipseShape,+ Triangle,+ Polygon,+ Line,}impl Tool {- pub const ALL: [Tool; 8] = [Tool::Move, Tool::RectMarquee, Tool::EllipseMarquee, Tool::Brush, Tool::Eraser, Tool::Eyedropper, Tool::Hand, Tool::Zoom];+ pub const ALL: [Tool; 34] = [+ Tool::Move,+ Tool::RectMarquee,+ Tool::EllipseMarquee,+ Tool::Lasso,+ Tool::PolygonLasso,+ Tool::MagicWand,+ Tool::Crop,+ Tool::Eyedropper,+ Tool::Brush,+ Tool::Eraser,+ Tool::Gradient,+ Tool::PaintBucket,+ Tool::Type,+ Tool::Hand,+ Tool::Zoom,+ Tool::SpotHealing,+ Tool::Healing,+ Tool::CloneStamp,+ Tool::HistoryBrush,+ Tool::Blur,+ Tool::Sharpen,+ Tool::Smudge,+ Tool::Dodge,+ Tool::Burn,+ Tool::Sponge,+ Tool::QuickSelection,+ Tool::ObjectSelection,+ Tool::Pen,+ Tool::PathSelection,+ Tool::Rectangle,+ Tool::EllipseShape,+ Tool::Triangle,+ Tool::Polygon,+ Tool::Line,+ ];pub fn label(self) -> &'static str {match self {@@ -26,11 +87,41 @@ impl Tool {Tool::Brush => "Brush Tool",Tool::Eraser => "Eraser Tool",Tool::Eyedropper => "Eyedropper Tool",+ Tool::Lasso => "Lasso Tool",+ Tool::PolygonLasso => "Polygonal Lasso Tool",+ Tool::MagicWand => "Magic Wand Tool",+ Tool::Crop => "Crop Tool",+ Tool::Gradient => "Gradient Tool",+ Tool::PaintBucket => "Paint Bucket Tool",+ Tool::Type => "Horizontal Type Tool",Tool::Hand => "Hand Tool",Tool::Zoom => "Zoom Tool",+ Tool::SpotHealing => "Spot Healing Brush Tool",+ Tool::Healing => "Healing Brush Tool",+ Tool::CloneStamp => "Clone Stamp Tool",+ Tool::HistoryBrush => "History Brush Tool",+ Tool::Blur => "Blur Tool",+ Tool::Sharpen => "Sharpen Tool",+ Tool::Smudge => "Smudge Tool",+ Tool::Dodge => "Dodge Tool",+ Tool::Burn => "Burn Tool",+ Tool::Sponge => "Sponge Tool",+ Tool::QuickSelection => "Quick Selection Tool",+ Tool::ObjectSelection => "Object Selection Tool",+ Tool::Pen => "Pen Tool",+ Tool::PathSelection => "Path Selection Tool",+ Tool::Rectangle => "Rectangle Tool",+ Tool::EllipseShape => "Ellipse Tool",+ Tool::Triangle => "Triangle Tool",+ Tool::Polygon => "Polygon Tool",+ Tool::Line => "Line Tool",}}- /// Photoshop default single-key shortcut.+ /// Retouching and painting tools that stroke with the brush (share the brush cursor and chip).+ pub fn is_brushlike(self) -> bool {+ matches!(self, Tool::Brush | Tool::Eraser | Tool::SpotHealing | Tool::Healing | Tool::CloneStamp | Tool::HistoryBrush | Tool::Blur | Tool::Sharpen | Tool::Smudge | Tool::Dodge | Tool::Burn | Tool::Sponge)+ }+ /// Photoshop default single-key shortcut (`'\0'` = none, e.g. the Blur group).pub fn key(self) -> char {match self {Tool::Move => 'V',@@ -38,8 +129,22 @@ impl Tool {Tool::Brush => 'B',Tool::Eraser => 'E',Tool::Eyedropper => 'I',+ Tool::Lasso | Tool::PolygonLasso => 'L',+ Tool::MagicWand => 'W',+ Tool::Crop => 'C',+ Tool::Gradient | Tool::PaintBucket => 'G',+ Tool::Type => 'T',Tool::Hand => 'H',Tool::Zoom => 'Z',+ Tool::SpotHealing | Tool::Healing => 'J',+ Tool::CloneStamp => 'S',+ Tool::HistoryBrush => 'Y',+ Tool::Blur | Tool::Sharpen | Tool::Smudge => '\0',+ Tool::Dodge | Tool::Burn | Tool::Sponge => 'O',+ Tool::QuickSelection | Tool::ObjectSelection => 'W',+ Tool::Pen => 'P',+ Tool::PathSelection => 'A',+ Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line => 'U',}}/// Glyph drawn in the toolbar (vector icons come later).@@ -51,8 +156,14 @@ impl Tool {Tool::Brush => "🖌",Tool::Eraser => "⌫",Tool::Eyedropper => "💧",+ Tool::Lasso | Tool::PolygonLasso => "L",+ Tool::MagicWand => "W",+ Tool::Crop => "C",+ Tool::Gradient | Tool::PaintBucket => "G",+ Tool::Type => "T",Tool::Hand => "✋",Tool::Zoom => "🔍",+ _ => "•",}}pub fn from_name(s: &str) -> Option<Tool> {@@ -111,11 +222,14 @@ pub struct View {pub center: [f32; 2],/// Recompute fit-to-screen on next frame.pub fit_pending: bool,+ /// Document size this view last showed; a change (Image/Canvas Size, crop) re-centres it.+ #[serde(default)]+ pub doc_size: [u32; 2],}impl Default for View {fn default() -> Self {- Self { zoom: 1.0, center: [0.0, 0.0], fit_pending: true }+ Self { zoom: 1.0, center: [0.0, 0.0], fit_pending: true, doc_size: [0, 0] }}}@@ -128,17 +242,182 @@ pub struct DocWindow {pub open: bool,}+/// Options-bar state for tools (Photoshop keeps these per tool).+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct ToolOptions {+ pub tolerance: f32,+ pub contiguous: bool,+ pub anti_alias: bool,+ pub sample_all_layers: bool,+ pub feather: f32,+ /// linear | radial | angle | reflected | diamond+ pub gradient_style: String,+ pub gradient_reverse: bool,+ pub fill_opacity: f32,+ /// Type tool: family, style name, size (pt), anti-aliasing and paragraph alignment.+ pub type_font: String,+ pub type_style: String,+ pub type_size: f32,+ pub type_aa: String,+ pub type_align: String,+ /// Clone Stamp / Healing Brush.+ pub clone_aligned: bool,+ /// current | currentAndBelow | all+ pub clone_sample: String,+ /// Spot Healing: contentAware | createTexture | proximityMatch+ pub spot_type: String,+ /// Dodge/Burn: shadows | midtones | highlights, exposure %, protect tones.+ pub tone_range: String,+ pub exposure: f32,+ pub protect_tones: bool,+ /// Sponge: desaturate | saturate, vibrance.+ pub sponge_mode: String,+ pub vibrance: bool,+ /// Blur/Sharpen/Smudge strength %, Sharpen protect detail, Smudge finger painting.+ pub strength: f32,+ pub protect_detail: bool,+ pub finger_painting: bool,+ /// Quick Selection enhance edge.+ pub enhance_edge: bool,+ /// Pen: "path" (work path) or "shape" (shape layer).+ pub vector_mode: String,+ /// Shape tools: fill with the foreground colour, stroke width (0 = none), rectangle corner+ /// radius, polygon sides, line weight.+ pub shape_fill: bool,+ pub stroke_width: f32,+ pub corner_radius: f32,+ pub polygon_sides: u32,+ pub line_weight: f32,+}++impl Default for ToolOptions {+ fn default() -> Self {+ Self {+ tolerance: 32.0,+ contiguous: true,+ anti_alias: true,+ sample_all_layers: false,+ feather: 0.0,+ gradient_style: "linear".into(),+ gradient_reverse: false,+ fill_opacity: 100.0,+ type_font: "Inter".into(),+ type_style: "Regular".into(),+ type_size: 48.0,+ type_aa: "sharp".into(),+ type_align: "left".into(),+ clone_aligned: true,+ clone_sample: "current".into(),+ spot_type: "contentAware".into(),+ tone_range: "midtones".into(),+ exposure: 50.0,+ protect_tones: true,+ sponge_mode: "desaturate".into(),+ vibrance: true,+ strength: 50.0,+ protect_detail: true,+ finger_painting: false,+ enhance_edge: false,+ vector_mode: "path".into(),+ shape_fill: true,+ stroke_width: 0.0,+ corner_radius: 0.0,+ polygon_sides: 5,+ line_weight: 3.0,+ }+ }+}++/// Free Transform in progress: the source frame `rect` and where its corners currently are.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct TransformSession {+ pub session: u64,+ pub layer: u64,+ pub rect: [f64; 4],+ /// Corners clockwise from top-left (document px).+ pub quad: [[f64; 2]; 4],+ /// Reference point (rotation / ⌥-scale centre).+ pub pivot: [f64; 2],+ pub interpolation: String,+}++/// In-progress inline type editing (Type tool). Offsets are character indices.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct TextEdit {+ pub layer: u64,+ pub caret: usize,+ pub anchor: usize,+ /// History coalescing key: the whole editing session is one "Edit Type Layer" step.+ pub session: String,+ /// The layer was created by this session (its name follows the text; empty on commit = delete).+ pub created: bool,+ #[serde(skip)]+ pub dragging: bool,+}++/// View-menu overlays.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(default)]+pub struct Extras {+ pub rulers: bool,+ pub grid: bool,+ pub guides: bool,+ pub snap: bool,+ pub lock_guides: bool,+}++impl Default for Extras {+ fn default() -> Self {+ Self { rulers: false, grid: false, guides: true, snap: true, lock_guides: false }+ }+}+/// Selected tab per dock card.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(default)]pub struct DockTabs {pub properties: usize,pub color: usize,pub layers: usize,+ /// Navigator | Histogram | Info.+ pub navigator: usize,+ /// History | Actions.+ pub history: usize,}#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub struct UiState {pub tool: Tool,+ /// Inline type editing session, if any.+ #[serde(default)]+ pub text_edit: Option<TextEdit>,+ /// Free Transform session, if any.+ #[serde(default)]+ pub transform: Option<TransformSession>,+ /// Clone Stamp / Healing source point (⌥-click) and the aligned offset once a stroke started.+ #[serde(default)]+ pub clone_source: Option<[f64; 2]>,+ #[serde(default)]+ pub clone_offset: Option<[f64; 2]>,+ /// Painting targets the active layer's mask instead of its pixels.+ #[serde(default)]+ pub mask_target: bool,+ /// Pen path under construction.+ #[serde(default)]+ pub pen: Option<crate::vector_ui::PenPath>,+ /// Selected row in the Paths panel ("work" or a saved path name).+ #[serde(default)]+ pub selected_path: Option<String>,+ /// Layers panel kind filter ("pixel", "adjustment", "type", "shape", "smart"); empty = all.+ #[serde(default)]+ pub layer_filter: Vec<String>,+ /// Recorded actions (Actions panel).+ #[serde(default)]+ pub actions: crate::actions::Actions,+ /// View extras: rulers (⌘R), grid (⌘'), guides (⌘;), snapping (⇧⌘;), locked guides (⌥⌘;).+ #[serde(default)]+ pub extras: Extras,pub panels: Panels,/// Views per open document (index-aligned with the session's documents).pub views: Vec<View>,@@ -151,6 +430,14 @@ pub struct UiState {/// Marquee options-bar mode: 0 new, 1 add, 2 subtract, 3 intersect (modifier keys override).#[serde(default)]pub selection_mode: u8,+ #[serde(default)]+ pub tool_options: ToolOptions,+ /// In-progress polygonal lasso vertices (document coordinates).+ #[serde(default)]+ pub polygon: Vec<[f64; 2]>,+ /// Crop tool rectangle being edited [x0, y0, x1, y1] (document coordinates).+ #[serde(default)]+ pub crop_rect: Option<[f64; 4]>,pub next_id: u64,/// Last status message (errors from commands, hints).pub status: String,@@ -163,6 +450,16 @@ impl Default for UiState {fn default() -> Self {Self {tool: Tool::Brush,+ text_edit: None,+ transform: None,+ mask_target: false,+ clone_source: None,+ clone_offset: None,+ extras: Extras::default(),+ actions: Default::default(),+ layer_filter: Vec::new(),+ pen: None,+ selected_path: None,panels: Panels::default(),views: Vec::new(),dialogs: Vec::new(),@@ -172,6 +469,9 @@ impl Default for UiState {palette_open: false,dock_tabs: DockTabs::default(),selection_mode: 0,+ tool_options: ToolOptions::default(),+ polygon: Vec::new(),+ crop_rect: None,next_id: 1,status: String::new(),status_error: false,diff --git a/crates/ui-egui/src/tone.rs b/crates/ui-egui/src/tone.rsnew file mode 100644index 000000000..04d4e0ca2--- /dev/null+++ b/crates/ui-egui/src/tone.rs@@ -0,0 +1,585 @@+//! Photoshop-style Levels and Curves editors for the Properties panel.+//!+//! Both draw the histogram of the image *below* the adjustment (what the adjustment receives) and+//! commit every change as `layer.setAdjustment` with a per-gesture `coalesce` key, so a drag is one+//! history step and the canvas (GPU compositor) updates live at full resolution.++use std::sync::Arc;++use egui::{Color32, Pos2, Rect, Sense, Stroke, pos2, vec2};+use photocraft_doc::{Document, LayerContent, LayerId};+use serde_json::{Value, json};++use crate::PhotocraftApp;+use crate::theme::Tokens;++const CHANNELS: [(&str, &str); 4] = [("rgb", "RGB"), ("red", "Red"), ("green", "Green"), ("blue", "Blue")];++/// Histograms (RGB composite, R, G, B) of 256 bins each.+pub type Histograms = [[u32; 256]; 4];++/// Histogram of the document with `hide` (the adjustment being edited) switched off.+fn compute_histograms(doc: &Document, hide: LayerId) -> Histograms {+ let mut d = doc.clone();+ if let Some(l) = d.layer_mut(hide) {+ l.visible = false;+ }+ let img = photocraft_compose::thumbnail(&d, 384);+ let mut h = [[0u32; 256]; 4];+ for p in img.pixels.chunks_exact(4) {+ if p[3] == 0 {+ continue;+ }+ for c in 0..3 {+ h[c + 1][p[c] as usize] += 1;+ }+ h[0][((p[0] as u32 + p[1] as u32 + p[2] as u32) / 3) as usize] += 1;+ }+ h+}++/// Cached histograms for the adjustment layer; recomputed only when something other than this+/// editor changed the document (see `PhotocraftApp::tone_hist`).+fn histograms(app: &mut PhotocraftApp, id: LayerId) -> Arc<Histograms> {+ let Some(st) = app.session.active() else { return Arc::new([[0; 256]; 4]) };+ let (doc_id, rev) = (st.doc.id, st.revision);+ if let Some((d, l, r, h)) = &app.tone_hist+ && *d == doc_id+ && *l == id+ && *r == rev+ {+ return h.clone();+ }+ let t0 = crate::gpu_canvas::now_ms();+ let h = Arc::new(compute_histograms(&st.doc, id));+ app.perf.span("histogram", crate::gpu_canvas::now_ms() - t0);+ app.tone_hist = Some((doc_id, id, rev, h.clone()));+ h+}++/// Commit adjustment params; the editor's own edits keep the histogram cache valid.+fn commit(app: &mut PhotocraftApp, id: LayerId, mut params: Value, gesture: &str) {+ params["layer"] = json!(id.0);+ params["coalesce"] = json!(format!("tone-{}-{gesture}", id.0));+ let cached = app.tone_hist.as_ref().is_some_and(|(_, l, r, _)| *l == id && app.session.active().is_some_and(|s| s.revision == *r));+ if app.run("layer.setAdjustment", params).is_ok()+ && cached+ && let (Some((_, _, r, _)), Some(st)) = (app.tone_hist.as_mut(), app.session.active())+ {+ *r = st.revision;+ }+}++fn draw_histogram(p: &egui::Painter, r: Rect, h: &[u32; 256], color: Color32) {+ // Scale to a high percentile so a single spike (e.g. pure white) doesn't flatten the rest.+ let mut sorted: Vec<u32> = h.to_vec();+ sorted.sort_unstable();+ let top = sorted[250].max(1) as f32 * 1.1;+ let mut pts = vec![pos2(r.left(), r.bottom())];+ for (i, v) in h.iter().enumerate() {+ let x = r.left() + (i as f32 + 0.5) / 256.0 * r.width();+ let y = r.bottom() - (*v as f32 / top).min(1.0) * r.height();+ pts.push(pos2(x, y));+ }+ pts.push(pos2(r.right(), r.bottom()));+ // One mesh of vertical strips: no anti-aliasing feather, so no seams between bins.+ let mut mesh = egui::Mesh::default();+ for w in pts.windows(2).skip(1).take(256) {+ let (a, b) = (w[0], w[1]);+ let i = mesh.vertices.len() as u32;+ for q in [pos2(a.x, r.bottom()), a, b, pos2(b.x, r.bottom())] {+ mesh.colored_vertex(q, color);+ }+ mesh.add_triangle(i, i + 1, i + 2);+ mesh.add_triangle(i, i + 2, i + 3);+ }+ p.add(mesh);+}++fn channel_color(ch: usize, t: &Tokens) -> Color32 {+ match ch {+ 1 => Color32::from_rgb(235, 80, 80),+ 2 => Color32::from_rgb(80, 205, 95),+ 3 => Color32::from_rgb(90, 140, 255),+ _ => t.text,+ }+}++fn channel_picker(ui: &mut egui::Ui, id: egui::Id, label: &str) -> usize {+ let mut ch: usize = ui.data(|d| d.get_temp(id)).unwrap_or(0);+ ui.horizontal(|ui| {+ let t = Tokens::get(ui.ctx());+ ui.label(egui::RichText::new(label).color(t.text_dim).size(12.0));+ let opts: Vec<(usize, &str)> = CHANNELS.iter().enumerate().map(|(i, (_, l))| (i, *l)).collect();+ crate::widgets::dropdown(ui, &format!("{id:?}-ch"), &mut ch, &opts, 110.0);+ });+ ui.data_mut(|d| d.insert_temp(id, ch));+ ch+}++// ---------------------------------------------------------------------------------------------+// Histogram panel++/// Histogram panel (Window › Histogram): whole-image histogram with Photoshop's statistics.+/// Recomputed at most every 250 ms while the document keeps changing (e.g. during painting).+pub fn histogram_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ let Some(st) = app.session.active() else {+ ui.label(egui::RichText::new("No document").color(t.text_faint));+ return;+ };+ let (doc_id, rev) = (st.doc.id, st.revision);+ let now = crate::gpu_canvas::now_ms();+ let stale = !matches!(&app.doc_hist, Some((d, r, _, _)) if *d == doc_id && *r == rev);+ let due = app.doc_hist.as_ref().is_none_or(|(d, _, at, _)| *d != doc_id || now - at > 250.0);+ if stale && due {+ let t0 = now;+ let h = Arc::new(compute_histograms(&st.doc, LayerId(u64::MAX)));+ app.perf.span("histogram", crate::gpu_canvas::now_ms() - t0);+ app.doc_hist = Some((doc_id, rev, now, h));+ } else if stale {+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(260));+ }+ let Some((_, _, _, h)) = app.doc_hist.clone() else { return };+ let size = app.session.active().map_or(photocraft_doc::Size::new(0, 0), |s| s.doc.size);+ // Statistics come from a downsampled cache (like Photoshop's cache levels).+ let level = (size.width.max(size.height) as f32 / 384.0).max(1.0).log2().ceil() as u32 + 1;+ let ch = channel_picker(ui, egui::Id::new("histogram-panel-ch"), "Channel:");+ let w = ui.available_width();+ let (r, _) = ui.allocate_exact_size(vec2(w, 100.0), Sense::hover());+ let p = ui.painter_at(r);+ p.rect_filled(r, 0.0, t.field);+ draw_histogram(&p, r, &h[ch], if ch == 0 { Color32::from_gray(if t.pro { 190 } else { 70 }) } else { channel_color(ch, &t) });+ if stale {+ // Photoshop's "cached data" warning triangle while the histogram lags the image.+ crate::icons::paint(ui, Rect::from_min_size(r.right_top() + vec2(-18.0, 2.0), vec2(16.0, 16.0)), "triangle-alert", 12.0, t.warning);+ }+ let hist = &h[ch];+ let n: u64 = hist.iter().map(|v| *v as u64).sum();+ if n == 0 {+ return;+ }+ let mean = hist.iter().enumerate().map(|(i, v)| i as f64 * *v as f64).sum::<f64>() / n as f64;+ let var = hist.iter().enumerate().map(|(i, v)| (i as f64 - mean).powi(2) * *v as f64).sum::<f64>() / n as f64;+ let mut acc = 0u64;+ let median = hist.iter().position(|v| {+ acc += *v as u64;+ acc * 2 >= n+ });+ ui.add_space(4.0);+ egui::Grid::new("hist-stats").num_columns(2).spacing(vec2(12.0, 2.0)).show(ui, |ui| {+ for (k, v) in [("Mean:", format!("{mean:.2}")), ("Std Dev:", format!("{:.2}", var.sqrt())), ("Median:", median.unwrap_or(0).to_string()), ("Pixels:", (size.width as u64 * size.height as u64).to_string()), ("Cache Level:", level.to_string())] {+ ui.label(egui::RichText::new(k).color(t.text_dim).size(11.5));+ ui.label(egui::RichText::new(v).font(crate::theme::mono(11.5)).color(t.text));+ ui.end_row();+ }+ });+}++// ---------------------------------------------------------------------------------------------+// Curves++/// Curve points (0–255) per channel from the adjustment: [rgb, red, green, blue].+fn curves_points(adj: &photocraft_doc::Adjustment) -> [Vec<[f32; 2]>; 4] {+ let conv = |v: &[photocraft_doc::adjust::CurvePoint]| v.iter().map(|p| [p.input * 255.0, p.output * 255.0]).collect::<Vec<_>>();+ match adj {+ photocraft_doc::Adjustment::Curves { master, per_channel } => [conv(master), conv(&per_channel[0]), conv(&per_channel[1]), conv(&per_channel[2])],+ _ => Default::default(),+ }+}++fn curves_params(pts: &[Vec<[f32; 2]>; 4]) -> Value {+ let arr = |v: &Vec<[f32; 2]>| json!(v.iter().map(|p| [p[0].round(), p[1].round()]).collect::<Vec<_>>());+ json!({"points": arr(&pts[0]), "red": arr(&pts[1]), "green": arr(&pts[2]), "blue": arr(&pts[3])})+}++fn lut_of(points: &[[f32; 2]]) -> Vec<f32> {+ let cp: Vec<photocraft_doc::adjust::CurvePoint> = points.iter().map(|p| photocraft_doc::adjust::CurvePoint { input: p[0] / 255.0, output: p[1] / 255.0 }).collect();+ photocraft_compose::adjust::curve_lut(&cp)+}++pub fn curves_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId) {+ let Some(adj) = app.session.active().and_then(|s| s.doc.layer(id)).and_then(|l| match &l.content {+ LayerContent::Adjustment(a) => Some(a.clone()),+ _ => None,+ }) else {+ return;+ };+ let t = Tokens::get(ui.ctx());+ let mem = egui::Id::new(("curves", id.0));+ let ch = channel_picker(ui, mem.with("ch"), "Channel:");+ let mut pts = curves_points(&adj);+ let hist = histograms(app, id);+ let side = ui.available_width().min(300.0);+ ui.add_space(4.0);+ let (full, resp) = ui.allocate_exact_size(vec2(side, side + 14.0), Sense::click_and_drag());+ let graph = Rect::from_min_size(full.min + vec2(14.0, 0.0), vec2(side - 14.0, side - 14.0));+ let p = ui.painter_at(full);+ p.rect_filled(graph, 0.0, t.field);+ draw_histogram(&p, graph, &hist[ch], Color32::from_gray(if t.pro { 88 } else { 170 }).gamma_multiply(0.75));+ // Grid: quarters (Photoshop default), baseline diagonal.+ for i in 1..4 {+ let f = i as f32 / 4.0;+ let g = Stroke::new(1.0, t.separator);+ p.line_segment([pos2(graph.left() + f * graph.width(), graph.top()), pos2(graph.left() + f * graph.width(), graph.bottom())], g);+ p.line_segment([pos2(graph.left(), graph.top() + f * graph.height()), pos2(graph.right(), graph.top() + f * graph.height())], g);+ }+ p.line_segment([graph.left_bottom(), graph.right_top()], Stroke::new(1.0, t.separator.gamma_multiply(1.6)));+ p.rect_stroke(graph, 0.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+ // Gradient bars: input (bottom) and output (left).+ let hbar = Rect::from_min_max(pos2(graph.left(), graph.bottom() + 4.0), pos2(graph.right(), graph.bottom() + 12.0));+ let vbar = Rect::from_min_max(pos2(full.left(), graph.top()), pos2(full.left() + 8.0, graph.bottom()));+ let mut mesh = egui::Mesh::default();+ let (c0, c1) = (Color32::BLACK, if ch == 0 { Color32::WHITE } else { channel_color(ch, &t) });+ mesh.colored_vertex(hbar.left_top(), c0);+ mesh.colored_vertex(hbar.right_top(), c1);+ mesh.colored_vertex(hbar.right_bottom(), c1);+ mesh.colored_vertex(hbar.left_bottom(), c0);+ mesh.colored_vertex(vbar.left_bottom(), c0);+ mesh.colored_vertex(vbar.right_bottom(), c0);+ mesh.colored_vertex(vbar.right_top(), c1);+ mesh.colored_vertex(vbar.left_top(), c1);+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(0, 2, 3);+ mesh.add_triangle(4, 5, 6);+ mesh.add_triangle(4, 6, 7);+ p.add(mesh);+ let to_scr = |q: [f32; 2]| pos2(graph.left() + q[0] / 255.0 * graph.width(), graph.bottom() - q[1] / 255.0 * graph.height());+ let to_val = |s: Pos2| [((s.x - graph.left()) / graph.width() * 255.0).clamp(0.0, 255.0), ((graph.bottom() - s.y) / graph.height() * 255.0).clamp(0.0, 255.0)];+ // Other channels' curves, faintly, when editing the composite (Photoshop shows them too).+ let draw_curve = |pts: &[[f32; 2]], color: Color32, width: f32| {+ let lut = lut_of(pts);+ let n = lut.len();+ let line: Vec<Pos2> = (0..n).step_by((n / 256).max(1)).map(|i| to_scr([i as f32 / (n - 1) as f32 * 255.0, lut[i].clamp(0.0, 1.0) * 255.0])).collect();+ p.add(egui::Shape::line(line, Stroke::new(width, color)));+ };+ if ch == 0 {+ for (c, cp) in pts.iter().enumerate().skip(1) {+ if cp.len() > 2 || cp.first().is_some_and(|q| q[1] != 0.0) || cp.last().is_some_and(|q| q[1] != 255.0) {+ draw_curve(cp, channel_color(c, &t).gamma_multiply(0.8), 1.0);+ }+ }+ }+ draw_curve(&pts[ch], channel_color(ch, &t), 1.5);+ // Interaction.+ let sel_id = mem.with("sel");+ let mut sel: Option<usize> = ui.data(|d| d.get_temp(sel_id)).flatten();+ let gesture_id = mem.with("gesture");+ let mut changed = false;+ let cur = &mut pts[ch];+ if (resp.drag_started() || resp.clicked())+ && let Some(pos) = resp.interact_pointer_pos()+ {+ let hit = cur.iter().enumerate().map(|(i, q)| (i, to_scr(*q).distance(pos))).filter(|(_, d)| *d < 9.0).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i);+ sel = match hit {+ Some(i) => Some(i),+ None if graph.contains(pos) => {+ let v = to_val(pos);+ let i = cur.iter().position(|q| q[0] > v[0]).unwrap_or(cur.len());+ cur.insert(i, v);+ changed = true;+ Some(i)+ }+ None => sel,+ };+ ui.data_mut(|d| d.insert_temp(gesture_id, ui.input(|i| i.time).to_bits()));+ }+ if resp.dragged()+ && let (Some(i), Some(pos)) = (sel, resp.interact_pointer_pos())+ && i < cur.len()+ {+ let far = !graph.expand(24.0).contains(pos);+ let endpoint = i == 0 || i + 1 == cur.len();+ if far && !endpoint && cur.len() > 2 {+ // Dragging a point out of the graph deletes it (Photoshop).+ cur.remove(i);+ sel = None;+ } else {+ let mut v = to_val(pos);+ let lo = if i > 0 { cur[i - 1][0] + 1.0 } else { 0.0 };+ let hi = if i + 1 < cur.len() { cur[i + 1][0] - 1.0 } else { 255.0 };+ v[0] = v[0].clamp(lo, hi.max(lo));+ cur[i] = v;+ }+ changed = true;+ }+ // Points.+ for (i, q) in cur.iter().enumerate() {+ let r = Rect::from_center_size(to_scr(*q), vec2(7.0, 7.0));+ if Some(i) == sel {+ p.rect_filled(r, 0.0, t.text);+ p.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::BLACK), egui::StrokeKind::Outside);+ } else {+ p.rect_filled(r, 0.0, t.field);+ p.rect_stroke(r, 0.0, Stroke::new(1.0, t.text), egui::StrokeKind::Inside);+ }+ }+ // Input / Output of the selected point.+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ let i = sel.filter(|i| *i < cur.len());+ let (mut vi, mut vo) = i.map_or((0.0, 0.0), |i| (cur[i][0], cur[i][1]));+ ui.label(egui::RichText::new("Input:").color(t.text_dim).size(12.0));+ let ri = ui.add_enabled_ui(i.is_some(), |ui| crate::widgets::value_field(ui, &mut vi, 0.0..=255.0, "", 52.0)).inner;+ ui.label(egui::RichText::new("Output:").color(t.text_dim).size(12.0));+ let ro = ui.add_enabled_ui(i.is_some(), |ui| crate::widgets::value_field(ui, &mut vo, 0.0..=255.0, "", 52.0)).inner;+ if let Some(i) = i+ && (ri.changed() || ro.changed())+ {+ let lo = if i > 0 { cur[i - 1][0] + 1.0 } else { 0.0 };+ let hi = if i + 1 < cur.len() { cur[i + 1][0] - 1.0 } else { 255.0 };+ cur[i] = [vi.round().clamp(lo, hi.max(lo)), vo.round().clamp(0.0, 255.0)];+ changed = true;+ }+ });+ ui.data_mut(|d| d.insert_temp(sel_id, sel));+ if changed {+ let g: u64 = ui.data(|d| d.get_temp(gesture_id)).unwrap_or(0);+ commit(app, id, curves_params(&pts), &g.to_string());+ }+}++// ---------------------------------------------------------------------------------------------+// Levels++type Lv = [f32; 5]; // in_black, gamma, in_white, out_black, out_white (0–255, gamma as is)++fn levels_values(adj: &photocraft_doc::Adjustment) -> [Lv; 4] {+ let conv = |c: &photocraft_doc::adjust::LevelsChannel| [c.in_black * 255.0, c.gamma, c.in_white * 255.0, c.out_black * 255.0, c.out_white * 255.0];+ match adj {+ photocraft_doc::Adjustment::Levels { master, per_channel } => [conv(master), conv(&per_channel[0]), conv(&per_channel[1]), conv(&per_channel[2])],+ _ => [[0.0, 1.0, 255.0, 0.0, 255.0]; 4],+ }+}++fn levels_params(v: &[Lv; 4]) -> Value {+ let obj = |l: &Lv| json!({"inBlack": l[0].round(), "gamma": (l[1] * 100.0).round() / 100.0, "inWhite": l[2].round(), "outBlack": l[3].round(), "outWhite": l[4].round()});+ let mut p = obj(&v[0]);+ p["red"] = obj(&v[1]);+ p["green"] = obj(&v[2]);+ p["blue"] = obj(&v[3]);+ p+}++/// A triangular slider handle below a bar.+fn handle(p: &egui::Painter, x: f32, y: f32, fill: Color32, stroke: Color32) {+ p.add(egui::Shape::convex_polygon(vec![pos2(x, y), pos2(x + 5.5, y + 9.0), pos2(x - 5.5, y + 9.0)], fill, Stroke::new(1.0, stroke)));+}++/// Input level (0–255) where the gamma slider sits: the input that maps to 50% grey.+fn gamma_pos(black: f32, white: f32, gamma: f32) -> f32 {+ black + (white - black) * 0.5f32.powf(gamma)+}++fn gamma_from_pos(black: f32, white: f32, x: f32) -> f32 {+ let t = ((x - black) / (white - black).max(1.0)).clamp(0.01, 0.99);+ (t.ln() / 0.5f32.ln()).clamp(0.01, 9.99)+}++pub fn levels_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId) {+ let Some(adj) = app.session.active().and_then(|s| s.doc.layer(id)).and_then(|l| match &l.content {+ LayerContent::Adjustment(a) => Some(a.clone()),+ _ => None,+ }) else {+ return;+ };+ let t = Tokens::get(ui.ctx());+ let mem = egui::Id::new(("levels", id.0));+ let hist = histograms(app, id);+ let mut ch = 0;+ let mut auto = false;+ ui.horizontal(|ui| {+ ch = channel_picker(ui, mem.with("ch"), "");+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ auto = crate::widgets::secondary_button(ui, "Auto", 0.0).clicked();+ });+ });+ let mut v = levels_values(&adj);+ let mut changed = false;+ let gesture_id = mem.with("gesture");+ if auto {+ // Clip 0.1% at each end of the composite histogram (Photoshop's default auto clipping).+ let h = &hist[if ch == 0 { 0 } else { ch }];+ let total: u32 = h.iter().sum();+ let clip = (total as f32 * 0.001) as u32;+ let (mut acc, mut lo) = (0u32, 0usize);+ while lo < 254 && acc + h[lo] <= clip {+ acc += h[lo];+ lo += 1;+ }+ let (mut acc, mut hi) = (0u32, 255usize);+ while hi > lo + 1 && acc + h[hi] <= clip {+ acc += h[hi];+ hi -= 1;+ }+ v[ch][0] = lo as f32;+ v[ch][2] = hi as f32;+ v[ch][1] = 1.0;+ changed = true;+ ui.data_mut(|d| d.insert_temp(gesture_id, ui.input(|i| i.time).to_bits()));+ }+ let w = ui.available_width().min(300.0);+ // Histogram.+ let (hr, _) = ui.allocate_exact_size(vec2(w, 110.0), Sense::hover());+ let hr = hr.shrink2(vec2(6.0, 0.0));+ let p = ui.painter_at(hr.expand(1.0));+ p.rect_filled(hr, 0.0, t.field);+ draw_histogram(&p, hr, &hist[ch], if ch == 0 { Color32::from_gray(if t.pro { 180 } else { 60 }) } else { channel_color(ch, &t).gamma_multiply(0.85) });+ p.rect_stroke(hr, 0.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);+ // Input sliders: black, gamma, white.+ let (sr, sresp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag());+ let track = sr.shrink2(vec2(6.0, 0.0));+ let xpos = |val: f32| track.left() + val / 255.0 * track.width();+ let xval = |x: f32| ((x - track.left()) / track.width() * 255.0).clamp(0.0, 255.0);+ let [b, g, wv, ob, ow] = v[ch];+ let gx = gamma_pos(b, wv, g);+ let drag_id = mem.with("drag");+ let mut which: Option<u8> = ui.data(|d| d.get_temp(drag_id)).flatten();+ if sresp.drag_started()+ && let Some(pos) = sresp.interact_pointer_pos()+ {+ let d = [(0u8, (xpos(b) - pos.x).abs()), (1, (xpos(gx) - pos.x).abs()), (2, (xpos(wv) - pos.x).abs())];+ which = d.iter().min_by(|a, c| a.1.total_cmp(&c.1)).map(|x| x.0);+ ui.data_mut(|d| d.insert_temp(gesture_id, ui.input(|i| i.time).to_bits()));+ }+ if sresp.dragged()+ && let (Some(k), Some(pos)) = (which, sresp.interact_pointer_pos())+ {+ let x = xval(pos.x);+ match k {+ 0 => {+ v[ch][0] = x.min(wv - 2.0).round();+ }+ 2 => {+ v[ch][2] = x.max(b + 2.0).round();+ }+ _ => v[ch][1] = gamma_from_pos(b, wv, x),+ }+ changed = true;+ }+ if sresp.drag_stopped() {+ which = None;+ }+ ui.data_mut(|d| d.insert_temp(drag_id, which));+ let sp = ui.painter_at(sr.expand(6.0));+ let [b, g, wv, _, _] = v[ch];+ handle(&sp, xpos(b), sr.top() + 2.0, Color32::BLACK, t.text_dim);+ handle(&sp, xpos(gamma_pos(b, wv, g)), sr.top() + 2.0, Color32::from_gray(128), t.text_dim);+ handle(&sp, xpos(wv), sr.top() + 2.0, Color32::WHITE, t.text_dim);+ ui.horizontal(|ui| {+ let fw = ((w - 16.0) / 3.0).min(70.0);+ let mut nb = v[ch][0];+ let mut ng = v[ch][1];+ let mut nw = v[ch][2];+ if crate::widgets::value_field(ui, &mut nb, 0.0..=253.0, "", fw).changed() {+ v[ch][0] = nb.round().min(v[ch][2] - 2.0);+ changed = true;+ }+ ui.add_space(((w - 3.0 * fw) / 2.0 - 12.0).max(0.0));+ if crate::widgets::value_field(ui, &mut ng, 0.01..=9.99, "", fw).changed() {+ v[ch][1] = ng.clamp(0.01, 9.99);+ changed = true;+ }+ ui.add_space(((w - 3.0 * fw) / 2.0 - 12.0).max(0.0));+ if crate::widgets::value_field(ui, &mut nw, 2.0..=255.0, "", fw).changed() {+ v[ch][2] = nw.round().max(v[ch][0] + 2.0);+ changed = true;+ }+ });+ // Output levels.+ ui.add_space(6.0);+ ui.label(egui::RichText::new("Output Levels").color(t.text_dim).size(12.0));+ let (ob_r, _) = ui.allocate_exact_size(vec2(w, 10.0), Sense::hover());+ let ob_r = ob_r.shrink2(vec2(6.0, 0.0));+ let mut mesh = egui::Mesh::default();+ let c1 = if ch == 0 { Color32::WHITE } else { channel_color(ch, &t) };+ mesh.colored_vertex(ob_r.left_top(), Color32::BLACK);+ mesh.colored_vertex(ob_r.right_top(), c1);+ mesh.colored_vertex(ob_r.right_bottom(), c1);+ mesh.colored_vertex(ob_r.left_bottom(), Color32::BLACK);+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(0, 2, 3);+ ui.painter().add(mesh);+ let (or, oresp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag());+ let otrack = or.shrink2(vec2(6.0, 0.0));+ let oxpos = |val: f32| otrack.left() + val / 255.0 * otrack.width();+ let oval = |x: f32| ((x - otrack.left()) / otrack.width() * 255.0).clamp(0.0, 255.0);+ let odrag_id = mem.with("odrag");+ let mut owhich: Option<u8> = ui.data(|d| d.get_temp(odrag_id)).flatten();+ if oresp.drag_started()+ && let Some(pos) = oresp.interact_pointer_pos()+ {+ owhich = Some(if (oxpos(ob) - pos.x).abs() <= (oxpos(ow) - pos.x).abs() { 0 } else { 1 });+ ui.data_mut(|d| d.insert_temp(gesture_id, ui.input(|i| i.time).to_bits()));+ }+ if oresp.dragged()+ && let (Some(k), Some(pos)) = (owhich, oresp.interact_pointer_pos())+ {+ v[ch][if k == 0 { 3 } else { 4 }] = oval(pos.x).round();+ changed = true;+ }+ if oresp.drag_stopped() {+ owhich = None;+ }+ ui.data_mut(|d| d.insert_temp(odrag_id, owhich));+ let op = ui.painter_at(or.expand(6.0));+ handle(&op, oxpos(v[ch][3]), or.top() + 2.0, Color32::BLACK, t.text_dim);+ handle(&op, oxpos(v[ch][4]), or.top() + 2.0, Color32::WHITE, t.text_dim);+ ui.horizontal(|ui| {+ let fw = ((w - 16.0) / 3.0).min(70.0);+ let (mut a, mut c) = (v[ch][3], v[ch][4]);+ if crate::widgets::value_field(ui, &mut a, 0.0..=255.0, "", fw).changed() {+ v[ch][3] = a.round();+ changed = true;+ }+ ui.add_space((w - 2.0 * fw - 16.0).max(0.0));+ if crate::widgets::value_field(ui, &mut c, 0.0..=255.0, "", fw).changed() {+ v[ch][4] = c.round();+ changed = true;+ }+ });+ let _ = (g, ob, ow);+ if changed {+ let gk: u64 = ui.data(|d| d.get_temp(gesture_id)).unwrap_or(0);+ commit(app, id, levels_params(&v), &gk.to_string());+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn gamma_slider_position_round_trips() {+ for g in [0.3f32, 1.0, 1.8, 4.0] {+ let x = gamma_pos(20.0, 230.0, g);+ assert!((gamma_from_pos(20.0, 230.0, x) - g).abs() < 1e-3, "{g}");+ }+ // Moving the grey slider left brightens (gamma > 1), as in Photoshop.+ assert!(gamma_from_pos(0.0, 255.0, 80.0) > 1.0);+ assert_eq!(gamma_pos(0.0, 255.0, 1.0), 127.5);+ }++ #[test]+ fn params_round_trip_through_engine() {+ let v: [Lv; 4] = [[10.0, 1.2, 240.0, 5.0, 250.0], [0.0, 1.0, 255.0, 0.0, 255.0], [3.0, 0.8, 200.0, 0.0, 255.0], [0.0, 1.0, 255.0, 0.0, 255.0]];+ let adj = photocraft_engine::commands::adjustment_from_params("levels", &levels_params(&v));+ let back = levels_values(&adj);+ for (a, b) in v.iter().flatten().zip(back.iter().flatten()) {+ assert!((a - b).abs() < 0.01, "{a} vs {b}");+ }+ let pts: [Vec<[f32; 2]>; 4] = [vec![[0.0, 0.0], [128.0, 150.0], [255.0, 255.0]], vec![[0.0, 10.0], [255.0, 245.0]], vec![[0.0, 0.0], [255.0, 255.0]], vec![[0.0, 0.0], [255.0, 255.0]]];+ let adj = photocraft_engine::commands::adjustment_from_params("curves", &curves_params(&pts));+ assert_eq!(curves_points(&adj), pts);+ }++ #[test]+ fn histogram_ignores_the_edited_adjustment() {+ let mut s = photocraft_engine::Session::new();+ s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); // white+ s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();+ let st = s.active().unwrap();+ let h = compute_histograms(&st.doc, st.active_layer.unwrap());+ assert!(h[0][255] > 0 && h[0][0] == 0, "sees the white image, not the inverted result");+ }+}diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rsnew file mode 100644index 000000000..b88d7db8c--- /dev/null+++ b/crates/ui-egui/src/transform_tool.rs@@ -0,0 +1,546 @@+//! Free Transform (⌘T): bounding box with handles over the canvas, live preview, commit via the+//! engine's `edit.transform` (one quad for scale/rotate/skew/distort/perspective).+//!+//! Gestures follow Photoshop CC: corner drag scales proportionally (⇧ for free), edges scale one+//! axis, ⌥ scales about the reference point, ⌘-drag a corner distorts, drag outside rotates+//! (⇧ snaps to 15°), drag inside moves, the reference point can be dragged. ↩ commits, Esc cancels.++use std::sync::Arc;++use egui::{Color32, CursorIcon, Pos2, Stroke, pos2, vec2};+use photocraft_algo::transform::Homography;+use photocraft_doc::{Document, LayerContent, LayerId};+use serde_json::json;++use crate::PhotocraftApp;+use crate::canvas::{ToolEvent, ViewXform};+use crate::state::TransformSession;++/// Preview state that isn't serialisable: the document without the transformed pixels, and a+/// texture of those pixels.+pub struct TransformPreview {+ pub session: u64,+ pub doc: Arc<Document>,+ pub texture: egui::TextureHandle,+ pub opacity: f32,+ gesture: Option<Gesture>,+}++fn corners(r: [f64; 4]) -> [[f64; 2]; 4] {+ [[r[0], r[1]], [r[2], r[1]], [r[2], r[3]], [r[0], r[3]]]+}++/// Start Free Transform on the active layer (or its selected pixels).+pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {+ let st = app.session.active().ok_or("no document")?;+ let id = st.active_layer.ok_or("no active layer")?;+ let doc = st.doc.clone();+ let layer = doc.layer(id).ok_or("no layer")?;+ if matches!(layer.content, LayerContent::Adjustment(_)) && layer.mask.is_none() {+ return Err("Adjustment layers have nothing to transform".into());+ }+ let b = photocraft_engine::transform_cmds::transform_bounds(&doc, layer);+ if b.is_empty() {+ return Err("Could not transform: the layer is empty".into());+ }+ crate::type_tool::commit(app);+ let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64];+ let session = app.ui.alloc_id();+ // Preview document: the moving pixels removed (layer hidden, or the selection lifted out).+ let mut pd = (*doc).clone();+ let mut lifted = None;+ if let Some(sel) = doc.selection.clone().filter(|_| !layer.is_group() && layer.surface().is_some()) {+ if let Some(surf) = pd.layer_mut(id).and_then(|l| l.surface_mut()) {+ let (l, rest) = photocraft_engine::transform_cmds::split_selected(surf, &sel);+ *surf = rest;+ lifted = Some(l);+ }+ } else if let Some(l) = pd.layer_mut(id) {+ l.visible = false;+ }+ let image = preview_image(&doc, id, lifted.as_ref(), b);+ let texture = ctx.load_texture(format!("transform-{session}"), image, egui::TextureOptions::LINEAR);+ app.transform_preview = Some(TransformPreview { session, doc: Arc::new(pd), texture, opacity: layer.opacity * layer.fill_opacity, gesture: None });+ app.ui.transform = Some(TransformSession {+ session,+ layer: id.0,+ rect,+ quad: corners(rect),+ pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0],+ interpolation: "bicubic".into(),+ });+ Ok(())+}++/// Texture of the moving pixels over `b`, at most 2048 px on the long side.+fn preview_image(doc: &Document, id: LayerId, lifted: Option<&photocraft_raster::Surface>, b: photocraft_geom::Rect) -> egui::ColorImage {+ let (w, h) = (b.width() as usize, b.height() as usize);+ let k = w.max(h).div_ceil(2048).max(1);+ let (tw, th) = (w.div_ceil(k), h.div_ceil(k));+ let mut px = vec![Color32::TRANSPARENT; tw * th];+ let layer = doc.layer(id);+ // Groups and type/fill layers preview from a flattened render of just that layer.+ let rendered;+ let surf: Option<&photocraft_raster::Surface> = match (lifted, layer.and_then(|l| l.surface())) {+ (Some(s), _) => Some(s),+ (None, Some(s)) if layer.is_some_and(|l| matches!(l.content, LayerContent::Raster(_))) => Some(s),+ _ => {+ let mut solo = doc.clone();+ for l in solo.layers.iter_mut() {+ if l.id != id && doc.layer(id).is_some_and(|_| !contains(l, id)) {+ l.visible = false;+ }+ }+ let buf = photocraft_compose::render(&solo, b);+ let mut s = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);+ let flat: Vec<f32> = buf.px.iter().flat_map(|p| *p).collect();+ s.write_region(b, &flat);+ rendered = s;+ Some(&rendered)+ }+ };+ let Some(surf) = surf else { return egui::ColorImage::new([tw, th], px) };+ let mut row = vec![[0u8; 4]; w];+ for ty in 0..th {+ let y = b.y0 + (ty * k) as i32;+ surf.read_rgba8_into(photocraft_geom::Rect::new(b.x0, y, b.x1, y + 1), &mut row);+ for tx in 0..tw {+ let p = row[(tx * k).min(w - 1)];+ px[ty * tw + tx] = Color32::from_rgba_unmultiplied(p[0], p[1], p[2], p[3]);+ }+ }+ egui::ColorImage::new([tw, th], px)+}++fn contains(l: &photocraft_doc::Layer, id: LayerId) -> bool {+ l.id == id || matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| contains(c, id)))+}++pub fn commit(app: &mut PhotocraftApp) {+ let Some(t) = app.ui.transform.take() else { return };+ app.transform_preview = None;+ if t.quad == corners(t.rect) {+ return; // untouched: nothing to do (Photoshop adds no history step either)+ }+ if let Err(e) = app.run("edit.transform", json!({"layer": t.layer, "rect": t.rect, "quad": t.quad, "interpolation": t.interpolation})) {+ app.ui.status = e;+ }+}++pub fn cancel(app: &mut PhotocraftApp) {+ app.ui.transform = None;+ app.transform_preview = None;+}++/// Which part of the box a document point hits.+#[derive(Clone, Copy, Debug, PartialEq)]+enum Hit {+ Corner(usize),+ Edge(usize),+ Pivot,+ Inside,+ Outside,+}++fn hit(t: &TransformSession, p: [f64; 2], tol: f64) -> Hit {+ let d = |a: [f64; 2]| ((a[0] - p[0]).powi(2) + (a[1] - p[1]).powi(2)).sqrt();+ if d(t.pivot) < tol {+ return Hit::Pivot;+ }+ for i in 0..4 {+ if d(t.quad[i]) < tol {+ return Hit::Corner(i);+ }+ }+ for i in 0..4 {+ let (a, b) = (t.quad[i], t.quad[(i + 1) % 4]);+ if d([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]) < tol {+ return Hit::Edge(i);+ }+ }+ if inside(&t.quad, p) { Hit::Inside } else { Hit::Outside }+}++fn inside(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool {+ let mut c = false;+ for i in 0..4 {+ let (a, b) = (q[i], q[(i + 3) % 4]);+ if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] {+ c = !c;+ }+ }+ c+}++/// Transient drag state (kept in egui memory; not part of the serialised session).+#[derive(Clone, Copy, Debug)]+struct Gesture {+ hit: Hit,+ start: [f64; 2],+ quad0: [[f64; 2]; 4],+ pivot0: [f64; 2],+}++/// Pointer input while transforming. Returns false when no transform is active.+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {+ let Some(t) = app.ui.transform.clone() else { return false };+ let tol = 8.0 / app.current_zoom().max(0.01) as f64;+ let Some(pv) = app.transform_preview.as_mut() else { return false };+ match ev {+ ToolEvent::Down { x, y, .. } => pv.gesture = Some(Gesture { hit: hit(&t, [x, y], tol), start: [x, y], quad0: t.quad, pivot0: t.pivot }),+ ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => {+ let g = pv.gesture;+ if matches!(ev, ToolEvent::Up { .. }) {+ pv.gesture = None;+ }+ if let (Some(g), Some(s)) = (g, app.ui.transform.as_mut()) {+ apply_drag(s, g, [x, y], mods);+ }+ }+ }+ true+}++fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods: egui::Modifiers) {+ let (dx, dy) = (p[0] - g.start[0], p[1] - g.start[1]);+ match g.hit {+ Hit::Inside => {+ s.quad = g.quad0.map(|q| [q[0] + dx, q[1] + dy]);+ s.pivot = [g.pivot0[0] + dx, g.pivot0[1] + dy];+ }+ Hit::Pivot => s.pivot = p,+ Hit::Outside => {+ let a0 = (g.start[1] - g.pivot0[1]).atan2(g.start[0] - g.pivot0[0]);+ let a1 = (p[1] - g.pivot0[1]).atan2(p[0] - g.pivot0[0]);+ let mut da = a1 - a0;+ if mods.shift {+ // Snap the resulting angle to 15° steps.+ let base = (g.quad0[1][1] - g.quad0[0][1]).atan2(g.quad0[1][0] - g.quad0[0][0]);+ let step = 15f64.to_radians();+ da = ((base + da) / step).round() * step - base;+ }+ let (sn, cs) = da.sin_cos();+ let c = g.pivot0;+ s.quad = g.quad0.map(|q| {+ let (x, y) = (q[0] - c[0], q[1] - c[1]);+ [c[0] + x * cs - y * sn, c[1] + x * sn + y * cs]+ });+ }+ Hit::Corner(i) if mods.command => {+ // Distort: move the corner freely.+ s.quad = g.quad0;+ s.quad[i] = [g.quad0[i][0] + dx, g.quad0[i][1] + dy];+ }+ Hit::Corner(_) | Hit::Edge(_) => {+ // Work in the box's own (unit) frame so rotated/skewed boxes scale along their axes.+ let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], g.quad0) else { return };+ let Some(inv) = h.inverse() else { return };+ let (u, v) = inv.apply(p[0], p[1]);+ let (pu, pv) = inv.apply(g.pivot0[0], g.pivot0[1]);+ // Moving edges/corner in unit space: [u0, v0, u1, v1] starting as [0, 0, 1, 1].+ let mut r = [0.0f64, 0.0, 1.0, 1.0];+ let (mu, mv) = match g.hit {+ Hit::Corner(0) => ((true, false), (true, false)),+ Hit::Corner(1) => ((false, true), (true, false)),+ Hit::Corner(2) => ((false, true), (false, true)),+ Hit::Corner(3) => ((true, false), (false, true)),+ Hit::Edge(0) => ((false, false), (true, false)),+ Hit::Edge(1) => ((false, true), (false, false)),+ Hit::Edge(2) => ((false, false), (false, true)),+ _ => ((true, false), (false, false)),+ };+ if mu.0 {+ r[0] = u;+ }+ if mu.1 {+ r[2] = u;+ }+ if mv.0 {+ r[1] = v;+ }+ if mv.1 {+ r[3] = v;+ }+ // ⌥: symmetric about the reference point.+ if mods.alt {+ if mu.0 {+ r[2] = 2.0 * pu - r[0];+ }+ if mu.1 {+ r[0] = 2.0 * pu - r[2];+ }+ if mv.0 {+ r[3] = 2.0 * pv - r[1];+ }+ if mv.1 {+ r[1] = 2.0 * pv - r[3];+ }+ }+ // Corners scale proportionally by default (Photoshop CC); ⇧ frees them.+ let corner = matches!(g.hit, Hit::Corner(_));+ if corner && !mods.shift {+ let (sx, sy) = (r[2] - r[0], r[3] - r[1]);+ let k = if sx.abs() > sy.abs() { sx.abs() } else { sy.abs() };+ let (nx, ny) = (k * sx.signum(), k * sy.signum());+ let (ax, ay) = if mods.alt { (pu, pv) } else { (if mu.0 { r[2] } else { r[0] }, if mv.0 { r[3] } else { r[1] }) };+ let fx = if mods.alt { 0.5 } else if mu.0 { 1.0 } else { 0.0 };+ let fy = if mods.alt { 0.5 } else if mv.0 { 1.0 } else { 0.0 };+ r[0] = ax - nx * fx;+ r[2] = r[0] + nx;+ r[1] = ay - ny * fy;+ r[3] = r[1] + ny;+ }+ let map = |a: f64, b: f64| {+ let (x, y) = h.apply(a, b);+ [x, y]+ };+ s.quad = [map(r[0], r[1]), map(r[2], r[1]), map(r[2], r[3]), map(r[0], r[3])];+ let (x, y) = h.apply(pu, pv);+ s.pivot = [x, y];+ }+ }+}++/// Cursor for hovering a document point while transforming.+pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option<CursorIcon> {+ let t = app.ui.transform.as_ref()?;+ let tol = 8.0 / app.current_zoom().max(0.01) as f64;+ Some(match hit(t, p, tol) {+ Hit::Corner(0 | 2) => CursorIcon::ResizeNwSe,+ Hit::Corner(_) => CursorIcon::ResizeNeSw,+ Hit::Edge(0 | 2) => CursorIcon::ResizeVertical,+ Hit::Edge(_) => CursorIcon::ResizeHorizontal,+ Hit::Pivot => CursorIcon::Crosshair,+ Hit::Inside => CursorIcon::Move,+ Hit::Outside => CursorIcon::Alias,+ })+}++/// Warped preview of the moving pixels plus the box, handles and reference point.+pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {+ let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return };+ let scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32);+ if let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], t.quad) {+ // A 24×24 grid keeps perspective previews straight.+ let n = 24;+ let mut mesh = egui::Mesh::with_texture(pv.texture.id());+ let tint = Color32::from_white_alpha((pv.opacity.clamp(0.0, 1.0) * 255.0) as u8);+ for j in 0..=n {+ for i in 0..=n {+ let (u, v) = (i as f64 / n as f64, j as f64 / n as f64);+ let (x, y) = h.apply(u, v);+ mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(x as f32, y as f32), uv: pos2(u as f32, v as f32), color: tint });+ }+ }+ for j in 0..n {+ for i in 0..n {+ let a = (j * (n + 1) + i) as u32;+ mesh.add_triangle(a, a + 1, a + n as u32 + 2);+ mesh.add_triangle(a, a + n as u32 + 2, a + n as u32 + 1);+ }+ }+ painter.add(mesh);+ }+ let accent = crate::theme::Tokens::get(painter.ctx()).accent;+ let pts: Vec<Pos2> = t.quad.iter().map(|q| scr(*q)).collect();+ painter.add(egui::Shape::closed_line(pts.clone(), Stroke::new(1.0, accent)));+ let mids: Vec<Pos2> = (0..4).map(|i| pts[i].lerp(pts[(i + 1) % 4], 0.5)).collect();+ for p in pts.iter().chain(mids.iter()) {+ let r = egui::Rect::from_center_size(*p, vec2(7.0, 7.0));+ painter.rect_filled(r, 0.0, Color32::WHITE);+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside);+ }+ // Reference point (Photoshop's crosshair circle).+ let c = scr(t.pivot);+ painter.circle_stroke(c, 5.0, Stroke::new(1.0, Color32::WHITE));+ painter.circle_stroke(c, 5.0, Stroke::new(0.5, Color32::BLACK));+ painter.line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, Color32::WHITE));+ painter.line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::WHITE));+}++/// Scale (%), angle (°) and translation implied by the current quad (affine readout).+fn readout(t: &TransformSession) -> (f64, f64, f64, f64) {+ let (w0, h0) = (t.rect[2] - t.rect[0], t.rect[3] - t.rect[1]);+ let e = [t.quad[1][0] - t.quad[0][0], t.quad[1][1] - t.quad[0][1]];+ let f = [t.quad[3][0] - t.quad[0][0], t.quad[3][1] - t.quad[0][1]];+ let sx = (e[0].hypot(e[1]) / w0.max(1e-9)) * 100.0;+ let sy = (f[0].hypot(f[1]) / h0.max(1e-9)) * 100.0;+ (sx, sy, e[1].atan2(e[0]).to_degrees(), 0.0)+}++/// Options bar while transforming: reference point X/Y, W/H %, angle, interpolation, ✓ / ⊘.+pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ let Some(t) = app.ui.transform.clone() else { return };+ let tk = crate::theme::Tokens::get(ui.ctx());+ let (sx, sy, angle, _) = readout(&t);+ let lbl = |ui: &mut egui::Ui, s: &str| {+ ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0));+ };+ let mut px = t.pivot[0] as f32;+ let mut py = t.pivot[1] as f32;+ lbl(ui, "X:");+ let rx = crate::widgets::value_field(ui, &mut px, -30000.0..=30000.0, "px", 72.0);+ lbl(ui, "Y:");+ let ry = crate::widgets::value_field(ui, &mut py, -30000.0..=30000.0, "px", 72.0);+ if (rx.changed() || ry.changed())+ && let Some(s) = app.ui.transform.as_mut()+ {+ let (dx, dy) = (px as f64 - s.pivot[0], py as f64 - s.pivot[1]);+ s.quad = s.quad.map(|q| [q[0] + dx, q[1] + dy]);+ s.pivot = [px as f64, py as f64];+ }+ crate::widgets::vline(ui, 22.0);+ let (mut w, mut h) = (sx as f32, sy as f32);+ lbl(ui, "W:");+ let rw = crate::widgets::value_field(ui, &mut w, -10000.0..=10000.0, "%", 66.0);+ let link_id = egui::Id::new("transform-link");+ let mut link: bool = ui.data(|d| d.get_temp(link_id)).unwrap_or(true);+ if crate::icons::button(ui, if link { "link" } else { "unlink" }, 22.0, link, "Maintain aspect ratio").clicked() {+ link = !link;+ ui.data_mut(|d| d.insert_temp(link_id, link));+ }+ lbl(ui, "H:");+ let rh = crate::widgets::value_field(ui, &mut h, -10000.0..=10000.0, "%", 66.0);+ if rw.changed() || rh.changed() {+ let (kx, ky) = if link {+ let k = if rw.changed() { w as f64 / sx.max(1e-9) } else { h as f64 / sy.max(1e-9) };+ (k, k)+ } else {+ (w as f64 / sx.max(1e-9), h as f64 / sy.max(1e-9))+ };+ scale_about_pivot(app, kx, ky);+ }+ crate::widgets::vline(ui, 22.0);+ let mut a = angle as f32;+ let (r, resp) = ui.allocate_exact_size(vec2(18.0, 22.0), egui::Sense::hover());+ crate::icons::paint(ui, r, "rotate-cw", 13.0, tk.text_dim);+ resp.on_hover_text("Rotate");+ if crate::widgets::value_field(ui, &mut a, -180.0..=180.0, "°", 60.0).changed() {+ rotate_about_pivot(app, (a as f64 - angle).to_radians());+ }+ crate::widgets::vline(ui, 22.0);+ lbl(ui, "Interpolation:");+ let mut interp = t.interpolation.clone();+ let opts = [("bicubic".to_string(), "Bicubic"), ("bilinear".to_string(), "Bilinear"), ("nearest".to_string(), "Nearest Neighbor")];+ if crate::widgets::dropdown(ui, "transform-interp", &mut interp, &opts, 130.0)+ && let Some(s) = app.ui.transform.as_mut()+ {+ s.interpolation = interp;+ }+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.add_space(8.0);+ if crate::icons::button(ui, "check", 24.0, false, "Commit transform (↩)").clicked() {+ commit(app);+ }+ if crate::icons::button(ui, "ban", 24.0, false, "Cancel transform (Esc)").clicked() {+ cancel(app);+ }+ });+}++/// Scale the box along its own axes about the reference point.+fn scale_about_pivot(app: &mut PhotocraftApp, kx: f64, ky: f64) {+ let Some(s) = app.ui.transform.as_mut() else { return };+ let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], s.quad) else { return };+ let Some(inv) = h.inverse() else { return };+ let (pu, pv) = inv.apply(s.pivot[0], s.pivot[1]);+ let m = |u: f64, v: f64| {+ let (x, y) = h.apply(pu + (u - pu) * kx, pv + (v - pv) * ky);+ [x, y]+ };+ s.quad = [m(0.0, 0.0), m(1.0, 0.0), m(1.0, 1.0), m(0.0, 1.0)];+}++fn rotate_about_pivot(app: &mut PhotocraftApp, da: f64) {+ let Some(s) = app.ui.transform.as_mut() else { return };+ let (sn, cs) = da.sin_cos();+ let c = s.pivot;+ s.quad = s.quad.map(|q| {+ let (x, y) = (q[0] - c[0], q[1] - c[1]);+ [c[0] + x * cs - y * sn, c[1] + x * sn + y * cs]+ });+}++#[cfg(test)]+mod tests {+ use super::*;++ fn session() -> TransformSession {+ TransformSession { session: 1, layer: 1, rect: [0.0, 0.0, 100.0, 50.0], quad: corners([0.0, 0.0, 100.0, 50.0]), pivot: [50.0, 25.0], interpolation: "bicubic".into() }+ }++ fn drag(s: &mut TransformSession, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) {+ let g = Gesture { hit: hit(s, from, 8.0), start: from, quad0: s.quad, pivot0: s.pivot };+ apply_drag(s, g, to, mods);+ }++ fn close(a: [[f64; 2]; 4], b: [[f64; 2]; 4]) -> bool {+ a.iter().flatten().zip(b.iter().flatten()).all(|(x, y)| (x - y).abs() < 1e-6)+ }++ #[test]+ fn corner_drag_scales_proportionally_about_opposite_corner() {+ let mut s = session();+ drag(&mut s, [100.0, 50.0], [200.0, 60.0], egui::Modifiers::NONE);+ assert!(close(s.quad, corners([0.0, 0.0, 200.0, 100.0])), "{:?}", s.quad);+ let mut s = session();+ drag(&mut s, [100.0, 50.0], [200.0, 60.0], egui::Modifiers::SHIFT);+ assert!(close(s.quad, corners([0.0, 0.0, 200.0, 60.0])), "shift = free: {:?}", s.quad);+ }++ #[test]+ fn alt_scales_about_reference_point_and_edges_scale_one_axis() {+ let mut s = session();+ drag(&mut s, [100.0, 25.0], [150.0, 25.0], egui::Modifiers::ALT);+ assert!(close(s.quad, corners([-50.0, 0.0, 150.0, 50.0])), "{:?}", s.quad);+ let mut s = session();+ drag(&mut s, [50.0, 50.0], [50.0, 80.0], egui::Modifiers::NONE);+ assert!(close(s.quad, corners([0.0, 0.0, 100.0, 80.0])), "{:?}", s.quad);+ }++ #[test]+ fn move_rotate_and_distort() {+ let mut s = session();+ drag(&mut s, [40.0, 20.0], [50.0, 30.0], egui::Modifiers::NONE);+ assert!(close(s.quad, corners([10.0, 10.0, 110.0, 60.0])));+ assert_eq!(s.pivot, [60.0, 35.0]);+ // Rotate 90° about the centre (drag from right of the box to below it).+ let mut s = session();+ drag(&mut s, [150.0, 25.0], [50.0, 125.0], egui::Modifiers::NONE);+ let (_, _, angle, _) = readout(&s);+ assert!((angle - 90.0).abs() < 1e-6, "{angle}");+ // ⇧ snaps: a 50° drag lands on 45°.+ let mut s = session();+ let a = 50f64.to_radians();+ drag(&mut s, [150.0, 25.0], [50.0 + 100.0 * a.cos(), 25.0 + 100.0 * a.sin()], egui::Modifiers::SHIFT);+ assert!((readout(&s).2 - 45.0).abs() < 1e-6);+ // ⌘ corner = distort.+ let mut s = session();+ drag(&mut s, [100.0, 0.0], [120.0, -10.0], egui::Modifiers::COMMAND);+ assert_eq!(s.quad[1], [120.0, -10.0]);+ assert_eq!(s.quad[0], [0.0, 0.0]);+ }++ #[test]+ fn begin_and_commit_through_the_engine() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();+ app.sync_views();+ app.session.execute("layer.new.layer", json!({})).unwrap();+ app.session+ .edit("paint", |doc, a| {+ doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 24, 24), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ let ctx = egui::Context::default();+ begin(&mut app, &ctx).unwrap();+ assert_eq!(app.ui.transform.as_ref().unwrap().rect, [8.0, 8.0, 24.0, 24.0]);+ scale_about_pivot(&mut app, 2.0, 2.0);+ commit(&mut app);+ let st = app.session.active().unwrap();+ let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds();+ assert!(b.width().abs_diff(32) <= 2 && b.x0.abs_diff(0) <= 1, "{b:?}");+ assert!(app.ui.transform.is_none() && app.transform_preview.is_none());+ }+}diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rsnew file mode 100644index 000000000..05fd1a3bc--- /dev/null+++ b/crates/ui-egui/src/type_tool.rs@@ -0,0 +1,918 @@+//! Type tool: click to add point text, drag to add paragraph text, edit inline with a caret.+//!+//! Every edit is an engine `type.*` command carrying the session's `coalesce` key, so a whole+//! typing session is one "Edit Type" history step and automation sees exactly what the user does.+//! Offsets in [`TextEdit`] are character indices (the engine's unit); the layout works in bytes.++use std::sync::Arc;++use egui::{Color32, Pos2, Stroke};+use photocraft_doc::{Document, LayerContent, LayerId, TextLayer};+use photocraft_geom::{Affine, Point};+use photocraft_text::TextLayout;+use serde_json::json;++use crate::PhotocraftApp;+use crate::canvas::ViewXform;+use crate::state::TextEdit;++pub const PLACEHOLDER: &str = "Lorem Ipsum";++fn text_layer(doc: &Document, id: LayerId) -> Option<&TextLayer> {+ match &doc.layer(id)?.content {+ LayerContent::Text(t) => Some(t),+ _ => None,+ }+}++fn byte_of(text: &str, ci: usize) -> usize {+ text.char_indices().nth(ci).map_or(text.len(), |(b, _)| b)+}++fn char_of(text: &str, bi: usize) -> usize {+ text[..bi.min(text.len())].chars().count()+}++/// Layout of a type layer (cached per document revision) and its text → document transform.+pub fn layout(app: &mut PhotocraftApp, id: LayerId) -> Option<(Arc<TextLayout>, Affine, String)> {+ let st = app.session.active()?;+ let (doc, rev) = (st.doc.clone(), st.revision);+ let t = text_layer(&doc, id)?;+ let key = (doc.id.0, rev, id.0);+ if let Some((k, l)) = &app.type_layout+ && *k == key+ {+ return Some((l.clone(), t.transform, t.text.clone()));+ }+ let l = Arc::new(photocraft_text::shared().lock().ok()?.layout(t, doc.resolution_dpi));+ app.type_layout = Some((key, l.clone()));+ Some((l, t.transform, t.text.clone()))+}++fn to_text(aff: &Affine, x: f64, y: f64) -> (f32, f32) {+ let p = aff.inverse().unwrap_or(Affine::IDENTITY).apply(Point::new(x, y));+ (p.x as f32, p.y as f32)+}++/// Topmost visible type layer whose laid-out text contains the document point.+fn hit_layer(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<LayerId> {+ let doc = app.session.active()?.doc.clone();+ let slop = 6.0 / app.current_zoom().max(0.01);+ let mut ids: Vec<LayerId> = doc.walk().into_iter().filter(|(_, _, l)| l.visible && matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();+ ids.reverse(); // walk() is bottom-up; hit the topmost first+ ids.into_iter().find(|id| {+ let Some((l, aff, _)) = layout(app, *id) else { return false };+ let (tx, ty) = to_text(&aff, x, y);+ l.bounds().is_some_and(|b| tx >= b[0] - slop && tx <= b[2] + slop && ty >= b[1] - slop && ty <= b[3] + slop)+ })+}++fn hit_offset(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> usize {+ let Some((l, aff, text)) = layout(app, id) else { return 0 };+ let (tx, ty) = to_text(&aff, x, y);+ char_of(&text, l.hit_test(tx, ty))+}++fn hex(c: [f32; 4]) -> String {+ let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2]))+}++/// Pointer down with the Type tool. Returns true when the press was consumed (no box drag).+pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) -> bool {+ if let Some(ed) = app.ui.text_edit.clone() {+ let id = LayerId(ed.layer);+ if hit_layer(app, x, y) == Some(id) {+ let off = hit_offset(app, id, x, y);+ let e = app.ui.text_edit.as_mut().expect("editing");+ e.caret = off;+ if !shift {+ e.anchor = off;+ }+ e.dragging = true;+ return true;+ }+ commit(app);+ return true; // Photoshop: a click outside commits without starting new text+ }+ if let Some(id) = hit_layer(app, x, y) {+ let _ = app.session.select_layer(id);+ let off = hit_offset(app, id, x, y);+ app.ui.text_edit = Some(TextEdit { layer: id.0, caret: off, anchor: off, session: session_key(app), created: false, dragging: true });+ return true;+ }+ false+}++pub fn pointer_move(app: &mut PhotocraftApp, x: f64, y: f64) {+ let Some(ed) = app.ui.text_edit.clone() else { return };+ if ed.dragging {+ let off = hit_offset(app, LayerId(ed.layer), x, y);+ if let Some(e) = app.ui.text_edit.as_mut() {+ e.caret = off;+ }+ }+}++/// Pointer up. `rect` is the dragged box (document px) when no edit session consumed the press.+pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {+ if let Some(e) = app.ui.text_edit.as_mut() {+ e.dragging = false;+ return;+ }+ let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs());+ let min = 4.0 / app.current_zoom().max(0.01) as f64;+ let o = app.ui.tool_options.clone();+ let mut p = json!({+ "text": PLACEHOLDER,+ "font": o.type_font,+ "fontStyle": o.type_style,+ "size": o.type_size,+ "align": o.type_align,+ "color": hex(app.session.tools.foreground),+ });+ if w >= min && h >= min {+ p["box"] = json!([start[0].min(end[0]).round(), start[1].min(end[1]).round(), w.round(), h.round()]);+ } else {+ p["x"] = json!(start[0].round());+ p["y"] = json!(start[1].round());+ }+ let key = session_key(app);+ p["coalesce"] = json!(key);+ if let Ok(v) = app.run("type.create", p)+ && let Some(id) = v.get("layer").and_then(serde_json::Value::as_u64)+ {+ if o.type_aa != "sharp" {+ let _ = app.run("type.edit", json!({"layer": id, "antialias": o.type_aa, "coalesce": key}));+ }+ // Like Photoshop: the placeholder is selected, so typing replaces it.+ let n = PLACEHOLDER.chars().count();+ app.ui.text_edit = Some(TextEdit { layer: id, caret: n, anchor: 0, session: key, created: true, dragging: false });+ }+}++fn session_key(app: &mut PhotocraftApp) -> String {+ format!("type-{}", app.ui.alloc_id())+}++fn current_text(app: &PhotocraftApp, id: LayerId) -> Option<String> {+ Some(text_layer(&app.session.active()?.doc, id)?.text.clone())+}++/// Replace the selection with `s`.+fn insert(app: &mut PhotocraftApp, s: &str) {+ let Some(ed) = app.ui.text_edit.clone() else { return };+ let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor));+ let s = s.replace("\r\n", "\n").replace('\r', "\n");+ if a == b && s.is_empty() {+ return;+ }+ if app.run("type.edit", json!({"layer": ed.layer, "replace": {"start": a, "end": b, "text": s}, "coalesce": ed.session})).is_ok()+ && let Some(e) = app.ui.text_edit.as_mut()+ {+ e.caret = a + s.chars().count();+ e.anchor = e.caret;+ }+}++/// Character index of the previous / next word boundary.+fn word_boundary(text: &str, from: usize, forward: bool) -> usize {+ let chars: Vec<char> = text.chars().collect();+ let mut i = from.min(chars.len());+ if forward {+ while i < chars.len() && !chars[i].is_alphanumeric() {+ i += 1;+ }+ while i < chars.len() && chars[i].is_alphanumeric() {+ i += 1;+ }+ } else {+ while i > 0 && !chars[i - 1].is_alphanumeric() {+ i -= 1;+ }+ while i > 0 && chars[i - 1].is_alphanumeric() {+ i -= 1;+ }+ }+ i+}++/// Double-click: select the word under the caret.+pub fn select_word(app: &mut PhotocraftApp) {+ let Some(ed) = app.ui.text_edit.clone() else { return };+ let Some(text) = current_text(app, LayerId(ed.layer)) else { return };+ let chars: Vec<char> = text.chars().collect();+ let (mut a, mut b) = (ed.caret.min(chars.len()), ed.caret.min(chars.len()));+ while a > 0 && chars[a - 1].is_alphanumeric() {+ a -= 1;+ }+ while b < chars.len() && chars[b].is_alphanumeric() {+ b += 1;+ }+ if let Some(e) = app.ui.text_edit.as_mut() {+ (e.anchor, e.caret) = (a, b);+ }+}++/// Caret on the neighbouring line (±1), keeping the x position.+fn vertical(app: &mut PhotocraftApp, id: LayerId, caret: usize, dir: i32) -> usize {+ let Some((l, _, text)) = layout(app, id) else { return caret };+ let (x, top, bottom) = l.caret(byte_of(&text, caret));+ let h = (bottom - top).max(1.0);+ let y = if dir < 0 { top - h * 0.5 } else { bottom + h * 0.5 };+ let Some(b) = l.bounds() else { return caret };+ if y < b[1] {+ return 0;+ }+ if y > b[3] {+ return text.chars().count();+ }+ char_of(&text, l.hit_test(x, y))+}++/// Line start / end for the caret's line.+fn line_edge(app: &mut PhotocraftApp, id: LayerId, caret: usize, end: bool) -> usize {+ let Some((l, _, text)) = layout(app, id) else { return caret };+ let b = byte_of(&text, caret);+ let line = l.lines.iter().find(|ln| b >= ln.range.start && b <= ln.range.end).or(l.lines.last());+ line.map_or(caret, |ln| char_of(&text, if end { ln.range.end } else { ln.range.start }))+}++/// Keyboard input while editing. Returns true when a type edit session is active (single-key+/// tool shortcuts must then be skipped). Handled events are removed from the frame's input.+pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {+ let Some(ed) = app.ui.text_edit.clone() else { return false };+ let id = LayerId(ed.layer);+ let Some(text) = current_text(app, id) else {+ app.ui.text_edit = None;+ return false;+ };+ // Undo/redo can shorten the text under us.+ let n = text.chars().count();+ if let Some(e) = app.ui.text_edit.as_mut() {+ e.caret = e.caret.min(n);+ e.anchor = e.anchor.min(n);+ }+ ctx.request_repaint_after(std::time::Duration::from_millis(530)); // caret blink+ let events = ctx.input(|i| i.events.clone());+ let mut handled = vec![false; events.len()];+ for (k, ev) in events.iter().enumerate() {+ let Some(ed) = app.ui.text_edit.clone() else { break };+ let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor));+ let text = current_text(app, id).unwrap_or_default();+ let n = text.chars().count();+ let set = |app: &mut PhotocraftApp, caret: usize, extend: bool| {+ if let Some(e) = app.ui.text_edit.as_mut() {+ e.caret = caret.min(n);+ if !extend {+ e.anchor = e.caret;+ }+ }+ };+ handled[k] = true;+ match ev {+ egui::Event::Text(s) | egui::Event::Paste(s) => insert(app, s),+ egui::Event::Copy | egui::Event::Cut => {+ if a < b {+ ctx.copy_text(text.chars().skip(a).take(b - a).collect());+ if matches!(ev, egui::Event::Cut) {+ insert(app, "");+ }+ }+ }+ egui::Event::Key { key, pressed: true, modifiers: m, .. } => {+ use egui::Key;+ match key {+ Key::Backspace | Key::Delete => {+ if a == b {+ let fwd = *key == Key::Delete;+ let to = match (fwd, m.alt, m.command) {+ (false, _, true) => line_edge(app, id, a, false),+ (false, true, _) => word_boundary(&text, a, false),+ (false, _, _) => a.saturating_sub(1),+ (true, true, _) => word_boundary(&text, a, true),+ (true, _, _) => (a + 1).min(n),+ };+ if to != a {+ if let Some(e) = app.ui.text_edit.as_mut() {+ e.anchor = to;+ }+ insert(app, "");+ }+ } else {+ insert(app, "");+ }+ }+ Key::ArrowLeft | Key::ArrowRight => {+ let fwd = *key == Key::ArrowRight;+ let to = if m.command {+ line_edge(app, id, ed.caret, fwd)+ } else if m.alt {+ word_boundary(&text, ed.caret, fwd)+ } else if a != b && !m.shift {+ if fwd { b } else { a }+ } else if fwd {+ ed.caret + 1+ } else {+ ed.caret.saturating_sub(1)+ };+ set(app, to, m.shift);+ }+ Key::ArrowUp | Key::ArrowDown => {+ let to = if m.command {+ if *key == Key::ArrowUp { 0 } else { n }+ } else {+ vertical(app, id, ed.caret, if *key == Key::ArrowUp { -1 } else { 1 })+ };+ set(app, to, m.shift);+ }+ Key::Home | Key::End => {+ let to = line_edge(app, id, ed.caret, *key == Key::End);+ set(app, to, m.shift);+ }+ Key::Enter if m.command => commit(app),+ Key::Enter => insert(app, "\n"),+ Key::Escape => commit(app),+ Key::A if m.command => {+ if let Some(e) = app.ui.text_edit.as_mut() {+ e.anchor = 0;+ e.caret = n;+ }+ }+ // Other command shortcuts (⌘Z, ⌘S, …) pass through to the menus.+ _ if m.command => handled[k] = false,+ _ => {}+ }+ }+ egui::Event::Key { pressed: false, modifiers: m, .. } => handled[k] = !m.command,+ _ => handled[k] = false,+ }+ }+ if handled.iter().any(|h| *h) {+ let mut k = 0;+ ctx.input_mut(|i| {+ i.events.retain(|_| {+ let keep = !handled.get(k).copied().unwrap_or(false);+ k += 1;+ keep+ })+ });+ }+ app.ui.text_edit.is_some()+}++/// End the editing session. A new layer left empty is deleted; a new layer is named after its text.+pub fn commit(app: &mut PhotocraftApp) {+ let Some(ed) = app.ui.text_edit.take() else { return };+ let Some(text) = current_text(app, LayerId(ed.layer)) else { return };+ if text.trim().is_empty() && ed.created {+ let _ = app.run("layer.delete", json!({"layer": ed.layer}));+ } else if ed.created {+ let name: String = text.lines().find(|l| !l.trim().is_empty()).unwrap_or("").trim().chars().take(40).collect();+ let _ = app.run("type.edit", json!({"layer": ed.layer, "name": name, "coalesce": ed.session}));+ }+}++/// Selection highlight, caret and text frame over the canvas.+pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {+ let Some(ed) = app.ui.text_edit.clone() else { return };+ let id = LayerId(ed.layer);+ let Some((l, aff, text)) = layout(app, id) else { return };+ let t = crate::theme::Tokens::get(painter.ctx());+ let scr = |x: f32, y: f32| -> Pos2 {+ let p = aff.apply(Point::new(x as f64, y as f64));+ xf.to_screen(p.x as f32, p.y as f32)+ };+ // Frame: paragraph text shows its box with handles; point text an underline per line.+ let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape));+ let frame = Stroke::new(1.0, t.accent);+ match shape {+ Some(photocraft_doc::text::TextShape::Box { x, y, width, height }) => {+ let c = [scr(x, y), scr(x + width, y), scr(x + width, y + height), scr(x, y + height)];+ painter.add(egui::Shape::closed_line(c.to_vec(), frame));+ let mids = [c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5), c[3].lerp(c[0], 0.5)];+ for p in c.iter().chain(mids.iter()) {+ let r = egui::Rect::from_center_size(*p, egui::vec2(7.0, 7.0));+ painter.rect_filled(r, 0.0, Color32::WHITE);+ painter.rect_stroke(r, 0.0, frame, egui::StrokeKind::Inside);+ }+ }+ _ => {+ for ln in &l.lines {+ let y = ln.baseline + ln.descent * 0.25;+ painter.line_segment([scr(ln.x0.min(0.0), y), scr(ln.x1.max(ln.x0 + 1.0), y)], Stroke::new(1.0, t.accent.gamma_multiply(0.8)));+ }+ }+ }+ // Selection: per line, the clusters inside [a, b).+ let (a, b) = (byte_of(&text, ed.caret.min(ed.anchor)), byte_of(&text, ed.caret.max(ed.anchor)));+ if a < b {+ let fill = Color32::from_rgba_unmultiplied(t.accent.r(), t.accent.g(), t.accent.b(), 110);+ for (li, ln) in l.lines.iter().enumerate() {+ let xs: Vec<(f32, f32)> = l.clusters.iter().filter(|c| c.line == li && c.range.start >= a && c.range.end <= b).map(|c| (c.x, c.x + c.advance)).collect();+ let (mut x0, mut x1) = xs.iter().fold((f32::MAX, f32::MIN), |(lo, hi), (p, q)| (lo.min(*p), hi.max(*q)));+ // A selected line break shows as a small sliver past the line end.+ if b > ln.range.end && a <= ln.range.end {+ x1 = x1.max(ln.x1 + (ln.ascent + ln.descent) * 0.25);+ x0 = x0.min(ln.x1);+ }+ if x0 < x1 {+ let (top, bot) = (ln.baseline - ln.ascent, ln.baseline + ln.descent);+ painter.add(egui::Shape::convex_polygon(vec![scr(x0, top), scr(x1, top), scr(x1, bot), scr(x0, bot)], fill, Stroke::NONE));+ }+ }+ } else {+ // Blinking caret (Photoshop's ~0.53 s rhythm), solid while dragging.+ let time = painter.ctx().input(|i| i.time);+ if ed.dragging || (time * 1000.0 / 530.0) as i64 % 2 == 0 {+ let (x, top, bot) = l.caret(a);+ let (x, top, bot) = if l.lines.is_empty() { (0.0, -(12.0 * l.px_per_pt.max(1.0)), 3.0) } else { (x, top, bot) };+ let c = if crate::theme::Tokens::get(painter.ctx()).pro { Color32::WHITE } else { Color32::BLACK };+ painter.line_segment([scr(x, top), scr(x, bot)], Stroke::new(1.5, c));+ painter.line_segment([scr(x, top), scr(x, bot)], Stroke::new(0.75, Color32::BLACK));+ }+ }+}++/// Font families (bundled + system), cached for the process.+pub fn families() -> &'static [String] {+ static FAMILIES: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();+ FAMILIES.get_or_init(|| photocraft_text::shared().lock().map(|mut e| e.fonts.families()).unwrap_or_default())+}++fn weight_name(w: f32) -> &'static str {+ match w.round() as i32 {+ ..=150 => "Thin",+ 151..=250 => "ExtraLight",+ 251..=350 => "Light",+ 351..=450 => "Regular",+ 451..=550 => "Medium",+ 551..=650 => "SemiBold",+ 651..=750 => "Bold",+ 751..=850 => "ExtraBold",+ _ => "Black",+ }+}++/// Style names ("Regular", "Bold Italic", …) available for a family.+pub fn styles(family: &str) -> Vec<String> {+ let faces = photocraft_text::shared().lock().map(|mut e| e.fonts.faces(family)).unwrap_or_default();+ let mut v: Vec<(i32, bool, String)> = faces+ .iter()+ .map(|f| {+ let w = weight_name(f.weight);+ let name = match (w, f.italic) {+ ("Regular", true) => "Italic".to_string(),+ (w, true) => format!("{w} Italic"),+ (w, false) => w.to_string(),+ };+ (f.weight.round() as i32, f.italic, name)+ })+ .collect();+ v.sort();+ v.dedup_by(|a, b| a.2 == b.2);+ let v: Vec<String> = v.into_iter().map(|x| x.2).collect();+ if v.is_empty() { vec!["Regular".into()] } else { v }+}++/// Searchable font-family combo box.+fn font_picker(ui: &mut egui::Ui, current: &mut String) -> bool {+ let mut changed = false;+ let search_id = ui.id().with("font-search");+ egui::ComboBox::from_id_salt("type-font").selected_text(current.as_str()).width(170.0).height(460.0).icon(crate::widgets::chevron_icon).show_ui(ui, |ui| {+ let mut q: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default();+ let r = ui.add(egui::TextEdit::singleline(&mut q).hint_text("Search fonts").desired_width(200.0));+ if !r.has_focus() && q.is_empty() {+ r.request_focus();+ }+ ui.data_mut(|d| d.insert_temp(search_id, q.clone()));+ let ql = q.to_lowercase();+ for f in families().iter().filter(|f| ql.is_empty() || f.to_lowercase().contains(&ql)) {+ if ui.selectable_label(f == current, f).clicked() {+ *current = f.clone();+ changed = true;+ ui.data_mut(|d| d.remove::<String>(search_id));+ }+ }+ });+ changed+}++/// The type layer the options bar edits: the one being edited, else the active layer if it is type.+fn target(app: &PhotocraftApp) -> Option<(u64, Option<[usize; 2]>)> {+ if let Some(ed) = &app.ui.text_edit {+ let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor));+ return Some((ed.layer, (a < b).then_some([a, b])));+ }+ let st = app.session.active()?;+ let id = st.active_layer?;+ text_layer(&st.doc, id).map(|_| (id.0, None))+}++/// Apply character/paragraph properties to the target (selection, else whole layer) and remember+/// them as tool defaults.+fn apply(app: &mut PhotocraftApp, props: serde_json::Value) {+ let Some((layer, range)) = target(app) else { return };+ let mut p = props;+ p["layer"] = json!(layer);+ if let Some(r) = range {+ p["range"] = json!(r);+ }+ if let Some(ed) = &app.ui.text_edit {+ p["coalesce"] = json!(ed.session);+ }+ let _ = app.run("type.setStyle", p);+}++/// Photoshop's Type options bar.+pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ let t = crate::theme::Tokens::get(ui.ctx());+ // Show the target layer's (first-run) style, else the tool defaults.+ let shown = target(app).and_then(|(id, _)| {+ let st = app.session.active()?;+ let tl = text_layer(&st.doc, LayerId(id))?;+ let run = tl.char_runs().into_iter().next().map(|r| r.style);+ Some((tl.font_family.clone(), run.as_ref().map(|s| s.font_style.clone()).unwrap_or_default(), tl.size_pt, tl.color))+ });+ let o = app.ui.tool_options.clone();+ let (mut fam, mut style, mut size) = match &shown {+ Some((f, s, z, _)) => (f.clone(), if s.is_empty() { "Regular".into() } else { s.clone() }, *z),+ None => (o.type_font.clone(), o.type_style.clone(), o.type_size),+ };+ let _ = crate::icons::button(ui, "text-cursor", 24.0, false, "Toggle text orientation");+ if font_picker(ui, &mut fam) {+ app.ui.tool_options.type_font = fam.clone();+ let st = styles(&fam);+ style = if st.contains(&style) { style } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) };+ app.ui.tool_options.type_style = style.clone();+ apply(app, json!({"font": fam, "fontStyle": style}));+ }+ let opts: Vec<(String, String)> = styles(&fam).into_iter().map(|s| (s.clone(), s)).collect();+ let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect();+ if crate::widgets::dropdown(ui, "type-style", &mut style, &opts_ref, 110.0) {+ app.ui.tool_options.type_style = style.clone();+ apply(app, json!({"fontStyle": style}));+ }+ let (r, _) = ui.allocate_exact_size(egui::vec2(18.0, 22.0), egui::Sense::hover());+ crate::icons::paint(ui, r, "type", 13.0, t.icon);+ if crate::widgets::value_field(ui, &mut size, 1.0..=1296.0, "pt", 66.0).changed() {+ app.ui.tool_options.type_size = size;+ apply(app, json!({"size": size}));+ }+ let mut aa = o.type_aa.clone();+ let aa_opts = [("none".to_string(), "None"), ("sharp".to_string(), "Sharp"), ("crisp".to_string(), "Crisp"), ("strong".to_string(), "Strong"), ("smooth".to_string(), "Smooth")];+ if crate::widgets::dropdown(ui, "type-aa", &mut aa, &aa_opts, 80.0) {+ app.ui.tool_options.type_aa = aa.clone();+ if let Some((layer, _)) = target(app) {+ let mut p = json!({"layer": layer, "antialias": aa});+ if let Some(ed) = &app.ui.text_edit {+ p["coalesce"] = json!(ed.session);+ }+ let _ = app.run("type.edit", p);+ }+ }+ crate::widgets::vline(ui, 22.0);+ ui.spacing_mut().item_spacing.x = 2.0;+ for (align, icon, tip) in [("left", "align-left", "Left align text"), ("center", "align-center", "Center text"), ("right", "align-right", "Right align text")] {+ if crate::icons::button(ui, icon, 24.0, o.type_align == align, tip).clicked() {+ app.ui.tool_options.type_align = align.into();+ apply(app, json!({"align": align}));+ }+ }+ ui.spacing_mut().item_spacing.x = 8.0;+ crate::widgets::vline(ui, 22.0);+ // Text colour swatch with a picker popup.+ let c = shown.as_ref().map(|s| s.3).map(|c| { let v = c.to_rgb(); [v[0], v[1], v[2], 1.0] }).unwrap_or(app.session.tools.foreground);+ let (rect, resp) = ui.allocate_exact_size(egui::vec2(28.0, 18.0), egui::Sense::click());+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ ui.painter().rect_filled(rect, 2.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2])));+ ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+ let resp = resp.on_hover_text("Set the text color");+ egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {+ let mut col = Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]));+ if egui::color_picker::color_picker_color32(ui, &mut col, egui::color_picker::Alpha::Opaque) {+ apply(app, json!({"color": format!("#{:02x}{:02x}{:02x}", col.r(), col.g(), col.b())}));+ }+ });+ if app.ui.text_edit.is_some() {+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.add_space(8.0);+ if crate::icons::button(ui, "check", 24.0, false, "Commit any current edits (⌘↩)").clicked() {+ commit(app);+ }+ if crate::icons::button(ui, "ban", 24.0, false, "Cancel any current edits (Esc)").clicked() {+ cancel(app);+ }+ });+ }+}++/// Character and paragraph style at the target (selection start, else the layer's first run).+fn styles_at(app: &PhotocraftApp) -> Option<(photocraft_doc::text::CharStyle, photocraft_doc::text::ParagraphStyle)> {+ let (layer, range) = target(app)?;+ let st = app.session.active()?;+ let t = text_layer(&st.doc, LayerId(layer))?;+ let at = range.map_or(0, |r| byte_of(&t.text, r[0]));+ let pick = |lens: Vec<usize>| -> usize {+ let mut acc = 0;+ for (i, len) in lens.iter().enumerate() {+ acc += len;+ if at < acc {+ return i;+ }+ }+ lens.len().saturating_sub(1)+ };+ let runs = t.char_runs();+ let paras = t.paragraph_runs();+ let c = runs.get(pick(runs.iter().map(|r| r.len).collect())).map(|r| r.style.clone())?;+ let p = paras.get(pick(paras.iter().map(|r| r.len).collect())).map(|r| r.style.clone()).unwrap_or_default();+ Some((c, p))+}++fn icon_label(ui: &mut egui::Ui, icon: &str, tip: &str) {+ let t = crate::theme::Tokens::get(ui.ctx());+ let (r, resp) = ui.allocate_exact_size(egui::vec2(18.0, 22.0), egui::Sense::hover());+ crate::icons::paint(ui, r, icon, 12.0, t.text_dim);+ resp.on_hover_text(tip);+}++/// Labelled numeric field (Photoshop's icon + value pairs). Returns the new value when edited.+fn num_field(ui: &mut egui::Ui, label: &str, tip: &str, v: f32, range: std::ops::RangeInclusive<f32>, unit: &str, width: f32) -> Option<f32> {+ let t = crate::theme::Tokens::get(ui.ctx());+ let mut v = v;+ let mut out = None;+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ let (r, resp) = ui.allocate_exact_size(egui::vec2(22.0, 22.0), egui::Sense::hover());+ ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, crate::theme::semibold(10.0), t.text_dim);+ resp.on_hover_text(tip);+ if crate::widgets::value_field(ui, &mut v, range, unit, width).changed() {+ out = Some(v);+ }+ });+ out+}++/// Photoshop's paragraph alignment glyphs: four text lines whose widths/offsets show the mode+/// (justify variants run full width, with the last line placed left/centre/right).+fn align_glyph(p: &egui::Painter, r: egui::Rect, a: photocraft_doc::text::TextAlign, c: Color32) {+ use photocraft_doc::text::TextAlign as A;+ let widths = [1.0, 0.62, 1.0, 0.62];+ for (i, w) in widths.iter().enumerate() {+ let y = r.top() + i as f32 * r.height() / 3.0;+ let full = r.width();+ let (len, x0) = match a {+ A::Left => (full * w, r.left()),+ A::Center => (full * w, r.center().x - full * w / 2.0),+ A::Right => (full * w, r.right() - full * w),+ A::JustifyAll => (full, r.left()),+ _ if i < 3 => (full, r.left()),+ A::JustifyLeft => (full * 0.55, r.left()),+ A::JustifyCenter => (full * 0.55, r.center().x - full * 0.275),+ _ => (full * 0.55, r.right() - full * 0.55),+ };+ p.line_segment([egui::pos2(x0, y), egui::pos2(x0 + len, y)], Stroke::new(1.5, c));+ }+}++/// Properties panel sections for a type layer: Character and Paragraph (Photoshop CC layout).+pub fn type_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ let Some((c, para)) = styles_at(app) else { return };+ let t = crate::theme::Tokens::get(ui.ctx());+ let section = |ui: &mut egui::Ui, title: &str| {+ ui.add_space(6.0);+ ui.label(egui::RichText::new(title).font(crate::theme::semibold(12.0)).color(t.text));+ ui.add_space(2.0);+ };+ section(ui, "Character");+ let mut fam = c.font_family.clone();+ ui.horizontal(|ui| {+ if font_picker(ui, &mut fam) {+ app.ui.tool_options.type_font = fam.clone();+ let st = styles(&fam);+ let style = if st.contains(&c.font_style) { c.font_style.clone() } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) };+ apply(app, json!({"font": fam, "fontStyle": style}));+ }+ });+ ui.horizontal(|ui| {+ let mut style = if c.font_style.is_empty() { "Regular".to_string() } else { c.font_style.clone() };+ let opts: Vec<(String, String)> = styles(&fam).into_iter().map(|s| (s.clone(), s)).collect();+ let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect();+ if crate::widgets::dropdown(ui, "props-type-style", &mut style, &opts_ref, 170.0) {+ apply(app, json!({"fontStyle": style}));+ }+ });+ let w = ((ui.available_width() - 70.0) / 2.0).clamp(50.0, 90.0);+ ui.horizontal(|ui| {+ if let Some(v) = num_field(ui, "tT", "Font size", c.size_pt, 0.1..=1296.0, "pt", w) {+ app.ui.tool_options.type_size = v;+ apply(app, json!({"size": v}));+ }+ let lead = c.leading_pt.unwrap_or(c.size_pt * para.auto_leading.max(0.01));+ if let Some(v) = num_field(ui, "A↕", "Leading (set to the font size × auto-leading when Auto)", lead, 0.1..=5000.0, "pt", w) {+ apply(app, json!({"leading": v}));+ }+ });+ ui.horizontal(|ui| {+ let mut k = match c.kerning {+ photocraft_doc::text::Kerning::Metrics => "metrics",+ photocraft_doc::text::Kerning::Optical => "optical",+ photocraft_doc::text::Kerning::Off => "off",+ }+ .to_string();+ icon_label(ui, "text-cursor", "Kerning");+ if crate::widgets::dropdown(ui, "props-kern", &mut k, &[("metrics".to_string(), "Metrics"), ("optical".to_string(), "Optical"), ("off".to_string(), "0")], w) {+ apply(app, json!({"kerning": k}));+ }+ if let Some(v) = num_field(ui, "VA", "Tracking (1/1000 em)", c.tracking, -1000.0..=10000.0, "", w) {+ apply(app, json!({"tracking": v}));+ }+ });+ ui.horizontal(|ui| {+ if let Some(v) = num_field(ui, "↕T", "Vertical scale", c.vertical_scale * 100.0, 0.0..=1000.0, "%", w) {+ apply(app, json!({"verticalScale": v}));+ }+ if let Some(v) = num_field(ui, "↔T", "Horizontal scale", c.horizontal_scale * 100.0, 0.0..=1000.0, "%", w) {+ apply(app, json!({"horizontalScale": v}));+ }+ });+ ui.horizontal(|ui| {+ if let Some(v) = num_field(ui, "Aª", "Baseline shift", c.baseline_shift_pt, -1296.0..=1296.0, "pt", w) {+ apply(app, json!({"baselineShift": v}));+ }+ // Colour chip.+ ui.add_space(8.0);+ ui.label(egui::RichText::new("Color:").color(t.text_dim).size(12.0));+ let rgb = c.color.to_rgb();+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ let (rect, resp) = ui.allocate_exact_size(egui::vec2(40.0, 18.0), egui::Sense::click());+ ui.painter().rect_filled(rect, 2.0, Color32::from_rgb(q(rgb[0]), q(rgb[1]), q(rgb[2])));+ ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+ egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {+ let mut col = Color32::from_rgb(q(rgb[0]), q(rgb[1]), q(rgb[2]));+ if egui::color_picker::color_picker_color32(ui, &mut col, egui::color_picker::Alpha::Opaque) {+ apply(app, json!({"color": format!("#{:02x}{:02x}{:02x}", col.r(), col.g(), col.b())}));+ }+ });+ });+ // Faux styles row: T (bold) T (italic) TT Tᴛ T̲ T̶+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 2.0;+ let caps = c.caps;+ let toggles: [(&str, &str, bool, serde_json::Value); 6] = [+ ("T", "Faux Bold", c.faux_bold, json!({"fauxBold": !c.faux_bold})),+ ("T", "Faux Italic", c.faux_italic, json!({"fauxItalic": !c.faux_italic})),+ ("TT", "All Caps", caps == photocraft_doc::text::Caps::AllCaps, json!({"caps": if caps == photocraft_doc::text::Caps::AllCaps { "normal" } else { "allCaps" }})),+ ("Tᴛ", "Small Caps", caps == photocraft_doc::text::Caps::SmallCaps, json!({"caps": if caps == photocraft_doc::text::Caps::SmallCaps { "normal" } else { "smallCaps" }})),+ ("T", "Underline", c.underline, json!({"underline": !c.underline})),+ ("T", "Strikethrough", c.strikethrough, json!({"strikethrough": !c.strikethrough})),+ ];+ for (i, (glyph, tip, on, props)) in toggles.into_iter().enumerate() {+ let (r, resp) = ui.allocate_exact_size(egui::vec2(28.0, 24.0), egui::Sense::click());+ let bg = if on { t.accent_soft } else if resp.hovered() { t.hover } else { Color32::TRANSPARENT };+ ui.painter().rect_filled(r, 3.0, bg);+ let font = if i == 0 { crate::theme::semibold(13.0) } else { egui::FontId::proportional(13.0) };+ let col = if on { t.text } else { t.text_dim };+ let g = ui.painter().layout_no_wrap(glyph.to_string(), font, col);+ let pos = r.center() - g.size() / 2.0;+ let gr = egui::Rect::from_min_size(pos, g.size());+ if i == 1 {+ // Faux italic: a slanted T drawn as strokes (no italic face is bundled).+ let (top, bot, cx) = (gr.top() + 3.0, gr.bottom() - 3.0, gr.center().x);+ let slant = (bot - top) * 0.25;+ ui.painter().line_segment([egui::pos2(cx - 4.0 + slant / 2.0, top), egui::pos2(cx + 4.0 + slant / 2.0, top)], Stroke::new(1.3, col));+ ui.painter().line_segment([egui::pos2(cx + slant / 2.0, top), egui::pos2(cx - slant / 2.0, bot)], Stroke::new(1.3, col));+ } else {+ ui.painter().galley(pos, g, col);+ }+ if i == 4 {+ ui.painter().line_segment([egui::pos2(gr.left(), gr.bottom() - 2.0), egui::pos2(gr.right(), gr.bottom() - 2.0)], Stroke::new(1.0, col));+ }+ if i == 5 {+ ui.painter().line_segment([egui::pos2(gr.left() - 1.0, gr.center().y), egui::pos2(gr.right() + 1.0, gr.center().y)], Stroke::new(1.0, col));+ }+ if resp.on_hover_text(tip).clicked() {+ apply(app, props);+ }+ }+ });+ section(ui, "Paragraph");+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 2.0;+ use photocraft_doc::text::TextAlign as A;+ let items = [+ ("left", "Left align text", A::Left),+ ("center", "Center text", A::Center),+ ("right", "Right align text", A::Right),+ ("justifyLeft", "Justify last left", A::JustifyLeft),+ ("justifyCenter", "Justify last centered", A::JustifyCenter),+ ("justifyRight", "Justify last right", A::JustifyRight),+ ("justifyAll", "Justify all", A::JustifyAll),+ ];+ for (key, tip, a) in items {+ let (r, resp) = ui.allocate_exact_size(egui::vec2(26.0, 24.0), egui::Sense::click());+ let on = para.align == a;+ ui.painter().rect_filled(r, 3.0, if on { t.accent_soft } else if resp.hovered() { t.hover } else { Color32::TRANSPARENT });+ if on {+ ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.accent_border), egui::StrokeKind::Inside);+ }+ align_glyph(ui.painter(), r.shrink2(egui::vec2(7.0, 7.0)), a, if on { t.text } else { t.icon });+ if resp.on_hover_text(tip).clicked() {+ apply(app, json!({"align": key}));+ }+ }+ });+ ui.horizontal(|ui| {+ if let Some(v) = num_field(ui, "→|", "Indent left margin", para.start_indent_pt, -1296.0..=1296.0, "pt", w) {+ apply(app, json!({"startIndent": v}));+ }+ if let Some(v) = num_field(ui, "|←", "Indent right margin", para.end_indent_pt, -1296.0..=1296.0, "pt", w) {+ apply(app, json!({"endIndent": v}));+ }+ });+ ui.horizontal(|ui| {+ if let Some(v) = num_field(ui, "¶→", "Indent first line", para.first_line_indent_pt, -1296.0..=1296.0, "pt", w) {+ apply(app, json!({"firstLineIndent": v}));+ }+ });+ ui.horizontal(|ui| {+ if let Some(v) = num_field(ui, "↑¶", "Add space before paragraph", para.space_before_pt, 0.0..=1296.0, "pt", w) {+ apply(app, json!({"spaceBefore": v}));+ }+ if let Some(v) = num_field(ui, "¶↓", "Add space after paragraph", para.space_after_pt, 0.0..=1296.0, "pt", w) {+ apply(app, json!({"spaceAfter": v}));+ }+ });+ let mut hy = para.hyphenate;+ if crate::widgets::checkbox(ui, &mut hy, "Hyphenate").changed() {+ apply(app, json!({"hyphenate": hy}));+ }+}++/// Cancel the editing session: undo it back to where it started (removes a new layer).+pub fn cancel(app: &mut PhotocraftApp) {+ let Some(ed) = app.ui.text_edit.take() else { return };+ let coalesced = app.session.active().is_some_and(|s| s.coalesce.as_deref() == Some(ed.session.as_str()));+ if coalesced {+ let _ = app.run("edit.undo", json!({}));+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 400, "height": 200})).unwrap();+ app.sync_views();+ app.ui.tool = crate::state::Tool::Type;+ app+ }++ fn layer_text(app: &PhotocraftApp) -> String {+ let ed = app.ui.text_edit.as_ref().unwrap();+ current_text(app, LayerId(ed.layer)).unwrap()+ }++ #[test]+ fn click_creates_placeholder_selected_and_typing_replaces_it() {+ let mut app = app();+ assert!(!pointer_down(&mut app, 50.0, 100.0, false));+ pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]);+ let ed = app.ui.text_edit.clone().unwrap();+ assert_eq!((ed.anchor, ed.caret), (0, PLACEHOLDER.chars().count()));+ insert(&mut app, "Héllo");+ insert(&mut app, " world");+ assert_eq!(layer_text(&app), "Héllo world");+ // Creating and typing share the session key: one step after the initial snapshot.+ let steps = app.session.active().unwrap().history.entries();+ assert_eq!(steps, ["Open", "New Type Layer"]);+ commit(&mut app);+ let doc = &app.session.active().unwrap().doc;+ assert_eq!(doc.layers.last().unwrap().name, "Héllo world");+ assert!(app.ui.text_edit.is_none());+ }++ #[test]+ fn empty_new_layer_is_deleted_on_commit() {+ let mut app = app();+ pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]);+ let n = app.session.active().unwrap().doc.layers.len();+ insert(&mut app, "");+ if let Some(e) = app.ui.text_edit.as_mut() {+ e.anchor = 0;+ }+ insert(&mut app, "");+ commit(&mut app);+ assert_eq!(app.session.active().unwrap().doc.layers.len(), n - 1);+ }++ #[test]+ fn word_boundaries() {+ assert_eq!(word_boundary("hello big world", 0, true), 5);+ assert_eq!(word_boundary("hello big world", 7, false), 6);+ assert_eq!(word_boundary("hello big world", 15, false), 10);+ }+}diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rsnew file mode 100644index 000000000..d6a110094--- /dev/null+++ b/crates/ui-egui/src/vector_ui.rs@@ -0,0 +1,598 @@+//! Vector tools: Shape tools (U), Pen (P), Path Selection (A), path overlays and the Paths panel.+//! All edits go through the engine's `shape.*` / `path.*` commands.++use egui::{Color32, Pos2, Rect, Sense, Stroke, pos2, vec2};+use photocraft_doc::vector::Path;+use photocraft_doc::{Document, LayerContent};+use photocraft_geom::Affine;+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};++use crate::PhotocraftApp;+use crate::canvas::ViewXform;+use crate::state::Tool;+use crate::theme::Tokens;++/// Pen tool path under construction: knots as [anchor, in, out] (document px).+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct PenPath {+ pub knots: Vec<[[f64; 2]; 3]>,+ #[serde(skip)]+ pub dragging: bool,+}++pub fn is_shape_tool(t: Tool) -> bool {+ matches!(t, Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line)+}++fn hex(c: [f32; 4]) -> String {+ let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2]))+}++fn stroke_param(app: &PhotocraftApp) -> Value {+ let o = &app.ui.tool_options;+ if o.stroke_width > 0.0 { json!({"width": o.stroke_width, "color": hex(app.session.tools.background)}) } else { Value::Null }+}++/// Finish a Shape-tool drag: ⇧ constrains proportions, ⌥ draws from the centre.+pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) {+ let o = app.ui.tool_options.clone();+ let fill = if o.shape_fill { json!(hex(app.session.tools.foreground)) } else { Value::Null };+ let stroke = stroke_param(app);+ let p = if tool == Tool::Line {+ let (mut dx, mut dy) = (end[0] - start[0], end[1] - start[1]);+ if mods.shift {+ // Snap to 45°.+ let a = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4;+ let len = dx.hypot(dy);+ (dx, dy) = (len * a.cos(), len * a.sin());+ }+ if dx.hypot(dy) < 1.0 {+ return;+ }+ json!({"kind": "line", "from": start, "to": [start[0] + dx, start[1] + dy], "weight": o.line_weight.max(1.0), "fill": fill, "stroke": stroke})+ } else {+ let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]);+ if mods.shift {+ let m = w.abs().max(h.abs());+ (w, h) = (m * w.signum(), m * h.signum());+ }+ let (x0, y0) = if mods.alt { (start[0] - w, start[1] - h) } else { (start[0], start[1]) };+ let (w, h) = if mods.alt { (w * 2.0, h * 2.0) } else { (w, h) };+ let rect = [x0.min(x0 + w).round(), y0.min(y0 + h).round(), w.abs().round(), h.abs().round()];+ if rect[2] < 1.0 || rect[3] < 1.0 {+ return;+ }+ match tool {+ Tool::Rectangle if o.corner_radius > 0.0 => json!({"kind": "roundedRect", "rect": rect, "radii": vec![o.corner_radius; 4], "fill": fill, "stroke": stroke}),+ Tool::Rectangle => json!({"kind": "rect", "rect": rect, "fill": fill, "stroke": stroke}),+ Tool::EllipseShape => json!({"kind": "ellipse", "rect": rect, "fill": fill, "stroke": stroke}),+ Tool::Triangle => json!({"kind": "polygon", "rect": rect, "sides": 3, "fill": fill, "stroke": stroke}),+ _ => json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3), "fill": fill, "stroke": stroke}),+ }+ };+ if let Err(e) = app.run("shape.create", p) {+ app.ui.status = e;+ app.ui.status_error = true;+ }+}++// ---------------------------------------------------------------------------------------------+// Pen++fn pen_to_json(pen: &PenPath, closed: bool) -> Value {+ json!({"subpaths": [{"closed": closed, "knots": pen.knots.iter().map(|k| json!({"anchor": k[0], "in": k[1], "out": k[2], "smooth": k[1] != k[0] || k[2] != k[0]})).collect::<Vec<_>>()}]})+}++/// Pen press: close on the first anchor, else add an anchor (dragging pulls smooth handles).+pub fn pen_down(app: &mut PhotocraftApp, x: f64, y: f64) {+ let tol = 6.0 / app.current_zoom().max(0.01) as f64;+ let pen = app.ui.pen.get_or_insert_with(PenPath::default);+ if let Some(first) = pen.knots.first().map(|k| k[0])+ && pen.knots.len() >= 2+ && (first[0] - x).hypot(first[1] - y) < tol+ {+ pen_commit(app, true);+ return;+ }+ pen.knots.push([[x, y]; 3]);+ pen.dragging = true;+}++pub fn pen_move(app: &mut PhotocraftApp, x: f64, y: f64) {+ if let Some(pen) = app.ui.pen.as_mut()+ && pen.dragging+ && let Some(k) = pen.knots.last_mut()+ {+ let a = k[0];+ k[2] = [x, y];+ k[1] = [2.0 * a[0] - x, 2.0 * a[1] - y];+ }+}++pub fn pen_up(app: &mut PhotocraftApp) {+ if let Some(pen) = app.ui.pen.as_mut() {+ pen.dragging = false;+ }+}++/// Finish the pen path: a work path (Path mode) or a new shape layer (Shape mode).+pub fn pen_commit(app: &mut PhotocraftApp, closed: bool) {+ let Some(pen) = app.ui.pen.take() else { return };+ if pen.knots.len() < 2 {+ return;+ }+ let path = pen_to_json(&pen, closed);+ let r = if app.ui.tool_options.vector_mode == "shape" {+ let fill = if closed && app.ui.tool_options.shape_fill { json!(hex(app.session.tools.foreground)) } else { Value::Null };+ let stroke = if closed { stroke_param(app) } else { json!({"width": app.ui.tool_options.stroke_width.max(1.0), "color": hex(app.session.tools.foreground)}) };+ app.run("shape.create", json!({"kind": "path", "path": path, "fill": fill, "stroke": stroke}))+ } else {+ app.run("path.set", json!({"name": "work", "path": path}))+ };+ if let Err(e) = r {+ app.ui.status = e;+ app.ui.status_error = true;+ }+}++// ---------------------------------------------------------------------------------------------+// Path Selection++/// The path Path Selection edits: the active shape layer's, else the work path.+fn target_path(app: &PhotocraftApp) -> Option<(Option<u64>, Path)> {+ let st = app.session.active()?;+ if let Some(l) = st.active_layer.and_then(|id| st.doc.layer(id))+ && let LayerContent::Shape(sh) = &l.content+ {+ return Some((Some(l.id.0), sh.path.clone()));+ }+ st.doc.work_path.clone().map(|p| (None, p))+}++pub fn path_selection_finish(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {+ let (dx, dy) = (end[0] - start[0], end[1] - start[1]);+ if dx.abs() + dy.abs() < 0.5 {+ return;+ }+ let Some((layer, path)) = target_path(app) else { return };+ let _ = match layer {+ Some(id) => app.run("shape.edit", json!({"layer": id, "move": [dx.round(), dy.round()]})),+ None => {+ let moved = path.transform(&Affine::translate(dx.round(), dy.round()));+ app.run("path.set", json!({"name": "work", "path": photocraft_engine::vector_cmds::path_json(&moved)}))+ }+ };+}++// ---------------------------------------------------------------------------------------------+// Drawing++fn bezier(p0: [f64; 2], c0: [f64; 2], c1: [f64; 2], p1: [f64; 2], t: f64) -> [f64; 2] {+ let u = 1.0 - t;+ let f = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d;+ [f(p0[0], c0[0], c1[0], p1[0]), f(p0[1], c0[1], c1[1], p1[1])]+}++/// Screen polylines for a path (one per subpath).+fn path_lines(path: &Path, xf: &dyn Fn([f64; 2]) -> Pos2) -> Vec<(Vec<Pos2>, bool)> {+ path.subpaths+ .iter()+ .map(|s| {+ let n = s.knots.len();+ let mut pts = Vec::new();+ let segs = if s.closed { n } else { n.saturating_sub(1) };+ for i in 0..segs {+ let (a, b) = (&s.knots[i], &s.knots[(i + 1) % n]);+ for k in 0..=16 {+ let q = bezier([a.anchor.x, a.anchor.y], [a.out_ctrl.x, a.out_ctrl.y], [b.in_ctrl.x, b.in_ctrl.y], [b.anchor.x, b.anchor.y], k as f64 / 16.0);+ pts.push(xf(q));+ }+ }+ if pts.is_empty()+ && let Some(k) = s.knots.first()+ {+ pts.push(xf([k.anchor.x, k.anchor.y]));+ }+ (pts, s.closed)+ })+ .collect()+}++/// Work path / active shape path outlines, anchors, and the pen path in progress.+pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) {+ let tool = app.ui.tool;+ let vector_tool = matches!(tool, Tool::Pen | Tool::PathSelection) || is_shape_tool(tool);+ let accent = Tokens::get(painter.ctx()).accent;+ let to_scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32);+ let draw_path = |p: &Path, anchors: bool| {+ for (pts, closed) in path_lines(p, &to_scr) {+ if closed {+ painter.add(egui::Shape::closed_line(pts, Stroke::new(1.0, accent)));+ } else {+ painter.add(egui::Shape::line(pts, Stroke::new(1.0, accent)));+ }+ }+ if anchors {+ for s in &p.subpaths {+ for k in &s.knots {+ let c = to_scr([k.anchor.x, k.anchor.y]);+ painter.rect_filled(Rect::from_center_size(c, vec2(6.0, 6.0)), 0.0, Color32::WHITE);+ painter.rect_stroke(Rect::from_center_size(c, vec2(6.0, 6.0)), 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside);+ }+ }+ }+ };+ if vector_tool {+ if let Some(wp) = &doc.work_path {+ draw_path(wp, tool == Tool::PathSelection);+ }+ let st = app.session.active();+ if let Some(l) = st.and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id)))+ && let LayerContent::Shape(sh) = &l.content+ {+ draw_path(&sh.path, tool == Tool::PathSelection);+ }+ }+ // Pen path in progress, with handles of the last knot and a rubber band to the pointer.+ if let Some(pen) = &app.ui.pen {+ let mut pts = Vec::new();+ for w in pen.knots.windows(2) {+ for k in 0..=16 {+ pts.push(to_scr(bezier(w[0][0], w[0][2], w[1][1], w[1][0], k as f64 / 16.0)));+ }+ }+ painter.add(egui::Shape::line(pts, Stroke::new(1.5, accent)));+ if let (Some(last), Some(h)) = (pen.knots.last(), app.hover_doc)+ && !pen.dragging+ {+ painter.add(egui::Shape::dashed_line(&[to_scr(last[0]), to_scr(h)], Stroke::new(1.0, accent), 4.0, 3.0));+ }+ for (i, k) in pen.knots.iter().enumerate() {+ let c = to_scr(k[0]);+ if i + 1 == pen.knots.len() && k[2] != k[0] {+ for hnd in [k[1], k[2]] {+ let hp = to_scr(hnd);+ painter.line_segment([c, hp], Stroke::new(1.0, accent));+ painter.circle_filled(hp, 3.0, accent);+ }+ }+ let r = Rect::from_center_size(c, vec2(6.0, 6.0));+ painter.rect_filled(r, 0.0, if i + 1 == pen.knots.len() { accent } else { Color32::WHITE });+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside);+ }+ }+}++// ---------------------------------------------------------------------------------------------+// Options bars++/// Options bar for vector tools; false for other tools.+pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {+ if !(is_shape_tool(tool) || matches!(tool, Tool::Pen | Tool::PathSelection)) {+ return false;+ }+ let t = Tokens::get(ui.ctx());+ let lbl = |ui: &mut egui::Ui, s: &str| {+ ui.label(egui::RichText::new(s).color(t.text_dim).size(12.0));+ };+ let o = &mut app.ui.tool_options;+ if tool == Tool::PathSelection {+ lbl(ui, "Drag to move the active shape's path or the Work Path");+ return true;+ }+ if tool == Tool::Pen {+ let opts = [("path".to_string(), "Path"), ("shape".to_string(), "Shape")];+ crate::widgets::dropdown(ui, "pen-mode", &mut o.vector_mode, &opts, 80.0);+ crate::widgets::vline(ui, 22.0);+ lbl(ui, "Click: corner · Drag: smooth · Click first point: close · ↩ finish · Esc cancel");+ return true;+ }+ let mut mode = "shape".to_string();+ crate::widgets::dropdown(ui, "shape-mode", &mut mode, &[("shape".to_string(), "Shape")], 80.0);+ crate::widgets::vline(ui, 22.0);+ lbl(ui, "Fill:");+ crate::widgets::checkbox(ui, &mut o.shape_fill, "");+ let fg = app.session.tools.foreground;+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ let (r, _) = ui.allocate_exact_size(vec2(22.0, 16.0), Sense::hover());+ ui.painter().rect_filled(r, 2.0, Color32::from_rgb(q(fg[0]), q(fg[1]), q(fg[2])));+ ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+ lbl(ui, "Stroke:");+ crate::widgets::value_field(ui, &mut o.stroke_width, 0.0..=288.0, "px", 58.0);+ match tool {+ Tool::Rectangle => {+ crate::widgets::vline(ui, 22.0);+ lbl(ui, "Radius:");+ crate::widgets::value_field(ui, &mut o.corner_radius, 0.0..=10000.0, "px", 62.0);+ }+ Tool::Polygon => {+ crate::widgets::vline(ui, 22.0);+ lbl(ui, "Sides:");+ let mut s = o.polygon_sides as f32;+ if crate::widgets::value_field(ui, &mut s, 3.0..=100.0, "", 48.0).changed() {+ o.polygon_sides = s.round().clamp(3.0, 100.0) as u32;+ }+ }+ Tool::Line => {+ crate::widgets::vline(ui, 22.0);+ lbl(ui, "Weight:");+ crate::widgets::value_field(ui, &mut o.line_weight, 1.0..=1000.0, "px", 58.0);+ }+ _ => {}+ }+ true+}++// ---------------------------------------------------------------------------------------------+// Properties (shape layers)++fn color_of(f: &photocraft_doc::Fill) -> Option<Color32> {+ match f {+ photocraft_doc::Fill::Solid(c) => {+ let v = c.to_rgba8();+ Some(Color32::from_rgb(v[0], v[1], v[2]))+ }+ _ => None,+ }+}++/// A colour swatch that opens a picker; returns the new `#rrggbb` when changed.+fn swatch(ui: &mut egui::Ui, current: Option<Color32>, tip: &str) -> Option<String> {+ let t = Tokens::get(ui.ctx());+ let (r, resp) = ui.allocate_exact_size(vec2(26.0, 18.0), Sense::click());+ match current {+ Some(c) => {+ ui.painter().rect_filled(r, 2.0, c);+ }+ None => {+ // "No colour": white with a red slash, like Photoshop.+ ui.painter().rect_filled(r, 2.0, Color32::WHITE);+ ui.painter().line_segment([r.left_bottom(), r.right_top()], Stroke::new(1.5, Color32::from_rgb(220, 40, 40)));+ }+ };+ ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+ let resp = resp.on_hover_text(tip);+ let mut out = None;+ egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {+ let mut c = current.unwrap_or(Color32::BLACK);+ if egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque) {+ out = Some(format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b()));+ }+ if current.is_some() && ui.button("No Color").clicked() {+ out = Some("none".into());+ }+ });+ out+}++/// Properties panel for a shape layer: Appearance (fill, stroke) and live shape geometry.+pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocraft_doc::LayerId) {+ let Some(sh) = app.session.active().and_then(|s| s.doc.layer(id)).and_then(|l| match &l.content {+ LayerContent::Shape(sh) => Some(sh.clone()),+ _ => None,+ }) else {+ return;+ };+ let t = Tokens::get(ui.ctx());+ let mut edit: Option<Value> = None;+ let key = |k: &str| format!("shape-{}-{k}", id.0);+ ui.add_space(6.0);+ ui.label(egui::RichText::new("Appearance").font(crate::theme::semibold(12.0)).color(t.text));+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new("Fill").color(t.text_dim).size(12.0));+ if let Some(c) = swatch(ui, sh.fill.as_ref().and_then(color_of), "Set shape fill type") {+ edit = Some(if c == "none" { json!({"fill": null}) } else { json!({"fill": c, "coalesce": key("fill")}) });+ }+ ui.add_space(12.0);+ ui.label(egui::RichText::new("Stroke").color(t.text_dim).size(12.0));+ if let Some(c) = swatch(ui, sh.stroke.as_ref().and_then(|s| color_of(&s.paint)), "Set shape stroke type") {+ edit = Some(if c == "none" { json!({"stroke": null}) } else { json!({"stroke": {"color": c, "width": sh.stroke.as_ref().map_or(3.0, |s| s.width)}, "coalesce": key("stroke")}) });+ }+ let mut w = sh.stroke.as_ref().map_or(0.0, |s| s.width);+ if crate::widgets::value_field(ui, &mut w, 0.0..=288.0, "px", 60.0).changed() {+ edit = Some(if w <= 0.0 { json!({"stroke": null}) } else { json!({"stroke": {"width": w}, "coalesce": key("stroke-w")}) });+ }+ if sh.stroke.is_some() {+ let mut align = match sh.stroke.as_ref().map(|s| s.align) {+ Some(photocraft_doc::vector::StrokeAlign::Inside) => "inside",+ Some(photocraft_doc::vector::StrokeAlign::Outside) => "outside",+ _ => "center",+ }+ .to_string();+ let opts = [("inside".to_string(), "Inside"), ("center".to_string(), "Center"), ("outside".to_string(), "Outside")];+ if crate::widgets::dropdown(ui, &key("align"), &mut align, &opts, 84.0) {+ edit = Some(json!({"stroke": {"align": align}}));+ }+ }+ });+ if let Some(live) = &sh.live {+ ui.add_space(6.0);+ ui.label(egui::RichText::new("Shape").font(crate::theme::semibold(12.0)).color(t.text));+ let num = |ui: &mut egui::Ui, label: &str, v: &mut f32, range: std::ops::RangeInclusive<f32>, unit: &str| -> bool {+ ui.label(egui::RichText::new(label).color(t.text_dim).size(12.0));+ crate::widgets::value_field(ui, v, range, unit, 64.0).changed()+ };+ match live {+ photocraft_doc::vector::LiveShape::Rect { rect, .. } | photocraft_doc::vector::LiveShape::Ellipse { rect } | photocraft_doc::vector::LiveShape::Polygon { rect, .. } => {+ ui.horizontal(|ui| {+ let (mut w, mut h) = (rect[2] as f32, rect[3] as f32);+ let cw = num(ui, "W", &mut w, 1.0..=300000.0, "px");+ let ch = num(ui, "H", &mut h, 1.0..=300000.0, "px");+ if cw || ch {+ edit = Some(json!({"rect": [rect[0], rect[1], w.round(), h.round()], "coalesce": key("wh")}));+ }+ });+ }+ photocraft_doc::vector::LiveShape::Line { .. } => {}+ }+ ui.horizontal(|ui| match live {+ photocraft_doc::vector::LiveShape::Rect { radii, .. } => {+ let mut r = radii[0] as f32;+ if num(ui, "Corner radius", &mut r, 0.0..=100000.0, "px") {+ edit = Some(json!({"radii": r, "coalesce": key("radius")}));+ }+ }+ photocraft_doc::vector::LiveShape::Polygon { sides, star_ratio, .. } => {+ let mut n = *sides as f32;+ if num(ui, "Sides", &mut n, 3.0..=100.0, "") {+ edit = Some(json!({"sides": n.round() as u32, "coalesce": key("sides")}));+ }+ let mut sr = (*star_ratio * 100.0) as f32;+ if num(ui, "Star ratio", &mut sr, 1.0..=100.0, "%") {+ edit = Some(json!({"starRatio": sr as f64 / 100.0, "coalesce": key("star")}));+ }+ }+ photocraft_doc::vector::LiveShape::Line { weight, .. } => {+ let mut w = *weight as f32;+ if num(ui, "Weight", &mut w, 1.0..=10000.0, "px") {+ edit = Some(json!({"weight": w, "coalesce": key("weight")}));+ }+ }+ _ => {}+ });+ }+ if let Some(mut p) = edit {+ p["layer"] = json!(id.0);+ if let Err(e) = app.run("shape.edit", p) {+ app.ui.status = e;+ app.ui.status_error = true;+ }+ }+}++// ---------------------------------------------------------------------------------------------+// Paths panel++fn thumb(ui: &egui::Ui, r: Rect, path: &Path, doc: &Document) {+ let t = Tokens::get(ui.ctx());+ ui.painter().rect_filled(r, 0.0, Color32::from_gray(if t.pro { 222 } else { 240 }));+ let (w, h) = (doc.size.width.max(1) as f64, doc.size.height.max(1) as f64);+ let s = (r.width() as f64 / w).min(r.height() as f64 / h);+ let off = r.center() - vec2((w * s) as f32 / 2.0, (h * s) as f32 / 2.0);+ let map = |q: [f64; 2]| pos2(off.x + (q[0] * s) as f32, off.y + (q[1] * s) as f32);+ for (pts, closed) in path_lines(path, &map) {+ if closed && pts.len() >= 3 {+ ui.painter().add(egui::Shape::closed_line(pts, Stroke::new(1.0, Color32::from_gray(40))));+ } else {+ ui.painter().add(egui::Shape::line(pts, Stroke::new(1.0, Color32::from_gray(40))));+ }+ }+}++pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ let Some(st) = app.session.active() else {+ ui.label(egui::RichText::new("No document").color(t.text_faint));+ return;+ };+ let doc = st.doc.clone();+ let mut rows: Vec<(String, Path, bool)> = doc.paths.iter().map(|p| (p.name.clone(), p.path.clone(), false)).collect();+ if let Some(wp) = &doc.work_path {+ rows.push(("Work Path".into(), wp.clone(), true));+ }+ if rows.is_empty() {+ ui.label(egui::RichText::new("Draw with the Pen tool (P) or make a work path from a selection.").color(t.text_faint).size(11.5));+ }+ let mut action: Option<(&str, Value)> = None;+ for (name, path, work) in &rows {+ let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());+ let key = if *work { "work".to_string() } else { name.clone() };+ let sel = app.ui.selected_path.as_deref() == Some(key.as_str());+ if sel {+ ui.painter().rect_filled(r, 0.0, t.row_selected);+ } else if resp.hovered() {+ ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5));+ }+ thumb(ui, Rect::from_min_size(pos2(r.left() + 8.0, r.top() + 4.0), vec2(28.0, 28.0)), path, &doc);+ let mut job = egui::text::LayoutJob::default();+ job.append(name, 0.0, egui::TextFormat { font_id: egui::FontId::proportional(12.0), color: t.text, italics: *work, ..Default::default() });+ let g = ui.painter().layout_job(job);+ ui.painter().galley(pos2(r.left() + 46.0, r.center().y - g.size().y / 2.0), g, t.text);+ if resp.clicked() {+ app.ui.selected_path = Some(key.clone());+ }+ // Double-clicking the Work Path saves it (Photoshop's "Save Path").+ if resp.double_clicked() && *work {+ let n = doc.paths.len() + 1;+ action = Some(("path.rename", json!({"name": "work", "to": format!("Path {n}")})));+ }+ ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator));+ }+ ui.add_space(4.0);+ let sel = app.ui.selected_path.clone().unwrap_or_else(|| "work".into());+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 2.0;+ let fg = hex(app.session.tools.foreground);+ let items: [(&str, &str, &str, Value); 6] = [+ ("paint-bucket", "Fill path with foreground color", "path.fill", json!({"name": sel, "color": fg})),+ ("circle", "Stroke path with brush", "path.stroke", json!({"name": sel, "tool": "brush"})),+ ("square-dashed", "Load path as a selection", "path.toSelection", json!({"name": sel})),+ ("spline", "Make work path from selection", "select.toWorkPath", json!({"tolerance": 2.0})),+ ("square", "Add vector mask", "layer.vectorMask.fromPath", json!({"name": sel})),+ ("trash", "Delete path", "path.delete", json!({"name": sel})),+ ];+ for (icon, tip, cmd, p) in items {+ let icon = if crate::icons::exists(icon) { icon } else { "square" };+ if crate::icons::button(ui, icon, 24.0, false, tip).clicked() {+ action = Some((cmd, p));+ }+ }+ });+ if let Some((cmd, p)) = action+ && let Err(e) = app.run(cmd, p)+ {+ app.ui.status = e;+ app.ui.status_error = true;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap();+ app.sync_views();+ app+ }++ #[test]+ fn shape_drag_creates_layers_with_modifiers() {+ let mut app = app();+ finish_shape(&mut app, Tool::Rectangle, [10.0, 10.0], [60.0, 30.0], egui::Modifiers::SHIFT);+ let st = app.session.active().unwrap();+ let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds();+ assert_eq!((b.width(), b.height()), (50, 50), "shift = square");+ finish_shape(&mut app, Tool::EllipseShape, [100.0, 100.0], [120.0, 110.0], egui::Modifiers::ALT);+ let st = app.session.active().unwrap();+ let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds();+ assert!(b.x0.abs_diff(80) <= 1 && b.width().abs_diff(40) <= 1, "alt = from centre: {b:?}");+ finish_shape(&mut app, Tool::Line, [10.0, 150.0], [90.0, 152.0], egui::Modifiers::SHIFT);+ assert_eq!(app.session.active().unwrap().doc.layers.len(), 4);+ }++ #[test]+ fn pen_builds_and_closes_a_work_path() {+ let mut app = app();+ app.ui.tool = Tool::Pen;+ for (x, y) in [(20.0, 20.0), (120.0, 20.0)] {+ pen_down(&mut app, x, y);+ pen_up(&mut app);+ }+ pen_down(&mut app, 120.0, 120.0);+ pen_move(&mut app, 140.0, 140.0); // smooth knot+ pen_up(&mut app);+ pen_down(&mut app, 20.5, 20.5); // click the first anchor: close+ assert!(app.ui.pen.is_none());+ let wp = app.session.active().unwrap().doc.work_path.clone().unwrap();+ assert!(wp.subpaths[0].closed && wp.subpaths[0].knots.len() == 3);+ assert!(wp.subpaths[0].knots[2].smooth);+ // Path Selection moves it.+ path_selection_finish(&mut app, [50.0, 50.0], [60.0, 55.0]);+ let wp = app.session.active().unwrap().doc.work_path.clone().unwrap();+ assert_eq!((wp.subpaths[0].knots[0].anchor.x, wp.subpaths[0].knots[0].anchor.y), (30.0, 25.0));+ }+}diff --git a/crates/vector/Cargo.toml b/crates/vector/Cargo.tomlnew file mode 100644index 000000000..dae501393--- /dev/null+++ b/crates/vector/Cargo.toml@@ -0,0 +1,19 @@+[package]+name = "photocraft-vector"+description = "Vector paths, shape layers, strokes and vector masks → anti-aliased coverage and surfaces"+version.workspace = true+edition.workspace = true+license.workspace = true+rust-version.workspace = true++[lints]+workspace = true++[dependencies]+photocraft-geom = { workspace = true }+photocraft-color = { workspace = true }+photocraft-raster = { workspace = true }+photocraft-doc = { workspace = true }++[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+rayon = { workspace = true }diff --git a/crates/vector/src/flatten.rs b/crates/vector/src/flatten.rsnew file mode 100644index 000000000..5639841b7--- /dev/null+++ b/crates/vector/src/flatten.rs@@ -0,0 +1,132 @@+//! Bézier flattening with a distance tolerance.++use photocraft_doc::{Path, Subpath};+use photocraft_geom::Point;++/// A flattened subpath.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Polyline {+ pub pts: Vec<(f64, f64)>,+ /// `true` for points that are knots of the source path (joins apply there); `false` for+ /// points inserted while flattening a curve.+ pub knot: Vec<bool>,+ pub closed: bool,+}++impl Polyline {+ fn push(&mut self, p: (f64, f64), knot: bool) {+ if let Some(&last) = self.pts.last()+ && (last.0 - p.0).abs() < 1e-12+ && (last.1 - p.1).abs() < 1e-12+ {+ if knot && let Some(k) = self.knot.last_mut() {+ *k = true;+ }+ return;+ }+ self.pts.push(p);+ self.knot.push(knot);+ }+}++/// Straight segment: both control points lie on the chord (within 1e-9 px) between its ends.+fn is_line(seg: &[Point; 4]) -> bool {+ let [p0, c1, c2, p1] = seg;+ let (dx, dy) = (p1.x - p0.x, p1.y - p0.y);+ let len2 = dx * dx + dy * dy;+ let on_chord = |c: &Point| {+ let (vx, vy) = (c.x - p0.x, c.y - p0.y);+ if len2 < 1e-24 {+ return vx.abs() < 1e-9 && vy.abs() < 1e-9;+ }+ let t = (vx * dx + vy * dy) / len2;+ let cross = (vx * dy - vy * dx).abs() / len2.sqrt();+ cross < 1e-9 && (-1e-9..=1.0 + 1e-9).contains(&t)+ };+ on_chord(c1) && on_chord(c2)+}++/// Number of uniform pieces so that the chord deviation of the cubic is at most `tol`+/// (bound `max|B''| / 8n²` with `max|B''| <= 6·max(|p0−2c1+c2|, |c1−2c2+p1|)`).+fn pieces(seg: &[Point; 4], tol: f64) -> usize {+ let [p0, c1, c2, p1] = seg;+ let d1 = ((p0.x - 2.0 * c1.x + c2.x).powi(2) + (p0.y - 2.0 * c1.y + c2.y).powi(2)).sqrt();+ let d2 = ((c1.x - 2.0 * c2.x + p1.x).powi(2) + (c1.y - 2.0 * c2.y + p1.y).powi(2)).sqrt();+ let m = d1.max(d2);+ // Small curves get a proportionally finer tolerance so their area stays accurate.+ let size = (c1.x - p0.x).hypot(c1.y - p0.y) + (c2.x - c1.x).hypot(c2.y - c1.y) + (p1.x - c2.x).hypot(p1.y - c2.y);+ let tol = tol.min(size * 1e-3).max(1e-4);+ let n = (0.75 * m / tol).sqrt().ceil();+ if n.is_finite() { (n as usize).clamp(1, 1 << 16) } else { 1 }+}++fn eval(seg: &[Point; 4], t: f64) -> (f64, f64) {+ let [p0, c1, c2, p1] = seg;+ let mt = 1.0 - t;+ let a = mt * mt * mt;+ let b = 3.0 * mt * mt * t;+ let c = 3.0 * mt * t * t;+ let d = t * t * t;+ (a * p0.x + b * c1.x + c * c2.x + d * p1.x, a * p0.y + b * c1.y + c * c2.y + d * p1.y)+}++/// Flattens one subpath. Closed subpaths do not repeat the first point at the end.+pub fn flatten_subpath(s: &Subpath, tol: f64) -> Polyline {+ let mut out = Polyline { closed: s.closed, ..Default::default() };+ if let Some(k) = s.knots.first() {+ out.push((k.anchor.x, k.anchor.y), true);+ }+ for seg in &s.segments() {+ if is_line(seg) {+ out.push((seg[3].x, seg[3].y), true);+ continue;+ }+ let n = pieces(seg, tol);+ for j in 1..=n {+ out.push(eval(seg, j as f64 / n as f64), j == n);+ }+ }+ if s.closed && out.pts.len() > 1 {+ let (a, b) = (out.pts[0], out.pts[out.pts.len() - 1]);+ if (a.0 - b.0).abs() < 1e-12 && (a.1 - b.1).abs() < 1e-12 {+ out.pts.pop();+ out.knot.pop();+ out.knot[0] = true;+ }+ }+ out+}++/// Flattens every subpath (see [`flatten_subpath`]).+pub fn flatten_path(p: &Path, tol: f64) -> Vec<Polyline> {+ p.subpaths.iter().map(|s| flatten_subpath(s, tol)).collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::shapes;++ #[test]+ fn lines_are_not_subdivided() {+ let s = Subpath::polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]);+ let p = flatten_subpath(&s, 0.1);+ assert_eq!(p.pts.len(), 3);+ assert!(p.knot.iter().all(|k| *k));+ }++ #[test]+ fn circle_flattening_respects_tolerance() {+ for tol in [1.0, 0.25, 0.01] {+ let path = shapes::ellipse(0.0, 0.0, 200.0, 200.0);+ let p = flatten_subpath(&path.subpaths[0], tol);+ // Kappa circles deviate from the true circle by ~0.027% of r; chords add ≤ tol.+ for w in p.pts.windows(2) {+ let m = ((w[0].0 + w[1].0) / 2.0 - 100.0, (w[0].1 + w[1].1) / 2.0 - 100.0);+ let r = (m.0 * m.0 + m.1 * m.1).sqrt();+ assert!(100.0 - r <= tol + 0.03, "tol {tol}: chord mid at r={r}");+ }+ assert!(p.pts.len() < 4 * (1 + (0.75 * 100.0 / tol.min(0.15)).sqrt() as usize + 1));+ }+ }+}diff --git a/crates/vector/src/lib.rs b/crates/vector/src/lib.rsnew file mode 100644index 000000000..eea7308d9--- /dev/null+++ b/crates/vector/src/lib.rs@@ -0,0 +1,375 @@+//! # photocraft-vector+//!+//! Rasterization of vector data from `photocraft-doc`: paths (with Photoshop path operations),+//! shape layers (fill + stroke), vector masks, and the inverse direction (tracing a coverage+//! mask back into a path for "Make Work Path").+//!+//! * [`flatten`]: cubic Bézier flattening with a distance tolerance.+//! * [`raster`]: exact area-coverage scanline rasterizer (non-zero / even-odd per component,+//! boolean combination of components, inversion).+//! * [`stroke`]: polygon stroking with miter/round/bevel joins, butt/round/square caps, dashes.+//! * [`shapes`]: live shapes (rectangles with corner radii, ellipses, polygons, stars, lines).+//! * [`trace`]: contour tracing + curve fitting (selection → path).+//!+//! Output is either raw coverage (`f32` per pixel) or sparse tiled [`Surface`]s in any+//! [`PixelFormat`] (only tiles that differ from the default are allocated). Pure Rust, no+//! platform dependencies; builds for `wasm32` (single-threaded there, rayon elsewhere).+#![forbid(unsafe_code)]++pub mod flatten;+pub mod raster;+pub mod shapes;+pub mod stroke;+pub mod trace;++use photocraft_color::{ColorMode, PixelFormat};+use photocraft_doc::{Fill, FillRule, GradientStyle, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, VectorMask};+use photocraft_geom::{Rect, TILE_SIZE};+use photocraft_raster::Surface;++pub use flatten::{Polyline, flatten_path, flatten_subpath};+pub use raster::Rasterizer;+pub use stroke::{StrokeStyle, stroke_polygons};++/// Default flattening tolerance in pixels (curve-to-chord distance).+pub const DEFAULT_TOLERANCE: f64 = 0.01;++/// Compiles the fill area of `path`: one component per subpath (filled with the path's rule)+/// folded with the subpath operations; open subpaths are closed implicitly.+pub fn fill_rasterizer(path: &Path, tol: f64) -> Rasterizer {+ let mut r = Rasterizer::new(path.inverted);+ for s in &path.subpaths {+ let pl = flatten_subpath(s, tol);+ r.add_component(&[pl.pts], s.op, path.fill_rule);+ }+ r+}++/// Compiles the stroke outline of `path` (all subpaths, one non-zero component).+pub fn stroke_rasterizer(path: &Path, style: &StrokeStyle, tol: f64) -> Rasterizer {+ // Stroke outlines tolerate a coarser flattening than fills (the offset hides chord error).+ let lines = flatten_path(path, (tol * 4.0).min(style.width.max(0.01) * 0.1).max(1e-3));+ let polys = stroke_polygons(&lines, style, tol);+ let mut r = Rasterizer::new(false);+ r.add_component(&polys, PathOp::Combine, FillRule::NonZero);+ r+}++/// Stroke geometry for a shape stroke (dash lengths are multiples of the width in the model).+pub fn stroke_style(s: &ShapeStroke) -> StrokeStyle {+ let w = f64::from(s.width.max(0.0));+ StrokeStyle {+ width: w,+ cap: s.cap,+ join: s.join,+ miter_limit: f64::from(s.miter_limit.max(1.0)),+ dashes: s.dashes.iter().map(|d| f64::from(*d) * w).collect(),+ dash_offset: f64::from(s.dash_offset) * w,+ }+}++/// Fill coverage of `path` over `rect` (row-major, `0..=1`).+pub fn path_coverage(path: &Path, rect: Rect) -> Vec<f32> {+ fill_rasterizer(path, DEFAULT_TOLERANCE).render(rect)+}++/// Effective vector-mask values over `rect` (density applied; all ones when disabled). Like+/// Photoshop, a vector mask without any subpath reveals everything (hides everything when+/// inverted): "Add Vector Mask" starts from an empty, revealing mask.+pub fn vector_mask_values(m: &VectorMask, rect: Rect) -> Vec<f32> {+ let n = rect.width() as usize * rect.height() as usize;+ if !m.enabled {+ return vec![1.0; n];+ }+ let mut v = if m.path.is_empty() { vec![if m.path.inverted { 0.0 } else { 1.0 }; n] } else { path_coverage(&m.path, rect) };+ if m.density < 1.0 {+ let d = m.density.clamp(0.0, 1.0);+ for x in &mut v {+ *x = 1.0 - d * (1.0 - *x);+ }+ }+ v+}++/// Tile-aligned bands (rows of tiles) covering `r`.+fn tile_bands(r: Rect) -> Vec<Rect> {+ let mut out = Vec::new();+ if r.is_empty() {+ return out;+ }+ let mut y = r.y0.div_euclid(TILE_SIZE) * TILE_SIZE;+ while y < r.y1 {+ let band = Rect::new(r.x0, y.max(r.y0), r.x1, (y + TILE_SIZE).min(r.y1));+ out.push(band);+ y += TILE_SIZE;+ }+ out+}++/// Splits a band buffer (`channels` floats per pixel) into tile-aligned pieces, skipping+/// pieces where `keep` is false for every pixel.+fn band_tiles(band: Rect, data: &[f32], channels: usize, keep: impl Fn(&[f32]) -> bool) -> Vec<(Rect, Vec<f32>)> {+ let w = band.width() as usize;+ let mut out = Vec::new();+ let mut x = band.x0.div_euclid(TILE_SIZE) * TILE_SIZE;+ while x < band.x1 {+ let tr = Rect::new(x.max(band.x0), band.y0, (x + TILE_SIZE).min(band.x1), band.y1);+ let tw = tr.width() as usize;+ let mut buf = Vec::with_capacity(tw * tr.height() as usize * channels);+ let mut any = false;+ for row in 0..tr.height() as usize {+ let o = (row * w + (tr.x0 - band.x0) as usize) * channels;+ let slice = &data[o..o + tw * channels];+ if !any && slice.chunks_exact(channels).any(&keep) {+ any = true;+ }+ buf.extend_from_slice(slice);+ }+ if any {+ out.push((tr, buf));+ }+ x += TILE_SIZE;+ }+ out+}++/// Runs `f` over the bands of `r` (in parallel groups on native targets) and writes the+/// resulting pieces into `surface`.+fn render_bands(surface: &mut Surface, r: Rect, f: &(dyn Fn(Rect) -> Vec<(Rect, Vec<f32>)> + Sync)) {+ let bands = tile_bands(r);+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ let group = rayon::current_num_threads().max(1) * 2;+ for chunk in bands.chunks(group) {+ let parts: Vec<Vec<(Rect, Vec<f32>)>> = chunk.par_iter().map(|b| f(*b)).collect();+ for (tr, v) in parts.into_iter().flatten() {+ surface.write_region(tr, &v);+ }+ }+ }+ #[cfg(target_arch = "wasm32")]+ for b in bands {+ for (tr, v) in f(b) {+ surface.write_region(tr, &v);+ }+ }+}++/// Renders a rasterizer's coverage into a single-channel surface of `format` (grayscale+/// model, no alpha, e.g. a selection or mask) over `clip`. Outside `clip` the surface reads 0,+/// or 1 for inverted paths whose coverage is written everywhere inside `clip`.+pub fn coverage_surface(r: &Rasterizer, format: PixelFormat, clip: Rect) -> Surface {+ let fmt = PixelFormat::new(ColorMode::Grayscale, format.sample, false);+ let mut s = Surface::new(fmt);+ let area = if r.is_inverted() { clip } else { r.pixel_bounds().map_or(Rect::EMPTY, |b| b.intersect(&clip)) };+ render_bands(&mut s, area, &|band| {+ let cov = r.render(band);+ band_tiles(band, &cov, 1, |p| p[0] > 0.0)+ });+ s+}++/// Colour source for fills and strokes.+#[derive(Clone, Debug)]+pub enum Paint {+ None,+ /// Straight RGBA.+ Solid([f32; 4]),+ Gradient { stops: Vec<(f32, [f32; 4])>, style: GradientStyle, angle: f32, scale: f32, reverse: bool, bounds: (f64, f64, f64, f64) },+}++impl Paint {+ /// Paint for a model fill, with gradients laid out over `bounds` (`x0, y0, x1, y1`).+ /// Patterns are not rendered yet (transparent), matching the compositor.+ pub fn from_fill(f: &Fill, bounds: (f64, f64, f64, f64)) -> Paint {+ let rgba = |c: &photocraft_color::Color| {+ let v = c.to_rgb();+ [v[0], v[1], v[2], c.alpha]+ };+ match f {+ Fill::Solid(c) => Paint::Solid(rgba(c)),+ Fill::Gradient { stops, angle, scale, style, reverse } => Paint::Gradient {+ stops: stops.iter().map(|(p, c)| (*p, rgba(c))).collect(),+ style: *style,+ angle: *angle,+ scale: *scale,+ reverse: *reverse,+ bounds,+ },+ Fill::Pattern { .. } => Paint::None,+ }+ }++ /// Straight RGBA at pixel centre `(x, y)`.+ pub fn at(&self, x: f64, y: f64) -> [f32; 4] {+ match self {+ Paint::None => [0.0; 4],+ Paint::Solid(c) => *c,+ Paint::Gradient { stops, style, angle, scale, reverse, bounds } => {+ let t = gradient_t(*style, *angle, *scale, *reverse, *bounds, x, y);+ sample_stops(stops, t)+ }+ }+ }+}++/// Gradient parameter at `(x, y)`: the gradient spans the bounds' extent along its angle+/// (degrees, counter-clockwise from 3 o'clock), centred on the bounds.+fn gradient_t(style: GradientStyle, angle: f32, scale: f32, reverse: bool, b: (f64, f64, f64, f64), x: f64, y: f64) -> f32 {+ let (w, h) = ((b.2 - b.0).max(1.0), (b.3 - b.1).max(1.0));+ let (cx, cy) = (b.0 + w / 2.0, b.1 + h / 2.0);+ let a = f64::from(angle).to_radians();+ let (s, c) = a.sin_cos();+ let (dx, dy) = (x - cx, y - cy);+ let along = dx * c - dy * s;+ let across = dx * s + dy * c;+ let len = ((c * w).powi(2) + (s * h).powi(2)).sqrt().max(1.0) * f64::from(scale.max(1e-3));+ let t = match style {+ GradientStyle::Linear => along / len + 0.5,+ GradientStyle::Reflected => (along / (len / 2.0)).abs(),+ GradientStyle::Radial => dx.hypot(dy) / (len / 2.0),+ GradientStyle::Diamond => (along.abs() + across.abs()) / (len / 2.0),+ GradientStyle::Angle => ((a - (-dy).atan2(dx)) / std::f64::consts::TAU).rem_euclid(1.0),+ };+ let t = t.clamp(0.0, 1.0) as f32;+ if reverse { 1.0 - t } else { t }+}++fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] {+ match stops {+ [] => [0.0; 4],+ [s] => s.1,+ _ => {+ if t <= stops[0].0 {+ return stops[0].1;+ }+ for w in stops.windows(2) {+ if t <= w[1].0 {+ let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 };+ return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k);+ }+ }+ stops[stops.len() - 1].1+ }+ }+}++/// Everything needed to render a shape layer, compiled once.+pub struct CompiledShape {+ fill: Option<(Rasterizer, Paint)>,+ stroke: Option<(Rasterizer, Paint, f32)>,+ /// Fill area used to clip inside/outside strokes.+ align: Option<(Rasterizer, bool)>,+ bounds: Option<Rect>,+}++impl CompiledShape {+ pub fn new(shape: &ShapeLayer, tol: f64) -> Self {+ let pb = shape.path.control_bounds().unwrap_or((0.0, 0.0, 0.0, 0.0));+ let area = fill_rasterizer(&shape.path, tol);+ let mut bounds = None;+ let fill = shape.fill.as_ref().map(|f| {+ bounds = area.pixel_bounds();+ (area.clone(), Paint::from_fill(f, pb))+ });+ let all_closed = shape.path.subpaths.iter().all(|s| s.closed);+ let mut align = None;+ let stroke = shape.stroke.as_ref().filter(|s| s.width > 0.0 && s.opacity > 0.0).map(|s| {+ let mut st = stroke_style(s);+ if all_closed && s.align != StrokeAlign::Center {+ // Inside/outside strokes: a centred stroke twice as wide, clipped by the fill area.+ st.width *= 2.0;+ align = Some((area.clone(), s.align == StrokeAlign::Inside));+ }+ let r = stroke_rasterizer(&shape.path, &st, tol);+ let sb = r.pixel_bounds();+ bounds = match (bounds, sb) {+ (Some(a), Some(b)) => Some(a.union(&b)),+ (a, b) => a.or(b),+ };+ (r, Paint::from_fill(&s.paint, pb), s.opacity.clamp(0.0, 1.0))+ });+ if shape.path.inverted && shape.fill.is_some() {+ bounds = Some(Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4));+ }+ CompiledShape { fill, stroke, align, bounds }+ }++ /// Pixel bounds of the rendering (`None` = nothing visible).+ pub fn bounds(&self) -> Option<Rect> {+ self.bounds+ }++ /// Straight RGBA for every pixel of `rect`.+ pub fn render_rgba(&self, rect: Rect) -> Vec<[f32; 4]> {+ let n = rect.width() as usize * rect.height() as usize;+ let mut out = vec![[0.0f32; 4]; n];+ let w = rect.width() as usize;+ if let Some((r, paint)) = &self.fill {+ let cov = r.render(rect);+ for (i, (o, c)) in out.iter_mut().zip(&cov).enumerate() {+ if *c > 0.0 {+ let (x, y) = ((rect.x0 + (i % w) as i32) as f64 + 0.5, (rect.y0 + (i / w) as i32) as f64 + 0.5);+ let mut p = paint.at(x, y);+ p[3] *= c;+ *o = p;+ }+ }+ }+ if let Some((r, paint, opacity)) = &self.stroke {+ let mut cov = r.render(rect);+ if let Some((area, inside)) = &self.align {+ let a = area.render(rect);+ for (c, f) in cov.iter_mut().zip(&a) {+ *c *= if *inside { *f } else { 1.0 - *f };+ }+ }+ for (i, (o, c)) in out.iter_mut().zip(&cov).enumerate() {+ if *c <= 0.0 {+ continue;+ }+ let (x, y) = ((rect.x0 + (i % w) as i32) as f64 + 0.5, (rect.y0 + (i / w) as i32) as f64 + 0.5);+ let s = paint.at(x, y);+ let sa = s[3] * c * opacity;+ let da = o[3];+ let a = sa + da * (1.0 - sa);+ if a > 0.0 {+ for k in 0..3 {+ o[k] = (s[k] * sa + o[k] * da * (1.0 - sa)) / a;+ }+ }+ o[3] = a;+ }+ }+ out+ }++ /// Renders into a new surface of `format` over `clip` (typically the canvas).+ pub fn render(&self, format: PixelFormat, clip: Rect) -> Surface {+ let mut s = Surface::new(format);+ let Some(b) = self.bounds else { return s };+ let area = b.intersect(&clip);+ let ch = format.channels();+ render_bands(&mut s, area, &|band| {+ let rgba = self.render_rgba(band);+ let mut vals = vec![0.0f32; rgba.len() * ch];+ for (p, o) in rgba.iter().zip(vals.chunks_exact_mut(ch)) {+ if p[3] > 0.0 {+ photocraft_raster::from_rgba_into(&format, *p, o);+ }+ }+ let alpha = format.alpha;+ band_tiles(band, &vals, ch, |px| if alpha { px[ch - 1] > 0.0 } else { px.iter().any(|v| *v != 0.0) })+ });+ s+ }+}++/// Renders a shape layer's appearance (fill, then stroke over it) in `format`, clipped to `clip`.+pub fn render_shape(shape: &ShapeLayer, format: PixelFormat, clip: Rect) -> Surface {+ CompiledShape::new(shape, DEFAULT_TOLERANCE).render(format, clip)+}++#[cfg(test)]+mod tests;diff --git a/crates/vector/src/raster.rs b/crates/vector/src/raster.rsnew file mode 100644index 000000000..8175aa343--- /dev/null+++ b/crates/vector/src/raster.rs@@ -0,0 +1,419 @@+//! Anti-aliased polygon rasterizer with exact area coverage and boolean combination.+//!+//! Each pixel row is cut into horizontal sub-bands at every edge endpoint and every edge+//! crossing inside the row, so that within a sub-band all active edges span its full height and+//! keep their left-to-right order. Walking the edges in that order with one winding counter per+//! *component* tells, between any two consecutive edges, whether the region is inside the+//! combined shape (non-zero or even-odd per component, folded with the path operations). The+//! boundary edges of the inside intervals are then accumulated as signed trapezoid areas ("area+//! to the right of the edge", +1 for a left boundary, −1 for a right boundary) into a per-row+//! cell buffer whose prefix sum is the exact covered area of every pixel. This is the classic+//! scanline/area-coverage technique (see e.g. FreeType's gray rasterizer or libart), written+//! from first principles here; it needs no sub-sampling and handles overlapping components+//! exactly.++use photocraft_doc::{FillRule, PathOp};+use photocraft_geom::Rect;++#[derive(Clone, Copy, Debug)]+struct Edge {+ x0: f64,+ y0: f64,+ y1: f64,+ /// +1 when the source segment runs downwards (y increasing), −1 upwards.+ dir: i32,+ comp: u32,+ dxdy: f64,+}++impl Edge {+ #[inline]+ fn x_at(&self, y: f64) -> f64 {+ self.x0 + (y - self.y0) * self.dxdy+ }+}++/// A combination step: a component (set of polygons filled with `rule`) and how it folds into+/// the result so far.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Component {+ pub op: PathOp,+ pub rule: FillRule,+}++/// A compiled set of polygons, ready to render coverage for any rectangle.+#[derive(Clone, Debug, Default)]+pub struct Rasterizer {+ /// Sorted by `y0`.+ edges: Vec<Edge>,+ comps: Vec<Component>,+ inverted: bool,+ bounds: Option<(f64, f64, f64, f64)>,+ /// Every component combines and none is inverted: inside = any component inside.+ union_only: bool,+}++impl Rasterizer {+ /// Empty rasterizer (renders nothing, or everything when `inverted`: the final result is+ /// inverted).+ pub fn new(inverted: bool) -> Self {+ Rasterizer { inverted, union_only: true, ..Default::default() }+ }++ /// Adds a component made of closed polygons (open input is closed implicitly).+ pub fn add_component(&mut self, polys: &[Vec<(f64, f64)>], op: PathOp, rule: FillRule) {+ let comp = self.comps.len() as u32;+ self.comps.push(Component { op, rule });+ if op != PathOp::Combine && comp != 0 {+ self.union_only = false;+ }+ for poly in polys {+ let n = poly.len();+ if n < 2 {+ continue;+ }+ for i in 0..n {+ let a = poly[i];+ let b = poly[(i + 1) % n];+ if !(a.0.is_finite() && a.1.is_finite() && b.0.is_finite() && b.1.is_finite()) {+ continue;+ }+ self.bounds = Some(match self.bounds {+ None => (a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)),+ Some(bb) => (bb.0.min(a.0.min(b.0)), bb.1.min(a.1.min(b.1)), bb.2.max(a.0.max(b.0)), bb.3.max(a.1.max(b.1))),+ });+ if a.1 == b.1 {+ continue;+ }+ let (p, q, dir) = if a.1 < b.1 { (a, b, 1) } else { (b, a, -1) };+ self.edges.push(Edge { x0: p.0, y0: p.1, y1: q.1, dir, comp, dxdy: (q.0 - p.0) / (q.1 - p.1) });+ }+ }+ self.edges.sort_by(|a, b| a.y0.total_cmp(&b.y0));+ }++ /// Pixel bounds of everything that may be covered (`None` = nothing; the whole plane+ /// when inverted is reported as `None` too — callers clip to their own area).+ pub fn pixel_bounds(&self) -> Option<Rect> {+ if self.inverted {+ return None;+ }+ let (x0, y0, x1, y1) = self.bounds?;+ let r = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32 + 1, y1.ceil() as i32 + 1);+ (!r.is_empty()).then_some(r)+ }++ pub fn is_inverted(&self) -> bool {+ self.inverted+ }++ /// Whether the combined shape is inside given per-component winding numbers.+ #[inline]+ fn inside(&self, wind: &[i32], union_count: i32) -> bool {+ if self.union_only {+ return (union_count > 0) ^ self.inverted;+ }+ let mut acc = false;+ for (i, c) in self.comps.iter().enumerate() {+ let v = match c.rule {+ FillRule::NonZero => wind[i] != 0,+ FillRule::EvenOdd => wind[i] & 1 != 0,+ };+ // Photoshop applies the first component as "combine".+ let op = if i == 0 { PathOp::Combine } else { c.op };+ acc = match op {+ PathOp::Combine => acc | v,+ PathOp::Subtract => acc & !v,+ PathOp::Intersect => acc & v,+ PathOp::Exclude => acc ^ v,+ };+ }+ acc ^ self.inverted+ }++ fn comp_inside(&self, comp: usize, w: i32) -> bool {+ match self.comps[comp].rule {+ FillRule::NonZero => w != 0,+ FillRule::EvenOdd => w & 1 != 0,+ }+ }++ /// Coverage (`0..=1`) of every pixel of `rect`, row-major. Rows are rendered in parallel+ /// strips on native targets.+ pub fn render(&self, rect: Rect) -> Vec<f32> {+ let w = rect.width() as usize;+ let h = rect.height() as usize;+ let mut out = vec![0.0f32; w * h];+ if w == 0 || h == 0 {+ return out;+ }+ #[cfg(not(target_arch = "wasm32"))]+ const STRIP: usize = 32;+ #[cfg(not(target_arch = "wasm32"))]+ if h > STRIP && w * h > 64 * 1024 {+ use rayon::prelude::*;+ out.par_chunks_mut(w * STRIP).enumerate().for_each(|(i, chunk)| {+ let y0 = rect.y0 + (i * STRIP) as i32;+ let rows = chunk.len() / w;+ self.render_into(Rect::new(rect.x0, y0, rect.x1, y0 + rows as i32), chunk);+ });+ return out;+ }+ self.render_into(rect, &mut out);+ out+ }++ /// Renders `rect` into `out` (`rect.width() * rect.height()` values), sequentially.+ pub fn render_into(&self, rect: Rect, out: &mut [f32]) {+ let w = rect.width() as usize;+ let mut st = RowState::new(self.comps.len(), w);+ // Edges are sorted by y0; `next` is the first edge not yet activated.+ let top = f64::from(rect.y0);+ let mut next = self.edges.partition_point(|e| e.y0 < top);+ st.active.extend((0..next).filter(|&i| self.edges[i].y1 > top));+ for (row, y) in (rect.y0..rect.y1).enumerate() {+ let (ya, yb) = (f64::from(y), f64::from(y) + 1.0);+ st.active.retain(|&i| self.edges[i].y1 > ya);+ while next < self.edges.len() && self.edges[next].y0 < yb {+ if self.edges[next].y1 > ya {+ st.active.push(next);+ }+ next += 1;+ }+ let acc = &mut st.acc;+ acc.iter_mut().for_each(|v| *v = 0.0);+ if st.active.is_empty() {+ if self.inverted {+ out[row * w..(row + 1) * w].iter_mut().for_each(|v| *v = 1.0);+ } else {+ out[row * w..(row + 1) * w].iter_mut().for_each(|v| *v = 0.0);+ }+ continue;+ }+ // Sub-band boundaries: the row edges plus every edge endpoint inside the row.+ st.cuts.clear();+ st.cuts.push(ya);+ st.cuts.push(yb);+ for &i in &st.active {+ let e = &self.edges[i];+ if e.y0 > ya && e.y0 < yb {+ st.cuts.push(e.y0);+ }+ if e.y1 > ya && e.y1 < yb {+ st.cuts.push(e.y1);+ }+ }+ st.cuts.sort_by(f64::total_cmp);+ st.cuts.dedup();+ let cuts = std::mem::take(&mut st.cuts);+ for c in cuts.windows(2) {+ self.band(c[0], c[1], rect.x0, &mut st, 0);+ }+ st.cuts = cuts;+ let row_out = &mut out[row * w..(row + 1) * w];+ let mut sum = 0.0f32;+ for (o, a) in row_out.iter_mut().zip(st.acc.iter()) {+ sum += *a;+ *o = sum.clamp(0.0, 1.0);+ }+ }+ }++ /// Accumulates the sub-band `[a, b)` of the current row.+ fn band(&self, a: f64, b: f64, x0: i32, st: &mut RowState, depth: u32) {+ if b - a <= 1e-12 {+ return;+ }+ st.band.clear();+ let mid = 0.5 * (a + b);+ for &i in &st.active {+ let e = &self.edges[i];+ if e.y0 <= mid && e.y1 >= mid {+ let (xa, xb) = (e.x_at(a), e.x_at(b));+ st.band.push(BandEdge { xa, xb, xm: 0.5 * (xa + xb), idx: i as u32 });+ }+ }+ if st.band.is_empty() {+ if self.inverted {+ add_full(&mut st.acc, b - a);+ }+ return;+ }+ st.band.sort_by(|p, q| p.xm.total_cmp(&q.xm));+ // An inversion of the order at the band's top or bottom means two edges cross inside+ // it: split there so the order is constant in every piece.+ if depth < 24 {+ for k in 1..st.band.len() {+ let (p, q) = (st.band[k - 1], st.band[k]);+ let top = p.xa - q.xa;+ let bot = p.xb - q.xb;+ if top > 1e-9 || bot > 1e-9 {+ // Crossing where (p - q)(y) = 0, linear in y over the band.+ let t = if (top - bot).abs() > 1e-15 { top / (top - bot) } else { 0.5 };+ let y = a + (b - a) * t.clamp(0.0, 1.0);+ let y = if y <= a + 1e-9 || y >= b - 1e-9 { mid } else { y };+ self.band(a, y, x0, st, depth + 1);+ self.band(y, b, x0, st, depth + 1);+ return;+ }+ }+ }+ st.wind.iter_mut().for_each(|w| *w = 0);+ let mut union_count = 0i32;+ let mut inside = self.inverted;+ if inside {+ add_full(&mut st.acc, b - a);+ }+ let n = st.band.len();+ for k in 0..n {+ let be = st.band[k];+ let e = &self.edges[be.idx as usize];+ let c = e.comp as usize;+ if self.union_only {+ let was = self.comp_inside(c, st.wind[c]);+ st.wind[c] += e.dir;+ let now = self.comp_inside(c, st.wind[c]);+ union_count += i32::from(now) - i32::from(was);+ } else {+ st.wind[c] += e.dir;+ }+ let now = self.inside(&st.wind, union_count);+ if now != inside {+ let w = if now { 1.0 } else { -1.0 };+ draw(&mut st.acc, x0, be.xa, a, be.xb, b, w);+ inside = now;+ }+ }+ }+}++#[derive(Clone, Copy, Debug)]+struct BandEdge {+ xa: f64,+ xb: f64,+ xm: f64,+ idx: u32,+}++struct RowState {+ active: Vec<usize>,+ cuts: Vec<f64>,+ band: Vec<BandEdge>,+ wind: Vec<i32>,+ /// Cell accumulator: `width + 1` cells (the extra one absorbs spill-over).+ acc: Vec<f32>,+}++impl RowState {+ fn new(comps: usize, width: usize) -> Self {+ RowState { active: Vec::new(), cuts: Vec::new(), band: Vec::new(), wind: vec![0; comps.max(1)], acc: vec![0.0; width + 1] }+ }+}++/// Coverage `h` over the whole row (a boundary left of the rectangle).+#[inline]+fn add_full(acc: &mut [f32], h: f64) {+ acc[0] += h as f32;+}++/// Adds `w` × the area to the right of the segment `(xa, ya) → (xb, yb)` (`ya < yb`, both inside+/// one pixel row) to the cell accumulator whose cell 0 is column `x0`.+fn draw(acc: &mut [f32], x0: i32, xa: f64, ya: f64, xb: f64, yb: f64, w: f64) {+ let width = (acc.len() - 1) as f64;+ let left = f64::from(x0);+ // Work in rectangle-relative x.+ let (mut ua, mut ub) = (xa - left, xb - left);+ let dy = yb - ya;+ if dy <= 0.0 {+ return;+ }+ // Order by x; the vertical extent per unit x is what matters.+ if ua > ub {+ std::mem::swap(&mut ua, &mut ub);+ }+ let dx = ub - ua;+ let h_of = |u0: f64, u1: f64| if dx > 1e-12 { dy * (u1 - u0) / dx } else { dy };+ // Part left of the rectangle: full coverage of every column.+ if ua < 0.0 {+ let cut = ub.min(0.0);+ acc[0] += (w * h_of(ua, cut)) as f32;+ if ub <= 0.0 {+ return;+ }+ ua = 0.0;+ }+ if ua >= width {+ return;+ }+ let end = ub.min(width);+ if dx <= 1e-12 {+ let c = ua.floor();+ let f = ua - c;+ let ci = c as usize;+ acc[ci] += (w * dy * (1.0 - f)) as f32;+ acc[ci + 1] += (w * dy * f) as f32;+ return;+ }+ let mut u = ua;+ while u < end {+ let c = u.floor();+ let v = (c + 1.0).min(end);+ let h = h_of(u, v);+ let m = 0.5 * (u + v) - c;+ let ci = c as usize;+ acc[ci] += (w * h * (1.0 - m)) as f32;+ acc[ci + 1] += (w * h * m) as f32;+ if v <= u {+ break;+ }+ u = v;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn square(x: f64, y: f64, s: f64) -> Vec<(f64, f64)> {+ vec![(x, y), (x + s, y), (x + s, y + s), (x, y + s)]+ }++ fn sum(v: &[f32]) -> f64 {+ v.iter().map(|x| f64::from(*x)).sum()+ }++ #[test]+ fn axis_aligned_square_exact() {+ let mut r = Rasterizer::new(false);+ r.add_component(&[square(2.25, 3.5, 4.0)], PathOp::Combine, FillRule::NonZero);+ let c = r.render(Rect::new(0, 0, 10, 10));+ assert!((sum(&c) - 16.0).abs() < 1e-4);+ assert!((c[3 * 10 + 2] - 0.75 * 0.5).abs() < 1e-5);+ assert!((c[5 * 10 + 4] - 1.0).abs() < 1e-6);+ assert_eq!(c[0], 0.0);+ }++ #[test]+ fn clipped_rect_matches_full_render() {+ let mut r = Rasterizer::new(false);+ r.add_component(&[vec![(1.3, 0.7), (17.9, 5.2), (8.1, 19.6)]], PathOp::Combine, FillRule::NonZero);+ let full = r.render(Rect::new(0, 0, 20, 20));+ let part = r.render(Rect::new(7, 4, 13, 15));+ for y in 4..15 {+ for x in 7..13 {+ let a = full[y * 20 + x];+ let b = part[(y - 4) * 6 + (x - 7)];+ assert!((a - b).abs() < 1e-5, "{x},{y}: {a} vs {b}");+ }+ }+ // Triangle area by the shoelace formula.+ let area = 0.5 * ((17.9f64 - 1.3) * (19.6 - 0.7) - (8.1 - 1.3) * (5.2 - 0.7)).abs();+ assert!((sum(&full) - area).abs() < 1e-3);+ }++ #[test]+ fn inverted_empty_is_full() {+ let r = Rasterizer::new(true);+ assert!(r.render(Rect::new(0, 0, 4, 4)).iter().all(|v| *v == 1.0));+ }+}diff --git a/crates/vector/src/shapes.rs b/crates/vector/src/shapes.rsnew file mode 100644index 000000000..a459ba816--- /dev/null+++ b/crates/vector/src/shapes.rs@@ -0,0 +1,153 @@+//! Parametric ("live") shapes → paths: rectangles with corner radii, ellipses, polygons, stars+//! and lines. Knots run clockwise on screen (y down), starting at the top.++use photocraft_doc::{Knot, LiveShape, Path, Subpath};+use photocraft_geom::Point;++/// Handle length of a quarter-circle cubic, `4/3·(√2 − 1)`.+pub const KAPPA: f64 = 0.552_284_749_830_793_4;++fn smooth(anchor: (f64, f64), inc: (f64, f64), out: (f64, f64)) -> Knot {+ Knot::smooth(Point::new(anchor.0, anchor.1), Point::new(inc.0, inc.1), Point::new(out.0, out.1))+}++/// Axis-aligned rectangle.+pub fn rect(x: f64, y: f64, w: f64, h: f64) -> Path {+ Path::new(vec![Subpath::polygon(&[(x, y), (x + w, y), (x + w, y + h), (x, y + h)])])+}++/// Clamps corner radii `[tl, tr, br, bl]` so adjacent radii never exceed a side (scaled down+/// uniformly, like CSS `border-radius`).+pub fn clamp_radii(w: f64, h: f64, radii: [f64; 4]) -> [f64; 4] {+ let r = radii.map(|v| v.max(0.0));+ let mut f: f64 = 1.0;+ for (a, b, side) in [(r[0], r[1], w), (r[1], r[2], h), (r[2], r[3], w), (r[3], r[0], h)] {+ if a + b > side && a + b > 0.0 {+ f = f.min(side / (a + b));+ }+ }+ r.map(|v| v * f)+}++/// Rectangle with corner radii `[top-left, top-right, bottom-right, bottom-left]`.+pub fn rounded_rect(x: f64, y: f64, w: f64, h: f64, radii: [f64; 4]) -> Path {+ let (w, h) = (w.abs(), h.abs());+ let [tl, tr, br, bl] = clamp_radii(w, h, radii);+ if tl <= 0.0 && tr <= 0.0 && br <= 0.0 && bl <= 0.0 {+ return rect(x, y, w, h);+ }+ let (x1, y1) = (x + w, y + h);+ let mut k = Vec::with_capacity(8);+ let corner = |p: (f64, f64)| Knot::corner(p.0, p.1);+ let push_arc = |k: &mut Vec<Knot>, start: (f64, f64), end: (f64, f64), c_start: (f64, f64), c_end: (f64, f64), r: f64| {+ if r <= 0.0 {+ k.push(corner(start));+ return;+ }+ k.push(Knot { anchor: Point::new(start.0, start.1), in_ctrl: Point::new(start.0, start.1), out_ctrl: Point::new(c_start.0, c_start.1), smooth: false });+ k.push(Knot { anchor: Point::new(end.0, end.1), in_ctrl: Point::new(c_end.0, c_end.1), out_ctrl: Point::new(end.0, end.1), smooth: false });+ };+ // Each corner arc from the end of one edge to the start of the next (clockwise).+ push_arc(&mut k, (x1 - tr, y), (x1, y + tr), (x1 - tr + KAPPA * tr, y), (x1, y + tr - KAPPA * tr), tr);+ push_arc(&mut k, (x1, y1 - br), (x1 - br, y1), (x1, y1 - br + KAPPA * br), (x1 - br + KAPPA * br, y1), br);+ push_arc(&mut k, (x + bl, y1), (x, y1 - bl), (x + bl - KAPPA * bl, y1), (x, y1 - bl + KAPPA * bl), bl);+ push_arc(&mut k, (x, y + tl), (x + tl, y), (x, y + tl - KAPPA * tl), (x + tl - KAPPA * tl, y), tl);+ // Start at the top-left arc end so the first knot is on the top edge.+ let n = k.len();+ k.rotate_left(n - 1);+ // Drop duplicated consecutive anchors (zero-length straight edges).+ let mut out: Vec<Knot> = Vec::with_capacity(k.len());+ for kn in k {+ if let Some(last) = out.last_mut()+ && (last.anchor.x - kn.anchor.x).abs() < 1e-12+ && (last.anchor.y - kn.anchor.y).abs() < 1e-12+ {+ last.out_ctrl = kn.out_ctrl;+ continue;+ }+ out.push(kn);+ }+ if out.len() > 1 {+ let (f, l) = (out[0], out[out.len() - 1]);+ if (f.anchor.x - l.anchor.x).abs() < 1e-12 && (f.anchor.y - l.anchor.y).abs() < 1e-12 {+ out[0].in_ctrl = l.in_ctrl;+ out.pop();+ }+ }+ Path::new(vec![Subpath { closed: true, knots: out, op: Default::default() }])+}++/// Ellipse inscribed in the rectangle.+pub fn ellipse(x: f64, y: f64, w: f64, h: f64) -> Path {+ let (rx, ry) = (w / 2.0, h / 2.0);+ let (cx, cy) = (x + rx, y + ry);+ let (kx, ky) = (rx * KAPPA, ry * KAPPA);+ let knots = vec![+ smooth((cx, cy - ry), (cx - kx, cy - ry), (cx + kx, cy - ry)),+ smooth((cx + rx, cy), (cx + rx, cy - ky), (cx + rx, cy + ky)),+ smooth((cx, cy + ry), (cx + kx, cy + ry), (cx - kx, cy + ry)),+ smooth((cx - rx, cy), (cx - rx, cy + ky), (cx - rx, cy - ky)),+ ];+ Path::new(vec![Subpath { closed: true, knots, op: Default::default() }])+}++/// Regular polygon (or star when `star_ratio < 1`) inscribed in the rectangle's ellipse, first+/// vertex at the top.+pub fn polygon(x: f64, y: f64, w: f64, h: f64, sides: u32, star_ratio: f64) -> Path {+ let sides = sides.clamp(3, 100) as usize;+ let (rx, ry) = (w / 2.0, h / 2.0);+ let (cx, cy) = (x + rx, y + ry);+ let star = star_ratio > 0.0 && star_ratio < 1.0;+ let count = if star { sides * 2 } else { sides };+ let pts: Vec<(f64, f64)> = (0..count)+ .map(|i| {+ let a = -std::f64::consts::FRAC_PI_2 + std::f64::consts::TAU * i as f64 / count as f64;+ let k = if star && i % 2 == 1 { star_ratio } else { 1.0 };+ (cx + rx * k * a.cos(), cy + ry * k * a.sin())+ })+ .collect();+ Path::new(vec![Subpath::polygon(&pts)])+}++/// A line drawn as a filled bar of `weight` px from `a` to `b`.+pub fn line(a: (f64, f64), b: (f64, f64), weight: f64) -> Path {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let l = dx.hypot(dy);+ let hw = weight.max(0.0) / 2.0;+ let (nx, ny) = if l > 0.0 { (-dy / l * hw, dx / l * hw) } else { (0.0, hw) };+ Path::new(vec![Subpath::polygon(&[(a.0 + nx, a.1 + ny), (b.0 + nx, b.1 + ny), (b.0 - nx, b.1 - ny), (a.0 - nx, a.1 - ny)])])+}++/// The path of a live shape.+pub fn live_path(s: &LiveShape) -> Path {+ match s {+ LiveShape::Rect { rect: [x, y, w, h], radii } => rounded_rect(*x, *y, *w, *h, *radii),+ LiveShape::Ellipse { rect: [x, y, w, h] } => ellipse(*x, *y, *w, *h),+ LiveShape::Polygon { rect: [x, y, w, h], sides, star_ratio } => polygon(*x, *y, *w, *h, *sides, *star_ratio),+ LiveShape::Line { from, to, weight } => line((from[0], from[1]), (to[0], to[1]), *weight),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rounded_rect_knots() {+ let p = rounded_rect(0.0, 0.0, 100.0, 50.0, [10.0; 4]);+ assert_eq!(p.subpaths[0].knots.len(), 8);+ let sharp = rounded_rect(0.0, 0.0, 100.0, 50.0, [0.0; 4]);+ assert_eq!(sharp.subpaths[0].knots.len(), 4);+ let mixed = rounded_rect(0.0, 0.0, 100.0, 50.0, [10.0, 0.0, 10.0, 0.0]);+ assert_eq!(mixed.subpaths[0].knots.len(), 6);+ assert_eq!(clamp_radii(10.0, 10.0, [10.0; 4]), [5.0; 4]);+ }++ #[test]+ fn star_vertices() {+ assert_eq!(polygon(0.0, 0.0, 10.0, 10.0, 5, 0.5).subpaths[0].knots.len(), 10);+ assert_eq!(polygon(0.0, 0.0, 10.0, 10.0, 6, 1.0).subpaths[0].knots.len(), 6);+ let top = polygon(0.0, 0.0, 10.0, 10.0, 3, 1.0).subpaths[0].knots[0].anchor;+ assert!((top.x - 5.0).abs() < 1e-9 && top.y.abs() < 1e-9);+ }+}diff --git a/crates/vector/src/stroke.rs b/crates/vector/src/stroke.rsnew file mode 100644index 000000000..8aa966ed1--- /dev/null+++ b/crates/vector/src/stroke.rs@@ -0,0 +1,400 @@+//! Polygon stroking: a stroke is the union of one quad per segment, a wedge per join and a+//! cap shape per open end. Every piece is emitted with positive orientation, so filling them+//! together with the non-zero rule yields their exact union without computing offset curves.+//! Dashing splits the flattened polylines by arc length first.++use photocraft_doc::{LineCap, LineJoin};++use crate::flatten::Polyline;++/// Stroke geometry in pixels.+#[derive(Clone, Debug, PartialEq)]+pub struct StrokeStyle {+ pub width: f64,+ pub cap: LineCap,+ pub join: LineJoin,+ /// Miter limit as a multiple of the width (ratio miter length / width, like SVG).+ pub miter_limit: f64,+ /// Dash pattern in px (`on, off, on, off…`); empty = solid.+ pub dashes: Vec<f64>,+ pub dash_offset: f64,+}++impl Default for StrokeStyle {+ fn default() -> Self {+ StrokeStyle { width: 1.0, cap: LineCap::Butt, join: LineJoin::Miter, miter_limit: 4.0, dashes: Vec::new(), dash_offset: 0.0 }+ }+}++type P = (f64, f64);++fn sub(a: P, b: P) -> P {+ (a.0 - b.0, a.1 - b.1)+}+fn add(a: P, b: P) -> P {+ (a.0 + b.0, a.1 + b.1)+}+fn mul(a: P, k: f64) -> P {+ (a.0 * k, a.1 * k)+}+fn len(a: P) -> f64 {+ a.0.hypot(a.1)+}+fn norm(a: P) -> P {+ let l = len(a);+ if l > 0.0 { (a.0 / l, a.1 / l) } else { (0.0, 0.0) }+}+/// Left normal in y-down coordinates.+fn perp(a: P) -> P {+ (a.1, -a.0)+}+fn cross(a: P, b: P) -> f64 {+ a.0 * b.1 - a.1 * b.0+}+fn dot(a: P, b: P) -> f64 {+ a.0 * b.0 + a.1 * b.1+}++fn signed_area(p: &[P]) -> f64 {+ let n = p.len();+ (0..n).map(|i| cross(p[i], p[(i + 1) % n])).sum::<f64>() * 0.5+}++/// Pushes `poly` with positive orientation (drops degenerate pieces).+fn emit(out: &mut Vec<Vec<P>>, mut poly: Vec<P>) {+ let a = signed_area(&poly);+ if a.abs() < 1e-12 {+ return;+ }+ if a < 0.0 {+ poly.reverse();+ }+ out.push(poly);+}++/// Angular step so that arc chords deviate at most `tol` from a circle of radius `r`.+fn arc_step(r: f64, tol: f64) -> f64 {+ if r <= tol {+ return std::f64::consts::FRAC_PI_2;+ }+ (2.0 * (1.0 - tol / r).clamp(-1.0, 1.0).acos()).clamp(0.01, std::f64::consts::FRAC_PI_2)+}++/// Vertex radius for chords of `step` radians so each chord's pie slice has the area of the+/// circular sector (keeps round caps/joins area-exact at any tessellation).+fn area_radius(r: f64, step: f64) -> f64 {+ if step < 1e-9 { r } else { r * (step / step.sin()).sqrt() }+}++fn circle(c: P, r: f64, tol: f64) -> Vec<P> {+ let n = ((std::f64::consts::TAU / arc_step(r, tol)).ceil() as usize).max(8);+ let rr = area_radius(r, std::f64::consts::TAU / n as f64);+ (0..n)+ .map(|i| {+ let a = std::f64::consts::TAU * i as f64 / n as f64;+ (c.0 + rr * a.cos(), c.1 + rr * a.sin())+ })+ .collect()+}++/// Stroke outline pieces for `lines`. Fill them with the non-zero rule.+pub fn stroke_polygons(lines: &[Polyline], style: &StrokeStyle, tol: f64) -> Vec<Vec<P>> {+ let mut out = Vec::new();+ if style.width <= 0.0 || !style.width.is_finite() {+ return out;+ }+ for pl in lines {+ if style.dashes.iter().any(|d| *d > 0.0) {+ for dash in dash_polyline(pl, &style.dashes, style.dash_offset) {+ stroke_one(&dash, style, tol, &mut out);+ }+ } else {+ stroke_one(pl, style, tol, &mut out);+ }+ }+ out+}++fn stroke_one(pl: &Polyline, style: &StrokeStyle, tol: f64, out: &mut Vec<Vec<P>>) {+ let hw = style.width * 0.5;+ // Drop repeated points.+ let mut pts: Vec<P> = Vec::with_capacity(pl.pts.len());+ let mut knot: Vec<bool> = Vec::with_capacity(pl.pts.len());+ for (i, p) in pl.pts.iter().enumerate() {+ if pts.last().is_some_and(|q| len(sub(*p, *q)) < 1e-9) {+ continue;+ }+ pts.push(*p);+ knot.push(pl.knot.get(i).copied().unwrap_or(true));+ }+ let mut closed = pl.closed;+ if closed && pts.len() > 1 && len(sub(pts[0], pts[pts.len() - 1])) < 1e-9 {+ pts.pop();+ knot.pop();+ }+ if pts.len() < 3 {+ closed = false;+ }+ if pts.is_empty() {+ return;+ }+ if pts.len() == 1 {+ // A dot: only round and square caps draw something.+ let c = pts[0];+ match style.cap {+ LineCap::Round => emit(out, circle(c, hw, tol)),+ LineCap::Square => emit(out, vec![(c.0 - hw, c.1 - hw), (c.0 + hw, c.1 - hw), (c.0 + hw, c.1 + hw), (c.0 - hw, c.1 + hw)]),+ LineCap::Butt => {}+ }+ return;+ }+ let n = pts.len();+ let segs = if closed { n } else { n - 1 };+ let dir = |i: usize| norm(sub(pts[(i + 1) % n], pts[i]));+ let seg_len = |i: usize| len(sub(pts[(i + 1) % n], pts[i]));+ // A vertex continues a ribbon (no separate join piece) when it is a flattening point with a+ // small turn whose inner offset does not fold back, or a knot where the path is straight.+ let cos_smooth = 25f64.to_radians().cos();+ let smooth = |j: usize| -> bool {+ if j == 0 || (!closed && j == n - 1) {+ return false;+ }+ let (i0, i1) = ((j + n - 1) % n, j);+ let d = dot(dir(i0), dir(i1));+ if knot[j] {+ return d > 1.0 - 1e-12;+ }+ if d < cos_smooth {+ return false;+ }+ let tan_half = ((1.0 - d) / (1.0 + d)).max(0.0).sqrt();+ hw * tan_half < 0.5 * seg_len(i0).min(seg_len(i1))+ };+ let mut left: Vec<P> = Vec::new();+ let mut right: Vec<P> = Vec::new();+ for i in 0..segs {+ let a = pts[i];+ let b = pts[(i + 1) % n];+ let nrm = mul(perp(dir(i)), hw);+ if left.is_empty() {+ left.push(add(a, nrm));+ right.push(sub(a, nrm));+ }+ let j = (i + 1) % n;+ if i + 1 < segs + usize::from(!closed) && smooth(j) {+ // Offset lines of both segments meet at v ± bisector · hw / cos(θ/2).+ let n2 = mul(perp(dir(j)), hw);+ let bis = norm(add(nrm, n2));+ let cos_half = ((1.0 + dot(dir(i), dir(j))) * 0.5).max(1e-9).sqrt();+ let off = mul(bis, hw / cos_half);+ left.push(add(b, off));+ right.push(sub(b, off));+ continue;+ }+ left.push(add(b, nrm));+ right.push(sub(b, nrm));+ let mut poly = std::mem::take(&mut left);+ poly.extend(right.drain(..).rev());+ emit(out, poly);+ let is_join = closed || j != n - 1;+ if is_join {+ let prev = pts[i];+ let v = pts[j];+ let next = pts[(j + 1) % n];+ let d1 = norm(sub(v, prev));+ let d2 = norm(sub(next, v));+ // Flattening points use miters (the true offset of a smooth curve) unless the+ // requested join is round; bevels only at real corners.+ let join = match (style.join, knot[j]) {+ (LineJoin::Round, _) => LineJoin::Round,+ (jn, true) => jn,+ (_, false) => LineJoin::Miter,+ };+ join_piece(v, d1, d2, hw, join, if knot[j] { style.miter_limit } else { f64::INFINITY }, tol, out);+ }+ }+ if !closed {+ let d0 = norm(sub(pts[1], pts[0]));+ let d1 = norm(sub(pts[n - 1], pts[n - 2]));+ cap_piece(pts[0], mul(d0, -1.0), hw, style.cap, tol, out);+ cap_piece(pts[n - 1], d1, hw, style.cap, tol, out);+ }+}++#[allow(clippy::too_many_arguments)]+fn join_piece(v: P, d1: P, d2: P, hw: f64, join: LineJoin, miter_limit: f64, tol: f64, out: &mut Vec<Vec<P>>) {+ let c = cross(d1, d2);+ let d = dot(d1, d2);+ if c.abs() < 1e-12 && d > 0.0 {+ return;+ }+ // Outer side: a right turn (c > 0 in y-down) opens the left side.+ let s = if c > 0.0 { 1.0 } else { -1.0 };+ let n1 = mul(perp(d1), hw * s);+ let n2 = mul(perp(d2), hw * s);+ let (a, b) = (add(v, n1), add(v, n2));+ match join {+ LineJoin::Bevel => emit(out, vec![v, a, b]),+ LineJoin::Miter => {+ // Miter length / width = 1 / sin(θ/2) where θ is the angle between the segments.+ let half = ((1.0 - d) * 0.5).max(0.0).sqrt(); // sin of half the turning angle+ let cos_half = ((1.0 + d) * 0.5).max(0.0).sqrt();+ if cos_half < 1e-9 || 1.0 / cos_half > miter_limit {+ emit(out, vec![v, a, b]);+ } else {+ let bis = norm(add(n1, n2));+ let m = add(v, mul(bis, hw / cos_half));+ let _ = half;+ emit(out, vec![v, a, m, b]);+ }+ }+ LineJoin::Round => {+ let a0 = n1.1.atan2(n1.0);+ let mut a1 = n2.1.atan2(n2.0);+ // Sweep the short way from n1 to n2 on the outer side.+ let mut delta = a1 - a0;+ while delta > std::f64::consts::PI {+ delta -= std::f64::consts::TAU;+ }+ while delta < -std::f64::consts::PI {+ delta += std::f64::consts::TAU;+ }+ if c.abs() < 1e-12 {+ // U-turn: half circle on the side of n1 rotating towards d1.+ delta = std::f64::consts::PI * if cross(n1, d1) > 0.0 { 1.0 } else { -1.0 };+ }+ a1 = a0 + delta;+ let steps = ((delta.abs() / arc_step(hw, tol)).ceil() as usize).max(1);+ let rr = area_radius(hw, delta.abs() / steps as f64);+ let mut poly = vec![v, a];+ for k in 1..steps {+ let t = a0 + (a1 - a0) * k as f64 / steps as f64;+ poly.push((v.0 + rr * t.cos(), v.1 + rr * t.sin()));+ }+ poly.push(b);+ emit(out, poly);+ }+ }+}++fn cap_piece(p: P, dir: P, hw: f64, cap: LineCap, tol: f64, out: &mut Vec<Vec<P>>) {+ match cap {+ LineCap::Butt => {}+ LineCap::Round => emit(out, circle(p, hw, tol)),+ LineCap::Square => {+ let n = mul(perp(dir), hw);+ let e = mul(dir, hw);+ emit(out, vec![add(p, n), add(add(p, n), e), add(sub(p, n), e), sub(p, n)]);+ }+ }+}++/// Splits a polyline into dashes (open polylines). `pattern` alternates on/off lengths in px.+pub fn dash_polyline(pl: &Polyline, pattern: &[f64], offset: f64) -> Vec<Polyline> {+ let mut pat: Vec<f64> = pattern.iter().map(|d| d.max(0.0)).collect();+ if pat.len() % 2 == 1 {+ let copy = pat.clone();+ pat.extend(copy);+ }+ let total: f64 = pat.iter().sum();+ if total <= 1e-9 || pl.pts.len() < 2 {+ return vec![pl.clone()];+ }+ let mut pts = pl.pts.clone();+ let mut knots = pl.knot.clone();+ knots.resize(pts.len(), true);+ if pl.closed {+ pts.push(pl.pts[0]);+ knots.push(true);+ }+ // Position in the pattern.+ let mut idx = 0usize;+ let mut left = pat[0];+ let mut skip = offset.rem_euclid(total);+ while skip > 0.0 {+ if skip >= left {+ skip -= left;+ idx = (idx + 1) % pat.len();+ left = pat[idx];+ } else {+ left -= skip;+ skip = 0.0;+ }+ }+ let mut out = Vec::new();+ let mut cur: Option<Polyline> = if idx.is_multiple_of(2) { Some(Polyline { pts: vec![pts[0]], knot: vec![true], closed: false }) } else { None };+ let mut guard = 0usize;+ for (wi, w) in pts.windows(2).enumerate() {+ let (a, b) = (w[0], w[1]);+ let b_knot = knots[wi + 1];+ let seg = len(sub(b, a));+ let mut pos = 0.0;+ while seg - pos > 1e-12 {+ guard += 1;+ if guard > 10_000_000 {+ break;+ }+ let step = left.min(seg - pos);+ pos += step;+ left -= step;+ let at_end = seg - pos <= 1e-12;+ let p = if at_end { b } else { add(a, mul(sub(b, a), pos / seg)) };+ if let Some(c) = cur.as_mut() {+ c.pts.push(p);+ c.knot.push(!at_end || b_knot);+ }+ if left <= 1e-12 {+ idx = (idx + 1) % pat.len();+ left = pat[idx];+ if idx % 2 == 1 {+ if let Some(c) = cur.take() {+ out.push(c);+ }+ } else {+ cur = Some(Polyline { pts: vec![p], knot: vec![true], closed: false });+ }+ }+ }+ // The vertex at `b` is a join inside a dash: keep it (already pushed when reached).+ }+ if let Some(c) = cur.take()+ && c.pts.len() > 1+ {+ out.push(c);+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn line(pts: &[P], closed: bool) -> Polyline {+ Polyline { pts: pts.to_vec(), knot: vec![true; pts.len()], closed }+ }++ #[test]+ fn dashes_split_by_length() {+ let pl = line(&[(0.0, 0.0), (10.0, 0.0)], false);+ let d = dash_polyline(&pl, &[2.0, 1.0], 0.0);+ // on [0,2] [3,5] [6,8] [9,10]+ assert_eq!(d.len(), 4);+ assert!((d[1].pts[0].0 - 3.0).abs() < 1e-9 && (d[1].pts.last().unwrap().0 - 5.0).abs() < 1e-9);+ assert!((d[3].pts.last().unwrap().0 - 10.0).abs() < 1e-9);+ let o = dash_polyline(&pl, &[2.0, 1.0], 1.0);+ assert!((o[0].pts.last().unwrap().0 - 1.0).abs() < 1e-9);+ }++ #[test]+ fn pieces_are_positive() {+ let pl = line(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], false);+ for join in [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel] {+ for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {+ let st = StrokeStyle { width: 2.0, join, cap, ..Default::default() };+ for p in stroke_polygons(std::slice::from_ref(&pl), &st, 0.1) {+ assert!(signed_area(&p) > 0.0);+ }+ }+ }+ }+}diff --git a/crates/vector/src/tests.rs b/crates/vector/src/tests.rsnew file mode 100644index 000000000..83dc92b66--- /dev/null+++ b/crates/vector/src/tests.rs@@ -0,0 +1,342 @@+use photocraft_color::{Color, PixelFormat, SampleType};+use photocraft_doc::{Fill, FillRule, LineCap, LineJoin, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath, VectorMask};+use photocraft_geom::Rect;++use crate::*;++fn area(v: &[f32]) -> f64 {+ v.iter().map(|x| f64::from(*x)).sum()+}++fn cov(path: &Path, rect: Rect) -> Vec<f32> {+ path_coverage(path, rect)+}++#[test]+fn circle_area_matches_analytic() {+ for r in [3.3, 10.0, 47.5, 200.25] {+ let c = 256.0 + 0.37;+ let p = shapes::ellipse(c - r, c - r, 2.0 * r, 2.0 * r);+ let got = area(&cov(&p, Rect::new(0, 0, 512, 512)));+ let want = std::f64::consts::PI * r * r;+ // The 4-arc Bézier circle overshoots the true circle by up to 0.027% of r.+ assert!((got - want).abs() / want < 0.005, "r={r}: {got} vs {want}");+ if r >= 10.0 {+ assert!((got - want).abs() / want < 0.0015, "r={r}: {got} vs {want}");+ }+ }+}++#[test]+fn rect_area_exact_and_rotated() {+ let p = shapes::rect(10.3, 20.7, 100.45, 50.2);+ let got = area(&cov(&p, Rect::new(0, 0, 200, 100)));+ assert!((got - 100.45 * 50.2).abs() < 1e-2, "{got}");+ // Rotated square: area preserved.+ let rot = p.transform(&photocraft_geom::Affine::rotate(0.4).then(&photocraft_geom::Affine::translate(60.0, 30.0)));+ let got = area(&cov(&rot, Rect::new(-100, -100, 400, 400)));+ assert!((got - 100.45 * 50.2).abs() / (100.45 * 50.2) < 1e-4, "{got}");+}++#[test]+fn coverage_is_tile_independent() {+ let p = shapes::polygon(3.0, 5.0, 90.0, 80.0, 7, 0.45);+ let full = cov(&p, Rect::new(0, 0, 100, 100));+ for (x0, y0) in [(0, 0), (13, 29), (50, 50)] {+ let r = Rect::new(x0, y0, x0 + 37, y0 + 23);+ let part = cov(&p, r);+ for y in r.y0..r.y1 {+ for x in r.x0..r.x1 {+ let a = full[(y * 100 + x) as usize];+ let b = part[((y - y0) * 37 + (x - x0)) as usize];+ assert!((a - b).abs() < 1e-5);+ }+ }+ }+}++/// Pentagram drawn as one self-intersecting subpath.+fn pentagram() -> Path {+ let pts: Vec<(f64, f64)> = (0..5)+ .map(|i| {+ let a = -std::f64::consts::FRAC_PI_2 + std::f64::consts::TAU * (i * 2 % 5) as f64 / 5.0;+ (50.0 + 40.0 * a.cos(), 50.0 + 40.0 * a.sin())+ })+ .collect();+ Path::new(vec![Subpath::polygon(&pts)])+}++#[test]+fn even_odd_vs_non_zero() {+ let r = Rect::new(0, 0, 100, 100);+ let nz = cov(&pentagram(), r);+ let mut eo_path = pentagram();+ eo_path.fill_rule = FillRule::EvenOdd;+ let eo = cov(&eo_path, r);+ // Centre: filled with non-zero (winding 2), empty with even-odd.+ assert_eq!(nz[50 * 100 + 50], 1.0);+ assert_eq!(eo[50 * 100 + 50], 0.0);+ // A star tip is filled with both.+ assert_eq!(nz[16 * 100 + 50], 1.0);+ assert_eq!(eo[16 * 100 + 50], 1.0);+ assert!(area(&nz) > area(&eo) + 500.0);+ // Non-zero area − even-odd area = the inner pentagon (circumradius R·cos72°/cos36°).+ let r_in = 40.0 * 72f64.to_radians().cos() / 36f64.to_radians().cos();+ let inner_pent = 2.5 * r_in * r_in * (72f64.to_radians()).sin();+ assert!(((area(&nz) - area(&eo)) - inner_pent).abs() / inner_pent < 0.01, "{} vs {inner_pent}", area(&nz) - area(&eo));+}++fn two_squares(op: PathOp) -> Path {+ Path::new(vec![shapes::rect(10.0, 10.0, 40.0, 40.0).subpaths.remove(0), shapes::rect(30.0, 30.0, 40.0, 40.0).subpaths.remove(0).with_op(op)])+}++#[test]+fn boolean_ops_areas() {+ let r = Rect::new(0, 0, 100, 100);+ let a = |op| area(&cov(&two_squares(op), r));+ assert!((a(PathOp::Combine) - (1600.0 * 2.0 - 400.0)).abs() < 1e-2);+ assert!((a(PathOp::Subtract) - 1200.0).abs() < 1e-2);+ assert!((a(PathOp::Intersect) - 400.0).abs() < 1e-2);+ assert!((a(PathOp::Exclude) - 2400.0).abs() < 1e-2);+ // Order matters: the first subpath is always combined.+ let mut p = two_squares(PathOp::Combine);+ p.subpaths[0].op = PathOp::Subtract;+ assert!((area(&cov(&p, r)) - 2800.0).abs() < 1e-2);+ // Inversion.+ let mut inv = two_squares(PathOp::Intersect);+ inv.inverted = true;+ assert!((area(&cov(&inv, r)) - (10000.0 - 400.0)).abs() < 1e-2);+ // Donut: circle minus a smaller circle (exact booleans, even with overlapping AA edges).+ let mut d = shapes::ellipse(10.0, 10.0, 80.0, 80.0);+ d.subpaths.push(shapes::ellipse(30.0, 30.0, 40.0, 40.0).subpaths.remove(0).with_op(PathOp::Subtract));+ let want = std::f64::consts::PI * (1600.0 - 400.0);+ assert!((area(&cov(&d, r)) - want).abs() / want < 0.002);+}++fn stroke_area(path: &Path, st: &StrokeStyle) -> f64 {+ let r = stroke_rasterizer(path, st, DEFAULT_TOLERANCE);+ area(&r.render(Rect::new(-50, -50, 250, 250)))+}++#[test]+fn stroke_widths_caps_and_joins() {+ let line = Path::new(vec![Subpath::polyline(&[(20.0, 50.0), (120.0, 50.0)])]);+ let st = |w: f64, cap| StrokeStyle { width: w, cap, ..Default::default() };+ // Butt: exactly length × width.+ for w in [1.0, 2.5, 10.0] {+ assert!((stroke_area(&line, &st(w, LineCap::Butt)) - 100.0 * w).abs() < 1e-2, "w={w}");+ }+ // Square adds w/2 at both ends; round adds a disc.+ assert!((stroke_area(&line, &st(10.0, LineCap::Square)) - 110.0 * 10.0).abs() < 1e-2);+ let round = stroke_area(&line, &st(10.0, LineCap::Round));+ assert!((round - (1000.0 + std::f64::consts::PI * 25.0)).abs() < 0.5, "{round}");+ // Right-angle polyline: miter fills the full corner square, bevel half, round a quarter disc.+ let l = Path::new(vec![Subpath::polyline(&[(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)])]);+ let j = |join| stroke_area(&l, &StrokeStyle { width: 10.0, join, ..Default::default() });+ let base = 2.0 * 100.0 * 10.0;+ let miter = j(LineJoin::Miter);+ let bevel = j(LineJoin::Bevel);+ let roundj = j(LineJoin::Round);+ // Two 100×10 bars share the inner 5×5 quarter; the outer 5×5 corner is the join.+ assert!((miter - (base - 25.0 + 25.0)).abs() < 1e-2, "{miter}");+ assert!((bevel - (base - 25.0 + 12.5)).abs() < 1e-2, "{bevel}");+ assert!((roundj - (base - 25.0 + std::f64::consts::PI * 25.0 / 4.0)).abs() < 0.1, "{roundj}");+ // Miter limit: a very sharp angle falls back to bevel.+ let sharp = Path::new(vec![Subpath::polyline(&[(0.0, 0.0), (100.0, 5.0), (0.0, 10.0)])]);+ let lim = |m| stroke_area(&sharp, &StrokeStyle { width: 4.0, join: LineJoin::Miter, miter_limit: m, ..Default::default() });+ assert!(lim(100.0) > lim(4.0) + 10.0);+}++#[test]+fn closed_rect_stroke_and_alignment() {+ let sq = shapes::rect(20.0, 20.0, 100.0, 100.0);+ let st = StrokeStyle { width: 10.0, ..Default::default() };+ // Centred miter stroke of a closed square: outer 110² minus inner 90².+ assert!((stroke_area(&sq, &st) - (110.0f64.powi(2) - 90.0f64.powi(2))).abs() < 1e-2);+ let shape = |align| ShapeLayer {+ path: sq.clone(),+ fill: None,+ stroke: Some(ShapeStroke { width: 10.0, paint: Fill::Solid(Color::BLACK), align, ..Default::default() }),+ ..Default::default()+ };+ let alpha_area = |sh: &ShapeLayer| {+ let rgba = CompiledShape::new(sh, DEFAULT_TOLERANCE).render_rgba(Rect::new(0, 0, 150, 150));+ rgba.iter().map(|p| f64::from(p[3])).sum::<f64>()+ };+ assert!((alpha_area(&shape(StrokeAlign::Inside)) - (100.0f64.powi(2) - 80.0f64.powi(2))).abs() < 0.05);+ assert!((alpha_area(&shape(StrokeAlign::Outside)) - (120.0f64.powi(2) - 100.0f64.powi(2))).abs() < 0.05);+ assert!((alpha_area(&shape(StrokeAlign::Center)) - (110.0f64.powi(2) - 90.0f64.powi(2))).abs() < 0.05);+}++#[test]+fn dashes_cover_expected_fraction() {+ let line = Path::new(vec![Subpath::polyline(&[(0.0, 50.0), (120.0, 50.0)])]);+ let st = StrokeStyle { width: 4.0, dashes: vec![8.0, 4.0], ..Default::default() };+ // 120 px = 10 periods of 12 px, 8 on each.+ assert!((stroke_area(&line, &st) - 80.0 * 4.0).abs() < 1e-2);+ // Photoshop-style dash units (multiples of width) via stroke_style.+ let s = stroke_style(&ShapeStroke { width: 4.0, dashes: vec![2.0, 1.0], ..Default::default() });+ assert_eq!(s.dashes, vec![8.0, 4.0]);+ // Round caps on zero-length dashes draw dots.+ let dots = StrokeStyle { width: 4.0, cap: LineCap::Round, dashes: vec![0.0, 12.0], ..Default::default() };+ let a = stroke_area(&line, &dots);+ let one = std::f64::consts::PI * 4.0;+ assert!(a > 9.0 * one && a < 11.5 * one, "{a}");+}++#[test]+fn render_shape_formats_and_paint() {+ let sh = ShapeLayer {+ path: shapes::rect(2.0, 2.0, 10.0, 10.0),+ fill: Some(Fill::Solid(Color::rgb(1.0, 0.0, 0.0))),+ stroke: Some(ShapeStroke { width: 2.0, paint: Fill::Solid(Color::rgb(0.0, 0.0, 1.0)), ..Default::default() }),+ ..Default::default()+ };+ for sample in SampleType::ALL {+ for mode in [photocraft_color::ColorMode::Rgb, photocraft_color::ColorMode::Grayscale, photocraft_color::ColorMode::Cmyk] {+ let fmt = PixelFormat::new(mode, sample, true);+ let s = render_shape(&sh, fmt, Rect::new(0, 0, 20, 20));+ assert_eq!(s.format(), fmt);+ assert_eq!(s.content_bounds(), Rect::new(1, 1, 13, 13));+ let centre = photocraft_raster::to_rgba(&fmt, &s.pixel(7, 7));+ let edge = photocraft_raster::to_rgba(&fmt, &s.pixel(2, 7));+ assert!((centre[3] - 1.0).abs() < 1e-3);+ if mode == photocraft_color::ColorMode::Rgb {+ assert!(centre[0] > 0.99 && centre[2] < 0.01);+ assert!(edge[2] > 0.99, "{edge:?}");+ }+ }+ }+ // Clip: nothing outside.+ let s = render_shape(&sh, PixelFormat::RGBA8, Rect::new(0, 0, 5, 5));+ assert_eq!(s.content_bounds(), Rect::new(1, 1, 5, 5));+}++#[test]+fn gradient_fill_spans_bounds() {+ let sh = ShapeLayer {+ path: shapes::rect(0.0, 0.0, 100.0, 10.0),+ fill: Some(Fill::Gradient {+ stops: vec![(0.0, Color::BLACK), (1.0, Color::WHITE)],+ angle: 0.0,+ scale: 1.0,+ style: photocraft_doc::GradientStyle::Linear,+ reverse: false,+ }),+ ..Default::default()+ };+ let rgba = CompiledShape::new(&sh, DEFAULT_TOLERANCE).render_rgba(Rect::new(0, 0, 100, 10));+ assert!(rgba[0][0] < 0.02 && rgba[99][0] > 0.98 && (rgba[50][0] - 0.505).abs() < 0.02);+}++#[test]+fn coverage_surface_and_vector_mask_values() {+ let p = shapes::rect(10.0, 10.0, 20.0, 20.0);+ let r = fill_rasterizer(&p, DEFAULT_TOLERANCE);+ let s = coverage_surface(&r, PixelFormat::GRAY8, Rect::new(0, 0, 300, 300));+ assert_eq!(s.content_bounds(), Rect::new(10, 10, 30, 30));+ assert_eq!(s.tile_count(), 1);+ let mut inv = p.clone();+ inv.inverted = true;+ let si = coverage_surface(&fill_rasterizer(&inv, DEFAULT_TOLERANCE), PixelFormat::GRAY8, Rect::new(0, 0, 40, 40));+ assert_eq!(si.sample_channel(0, 0, 0), 1.0);+ assert_eq!(si.sample_channel(15, 15, 0), 0.0);+ let mut vm = VectorMask::new(p);+ vm.density = 0.25;+ let v = vector_mask_values(&vm, Rect::new(0, 0, 40, 40));+ assert!((v[0] - 0.75).abs() < 1e-6 && (v[15 * 40 + 15] - 1.0).abs() < 1e-6);+ vm.enabled = false;+ assert!(vector_mask_values(&vm, Rect::new(0, 0, 4, 4)).iter().all(|x| *x == 1.0));+ // Empty vector masks reveal all (hide all when inverted).+ let mut empty = VectorMask::new(Path::default());+ assert!(vector_mask_values(&empty, Rect::new(0, 0, 4, 4)).iter().all(|x| *x == 1.0));+ empty.path.inverted = true;+ assert!(vector_mask_values(&empty, Rect::new(0, 0, 4, 4)).iter().all(|x| *x == 0.0));+}++fn iou(a: &[f32], b: &[f32]) -> f64 {+ let (mut i, mut u) = (0.0, 0.0);+ for (x, y) in a.iter().zip(b) {+ i += f64::from(x.min(*y));+ u += f64::from(x.max(*y));+ }+ i / u.max(1e-9)+}++#[test]+fn trace_roundtrip_iou() {+ let rect = Rect::new(0, 0, 160, 120);+ // Antialiased donut + a hard rectangle, as a selection would hold.+ let mut src = shapes::ellipse(10.0, 10.0, 90.0, 90.0);+ src.subpaths.push(shapes::ellipse(35.0, 35.0, 40.0, 40.0).subpaths.remove(0).with_op(PathOp::Subtract));+ src.subpaths.push(shapes::rect(110.0, 20.0, 40.0, 80.0).subpaths.remove(0));+ let mask = cov(&src, rect);+ for tol in [0.5, 1.0, 2.0] {+ let traced = trace::trace_mask(&mask, rect, 0.0, tol);+ assert_eq!(traced.subpaths.len(), 3, "tol {tol}");+ let back = cov(&traced, rect);+ let v = iou(&mask, &back);+ assert!(v > 0.98, "tol {tol}: IoU {v}");+ let knots: usize = traced.subpaths.iter().map(|s| s.knots.len()).sum();+ assert!(knots < 60, "tol {tol}: {knots} knots");+ }+ // Hard-edged (binary) mask.+ let hard: Vec<f32> = mask.iter().map(|v| if *v >= 0.5 { 1.0 } else { 0.0 }).collect();+ let back = cov(&trace::trace_mask(&hard, rect, 0.0, 1.0), rect);+ assert!(iou(&hard, &back) > 0.98);+}++/// Performance on a 6016² canvas (run with `--release --ignored --nocapture`).+#[test]+#[ignore]+fn perf_6016() {+ let canvas = Rect::new(0, 0, 6016, 6016);+ // A complex path: 400-point star spiral with curves (Bézier knots).+ let mut knots = Vec::new();+ let n = 2000;+ for i in 0..n {+ let t = i as f64 / n as f64 * std::f64::consts::TAU;+ let r = 2400.0 + 500.0 * (t * 37.0).sin() + 200.0 * (t * 101.0).cos();+ let (x, y) = (3008.0 + r * t.cos(), 3008.0 + r * t.sin());+ let d = 6.0;+ knots.push(photocraft_doc::Knot::smooth(+ photocraft_geom::Point::new(x, y),+ photocraft_geom::Point::new(x - d * t.sin(), y + d * t.cos()),+ photocraft_geom::Point::new(x + d * t.sin(), y - d * t.cos()),+ ));+ }+ let mut path = Path::new(vec![Subpath { closed: true, knots, op: PathOp::Combine }]);+ path.subpaths.push(shapes::ellipse(2000.0, 2000.0, 2016.0, 2016.0).subpaths.remove(0).with_op(PathOp::Exclude));+ let sh = ShapeLayer {+ path: path.clone(),+ fill: Some(Fill::Solid(Color::rgb(0.2, 0.5, 0.9))),+ stroke: Some(ShapeStroke { width: 12.0, join: LineJoin::Round, dashes: vec![3.0, 2.0], ..Default::default() }),+ ..Default::default()+ };+ let t = std::time::Instant::now();+ let r = fill_rasterizer(&path, DEFAULT_TOLERANCE);+ let c = r.render(canvas);+ let fill_ms = t.elapsed().as_secs_f64() * 1000.0;+ let st = stroke_style(sh.stroke.as_ref().unwrap());+ let t = std::time::Instant::now();+ let lines = flatten_path(&path, 0.04);+ let polys = stroke_polygons(&lines, &st, 0.01);+ eprintln!("flatten+pieces {:.0} ms: {} polylines {} pts, {} pieces {} verts", t.elapsed().as_secs_f64() * 1000.0, lines.len(), lines.iter().map(|l| l.pts.len()).sum::<usize>(), polys.len(), polys.iter().map(|p| p.len()).sum::<usize>());+ let t = std::time::Instant::now();+ let sr = stroke_rasterizer(&path, &st, DEFAULT_TOLERANCE);+ let sc = sr.render(canvas);+ let stroke_ms = t.elapsed().as_secs_f64() * 1000.0;+ let t = std::time::Instant::now();+ let s = render_shape(&sh, PixelFormat::RGBA8, canvas);+ let shape_ms = t.elapsed().as_secs_f64() * 1000.0;+ let t = std::time::Instant::now();+ let s16 = render_shape(&sh, PixelFormat::RGBA16, canvas);+ let shape16_ms = t.elapsed().as_secs_f64() * 1000.0;+ eprintln!(+ "6016²: fill coverage {fill_ms:.0} ms (area {:.0}), stroke coverage {stroke_ms:.0} ms (area {:.0}), shape→RGBA8 surface {shape_ms:.0} ms ({} tiles), RGBA16 {shape16_ms:.0} ms",+ area(&c),+ area(&sc),+ s.tile_count()+ );+ assert!(s16.tile_count() > 0);+}diff --git a/crates/vector/src/trace.rs b/crates/vector/src/trace.rsnew file mode 100644index 000000000..aab5ce665--- /dev/null+++ b/crates/vector/src/trace.rs@@ -0,0 +1,443 @@+//! Coverage mask → path ("Make Work Path" from a selection).+//!+//! 1. Marching squares at level 0.5 over pixel centres (linear interpolation along cell edges,+//! saddles resolved with the cell average) gives closed, non-intersecting contours.+//! 2. Corners are found where the direction over a ±1.5 px window turns by more than 60°.+//! 3. Each run between corners is fitted with cubic Béziers by least squares with Newton+//! reparameterisation, splitting at the worst point until within `tolerance` (P. J.+//! Schneider, "An Algorithm for Automatically Fitting Digitized Curves", Graphics Gems, 1990).+//!+//! Contours are emitted as subpaths: the first combines, the rest *exclude*, which is the+//! even-odd area for nested, non-crossing contours regardless of their orientation.++use std::collections::HashMap;++use photocraft_doc::{Knot, Path, PathOp, Subpath};+use photocraft_geom::{Point, Rect};++type P = (f64, f64);++/// Traces the 0.5 iso-contours of `values` (row-major over `rect`, values outside read as+/// `outside`) and fits curves within `tolerance` px.+pub fn trace_mask(values: &[f32], rect: Rect, outside: f32, tolerance: f64) -> Path {+ let loops = contours(values, rect, outside);+ let mut subpaths = Vec::new();+ for (i, lp) in loops.iter().enumerate() {+ if lp.len() < 3 {+ continue;+ }+ // Fit to half the tolerance: the worst point may deviate by the full amount only rarely.+ let mut s = fit_closed(lp, (tolerance * 0.5).max(0.05));+ s.op = if i == 0 { PathOp::Combine } else { PathOp::Exclude };+ subpaths.push(s);+ }+ Path::new(subpaths)+}++/// Closed iso-contours at 0.5 through pixel centres.+pub fn contours(values: &[f32], rect: Rect, outside: f32) -> Vec<Vec<P>> {+ let w = rect.width() as i64;+ let h = rect.height() as i64;+ let get = |x: i64, y: i64| -> f32 { if x < 0 || y < 0 || x >= w || y >= h { outside } else { values[(y * w + x) as usize] } };+ // Edge ids: horizontal edge between (x,y)-(x+1,y) = (x, y, 0); vertical (x,y)-(x,y+1) = (x, y, 1).+ let lvl = 0.5f32;+ let point = |a: (i64, i64), b: (i64, i64)| -> P {+ let (va, vb) = (get(a.0, a.1), get(b.0, b.1));+ let t = if (vb - va).abs() > 1e-9 { f64::from((lvl - va) / (vb - va)).clamp(0.0, 1.0) } else { 0.5 };+ let (ax, ay) = (a.0 as f64 + 0.5, a.1 as f64 + 0.5);+ let (bx, by) = (b.0 as f64 + 0.5, b.1 as f64 + 0.5);+ (f64::from(rect.x0) + ax + (bx - ax) * t, f64::from(rect.y0) + ay + (by - ay) * t)+ };+ // Segments from edge -> edge, oriented with the inside on the left (y down).+ let mut next: HashMap<(i64, i64, u8), (i64, i64, u8)> = HashMap::new();+ for cy in -1..h {+ for cx in -1..w {+ let tl = get(cx, cy) >= lvl;+ let tr = get(cx + 1, cy) >= lvl;+ let br = get(cx + 1, cy + 1) >= lvl;+ let bl = get(cx, cy + 1) >= lvl;+ let idx = u8::from(tl) | u8::from(tr) << 1 | u8::from(br) << 2 | u8::from(bl) << 3;+ if idx == 0 || idx == 15 {+ continue;+ }+ let top = (cx, cy, 0u8);+ let bottom = (cx, cy + 1, 0u8);+ let left = (cx, cy, 1u8);+ let right = (cx + 1, cy, 1u8);+ // Walking along the contour with the inside on the left-hand side.+ let mut seg = |a: (i64, i64, u8), b: (i64, i64, u8)| {+ next.insert(a, b);+ };+ match idx {+ 1 => seg(left, top),+ 2 => seg(top, right),+ 3 => seg(left, right),+ 4 => seg(right, bottom),+ 5 => {+ let centre = (get(cx, cy) + get(cx + 1, cy) + get(cx + 1, cy + 1) + get(cx, cy + 1)) / 4.0;+ if centre >= lvl {+ seg(left, bottom);+ seg(right, top);+ } else {+ seg(left, top);+ seg(right, bottom);+ }+ }+ 6 => seg(top, bottom),+ 7 => seg(left, bottom),+ 8 => seg(bottom, left),+ 9 => seg(bottom, top),+ 10 => {+ let centre = (get(cx, cy) + get(cx + 1, cy) + get(cx + 1, cy + 1) + get(cx, cy + 1)) / 4.0;+ if centre >= lvl {+ seg(top, left);+ seg(bottom, right);+ } else {+ seg(top, right);+ seg(bottom, left);+ }+ }+ 11 => seg(bottom, right),+ 12 => seg(right, left),+ 13 => seg(right, top),+ 14 => seg(top, left),+ _ => {}+ }+ }+ }+ let edge_point = |e: (i64, i64, u8)| if e.2 == 0 { point((e.0, e.1), (e.0 + 1, e.1)) } else { point((e.0, e.1), (e.0, e.1 + 1)) };+ let mut keys: Vec<(i64, i64, u8)> = next.keys().copied().collect();+ keys.sort_unstable_by_key(|k| (k.1, k.0, k.2));+ let mut out = Vec::new();+ for start in keys {+ if !next.contains_key(&start) {+ continue;+ }+ let mut lp = Vec::new();+ let mut cur = start;+ while let Some(n) = next.remove(&cur) {+ lp.push(edge_point(cur));+ cur = n;+ if cur == start {+ break;+ }+ }+ // Drop consecutive duplicates (interpolation can land on a corner).+ lp.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9);+ if lp.len() >= 3 {+ out.push(lp);+ }+ }+ out+}++fn sub(a: P, b: P) -> P {+ (a.0 - b.0, a.1 - b.1)+}+fn add(a: P, b: P) -> P {+ (a.0 + b.0, a.1 + b.1)+}+fn mul(a: P, k: f64) -> P {+ (a.0 * k, a.1 * k)+}+fn dot(a: P, b: P) -> f64 {+ a.0 * b.0 + a.1 * b.1+}+fn len(a: P) -> f64 {+ a.0.hypot(a.1)+}+fn norm(a: P) -> P {+ let l = len(a);+ if l > 1e-12 { (a.0 / l, a.1 / l) } else { (0.0, 0.0) }+}++/// Point `window` px of arc length away from `i` (forwards or backwards) on a closed loop.+fn walk(lp: &[P], i: usize, window: f64, fwd: bool) -> P {+ let n = lp.len();+ let mut acc = 0.0;+ let mut cur = i;+ for _ in 0..n {+ let nx = if fwd { (cur + 1) % n } else { (cur + n - 1) % n };+ let d = len(sub(lp[nx], lp[cur]));+ if acc + d >= window {+ let t = (window - acc) / d.max(1e-12);+ return add(lp[cur], mul(sub(lp[nx], lp[cur]), t));+ }+ acc += d;+ cur = nx;+ }+ lp[cur]+}++/// Indices of corner points.+fn corners(lp: &[P]) -> Vec<usize> {+ let n = lp.len();+ let window = 1.5;+ let cos_thresh = (60f64).to_radians().cos();+ let turn: Vec<f64> = (0..n)+ .map(|i| {+ let a = norm(sub(lp[i], walk(lp, i, window, false)));+ let b = norm(sub(walk(lp, i, window, true), lp[i]));+ dot(a, b)+ })+ .collect();+ let mut out = Vec::new();+ for i in 0..n {+ if turn[i] >= cos_thresh {+ continue;+ }+ // Local minimum of the cosine within ±window (ties: first index).+ let mut is_min = true;+ let mut acc = 0.0;+ let mut j = i;+ while acc < window {+ let nx = (j + 1) % n;+ acc += len(sub(lp[nx], lp[j]));+ j = nx;+ if j == i {+ break;+ }+ if turn[j] < turn[i] {+ is_min = false;+ break;+ }+ }+ acc = 0.0;+ j = i;+ while is_min && acc < window {+ let pv = (j + n - 1) % n;+ acc += len(sub(lp[j], lp[pv]));+ j = pv;+ if j == i {+ break;+ }+ if turn[j] <= turn[i] {+ is_min = false;+ }+ }+ if is_min {+ out.push(i);+ }+ }+ out+}++/// Fits a closed loop with cubic Béziers.+fn fit_closed(lp: &[P], tol: f64) -> Subpath {+ let n = lp.len();+ let cs = corners(lp);+ let mut segs: Vec<[P; 4]> = Vec::new();+ let mut corner_at_start: Vec<bool> = Vec::new();+ if cs.is_empty() {+ // Smooth loop: start at 0 with a shared tangent at the seam.+ let mut pts: Vec<P> = lp.to_vec();+ pts.push(lp[0]);+ let t = norm(sub(lp[1 % n], lp[n - 1]));+ let before = segs.len();+ fit_cubic(&pts, t, mul(t, -1.0), tol * tol, &mut segs, 0);+ corner_at_start.extend((before..segs.len()).map(|_| false));+ } else {+ for (k, &c) in cs.iter().enumerate() {+ let end = cs[(k + 1) % cs.len()];+ let mut pts = vec![lp[c]];+ let mut j = c;+ loop {+ j = (j + 1) % n;+ pts.push(lp[j]);+ if j == end {+ break;+ }+ }+ let m = pts.len();+ let t1 = norm(sub(pts[1.min(m - 1)], pts[0]));+ let t2 = norm(sub(pts[m.saturating_sub(2)], pts[m - 1]));+ let before = segs.len();+ fit_cubic(&pts, t1, t2, tol * tol, &mut segs, 0);+ corner_at_start.extend((before..segs.len()).enumerate().map(|(q, _)| q == 0));+ }+ }+ let mut knots: Vec<Knot> = Vec::with_capacity(segs.len());+ let pt = |p: P| Point::new(p.0, p.1);+ for (i, s) in segs.iter().enumerate() {+ knots.push(Knot { anchor: pt(s[0]), in_ctrl: pt(s[0]), out_ctrl: pt(s[1]), smooth: !corner_at_start[i] });+ }+ let m = segs.len();+ for i in 0..m {+ knots[(i + 1) % m].in_ctrl = pt(segs[i][2]);+ }+ Subpath { closed: true, knots, op: PathOp::Combine }+}++fn bezier(b: &[P; 4], t: f64) -> P {+ let mt = 1.0 - t;+ let (a, bb, c, d) = (mt * mt * mt, 3.0 * mt * mt * t, 3.0 * mt * t * t, t * t * t);+ (a * b[0].0 + bb * b[1].0 + c * b[2].0 + d * b[3].0, a * b[0].1 + bb * b[1].1 + c * b[2].1 + d * b[3].1)+}++fn bezier_d1(b: &[P; 4], t: f64) -> P {+ let mt = 1.0 - t;+ let q0 = mul(sub(b[1], b[0]), 3.0);+ let q1 = mul(sub(b[2], b[1]), 3.0);+ let q2 = mul(sub(b[3], b[2]), 3.0);+ add(add(mul(q0, mt * mt), mul(q1, 2.0 * mt * t)), mul(q2, t * t))+}++fn bezier_d2(b: &[P; 4], t: f64) -> P {+ let r0 = mul(add(sub(b[2], mul(b[1], 2.0)), b[0]), 6.0);+ let r1 = mul(add(sub(b[3], mul(b[2], 2.0)), b[1]), 6.0);+ add(mul(r0, 1.0 - t), mul(r1, t))+}++fn chord_params(pts: &[P]) -> Vec<f64> {+ let mut u = vec![0.0; pts.len()];+ for i in 1..pts.len() {+ u[i] = u[i - 1] + len(sub(pts[i], pts[i - 1]));+ }+ let total = u[pts.len() - 1];+ if total > 0.0 {+ for v in &mut u {+ *v /= total;+ }+ }+ u+}++/// Least-squares control points with fixed end tangents.+fn generate(pts: &[P], u: &[f64], t1: P, t2: P) -> [P; 4] {+ let (p0, p3) = (pts[0], pts[pts.len() - 1]);+ let mut c = [[0.0f64; 2]; 2];+ let mut x = [0.0f64; 2];+ for (i, &t) in u.iter().enumerate() {+ let mt = 1.0 - t;+ let b1 = 3.0 * mt * mt * t;+ let b2 = 3.0 * mt * t * t;+ let a1 = mul(t1, b1);+ let a2 = mul(t2, b2);+ c[0][0] += dot(a1, a1);+ c[0][1] += dot(a1, a2);+ c[1][1] += dot(a2, a2);+ let b0 = mt * mt * mt;+ let b3 = t * t * t;+ let tmp = sub(pts[i], add(mul(p0, b0 + b1), mul(p3, b2 + b3)));+ x[0] += dot(a1, tmp);+ x[1] += dot(a2, tmp);+ }+ c[1][0] = c[0][1];+ let det = c[0][0] * c[1][1] - c[1][0] * c[0][1];+ let det0 = c[0][0] * x[1] - c[1][0] * x[0];+ let det1 = x[0] * c[1][1] - x[1] * c[0][1];+ let (mut al, mut ar) = if det.abs() > 1e-12 { (det1 / det, det0 / det) } else { (0.0, 0.0) };+ let seg = len(sub(p3, p0));+ let eps = 1e-6 * seg;+ if al < eps || ar < eps {+ al = seg / 3.0;+ ar = seg / 3.0;+ }+ [p0, add(p0, mul(t1, al)), add(p3, mul(t2, ar)), p3]+}++fn max_error(pts: &[P], b: &[P; 4], u: &[f64]) -> (f64, usize) {+ let mut best = (0.0, pts.len() / 2);+ for i in 1..pts.len() - 1 {+ let d = sub(bezier(b, u[i]), pts[i]);+ let e = dot(d, d);+ if e >= best.0 {+ best = (e, i);+ }+ }+ best+}++fn reparam(pts: &[P], u: &[f64], b: &[P; 4]) -> Vec<f64> {+ pts.iter()+ .zip(u)+ .map(|(p, &t)| {+ let q = bezier(b, t);+ let d1 = bezier_d1(b, t);+ let d2 = bezier_d2(b, t);+ let num = dot(sub(q, *p), d1);+ let den = dot(d1, d1) + dot(sub(q, *p), d2);+ if den.abs() < 1e-12 { t } else { (t - num / den).clamp(0.0, 1.0) }+ })+ .collect()+}++fn fit_cubic(pts: &[P], t1: P, t2: P, err2: f64, out: &mut Vec<[P; 4]>, depth: u32) {+ let n = pts.len();+ if n == 2 || depth > 40 {+ let d = len(sub(pts[n - 1], pts[0])) / 3.0;+ out.push([pts[0], add(pts[0], mul(t1, d)), add(pts[n - 1], mul(t2, d)), pts[n - 1]]);+ return;+ }+ let mut u = chord_params(pts);+ let mut b = generate(pts, &u, t1, t2);+ let (mut e, mut split) = max_error(pts, &b, &u);+ if e < err2 {+ out.push(b);+ return;+ }+ if e < err2 * 16.0 {+ for _ in 0..6 {+ let u2 = reparam(pts, &u, &b);+ let b2 = generate(pts, &u2, t1, t2);+ let (e2, s2) = max_error(pts, &b2, &u2);+ u = u2;+ b = b2;+ e = e2;+ split = s2;+ if e < err2 {+ out.push(b);+ return;+ }+ }+ }+ let split = split.clamp(1, n - 2);+ let tc = norm(sub(pts[split - 1], pts[split + 1]));+ let tc = if len(tc) < 0.5 { norm(sub(pts[split - 1], pts[split])) } else { tc };+ fit_cubic(&pts[..=split], t1, tc, err2, out, depth + 1);+ fit_cubic(&pts[split..], mul(tc, -1.0), t2, err2, out, depth + 1);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn square_contour_orientation_and_count() {+ let (w, h) = (6, 5);+ let mut v = vec![0.0f32; w * h];+ for y in 1..4 {+ for x in 1..5 {+ v[y * w + x] = 1.0;+ }+ }+ let c = contours(&v, Rect::new(0, 0, w as i32, h as i32), 0.0);+ assert_eq!(c.len(), 1);+ // Inside on the left in y-down screen space = counter-clockwise = negative shoelace area.+ let a: f64 = (0..c[0].len()).map(|i| {+ let (p, q) = (c[0][i], c[0][(i + 1) % c[0].len()]);+ p.0 * q.1 - q.0 * p.1+ }).sum::<f64>() * 0.5;+ assert!(a < 0.0, "area {a}");+ let a = -a;+ // Pixels 1..5 x 1..4 → contour through their outer half-pixel boundary (4×3 area with+ // 45° chamfered corners: 12 − 4·0.125).+ assert!((a - 11.5).abs() < 1e-9, "area {a}");+ }++ #[test]+ fn traced_rect_has_corners() {+ let (w, h) = (40, 30);+ let mut v = vec![0.0f32; w * h];+ for y in 5..25 {+ for x in 5..35 {+ v[y * w + x] = 1.0;+ }+ }+ let p = trace_mask(&v, Rect::new(0, 0, w as i32, h as i32), 0.0, 1.0);+ assert_eq!(p.subpaths.len(), 1);+ let k = &p.subpaths[0].knots;+ assert!(k.len() >= 4 && k.len() <= 12, "{} knots", k.len());+ assert!(k.iter().filter(|k| !k.smooth).count() >= 4);+ }+}diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex d119ec325..3f8305adf 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -13,18 +13,20 @@ Each reply is one JSON line with the same `id`:{"id": 2, "ok": false, "error": "unknown tool `foo`"}```-The transport is `apps/photocraft/src/control_server.rs`, and the handlers are in `crates/ui-egui/src/control.rs`. An MCP server will wrap this same protocol (milestone M11).+The transport is `apps/photocraft/src/control_server.rs`, and the handlers are in `crates/ui-egui/src/control.rs`. The MCP server (`photocraft-cli mcp --bridge 127.0.0.1:<port>`, crate `photocraft-automation`) wraps this same protocol. See [MCP bridge](#mcp-bridge) below.## Methods- `engine.execute {command, params}`: run any engine or UI command by id- `engine.commands`: list commands with enablement- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, menu tree, window size)-- `ui.set {tool?, panels?, zoom?, center?, dark?}`: change UI state+- `ui.set {tool?, panels?, dockTabs?, maskTarget?, zoom?, center?, dark?}`: change UI state- `ui.menu.invoke {id}` / `ui.menu.list`: activate a menu item by id; list the menu tree- `ui.dialog.open {kind, fields?}` / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`- `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?}], modifiers?}`: drive the active tool in document coordinates+- `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`+- `ui.type {text}`: type text (goes to the focused widget, or to the canvas while the Type tool is editing)- `ui.resize {width, height}`: resize the main window- `ui.screenshot {path?, focus?}`: capture the main window (PNG). Raises the window first (default)because occluded macOS windows stop rendering@@ -48,3 +50,34 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i| `document.pixel` | `{"x":10,"y":10}`: composite RGBA |UI-level commands (`file.open`, `file.save`, `view.zoomIn`, `window.theme.pro`, `edit.search`, …) are also accepted by `engine.execute` and `ui.menu.invoke`.++## MCP bridge++`photocraft-automation` provides an MCP server built on the official Rust SDK (`rmcp`). It runs in one of two modes:++- **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window.+- **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878`): every tool is forwarded to a running `photocraft --control 7878` over this protocol, so agents see and drive the live app.++The bridge keeps one TCP connection open. It reconnects once if a request fails, and it skips reply lines whose `id` doesn't match the request (for example, stale replies to requests that timed out). It only accepts loopback addresses, because the app only listens on loopback.++How each MCP tool maps onto control methods in bridge mode:++| MCP tool | Control method |+|---|---|+| `command_run {id, params}` | `engine.execute {command: id, params}` |+| `command_list {filter?, enabled_only?}` | `engine.commands` (filtered by the MCP server) |+| `doc_new {…}` | `engine.execute {command: "file.new", params}` |+| `doc_inspect` | `engine.execute {command: "document.inspect"}` |+| `doc_open {path}` | `app.open {path}` |+| `doc_save {path}` / `doc_export {path}` | `app.save {path}` |+| `doc_render_preview {max_side?}` | `ui.screenshot {path: <temp>}`, returned as PNG image content |+| `session_list`, `ui_inspect` | `ui.inspect` |+| `ui_screenshot {max_side?}` | `ui.screenshot`, returned as PNG image content |+| `ui_pointer {events, modifiers?}` | `ui.pointer` |+| `ui_menu_invoke {id}` | `ui.menu.invoke` |+| `ui_set {fields}` | `ui.set` |+| `control_call {method, params}` | any method, passed through unchanged |++`doc_select` and `doc_close` work only in headless mode. The `ui_*` tools and `control_call` work only in bridge mode; in headless mode they return a tool error that explains how to start bridge mode.++**Security note:** the control port has no authentication. Any local process can drive the app. Only enable `--control` when you need it. A token handshake is planned (architecture §12).diff --git a/docs/development.md b/docs/development.mdindex d427f80ce..709391743 100644--- a/docs/development.md+++ b/docs/development.md@@ -49,6 +49,78 @@ See `docs/control-protocol.md` for every method. Tips:- **Capture only our own window.** For native captures (to see the real title bar and traffic lights), capture by window id (`screencapture -l <CGWindowID>`), never a screen region, which can grab other apps.- **Pointer gestures:** `ui.pointer` takes events in *document* coordinates and runs them through the same tool state machine as the mouse.+## Headless CLI++`apps/photocraft-cli` builds the binary `photocraft-cli`:++```sh+cargo run -p photocraft-cli -- convert in.psd out.pcraft # any supported format -> any+cargo run -p photocraft-cli -- info out.pcraft # JSON: size, mode, depth, layer tree+cargo run -p photocraft-cli -- run in.png --cmd layer.new.layer --params '{"name":"Ink"}' \+ --cmd filter.blur.gaussian --params '{"radius":3}' --out out.psd+cargo run -p photocraft-cli -- run --new '{"width":800,"height":600}' --cmd document.inspect+cargo run -p photocraft-cli -- batch --actions actions.json --in photos/ --out done/ --format jpg+cargo run -p photocraft-cli -- commands --filter blur # the command registry+```++`actions.json` is `[{"command": "<id>", "params": {…}}, …]`, which is the same shape as a recorded action. `run` prints one JSON line per command result.++## Native format (.pcraft)++`crates/format` defines the lossless native bundle. It is either a ZIP of STORE entries or a directory with the same layout:++- `manifest.json`: the versioned document tree, with migrations in `format/src/migrate.rs`.+- `tiles/<blake3>.zst` and `blobs/<blake3>.zst`: zstd-compressed objects, content-addressed by the BLAKE3 hash of their uncompressed bytes.+- `thumb.png` and `composite/preview.png`: previews.++Keep one `PcraftWriter` per open document: re-saving then only compresses and writes tiles that changed, and directory bundles garbage-collect unreferenced objects. `format::Autosaver` writes snapshots into a recovery directory on a background thread. `list_recovery` / `recover` / `discard_recovery` implement crash recovery.++`photocraft-io` routes `.pcraft` through this crate in `import`/`export`, detecting it by magic or by extension.++## MCP (agents)++`photocraft-cli mcp` serves MCP on stdio using `crates/automation`, which is built on `rmcp`:++- **Headless:** `photocraft-cli mcp`. It drives an in-process engine session.+- **Live app:** start `photocraft --control 7878`, then run `photocraft-cli mcp --bridge 127.0.0.1:7878`. See `docs/control-protocol.md#mcp-bridge`.++Tools:++- `session_list`+- `doc_open`, `doc_new`, `doc_save`, `doc_export`, `doc_inspect`, `doc_render_preview` (returns a PNG image), `doc_select`, `doc_close`+- `command_list`, `command_run`+- bridge only: `ui_inspect`, `ui_screenshot`, `ui_pointer`, `ui_menu_invoke`, `ui_set`, `control_call`++Claude Code (`.mcp.json` in the repo root, or `claude mcp add`):++```json+{+ "mcpServers": {+ "photocraft": {+ "command": "/path/to/photocraft/target/release/photocraft-cli",+ "args": ["mcp"]+ },+ "photocraft-live": {+ "command": "/path/to/photocraft/target/release/photocraft-cli",+ "args": ["mcp", "--bridge", "127.0.0.1:7878"]+ }+ }+}+```++```sh+cargo build --release -p photocraft-cli+claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp+```++A typical agent loop:++1. `doc_open {path}`+2. `command_list {filter:"blur"}`+3. `command_run {id:"filter.blur.gaussian", params:{radius:4}}`+4. `doc_render_preview` to check the result+5. `doc_save {path:"out.pcraft"}`+## Testing strategy- **Unit and property tests** in every crate. proptest is used for tile COW, regions and codecs.@@ -90,3 +162,20 @@ How the web shell (`apps/photocraft-web/src/web.rs`) differs from desktop:- **Drag-and-drop:** `WebShell` takes the frame's `dropped_files` before the app sees them. It reads each file with `DroppedFile::bytes_async` and pushes the bytes into the inbox.- **No control server:** browsers can't listen on TCP. To automate the web build, drive headless Chrome with `--remote-debugging-port`. `Page.setInterceptFileChooserDialog` plus `DOM.setFileInputFiles` covers Open, `Input.dispatchDragEvent` with `files` covers drops, and `Browser.setDownloadBehavior` captures downloads.- Headless Chrome on macOS (`--headless=new --enable-unsafe-webgpu`) gets a real WebGPU adapter.+++## Offscreen UI snapshots (no window)++Render the full UI headlessly with the real wgpu canvas, e.g. for design reviews or when the app+window would be occluded (macOS doesn't render occluded windows, so live `ui.screenshot` must raise+the window and steal focus):++```sh+cargo run --release -p photocraft-ui-egui --example snapshot -- \+ --out ui.png --size 1440x900 --scale 2 --open photo.jpg \+ --script '[["ui.set", {"tool": "type"}], ["ui.menu.invoke", {"id": "image.canvasSize"}]]'+```++`--script` is a list of control-protocol calls (`[method, params]`), applied in order.+Input calls (`ui.key`, `ui.type`, `ui.click`) now reply only after the app has processed the events,+so a following `ui.inspect` observes their effect.diff --git a/docs/ui-design.md b/docs/ui-design.mdindex 878db7f79..7e69a01d3 100644--- a/docs/ui-design.md+++ b/docs/ui-design.md@@ -23,3 +23,33 @@ Switch themes with the sun icon, Window → Theme, or `ui.set {"theme":"classic"- Document tabs read "name @ 12.5% (RGB/8)".- Toolbar tool groups carry a corner triangle.- **Verify every visual change** with `ui.screenshot`, at several window sizes and in every theme.++## Adding icons++```sh+curl -sfL -o assets/icons/<name>.svg https://raw.githubusercontent.com/lucide-icons/lucide/main/icons/<name>.svg+# regenerate the embedded table+{ printf '%s\n' '//! Lucide icons (ISC licence), embedded and tinted at runtime.' '' 'pub static ICONS: &[(&str, &[u8])] = &['; \+ for f in assets/icons/*.svg; do n=$(basename $f .svg); echo " (\"$n\", include_bytes!(\"../../../assets/icons/$n.svg\")),"; done; echo '];'; } \+ > crates/ui-egui/src/icon_data.rs+```++## Interaction models (match Photoshop CC)++| Feature | Module | Behaviour |+|---|---|---|+| Type tool | `type_tool.rs` | Click: point text with the placeholder "Lorem Ipsum" selected. Drag: paragraph box. Inline caret and selection drawn from the text engine layout. ⌥/⌘ word and line navigation, ↩ newline, ⌘↩ or Esc commits, a click outside commits. One history step per session (`coalesce`). A new layer is named after its text; an empty one is deleted. |+| Free Transform | `transform_tool.rs` | ⌘T. Corners scale proportionally (⇧ frees them); edges scale one axis; ⌥ scales about the reference point; ⌘-corner distorts; dragging outside rotates (⇧ snaps to 15°); dragging inside moves. Preview = document without the moving pixels + a textured 24×24 mesh. ↩ or a double-click commits via `edit.transform {rect, quad}`. |+| Layer masks | `panels.rs` | Clicking the mask thumbnail targets the mask (corner-bracket frame; the tab reads "Layer, Layer Mask/8"). Brush, eraser (paints background colour), gradient and bucket then send `"target": "mask"`. Adjustment and fill layers target their mask automatically. |+| Levels / Curves | `tone.rs` | Histogram of the image *below* the adjustment. Curves: click to add a point, drag out to delete. Every change is a coalesced `layer.setAdjustment`, so one drag = one undo step and the canvas updates at full resolution on the GPU. |++Where the font lacks a symbol (e.g. ∠ ↦ ▔), draw it with the painter or use a Lucide icon; never ship+missing-glyph boxes. Check every new panel with the offscreen snapshot tool (`docs/development.md`).++## Menus++`menu_catalog.rs` holds Photoshop's menu tree (standard command names, order, separators, default shortcuts). Items whose id matches an engine or UI command are live; others render disabled until implemented. Give new commands the catalogue's id (for example `image.imageSize`) and they light up in the right place automatically.++## Automation for visual checks++Use `ui.click {x,y}`, `ui.move`, `ui.key` and `ui.type` (synthetic input in screen points) to open menus, popups and context menus, then `ui.screenshot`.diff --git a/xtask/src/layers.rs b/xtask/src/layers.rsindex 1ca7c9294..753707507 100644--- a/xtask/src/layers.rs+++ b/xtask/src/layers.rs@@ -67,8 +67,9 @@ pub const TABLE: &[(&str, Class)] = &[/// Explicit orderings *within* a layer (earlier may be used by later)./// The L0 foundation is a small chain: `raster` builds on `color` and-/// `geom`, which the §3 diagram draws on one line.-pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["geom", "color", "raster"]];+/// `geom`, which the §3 diagram draws on one line. The GPU backend (`gpu`)+/// reuses the CPU reference (`compose`) for LUTs and parity tests.+pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["geom", "color", "raster"], &["compose", "gpu"]];fn intra_layer_allowed(from: &str, to: &str) -> bool {let (from, to) = (short_name(from), short_name(to));