Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

more algorithms, progress

Brandon Thomas536a7346fbd6
diff --git a/AGENTS.md b/AGENTS.md
index 0735bdf8b..2df9f74e7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,6 +1,6 @@
# AGENTS.md: guide for AI agents and contributors
-Photocraft is an open-source, native, Photoshop-comparable image editor written in **Rust only** (no JavaScript or TypeScript). Read this file first, then `docs/`.
+Photocraft is an open-source, native, Photoshop-comparable image editor written in **Rust only** (no JavaScript or TypeScript). The goal is 1:1 Photoshop parity (same menus, shortcuts, behaviour and file fidelity) with better performance, and every feature drivable by agents. Read this file first, then `docs/`.
## 1. Orientation (5 minutes)
@@ -8,19 +8,21 @@ Photocraft is an open-source, native, Photoshop-comparable image editor written
|---|---|
| `docs/architecture.md` | Crate map, dependency layers, the engine/UI seam, document model |
| `docs/development.md` | Build, test, run, drive the app programmatically, debug tricks |
-| `docs/contributing.md` | Rules: clean-room, tests, layering, style, commits |
+| `docs/contributing.md` | Rules: clean-room, tests, layering, style, commits; the "add a command" checklist |
| `docs/control-protocol.md` | JSON control channel: how agents drive and screenshot the running app |
| `docs/ui-design.md` | Design tokens, themes, widgets, and how to match Photoshop's look |
+| `docs/roadmap.md` | Milestones and the **current focus** |
+| `docs/parity.md` | Generated list of every Photoshop menu item, live or missing |
| `crates/<name>/README.md` (where present) | Public API of that crate |
## 2. Workspace map
```text
crates/
- geom color raster L0 foundation (runtime pixel formats, COW tiles, blend math)
+ geom cms color raster L0 foundation (geometry, ICC colour management, pixel formats + blend math, COW tiles)
psd codecs L0 standalone format crates (no workspace deps; publishable)
- doc L1 document model (layers, masks, adjustments, effects: pure data)
- ops paint algo text L2 history, brush engine, imaging algorithms, text engine
+ doc L1 document model (layers, masks, adjustments, effects, smart objects: pure data)
+ ops paint algo text vector L2 history, brush engine, imaging algorithms, type engine, paths/shapes
compose gpu format L3 CPU compositor (the oracle), wgpu compositor, .pcraft native format
io L4 document <-> PSD / flat formats
engine L5 Session + command registry (every action is a command)
@@ -29,40 +31,63 @@ crates/
apps/
photocraft desktop app (eframe/wgpu), TCP control server
photocraft-cli headless CLI (convert/info/run/batch/commands/mcp)
-xtask/ cargo xtask layers | wasm | ci | stats | corpus
+ photocraft-web the same app in the browser (trunk + wasm-bindgen)
+xtask/ cargo xtask layers | wasm | ci | stats | corpus | parity
```
-**Layering is enforced** by `cargo xtask layers`. A crate may depend only on lower layers. `psd` and `codecs` depend on nothing in the workspace. Nothing below `ui-egui` may use egui, eframe, winit or rfd.
+**Layering is enforced** by `cargo xtask layers`. A crate may depend only on lower layers. `psd`, `codecs` and `cms` depend on nothing in the workspace. Nothing below `ui-egui` may use egui, eframe, winit or rfd. A new crate must be registered in `xtask/src/layers.rs`.
## 3. Golden rules
-1. **Everything is a command.** New user-visible behaviour = a command in `crates/engine/src/commands.rs` (id, label, menu path, shortcut, params doc, `enabled`, `run`) plus tests in `crates/engine/src/tests.rs`. The UI, CLI, control channel and future MCP all dispatch commands by id.
-2. **No format or colour assumptions.** Bit depth (8/16/32f) and colour model (RGB/Gray/CMYK/Lab…) are runtime data. Never introduce a `u8`-only pixel path in public APIs. Test at several depths.
-3. **Clean-room.** We studied Photon Studio (proprietary) and Photoshop for *behaviour and look only*. Never copy their code, shaders or assets. Implement from public specs (Adobe PSD spec, ISO 32000 blend modes, papers) and observation. Third-party assets must be permissively licensed and recorded (see `assets/`).
-4. **Tests are the gate.** Every change comes with tests. Format crates use round-trip, synthetic-generator, oracle and fuzz tests. Keep the real-file PSD corpus results from regressing.
+1. **Everything is a command.** New user-visible behaviour = a command in the engine (`crates/engine/src/*_cmds.rs`, registered in `commands.rs`) with id, label, menu path, shortcut, params doc, `enabled` and `run`, plus tests. The UI, CLI, control channel and MCP all dispatch commands by id. Use the **exact id from `crates/ui-egui/src/menu_catalog.rs`** and the menu item goes live automatically. Only pure view/window state (zoom, panels, screen mode) belongs to the shell (`menus.rs` `UI_COMMANDS`).
+2. **No format or colour assumptions.** Bit depth (8/16/32f) and colour model (RGB/Gray/CMYK/Lab…) are runtime data. Never introduce a `u8`-only pixel path in public APIs. Never assume sRGB: colour conversions go through `photocraft-cms` (`Transform`, `transform::cached`). Test at several depths.
+3. **Clean-room.** We studied Photon Studio (proprietary) and Photoshop for *behaviour and look only*. Never copy their code, shaders, profiles or assets. Implement from public specs (Adobe PSD spec, ICC, ISO 32000 blend modes, papers) and observation. Third-party assets must be permissively licensed and recorded (see `assets/`, `docs/images/SOURCES.md`).
+4. **Tests are the gate.** Every change comes with tests. Format crates use round-trip, synthetic-generator, oracle and fuzz tests. Keep the PSD corpus results and the parity floor (`crates/ui-egui/src/parity.rs`) from regressing.
5. **The UI is thin and data-driven.** UI state lives in `ui-egui/src/state.rs` (serde), so the control channel can read and drive it. Colours and radii come from `theme::Tokens`, never hard-coded.
-6. **Verify UI changes visually.** Launch the app with `--control`, drive it, take `ui.screenshot`, and look at the PNG. See `docs/development.md`.
-7. **Never break wasm.** L0–L6 must `cargo check --target wasm32-unknown-unknown` (run `cargo xtask wasm`).
+6. **Verify UI changes visually.** Render offscreen with `cargo run -p photocraft-ui-egui --example snapshot` (no window, no focus stealing), or launch with `--control` and take `ui.screenshot`. Look at the PNG. Demo images must be public-domain art, never personal photos. When fetching assets, never put a person's name, email or other personal details in requests (User-Agent, headers, URLs); use a generic `Photocraft-dev` User-Agent.
+7. **Never break wasm.** L0–L6 must `cargo check --target wasm32-unknown-unknown` (run `cargo xtask wasm`). File-system code is `cfg(not(target_arch = "wasm32"))` or goes through the platform services.
+8. **Performance is a feature.** Benchmark heavy operations on a 24–36 MP image in release. Work per tile in parallel (rayon), skip empty tiles, never scan a full surface per frame (cache per revision), and record before/after timings in the dev log.
-## 4. Before you finish a task
+## 4. Picking work
+
+Priorities: important infrastructure first, then low-hanging parity, then the long tail.
+
+1. `docs/roadmap.md` → **Current focus**.
+2. `cargo xtask parity` → `docs/parity.md` lists every missing menu item, grouped by menu. Low-hanging fruit is usually a missing command whose algorithm already exists in `algo`, `paint`, `vector` or `text`.
+3. `log/devlog.md` → the "Still open" bullets of recent entries.
+
+When parity rises, raise `FLOOR` in `crates/ui-egui/src/parity.rs` (never lower it).
+
+## 5. Before you finish a task
```sh
cargo test -p <crates you touched>
cargo clippy -p <crates> --all-targets -- -D warnings
cargo xtask layers
cargo xtask wasm # if you touched L0–L6
+cargo xtask parity # if you added commands; commit the regenerated docs/parity.md
```
-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.
+Then append a terse entry to `log/devlog.md` (what landed, numbers, what's still open). Sessions can end abruptly (crashes, context limits), so the dev log plus a green tree is how the next agent picks up. Keep the tree building at every step.
+
+## 6. Parallel agents
+
+- Use your own target dir (`CARGO_TARGET_DIR=target/agent-<name>`) to avoid the Cargo build lock, and edit only the files you own. Shared files (`engine/src/lib.rs`, the `v.extend(...)` list in `engine/src/commands.rs`, `ui-egui/src/menus.rs`, `state.rs`) get small, surgical edits; re-read before editing.
+- Put new commands in a **new module** (`engine/src/<area>_cmds.rs` with a `specs()` function) rather than growing a shared file.
+- If someone else's in-progress edit breaks the build, wait and retry; don't fix their files.
+- 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.
+- Disk space: each target dir is about 10 GB. Delete `target/agent-*` dirs of finished agents.
-## 5. Where things are tracked
+## 7. Where things are tracked
+- `docs/roadmap.md`: milestones M0–M12, status and the current focus.
+- `docs/parity.md`: generated Photoshop menu coverage.
- `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
+## 8. 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.
+If the field has a PSD equivalent, map it in `crates/io` too, and keep unknown PSD blocks verbatim.
diff --git a/Cargo.lock b/Cargo.lock
index df43933eb..1c97a7844 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3246,6 +3246,7 @@ dependencies = [
"photocraft-compose",
"photocraft-doc",
"photocraft-engine",
+ "photocraft-format",
"photocraft-geom",
"photocraft-io",
"photocraft-raster",
@@ -3329,6 +3330,7 @@ dependencies = [
name = "photocraft-color"
version = "0.1.0"
dependencies = [
+ "photocraft-cms",
"serde",
]
@@ -3362,11 +3364,15 @@ dependencies = [
name = "photocraft-engine"
version = "0.1.0"
dependencies = [
+ "blake3",
"photocraft-algo",
+ "photocraft-cms",
"photocraft-color",
"photocraft-compose",
"photocraft-doc",
+ "photocraft-format",
"photocraft-geom",
+ "photocraft-io",
"photocraft-ops",
"photocraft-paint",
"photocraft-raster",
@@ -3420,6 +3426,7 @@ dependencies = [
name = "photocraft-io"
version = "0.1.0"
dependencies = [
+ "photocraft-cms",
"photocraft-codecs",
"photocraft-color",
"photocraft-compose",
@@ -3449,6 +3456,7 @@ dependencies = [
"photocraft-geom",
"photocraft-raster",
"serde",
+ "serde_json",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 6275592e6..888d9071f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,6 +13,7 @@ rust-version = "1.90"
# internal
photocraft-geom = { path = "crates/geom" }
photocraft-color = { path = "crates/color" }
+photocraft-cms = { path = "crates/cms" }
photocraft-raster = { path = "crates/raster" }
photocraft-doc = { path = "crates/doc" }
photocraft-ops = { path = "crates/ops" }
diff --git a/README.md b/README.md
index 8189dc279..72ad0a7ca 100644
--- a/README.md
+++ b/README.md
@@ -1,26 +1,241 @@
-photocraft
-===========
+<h1 align="center">📷 Photocraft</h1>
-By the artcraft team
+<p align="center">
+ <b>The image editor you already know how to use.</b><br>
+ Layers, masks, adjustment layers, layer styles, type, vectors, brushes and real PSD files,<br>
+ in a native app written entirely in Rust. Open source, offline, and yours.
+</p>
+
+<p align="center">
+ <img alt="100% Rust" src="https://img.shields.io/badge/100%25-Rust-b7410e?style=flat-square&logo=rust">
+ <img alt="macOS · Windows · Linux · Web" src="https://img.shields.io/badge/macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20Web-native-2b6cb0?style=flat-square">
+ <img alt="License: MIT or Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-3a3a3a?style=flat-square">
+ <img alt="Status: early alpha" src="https://img.shields.io/badge/status-early%20alpha-d69e2e?style=flat-square">
+</p>
-An open-source, native image editor written in Rust, aiming for Photoshop-level capability and ergonomics.
+<p align="center">
+ <a href="#features">Features</a> ·
+ <a href="#everything-in-the-box">Everything in the box</a> ·
+ <a href="#psd-without-compromise">PSD</a> ·
+ <a href="#built-for-agents">Agents</a> ·
+ <a href="#get-started">Get started</a> ·
+ <a href="#crafting-apps">Crafting Apps</a>
+</p>
<p align="center">
<img src="docs/images/photocraft-demo.jpg" alt="Photocraft editing Hokusai's The Great Wave: a caption card with a drop shadow, type layers, Vibrance and Curves adjustment layers, and the Curves editor with its histogram" width="100%">
<br>
- <sub>Artwork: <i>The Great Wave off Kanagawa</i>, Katsushika Hokusai, c. 1831 (public domain, via Wikimedia Commons).</sub>
+ <sub><i>The Great Wave off Kanagawa</i>, Katsushika Hokusai, c. 1831</sub>
</p>
-- **Native and portable:** egui on wgpu (Metal/Vulkan/DX12/WebGPU), for macOS, Windows, Linux and the web. Mobile shells come later.
-- **Photoshop-grade formats:** a standalone PSD/PSB crate (byte-exact round trips on a real-file corpus), plus 13 raster formats with symmetric read/write at 8/16/32-bit.
-- **Engine first:** every action is a command, so the UI, CLI and automation (a JSON control channel and an MCP server) all drive the same core.
+<br>
+
+<table>
+ <tr>
+ <td width="25%" valign="top">
+ <h3>🎛️ Familiar by design</h3>
+ The menus, shortcuts, panels and tools are where your hands expect them, from ⌘J to ⇧⌘D. If you know Photoshop, you already know Photocraft.
+ </td>
+ <td width="25%" valign="top">
+ <h3>⚡ Native and fast</h3>
+ A GPU compositor on wgpu (Metal, Vulkan, DX12, WebGPU), copy-on-write tiles and multithreaded filters. No Electron, no web view, no waiting.
+ </td>
+ <td width="25%" valign="top">
+ <h3>🗂️ Real PSD files</h3>
+ Open, edit and save layered Photoshop documents. 134 of 135 real-world PSDs round-trip byte for byte.
+ </td>
+ <td width="25%" valign="top">
+ <h3>🤖 Agent-ready</h3>
+ Every action is a command, so you can drive the same engine from the UI, the CLI, a JSON control channel or an MCP server.
+ </td>
+ </tr>
+</table>
+
+<br>
+
+## Features
+
+<table>
+ <tr>
+ <td width="58%"><img src="docs/images/photocraft-adjustments.jpg" alt="Vibrance and Levels adjustment layers with the Histogram panel" width="100%"></td>
+ <td width="42%" valign="middle">
+ <h3>Edit without regret.</h3>
+ Adjustment layers keep every edit live. Stack Levels, Curves, Vibrance, Hue/Saturation and a dozen more, mask them to an area, reorder them, or turn them off, and your original pixels never change.
+ <br><br>
+ <b>16 adjustment layers</b> that also apply directly to pixels, including Curves with per-channel editing, Levels with a live histogram, Black &amp; White, Channel Mixer, Gradient Map, Photo Filter, Selective Color and Color Lookup (.cube, .3dl, .look). Plus Shadows/Highlights, Replace Color, Match Color, HDR Toning, Desaturate and Equalize.
+ <br><br>
+ <sub><i>Impression, Sunrise</i>, Claude Monet, 1872</sub>
+ </td>
+ </tr>
+ <tr>
+ <td width="42%" valign="middle">
+ <h3>Styles that sell the shot.</h3>
+ Drop Shadow, Inner Shadow, Outer and Inner Glow, Bevel &amp; Emboss, Satin, Stroke, and Color, Gradient and Pattern Overlay, live on any layer, including type. Patterns come from a library (built-ins, Edit › Define Pattern, <code>.pat</code> import/export) and PSD <code>Patt</code> blocks.
+ <br><br>
+ Copy and paste styles between layers, hide all effects at once, and open styles straight from your PSDs, rendered to match Photoshop.
+ <br><br>
+ <sub><i>Earthrise</i>, William Anders / NASA, 1968</sub>
+ </td>
+ <td width="58%"><img src="docs/images/photocraft-layer-styles.jpg" alt="Outer Glow and Stroke on live type, in the Layer Style dialog" width="100%"></td>
+ </tr>
+ <tr>
+ <td width="58%"><img src="docs/images/photocraft-masks.jpg" alt="A feathered elliptical selection used as the mask of a Hue/Saturation layer" width="100%"></td>
+ <td width="42%" valign="middle">
+ <h3>Selections that understand your image.</h3>
+ Marquees, lassos and the Magic Wand for precision; Quick Selection, Object Selection and Select Subject when you want the computer to do the tracing; Select and Mask to refine hair-fine edges.
+ <br><br>
+ Feather, expand, contract, smooth, grow, reselect. Turn any selection into a layer mask, a vector path or a shape. Smart selection runs on your machine, with no cloud and no account.
+ <br><br>
+ <sub><i>Girl with a Pearl Earring</i>, Johannes Vermeer, c. 1665</sub>
+ </td>
+ </tr>
+ <tr>
+ <td width="42%" valign="middle">
+ <h3>Type that sets beautifully.</h3>
+ Point and paragraph text, edited right on the canvas, with full Character and Paragraph controls: font, weight, size, leading, tracking, alignment and colour.
+ <br><br>
+ Type layers stay editable, take layer styles, and round-trip through PSD.
+ <br><br>
+ <sub><i>Among the Sierra Nevada, California</i>, Albert Bierstadt, 1868</sub>
+ </td>
+ <td width="58%"><img src="docs/images/photocraft-type.jpg" alt="Point and paragraph type edited inline" width="100%"></td>
+ </tr>
+ <tr>
+ <td width="58%"><img src="docs/images/photocraft-vector.jpg" alt="Shape layers with gradient fills and dashed strokes" width="100%"></td>
+ <td width="42%" valign="middle">
+ <h3>Pixel-perfect vectors.</h3>
+ Rectangle, Ellipse, Triangle, Polygon, Line and the Pen tool, with resolution-independent shape layers, gradient fills, and dashed, aligned strokes.
+ <br><br>
+ Combine shapes (unite, subtract, intersect, exclude), keep paths in the Paths panel, use them as vector masks, or stroke and fill them. 116 of 116 shape layers in our PSD corpus match Photoshop's pixels.
+ <br><br>
+ <sub><i>Water Lilies</i>, Claude Monet, 1906</sub>
+ </td>
+ </tr>
+ <tr>
+ <td width="42%" valign="middle">
+ <h3>See it before you commit.</h3>
+ Every filter dialog previews live on the canvas, through your selection. Blurs (Gaussian, Box, Motion, Radial, Surface, Smart, Lens, Shape, and the Blur Gallery: Tilt-Shift, Iris, Field, Spin, Path), sharpening, Reduce Noise, distortions (Twirl, Wave, Ripple, Displace, Shear, Zig Zag…), Pixelate, Stylize (Oil Paint, Wind, Extrude…), Render (Clouds, Fibers, Lens Flare, Lighting Effects) and more.
+ <br><br>
+ Run filters on a smart object and they stay editable: change, hide, reorder or mask them at any time.
+ <br><br>
+ Large-radius blurs use running-sum box passes across all cores: a radius-180 Gaussian on 3.6 MP takes under a second.
+ <br><br>
+ <sub><i>The Starry Night</i>, Vincent van Gogh, 1889</sub>
+ </td>
+ <td width="58%"><img src="docs/images/photocraft-filters.jpg" alt="The Twirl filter previewed live on the canvas" width="100%"></td>
+ </tr>
+ <tr>
+ <td width="58%"><img src="docs/images/photocraft-transform.jpg" alt="Free Transform handles and the History panel" width="100%"></td>
+ <td width="42%" valign="middle">
+ <h3>Shape it any way you like.</h3>
+ Free Transform with scale, rotate, skew, distort and perspective; exact 90° and 180° rotations and flips; Transform Again. Layers, type, shapes, masks and selections all transform together.
+ <br><br>
+ Full history, Toggle Last State and the History Brush mean every step can be undone, even one brush stroke at a time.
+ <br><br>
+ <sub><i>The Tetons and the Snake River</i>, Ansel Adams, 1942</sub>
+ </td>
+ </tr>
+ <tr>
+ <td width="42%" valign="middle">
+ <h3>Ship it anywhere.</h3>
+ Export As with format, quality, transparency and scale, plus a preview and an instant file-size estimate. Quick Export to PNG in one click.
+ <br><br>
+ Choose a dark Pro theme, the airy Studio themes, or a Classic look.
+ <br><br>
+ <sub><i>The Kiss</i>, Gustav Klimt, 1907–1908</sub>
+ </td>
+ <td width="58%"><img src="docs/images/photocraft-export-light.jpg" alt="Export As in the light theme" width="100%"></td>
+ </tr>
+</table>
+
+<br>
+
+## Everything in the box
+
+<table>
+ <tr>
+ <td width="33%" valign="top">
+ <h4>🧰 34 tools</h4>
+ Move · Rectangular and Elliptical Marquee · Lasso · Polygonal Lasso · Magic Wand · Quick Selection · Object Selection · Crop · Eyedropper · Brush · Pencil · Mixer Brush · Color Replacement · Eraser · Clone Stamp · Healing Brush · Spot Healing · History Brush · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Path Selection · Type · five Shape tools · Hand · Zoom
+ </td>
+ <td width="33%" valign="top">
+ <h4>🖌️ A real brush engine</h4>
+ Shape Dynamics, Scattering, Texture, Dual Brush, Color Dynamics, Transfer, Brush Pose, Wet Edges, Build-up and Smoothing (including Pulled String), driven by pen pressure, tilt, rotation and direction. Brush presets, Define Brush from Selection, and deterministic, replayable strokes.
+ </td>
+ <td width="33%" valign="top">
+ <h4>🗃️ Layers, done properly</h4>
+ Groups, clipping masks, pixel and vector masks, fill layers (solid, gradient and pattern), adjustment layers, live smart objects with smart filters and lossless transforms and warps, multi-layer selection with align, distribute and link, alpha channels and Quick Mask, 27 blend modes, opacity and fill, locks, colour labels, layer filters, merge, flatten, rasterize, Layer via Copy/Cut, Paste Into.
+ </td>
+ </tr>
+ <tr>
+ <td width="33%" valign="top">
+ <h4>🎨 Any colour, any depth</h4>
+ RGB, Grayscale, CMYK and Lab documents at 8, 16 and 32 bits per channel. Bit depth and colour model are runtime data, so every tool works at every depth.
+ <br><br>
+ Real ICC colour management in pure Rust: embedded profiles, Assign and Convert to Profile with all four rendering intents and black point compensation, soft proofing (⌘Y) and Gamut Warning (⇧⌘Y) on the GPU.
+ </td>
+ <td width="33%" valign="top">
+ <h4>🗂️ Formats</h4>
+ PSD and PSB, plus PNG, JPEG, TIFF, WebP, GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and AVIF, with symmetric read and write at 8, 16 and 32 bits, and the native <code>.pcraft</code> format.
+ </td>
+ <td width="33%" valign="top">
+ <h4>🪄 The everyday essentials</h4>
+ Auto Tone, Contrast and Color · Equalize · Image and Canvas Size · Crop and Trim · Reveal All · Edit › Fill and Stroke · Copy Merged · Paste in Place · guides, rulers, grid and snapping · Actions record and replay · a command palette (⌘K).
+ </td>
+ </tr>
+</table>
+
+<br>
+
+## PSD without compromise
+
+Photocraft's PSD support is a standalone crate written from Adobe's public specification and tested against a corpus of real-world files.
+
+- **Byte-exact round trips:** 134 of 135 corpus files are written back identical, and anything we don't model yet (raw blocks, descriptors, extras) is preserved verbatim instead of being dropped.
+- **Pixels that match:** a composite oracle compares our render with Photoshop's own merged image, covering gradient interpolation (Classic, Perceptual and Linear), layer effects, shape strokes, clipping and fill opacity.
+- **Large documents:** PSB, 16 and 32-bit files, and CMYK and Lab documents open natively.
+
+## Built for agents
+
+Every menu item, tool and dialog runs a command from one registry of 500+ commands. The UI, the CLI, the JSON control channel and the MCP server all call the same commands, so anything you can click, a script or an AI agent can do too.
```sh
-cargo run --release -p photocraft -- image.psd
-cargo test --workspace
+# Headless: open, edit, save
+photocraft-cli run wave.psd \
+ --cmd filter.sharpen.smartSharpen --params '{"amount":80}' \
+ --cmd layer.newAdjustmentLayer.curves --params '{"points":[[0,0],[64,48],[192,212],[255,255]]}' \
+ --out wave-final.png
+
+# Apply one action list to a folder of images
+photocraft-cli batch --actions grade.json --in ./raw --out ./graded
+
+# Let an agent drive it over MCP (headless, or bridged to the running app)
+photocraft-cli mcp
```
-Start with [`AGENTS.md`](AGENTS.md), then [`docs/`](docs/).
+The desktop app also listens on a local control channel (`photocraft --control`) for inspecting UI state, driving tools with pointer events, and taking offscreen screenshots. Every image in this README was rendered that way. See [`docs/control-protocol.md`](docs/control-protocol.md).
+
+## Under the hood
+
+- **Engine first:** a pure-data document model and a command engine, with a thin egui UI on top. Layering is enforced at build time across 24 crates.
+- **Two compositors:** a CPU compositor serves as the reference oracle, and a wgpu compositor puts the canvas on the GPU. They are tested against each other.
+- **Copy-on-write tiles:** 256² sparse tiles make undo cheap and huge canvases light, and effect maps are cached per layer state.
+- **Runs in the browser:** the whole engine and UI compile to WebAssembly.
+- **Clean-room:** implemented from public specs and observed behaviour only. No proprietary code, shaders or assets.
+- **Tested:** more than 1,600 tests, including PSD round trips, synthetic generators, compositor oracles and multi-depth checks.
+
+## Get started
+
+```sh
+git clone https://github.com/storytold/photocraft
+cd photocraft
+cargo run --release -p photocraft -- image.psd # the desktop app
+cargo test --workspace # the test suite
+```
+
+New contributors and AI agents: start with [`AGENTS.md`](AGENTS.md), then [`docs/`](docs/).
+
+> **Status:** Photocraft is in early alpha. The core editing workflow is here, and we're working toward full Photoshop parity milestone by milestone (see [`docs/roadmap.md`](docs/roadmap.md)). Progress is measured, not guessed: `cargo xtask parity` checks every item in Photoshop's menu tree against the live command registry and writes [`docs/parity.md`](docs/parity.md). Expect rough edges, and please file issues.
## Crafting Apps
@@ -50,3 +265,11 @@ Open-source, clean-room, pure-Rust creative apps that share the same conventions
</td>
</tr>
</table>
+
+---
+
+<p align="center"><sub>
+ Built by the artcraft team. Licensed under MIT or Apache-2.0.<br>
+ Every artwork shown is in the public domain (Wikimedia Commons, NASA, U.S. National Archives); sources are listed in <a href="docs/images/SOURCES.md"><code>docs/images/SOURCES.md</code></a>.<br>
+ Photoshop is a trademark of Adobe Inc. Photocraft is an independent project, not affiliated with or endorsed by Adobe.
+</sub></p>
diff --git a/apps/photocraft-web/Cargo.toml b/apps/photocraft-web/Cargo.toml
index 675181521..41baa6325 100644
--- a/apps/photocraft-web/Cargo.toml
+++ b/apps/photocraft-web/Cargo.toml
@@ -29,4 +29,4 @@ rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
-web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration"] }
+web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage"] }
diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs
index df84dd9cc..0ddd6b7e8 100644
--- a/apps/photocraft-web/src/web.rs
+++ b/apps/photocraft-web/src/web.rs
@@ -176,9 +176,24 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
.map_err(|e| e.to_string())
})),
inbox: Some(inbox),
+ // Preferences live in the browser's localStorage.
+ load_prefs: Some(Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten())),
+ save_prefs: Some(Box::new(|text: &str| {
+ local_storage()
+ .ok_or("no localStorage")?
+ .set_item(PREFS_KEY, text)
+ .map_err(|e| format!("{e:?}"))
+ })),
+ ..Default::default()
}
}
+const PREFS_KEY: &str = "photocraft.preferences";
+
+fn local_storage() -> Option<web_sys::Storage> {
+ web_sys::window()?.local_storage().ok().flatten()
+}
+
/// Trigger a browser download of `bytes` named after the last component of `path`.
fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml
index 405134fd0..83d194b61 100644
--- a/apps/photocraft/Cargo.toml
+++ b/apps/photocraft/Cargo.toml
@@ -17,6 +17,7 @@ photocraft-compose = { workspace = true }
photocraft-engine = { workspace = true }
photocraft-codecs = { workspace = true }
photocraft-io = { workspace = true }
+photocraft-format = { workspace = true }
photocraft-ui-egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11"] }
egui = { workspace = true }
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs
index da3dfbccc..7de21ee5b 100644
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@ -37,8 +37,10 @@ fn main() -> eframe::Result {
Box::new(move |cc| {
let mut app = PhotocraftApp::new(Session::new(), services::native());
app.integrated_titlebar = cfg!(target_os = "macos");
+ // Preferences › Performance › Use Graphics Processor.
if let Some(rs) = cc.wgpu_render_state.clone()
&& std::env::var_os("PHOTOCRAFT_CPU_CANVAS").is_none()
+ && app.session.prefs().performance.use_gpu
{
app.set_wgpu(rs);
}
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index 01978b88f..3cd8d4e77 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -4,11 +4,54 @@ use photocraft_codecs::{ChannelLayout, EncodeOptions, Image, SampleType as CS};
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Document, Layer, Size};
use photocraft_geom::Rect;
+use photocraft_format::Autosaver;
use photocraft_ui_egui::Services;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::Arc;
const IMAGE_EXTS: &[&str] = &["psd", "psb", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam", "pfm"];
+/// Per-user settings directory: `PHOTOCRAFT_CONFIG_DIR`, else the platform convention
+/// (macOS `~/Library/Application Support/Photocraft`, Windows `%APPDATA%\Photocraft`, Linux
+/// `$XDG_CONFIG_HOME/photocraft` or `~/.config/photocraft`).
+pub fn config_dir() -> Option<PathBuf> {
+ if let Some(d) = std::env::var_os("PHOTOCRAFT_CONFIG_DIR") {
+ return Some(PathBuf::from(d));
+ }
+ let home = std::env::var_os("HOME").map(PathBuf::from);
+ if cfg!(target_os = "macos") {
+ return home.map(|h| h.join("Library/Application Support/Photocraft"));
+ }
+ if cfg!(windows) {
+ return std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("Photocraft"));
+ }
+ std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft"))
+}
+
+fn prefs_file() -> Option<PathBuf> {
+ config_dir().map(|d| d.join("preferences.json"))
+}
+
+fn recovery_dir() -> Option<PathBuf> {
+ config_dir().map(|d| d.join("Recovery"))
+}
+
+/// Write `bytes` atomically (temp file + rename) so a crash never leaves half a preferences file.
+fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
+ }
+ let tmp = path.with_extension("tmp");
+ std::fs::write(&tmp, bytes).map_err(|e| e.to_string())?;
+ std::fs::rename(&tmp, path).map_err(|e| e.to_string())
+}
+
pub fn native() -> Services {
+ let savers: Rc<RefCell<HashMap<u64, Autosaver>>> = Rc::default();
+ let savers2 = savers.clone();
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, settings: &photocraft_ui_egui::ExportSettings| {
@@ -45,6 +88,38 @@ pub fn native() -> Services {
let img = arboard::Clipboard::new().ok()?.get_image().ok()?;
Some((img.width as u32, img.height as u32, img.bytes.into_owned()))
})),
+ load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())),
+ save_prefs: Some(Box::new(|text: &str| write_atomic(&prefs_file().ok_or("no config directory")?, text.as_bytes()))),
+ // Crash recovery: background incremental .pcraft saves into the recovery directory.
+ autosave: Some(Box::new(move |doc: &Arc<Document>, revision: u64, path: Option<&str>| {
+ let dir = recovery_dir().ok_or("no config directory")?;
+ let mut map = savers.borrow_mut();
+ let saver = map.entry(doc.id.0).or_insert_with(|| Autosaver::new(&dir, &format!("doc-{}", doc.id.0)));
+ saver.request(doc.clone(), revision, path.map(str::to_string), Default::default());
+ Ok(())
+ })),
+ discard_autosave: Some(Box::new(move |id: u64| {
+ if let Some(s) = savers2.borrow_mut().remove(&id) {
+ let _ = s.discard();
+ }
+ })),
+ recover: Some(Box::new(|| {
+ let Some(dir) = recovery_dir() else { return Vec::new() };
+ let mut out = Vec::new();
+ for entry in photocraft_format::list_recovery(&dir) {
+ if let Ok(doc) = photocraft_format::recover(&entry) {
+ out.push((entry.info.original_path.clone(), doc));
+ }
+ // Recovered documents autosave again under their new ids.
+ let _ = photocraft_format::discard_recovery(&dir, &entry);
+ }
+ out
+ })),
+ append_text: Some(Box::new(|path: &str, text: &str| {
+ use std::io::Write;
+ let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).map_err(|e| e.to_string())?;
+ f.write_all(text.as_bytes()).map_err(|e| e.to_string())
+ })),
}
}
diff --git a/crates/algo/examples/bench_filters2.rs b/crates/algo/examples/bench_filters2.rs
new file mode 100644
index 000000000..4485cb7ac
--- /dev/null
+++ b/crates/algo/examples/bench_filters2.rs
@@ -0,0 +1,58 @@
+//! Timing for the heavier second-batch filters on a ~24 MP (6000×4000) RGBA8 layer.
+//! `cargo run --release -p photocraft-algo --example bench_filters2 [filter-name-substring]`
+use photocraft_algo::*;
+use photocraft_color::PixelFormat;
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+
+fn main() {
+ let only = std::env::args().nth(1);
+ let (w, h) = (6000, 4000);
+ let r = Rect::new(0, 0, w, h);
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ // Busy deterministic content (gradients plus texture) so edge-aware filters do real work.
+ let bytes: Vec<u8> = (0..h)
+ .flat_map(|y| (0..w).flat_map(move |x| [(x % 256) as u8, ((x * 3 + y) / 11 % 256) as u8, ((x ^ y) % 256) as u8, 255]))
+ .collect();
+ s.write_interleaved(r, &bytes);
+ let cases = vec![
+ FilterParams::OilPaint { stylization: 4.0, cleanliness: 5.0, scale: 1.0, bristle_detail: 5.0, lighting: true, angle: -60.0, shine: 1.0 },
+ FilterParams::ReduceNoise { strength: 6.0, preserve_details: 60.0, reduce_color_noise: 45.0, sharpen_details: 25.0, remove_jpeg_artifact: false },
+ FilterParams::LensBlur {
+ radius: 15.0,
+ blades: 6,
+ curvature: 0.0,
+ rotation: 0.0,
+ depth: DepthSource::None,
+ focal_distance: 0.0,
+ invert_depth: false,
+ brightness: 20.0,
+ threshold: 230.0,
+ noise: 0.0,
+ distribution: Distribution::Uniform,
+ monochromatic: false,
+ seed: 0,
+ depth_map: None,
+ },
+ FilterParams::SmartBlur { radius: 3.0, threshold: 25.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal },
+ FilterParams::ShapeBlur { radius: 10.0, shape: BlurShape::Star },
+ FilterParams::TiltShift { blur: 15.0, center_x: 0.5, center_y: 0.5, angle: 0.0, focus: 0.1, transition: 0.15 },
+ FilterParams::IrisBlur { pins: vec![IrisPin::default()] },
+ FilterParams::FieldBlur { pins: vec![FieldPin { x: 0.2, y: 0.2, blur: 0.0 }, FieldPin { x: 0.8, y: 0.8, blur: 30.0 }] },
+ FilterParams::SpinBlur { pins: vec![SpinPin::default()] },
+ FilterParams::PathBlur { paths: vec![BlurPath::default()] },
+ FilterParams::Crystallize { cell_size: 10.0, seed: 0 },
+ FilterParams::ColorHalftone { max_radius: 8.0, angles: [108.0, 162.0, 90.0, 45.0] },
+ FilterParams::LightingEffects { lights: vec![Light::default()], gloss: 0.0, metallic: 0.0, exposure: 0.0, ambience: 8.0, texture: TextureChannel::Luminance, height: 50.0, white_is_high: true },
+ ];
+ for p in cases {
+ if only.as_deref().is_some_and(|o| !p.label().to_lowercase().contains(&o.to_lowercase())) {
+ continue;
+ }
+ let area = output_area(&p, s.content_bounds(), r, None).intersect(&r);
+ let t = std::time::Instant::now();
+ let out = apply(&s, &p, area, r, None);
+ println!("{:<18} {w}x{h} RGBA8: {:.2?}", p.label(), t.elapsed());
+ drop(out);
+ }
+}
diff --git a/crates/algo/src/blur2.rs b/crates/algo/src/blur2.rs
new file mode 100644
index 000000000..b510fad0f
--- /dev/null
+++ b/crates/algo/src/blur2.rs
@@ -0,0 +1,381 @@
+//! Smart Blur, Shape Blur and Lens Blur.
+//!
+//! Shaped kernels are applied as horizontal spans over per-row prefix sums
+//! (f64, to keep 16-bit precision), so a kernel of radius r costs O(r) per
+//! pixel instead of O(r²).
+
+use std::f32::consts::{PI, TAU};
+
+use photocraft_geom::Rect;
+
+use crate::fxutil::{MAXC, luma, native, ncol, premul_window, smoothstep, unpremul_px, xy};
+use crate::image::Image;
+use crate::noise::hash01;
+use crate::{BlurQuality, BlurShape, Ctx, DepthSource, Distribution, SmartBlurMode};
+
+// ---------- span kernels ----------
+
+/// A binary kernel as horizontal runs `(dy, dx0, dx1)` (inclusive).
+pub(crate) struct Spans {
+ pub rows: Vec<(i32, i32, i32)>,
+ pub count: f64,
+}
+
+impl Spans {
+ /// Rasterizes `inside(u, v)` (u, v in −1…1) over a disc of radius `r`.
+ pub(crate) fn new(r: f32, inside: impl Fn(f32, f32) -> bool) -> Spans {
+ let ri = r.max(0.0).ceil() as i32;
+ let mut rows = Vec::new();
+ let mut count = 0.0;
+ if r < 0.5 {
+ return Spans { rows: vec![(0, 0, 0)], count: 1.0 };
+ }
+ for dy in -ri..=ri {
+ let mut run: Option<i32> = None;
+ for dx in -ri..=ri + 1 {
+ let hit = dx <= ri && inside(dx as f32 / r, dy as f32 / r);
+ match (hit, run) {
+ (true, None) => run = Some(dx),
+ (false, Some(s)) => {
+ rows.push((dy, s, dx - 1));
+ count += (dx - s) as f64;
+ run = None;
+ }
+ _ => {}
+ }
+ }
+ }
+ if rows.is_empty() {
+ rows.push((0, 0, 0));
+ count = 1.0;
+ }
+ Spans { rows, count }
+ }
+}
+
+/// Per-row prefix sums of an interleaved window: `(w + 1) × h × n`.
+pub(crate) struct Prefix {
+ w: usize,
+ n: usize,
+ data: Vec<f64>,
+}
+
+impl Prefix {
+ pub(crate) fn new(p: &[f32], w: usize, h: usize, n: usize) -> Prefix {
+ let mut data = vec![0.0f64; (w + 1) * h * n];
+ for y in 0..h {
+ let src = &p[y * w * n..(y + 1) * w * n];
+ let dst = &mut data[y * (w + 1) * n..(y + 1) * (w + 1) * n];
+ for x in 0..w {
+ for c in 0..n {
+ dst[(x + 1) * n + c] = dst[x * n + c] + src[x * n + c] as f64;
+ }
+ }
+ }
+ Prefix { w, n, data }
+ }
+
+ /// Kernel mean at window pixel `(x, y)` into `acc` (n values).
+ #[inline]
+ pub(crate) fn mean(&self, spans: &Spans, x: i32, y: i32, acc: &mut [f64]) {
+ let n = self.n;
+ acc[..n].fill(0.0);
+ let h = (self.data.len() / ((self.w + 1) * n)) as i32;
+ for &(dy, a, b) in &spans.rows {
+ let yy = y + dy;
+ if yy < 0 || yy >= h {
+ continue;
+ }
+ let x0 = (x + a).clamp(0, self.w as i32) as usize;
+ let x1 = (x + b + 1).clamp(0, self.w as i32) as usize;
+ let row = yy as usize * (self.w + 1) * n;
+ let (hi, lo) = (&self.data[row + x1 * n..row + x1 * n + n], &self.data[row + x0 * n..row + x0 * n + n]);
+ for ((a, h), l) in acc.iter_mut().zip(hi).zip(lo) {
+ *a += h - l;
+ }
+ }
+ for v in acc.iter_mut().take(n) {
+ *v /= spans.count;
+ }
+ }
+}
+
+/// Point-in-polygon (even–odd) for `pts`.
+fn in_poly(u: f32, v: f32, pts: &[(f32, f32)]) -> bool {
+ let mut inside = false;
+ let mut j = pts.len() - 1;
+ for i in 0..pts.len() {
+ let (xi, yi) = pts[i];
+ let (xj, yj) = pts[j];
+ if (yi > v) != (yj > v) && u < (xj - xi) * (v - yi) / (yj - yi) + xi {
+ inside = !inside;
+ }
+ j = i;
+ }
+ inside
+}
+
+/// Radius of a regular `n`-gon (circumradius 1) in direction `theta`.
+fn polygon_radius(theta: f32, n: u32, rot: f32) -> f32 {
+ let seg = TAU / n as f32;
+ let a = (theta - rot).rem_euclid(seg) - seg / 2.0;
+ (PI / n as f32).cos() / a.cos()
+}
+
+fn shape_inside(shape: BlurShape) -> Box<dyn Fn(f32, f32) -> bool + Send + Sync> {
+ match shape {
+ BlurShape::Circle => Box::new(|u, v| u * u + v * v <= 1.0),
+ BlurShape::Ring => Box::new(|u, v| {
+ let d = u * u + v * v;
+ (0.36..=1.0).contains(&d)
+ }),
+ BlurShape::Square => Box::new(|_, _| true),
+ BlurShape::Diamond => Box::new(|u, v| u.abs() + v.abs() <= 1.0),
+ BlurShape::Triangle => Box::new(|u, v| v <= 0.75 && u.abs() <= (v + 1.0) / 1.75),
+ BlurShape::Hexagon => Box::new(|u, v| (u * u + v * v).sqrt() <= polygon_radius(v.atan2(u), 6, 0.0)),
+ BlurShape::Star => {
+ let pts: Vec<(f32, f32)> = (0..10)
+ .map(|i| {
+ let r = if i % 2 == 0 { 1.0 } else { 0.42 };
+ let a = -PI / 2.0 + i as f32 * PI / 5.0;
+ (r * a.cos(), r * a.sin())
+ })
+ .collect();
+ Box::new(move |u, v| in_poly(u, v, &pts))
+ }
+ BlurShape::Heart => Box::new(|u, v| {
+ // (x² + y² − 1)³ − x²y³ ≤ 0, scaled into the unit square and flipped (y up).
+ let (x, y) = (u * 1.2, -v * 1.2 + 0.15);
+ (x * x + y * y - 1.0).powi(3) - x * x * y * y * y <= 0.0
+ }),
+ BlurShape::Cross => Box::new(|u, v| u.abs() <= 0.3 || v.abs() <= 0.3),
+ }
+}
+
+/// Shape Blur: mean over a built-in shape of the given radius.
+pub(crate) fn shape_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, shape: BlurShape) -> Vec<f32> {
+ let spans = Spans::new(radius.max(0.0), shape_inside(shape));
+ conv_spans(src, out, ctx, &spans)
+}
+
+fn conv_spans(src: &Image, out: Rect, ctx: &Ctx, spans: &Spans) -> Vec<f32> {
+ let n = src.ch;
+ let win = src.rect;
+ let (ww, wh) = (win.width() as usize, win.height() as usize);
+ let p = premul_window(src, win, ctx.alpha);
+ let pre = Prefix::new(&p, ww, wh, n);
+ let mut acc = [0.0f64; MAXC];
+ let mut px = [0.0f32; MAXC];
+ let mut res = Vec::with_capacity(out.width() as usize * out.height() as usize * n);
+ for y in out.y0..out.y1 {
+ for x in out.x0..out.x1 {
+ pre.mean(spans, x - win.x0, y - win.y0, &mut acc);
+ for (p, a) in px.iter_mut().zip(&acc).take(n) {
+ *p = *a as f32;
+ }
+ unpremul_px(&mut px[..n], ctx.alpha);
+ res.extend_from_slice(&px[..n]);
+ }
+ }
+ res
+}
+
+// ---------- smart blur ----------
+
+/// Smart Blur: averages only neighbours within `threshold` levels of the
+/// centre pixel (so edges stay crisp); Edge Only / Overlay Edge draw the
+/// edges (where neighbours differ by more than the threshold) in white.
+pub(crate) fn smart_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, threshold: f32, quality: BlurQuality, mode: SmartBlurMode) -> Vec<f32> {
+ let n = src.ch;
+ let cc = ncol(ctx, n);
+ let r = radius.clamp(0.1, 100.0);
+ let t = threshold.clamp(0.1, 100.0) / 255.0;
+ let ri = r.ceil() as i32;
+ let target = match quality {
+ BlurQuality::Low => 4,
+ BlurQuality::Medium => 7,
+ BlurQuality::High => 12,
+ };
+ let stride = ((ri + target - 1) / target).max(1);
+ let offs: Vec<(i32, i32)> = (-ri..=ri)
+ .step_by(stride as usize)
+ .flat_map(|dy| (-ri..=ri).step_by(stride as usize).map(move |dx| (dx, dy)))
+ .filter(|(dx, dy)| ((dx * dx + dy * dy) as f32) <= r * r + 0.5)
+ .collect();
+ let white = native(ctx, [1.0, 1.0, 1.0, 1.0]);
+ let black = native(ctx, [0.0, 0.0, 0.0, 1.0]);
+ let mut res = src.crop(out);
+ let mut q = [0.0f32; MAXC];
+ let mut acc = [0.0f32; MAXC];
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ let me: [f32; MAXC] = std::array::from_fn(|c| if c < n { px[c] } else { 0.0 });
+ let differs = |q: &[f32]| (0..cc).any(|c| (q[c] - me[c]).abs() > t);
+ if mode != SmartBlurMode::Normal {
+ let mut edge = false;
+ for (dx, dy) in [(1, 0), (0, 1), (-1, 0), (0, -1)] {
+ for (c, v) in q.iter_mut().enumerate().take(n) {
+ *v = src.get(x + dx, y + dy, c);
+ }
+ if differs(&q[..n]) {
+ edge = true;
+ break;
+ }
+ }
+ let a = if ctx.alpha { px[n - 1] } else { 1.0 };
+ if edge {
+ px[..cc].copy_from_slice(&white[..cc]);
+ } else if mode == SmartBlurMode::EdgeOnly {
+ px[..cc].copy_from_slice(&black[..cc]);
+ }
+ if ctx.alpha {
+ px[n - 1] = a;
+ }
+ continue;
+ }
+ acc[..n].fill(0.0);
+ let mut wsum = 0.0f32;
+ for &(dx, dy) in &offs {
+ for (c, v) in q.iter_mut().enumerate().take(n) {
+ *v = src.get(x + dx, y + dy, c);
+ }
+ if differs(&q[..n]) {
+ continue;
+ }
+ let a = if ctx.alpha { q[n - 1] } else { 1.0 };
+ for c in 0..n {
+ acc[c] += if ctx.alpha && c < n - 1 { q[c] * a } else { q[c] };
+ }
+ wsum += 1.0;
+ }
+ if wsum > 0.0 {
+ for c in 0..n {
+ px[c] = acc[c] / wsum;
+ }
+ unpremul_px(px, ctx.alpha);
+ }
+ }
+ res
+}
+
+// ---------- lens blur ----------
+
+pub(crate) struct LensSpec<'a> {
+ pub radius: f32,
+ pub blades: u32,
+ pub curvature: f32,
+ pub rotation: f32,
+ pub depth: DepthSource,
+ pub focal: f32,
+ pub invert: bool,
+ pub brightness: f32,
+ pub threshold: f32,
+ pub noise: f32,
+ pub distribution: Distribution,
+ pub mono: bool,
+ pub seed: u32,
+ pub depth_map: Option<&'a Image>,
+}
+
+/// Depth levels the per-pixel iris radius is interpolated between.
+const LENS_LEVELS: usize = 8;
+
+/// Lens Blur: an iris-shaped (polygon → circle by curvature) bokeh kernel,
+/// with highlights above the threshold brightened first so they bloom into
+/// iris shapes. With a depth map the iris radius grows with distance from
+/// the focal plane. Finally optional noise restores grain.
+pub(crate) fn lens_blur(src: &Image, out: Rect, ctx: &Ctx, spec: &LensSpec) -> Vec<f32> {
+ let n = src.ch;
+ let cc = ncol(ctx, n);
+ let win = src.rect;
+ let (ww, wh) = (win.width() as usize, win.height() as usize);
+ let rmax = spec.radius.clamp(0.0, 100.0);
+ let blades = spec.blades.clamp(3, 8);
+ let curv = spec.curvature.clamp(0.0, 100.0) / 100.0;
+ let rot = spec.rotation.to_radians();
+ let iris = move |u: f32, v: f32| {
+ let rho = (u * u + v * v).sqrt();
+ let pr = polygon_radius(v.atan2(u), blades, rot - PI / 2.0);
+ rho <= pr + (1.0 - pr) * curv
+ };
+ let levels: Vec<Spans> = (0..=LENS_LEVELS).map(|k| Spans::new(rmax * k as f32 / LENS_LEVELS as f32, iris)).collect();
+ // Specular highlight boost before blurring.
+ let mut p = premul_window(src, win, ctx.alpha);
+ let boost = spec.brightness.clamp(0.0, 100.0) / 100.0 * 4.0;
+ if boost > 0.0 {
+ let th = spec.threshold.clamp(0.0, 255.0) / 255.0;
+ let sub = crate::fxutil::subtractive(ctx);
+ for px in p.chunks_exact_mut(n) {
+ let a = if ctx.alpha { px[n - 1] } else { 1.0 };
+ if a <= 0.0 {
+ continue;
+ }
+ let mut st = [0.0f32; MAXC];
+ for c in 0..n {
+ st[c] = if ctx.alpha && c < n - 1 { px[c] / a } else { px[c] };
+ }
+ let l = luma(ctx, &st[..n]);
+ let k = 1.0 + boost * smoothstep(th, th + 0.02, l);
+ for v in px.iter_mut().take(cc) {
+ *v = if sub { a - (a - *v) / k } else { *v * k };
+ }
+ }
+ }
+ let pre = Prefix::new(&p, ww, wh, n);
+ let depth_at = |x: i32, y: i32| -> Option<f32> {
+ let d = match spec.depth {
+ DepthSource::None => return None,
+ DepthSource::Transparency => {
+ if !ctx.alpha {
+ return None;
+ }
+ src.get(x, y, n - 1)
+ }
+ DepthSource::LayerMask => spec.depth_map?.get(x, y, 0),
+ };
+ Some(if spec.invert { 1.0 - d } else { d })
+ };
+ let focal = spec.focal.clamp(0.0, 255.0) / 255.0;
+ let amount = spec.noise.clamp(0.0, 100.0) / 100.0 * 0.25;
+ let mut acc = [0.0f64; MAXC];
+ let mut acc2 = [0.0f64; MAXC];
+ let mut px = [0.0f32; MAXC];
+ let mut res = Vec::with_capacity(out.width() as usize * out.height() as usize * n);
+ for y in out.y0..out.y1 {
+ for x in out.x0..out.x1 {
+ let (wx, wy) = (x - win.x0, y - win.y0);
+ let level = match depth_at(x, y) {
+ None => LENS_LEVELS as f32,
+ Some(d) => ((d - focal).abs() * LENS_LEVELS as f32).min(LENS_LEVELS as f32),
+ };
+ let lo = level.floor() as usize;
+ let f = level - lo as f32;
+ pre.mean(&levels[lo], wx, wy, &mut acc);
+ if f > 1e-4 && lo < LENS_LEVELS {
+ pre.mean(&levels[lo + 1], wx, wy, &mut acc2);
+ for c in 0..n {
+ acc[c] += (acc2[c] - acc[c]) * f as f64;
+ }
+ }
+ for c in 0..n {
+ px[c] = acc[c] as f32;
+ }
+ unpremul_px(&mut px[..n], ctx.alpha);
+ if amount > 0.0 && (!ctx.alpha || px[n - 1] > 0.0) {
+ for (c, v) in px.iter_mut().enumerate().take(cc) {
+ let ch = if spec.mono { 0 } else { c as u32 };
+ *v += match spec.distribution {
+ Distribution::Uniform => (hash01(x, y, ch + 200, spec.seed) - 0.5) * 2.0 * amount,
+ Distribution::Gaussian => {
+ let u1 = hash01(x, y, ch * 2 + 301, spec.seed).max(1e-7);
+ let u2 = hash01(x, y, ch * 2 + 302, spec.seed);
+ (-2.0 * u1.ln()).sqrt() * (TAU * u2).cos() * amount * 0.5
+ }
+ };
+ }
+ }
+ res.extend_from_slice(&px[..n]);
+ }
+ }
+ res
+}
diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs
new file mode 100644
index 000000000..61b1fd098
--- /dev/null
+++ b/crates/algo/src/content_aware.rs
@@ -0,0 +1,330 @@
+//! Edit › Content-Aware Fill: patch-based completion ([`crate::inpaint::complete`]) with a
+//! restricted sampling area, geometric adaptation and colour adaptation.
+//!
+//! * **Sampling area**: pixels outside the allowed `source` mask may not be copied from. The
+//! completion only copies fully-known patches, so excluded pixels are handed to it as
+//! unknown and restored afterwards; only the real hole keeps the synthesised values.
+//! * **Rotation / scale / mirror adaptation**: the sampling window is extended with rotated,
+//! rescaled and mirrored copies of itself, laid out side by side (separated by unknown gaps
+//! wider than a patch), so the patch search can pick transformed source patches, as in
+//! the generalised PatchMatch of C. Barnes, E. Shechtman, D. B. Goldman, A. Finkelstein,
+//! *The Generalized PatchMatch Correspondence Algorithm*, ECCV 2010 (which searches over
+//! rotations and scales; we enumerate a small set instead).
+//! * **Colour adaptation**: the low frequencies of the fill are pulled towards the smooth
+//! membrane interpolation of the hole boundary (P. Pérez, M. Gangnet, A. Blake, *Poisson
+//! Image Editing*, SIGGRAPH 2003 uses the same membrane for seamless cloning), which corrects
+//! gradual brightness and colour changes across the hole while keeping the copied texture.
+//!
+//! Buffers are interleaved `w × h × ch` normalised floats (any model/depth); deterministic.
+
+use crate::inpaint::{CompleteParams, complete};
+use crate::poisson::membrane_fill;
+
+/// Options for [`fill`].
+#[derive(Clone, Debug, PartialEq)]
+pub struct FillOptions {
+ /// Colour adaptation strength `0..=1` (Photoshop: none 0, default ≈0.35, high, very high).
+ pub color_adaptation: f32,
+ /// Extra source rotations in degrees (Photoshop's rotation adaptation levels).
+ pub rotations: Vec<f32>,
+ /// Add downscaled and upscaled source copies.
+ pub scale: bool,
+ /// Add a horizontally mirrored source copy.
+ pub mirror: bool,
+ pub seed: u64,
+}
+
+impl Default for FillOptions {
+ fn default() -> Self {
+ Self { color_adaptation: 0.35, rotations: Vec::new(), scale: false, mirror: false, seed: 1 }
+ }
+}
+
+/// Rotation set for Photoshop's adaptation levels: none, low, medium, high, full.
+pub fn rotation_level(level: &str) -> Vec<f32> {
+ match level {
+ "low" => vec![-10.0, 10.0],
+ "medium" => vec![-20.0, 20.0],
+ "high" => vec![-35.0, 35.0],
+ "full" => vec![90.0, 180.0, 270.0],
+ _ => Vec::new(),
+ }
+}
+
+/// Colour adaptation strength for Photoshop's levels: none, default, high, veryHigh.
+pub fn color_level(level: &str) -> f32 {
+ match level {
+ "none" => 0.0,
+ "high" => 0.65,
+ "veryHigh" => 0.9,
+ _ => 0.35,
+ }
+}
+
+/// One source variant: pixels and which of them are usable.
+struct Variant {
+ w: usize,
+ h: usize,
+ img: Vec<f32>,
+ ok: Vec<bool>,
+}
+
+/// A source buffer and which of its pixels may be sampled.
+#[derive(Clone, Copy)]
+struct Src<'a> {
+ w: usize,
+ h: usize,
+ ch: usize,
+ img: &'a [f32],
+ ok: &'a [bool],
+}
+
+/// Sample the source bilinearly at (x, y); false when any tap is unusable.
+fn sample(src: Src, x: f32, y: f32, out: &mut [f32]) -> bool {
+ let Src { w, h, ch, img, ok } = src;
+ if x < 0.0 || y < 0.0 || x > (w - 1) as f32 || y > (h - 1) as f32 {
+ return false;
+ }
+ let (x0, y0) = (x.floor() as usize, y.floor() as usize);
+ let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
+ let (tx, ty) = (x - x0 as f32, y - y0 as f32);
+ for (xx, yy) in [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] {
+ if !ok[yy * w + xx] {
+ return false;
+ }
+ }
+ for (c, o) in out.iter_mut().enumerate().take(ch) {
+ let p = |xx: usize, yy: usize| img[(yy * w + xx) * ch + c];
+ let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx;
+ let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx;
+ *o = top + (bot - top) * ty;
+ }
+ true
+}
+
+/// Transformed copy of the source: rotation (degrees) and scale about the centre, optional mirror.
+fn variant(src: Src, deg: f32, scale: f32, mirror: bool) -> Variant {
+ let Src { w, h, ch, .. } = src;
+ let (s, c) = (-deg.to_radians()).sin_cos();
+ // Output size: the rotated, scaled bounding box.
+ let (fw, fh) = (w as f32 * scale, h as f32 * scale);
+ let ow = ((fw * c.abs() + fh * s.abs()).round() as usize).max(1);
+ let oh = ((fw * s.abs() + fh * c.abs()).round() as usize).max(1);
+ let (icx, icy) = ((w as f32 - 1.0) / 2.0, (h as f32 - 1.0) / 2.0);
+ let (ocx, ocy) = ((ow as f32 - 1.0) / 2.0, (oh as f32 - 1.0) / 2.0);
+ let mut out = Variant { w: ow, h: oh, img: vec![0.0; ow * oh * ch], ok: vec![false; ow * oh] };
+ let mut px = vec![0.0f32; ch];
+ for y in 0..oh {
+ for x in 0..ow {
+ let (dx, dy) = ((x as f32 - ocx) / scale, (y as f32 - ocy) / scale);
+ let mut sx = icx + dx * c - dy * s;
+ let sy = icy + dx * s + dy * c;
+ if mirror {
+ sx = (w as f32 - 1.0) - sx;
+ }
+ if sample(src, sx, sy, &mut px) {
+ let i = y * ow + x;
+ out.ok[i] = true;
+ out.img[i * ch..(i + 1) * ch].copy_from_slice(&px);
+ }
+ }
+ }
+ out
+}
+
+/// Separable box blur of radius `r` (edge-clamped).
+fn box_blur(w: usize, h: usize, ch: usize, v: &[f32], r: usize) -> Vec<f32> {
+ if r == 0 {
+ return v.to_vec();
+ }
+ let pass = |src: &[f32], horizontal: bool| -> Vec<f32> {
+ let mut dst = vec![0.0f32; src.len()];
+ let (n, m) = if horizontal { (h, w) } else { (w, h) };
+ let idx = |line: usize, k: usize| if horizontal { line * w + k } else { k * w + line };
+ let norm = 1.0 / (2 * r + 1) as f32;
+ for line in 0..n {
+ for c in 0..ch {
+ let at = |k: i64| src[idx(line, k.clamp(0, m as i64 - 1) as usize) * ch + c];
+ let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum();
+ for k in 0..m {
+ dst[idx(line, k) * ch + c] = acc * norm;
+ acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64);
+ }
+ }
+ }
+ dst
+ };
+ pass(&pass(v, true), false)
+}
+
+/// Fill `hole` in `img`, copying only from pixels where `source` is true (and not in the hole).
+/// Returns the full buffer (unchanged outside the hole). Falls back to the membrane fill when
+/// nothing can be sampled.
+pub fn fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], source: &[bool], opts: &FillOptions) -> Vec<f32> {
+ assert_eq!(img.len(), w * h * ch);
+ assert_eq!(hole.len(), w * h);
+ assert_eq!(source.len(), w * h);
+ if !hole.iter().any(|h| *h) {
+ return img.to_vec();
+ }
+ let params = CompleteParams { seed: opts.seed, ..Default::default() };
+ let gap = 2 * params.patch_radius + 2;
+ let ok: Vec<bool> = hole.iter().zip(source).map(|(h, s)| !h && *s).collect();
+ let src = Src { w, h, ch, img, ok: &ok };
+ // Variants: the identity (which holds the hole) first, then the adaptations.
+ let mut extra: Vec<Variant> = Vec::new();
+ if opts.mirror {
+ extra.push(variant(src, 0.0, 1.0, true));
+ }
+ for &deg in &opts.rotations {
+ extra.push(variant(src, deg, 1.0, false));
+ }
+ if opts.scale {
+ extra.push(variant(src, 0.0, 0.8, false));
+ extra.push(variant(src, 0.0, 1.25, false));
+ }
+ // Mosaic: identity at the left, variants in a column to its right.
+ let col_w = extra.iter().map(|v| v.w).max().unwrap_or(0);
+ let col_h: usize = extra.iter().map(|v| v.h + gap).sum();
+ let mw = if extra.is_empty() { w } else { w + gap + col_w };
+ let mh = h.max(col_h);
+ let mut mimg = vec![0.0f32; mw * mh * ch];
+ let mut unknown = vec![true; mw * mh];
+ for y in 0..h {
+ for x in 0..w {
+ let (s, d) = (y * w + x, y * mw + x);
+ mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]);
+ unknown[d] = !ok[s];
+ }
+ }
+ let mut oy = 0;
+ for v in &extra {
+ for y in 0..v.h {
+ for x in 0..v.w {
+ let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x);
+ mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]);
+ unknown[d] = !v.ok[s];
+ }
+ }
+ oy += v.h + gap;
+ }
+ let filled = complete(mw, mh, ch, &mimg, &unknown, &params);
+ let mut out = img.to_vec();
+ match filled {
+ Some(f) => {
+ for y in 0..h {
+ for x in 0..w {
+ if hole[y * w + x] {
+ let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch);
+ out[d..d + ch].copy_from_slice(&f[s..s + ch]);
+ }
+ }
+ }
+ }
+ None => out = membrane_fill(w, h, ch, img, hole),
+ }
+ if opts.color_adaptation > 0.0 {
+ adapt_colors(w, h, ch, img, hole, &mut out, opts.color_adaptation);
+ }
+ out
+}
+
+/// Pull the fill's low frequencies towards the membrane interpolation of the hole boundary.
+fn adapt_colors(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], out: &mut [f32], k: f32) {
+ let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
+ for y in 0..h {
+ for x in 0..w {
+ if hole[y * w + x] {
+ (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1));
+ }
+ }
+ }
+ let r = ((x1 - x0).max(y1 - y0) / 6).clamp(1, 32);
+ let membrane = membrane_fill(w, h, ch, img, hole);
+ let low = box_blur(w, h, ch, out, r);
+ for (i, &hl) in hole.iter().enumerate() {
+ if hl {
+ for c in 0..ch {
+ let j = i * ch + c;
+ out[j] = (out[j] + k * (membrane[j] - low[j])).clamp(0.0, 1.0);
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Vertical stripes (period 6) in grey, with a hole in the middle.
+ fn stripes(w: usize, h: usize) -> (Vec<f32>, Vec<bool>) {
+ let img: Vec<f32> = (0..w * h).map(|i| if (i % w) % 6 < 3 { 0.2 } else { 0.8 }).collect();
+ let hole: Vec<bool> = (0..w * h).map(|i| (i % w).abs_diff(w / 2) < 4 && (i / w).abs_diff(h / 2) < 4).collect();
+ (img, hole)
+ }
+
+ #[test]
+ fn fills_only_the_hole_with_known_texture() {
+ let (w, h) = (48, 32);
+ let (img, hole) = stripes(w, h);
+ let src = vec![true; w * h];
+ let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: 0.0, ..Default::default() });
+ for i in 0..w * h {
+ if !hole[i] {
+ assert_eq!(out[i], img[i]);
+ }
+ }
+ // The hole is filled with stripe values, not a flat average.
+ let vals: Vec<f32> = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).collect();
+ assert!(vals.iter().any(|v| *v < 0.35) && vals.iter().any(|v| *v > 0.65), "{vals:?}");
+ }
+
+ #[test]
+ fn sampling_area_restricts_sources() {
+ // Left half dark, right half bright; sampling only the right half fills bright.
+ let (w, h) = (40, 20);
+ let img: Vec<f32> = (0..w * h).map(|i| if i % w < 20 { 0.1 } else { 0.9 }).collect();
+ let hole: Vec<bool> = (0..w * h).map(|i| (16..24).contains(&(i % w)) && (6..14).contains(&(i / w))).collect();
+ let right: Vec<bool> = (0..w * h).map(|i| i % w >= 24).collect();
+ let out = fill(w, h, 1, &img, &hole, &right, &FillOptions { color_adaptation: 0.0, ..Default::default() });
+ let mean: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).sum::<f32>() / 64.0;
+ assert!(mean > 0.8, "mean {mean}");
+ }
+
+ #[test]
+ fn adaptations_run_and_stay_deterministic() {
+ let (w, h) = (32, 24);
+ let (img, hole) = stripes(w, h);
+ let rgb: Vec<f32> = img.iter().flat_map(|v| [*v, *v * 0.5, 1.0 - *v]).collect();
+ let src = vec![true; w * h];
+ let opts = FillOptions { color_adaptation: 0.65, rotations: rotation_level("low"), scale: true, mirror: true, seed: 7 };
+ let a = fill(w, h, 3, &rgb, &hole, &src, &opts);
+ let b = fill(w, h, 3, &rgb, &hole, &src, &opts);
+ assert_eq!(a, b);
+ assert!(a.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)));
+ }
+
+ #[test]
+ fn color_adaptation_follows_a_gradient() {
+ // A horizontal brightness ramp with a hole: adaptation keeps the fill near the ramp.
+ let (w, h) = (40, 20);
+ let img: Vec<f32> = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect();
+ let hole: Vec<bool> = (0..w * h).map(|i| (14..26).contains(&(i % w)) && (5..15).contains(&(i / w))).collect();
+ let src = vec![true; w * h];
+ let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: 0.9, ..Default::default() });
+ let err: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| (out[i] - img[i]).abs()).sum::<f32>() / 120.0;
+ assert!(err < 0.12, "mean error {err}");
+ }
+
+ #[test]
+ fn variant_geometry() {
+ let img = vec![0.5f32; 10 * 6];
+ let ok = vec![true; 60];
+ let src = Src { w: 10, h: 6, ch: 1, img: &img, ok: &ok };
+ let v = variant(src, 90.0, 1.0, false);
+ assert_eq!((v.w, v.h), (6, 10));
+ let v = variant(src, 0.0, 0.8, true);
+ assert_eq!((v.w, v.h), (8, 5));
+ assert!(v.ok.iter().filter(|o| **o).count() > 20);
+ }
+}
diff --git a/crates/algo/src/denoise.rs b/crates/algo/src/denoise.rs
new file mode 100644
index 000000000..07f474563
--- /dev/null
+++ b/crates/algo/src/denoise.rs
@@ -0,0 +1,180 @@
+//! Reduce Noise: edge-preserving luminance smoothing, chroma smoothing guided
+//! by the luminance, and optional detail sharpening.
+//!
+//! Smoothing uses the guided filter (He, Sun & Tang, "Guided Image
+//! Filtering", ECCV 2010): O(1) per pixel whatever the radius, and edge-aware
+//! because the local linear model follows the guide's variance.
+
+use photocraft_color::ColorMode;
+use photocraft_geom::Rect;
+
+use crate::Ctx;
+use crate::fxutil::{MAXC, box_blur_n, gauss_blur_n, rgba, set_rgba};
+use crate::image::Image;
+
+pub(crate) struct DenoiseSpec {
+ pub strength: f32,
+ pub preserve: f32,
+ pub color: f32,
+ pub sharpen: f32,
+ pub jpeg: bool,
+}
+
+const MAX_LUMA_R: usize = 5;
+const MAX_CHROMA_R: usize = 9;
+
+/// Pixels read beyond an output tile (two box passes per guided filter, plus sharpening).
+pub(crate) fn reach() -> f32 {
+ (2 * MAX_LUMA_R + 2 * MAX_CHROMA_R + 6) as f32
+}
+
+/// Guided filter of `p` with guide `g` (both `w × h`), box radius `r`.
+fn guided(g: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec<f32> {
+ let len = w * h;
+ // Interleave the four box-filtered moments to run one pass.
+ let mut m = vec![0.0f32; len * 4];
+ for i in 0..len {
+ m[i * 4] = g[i];
+ m[i * 4 + 1] = p[i];
+ m[i * 4 + 2] = g[i] * g[i];
+ m[i * 4 + 3] = g[i] * p[i];
+ }
+ box_blur_n(&mut m, w, h, 4, r);
+ let mut ab = vec![0.0f32; len * 2];
+ for i in 0..len {
+ let (mg, mp, mgg, mgp) = (m[i * 4], m[i * 4 + 1], m[i * 4 + 2], m[i * 4 + 3]);
+ let var = (mgg - mg * mg).max(0.0);
+ let a = (mgp - mg * mp) / (var + eps);
+ ab[i * 2] = a;
+ ab[i * 2 + 1] = mp - a * mg;
+ }
+ box_blur_n(&mut ab, w, h, 2, r);
+ (0..len).map(|i| ab[i * 2] * g[i] + ab[i * 2 + 1]).collect()
+}
+
+pub(crate) fn reduce_noise(src: &Image, out: Rect, ctx: &Ctx, spec: &DenoiseSpec) -> Vec<f32> {
+ let n = src.ch;
+ let win = src.rect;
+ let (ww, wh) = (win.width() as usize, win.height() as usize);
+ let len = ww * wh;
+ let s = spec.strength.clamp(0.0, 10.0) / 10.0;
+ let col = spec.color.clamp(0.0, 100.0) / 100.0;
+ let sh = spec.sharpen.clamp(0.0, 100.0) / 100.0;
+ if (s <= 0.0 && col <= 0.0 && sh <= 0.0 && !spec.jpeg) || len == 0 {
+ return src.crop(out);
+ }
+ // Decompose into luma + two chroma planes.
+ #[derive(PartialEq)]
+ enum Model {
+ Gray,
+ Ycc,
+ Lab,
+ ViaRgb,
+ }
+ let model = match ctx.mode {
+ ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => Model::Gray,
+ ColorMode::Rgb => Model::Ycc,
+ ColorMode::Lab => Model::Lab,
+ _ => Model::ViaRgb,
+ };
+ let mut yv = vec![0.0f32; len];
+ let mut c1 = vec![0.0f32; if model == Model::Gray { 0 } else { len }];
+ let mut c2 = vec![0.0f32; if model == Model::Gray { 0 } else { len }];
+ let mut px = [0.0f32; MAXC];
+ for (i, yy) in yv.iter_mut().enumerate() {
+ let (x, y) = (win.x0 + (i % ww) as i32, win.y0 + (i / ww) as i32);
+ for (c, v) in px.iter_mut().enumerate().take(n) {
+ *v = src.get(x, y, c);
+ }
+ match model {
+ Model::Gray => *yy = px[0],
+ Model::Lab => {
+ *yy = px[0];
+ c1[i] = px[1];
+ c2[i] = px[2];
+ }
+ Model::Ycc | Model::ViaRgb => {
+ let c = if model == Model::Ycc { [px[0], px[1], px[2], 1.0] } else { rgba(ctx, &px[..n]) };
+ let l = 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2];
+ *yy = l;
+ c1[i] = c[2] - l;
+ c2[i] = c[0] - l;
+ }
+ }
+ }
+ // JPEG deblocking: soften luma across the 8×8 grid lines (document-anchored).
+ if spec.jpeg {
+ let orig = yv.clone();
+ for yy in 1..wh.saturating_sub(1) {
+ for xx in 1..ww - 1 {
+ let (dx, dy) = ((win.x0 + xx as i32).rem_euclid(8), (win.y0 + yy as i32).rem_euclid(8));
+ if dx == 0 || dx == 7 || dy == 0 || dy == 7 {
+ let mut a = 0.0;
+ for j in 0..3 {
+ for k in 0..3 {
+ a += orig[(yy + j - 1) * ww + xx + k - 1];
+ }
+ }
+ yv[yy * ww + xx] = 0.5 * orig[yy * ww + xx] + 0.5 * a / 9.0;
+ }
+ }
+ }
+ }
+ // Luminance: edge-preserving smoothing; Preserve Details shrinks the regularisation.
+ if s > 0.0 {
+ let r = (1.0 + spec.strength.clamp(0.0, 10.0) * 0.4).round() as usize;
+ let keep = spec.preserve.clamp(0.0, 100.0) / 100.0;
+ let eps = (0.004 + 0.05 * s).powi(2) * (1.05 - keep);
+ let d = guided(&yv, &yv, ww, wh, r.min(MAX_LUMA_R), eps);
+ let k = s.sqrt();
+ for (v, dv) in yv.iter_mut().zip(d) {
+ *v += (dv - *v) * k;
+ }
+ }
+ // Chroma: guided by the cleaned luma so colour edges stay put.
+ if col > 0.0 && model != Model::Gray {
+ let r = (1.0 + col * 8.0).round() as usize;
+ let eps = (0.01 + 0.05 * col).powi(2);
+ for plane in [&mut c1, &mut c2] {
+ let d = guided(&yv, plane, ww, wh, r.min(MAX_CHROMA_R), eps);
+ for (v, dv) in plane.iter_mut().zip(d) {
+ *v += (dv - *v) * col;
+ }
+ }
+ }
+ // Sharpen Details: unsharp mask on luma.
+ if sh > 0.0 {
+ let mut bl = yv.clone();
+ gauss_blur_n(&mut bl, ww, wh, 1, 1.0);
+ for (v, b) in yv.iter_mut().zip(bl) {
+ *v += (*v - b) * sh * 1.2;
+ }
+ }
+ let mut res = src.crop(out);
+ for (i, p) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = crate::fxutil::xy(out, i);
+ let k = ((y - win.y0) as usize) * ww + (x - win.x0) as usize;
+ match model {
+ Model::Gray => p[0] = yv[k],
+ Model::Lab => {
+ p[0] = yv[k];
+ p[1] = c1[k];
+ p[2] = c2[k];
+ }
+ Model::Ycc | Model::ViaRgb => {
+ let l = yv[k];
+ let (b, r) = (c1[k] + l, c2[k] + l);
+ let g = (l - 0.299 * r - 0.114 * b) / 0.587;
+ if model == Model::Ycc {
+ p[0] = r;
+ p[1] = g;
+ p[2] = b;
+ } else {
+ let a = if ctx.alpha { p[n - 1] } else { 1.0 };
+ set_rgba(ctx, p, [r, g, b, a]);
+ }
+ }
+ }
+ }
+ res
+}
diff --git a/crates/algo/src/distort.rs b/crates/algo/src/distort.rs
index 5f1c0ffe1..0c83085e7 100644
--- a/crates/algo/src/distort.rs
+++ b/crates/algo/src/distort.rs
@@ -9,7 +9,7 @@ use crate::noise::hash01;
use crate::other::edge_of;
use crate::{Ctx, PolarMode, RippleSize, SpherizeMode, UndefinedAreas, WaveType};
-fn remap(src: &Image, out: Rect, ctx: &Ctx, edge: Edge, f: impl Fn(f32, f32) -> (f32, f32)) -> Vec<f32> {
+pub(crate) fn remap(src: &Image, out: Rect, ctx: &Ctx, edge: Edge, f: impl Fn(f32, f32) -> (f32, f32)) -> Vec<f32> {
let n = src.ch;
let mut res = Vec::with_capacity(out.width() as usize * out.height() as usize * n);
let mut tmp = vec![0.0f32; n];
@@ -23,7 +23,7 @@ fn remap(src: &Image, out: Rect, ctx: &Ctx, edge: Edge, f: impl Fn(f32, f32) ->
res
}
-fn centre(b: Rect) -> (f32, f32, f32) {
+pub(crate) fn centre(b: Rect) -> (f32, f32, f32) {
let (w, h) = (b.width() as f32, b.height() as f32);
(b.x0 as f32 + w / 2.0, b.y0 as f32 + h / 2.0, w.min(h) / 2.0)
}
diff --git a/crates/algo/src/distort2.rs b/crates/algo/src/distort2.rs
new file mode 100644
index 000000000..063ed8ecd
--- /dev/null
+++ b/crates/algo/src/distort2.rs
@@ -0,0 +1,130 @@
+//! Displace, Shear, ZigZag (inverse mapping over the reference bounds).
+
+use photocraft_geom::Rect;
+
+use crate::distort::{centre, remap};
+use crate::image::Image;
+use crate::other::edge_of;
+use crate::{Ctx, UndefinedAreas, ZigZagStyle};
+
+/// Max displacement at 100 % scale and full map contrast, px.
+const DISPLACE_PX: f32 = 128.0;
+
+/// Bilinear read of channel `c` of a map at map-local coordinates (clamped).
+fn map_sample(map: &Image, u: f32, v: f32, c: usize) -> f32 {
+ let r = map.rect;
+ let (w, h) = (r.width() as i32, r.height() as i32);
+ let (fx, fy) = (u - 0.5, v - 0.5);
+ let (x0, y0) = (fx.floor(), fy.floor());
+ let (ax, ay) = (fx - x0, fy - y0);
+ let g = |x: i32, y: i32| map.get(r.x0 + x.clamp(0, w - 1), r.y0 + y.clamp(0, h - 1), c);
+ let (x0, y0) = (x0 as i32, y0 as i32);
+ let top = g(x0, y0) + (g(x0 + 1, y0) - g(x0, y0)) * ax;
+ let bot = g(x0, y0 + 1) + (g(x0 + 1, y0 + 1) - g(x0, y0 + 1)) * ax;
+ top + (bot - top) * ay
+}
+
+/// Displace: the map's first channel shifts pixels horizontally and its
+/// second (or first, for one-channel maps) vertically; mid-gray = no shift.
+/// The map is stretched over the bounds or tiled from their top-left.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn displace(src: &Image, out: Rect, ctx: &Ctx, scale: (f32, f32), stretch: bool, undefined: UndefinedAreas, map: Option<&Image>) -> Vec<f32> {
+ let Some(map) = map.filter(|m| !m.rect.is_empty()) else { return src.crop(out) };
+ let b = ctx.bounds;
+ let (mw, mh) = (map.rect.width() as f32, map.rect.height() as f32);
+ let (bw, bh) = (b.width().max(1) as f32, b.height().max(1) as f32);
+ // Colour channels of the map (alpha excluded when present: 2 = gray+alpha, 4 = RGBA…).
+ let vc = if map.ch >= 3 { 1 } else { 0 };
+ let (sx, sy) = (scale.0 / 100.0 * DISPLACE_PX, scale.1 / 100.0 * DISPLACE_PX);
+ remap(src, out, ctx, edge_of(undefined), |x, y| {
+ let (lx, ly) = (x - b.x0 as f32, y - b.y0 as f32);
+ let (u, v) = if stretch { (lx / bw * mw, ly / bh * mh) } else { (lx.rem_euclid(mw), ly.rem_euclid(mh)) };
+ let dx = (map_sample(map, u, v, 0) - 0.5) * 2.0 * sx;
+ let dy = (map_sample(map, u, v, vc) - 0.5) * 2.0 * sy;
+ (x + dx, y + dy)
+ })
+}
+
+/// Catmull–Rom interpolation through sorted `(t, value)` points (clamped ends).
+fn curve_at(pts: &[[f32; 2]], t: f32) -> f32 {
+ match pts.len() {
+ 0 => 0.0,
+ 1 => pts[0][1],
+ _ => {
+ if t <= pts[0][0] {
+ return pts[0][1];
+ }
+ let last = pts.len() - 1;
+ if t >= pts[last][0] {
+ return pts[last][1];
+ }
+ let i = pts.windows(2).position(|w| t >= w[0][0] && t <= w[1][0]).unwrap_or(0);
+ let p1 = pts[i];
+ let p2 = pts[i + 1];
+ let p0 = if i > 0 { pts[i - 1] } else { p1 };
+ let p3 = if i + 2 <= last { pts[i + 2] } else { p2 };
+ let span = (p2[0] - p1[0]).max(1e-6);
+ let s = (t - p1[0]) / span;
+ // Tangents scaled to the span (non-uniform Catmull–Rom).
+ let m1 = if i > 0 { (p2[1] - p0[1]) / (p2[0] - p0[0]).max(1e-6) * span } else { p2[1] - p1[1] };
+ let m2 = if i + 2 <= last { (p3[1] - p1[1]) / (p3[0] - p1[0]).max(1e-6) * span } else { p2[1] - p1[1] };
+ let (s2, s3) = (s * s, s * s * s);
+ (2.0 * s3 - 3.0 * s2 + 1.0) * p1[1] + (s3 - 2.0 * s2 + s) * m1 + (-2.0 * s3 + 3.0 * s2) * p2[1] + (s3 - s2) * m2
+ }
+ }
+}
+
+/// Shear: each row shifts horizontally by the curve through `points`
+/// (`[t, offset]`, t top→bottom, offset in half-widths).
+pub(crate) fn shear(src: &Image, out: Rect, ctx: &Ctx, points: &[[f32; 2]], undefined: UndefinedAreas) -> Vec<f32> {
+ let b = ctx.bounds;
+ let mut pts: Vec<[f32; 2]> = points.iter().map(|p| [p[0].clamp(0.0, 1.0), p[1].clamp(-1.0, 1.0)]).collect();
+ pts.sort_by(|a, b| a[0].total_cmp(&b[0]));
+ pts.dedup_by(|a, b| (a[0] - b[0]).abs() < 1e-6);
+ let (bw, bh) = (b.width().max(1) as f32, b.height().max(1) as f32);
+ // Per-row offsets are shared by every pixel of the row.
+ let rows: Vec<f32> = (out.y0..out.y1).map(|y| curve_at(&pts, (y as f32 + 0.5 - b.y0 as f32) / bh) * bw / 2.0).collect();
+ remap(src, out, ctx, edge_of(undefined), |x, y| {
+ let i = ((y - 0.5) as i32 - out.y0).clamp(0, rows.len() as i32 - 1) as usize;
+ (x - rows[i], y)
+ })
+}
+
+/// ZigZag: radial ripples inside the bounds' inscribed circle — angular
+/// (around centre), radial (out from centre) or both (pond ripples).
+pub(crate) fn zigzag(src: &Image, out: Rect, ctx: &Ctx, amount: f32, ridges: f32, style: ZigZagStyle) -> Vec<f32> {
+ let (cx, cy, rr) = centre(ctx.bounds);
+ let a = (amount / 100.0).clamp(-1.0, 1.0);
+ let k = ridges.clamp(0.0, 20.0).max(0.5);
+ remap(src, out, ctx, crate::image::Edge::Repeat, |x, y| {
+ let (dx, dy) = (x - cx, y - cy);
+ let r = (dx * dx + dy * dy).sqrt();
+ if r >= rr || r <= 0.0 || a == 0.0 {
+ return (x, y);
+ }
+ let rn = r / rr;
+ let wave = (std::f32::consts::TAU * k * rn).sin() * (1.0 - rn);
+ let (radial, angular) = match style {
+ ZigZagStyle::OutFromCenter => (a * wave * rr / (4.0 * k), 0.0),
+ ZigZagStyle::AroundCenter => (0.0, a * wave * std::f32::consts::PI / (2.0 * k)),
+ ZigZagStyle::PondRipples => (a * wave * rr / (8.0 * k), a * wave * std::f32::consts::PI / (4.0 * k)),
+ };
+ let th = dy.atan2(dx) + angular;
+ let rs = (r + radial).max(0.0);
+ (cx + rs * th.cos(), cy + rs * th.sin())
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::curve_at;
+
+ #[test]
+ fn curve_passes_through_points_and_clamps() {
+ let pts = [[0.0, 0.0], [0.5, 0.4], [1.0, -0.2]];
+ assert!((curve_at(&pts, 0.5) - 0.4).abs() < 1e-6);
+ assert!((curve_at(&pts, 1.0) + 0.2).abs() < 1e-6);
+ assert_eq!(curve_at(&pts, -1.0), 0.0);
+ assert_eq!(curve_at(&[[0.0, 0.3], [1.0, 0.3]], 0.42), 0.3);
+ }
+}
diff --git a/crates/algo/src/features.rs b/crates/algo/src/features.rs
new file mode 100644
index 000000000..34c8cda4f
--- /dev/null
+++ b/crates/algo/src/features.rs
@@ -0,0 +1,546 @@
+//! Image registration for Edit › Auto-Align Layers: corners, binary descriptors, matching and
+//! robust model fitting.
+//!
+//! * Corners: C. Harris, M. Stephens, *A Combined Corner and Edge Detector*, Alvey Vision
+//! Conference 1988 (structure tensor `det − k·trace²`, Gaussian window), with non-maximum
+//! suppression and a minimum spacing so corners spread over the image.
+//! * Descriptors: steered BRIEF as in E. Rublee, V. Rabaud, K. Konolige, G. Bradski, *ORB: an
+//! efficient alternative to SIFT or SURF*, ICCV 2011 — 256 intensity comparisons (M. Calonder
+//! et al., *BRIEF*, ECCV 2010) on a smoothed 31×31 patch, rotated by the patch's
+//! intensity-centroid orientation.
+//! * Matching: brute-force Hamming distance with D. Lowe's ratio test (*Distinctive Image
+//! Features from Scale-Invariant Keypoints*, IJCV 2004) and a mutual-nearest check.
+//! * Fitting: RANSAC (M. Fischler, R. Bolles, *Random Sample Consensus*, CACM 1981) over
+//! translation, similarity or homography models; homographies use the normalised DLT of
+//! R. Hartley, *In Defense of the Eight-Point Algorithm*, PAMI 1997. The winning model is refit
+//! to all inliers by least squares.
+//!
+//! Everything is deterministic (fixed-seed RNG). Images are `w × h` luminance in `0..=1`.
+
+use crate::transform::Homography;
+
+/// A detected corner.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Corner {
+ pub x: f32,
+ pub y: f32,
+ pub score: f32,
+}
+
+/// A 256-bit descriptor.
+pub type Descriptor = [u64; 4];
+
+/// Model fitted by [`ransac`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Model {
+ Translation,
+ /// Rotation, uniform scale and translation.
+ Similarity,
+ Homography,
+}
+
+/// Patch radius used by descriptors (corners closer than this to the border are dropped).
+pub const PATCH_RADIUS: usize = 15;
+
+struct Rng(u64);
+impl Rng {
+ 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)
+ }
+ fn unit(&mut self) -> f64 {
+ (self.next() >> 11) as f64 / (1u64 << 53) as f64
+ }
+ fn below(&mut self, n: usize) -> usize {
+ (self.next() % n.max(1) as u64) as usize
+ }
+}
+
+fn blur(w: usize, h: usize, v: &[f32], r: usize) -> Vec<f32> {
+ let pass = |src: &[f32], horizontal: bool| -> Vec<f32> {
+ let mut dst = vec![0.0f32; src.len()];
+ let (n, m) = if horizontal { (h, w) } else { (w, h) };
+ for line in 0..n {
+ let at = |k: i64| {
+ let k = k.clamp(0, m as i64 - 1) as usize;
+ if horizontal { src[line * w + k] } else { src[k * w + line] }
+ };
+ let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum();
+ for k in 0..m {
+ let i = if horizontal { line * w + k } else { k * w + line };
+ dst[i] = acc / (2 * r + 1) as f32;
+ acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64);
+ }
+ }
+ dst
+ };
+ pass(&pass(v, true), false)
+}
+
+/// Harris corners: at most `max` corners at least `min_dist` pixels apart, strongest first,
+/// only where `valid` (if given) is true for the whole descriptor patch.
+pub fn harris(w: usize, h: usize, img: &[f32], max: usize, min_dist: f32, valid: Option<&[bool]>) -> Vec<Corner> {
+ if w < 2 * PATCH_RADIUS + 3 || h < 2 * PATCH_RADIUS + 3 {
+ return Vec::new();
+ }
+ let (mut xx, mut yy, mut xy) = (vec![0.0f32; w * h], vec![0.0f32; w * h], vec![0.0f32; w * h]);
+ for y in 1..h - 1 {
+ for x in 1..w - 1 {
+ let p = |dx: i64, dy: i64| img[((y as i64 + dy) as usize) * w + (x as i64 + dx) as usize];
+ // Sobel.
+ let gx = (p(1, -1) + 2.0 * p(1, 0) + p(1, 1)) - (p(-1, -1) + 2.0 * p(-1, 0) + p(-1, 1));
+ let gy = (p(-1, 1) + 2.0 * p(0, 1) + p(1, 1)) - (p(-1, -1) + 2.0 * p(0, -1) + p(1, -1));
+ let i = y * w + x;
+ xx[i] = gx * gx;
+ yy[i] = gy * gy;
+ xy[i] = gx * gy;
+ }
+ }
+ // Two box passes approximate the Gaussian window.
+ let (xx, yy, xy) = (blur(w, h, &blur(w, h, &xx, 1), 1), blur(w, h, &blur(w, h, &yy, 1), 1), blur(w, h, &blur(w, h, &xy, 1), 1));
+ let r: Vec<f32> = (0..w * h).map(|i| xx[i] * yy[i] - xy[i] * xy[i] - 0.04 * (xx[i] + yy[i]).powi(2)).collect();
+ let peak = r.iter().copied().fold(0.0f32, f32::max);
+ if peak <= 0.0 {
+ return Vec::new();
+ }
+ let m = PATCH_RADIUS + 1;
+ let mut cand: Vec<Corner> = Vec::new();
+ for y in m..h - m {
+ for x in m..w - m {
+ let v = r[y * w + x];
+ if v < peak * 0.01 {
+ continue;
+ }
+ let is_max = (-1i64..=1).all(|dy| (-1i64..=1).all(|dx| (dx == 0 && dy == 0) || r[((y as i64 + dy) as usize) * w + (x as i64 + dx) as usize] <= v));
+ if !is_max {
+ continue;
+ }
+ if let Some(ok) = valid {
+ let all = (y - PATCH_RADIUS..=y + PATCH_RADIUS).step_by(5).all(|yy| (x - PATCH_RADIUS..=x + PATCH_RADIUS).step_by(5).all(|xx| ok[yy * w + xx]));
+ if !all {
+ continue;
+ }
+ }
+ cand.push(Corner { x: x as f32, y: y as f32, score: v });
+ }
+ }
+ cand.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.y.total_cmp(&b.y)).then(a.x.total_cmp(&b.x)));
+ // Minimum spacing via a coarse occupancy grid.
+ let cell = min_dist.max(1.0);
+ let (gw, gh) = ((w as f32 / cell).ceil() as usize + 1, (h as f32 / cell).ceil() as usize + 1);
+ let mut grid: Vec<Vec<(f32, f32)>> = vec![Vec::new(); gw * gh];
+ let mut out = Vec::new();
+ for c in cand {
+ let (gx, gy) = ((c.x / cell) as usize, (c.y / cell) as usize);
+ let near = (gy.saturating_sub(1)..=(gy + 1).min(gh - 1)).any(|yy| (gx.saturating_sub(1)..=(gx + 1).min(gw - 1)).any(|xx| grid[yy * gw + xx].iter().any(|&(px, py)| (px - c.x).hypot(py - c.y) < min_dist)));
+ if near {
+ continue;
+ }
+ grid[gy * gw + gx].push((c.x, c.y));
+ out.push(c);
+ if out.len() >= max {
+ break;
+ }
+ }
+ out
+}
+
+/// The 256 BRIEF test pairs (fixed, Gaussian around the centre, σ = 31/5, clipped to the patch).
+fn pairs() -> &'static [[f32; 4]; 256] {
+ static P: std::sync::OnceLock<[[f32; 4]; 256]> = std::sync::OnceLock::new();
+ P.get_or_init(|| {
+ let mut rng = Rng(0x0B21_EF00);
+ let mut gauss = || {
+ // Box–Muller.
+ let (u, v) = (rng.unit().max(1e-12), rng.unit());
+ ((-2.0 * u.ln()).sqrt() * (std::f64::consts::TAU * v).cos() * 31.0 / 5.0).clamp(-13.0, 13.0) as f32
+ };
+ let mut p = [[0.0f32; 4]; 256];
+ for q in &mut p {
+ *q = [gauss(), gauss(), gauss(), gauss()];
+ }
+ p
+ })
+}
+
+/// Steered-BRIEF descriptors for `corners` (orientation from the intensity centroid unless
+/// `upright`). Returns one descriptor per corner, in order.
+pub fn describe(w: usize, h: usize, img: &[f32], corners: &[Corner], upright: bool) -> Vec<Descriptor> {
+ let smooth = blur(w, h, img, 2);
+ let at = |x: f32, y: f32| -> f32 {
+ let (xi, yi) = ((x.round() as i64).clamp(0, w as i64 - 1) as usize, (y.round() as i64).clamp(0, h as i64 - 1) as usize);
+ smooth[yi * w + xi]
+ };
+ corners
+ .iter()
+ .map(|c| {
+ let (s, co) = if upright {
+ (0.0, 1.0)
+ } else {
+ let (mut m10, mut m01) = (0.0f32, 0.0f32);
+ let r = PATCH_RADIUS as i64;
+ for dy in -r..=r {
+ for dx in -r..=r {
+ if dx * dx + dy * dy <= r * r {
+ let v = at(c.x + dx as f32, c.y + dy as f32);
+ m10 += dx as f32 * v;
+ m01 += dy as f32 * v;
+ }
+ }
+ }
+ m01.atan2(m10).sin_cos()
+ };
+ let mut d = [0u64; 4];
+ for (i, p) in pairs().iter().enumerate() {
+ let rot = |x: f32, y: f32| (c.x + x * co - y * s, c.y + x * s + y * co);
+ let (ax, ay) = rot(p[0], p[1]);
+ let (bx, by) = rot(p[2], p[3]);
+ if at(ax, ay) < at(bx, by) {
+ d[i / 64] |= 1 << (i % 64);
+ }
+ }
+ d
+ })
+ .collect()
+}
+
+pub fn hamming(a: &Descriptor, b: &Descriptor) -> u32 {
+ a.iter().zip(b).map(|(x, y)| (x ^ y).count_ones()).sum()
+}
+
+/// Matches `(index in a, index in b)` passing the ratio test and the mutual-nearest check.
+pub fn match_descriptors(a: &[Descriptor], b: &[Descriptor], ratio: f32) -> Vec<(usize, usize)> {
+ let best = |d: &Descriptor, set: &[Descriptor]| -> Option<(usize, u32, u32)> {
+ let mut first = (usize::MAX, u32::MAX);
+ let mut second = u32::MAX;
+ for (j, e) in set.iter().enumerate() {
+ let h = hamming(d, e);
+ if h < first.1 {
+ second = first.1;
+ first = (j, h);
+ } else if h < second {
+ second = h;
+ }
+ }
+ (first.0 != usize::MAX).then_some((first.0, first.1, second))
+ };
+ let mut out = Vec::new();
+ for (i, d) in a.iter().enumerate() {
+ let Some((j, d1, d2)) = best(d, b) else { continue };
+ if d1 > 80 || (d2 != u32::MAX && d1 as f32 > ratio * d2 as f32) {
+ continue;
+ }
+ if best(&b[j], a).is_some_and(|(k, _, _)| k == i) {
+ out.push((i, j));
+ }
+ }
+ out
+}
+
+// ------------------------------------------------------------------ model fitting
+
+/// Solve the `n × n` system `a · x = b` (row-major) by Gaussian elimination with partial pivoting.
+fn solve(n: usize, mut a: Vec<f64>, mut b: Vec<f64>) -> Option<Vec<f64>> {
+ for c in 0..n {
+ let p = (c..n).max_by(|&i, &j| a[i * n + c].abs().total_cmp(&a[j * n + c].abs()))?;
+ if a[p * n + c].abs() < 1e-12 {
+ return None;
+ }
+ if p != c {
+ for k in 0..n {
+ a.swap(c * n + k, p * n + k);
+ }
+ b.swap(c, p);
+ }
+ for r in c + 1..n {
+ let f = a[r * n + c] / a[c * n + c];
+ for k in c..n {
+ a[r * n + k] -= f * a[c * n + k];
+ }
+ b[r] -= f * b[c];
+ }
+ }
+ let mut x = vec![0.0; n];
+ for r in (0..n).rev() {
+ let s: f64 = (r + 1..n).map(|k| a[r * n + k] * x[k]).sum();
+ x[r] = (b[r] - s) / a[r * n + r];
+ }
+ Some(x)
+}
+
+/// Least squares `min |A x − b|` through the normal equations.
+fn least_squares(rows: &[(Vec<f64>, f64)], n: usize) -> Option<Vec<f64>> {
+ let mut ata = vec![0.0; n * n];
+ let mut atb = vec![0.0; n];
+ for (r, b) in rows {
+ for i in 0..n {
+ atb[i] += r[i] * b;
+ for j in 0..n {
+ ata[i * n + j] += r[i] * r[j];
+ }
+ }
+ }
+ solve(n, ata, atb)
+}
+
+/// Hartley normalisation: centroid to the origin, mean distance √2.
+fn normaliser(pts: &[[f64; 2]]) -> Homography {
+ let n = pts.len().max(1) as f64;
+ let (cx, cy) = (pts.iter().map(|p| p[0]).sum::<f64>() / n, pts.iter().map(|p| p[1]).sum::<f64>() / n);
+ let d = pts.iter().map(|p| (p[0] - cx).hypot(p[1] - cy)).sum::<f64>() / n;
+ let s = if d > 1e-12 { std::f64::consts::SQRT_2 / d } else { 1.0 };
+ Homography([s, 0.0, -s * cx, 0.0, s, -s * cy, 0.0, 0.0, 1.0])
+}
+
+/// Fit a model mapping `src[i]` → `dst[i]` by least squares (exact for minimal sets).
+pub fn fit(model: Model, src: &[[f64; 2]], dst: &[[f64; 2]]) -> Option<Homography> {
+ let n = src.len();
+ match model {
+ Model::Translation => {
+ if n == 0 {
+ return None;
+ }
+ let (tx, ty) = src.iter().zip(dst).fold((0.0, 0.0), |(ax, ay), (s, d)| (ax + d[0] - s[0], ay + d[1] - s[1]));
+ Some(Homography([1.0, 0.0, tx / n as f64, 0.0, 1.0, ty / n as f64, 0.0, 0.0, 1.0]))
+ }
+ Model::Similarity => {
+ if n < 2 {
+ return None;
+ }
+ // x' = a·x − b·y + tx, y' = b·x + a·y + ty.
+ let rows: Vec<(Vec<f64>, f64)> = src.iter().zip(dst).flat_map(|(s, d)| [(vec![s[0], -s[1], 1.0, 0.0], d[0]), (vec![s[1], s[0], 0.0, 1.0], d[1])]).collect();
+ let v = least_squares(&rows, 4)?;
+ Some(Homography([v[0], -v[1], v[2], v[1], v[0], v[3], 0.0, 0.0, 1.0]))
+ }
+ Model::Homography => {
+ if n < 4 {
+ return None;
+ }
+ let (ts, td) = (normaliser(src), normaliser(dst));
+ let rows: Vec<(Vec<f64>, f64)> = src
+ .iter()
+ .zip(dst)
+ .flat_map(|(s, d)| {
+ let (x, y) = ts.apply(s[0], s[1]);
+ let (u, v) = td.apply(d[0], d[1]);
+ [(vec![x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y], u), (vec![0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y], v)]
+ })
+ .collect();
+ let h = least_squares(&rows, 8)?;
+ let hn = Homography([h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7], 1.0]);
+ let m = td.inverse()?.mul(&hn).mul(&ts);
+ let k = m.0[8];
+ (k.abs() > 1e-12).then(|| Homography(m.0.map(|v| v / k)))
+ }
+ }
+}
+
+fn min_points(model: Model) -> usize {
+ match model {
+ Model::Translation => 1,
+ Model::Similarity => 2,
+ Model::Homography => 4,
+ }
+}
+
+/// RANSAC: the model with the most correspondences within `threshold` pixels after `iters`
+/// random minimal samples, refit to its inliers. Returns the model and the inlier indices.
+pub fn ransac(model: Model, src: &[[f64; 2]], dst: &[[f64; 2]], iters: usize, threshold: f64, seed: u64) -> Option<(Homography, Vec<usize>)> {
+ let k = min_points(model);
+ let n = src.len();
+ if n < k {
+ return None;
+ }
+ let mut rng = Rng(seed ^ 0xA11C_0DE5);
+ let inliers_of = |h: &Homography| -> Vec<usize> {
+ (0..n)
+ .filter(|&i| {
+ let (x, y) = h.apply(src[i][0], src[i][1]);
+ x.is_finite() && (x - dst[i][0]).hypot(y - dst[i][1]) <= threshold
+ })
+ .collect()
+ };
+ let mut best: Option<(Homography, Vec<usize>)> = None;
+ for _ in 0..iters.max(1) {
+ let mut idx: Vec<usize> = Vec::with_capacity(k);
+ while idx.len() < k {
+ let i = rng.below(n);
+ if !idx.contains(&i) {
+ idx.push(i);
+ }
+ if n == k {
+ idx = (0..k).collect();
+ }
+ }
+ let (s, d): (Vec<[f64; 2]>, Vec<[f64; 2]>) = idx.iter().map(|&i| (src[i], dst[i])).unzip();
+ let Some(h) = fit(model, &s, &d) else { continue };
+ let inl = inliers_of(&h);
+ if best.as_ref().is_none_or(|(_, b)| inl.len() > b.len()) {
+ best = Some((h, inl));
+ }
+ }
+ let (h, inl) = best?;
+ if inl.len() < k {
+ return None;
+ }
+ // Refit to all inliers, then re-collect.
+ let (s, d): (Vec<[f64; 2]>, Vec<[f64; 2]>) = inl.iter().map(|&i| (src[i], dst[i])).unzip();
+ let h2 = fit(model, &s, &d).unwrap_or(h);
+ let inl2 = inliers_of(&h2);
+ Some(if inl2.len() >= inl.len() { (h2, inl2) } else { (h, inl) })
+}
+
+/// Register `moving` onto `reference` (both `w × h` luminance; optional validity masks for
+/// transparent areas). Returns the model mapping `moving` coordinates to `reference`
+/// coordinates and the inlier count.
+pub fn register(w: usize, h: usize, reference: &[f32], moving: &[f32], valid_ref: Option<&[bool]>, valid_mov: Option<&[bool]>, model: Model) -> Option<(Homography, usize)> {
+ let upright = model == Model::Translation;
+ let min_dist = (w.max(h) as f32 / 60.0).clamp(4.0, 24.0);
+ let ca = harris(w, h, reference, 600, min_dist, valid_ref);
+ let cb = harris(w, h, moving, 600, min_dist, valid_mov);
+ if ca.len() < 4 || cb.len() < 4 {
+ return None;
+ }
+ let (da, db) = (describe(w, h, reference, &ca, upright), describe(w, h, moving, &cb, upright));
+ let matches = match_descriptors(&db, &da, 0.85);
+ let src: Vec<[f64; 2]> = matches.iter().map(|&(i, _)| [cb[i].x as f64, cb[i].y as f64]).collect();
+ let dst: Vec<[f64; 2]> = matches.iter().map(|&(_, j)| [ca[j].x as f64, ca[j].y as f64]).collect();
+ let threshold = (w.max(h) as f64 / 400.0).clamp(1.5, 4.0);
+ let (hm, inl) = ransac(model, &src, &dst, 1000, threshold, 7)?;
+ (inl.len() >= min_points(model).max(6)).then_some((hm, inl.len()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Deterministic textured test image: blobs of varying brightness.
+ fn texture(w: usize, h: usize) -> Vec<f32> {
+ let mut rng = Rng(42);
+ let mut img = vec![0.3f32; w * h];
+ for _ in 0..140 {
+ let (cx, cy) = (rng.unit() * w as f64, rng.unit() * h as f64);
+ let r = 3.0 + rng.unit() * 9.0;
+ let v = rng.unit() as f32;
+ let sq = rng.unit() > 0.5;
+ for y in 0..h {
+ for x in 0..w {
+ let (dx, dy) = (x as f64 - cx, y as f64 - cy);
+ let inside = if sq { dx.abs() < r && dy.abs() < r * 0.6 } else { dx.hypot(dy) < r };
+ if inside {
+ img[y * w + x] = v;
+ }
+ }
+ }
+ }
+ img
+ }
+
+ /// Resample `img` by `h` (destination → source lookup with `inv`), bilinear, edge-clamped.
+ fn warp(w: usize, hgt: usize, img: &[f32], inv: &Homography) -> Vec<f32> {
+ let mut out = vec![0.3f32; w * hgt];
+ for y in 0..hgt {
+ for x in 0..w {
+ let (sx, sy) = inv.apply(x as f64, y as f64);
+ if sx < 0.0 || sy < 0.0 || sx >= (w - 1) as f64 || sy >= (hgt - 1) as f64 {
+ continue;
+ }
+ let (x0, y0) = (sx.floor() as usize, sy.floor() as usize);
+ let (tx, ty) = ((sx - x0 as f64) as f32, (sy - y0 as f64) as f32);
+ let p = |xx: usize, yy: usize| img[yy * w + xx];
+ let top = p(x0, y0) + (p(x0 + 1, y0) - p(x0, y0)) * tx;
+ let bot = p(x0, y0 + 1) + (p(x0 + 1, y0 + 1) - p(x0, y0 + 1)) * tx;
+ out[y * w + x] = top + (bot - top) * ty;
+ }
+ }
+ out
+ }
+
+ #[test]
+ fn harris_finds_square_corners() {
+ let (w, h) = (80, 80);
+ let mut img = vec![0.0f32; w * h];
+ for y in 30..50 {
+ for x in 30..50 {
+ img[y * w + x] = 1.0;
+ }
+ }
+ let c = harris(w, h, &img, 10, 5.0, None);
+ assert!(c.len() >= 4, "{c:?}");
+ for (x, y) in [(30.0, 30.0), (49.0, 49.0)] {
+ assert!(c.iter().any(|k| (k.x - x).abs() <= 2.0 && (k.y - y).abs() <= 2.0), "corner near ({x},{y}): {c:?}");
+ }
+ }
+
+ #[test]
+ fn fits_are_exact_on_clean_data() {
+ let src = [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0], [5.0, 3.0]];
+ let truth = Homography([1.1, 0.05, 3.0, -0.02, 0.95, -2.0, 0.001, 0.0005, 1.0]);
+ let dst: Vec<[f64; 2]> = src.iter().map(|p| {
+ let (x, y) = truth.apply(p[0], p[1]);
+ [x, y]
+ }).collect();
+ let h = fit(Model::Homography, &src, &dst).unwrap();
+ for p in &src {
+ let (a, b) = (h.apply(p[0], p[1]), truth.apply(p[0], p[1]));
+ assert!((a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6);
+ }
+ let sim = Homography([0.9, -0.2, 4.0, 0.2, 0.9, 1.0, 0.0, 0.0, 1.0]);
+ let dst: Vec<[f64; 2]> = src.iter().map(|p| {
+ let (x, y) = sim.apply(p[0], p[1]);
+ [x, y]
+ }).collect();
+ let h = fit(Model::Similarity, &src, &dst).unwrap();
+ assert!(h.0.iter().zip(sim.0).all(|(a, b)| (a - b).abs() < 1e-9));
+ }
+
+ #[test]
+ fn ransac_rejects_outliers() {
+ let mut src = Vec::new();
+ let mut dst = Vec::new();
+ for i in 0..40 {
+ let p = [(i * 7 % 50) as f64, (i * 13 % 50) as f64];
+ src.push(p);
+ dst.push(if i % 4 == 0 { [p[0] * 3.0 + 40.0, -p[1]] } else { [p[0] + 12.0, p[1] - 5.0] });
+ }
+ let (h, inl) = ransac(Model::Translation, &src, &dst, 100, 1.0, 1).unwrap();
+ assert_eq!(inl.len(), 30);
+ assert!((h.0[2] - 12.0).abs() < 1e-9 && (h.0[5] + 5.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn registers_translation_and_similarity() {
+ let (w, h) = (192, 160);
+ let reference = texture(w, h);
+ // The moving image is the reference shifted by (+9, −6): registration maps it back.
+ let shift = Homography([1.0, 0.0, 9.0, 0.0, 1.0, -6.0, 0.0, 0.0, 1.0]);
+ let moving = warp(w, h, &reference, &shift.inverse().unwrap());
+ let (m, n) = register(w, h, &reference, &moving, None, None, Model::Translation).unwrap();
+ assert!(n >= 6);
+ assert!((m.0[2] + 9.0).abs() < 1.0 && (m.0[5] - 6.0).abs() < 1.0, "{m:?}");
+ // Rotated 4° and scaled 1.03 about the centre.
+ let (c, s) = (4f64.to_radians().cos() * 1.03, 4f64.to_radians().sin() * 1.03);
+ let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0);
+ let sim = Homography([c, -s, cx - c * cx + s * cy, s, c, cy - s * cx - c * cy, 0.0, 0.0, 1.0]);
+ let moving = warp(w, h, &reference, &sim.inverse().unwrap());
+ let (m, _) = register(w, h, &reference, &moving, None, None, Model::Similarity).unwrap();
+ // m should undo sim: m · sim ≈ identity at a few points.
+ for p in [[40.0, 40.0], [150.0, 120.0], [96.0, 80.0]] {
+ let (x, y) = sim.apply(p[0], p[1]);
+ let (bx, by) = m.apply(x, y);
+ assert!((bx - p[0]).abs() < 1.5 && (by - p[1]).abs() < 1.5, "{p:?} → {bx},{by}");
+ }
+ }
+
+ #[test]
+ fn descriptors_are_deterministic() {
+ let (w, h) = (96, 96);
+ let img = texture(w, h);
+ let c = harris(w, h, &img, 50, 6.0, None);
+ assert_eq!(describe(w, h, &img, &c, false), describe(w, h, &img, &c, false));
+ assert_eq!(hamming(&[0, 0, 0, 0], &[1, 3, 0, u64::MAX]), 67);
+ }
+}
diff --git a/crates/algo/src/fxutil.rs b/crates/algo/src/fxutil.rs
new file mode 100644
index 000000000..dec6d7294
--- /dev/null
+++ b/crates/algo/src/fxutil.rs
@@ -0,0 +1,239 @@
+//! Shared helpers for the second filter batch: colour-model access, window
+//! buffers, single-channel box/Gaussian blurs and jittered cell points.
+
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_geom::Rect;
+use photocraft_raster::{from_rgba_into, to_rgba};
+
+use crate::Ctx;
+use crate::image::Image;
+use crate::noise::hash01;
+
+/// Max channels per pixel we keep on the stack (CMYK + alpha + spare).
+pub(crate) const MAXC: usize = 8;
+
+/// The context's model as an `f32` format (for colour conversions).
+#[inline]
+pub(crate) fn fmt(ctx: &Ctx) -> PixelFormat {
+ PixelFormat::new(ctx.mode, SampleType::F32, ctx.alpha)
+}
+
+/// Colour channels (excluding alpha).
+#[inline]
+pub(crate) fn ncol(ctx: &Ctx, n: usize) -> usize {
+ if ctx.alpha { n - 1 } else { n }
+}
+
+/// Whether channel values are ink amounts (1 = dark) rather than light.
+#[inline]
+pub(crate) fn subtractive(ctx: &Ctx) -> bool {
+ ctx.mode == ColorMode::Cmyk
+}
+
+/// Whether per-channel "brightness" operations should run on an RGB
+/// conversion instead of the native channels (Lab's a/b are not intensities).
+#[inline]
+pub(crate) fn via_rgb(ctx: &Ctx) -> bool {
+ ctx.mode == ColorMode::Lab
+}
+
+/// Document coordinates of the `i`th pixel of `out`.
+#[inline]
+pub(crate) fn xy(out: Rect, i: usize) -> (i32, i32) {
+ let w = out.width() as usize;
+ (out.x0 + (i % w) as i32, out.y0 + (i / w) as i32)
+}
+
+/// Straight sRGB RGBA of a native pixel.
+#[inline]
+pub(crate) fn rgba(ctx: &Ctx, px: &[f32]) -> [f32; 4] {
+ to_rgba(&fmt(ctx), px)
+}
+
+/// Writes straight sRGB RGBA into a native pixel.
+#[inline]
+pub(crate) fn set_rgba(ctx: &Ctx, px: &mut [f32], c: [f32; 4]) {
+ let mut tmp = [0.0f32; MAXC];
+ let n = from_rgba_into(&fmt(ctx), c, &mut tmp);
+ let m = n.min(px.len());
+ px[..m].copy_from_slice(&tmp[..m]);
+}
+
+/// A straight sRGB RGBA colour in the native model.
+pub(crate) fn native(ctx: &Ctx, c: [f32; 4]) -> [f32; MAXC] {
+ let mut tmp = [0.0f32; MAXC];
+ from_rgba_into(&fmt(ctx), c, &mut tmp);
+ tmp
+}
+
+/// Rec. 601 luma of a native pixel.
+#[inline]
+pub(crate) fn luma(ctx: &Ctx, px: &[f32]) -> f32 {
+ match ctx.mode {
+ ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => px[0],
+ ColorMode::Lab => px[0],
+ ColorMode::Rgb => 0.299 * px[0] + 0.587 * px[1] + 0.114 * px[2],
+ _ => {
+ let c = rgba(ctx, px);
+ 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]
+ }
+ }
+}
+
+/// Interleaved premultiplied copy of `src` over `win` (zero outside).
+pub(crate) fn premul_window(src: &Image, win: Rect, alpha: bool) -> Vec<f32> {
+ let n = src.ch;
+ let mut v = Vec::with_capacity(win.width() as usize * win.height() as usize * n);
+ for y in win.y0..win.y1 {
+ for x in win.x0..win.x1 {
+ let a = if alpha { src.get(x, y, n - 1) } else { 1.0 };
+ for c in 0..n {
+ let s = src.get(x, y, c);
+ v.push(if alpha && c < n - 1 { s * a } else { s });
+ }
+ }
+ }
+ v
+}
+
+/// Unpremultiplies one interleaved pixel in place.
+#[inline]
+pub(crate) fn unpremul_px(px: &mut [f32], alpha: bool) {
+ if !alpha {
+ return;
+ }
+ let n = px.len();
+ let a = px[n - 1];
+ for v in px.iter_mut().take(n - 1) {
+ *v = if a > 1e-7 { *v / a } else { 0.0 };
+ }
+}
+
+/// In-place running-sum box blur of every row of a `w × h × n` interleaved
+/// buffer with radius `r` (edges clamped). `scratch` must hold `w × n`.
+fn box_rows_n(buf: &mut [f32], w: usize, n: usize, r: usize, scratch: &mut Vec<f32>) {
+ if r == 0 || w == 0 {
+ return;
+ }
+ let norm = 1.0 / (2 * r + 1) as f64;
+ for row in buf.chunks_exact_mut(w * n) {
+ scratch.clear();
+ scratch.extend_from_slice(row);
+ // f64 sums: rounding must not depend on where a window starts (tile independence).
+ let at = |x: isize, c: usize| scratch[(x.clamp(0, w as isize - 1) as usize) * n + c] as f64;
+ for c in 0..n {
+ let mut acc: f64 = (-(r as isize)..=r as isize).map(|x| at(x, c)).sum();
+ for x in 0..w {
+ row[x * n + c] = (acc * norm) as f32;
+ acc += at(x as isize + r as isize + 1, c) - at(x as isize - r as isize, c);
+ }
+ }
+ }
+}
+
+/// Same as [`box_rows_n`] over columns (no transpose; walks with a stride).
+fn box_cols_n(buf: &mut [f32], w: usize, h: usize, n: usize, r: usize, scratch: &mut Vec<f32>) {
+ if r == 0 || h == 0 {
+ return;
+ }
+ let norm = 1.0 / (2 * r + 1) as f64;
+ for x in 0..w {
+ scratch.clear();
+ for y in 0..h {
+ scratch.extend_from_slice(&buf[(y * w + x) * n..(y * w + x + 1) * n]);
+ }
+ let at = |y: isize, c: usize| scratch[(y.clamp(0, h as isize - 1) as usize) * n + c] as f64;
+ for c in 0..n {
+ let mut acc: f64 = (-(r as isize)..=r as isize).map(|y| at(y, c)).sum();
+ for y in 0..h {
+ buf[(y * w + x) * n + c] = (acc * norm) as f32;
+ acc += at(y as isize + r as isize + 1, c) - at(y as isize - r as isize, c);
+ }
+ }
+ }
+}
+
+/// Box blur of an interleaved buffer (radius `r` in both directions).
+pub(crate) fn box_blur_n(buf: &mut [f32], w: usize, h: usize, n: usize, r: usize) {
+ let mut scratch = Vec::with_capacity(w.max(h) * n);
+ box_rows_n(buf, w, n, r, &mut scratch);
+ box_cols_n(buf, w, h, n, r, &mut scratch);
+}
+
+/// Odd box widths whose 3-fold convolution approximates a Gaussian of `sigma`
+/// (Kovesi 2010), returned as radii.
+pub(crate) fn gauss_box_radii(sigma: f32) -> [usize; 3] {
+ let n = 3.0f32;
+ let w_ideal = (12.0 * sigma * sigma / n + 1.0).sqrt();
+ let mut wl = w_ideal.floor() as i32;
+ if wl % 2 == 0 {
+ wl -= 1;
+ }
+ let wl = wl.max(1);
+ let wu = wl + 2;
+ let m = ((12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0)).round().clamp(0.0, n) as usize;
+ std::array::from_fn(|i| if i < m { (wl as usize - 1) / 2 } else { (wu as usize - 1) / 2 })
+}
+
+/// Approximate Gaussian blur (three box passes) of an interleaved buffer.
+/// Exact small kernels are not needed here: callers use it for smoothing
+/// fields and blur levels, where cost independent of `sigma` matters more.
+pub(crate) fn gauss_blur_n(buf: &mut [f32], w: usize, h: usize, n: usize, sigma: f32) {
+ if sigma < 0.3 {
+ return;
+ }
+ let mut scratch = Vec::with_capacity(w.max(h) * n);
+ for r in gauss_box_radii(sigma) {
+ box_rows_n(buf, w, n, r, &mut scratch);
+ }
+ for r in gauss_box_radii(sigma) {
+ box_cols_n(buf, w, h, n, r, &mut scratch);
+ }
+}
+
+/// Jittered feature point of grid cell `(cx, cy)` (cells of `cell` px anchored at `origin`).
+#[inline]
+pub(crate) fn cell_point(cx: i32, cy: i32, cell: f32, seed: u32, origin: (f32, f32)) -> (f32, f32) {
+ (origin.0 + (cx as f32 + 0.1 + 0.8 * hash01(cx, cy, 11, seed)) * cell, origin.1 + (cy as f32 + 0.1 + 0.8 * hash01(cx, cy, 12, seed)) * cell)
+}
+
+#[inline]
+pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
+ if e1 <= e0 {
+ return if x >= e1 { 1.0 } else { 0.0 };
+ }
+ let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+/// Adds the premultiplied bilinear sample of `src` at `(x, y)` (pixel centres at .5, edges
+/// clamped to `clip`, which must lie inside `src.rect`) into `acc`. A fast path for blurs that
+/// average many samples; unpremultiply the sum once at the end.
+#[inline]
+pub(crate) fn add_sample_premul(src: &Image, x: f32, y: f32, clip: Rect, alpha: bool, acc: &mut [f32]) {
+ let n = src.ch;
+ let fx = (x - 0.5).clamp(clip.x0 as f32, (clip.x1 - 1) as f32);
+ let fy = (y - 0.5).clamp(clip.y0 as f32, (clip.y1 - 1) as f32);
+ let (x0, y0) = (fx.floor() as i32, fy.floor() as i32);
+ let (x1, y1) = ((x0 + 1).min(clip.x1 - 1), (y0 + 1).min(clip.y1 - 1));
+ let (ax, ay) = (fx - x0 as f32, fy - y0 as f32);
+ let w = src.rect.width() as usize;
+ let idx = |xx: i32, yy: i32| ((yy - src.rect.y0) as usize * w + (xx - src.rect.x0) as usize) * n;
+ for (i, k) in [(idx(x0, y0), (1.0 - ax) * (1.0 - ay)), (idx(x1, y0), ax * (1.0 - ay)), (idx(x0, y1), (1.0 - ax) * ay), (idx(x1, y1), ax * ay)] {
+ if k <= 0.0 {
+ continue;
+ }
+ let px = &src.data[i..i + n];
+ let a = if alpha { px[n - 1] * k } else { k };
+ if alpha {
+ for c in 0..n - 1 {
+ acc[c] += px[c] * a;
+ }
+ acc[n - 1] += a;
+ } else {
+ for c in 0..n {
+ acc[c] += px[c] * a;
+ }
+ }
+ }
+}
diff --git a/crates/algo/src/gallery.rs b/crates/algo/src/gallery.rs
new file mode 100644
index 000000000..9cfff3764
--- /dev/null
+++ b/crates/algo/src/gallery.rs
@@ -0,0 +1,274 @@
+//! Blur Gallery: Tilt-Shift, Iris, Field (spatially varying Gaussian blur),
+//! Spin (rotational blur inside ellipses) and Path (motion along paths).
+//!
+//! Spatially varying blur interpolates between a stack of Gaussian levels
+//! (σ = 0 and a geometric series up to the maximum), each computed with a
+//! radius-independent box cascade, so cost grows with the number of levels,
+//! not the blur size.
+
+use photocraft_geom::Rect;
+
+use crate::fxutil::{MAXC, add_sample_premul, gauss_blur_n, premul_window, smoothstep, unpremul_px, xy};
+use crate::image::Image;
+use crate::{BlurPath, Ctx, FieldPin, IrisPin, SpinPin};
+
+/// Gaussian σ for a gallery blur amount in px.
+fn sigma_of(blur: f32) -> f32 {
+ blur.clamp(0.0, 500.0) * 0.6
+}
+
+/// Pixels read beyond an output tile for a maximum blur amount.
+pub(crate) fn reach(blur: f32) -> f32 {
+ 3.0 * sigma_of(blur) + 2.0
+}
+
+const LEVELS: usize = 6;
+
+/// Blurs `src` over `out` with a per-pixel σ (`sigma(x, y)`, ≤ `smax`).
+fn variable_blur(src: &Image, out: Rect, ctx: &Ctx, smax: f32, sigma: impl Fn(f32, f32) -> f32) -> Vec<f32> {
+ let n = src.ch;
+ if smax < 0.3 {
+ return src.crop(out);
+ }
+ let win = src.rect;
+ let (ww, wh) = (win.width() as usize, win.height() as usize);
+ let (ow, oh) = (out.width() as usize, out.height() as usize);
+ // Level σs: 0, then smax / 2^(LEVELS-1) … smax.
+ let lv: Vec<f32> = std::iter::once(0.0).chain((0..LEVELS).map(|k| smax / 2f32.powi((LEVELS - 1 - k) as i32))).collect();
+ let sig: Vec<f32> = (0..ow * oh).map(|i| {
+ let (x, y) = xy(out, i);
+ sigma(x as f32 + 0.5, y as f32 + 0.5).clamp(0.0, smax)
+ }).collect();
+ // Hat-function weight of level k for σ s.
+ let weight = |k: usize, s: f32| -> f32 {
+ let c = lv[k];
+ if k > 0 && s >= lv[k - 1] && s <= c {
+ (s - lv[k - 1]) / (c - lv[k - 1]).max(1e-6)
+ } else if k + 1 < lv.len() && s >= c && s <= lv[k + 1] {
+ (lv[k + 1] - s) / (lv[k + 1] - c).max(1e-6)
+ } else if k + 1 == lv.len() && s >= c {
+ 1.0
+ } else {
+ 0.0
+ }
+ };
+ let p = premul_window(src, win, ctx.alpha);
+ let mut acc = vec![0.0f32; ow * oh * n];
+ let mut buf = Vec::new();
+ for (k, &lvk) in lv.iter().enumerate() {
+ if !sig.iter().any(|&s| weight(k, s) > 0.0) {
+ continue;
+ }
+ let level: &[f32] = if k == 0 {
+ &p
+ } else {
+ buf.clear();
+ buf.extend_from_slice(&p);
+ gauss_blur_n(&mut buf, ww, wh, n, lvk);
+ &buf
+ };
+ for (i, &s) in sig.iter().enumerate() {
+ let wk = weight(k, s);
+ if wk <= 0.0 {
+ continue;
+ }
+ let (x, y) = xy(out, i);
+ let o = (((y - win.y0) as usize) * ww + (x - win.x0) as usize) * n;
+ for c in 0..n {
+ acc[i * n + c] += level[o + c] * wk;
+ }
+ }
+ }
+ for px in acc.chunks_exact_mut(n) {
+ unpremul_px(px, ctx.alpha);
+ }
+ acc
+}
+
+fn short_side(b: Rect) -> f32 {
+ (b.width().min(b.height()) as f32).max(1.0)
+}
+
+/// Tilt-Shift: a sharp band through the centre at `angle`, blurring with
+/// distance beyond `focus` over `transition` (both fractions of the shorter side).
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn tilt_shift(src: &Image, out: Rect, ctx: &Ctx, blur: f32, centre: (f32, f32), angle: f32, focus: f32, transition: f32) -> Vec<f32> {
+ let b = ctx.bounds;
+ let ss = short_side(b);
+ let (cx, cy) = (b.x0 as f32 + centre.0 * b.width() as f32, b.y0 as f32 + centre.1 * b.height() as f32);
+ // Band normal (the band runs along `angle`).
+ let (s, c) = angle.to_radians().sin_cos();
+ let (nx, ny) = (s, c);
+ let smax = sigma_of(blur);
+ let (f0, f1) = (focus.max(0.0), focus.max(0.0) + transition.max(1e-3));
+ variable_blur(src, out, ctx, smax, |x, y| {
+ let d = ((x - cx) * nx + (y - cy) * ny).abs() / ss;
+ smax * smoothstep(f0, f1, d)
+ })
+}
+
+/// Normalized (super)elliptical distance of a point from an iris/spin pin.
+#[allow(clippy::too_many_arguments)]
+fn pin_distance(x: f32, y: f32, b: Rect, px: f32, py: f32, rx: f32, ry: f32, angle: f32, m: f32) -> (f32, f32, f32) {
+ let ss = short_side(b);
+ let (cx, cy) = (b.x0 as f32 + px * b.width() as f32, b.y0 as f32 + py * b.height() as f32);
+ let (s, c) = angle.to_radians().sin_cos();
+ let (dx, dy) = (x - cx, y - cy);
+ let (u, v) = (dx * c + dy * s, -dx * s + dy * c);
+ let (u, v) = (u / (rx.max(1e-3) * ss), v / (ry.max(1e-3) * ss));
+ let e = if (m - 2.0).abs() < 1e-3 { (u * u + v * v).sqrt() } else { (u.abs().powf(m) + v.abs().powf(m)).powf(1.0 / m) };
+ (e, u, v)
+}
+
+/// Iris Blur: everything outside each pin's ellipse is blurred; the sharp
+/// core is `feather` of the ellipse. Sharpness from any pin wins.
+pub(crate) fn iris(src: &Image, out: Rect, ctx: &Ctx, pins: &[IrisPin]) -> Vec<f32> {
+ let b = ctx.bounds;
+ let smax = pins.iter().map(|p| sigma_of(p.blur)).fold(0.0, f32::max);
+ if pins.is_empty() {
+ return src.crop(out);
+ }
+ variable_blur(src, out, ctx, smax, |x, y| {
+ pins.iter()
+ .map(|p| {
+ let m = 2.0 + p.roundness.clamp(0.0, 100.0) / 100.0 * 6.0;
+ let (e, _, _) = pin_distance(x, y, b, p.x, p.y, p.radius_x, p.radius_y, p.angle, m);
+ sigma_of(p.blur) * smoothstep(p.feather.clamp(0.0, 0.999), 1.0, e)
+ })
+ .fold(f32::MAX, f32::min)
+ })
+}
+
+/// Field Blur: blur amounts at pins, interpolated by inverse squared distance.
+pub(crate) fn field(src: &Image, out: Rect, ctx: &Ctx, pins: &[FieldPin]) -> Vec<f32> {
+ let b = ctx.bounds;
+ if pins.is_empty() {
+ return src.crop(out);
+ }
+ let smax = pins.iter().map(|p| sigma_of(p.blur)).fold(0.0, f32::max);
+ let pts: Vec<(f32, f32, f32)> = pins.iter().map(|p| (b.x0 as f32 + p.x * b.width() as f32, b.y0 as f32 + p.y * b.height() as f32, sigma_of(p.blur))).collect();
+ variable_blur(src, out, ctx, smax, |x, y| {
+ let (mut ws, mut s) = (0.0f32, 0.0f32);
+ for &(px, py, sg) in &pts {
+ let w = 1.0 / ((x - px).powi(2) + (y - py).powi(2) + 1.0);
+ ws += w;
+ s += w * sg;
+ }
+ s / ws
+ })
+}
+
+/// Spin Blur: content inside each ellipse is blurred along arcs about its
+/// centre (`blur_angle` degrees of rotation), feathered at the rim.
+pub(crate) fn spin(src: &Image, out: Rect, ctx: &Ctx, pins: &[SpinPin]) -> Vec<f32> {
+ let n = src.ch;
+ let b = ctx.bounds;
+ let ss = short_side(b);
+ let mut res = src.crop(out);
+ let clip = b.intersect(&src.rect);
+ if clip.is_empty() {
+ return res;
+ }
+ let mut acc = [0.0f32; MAXC];
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ for p in pins {
+ let (e, u, v) = pin_distance(fx, fy, b, p.x, p.y, p.radius_x, p.radius_y, p.angle, 2.0);
+ if e >= 1.0 {
+ continue;
+ }
+ let theta = p.blur_angle.clamp(0.0, 360.0).to_radians();
+ let rpx = e * p.radius_x.max(p.radius_y) * ss;
+ // ~2 px between samples along the arc is smooth enough for a blur and halves the cost.
+ let m = ((theta * rpx / 2.0).ceil() as usize).clamp(2, 64);
+ let (cx, cy) = (b.x0 as f32 + p.x * b.width() as f32, b.y0 as f32 + p.y * b.height() as f32);
+ let (sa, ca) = p.angle.to_radians().sin_cos();
+ acc[..n].fill(0.0);
+ for j in 0..m {
+ let phi = theta * (j as f32 / (m - 1) as f32 - 0.5);
+ let (sp, cp) = phi.sin_cos();
+ // Rotate in the ellipse's normalized space, then map back.
+ let (ru, rv) = (u * cp - v * sp, u * sp + v * cp);
+ let (lu, lv) = (ru * p.radius_x * ss, rv * p.radius_y * ss);
+ let (sx, sy) = (cx + lu * ca - lv * sa, cy + lu * sa + lv * ca);
+ add_sample_premul(src, sx, sy, clip, ctx.alpha, &mut acc[..n]);
+ }
+ for v in acc.iter_mut().take(n) {
+ *v /= m as f32;
+ }
+ unpremul_px(&mut acc[..n], ctx.alpha);
+ let k = 1.0 - smoothstep(0.85, 1.0, e);
+ for c in 0..n {
+ px[c] += (acc[c] - px[c]) * k;
+ }
+ break;
+ }
+ }
+ res
+}
+
+/// Path Blur: motion blur whose direction follows the nearest paths
+/// (inverse-distance weighted tangents) and whose length is the path speed,
+/// optionally tapering toward each path's end.
+pub(crate) fn path(src: &Image, out: Rect, ctx: &Ctx, paths: &[BlurPath]) -> Vec<f32> {
+ let n = src.ch;
+ let b = ctx.bounds;
+ let (bw, bh) = (b.width() as f32, b.height() as f32);
+ // Segments in document space: (ax, ay, bx, by, path index, t0, t1 along path).
+ let mut segs = Vec::new();
+ for (pi, p) in paths.iter().enumerate() {
+ let pts: Vec<(f32, f32)> = p.points.iter().map(|q| (b.x0 as f32 + q[0] * bw, b.y0 as f32 + q[1] * bh)).collect();
+ let total: f32 = pts.windows(2).map(|w| (w[1].0 - w[0].0).hypot(w[1].1 - w[0].1)).sum::<f32>().max(1e-3);
+ let mut run = 0.0;
+ for w in pts.windows(2) {
+ let l = (w[1].0 - w[0].0).hypot(w[1].1 - w[0].1);
+ segs.push((w[0].0, w[0].1, w[1].0, w[1].1, pi, run / total, (run + l) / total));
+ run += l;
+ }
+ }
+ let mut res = src.crop(out);
+ let clip = b.intersect(&src.rect);
+ if segs.is_empty() || clip.is_empty() {
+ return res;
+ }
+ let mut acc = [0.0f32; MAXC];
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let (mut dx, mut dy, mut len, mut ws) = (0.0f32, 0.0f32, 0.0f32, 0.0f32);
+ for &(ax, ay, bx, by, pi, t0, t1) in &segs {
+ let (sx, sy) = (bx - ax, by - ay);
+ let l2 = (sx * sx + sy * sy).max(1e-6);
+ let t = (((fx - ax) * sx + (fy - ay) * sy) / l2).clamp(0.0, 1.0);
+ let d2 = (fx - ax - sx * t).powi(2) + (fy - ay - sy * t).powi(2);
+ let w = 1.0 / (d2 + 1.0);
+ let l = l2.sqrt();
+ let p = &paths[pi];
+ let along = t0 + (t1 - t0) * t;
+ dx += w * sx / l;
+ dy += w * sy / l;
+ len += w * p.speed.abs() * (1.0 - p.taper.clamp(0.0, 100.0) / 100.0 * along);
+ ws += w;
+ }
+ let m = (dx * dx + dy * dy).sqrt();
+ let len = len / ws;
+ if m < 1e-6 || len < 0.5 {
+ continue;
+ }
+ let (ux, uy) = (dx / m, dy / m);
+ // Samples ~1.5 px apart (bilinear fills the gaps), capped for very long blurs.
+ let steps = ((len / 1.5).ceil() as usize + 1).clamp(2, 64);
+ acc[..n].fill(0.0);
+ for j in 0..steps {
+ let o = len * (j as f32 / (steps - 1) as f32 - 0.5);
+ add_sample_premul(src, fx + ux * o, fy + uy * o, clip, ctx.alpha, &mut acc[..n]);
+ }
+ for v in acc.iter_mut().take(n) {
+ *v /= steps as f32;
+ }
+ unpremul_px(&mut acc[..n], ctx.alpha);
+ px.copy_from_slice(&acc[..n]);
+ }
+ res
+}
diff --git a/crates/algo/src/image.rs b/crates/algo/src/image.rs
index 273743401..f3afa6e7c 100644
--- a/crates/algo/src/image.rs
+++ b/crates/algo/src/image.rs
@@ -29,6 +29,30 @@ impl Image {
Image { rect, ch: s.channels(), data: s.read_region(rect) }
}
+ /// Reads `rect`, repeating the nearest pixel of `extent` for samples outside it. Photoshop
+ /// treats the canvas edge this way when filtering a layer, so a blur doesn't fade a
+ /// full-canvas layer to transparent at the document edge.
+ pub fn read_clamped(s: &Surface, rect: Rect, extent: Rect) -> Self {
+ let inner = rect.intersect(&extent);
+ if inner.is_empty() || inner == rect {
+ return Self::read(s, rect);
+ }
+ let src = Self::read(s, inner);
+ let mut img = Self::new(rect, src.ch);
+ let ch = src.ch;
+ let w = rect.width() as usize;
+ for y in rect.y0..rect.y1 {
+ let sy = y.clamp(inner.y0, inner.y1 - 1);
+ let row = (y - rect.y0) as usize * w * ch;
+ for x in rect.x0..rect.x1 {
+ let sx = x.clamp(inner.x0, inner.x1 - 1);
+ let d = row + (x - rect.x0) as usize * ch;
+ img.data[d..d + ch].copy_from_slice(src.px(sx, sy));
+ }
+ }
+ img
+ }
+
/// New zeroed image.
pub fn new(rect: Rect, ch: usize) -> Self {
Image { rect, ch, data: vec![0.0; rect.width() as usize * rect.height() as usize * ch] }
diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs
index 89de57b53..1af4eff3f 100644
--- a/crates/algo/src/lib.rs
+++ b/crates/algo/src/lib.rs
@@ -18,8 +18,19 @@
#![forbid(unsafe_code)]
mod blur;
+mod blur2;
+mod denoise;
mod distort;
+mod distort2;
+mod fxutil;
+mod gallery;
mod image;
+mod oil;
+mod other2;
+mod pixelate;
+mod render;
+mod stylize2;
+mod video;
mod noise;
mod other;
pub mod paint;
@@ -27,14 +38,28 @@ pub mod resample;
pub mod selection;
pub mod segment;
pub mod matting;
+pub mod quantize;
+pub mod stack;
+pub mod tone;
pub mod transform;
+pub mod warp;
+pub mod liquify;
+pub mod puppet;
+pub mod perspective;
pub mod poisson;
pub mod inpaint;
pub mod retouch;
+pub mod seam;
+pub mod content_aware;
+pub mod features;
+pub mod pyramid;
mod sharpen;
mod stylize;
pub use image::{Edge, Image};
+pub use params_ext::*;
+
+mod params_ext;
use photocraft_color::ColorMode;
use photocraft_geom::Rect;
@@ -169,6 +194,102 @@ pub enum FilterParams {
/// Amount −999…999 %.
Ripple { amount: f32, size: RippleSize },
PolarCoordinates { mode: PolarMode },
+
+ // ---- Pixelate ----
+ /// Max dot radius px (4–127); screen angles per channel in degrees.
+ ColorHalftone { max_radius: f32, angles: [f32; 4] },
+ /// Cell size px (3–300).
+ Crystallize { cell_size: f32, seed: u32 },
+ Facet,
+ Fragment,
+ Mezzotint { kind: MezzotintType, seed: u32 },
+ /// Cell size px (3–300); `background` is straight sRGB RGBA.
+ Pointillize { cell_size: f32, seed: u32, background: [f32; 4] },
+
+ // ---- Stylize ----
+ Diffuse { mode: DiffuseMode, seed: u32 },
+ /// Size px (2–255), depth (1–255).
+ Extrude { kind: ExtrudeType, size: f32, depth: f32, level_based: bool, solid_front: bool, mask_incomplete: bool, seed: u32 },
+ /// Photoshop's Oil Paint units: stylization 0.1–10, cleanliness 0–10, scale 0.1–10,
+ /// bristle detail 0–10, lighting angle degrees, shine 0–10.
+ OilPaint { stylization: f32, cleanliness: f32, scale: f32, bristle_detail: f32, lighting: bool, angle: f32, shine: f32 },
+ /// Tiles along the shorter side (1–99), max offset % (1–99).
+ Tiles { count: u32, max_offset: f32, fill: TileFill, foreground: [f32; 4], background: [f32; 4], seed: u32 },
+ /// Level 0–255; `upper` traces the side above the level.
+ TraceContour { level: f32, upper: bool },
+ Wind { method: WindMethod, from_right: bool, seed: u32 },
+
+ // ---- Distort ----
+ /// Scales in % (−999…999; 100 % = 128 px at full map contrast). The map is
+ /// supplied by the caller (another document, layer or file).
+ Displace {
+ horizontal: f32,
+ vertical: f32,
+ stretch: bool,
+ undefined: UndefinedAreas,
+ #[serde(skip)]
+ map: Option<std::sync::Arc<Image>>,
+ },
+ /// Curve points `[t, offset]`: t 0–1 top→bottom, offset −1…1 of half the width.
+ Shear { points: Vec<[f32; 2]>, undefined: UndefinedAreas },
+ /// Amount −100…100, ridges 0–20.
+ ZigZag { amount: f32, ridges: f32, style: ZigZagStyle },
+
+ // ---- Render ----
+ /// Variance 1–64, strength 1–64; colours straight sRGB RGBA.
+ Fibers { variance: f32, strength: f32, seed: u32, foreground: [f32; 4], background: [f32; 4] },
+ /// Brightness 10–300 %, centre as a fraction of the bounds.
+ LensFlare { brightness: f32, center_x: f32, center_y: f32, lens: LensType },
+ /// Gloss/metallic/exposure/ambience −100…100; bump height 0–100.
+ LightingEffects { lights: Vec<Light>, gloss: f32, metallic: f32, exposure: f32, ambience: f32, texture: TextureChannel, height: f32, white_is_high: bool },
+
+ // ---- Noise ----
+ /// Strength 0–10, the rest 0–100 %.
+ ReduceNoise { strength: f32, preserve_details: f32, reduce_color_noise: f32, sharpen_details: f32, remove_jpeg_artifact: bool },
+
+ // ---- Blur ----
+ /// Radius 0.1–100 px, threshold 0.1–100 levels.
+ SmartBlur { radius: f32, threshold: f32, quality: BlurQuality, mode: SmartBlurMode },
+ /// Iris radius 0–100 px, `blades` 3–8, curvature 0–100, rotation degrees;
+ /// focal distance 0–255; specular brightness 0–100 / threshold 0–255; noise 0–100.
+ LensBlur {
+ radius: f32,
+ blades: u32,
+ curvature: f32,
+ rotation: f32,
+ depth: DepthSource,
+ focal_distance: f32,
+ invert_depth: bool,
+ brightness: f32,
+ threshold: f32,
+ noise: f32,
+ distribution: Distribution,
+ monochromatic: bool,
+ seed: u32,
+ /// Depth for [`DepthSource::LayerMask`] (channel 0, document coordinates), supplied by the caller.
+ #[serde(skip)]
+ depth_map: Option<std::sync::Arc<Image>>,
+ },
+ /// Radius 5–1000 px.
+ ShapeBlur { radius: f32, shape: BlurShape },
+
+ // ---- Blur Gallery ----
+ /// Centre fractions, angle degrees, focus/transition as fractions of the bounds' shorter side.
+ TiltShift { blur: f32, center_x: f32, center_y: f32, angle: f32, focus: f32, transition: f32 },
+ IrisBlur { pins: Vec<IrisPin> },
+ FieldBlur { pins: Vec<FieldPin> },
+ SpinBlur { pins: Vec<SpinPin> },
+ PathBlur { paths: Vec<BlurPath> },
+
+ // ---- Other ----
+ /// 5×5 kernel (row-major, centre = index 12), divided by `scale`, plus `offset` levels.
+ Custom { kernel: Vec<f32>, scale: f32, offset: f32 },
+ HsbHsl { input: HsbModel, output: HsbModel },
+
+ // ---- Video ----
+ /// Removes the even (or odd) lines and rebuilds them by interpolation (or duplication).
+ DeInterlace { eliminate_even: bool, interpolate: bool },
+ NtscColors,
}
impl FilterParams {
@@ -197,6 +318,7 @@ impl FilterParams {
| FilterParams::Wave { .. }
| FilterParams::Ripple { .. }
| FilterParams::PolarCoordinates { .. } => Halo::Bounds,
+ other => halo_ext(other),
}
}
@@ -235,10 +357,75 @@ impl FilterParams {
FilterParams::Wave { .. } => "Wave",
FilterParams::Ripple { .. } => "Ripple",
FilterParams::PolarCoordinates { .. } => "Polar Coordinates",
+ FilterParams::ColorHalftone { .. } => "Color Halftone",
+ FilterParams::Crystallize { .. } => "Crystallize",
+ FilterParams::Facet => "Facet",
+ FilterParams::Fragment => "Fragment",
+ FilterParams::Mezzotint { .. } => "Mezzotint",
+ FilterParams::Pointillize { .. } => "Pointillize",
+ FilterParams::Diffuse { .. } => "Diffuse",
+ FilterParams::Extrude { .. } => "Extrude",
+ FilterParams::OilPaint { .. } => "Oil Paint",
+ FilterParams::Tiles { .. } => "Tiles",
+ FilterParams::TraceContour { .. } => "Trace Contour",
+ FilterParams::Wind { .. } => "Wind",
+ FilterParams::Displace { .. } => "Displace",
+ FilterParams::Shear { .. } => "Shear",
+ FilterParams::ZigZag { .. } => "ZigZag",
+ FilterParams::Fibers { .. } => "Fibers",
+ FilterParams::LensFlare { .. } => "Lens Flare",
+ FilterParams::LightingEffects { .. } => "Lighting Effects",
+ FilterParams::ReduceNoise { .. } => "Reduce Noise",
+ FilterParams::SmartBlur { .. } => "Smart Blur",
+ FilterParams::LensBlur { .. } => "Lens Blur",
+ FilterParams::ShapeBlur { .. } => "Shape Blur",
+ FilterParams::TiltShift { .. } => "Tilt-Shift",
+ FilterParams::IrisBlur { .. } => "Iris Blur",
+ FilterParams::FieldBlur { .. } => "Field Blur",
+ FilterParams::SpinBlur { .. } => "Spin Blur",
+ FilterParams::PathBlur { .. } => "Path Blur",
+ FilterParams::Custom { .. } => "Custom",
+ FilterParams::HsbHsl { .. } => "HSB/HSL",
+ FilterParams::DeInterlace { .. } => "De-Interlace",
+ FilterParams::NtscColors => "NTSC Colors",
}
}
}
+/// Halos of the second filter batch.
+fn halo_ext(p: &FilterParams) -> Halo {
+ let r = |v: f32| Halo::Radius(v.max(0.0).ceil() as i32 + 1);
+ match p {
+ FilterParams::ColorHalftone { max_radius, .. } => r(max_radius * 3.0),
+ FilterParams::Crystallize { cell_size, .. } => r(cell_size.max(1.0) * 3.0),
+ FilterParams::Pointillize { cell_size, .. } => r(cell_size.max(1.0) * 2.0),
+ FilterParams::Facet => r(3.0),
+ FilterParams::Fragment => r(4.0),
+ FilterParams::Mezzotint { .. } | FilterParams::HsbHsl { .. } | FilterParams::NtscColors => Halo::Radius(0),
+ FilterParams::Diffuse { .. } => r(1.0),
+ FilterParams::Extrude { size, depth, .. } => r(stylize2::extrude_reach(*depth) + size.clamp(2.0, 255.0) * 3.0 + 1.0),
+ FilterParams::OilPaint { stylization, scale, .. } => r(oil::reach(*stylization, *scale)),
+ FilterParams::Tiles { .. } => Halo::Bounds,
+ FilterParams::TraceContour { .. } => r(1.0),
+ FilterParams::Wind { method, .. } => r(stylize2::wind_reach(*method)),
+ FilterParams::Displace { .. } | FilterParams::Shear { .. } | FilterParams::ZigZag { .. } | FilterParams::SpinBlur { .. } => Halo::Bounds,
+ // Generators and per-pixel renders only need the bounds geometry (always in the context).
+ FilterParams::Fibers { .. } | FilterParams::LensFlare { .. } => Halo::Radius(0),
+ FilterParams::LightingEffects { .. } => r(1.0),
+ FilterParams::ReduceNoise { .. } => r(denoise::reach()),
+ FilterParams::SmartBlur { radius, .. } => r(*radius),
+ FilterParams::LensBlur { radius, .. } => r(*radius),
+ FilterParams::ShapeBlur { radius, .. } => r(*radius),
+ FilterParams::TiltShift { blur, .. } => r(gallery::reach(*blur)),
+ FilterParams::IrisBlur { pins } => r(gallery::reach(pins.iter().map(|p| p.blur).fold(0.0, f32::max))),
+ FilterParams::FieldBlur { pins } => r(gallery::reach(pins.iter().map(|p| p.blur).fold(0.0, f32::max))),
+ FilterParams::PathBlur { paths } => r(paths.iter().map(|p| p.speed.abs()).fold(0.0, f32::max) / 2.0 + 1.0),
+ FilterParams::Custom { .. } => r(2.0),
+ FilterParams::DeInterlace { .. } => r(1.0),
+ _ => Halo::Radius(0),
+ }
+}
+
/// Context a filter runs in.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Ctx {
@@ -293,6 +480,74 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec<f
),
FilterParams::Ripple { amount, size } => distort::ripple(src, out, ctx, *amount, *size),
FilterParams::PolarCoordinates { mode } => distort::polar(src, out, ctx, *mode),
+ FilterParams::ColorHalftone { max_radius, angles } => pixelate::color_halftone(src, out, ctx, *max_radius, *angles),
+ FilterParams::Crystallize { cell_size, seed } => pixelate::crystallize(src, out, ctx, *cell_size, *seed),
+ FilterParams::Facet => pixelate::facet(src, out, ctx),
+ FilterParams::Fragment => pixelate::fragment(src, out, ctx),
+ FilterParams::Mezzotint { kind, seed } => pixelate::mezzotint(src, out, ctx, *kind, *seed),
+ FilterParams::Pointillize { cell_size, seed, background } => pixelate::pointillize(src, out, ctx, *cell_size, *seed, *background),
+ FilterParams::Diffuse { mode, seed } => stylize2::diffuse(src, out, ctx, *mode, *seed),
+ FilterParams::Extrude { kind, size, depth, level_based, solid_front, mask_incomplete, seed } => {
+ stylize2::extrude(src, out, ctx, &stylize2::ExtrudeSpec { kind: *kind, size: *size, depth: *depth, level_based: *level_based, solid_front: *solid_front, mask_incomplete: *mask_incomplete, seed: *seed })
+ }
+ FilterParams::OilPaint { stylization, cleanliness, scale, bristle_detail, lighting, angle, shine } => oil::oil_paint(
+ src,
+ out,
+ ctx,
+ &oil::OilSpec { stylization: *stylization, cleanliness: *cleanliness, scale: *scale, bristle_detail: *bristle_detail, lighting: *lighting, angle: *angle, shine: *shine },
+ ),
+ FilterParams::Tiles { count, max_offset, fill, foreground, background, seed } => stylize2::tiles(src, out, ctx, *count, *max_offset, *fill, (*foreground, *background), *seed),
+ FilterParams::TraceContour { level, upper } => stylize2::trace_contour(src, out, ctx, *level, *upper),
+ FilterParams::Wind { method, from_right, seed } => stylize2::wind(src, out, ctx, *method, *from_right, *seed),
+ FilterParams::Displace { horizontal, vertical, stretch, undefined, map } => distort2::displace(src, out, ctx, (*horizontal, *vertical), *stretch, *undefined, map.as_deref()),
+ FilterParams::Shear { points, undefined } => distort2::shear(src, out, ctx, points, *undefined),
+ FilterParams::ZigZag { amount, ridges, style } => distort2::zigzag(src, out, ctx, *amount, *ridges, *style),
+ FilterParams::Fibers { variance, strength, seed, foreground, background } => render::fibers(src, out, ctx, *variance, *strength, *seed, (*foreground, *background)),
+ FilterParams::LensFlare { brightness, center_x, center_y, lens } => render::lens_flare(src, out, ctx, *brightness, (*center_x, *center_y), *lens),
+ FilterParams::LightingEffects { lights, gloss, metallic, exposure, ambience, texture, height, white_is_high } => render::lighting(
+ src,
+ out,
+ ctx,
+ &render::LightingSpec { lights, gloss: *gloss, metallic: *metallic, exposure: *exposure, ambience: *ambience, texture: *texture, height: *height, white_is_high: *white_is_high },
+ ),
+ FilterParams::ReduceNoise { strength, preserve_details, reduce_color_noise, sharpen_details, remove_jpeg_artifact } => denoise::reduce_noise(
+ src,
+ out,
+ ctx,
+ &denoise::DenoiseSpec { strength: *strength, preserve: *preserve_details, color: *reduce_color_noise, sharpen: *sharpen_details, jpeg: *remove_jpeg_artifact },
+ ),
+ FilterParams::SmartBlur { radius, threshold, quality, mode } => blur2::smart_blur(src, out, ctx, *radius, *threshold, *quality, *mode),
+ FilterParams::LensBlur { radius, blades, curvature, rotation, depth, focal_distance, invert_depth, brightness, threshold, noise, distribution, monochromatic, seed, depth_map } => blur2::lens_blur(
+ src,
+ out,
+ ctx,
+ &blur2::LensSpec {
+ radius: *radius,
+ blades: *blades,
+ curvature: *curvature,
+ rotation: *rotation,
+ depth: *depth,
+ focal: *focal_distance,
+ invert: *invert_depth,
+ brightness: *brightness,
+ threshold: *threshold,
+ noise: *noise,
+ distribution: *distribution,
+ mono: *monochromatic,
+ seed: *seed,
+ depth_map: depth_map.as_deref(),
+ },
+ ),
+ FilterParams::ShapeBlur { radius, shape } => blur2::shape_blur(src, out, ctx, *radius, *shape),
+ FilterParams::TiltShift { blur, center_x, center_y, angle, focus, transition } => gallery::tilt_shift(src, out, ctx, *blur, (*center_x, *center_y), *angle, *focus, *transition),
+ FilterParams::IrisBlur { pins } => gallery::iris(src, out, ctx, pins),
+ FilterParams::FieldBlur { pins } => gallery::field(src, out, ctx, pins),
+ FilterParams::SpinBlur { pins } => gallery::spin(src, out, ctx, pins),
+ FilterParams::PathBlur { paths } => gallery::path(src, out, ctx, paths),
+ FilterParams::Custom { kernel, scale, offset } => other2::custom(src, out, ctx, kernel, *scale, *offset),
+ FilterParams::HsbHsl { input, output } => other2::hsb_hsl(src, out, ctx, *input, *output),
+ FilterParams::DeInterlace { eliminate_even, interpolate } => video::deinterlace(src, out, ctx, *eliminate_even, *interpolate),
+ FilterParams::NtscColors => video::ntsc(src, out, ctx),
}
}
@@ -323,11 +578,27 @@ pub fn output_area(params: &FilterParams, content: Rect, bounds: Rect, selection
/// Applies a filter to `area` of `surface`, mixing with the original by the
/// selection coverage (channel 0 of `selection`). Returns the new surface.
pub fn apply(surface: &Surface, params: &FilterParams, area: Rect, bounds: Rect, selection: Option<&Surface>) -> Surface {
- apply_tiled(surface, params, area, bounds, selection, TILE)
+ apply_tiled(surface, params, area, bounds, selection, auto_tile(params), None)
+}
+
+/// [`apply`] for a layer in a document: neighbourhood filters repeat the edge pixels of `extent`
+/// (the canvas plus any off-canvas pixels the layer has) instead of reading transparency beyond
+/// it, and the output is clipped to `extent`, as Photoshop does at the canvas edge.
+pub fn apply_in(surface: &Surface, params: &FilterParams, area: Rect, bounds: Rect, selection: Option<&Surface>, extent: Rect) -> Surface {
+ apply_tiled(surface, params, area.intersect(&extent), bounds, selection, auto_tile(params), Some(extent))
}
-/// [`apply`] with an explicit tile size (tests use it to check tile independence).
-pub fn apply_tiled(surface: &Surface, params: &FilterParams, area: Rect, bounds: Rect, selection: Option<&Surface>, tile: i32) -> Surface {
+/// Results do not depend on the tiling, so wide-halo filters use bigger tiles to keep the
+/// re-read margin (and its cost) below ~2× the tile area.
+fn auto_tile(params: &FilterParams) -> i32 {
+ match params.halo() {
+ Halo::Radius(r) => TILE.max((2 * r + 63) / 64 * 64).min(2048),
+ Halo::Bounds => TILE,
+ }
+}
+
+/// [`apply`] / [`apply_in`] with an explicit tile size (tests use it to check tile independence).
+pub fn apply_tiled(surface: &Surface, params: &FilterParams, area: Rect, bounds: Rect, selection: Option<&Surface>, tile: i32, extent: Option<Rect>) -> Surface {
let mut out = surface.clone();
if area.is_empty() {
return out;
@@ -351,7 +622,10 @@ pub fn apply_tiled(surface: &Surface, params: &FilterParams, area: Rect, bounds:
let src = match (&shared, halo) {
(Some(s), _) => s,
(None, Halo::Radius(r)) => {
- owned = Image::read(surface, t.inflate(r));
+ owned = match extent {
+ Some(e) => Image::read_clamped(surface, t.inflate(r), e),
+ None => Image::read(surface, t.inflate(r)),
+ };
&owned
}
(None, Halo::Bounds) => unreachable!("shared image exists for global filters"),
@@ -390,3 +664,5 @@ pub fn apply_tiled(surface: &Surface, params: &FilterParams, area: Rect, bounds:
#[cfg(test)]
mod tests;
+#[cfg(test)]
+mod tests_ext;
diff --git a/crates/algo/src/liquify.rs b/crates/algo/src/liquify.rs
new file mode 100644
index 000000000..a461e5b8a
--- /dev/null
+++ b/crates/algo/src/liquify.rs
@@ -0,0 +1,808 @@
+//! Filter › Liquify: a dense displacement field edited by brush strokes, then used to resample
+//! the layer once.
+//!
+//! The field stores, for every node of a regular grid (one node per `cell` document pixels), the
+//! offset `d` such that output pixel `p` shows the source at `p + d(p)` (an inverse map, so
+//! applying it never leaves holes). Strokes are plain data ([`LiquifyStroke`]: tool, brush and
+//! points), applied in order by [`LiquifyField::apply_stroke`]; replaying the same strokes on the
+//! same bounds gives the same field bit for bit, which is what makes the filter a replayable
+//! command and a smart filter.
+//!
+//! Every tool is written as "where does the new output at `p` come from in the current output":
+//! `q = M(p)` (Forward Warp: `p - kΔ`, Twirl: a rotation about the brush centre, Pucker/Bloat: a
+//! scaling about it), so the new field is `d'(p) = q + d(q) - p`, sampled bilinearly from the
+//! field as it was before the dab. Reconstruct scales `d` toward zero and Smooth relaxes it toward
+//! its local mean. Freeze/Thaw paint a mask that scales every tool's strength down.
+//!
+//! [`apply_liquify`] upsamples the field with Catmull-Rom (bicubic) per pixel and samples the
+//! source (premultiplied, bicubic), tile by tile in parallel; tiles where the field is zero are
+//! copied untouched. [`ProxyImage::render`] is the cheap preview path: bilinear field and
+//! bilinear source on a downsampled RGBA copy, re-rendered only where a dab changed things.
+
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde::{Deserialize, Serialize};
+
+/// The Liquify tools (Photoshop's left tool strip, minus Hand/Zoom/Face).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum LiquifyTool {
+ #[default]
+ ForwardWarp,
+ Reconstruct,
+ Smooth,
+ TwirlCw,
+ TwirlCcw,
+ Pucker,
+ Bloat,
+ PushLeft,
+ Freeze,
+ Thaw,
+ /// The Reconstruct… button: scales the whole (unfrozen) field toward zero by `amount` %.
+ ReconstructAll,
+}
+
+impl LiquifyTool {
+ pub const ALL: [LiquifyTool; 10] = [
+ LiquifyTool::ForwardWarp,
+ LiquifyTool::Reconstruct,
+ LiquifyTool::Smooth,
+ LiquifyTool::TwirlCw,
+ LiquifyTool::TwirlCcw,
+ LiquifyTool::Pucker,
+ LiquifyTool::Bloat,
+ LiquifyTool::PushLeft,
+ LiquifyTool::Freeze,
+ LiquifyTool::Thaw,
+ ];
+
+ pub fn label(self) -> &'static str {
+ match self {
+ LiquifyTool::ForwardWarp => "Forward Warp",
+ LiquifyTool::Reconstruct => "Reconstruct",
+ LiquifyTool::Smooth => "Smooth",
+ LiquifyTool::TwirlCw => "Twirl Clockwise",
+ LiquifyTool::TwirlCcw => "Twirl Counterclockwise",
+ LiquifyTool::Pucker => "Pucker",
+ LiquifyTool::Bloat => "Bloat",
+ LiquifyTool::PushLeft => "Push Left",
+ LiquifyTool::Freeze => "Freeze Mask",
+ LiquifyTool::Thaw => "Thaw Mask",
+ LiquifyTool::ReconstructAll => "Reconstruct All",
+ }
+ }
+
+ /// Tools that act while the brush is held still (each recorded point is a dab).
+ pub fn is_stationary(self) -> bool {
+ !matches!(self, LiquifyTool::ForwardWarp | LiquifyTool::PushLeft)
+ }
+}
+
+fn d_size() -> f64 {
+ 100.0
+}
+fn d_density() -> f64 {
+ 50.0
+}
+fn d_pressure() -> f64 {
+ 100.0
+}
+fn d_rate() -> f64 {
+ 80.0
+}
+
+/// One brush stroke: the tool, its brush options and the points it passed through
+/// (`[x, y]` or `[x, y, pressure 0..1]`, document pixels).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LiquifyStroke {
+ #[serde(default)]
+ pub tool: LiquifyTool,
+ /// Brush diameter (px).
+ #[serde(default = "d_size")]
+ pub size: f64,
+ /// Edge feathering, 0 (hard) ..100 (soft).
+ #[serde(default = "d_density")]
+ pub density: f64,
+ /// Overall strength, 0..100.
+ #[serde(default = "d_pressure")]
+ pub pressure: f64,
+ /// Speed of the stationary tools, 0..100.
+ #[serde(default = "d_rate")]
+ pub rate: f64,
+ #[serde(default)]
+ pub points: Vec<Vec<f64>>,
+ /// `reconstructAll` only: how much to restore, 0..100.
+ #[serde(default)]
+ pub amount: Option<f64>,
+}
+
+impl LiquifyStroke {
+ pub fn new(tool: LiquifyTool, size: f64) -> Self {
+ LiquifyStroke { tool, size, density: d_density(), pressure: d_pressure(), rate: d_rate(), points: Vec::new(), amount: None }
+ }
+
+ /// Validates the stroke (finite numbers, 2 or 3 per point).
+ pub fn validate(&self) -> Result<(), String> {
+ if !(self.size.is_finite() && self.size >= 1.0 && self.size <= 15000.0) {
+ return Err(format!("brush size {} out of range 1..15000", self.size));
+ }
+ for p in &self.points {
+ if !(2..=3).contains(&p.len()) || p.iter().any(|v| !v.is_finite()) {
+ return Err("stroke points are [x, y] or [x, y, pressure]".into());
+ }
+ }
+ Ok(())
+ }
+}
+
+/// The displacement field plus the freeze mask, over `bounds` (document pixels).
+#[derive(Clone, Debug, PartialEq)]
+pub struct LiquifyField {
+ pub bounds: Rect,
+ /// Document pixels per field node.
+ pub cell: f64,
+ pub w: usize,
+ pub h: usize,
+ /// Inverse displacement per node, row-major.
+ pub d: Vec<[f32; 2]>,
+ /// Freeze mask per node (0 = free, 1 = frozen).
+ pub freeze: Vec<f32>,
+}
+
+/// The default field resolution for `bounds`: 2 px per node up to 4 MP, 4 px beyond.
+pub fn auto_cell(bounds: Rect) -> f64 {
+ if bounds.size().area() <= 4_200_000 { 2.0 } else { 4.0 }
+}
+
+impl LiquifyField {
+ pub fn new(bounds: Rect, cell: f64) -> Self {
+ let cell = cell.clamp(1.0, 64.0);
+ let w = (f64::from(bounds.width()) / cell).ceil() as usize + 2;
+ let h = (f64::from(bounds.height()) / cell).ceil() as usize + 2;
+ LiquifyField { bounds, cell, w, h, d: vec![[0.0; 2]; w * h], freeze: vec![0.0; w * h] }
+ }
+
+ /// Document position of node (i, j) (node 0 sits on the first pixel centre).
+ #[inline]
+ pub fn node_pos(&self, i: usize, j: usize) -> [f64; 2] {
+ [f64::from(self.bounds.x0) + 0.5 + i as f64 * self.cell, f64::from(self.bounds.y0) + 0.5 + j as f64 * self.cell]
+ }
+
+ /// Field coordinates of a document point.
+ #[inline]
+ fn to_grid(&self, x: f64, y: f64) -> (f64, f64) {
+ ((x - f64::from(self.bounds.x0) - 0.5) / self.cell, (y - f64::from(self.bounds.y0) - 0.5) / self.cell)
+ }
+
+ pub fn is_identity(&self) -> bool {
+ self.d.iter().all(|v| v[0] == 0.0 && v[1] == 0.0)
+ }
+
+ /// Largest displacement magnitude (px).
+ pub fn max_displacement(&self) -> f32 {
+ self.d.iter().map(|v| v[0].hypot(v[1])).fold(0.0, f32::max)
+ }
+
+ /// Bilinear displacement at a document point (zero outside the field).
+ pub fn sample(&self, x: f64, y: f64) -> [f64; 2] {
+ let (gx, gy) = self.to_grid(x, y);
+ bilinear(&self.d, self.w, self.h, gx, gy)
+ }
+
+ /// Freeze value at a document point (bilinear).
+ pub fn freeze_at(&self, x: f64, y: f64) -> f32 {
+ let (gx, gy) = self.to_grid(x, y);
+ let gx = gx.clamp(0.0, (self.w - 1) as f64);
+ let gy = gy.clamp(0.0, (self.h - 1) as f64);
+ let (i, j) = ((gx as usize).min(self.w - 2), (gy as usize).min(self.h - 2));
+ let (fx, fy) = ((gx - i as f64) as f32, (gy - j as f64) as f32);
+ let at = |i: usize, j: usize| self.freeze[j * self.w + i];
+ (at(i, j) * (1.0 - fx) + at(i + 1, j) * fx) * (1.0 - fy) + (at(i, j + 1) * (1.0 - fx) + at(i + 1, j + 1) * fx) * fy
+ }
+
+ /// Applies one stroke. Returns the document rectangle whose output changed.
+ pub fn apply_stroke(&mut self, s: &LiquifyStroke) -> Rect {
+ if s.tool == LiquifyTool::ReconstructAll {
+ let k = (s.amount.unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32;
+ for (v, f) in self.d.iter_mut().zip(&self.freeze) {
+ let m = 1.0 - k * (1.0 - f);
+ v[0] *= m;
+ v[1] *= m;
+ }
+ return self.bounds;
+ }
+ let pts: Vec<[f64; 3]> = s.points.iter().filter(|p| p.len() >= 2).map(|p| [p[0], p[1], p.get(2).copied().unwrap_or(1.0).clamp(0.0, 1.0)]).collect();
+ let mut dirty = Rect::EMPTY;
+ let Some(&first) = pts.first() else { return dirty };
+ let r = (s.size / 2.0).max(0.5);
+ let spacing = (r * 0.2).max(0.5);
+ if pts.len() == 1 || pts.windows(2).all(|w| w[0][..2] == w[1][..2]) {
+ // The brush never moved: stationary tools dab at every recorded point, warps do nothing.
+ if !s.tool.is_stationary() {
+ return dirty;
+ }
+ for p in &pts {
+ dirty = dirty.union(&self.dab(s, [p[0], p[1]], [0.0, 0.0], p[2]));
+ }
+ return dirty;
+ }
+ if s.tool.is_stationary() {
+ dirty = dirty.union(&self.dab(s, [first[0], first[1]], [0.0, 0.0], first[2]));
+ }
+ for w in pts.windows(2) {
+ let (a, b) = (w[0], w[1]);
+ let len = (b[0] - a[0]).hypot(b[1] - a[1]);
+ if len == 0.0 {
+ if s.tool.is_stationary() {
+ dirty = dirty.union(&self.dab(s, [b[0], b[1]], [0.0, 0.0], b[2]));
+ }
+ continue;
+ }
+ let steps = (len / spacing).ceil().max(1.0) as usize;
+ for k in 1..=steps {
+ let t0 = (k - 1) as f64 / steps as f64;
+ let t1 = k as f64 / steps as f64;
+ let c = [a[0] + (b[0] - a[0]) * t1, a[1] + (b[1] - a[1]) * t1];
+ let delta = [(b[0] - a[0]) * (t1 - t0), (b[1] - a[1]) * (t1 - t0)];
+ let pr = a[2] + (b[2] - a[2]) * t1;
+ // Forward Warp centres the dab where the brush was (it drags what is under it).
+ let centre = if s.tool.is_stationary() { c } else { [c[0] - delta[0], c[1] - delta[1]] };
+ dirty = dirty.union(&self.dab(s, centre, delta, pr));
+ }
+ }
+ dirty
+ }
+
+ /// One dab at `c` with brush motion `delta`. Returns the document rect it affected.
+ fn dab(&mut self, s: &LiquifyStroke, c: [f64; 2], delta: [f64; 2], point_pressure: f64) -> Rect {
+ let r = (s.size / 2.0).max(0.5);
+ let strength = (s.pressure / 100.0).clamp(0.0, 1.0) * point_pressure;
+ let rate = (s.rate / 100.0).clamp(0.0, 1.0);
+ let density = (s.density / 100.0).clamp(0.0, 1.0);
+ if strength <= 0.0 {
+ return Rect::EMPTY;
+ }
+ let (gx0, gy0) = self.to_grid(c[0] - r, c[1] - r);
+ let (gx1, gy1) = self.to_grid(c[0] + r, c[1] + r);
+ let i0 = gx0.floor().max(0.0) as usize;
+ let j0 = gy0.floor().max(0.0) as usize;
+ let i1 = (gx1.ceil().max(-1.0) as isize).min(self.w as isize - 1);
+ let j1 = (gy1.ceil().max(-1.0) as isize).min(self.h as isize - 1);
+ if i1 < i0 as isize || j1 < j0 as isize {
+ return Rect::EMPTY;
+ }
+ let (i1, j1) = (i1 as usize, j1 as usize);
+ // Snapshot of the affected nodes plus a margin (sampling reads around them).
+ let m = ((delta[0].abs().max(delta[1].abs()) + r * 0.2) / self.cell).ceil() as usize + 2;
+ let (si0, sj0) = (i0.saturating_sub(m), j0.saturating_sub(m));
+ let (si1, sj1) = ((i1 + m).min(self.w - 1), (j1 + m).min(self.h - 1));
+ let sw = si1 - si0 + 1;
+ let sh = sj1 - sj0 + 1;
+ let mut snap = Vec::with_capacity(sw * sh);
+ for j in sj0..=sj1 {
+ snap.extend_from_slice(&self.d[j * self.w + si0..=j * self.w + si1]);
+ }
+ let old = |gx: f64, gy: f64| -> [f64; 2] {
+ let (lx, ly) = (gx - si0 as f64, gy - sj0 as f64);
+ if lx >= 0.0 && ly >= 0.0 && lx <= (sw - 1) as f64 && ly <= (sh - 1) as f64 {
+ bilinear(&snap, sw, sh, lx, ly)
+ } else {
+ // Outside the snapshot nothing changed: read the live field.
+ bilinear(&self.d, self.w, self.h, gx, gy)
+ }
+ };
+ let mut writes: Vec<(usize, [f32; 2], f32)> = Vec::with_capacity((i1 - i0 + 1) * (j1 - j0 + 1));
+ let inv_cell = 1.0 / self.cell;
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let p = self.node_pos(i, j);
+ let (dx, dy) = (p[0] - c[0], p[1] - c[1]);
+ let t2 = (dx * dx + dy * dy) / (r * r);
+ if t2 >= 1.0 {
+ continue;
+ }
+ let soft = (1.0 - t2) * (1.0 - t2);
+ let fall = (1.0 - density) + density * soft;
+ let idx = j * self.w + i;
+ let k_raw = strength * fall;
+ if s.tool == LiquifyTool::Freeze || s.tool == LiquifyTool::Thaw {
+ let f = self.freeze[idx];
+ let v = if s.tool == LiquifyTool::Freeze { (f as f64 + k_raw).min(1.0) } else { (f as f64 - k_raw).max(0.0) };
+ writes.push((idx, self.d[idx], v as f32));
+ continue;
+ }
+ let k = k_raw * (1.0 - f64::from(self.freeze[idx]));
+ if k <= 0.0 {
+ continue;
+ }
+ let cur = self.d[idx];
+ let new = match s.tool {
+ LiquifyTool::Reconstruct => {
+ let a = (1.0 - k * (0.1 + 0.4 * rate)) as f32;
+ [cur[0] * a, cur[1] * a]
+ }
+ LiquifyTool::Smooth => {
+ let (gx, gy) = ((i - si0) as isize, (j - sj0) as isize);
+ let at = |x: isize, y: isize| snap[(y.clamp(0, sh as isize - 1) as usize) * sw + x.clamp(0, sw as isize - 1) as usize];
+ let mut mean = [0.0f32; 2];
+ for (ox, oy) in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, -1), (-1, 1), (1, 1)] {
+ let v = at(gx + ox, gy + oy);
+ mean[0] += v[0] / 8.0;
+ mean[1] += v[1] / 8.0;
+ }
+ let a = (k * (0.1 + 0.4 * rate)) as f32;
+ [cur[0] + (mean[0] - cur[0]) * a, cur[1] + (mean[1] - cur[1]) * a]
+ }
+ _ => {
+ let q = match s.tool {
+ LiquifyTool::ForwardWarp => [p[0] - k * delta[0], p[1] - k * delta[1]],
+ // Left of the stroke direction (y down): (dx, dy) → (dy, -dx).
+ LiquifyTool::PushLeft => [p[0] - k * delta[1], p[1] + k * delta[0]],
+ LiquifyTool::TwirlCw | LiquifyTool::TwirlCcw => {
+ let th = k * rate * 0.12 * if s.tool == LiquifyTool::TwirlCw { 1.0 } else { -1.0 };
+ // Content turns by +th, so sample at the point turned by -th.
+ let (sn, cs) = (-th).sin_cos();
+ [c[0] + dx * cs - dy * sn, c[1] + dx * sn + dy * cs]
+ }
+ LiquifyTool::Pucker => {
+ let a = 1.0 + k * rate * 0.06;
+ [c[0] + dx * a, c[1] + dy * a]
+ }
+ _ => {
+ let a = 1.0 - k * rate * 0.06;
+ [c[0] + dx * a, c[1] + dy * a]
+ }
+ };
+ let (qx, qy) = ((q[0] - p[0]) * inv_cell + i as f64, (q[1] - p[1]) * inv_cell + j as f64);
+ let dq = old(qx, qy);
+ [(q[0] + dq[0] - p[0]) as f32, (q[1] + dq[1] - p[1]) as f32]
+ }
+ };
+ writes.push((idx, new, self.freeze[idx]));
+ }
+ }
+ for (idx, d, f) in writes {
+ self.d[idx] = d;
+ self.freeze[idx] = f;
+ }
+ let pad = r.ceil() as i32 + 2;
+ Rect::new(c[0].floor() as i32 - pad, c[1].floor() as i32 - pad, c[0].ceil() as i32 + pad, c[1].ceil() as i32 + pad).intersect(&self.bounds)
+ }
+
+ /// Replays strokes on a fresh field.
+ pub fn from_strokes(bounds: Rect, cell: f64, strokes: &[LiquifyStroke]) -> Self {
+ let mut f = LiquifyField::new(bounds, cell);
+ for s in strokes {
+ f.apply_stroke(s);
+ }
+ f
+ }
+
+ /// Catmull-Rom (bicubic) displacement at grid coordinates.
+ fn sample_cubic(&self, gx: f64, gy: f64, wx: &[f64; 4], wy: &[f64; 4]) -> [f64; 2] {
+ let (ix, iy) = (gx.floor() as isize, gy.floor() as isize);
+ let mut acc = [0.0f64; 2];
+ for (jj, wyj) in wy.iter().enumerate() {
+ let y = (iy - 1 + jj as isize).clamp(0, self.h as isize - 1) as usize;
+ let row = &self.d[y * self.w..(y + 1) * self.w];
+ for (ii, wxi) in wx.iter().enumerate() {
+ let x = (ix - 1 + ii as isize).clamp(0, self.w as isize - 1) as usize;
+ let k = wxi * wyj;
+ acc[0] += f64::from(row[x][0]) * k;
+ acc[1] += f64::from(row[x][1]) * k;
+ }
+ }
+ acc
+ }
+
+ /// Whether any node influencing document rect `r` is displaced.
+ fn touches(&self, r: Rect) -> bool {
+ let (gx0, gy0) = self.to_grid(f64::from(r.x0), f64::from(r.y0));
+ let (gx1, gy1) = self.to_grid(f64::from(r.x1), f64::from(r.y1));
+ let i0 = (gx0.floor() as isize - 2).clamp(0, self.w as isize - 1) as usize;
+ let j0 = (gy0.floor() as isize - 2).clamp(0, self.h as isize - 1) as usize;
+ let i1 = (gx1.ceil() as isize + 2).clamp(0, self.w as isize - 1) as usize;
+ let j1 = (gy1.ceil() as isize + 2).clamp(0, self.h as isize - 1) as usize;
+ (j0..=j1).any(|j| self.d[j * self.w + i0..=j * self.w + i1].iter().any(|v| v[0] != 0.0 || v[1] != 0.0))
+ }
+}
+
+fn bilinear(d: &[[f32; 2]], w: usize, h: usize, gx: f64, gy: f64) -> [f64; 2] {
+ if !(gx > -1.0 && gy > -1.0 && gx < w as f64 && gy < h as f64) {
+ return [0.0, 0.0];
+ }
+ let gx = gx.clamp(0.0, (w - 1) as f64);
+ let gy = gy.clamp(0.0, (h - 1) as f64);
+ let (i, j) = ((gx as usize).min(w.saturating_sub(2)), (gy as usize).min(h.saturating_sub(2)));
+ let (fx, fy) = (gx - i as f64, gy - j as f64);
+ let i1 = (i + 1).min(w - 1);
+ let j1 = (j + 1).min(h - 1);
+ let at = |x: usize, y: usize| d[y * w + x];
+ let (a, b, c, e) = (at(i, j), at(i1, j), at(i, j1), at(i1, j1));
+ let l = |k: usize| (f64::from(a[k]) * (1.0 - fx) + f64::from(b[k]) * fx) * (1.0 - fy) + (f64::from(c[k]) * (1.0 - fx) + f64::from(e[k]) * fx) * fy;
+ [l(0), l(1)]
+}
+
+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]
+}
+
+/// Resamples `src` through the field: inside `field.bounds` each pixel shows the source at
+/// `p + d(p)` (bicubic field, bicubic premultiplied source, edge pixels repeat past the field
+/// bounds); everything outside the bounds is kept. Same format as `src`.
+pub fn apply_liquify(src: &Surface, field: &LiquifyField) -> Surface {
+ let fmt = src.format();
+ let n = fmt.channels();
+ let alpha = fmt.alpha;
+ let b = field.bounds;
+ let mut out = src.clone();
+ if field.is_identity() || b.is_empty() {
+ return out;
+ }
+ let maxd = f64::from(field.max_displacement()).ceil() as i32 + 3;
+ let tiles: Vec<Rect> = b.tiles().map(|t| t.rect().intersect(&b)).filter(|r| !r.is_empty() && field.touches(*r)).collect();
+ let work = |t: &Rect| -> Option<(Rect, Vec<f32>)> {
+ let w = t.width() as usize;
+ let h = t.height() as usize;
+ // Field per pixel (bicubic), rows share their y weights.
+ let mut disp = vec![[0.0f64; 2]; w * h];
+ let (mut fx0, mut fy0, mut fx1, mut fy1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
+ let mut moved = false;
+ for y in 0..h {
+ let py = f64::from(t.y0) + y as f64 + 0.5;
+ let gy = (py - f64::from(b.y0) - 0.5) / field.cell;
+ let wy = catmull_rom(gy - gy.floor());
+ for x in 0..w {
+ let px = f64::from(t.x0) + x as f64 + 0.5;
+ let gx = (px - f64::from(b.x0) - 0.5) / field.cell;
+ let wx = catmull_rom(gx - gx.floor());
+ let d = field.sample_cubic(gx, gy, &wx, &wy);
+ if d[0] != 0.0 || d[1] != 0.0 {
+ moved = true;
+ }
+ disp[y * w + x] = d;
+ let (sx, sy) = (px + d[0], py + d[1]);
+ fx0 = fx0.min(sx);
+ fy0 = fy0.min(sy);
+ fx1 = fx1.max(sx);
+ fy1 = fy1.max(sy);
+ }
+ }
+ if !moved {
+ return None;
+ }
+ let foot = Rect::new(fx0.floor() as i32 - 3, fy0.floor() as i32 - 3, fx1.ceil() as i32 + 3, fy1.ceil() as i32 + 3).intersect(&t.inflate(maxd)).intersect(&b);
+ if foot.is_empty() {
+ return None;
+ }
+ let mut px = src.read_region(foot);
+ if alpha {
+ for p in px.chunks_exact_mut(n) {
+ let al = p[n - 1];
+ for v in &mut p[..n - 1] {
+ *v *= al;
+ }
+ }
+ }
+ let fw = foot.width() as usize;
+ let at = |x: i32, y: i32| -> usize {
+ let x = x.clamp(foot.x0, foot.x1 - 1);
+ let y = y.clamp(foot.y0, foot.y1 - 1);
+ ((y - foot.y0) as usize * fw + (x - foot.x0) as usize) * n
+ };
+ let snap = |t: f64| if (t - t.round()).abs() < 1e-7 { t.round() } else { t };
+ let mut outp = vec![0.0f32; w * h * n];
+ let mut acc = [0.0f64; 8];
+ for y in 0..h {
+ for x in 0..w {
+ let d = disp[y * w + x];
+ let u = snap(f64::from(t.x0) + x as f64 + d[0]);
+ let v = snap(f64::from(t.y0) + y as f64 + d[1]);
+ let (ix, iy) = (u.floor() as i32, v.floor() as i32);
+ let (wx, wy) = (catmull_rom(u - f64::from(ix)), catmull_rom(v - f64::from(iy)));
+ acc[..n].fill(0.0);
+ for (j, wyj) in wy.iter().enumerate() {
+ for (i, wxi) in wx.iter().enumerate() {
+ let k = wxi * wyj;
+ if k == 0.0 {
+ continue;
+ }
+ let o = at(ix - 1 + i as i32, iy - 1 + j as i32);
+ for (c, s) in acc.iter_mut().enumerate().take(n) {
+ *s += f64::from(px[o + c]) * k;
+ }
+ }
+ }
+ let o = (y * w + x) * n;
+ if alpha {
+ let al = acc[n - 1].clamp(0.0, 1.0);
+ outp[o + n - 1] = al as f32;
+ for c in 0..n - 1 {
+ outp[o + c] = if al > 0.0 { (acc[c] / al).clamp(0.0, 1.0) as f32 } else { 0.0 };
+ }
+ } else {
+ for c in 0..n {
+ outp[o + c] = acc[c].clamp(0.0, 1.0) as f32;
+ }
+ }
+ }
+ }
+ 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);
+ }
+ if alpha {
+ out.prune();
+ }
+ out
+}
+
+/// A downsampled, premultiplied RGBA copy of a layer for the interactive preview.
+#[derive(Clone, Debug)]
+pub struct ProxyImage {
+ /// Document region the proxy covers (the field bounds).
+ pub bounds: Rect,
+ /// Document pixels per proxy pixel.
+ pub scale: f64,
+ pub w: usize,
+ pub h: usize,
+ /// Premultiplied RGBA, row-major.
+ pub px: Vec<[f32; 4]>,
+}
+
+impl ProxyImage {
+ /// Box-downsamples `src` over `bounds` so the longer side is at most `max_side`.
+ pub fn new(src: &Surface, bounds: Rect, max_side: usize) -> Self {
+ let side = bounds.width().max(bounds.height()).max(1) as f64;
+ let scale = (side / max_side.max(1) as f64).max(1.0).ceil();
+ let w = ((f64::from(bounds.width()) / scale).ceil() as usize).max(1);
+ let h = ((f64::from(bounds.height()) / scale).ceil() as usize).max(1);
+ let k = scale as i32;
+ let mut px = vec![[0.0f32; 4]; w * h];
+ let fmt = src.format();
+ let fill_rows = |y: usize, row: &mut [[f32; 4]]| {
+ let r = Rect::new(bounds.x0, bounds.y0 + y as i32 * k, bounds.x0 + w as i32 * k, (bounds.y0 + (y as i32 + 1) * k).min(bounds.y1));
+ let mut buf = vec![[0.0f32; 4]; r.width() as usize * r.height() as usize];
+ src.read_rgba_into(r, &mut buf);
+ let rw = r.width() as usize;
+ for (x, o) in row.iter_mut().enumerate() {
+ let mut acc = [0.0f32; 4];
+ let mut cnt = 0.0f32;
+ for yy in 0..r.height() as usize {
+ for xx in x * k as usize..((x + 1) * k as usize).min(rw) {
+ let p = buf[yy * rw + xx];
+ let a = if fmt.alpha { p[3] } else { 1.0 };
+ acc[0] += p[0] * a;
+ acc[1] += p[1] * a;
+ acc[2] += p[2] * a;
+ acc[3] += a;
+ cnt += 1.0;
+ }
+ }
+ if cnt > 0.0 {
+ *o = acc.map(|v| v / cnt);
+ }
+ }
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ px.par_chunks_mut(w).enumerate().for_each(|(y, row)| fill_rows(y, row));
+ }
+ #[cfg(target_arch = "wasm32")]
+ px.chunks_mut(w).enumerate().for_each(|(y, row)| fill_rows(y, row));
+ ProxyImage { bounds, scale, w, h, px }
+ }
+
+ /// Renders proxy pixels `r` (proxy coordinates) through the field into `out` (premultiplied
+ /// RGBA8, `w × h`): bilinear field, bilinear source.
+ pub fn render(&self, field: &LiquifyField, r: [usize; 4], out: &mut [[u8; 4]]) {
+ let [x0, y0, x1, y1] = [r[0].min(self.w), r[1].min(self.h), r[2].min(self.w), r[3].min(self.h)];
+ if x0 >= x1 || y0 >= y1 {
+ return;
+ }
+ let s = self.scale;
+ let (bx, by) = (f64::from(self.bounds.x0), f64::from(self.bounds.y0));
+ let row = |y: usize, line: &mut [[u8; 4]]| {
+ let py = by + (y as f64 + 0.5) * s;
+ for x in x0..x1 {
+ let px = bx + (x as f64 + 0.5) * s;
+ let d = field.sample(px, py);
+ let (u, v) = ((px + d[0] - bx) / s - 0.5, (py + d[1] - by) / s - 0.5);
+ let (iu, iv) = (u.floor(), v.floor());
+ let (fu, fv) = ((u - iu) as f32, (v - iv) as f32);
+ let at = |x: f64, y: f64| self.px[(y.clamp(0.0, (self.h - 1) as f64) as usize) * self.w + x.clamp(0.0, (self.w - 1) as f64) as usize];
+ let (a, b, c, e) = (at(iu, iv), at(iu + 1.0, iv), at(iu, iv + 1.0), at(iu + 1.0, iv + 1.0));
+ let mut o = [0u8; 4];
+ for k in 0..4 {
+ let v = (a[k] * (1.0 - fu) + b[k] * fu) * (1.0 - fv) + (c[k] * (1.0 - fu) + e[k] * fu) * fv;
+ o[k] = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
+ }
+ line[x] = o;
+ }
+ };
+ let rows = &mut out[y0 * self.w..y1 * self.w];
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ rows.par_chunks_mut(self.w).enumerate().for_each(|(i, line)| row(y0 + i, line));
+ }
+ #[cfg(target_arch = "wasm32")]
+ rows.chunks_mut(self.w).enumerate().for_each(|(i, line)| row(y0 + i, line));
+ }
+
+ /// The proxy pixel rectangle covering document rect `r`.
+ pub fn proxy_rect(&self, r: Rect) -> [usize; 4] {
+ let s = self.scale;
+ let f = |v: i32, o: i32| (f64::from(v - o) / s).max(0.0);
+ [f(r.x0, self.bounds.x0).floor() as usize, f(r.y0, self.bounds.y0).floor() as usize, (f(r.x1, self.bounds.x0).ceil() as usize + 1).min(self.w), (f(r.y1, self.bounds.y0).ceil() as usize + 1).min(self.h)]
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::{ColorMode, PixelFormat, SampleType};
+
+ fn sample(st: SampleType) -> Surface {
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true));
+ for y in 0..64 {
+ for x in 0..96 {
+ let v = ((x / 4 + y / 4) % 2) as f32;
+ s.write_pixel(x, y, &[v, (x as f32) / 96.0, (y as f32) / 64.0, 1.0]);
+ }
+ }
+ s
+ }
+
+ fn bounds() -> Rect {
+ Rect::new(0, 0, 96, 64)
+ }
+
+ fn worst(a: &Surface, b: &Surface, r: Rect) -> f32 {
+ a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max)
+ }
+
+ #[test]
+ fn no_strokes_is_identity_at_every_depth() {
+ for st in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let s = sample(st);
+ let f = LiquifyField::new(bounds(), 2.0);
+ assert_eq!(apply_liquify(&s, &f), s);
+ // A field with exactly-zero strokes (zero pressure) is still identity.
+ let mut st0 = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0);
+ st0.pressure = 0.0;
+ st0.points = vec![vec![40.0, 30.0], vec![60.0, 30.0]];
+ let f = LiquifyField::from_strokes(bounds(), 2.0, &[st0]);
+ assert!(f.is_identity());
+ }
+ }
+
+ #[test]
+ fn forward_warp_displaces_along_the_stroke_and_reconstruct_restores() {
+ let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0);
+ s.points = vec![vec![40.0, 32.0], vec![52.0, 32.0]];
+ let mut f = LiquifyField::from_strokes(bounds(), 2.0, &[s]);
+ // Content moved right: the output at the end point samples from the left.
+ let d = f.sample(52.0, 32.0);
+ assert!(d[0] < -4.0 && d[1].abs() < 0.5, "{d:?}");
+ // A pixel-level check: a marker column follows the stroke.
+ let mut img = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, true));
+ img.fill_rect(bounds(), &[0.0, 1.0]);
+ img.fill_rect(Rect::new(40, 28, 42, 36), &[1.0, 1.0]);
+ let out = apply_liquify(&img, &f);
+ let brightest = (30..70).max_by(|a, b| out.pixel(*a, 32)[0].total_cmp(&out.pixel(*b, 32)[0])).unwrap();
+ assert!(brightest > 44, "marker moved right: {brightest}");
+ // Reconstruct All restores the original exactly.
+ let mut rec = LiquifyStroke::new(LiquifyTool::ReconstructAll, 10.0);
+ rec.amount = Some(100.0);
+ f.apply_stroke(&rec);
+ assert!(f.is_identity());
+ assert_eq!(apply_liquify(&img, &f), img);
+ }
+
+ #[test]
+ fn reconstruct_brush_reduces_the_field_and_freeze_protects() {
+ let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0);
+ s.points = vec![vec![30.0, 32.0], vec![45.0, 32.0]];
+ let mut f = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s));
+ let before = f.max_displacement();
+ let mut r = LiquifyStroke::new(LiquifyTool::Reconstruct, 80.0);
+ r.points = vec![vec![40.0, 32.0]; 30];
+ f.apply_stroke(&r);
+ assert!(f.max_displacement() < before * 0.2, "{} vs {before}", f.max_displacement());
+ // Frozen area doesn't move.
+ let mut fr = LiquifyStroke::new(LiquifyTool::Freeze, 60.0);
+ fr.density = 0.0;
+ fr.points = vec![vec![40.0, 32.0]];
+ let mut g = LiquifyField::new(bounds(), 2.0);
+ g.apply_stroke(&fr);
+ assert!(g.freeze_at(40.0, 32.0) > 0.99);
+ g.apply_stroke(&s);
+ assert!(g.sample(40.0, 32.0)[0].abs() < 1e-3);
+ // Thaw unfreezes.
+ let mut th = fr.clone();
+ th.tool = LiquifyTool::Thaw;
+ g.apply_stroke(&th);
+ assert!(g.freeze_at(40.0, 32.0) < 0.01);
+ }
+
+ #[test]
+ fn twirl_pucker_bloat_and_push_left_have_the_right_sense() {
+ let at = |tool: LiquifyTool, pts: Vec<Vec<f64>>| {
+ let mut s = LiquifyStroke::new(tool, 40.0);
+ s.points = pts;
+ LiquifyField::from_strokes(bounds(), 2.0, &[s])
+ };
+ let c = vec![vec![48.0, 32.0]; 10];
+ // Pucker pulls content in: the output samples outward (d points away from the centre).
+ let f = at(LiquifyTool::Pucker, c.clone());
+ assert!(f.sample(58.0, 32.0)[0] > 0.1);
+ let f = at(LiquifyTool::Bloat, c.clone());
+ assert!(f.sample(58.0, 32.0)[0] < -0.1);
+ // Twirl clockwise (y down): content right of centre moves down, so it samples from above.
+ let f = at(LiquifyTool::TwirlCw, c.clone());
+ assert!(f.sample(58.0, 32.0)[1] < -0.1, "{:?}", f.sample(58.0, 32.0));
+ let f = at(LiquifyTool::TwirlCcw, c);
+ assert!(f.sample(58.0, 32.0)[1] > 0.1);
+ // Push Left while dragging up moves content left (samples from the right).
+ let f = at(LiquifyTool::PushLeft, vec![vec![48.0, 44.0], vec![48.0, 20.0]]);
+ assert!(f.sample(48.0, 32.0)[0] > 0.5, "{:?}", f.sample(48.0, 32.0));
+ // Smooth reduces sharp field differences.
+ let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 12.0);
+ s.points = vec![vec![40.0, 32.0], vec![50.0, 32.0]];
+ let mut g = LiquifyField::from_strokes(bounds(), 2.0, &[s]);
+ let m0 = g.max_displacement();
+ let mut sm = LiquifyStroke::new(LiquifyTool::Smooth, 60.0);
+ sm.points = vec![vec![45.0, 32.0]; 20];
+ g.apply_stroke(&sm);
+ assert!(g.max_displacement() < m0);
+ }
+
+ #[test]
+ fn replay_is_deterministic_and_depths_agree() {
+ let mut s = LiquifyStroke::new(LiquifyTool::TwirlCw, 50.0);
+ s.points = vec![vec![48.0, 32.0, 0.5], vec![50.0, 33.0, 1.0], vec![52.0, 34.0]];
+ let a = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s));
+ let b = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s));
+ assert_eq!(a, b);
+ let r8 = apply_liquify(&sample(SampleType::U8), &a);
+ let r32 = apply_liquify(&sample(SampleType::F32), &a);
+ assert!(worst(&r8, &r32, bounds()) < 2.0 / 255.0 + 1e-4);
+ }
+
+ #[test]
+ fn proxy_matches_the_full_render_roughly() {
+ let src = sample(SampleType::U8);
+ let mut s = LiquifyStroke::new(LiquifyTool::Bloat, 40.0);
+ s.points = vec![vec![48.0, 32.0]; 8];
+ let f = LiquifyField::from_strokes(bounds(), 2.0, &[s]);
+ let p = ProxyImage::new(&src, bounds(), 96);
+ assert_eq!((p.w, p.h, p.scale), (96, 64, 1.0));
+ let mut out = vec![[0u8; 4]; p.w * p.h];
+ p.render(&f, [0, 0, p.w, p.h], &mut out);
+ let full = apply_liquify(&src, &f);
+ let mut bad = 0;
+ for y in 0..64 {
+ for x in 0..96 {
+ let q = full.pixel(x, y);
+ let o = out[y as usize * 96 + x as usize];
+ if (f32::from(o[1]) / 255.0 - q[1]).abs() > 0.1 {
+ bad += 1;
+ }
+ }
+ }
+ assert!(bad < 96 * 64 / 50, "{bad}");
+ }
+}
diff --git a/crates/algo/src/oil.rs b/crates/algo/src/oil.rs
new file mode 100644
index 000000000..c96850d80
--- /dev/null
+++ b/crates/algo/src/oil.rs
@@ -0,0 +1,197 @@
+//! Oil Paint: flow-guided smoothing plus a lit bristle relief.
+//!
+//! The approach follows published non-photorealistic rendering work rather
+//! than any product: the structure tensor of the luminance (Brox et al.) gives
+//! a smooth stroke direction field, and a line integral convolution (Cabral &
+//! Leedom 1993) smears colour along it, as in flow-based abstraction (Kyprianidis
+//! & Döllner 2008). Convolving white noise along the same field produces the
+//! bristle streaks, which together with the smoothed luminance form a height
+//! map shaded by a directional light.
+
+use photocraft_color::ColorMode;
+use photocraft_geom::Rect;
+
+use crate::Ctx;
+use crate::fxutil::{MAXC, gauss_blur_n, ncol, premul_window, unpremul_px};
+use crate::image::Image;
+use crate::noise::hash01;
+
+pub(crate) struct OilSpec {
+ pub stylization: f32,
+ pub cleanliness: f32,
+ pub scale: f32,
+ pub bristle_detail: f32,
+ pub lighting: bool,
+ pub angle: f32,
+ pub shine: f32,
+}
+
+fn stroke_len(stylization: f32) -> f32 {
+ 1.5 + stylization.clamp(0.1, 10.0) * 2.0
+}
+fn tensor_sigma(scale: f32) -> f32 {
+ 0.8 + scale.clamp(0.1, 10.0) * 0.6
+}
+
+/// Pixels read beyond an output tile.
+pub(crate) fn reach(stylization: f32, scale: f32) -> f32 {
+ stroke_len(stylization) + 3.0 * tensor_sigma(scale) + 3.0 * 2.5 + 4.0
+}
+
+pub(crate) fn oil_paint(src: &Image, out: Rect, ctx: &Ctx, spec: &OilSpec) -> Vec<f32> {
+ let n = src.ch;
+ let win = src.rect;
+ let (ww, wh) = (win.width() as usize, win.height() as usize);
+ let alpha = ctx.alpha;
+ let cc = ncol(ctx, n);
+ // 1. Premultiplied colour, cleaned (pre-smoothed) by `cleanliness`.
+ let mut p = premul_window(src, win, alpha);
+ gauss_blur_n(&mut p, ww, wh, n, spec.cleanliness.clamp(0.0, 10.0) * 0.25);
+ // 2. Luminance-like intensity for the structure tensor (channel mean works in every model).
+ let lum: Vec<f32> = p.chunks_exact(n).map(|px| px[..cc].iter().sum::<f32>() / cc as f32).collect();
+ // 3. Smoothed structure tensor (E, F, G).
+ let mut efg = vec![0.0f32; ww * wh * 3];
+ for y in 1..wh.saturating_sub(1) {
+ for x in 1..ww - 1 {
+ let l = |dx: isize, dy: isize| lum[((y as isize + dy) as usize) * ww + (x as isize + dx) as usize];
+ let gx = (l(1, -1) + 2.0 * l(1, 0) + l(1, 1)) - (l(-1, -1) + 2.0 * l(-1, 0) + l(-1, 1));
+ let gy = (l(-1, 1) + 2.0 * l(0, 1) + l(1, 1)) - (l(-1, -1) + 2.0 * l(0, -1) + l(1, -1));
+ let o = (y * ww + x) * 3;
+ efg[o] = gx * gx;
+ efg[o + 1] = gx * gy;
+ efg[o + 2] = gy * gy;
+ }
+ }
+ gauss_blur_n(&mut efg, ww, wh, 3, tensor_sigma(spec.scale));
+ // 4. Stroke direction = minor eigenvector (along edges).
+ let tangent: Vec<(f32, f32)> = efg
+ .chunks_exact(3)
+ .map(|t| {
+ let (e, f, g) = (t[0], t[1], t[2]);
+ let l1 = 0.5 * (e + g + ((e - g) * (e - g) + 4.0 * f * f).sqrt());
+ let (tx, ty) = (l1 - e, -f);
+ let m = (tx * tx + ty * ty).sqrt();
+ // Near-isotropic structure has no stable direction; treat as flat.
+ if m < 1e-6 || (l1 - (e + g - l1)) < 1e-6 {
+ // Flat areas: gentle diagonal strokes.
+ (std::f32::consts::FRAC_1_SQRT_2, std::f32::consts::FRAC_1_SQRT_2)
+ } else {
+ (tx / m, ty / m)
+ }
+ })
+ .collect();
+ // 5. Line integral convolution over `out` grown by 1 (for the relief gradient).
+ let r1 = out.inflate(1).intersect(&win);
+ let (rw, rh) = (r1.width() as usize, r1.height() as usize);
+ let len = stroke_len(spec.stylization);
+ let h = (len / 10.0).max(1.0);
+ let steps = (len / h).ceil() as i32;
+ let mut col = vec![0.0f32; rw * rh * n];
+ let mut bristle = vec![0.0f32; rw * rh];
+ let sample = |x: f32, y: f32, acc: &mut [f32], k: f32| {
+ let x = x.clamp(0.0, (ww - 1) as f32);
+ let y = y.clamp(0.0, (wh - 1) as f32);
+ let (x0, y0) = (x.floor() as usize, y.floor() as usize);
+ let (x1, y1) = ((x0 + 1).min(ww - 1), (y0 + 1).min(wh - 1));
+ let (ax, ay) = (x - x0 as f32, y - y0 as f32);
+ let w00 = (1.0 - ax) * (1.0 - ay) * k;
+ let w10 = ax * (1.0 - ay) * k;
+ let w01 = (1.0 - ax) * ay * k;
+ let w11 = ax * ay * k;
+ let (i00, i10, i01, i11) = ((y0 * ww + x0) * n, (y0 * ww + x1) * n, (y1 * ww + x0) * n, (y1 * ww + x1) * n);
+ for c in 0..acc.len() {
+ acc[c] += p[i00 + c] * w00 + p[i10 + c] * w10 + p[i01 + c] * w01 + p[i11 + c] * w11;
+ }
+ };
+ let mut acc = [0.0f32; MAXC];
+ for ry in 0..rh {
+ for rx in 0..rw {
+ let (dx, dy) = ((r1.x0 - win.x0) as f32 + rx as f32, (r1.y0 - win.y0) as f32 + ry as f32);
+ acc[..n].fill(0.0);
+ let mut wsum = 0.0;
+ let mut nsum = 0.0;
+ sample(dx, dy, &mut acc[..n], 1.0);
+ wsum += 1.0;
+ nsum += hash01(win.x0 + dx as i32, win.y0 + dy as i32, 71, 0);
+ for dir in [1.0f32, -1.0] {
+ let (mut qx, mut qy) = (dx, dy);
+ let (mut px, mut py) = (0.0f32, 0.0f32);
+ for k in 1..=steps {
+ let ti = (qy.round().clamp(0.0, (wh - 1) as f32) as usize) * ww + qx.round().clamp(0.0, (ww - 1) as f32) as usize;
+ let (mut tx, mut ty) = tangent[ti];
+ if k == 1 {
+ tx *= dir;
+ ty *= dir;
+ } else if tx * px + ty * py < 0.0 {
+ tx = -tx;
+ ty = -ty;
+ }
+ px = tx;
+ py = ty;
+ qx += tx * h;
+ qy += ty * h;
+ let wk = 1.0 - k as f32 / (steps + 1) as f32;
+ sample(qx, qy, &mut acc[..n], wk);
+ wsum += wk;
+ nsum += wk * hash01(win.x0 + qx.round() as i32, win.y0 + qy.round() as i32, 71, 0);
+ }
+ }
+ let o = (ry * rw + rx) * n;
+ for c in 0..n {
+ col[o + c] = acc[c] / wsum;
+ }
+ bristle[ry * rw + rx] = nsum / wsum - 0.5;
+ }
+ }
+ // 6. Relief lighting.
+ let (ls, lc) = spec.angle.to_radians().sin_cos();
+ let elev = 45f32.to_radians();
+ let light = [lc * elev.cos(), -ls * elev.cos(), elev.sin()];
+ let half = {
+ let v = [light[0], light[1], light[2] + 1.0];
+ let m = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
+ [v[0] / m, v[1] / m, v[2] / m]
+ };
+ let amp = spec.bristle_detail.clamp(0.0, 10.0) / 10.0;
+ let shine = spec.shine.clamp(0.0, 10.0) / 10.0;
+ let sub = ctx.mode == ColorMode::Cmyk;
+ let lab = ctx.mode == ColorMode::Lab;
+ let height = |rx: usize, ry: usize| -> f32 {
+ let o = (ry * rw + rx) * n;
+ let l = col[o..o + cc].iter().sum::<f32>() / cc as f32;
+ let l = if sub { 1.0 - l } else { l };
+ l * 2.0 + bristle[ry * rw + rx] * amp * 6.0
+ };
+ let flat_spec = half[2].powf(40.0);
+ let mut res = Vec::with_capacity(out.width() as usize * out.height() as usize * n);
+ for y in out.y0..out.y1 {
+ for x in out.x0..out.x1 {
+ let (rx, ry) = ((x - r1.x0) as usize, (y - r1.y0) as usize);
+ let o = (ry * rw + rx) * n;
+ let mut px = [0.0f32; MAXC];
+ px[..n].copy_from_slice(&col[o..o + n]);
+ unpremul_px(&mut px[..n], alpha);
+ // Painting restyles colour, not coverage: keep the layer's own alpha (no faded
+ // canvas edges from smearing in transparent margins).
+ if alpha {
+ px[n - 1] = src.get(x, y, n - 1);
+ }
+ if spec.lighting {
+ let hx = height((rx + 1).min(rw - 1), ry) - height(rx.saturating_sub(1), ry);
+ let hy = height(rx, (ry + 1).min(rh - 1)) - height(rx, ry.saturating_sub(1));
+ let nv = [-hx * 0.5, -hy * 0.5, 1.0];
+ let m = (nv[0] * nv[0] + nv[1] * nv[1] + 1.0).sqrt();
+ let ndl = (nv[0] * light[0] + nv[1] * light[1] + nv[2] * light[2]) / m;
+ let ndh = ((nv[0] * half[0] + nv[1] * half[1] + nv[2] * half[2]) / m).max(0.0);
+ let shade = 1.0 + (ndl - light[2]) * 1.2;
+ let spec_v = shine * (ndh.powf(40.0) - flat_spec).max(0.0) * 0.8;
+ let chans = if lab { 1 } else { cc };
+ for v in px.iter_mut().take(chans) {
+ *v = if sub { 1.0 - ((1.0 - *v) * shade + spec_v) } else { *v * shade + spec_v };
+ }
+ }
+ res.extend_from_slice(&px[..n]);
+ }
+ }
+ res
+}
diff --git a/crates/algo/src/other2.rs b/crates/algo/src/other2.rs
new file mode 100644
index 000000000..59682f361
--- /dev/null
+++ b/crates/algo/src/other2.rs
@@ -0,0 +1,136 @@
+//! Filter › Other: Custom (5×5 convolution) and HSB/HSL.
+
+use photocraft_color::ColorMode;
+use photocraft_geom::Rect;
+
+use crate::fxutil::{ncol, rgba, set_rgba, xy};
+use crate::image::Image;
+use crate::{Ctx, HsbModel};
+
+/// Custom: `Σ kernel·pixel / scale + offset/255` per colour channel (alpha
+/// kept). Kernels shorter than 25 entries are zero-padded.
+pub(crate) fn custom(src: &Image, out: Rect, ctx: &Ctx, kernel: &[f32], scale: f32, offset: f32) -> Vec<f32> {
+ let n = src.ch;
+ let cc = ncol(ctx, n);
+ let k: Vec<(i32, i32, f32)> = (0..25).filter_map(|i| kernel.get(i).copied().filter(|v| *v != 0.0).map(|v| (i as i32 % 5 - 2, i as i32 / 5 - 2, v))).collect();
+ let s = if scale == 0.0 { 1.0 } else { scale };
+ let off = offset / 255.0;
+ let mut res = src.crop(out);
+ if k.is_empty() {
+ return res;
+ }
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ for (c, v) in px.iter_mut().enumerate().take(cc) {
+ let sum: f32 = k.iter().map(|&(dx, dy, w)| src.get(x + dx, y + dy, c) * w).sum();
+ *v = sum / s + off;
+ }
+ }
+ res
+}
+
+/// RGB → HSB (hue, saturation, brightness), all 0–1.
+pub(crate) fn rgb_to_hsb(c: [f32; 3]) -> [f32; 3] {
+ let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2]));
+ let d = mx - mn;
+ let h = hue(c, mx, d);
+ [h, if mx > 0.0 { d / mx } else { 0.0 }, mx]
+}
+
+/// RGB → HSL, all 0–1.
+pub(crate) fn rgb_to_hsl(c: [f32; 3]) -> [f32; 3] {
+ let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2]));
+ let d = mx - mn;
+ let l = (mx + mn) / 2.0;
+ let s = if d <= 0.0 { 0.0 } else { d / (1.0 - (2.0 * l - 1.0).abs()).max(1e-7) };
+ [hue(c, mx, d), s.clamp(0.0, 1.0), l]
+}
+
+fn hue(c: [f32; 3], mx: f32, d: f32) -> f32 {
+ if d <= 0.0 {
+ return 0.0;
+ }
+ let h = if mx == c[0] {
+ ((c[1] - c[2]) / d).rem_euclid(6.0)
+ } else if mx == c[1] {
+ (c[2] - c[0]) / d + 2.0
+ } else {
+ (c[0] - c[1]) / d + 4.0
+ };
+ h / 6.0
+}
+
+/// Chroma/min helper: RGB from hue, chroma and the value to add.
+fn from_hcm(h: f32, chroma: f32, m: f32) -> [f32; 3] {
+ let hp = h.rem_euclid(1.0) * 6.0;
+ let x = chroma * (1.0 - (hp.rem_euclid(2.0) - 1.0).abs());
+ let (r, g, b) = match hp as i32 {
+ 0 => (chroma, x, 0.0),
+ 1 => (x, chroma, 0.0),
+ 2 => (0.0, chroma, x),
+ 3 => (0.0, x, chroma),
+ 4 => (x, 0.0, chroma),
+ _ => (chroma, 0.0, x),
+ };
+ [r + m, g + m, b + m]
+}
+
+pub(crate) fn hsb_to_rgb(c: [f32; 3]) -> [f32; 3] {
+ let chroma = c[2] * c[1];
+ from_hcm(c[0], chroma, c[2] - chroma)
+}
+
+pub(crate) fn hsl_to_rgb(c: [f32; 3]) -> [f32; 3] {
+ let chroma = (1.0 - (2.0 * c[2] - 1.0).abs()) * c[1];
+ from_hcm(c[0], chroma, c[2] - chroma / 2.0)
+}
+
+/// HSB/HSL: reinterprets the three colour channels — encodes RGB as
+/// H, S, B/L in the R, G, B channels, or decodes such channels back to RGB.
+pub(crate) fn hsb_hsl(src: &Image, out: Rect, ctx: &Ctx, input: HsbModel, output: HsbModel) -> Vec<f32> {
+ let n = src.ch;
+ let mut res = src.crop(out);
+ if input == output {
+ return res;
+ }
+ let native = ctx.mode == ColorMode::Rgb;
+ for px in res.chunks_exact_mut(n) {
+ let c4 = if native { [px[0], px[1], px[2], 1.0] } else { rgba(ctx, px) };
+ let c = [c4[0].clamp(0.0, 1.0), c4[1].clamp(0.0, 1.0), c4[2].clamp(0.0, 1.0)];
+ let rgb = match input {
+ HsbModel::Rgb => c,
+ HsbModel::Hsb => hsb_to_rgb(c),
+ HsbModel::Hsl => hsl_to_rgb(c),
+ };
+ let o = match output {
+ HsbModel::Rgb => rgb,
+ HsbModel::Hsb => rgb_to_hsb(rgb),
+ HsbModel::Hsl => rgb_to_hsl(rgb),
+ };
+ if native {
+ px[..3].copy_from_slice(&o);
+ } else {
+ set_rgba(ctx, px, [o[0], o[1], o[2], c4[3]]);
+ }
+ }
+ res
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hsb_hsl_round_trip() {
+ for c in [[0.2, 0.7, 0.4], [1.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.1, 0.2, 0.9], [0.9, 0.8, 0.05]] {
+ let a = hsb_to_rgb(rgb_to_hsb(c));
+ let b = hsl_to_rgb(rgb_to_hsl(c));
+ for k in 0..3 {
+ assert!((a[k] - c[k]).abs() < 1e-5 && (b[k] - c[k]).abs() < 1e-5, "{c:?} {a:?} {b:?}");
+ }
+ }
+ assert_eq!(rgb_to_hsb([1.0, 0.0, 0.0]), [0.0, 1.0, 1.0]);
+ let l = rgb_to_hsl([0.0, 0.0, 1.0]);
+ assert!((l[0] - 2.0 / 3.0).abs() < 1e-6 && (l[2] - 0.5).abs() < 1e-6);
+ }
+}
diff --git a/crates/algo/src/params_ext.rs b/crates/algo/src/params_ext.rs
new file mode 100644
index 000000000..3a9572fb4
--- /dev/null
+++ b/crates/algo/src/params_ext.rs
@@ -0,0 +1,286 @@
+//! Option enums and parameter objects for the second batch of filters
+//! (pixelate, stylize, render, blur gallery, video…).
+
+use serde::{Deserialize, Serialize};
+
+/// Mezzotint pattern.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum MezzotintType {
+ #[default]
+ FineDots,
+ MediumDots,
+ GrainyDots,
+ CoarseDots,
+ ShortLines,
+ MediumLines,
+ LongLines,
+ ShortStrokes,
+ MediumStrokes,
+ LongStrokes,
+}
+
+/// Diffuse mode.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum DiffuseMode {
+ #[default]
+ Normal,
+ DarkenOnly,
+ LightenOnly,
+ Anisotropic,
+}
+
+/// Extrude geometry.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum ExtrudeType {
+ #[default]
+ Blocks,
+ Pyramids,
+}
+
+/// What Tiles puts in the gaps between tiles.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum TileFill {
+ #[default]
+ Background,
+ Foreground,
+ Inverse,
+ Unaltered,
+}
+
+/// Wind method.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum WindMethod {
+ #[default]
+ Wind,
+ Blast,
+ Stagger,
+}
+
+/// ZigZag style.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum ZigZagStyle {
+ AroundCenter,
+ OutFromCenter,
+ #[default]
+ PondRipples,
+}
+
+/// Lens Flare lens type.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum LensType {
+ /// 50–300 mm zoom.
+ #[default]
+ Zoom,
+ Prime35,
+ Prime105,
+ MoviePrime,
+}
+
+/// Lighting Effects light type.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum LightKind {
+ #[default]
+ Spot,
+ Point,
+ Infinite,
+}
+
+/// One Lighting Effects light. Positions are fractions of the reference
+/// bounds; `z` is the height above the surface as a fraction of the bounds'
+/// shorter side.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct Light {
+ pub kind: LightKind,
+ pub x: f32,
+ pub y: f32,
+ pub z: f32,
+ /// Spot: where the light points (fractions of the bounds).
+ pub target_x: f32,
+ pub target_y: f32,
+ /// Infinite: direction the light comes from (degrees, 0 = right, counter-clockwise) and elevation.
+ pub angle: f32,
+ pub elevation: f32,
+ /// Linear RGB 0–1.
+ pub color: [f32; 3],
+ /// −100…100 (negative lights darken).
+ pub intensity: f32,
+ /// Spot cone half-angle in degrees.
+ pub cone: f32,
+ /// Spot hotspot, 0–100 % of the cone at full intensity.
+ pub hotspot: f32,
+ /// Point light reach as a fraction of the bounds' shorter side.
+ pub radius: f32,
+}
+
+impl Default for Light {
+ fn default() -> Self {
+ Light {
+ kind: LightKind::Spot,
+ x: 0.25,
+ y: 0.2,
+ z: 0.6,
+ target_x: 0.5,
+ target_y: 0.55,
+ angle: 135.0,
+ elevation: 45.0,
+ color: [1.0, 1.0, 1.0],
+ intensity: 75.0,
+ cone: 45.0,
+ hotspot: 50.0,
+ radius: 0.8,
+ }
+ }
+}
+
+/// Bump texture source for Lighting Effects.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum TextureChannel {
+ #[default]
+ None,
+ Red,
+ Green,
+ Blue,
+ Alpha,
+ Luminance,
+}
+
+/// Smart Blur sampling quality.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum BlurQuality {
+ Low,
+ #[default]
+ Medium,
+ High,
+}
+
+/// Smart Blur output.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum SmartBlurMode {
+ #[default]
+ Normal,
+ EdgeOnly,
+ OverlayEdge,
+}
+
+/// Where Lens Blur reads depth.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum DepthSource {
+ #[default]
+ None,
+ Transparency,
+ LayerMask,
+}
+
+/// Built-in Shape Blur kernels.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum BlurShape {
+ #[default]
+ Circle,
+ Ring,
+ Square,
+ Diamond,
+ Triangle,
+ Hexagon,
+ Star,
+ Heart,
+ Cross,
+}
+
+/// Colour encodings for Filter › Other › HSB/HSL.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum HsbModel {
+ #[default]
+ Rgb,
+ Hsb,
+ Hsl,
+}
+
+/// Iris Blur pin: an ellipse (fractions of the bounds' shorter side) that stays sharp.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct IrisPin {
+ pub x: f32,
+ pub y: f32,
+ pub radius_x: f32,
+ pub radius_y: f32,
+ /// Ellipse rotation in degrees.
+ pub angle: f32,
+ /// 0 = ellipse, 100 = rounded rectangle.
+ pub roundness: f32,
+ /// Sharp core as a fraction of the ellipse (0–1).
+ pub feather: f32,
+ /// Blur at and beyond the ellipse, px.
+ pub blur: f32,
+}
+
+impl Default for IrisPin {
+ fn default() -> Self {
+ IrisPin { x: 0.5, y: 0.5, radius_x: 0.35, radius_y: 0.25, angle: 0.0, roundness: 0.0, feather: 0.5, blur: 15.0 }
+ }
+}
+
+/// Field Blur pin: a blur amount at a point.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct FieldPin {
+ pub x: f32,
+ pub y: f32,
+ pub blur: f32,
+}
+
+impl Default for FieldPin {
+ fn default() -> Self {
+ FieldPin { x: 0.5, y: 0.5, blur: 15.0 }
+ }
+}
+
+/// Spin Blur pin: an ellipse whose content is rotated about its centre.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct SpinPin {
+ pub x: f32,
+ pub y: f32,
+ pub radius_x: f32,
+ pub radius_y: f32,
+ pub angle: f32,
+ /// Blur arc in degrees.
+ pub blur_angle: f32,
+}
+
+impl Default for SpinPin {
+ fn default() -> Self {
+ SpinPin { x: 0.5, y: 0.5, radius_x: 0.3, radius_y: 0.3, angle: 0.0, blur_angle: 15.0 }
+ }
+}
+
+/// Path Blur path: a polyline (fractions of the bounds) giving the motion direction.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct BlurPath {
+ pub points: Vec<[f32; 2]>,
+ /// Blur length in px.
+ pub speed: f32,
+ /// 0–100: how much the blur fades toward the path's end.
+ pub taper: f32,
+}
+
+impl Default for BlurPath {
+ fn default() -> Self {
+ BlurPath { points: vec![[0.2, 0.5], [0.8, 0.5]], speed: 50.0, taper: 0.0 }
+ }
+}
diff --git a/crates/algo/src/perspective.rs b/crates/algo/src/perspective.rs
new file mode 100644
index 000000000..4984bfa58
--- /dev/null
+++ b/crates/algo/src/perspective.rs
@@ -0,0 +1,311 @@
+//! Edit › Perspective Warp: planes (quads) drawn over the image in Layout mode, whose corners are
+//! then moved in Warp mode; the image follows a piecewise-homography map.
+//!
+//! Each plane maps its source quad onto its destination quad with a homography
+//! `M_i = H_dst ∘ H_src⁻¹` (through the unit square, so `(u, v)` are the plane's projective
+//! coordinates). Two homographies that agree on an edge's endpoints map the edge onto the same
+//! segment but generally with a different spacing along it, so on its own a piecewise map tears
+//! at shared edges. For every edge shared by two planes we therefore take the average of both
+//! planes' images of each edge point as the target and add the difference, faded linearly
+//! across the plane (weight `1 − u`, `u`, `1 − v` or `v` from that edge to the opposite one).
+//! The correction vanishes at the corners (shared corners have one destination), so the map is
+//! exactly continuous across shared edges, exactly the homography for a lone plane, and exactly
+//! the identity when nothing moved. Points outside every plane use the nearest plane, with
+//! `(u, v)` clamped for the corrections.
+//!
+//! Corners that coincide (within half a pixel) in the source are linked: they share one
+//! destination (the mean of the given ones), as Photoshop's snapped planes do.
+
+use serde::{Deserialize, Serialize};
+
+use crate::transform::Homography;
+
+/// One plane: source quad (Layout mode) and destination quad (Warp mode), corners clockwise from
+/// top-left, document pixels.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Plane {
+ pub src: [[f64; 2]; 4],
+ pub dst: [[f64; 2]; 4],
+}
+
+impl Plane {
+ pub fn identity(q: [[f64; 2]; 4]) -> Self {
+ Plane { src: q, dst: q }
+ }
+}
+
+const LINK_EPS: f64 = 0.5;
+
+/// Unit square corners in plane order.
+const UNIT: [[f64; 2]; 4] = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
+
+fn unit_to_quad(q: &[[f64; 2]; 4]) -> Option<Homography> {
+ Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], *q)
+}
+
+/// Groups of linked corners: `(plane, corner)` pairs that coincide in the source.
+pub fn linked_corners(planes: &[Plane]) -> Vec<Vec<(usize, usize)>> {
+ let mut groups: Vec<Vec<(usize, usize)>> = Vec::new();
+ for (pi, p) in planes.iter().enumerate() {
+ for (ci, c) in p.src.iter().enumerate() {
+ let g = groups.iter_mut().find(|g| {
+ let (a, b) = g[0];
+ let o = planes[a].src[b];
+ (o[0] - c[0]).abs() <= LINK_EPS && (o[1] - c[1]).abs() <= LINK_EPS
+ });
+ match g {
+ Some(g) => g.push((pi, ci)),
+ None => groups.push(vec![(pi, ci)]),
+ }
+ }
+ }
+ groups
+}
+
+/// Snaps linked corners to one source and one destination position (their means).
+pub fn unify(planes: &mut [Plane]) {
+ for g in linked_corners(planes) {
+ if g.len() < 2 {
+ continue;
+ }
+ let n = g.len() as f64;
+ let s = g.iter().fold([0.0, 0.0], |a, &(p, c)| [a[0] + planes[p].src[c][0] / n, a[1] + planes[p].src[c][1] / n]);
+ let d = g.iter().fold([0.0, 0.0], |a, &(p, c)| [a[0] + planes[p].dst[c][0] / n, a[1] + planes[p].dst[c][1] / n]);
+ for &(p, c) in &g {
+ planes[p].src[c] = s;
+ planes[p].dst[c] = d;
+ }
+ }
+}
+
+/// Edge `k` of a plane runs from corner `k` to corner `k + 1`.
+fn edge_uv(k: usize, u: f64, v: f64) -> ([f64; 2], f64) {
+ // (point on the edge in plane coordinates, weight of that edge's correction)
+ match k {
+ 0 => ([u, 0.0], 1.0 - v),
+ 1 => ([1.0, v], u),
+ 2 => ([u, 1.0], v),
+ _ => ([0.0, v], 1.0 - u),
+ }
+}
+
+struct PlaneMap {
+ src: Homography,
+ src_inv: Homography,
+ dst: Homography,
+ quad: [[f64; 2]; 4],
+ /// For each edge: the neighbouring plane sharing it, if any.
+ shared: [Option<usize>; 4],
+}
+
+/// A prepared perspective warp (forward map, source → destination).
+pub struct PerspectiveMap {
+ planes: Vec<PlaneMap>,
+}
+
+/// Straighten modes (Photoshop's Warp-mode buttons).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Straighten {
+ Horizontal,
+ Vertical,
+ Auto,
+}
+
+impl Straighten {
+ pub fn parse(s: &str) -> Option<Self> {
+ match s.to_ascii_lowercase().as_str() {
+ "h" | "horizontal" | "level" => Some(Straighten::Horizontal),
+ "v" | "vertical" => Some(Straighten::Vertical),
+ "auto" | "both" => Some(Straighten::Auto),
+ _ => None,
+ }
+ }
+}
+
+/// Makes the destination edges that are near-horizontal exactly horizontal and/or near-vertical
+/// exactly vertical (within 45°), moving linked corners together.
+pub fn straighten(planes: &mut [Plane], mode: Straighten) {
+ unify(planes);
+ let groups = linked_corners(planes);
+ let group_of = |p: usize, c: usize| groups.iter().position(|g| g.contains(&(p, c))).unwrap_or(0);
+ let mut pos: Vec<[f64; 2]> = groups.iter().map(|g| planes[g[0].0].dst[g[0].1]).collect();
+ let edges: Vec<(usize, usize)> = (0..planes.len()).flat_map(|p| (0..4).map(move |k| (p, k))).map(|(p, k)| (group_of(p, k), group_of(p, (k + 1) % 4))).collect();
+ for (a, b) in edges {
+ let (pa, pb) = (pos[a], pos[b]);
+ let (dx, dy) = ((pb[0] - pa[0]).abs(), (pb[1] - pa[1]).abs());
+ if dy <= dx && matches!(mode, Straighten::Horizontal | Straighten::Auto) {
+ let y = (pa[1] + pb[1]) / 2.0;
+ pos[a][1] = y;
+ pos[b][1] = y;
+ } else if dx < dy && matches!(mode, Straighten::Vertical | Straighten::Auto) {
+ let x = (pa[0] + pb[0]) / 2.0;
+ pos[a][0] = x;
+ pos[b][0] = x;
+ }
+ }
+ for (g, p) in groups.iter().zip(pos) {
+ for &(pi, ci) in g {
+ planes[pi].dst[ci] = p;
+ }
+ }
+}
+
+impl PerspectiveMap {
+ /// Prepares the map. `None` if a quad is degenerate (or there are no planes).
+ pub fn new(planes: &[Plane]) -> Option<Self> {
+ if planes.is_empty() {
+ return None;
+ }
+ let mut planes = planes.to_vec();
+ unify(&mut planes);
+ let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() <= LINK_EPS && (a[1] - b[1]).abs() <= LINK_EPS;
+ let mut maps = Vec::with_capacity(planes.len());
+ for (i, p) in planes.iter().enumerate() {
+ let src = unit_to_quad(&p.src)?;
+ let src_inv = src.inverse()?;
+ let dst = unit_to_quad(&p.dst)?;
+ let mut shared = [None; 4];
+ for (k, s) in shared.iter_mut().enumerate() {
+ let (a, b) = (p.src[k], p.src[(k + 1) % 4]);
+ *s = planes.iter().enumerate().find(|(j, o)| *j != i && (0..4).any(|m| {
+ let (c, d) = (o.src[m], o.src[(m + 1) % 4]);
+ (near(a, c) && near(b, d)) || (near(a, d) && near(b, c))
+ })).map(|(j, _)| j);
+ }
+ maps.push(PlaneMap { src, src_inv, dst, quad: p.src, shared });
+ }
+ Some(PerspectiveMap { planes: maps })
+ }
+
+ /// The plane containing `p` (or the nearest one) and `p`'s plane coordinates.
+ fn locate(&self, x: f64, y: f64) -> (usize, f64, f64) {
+ let mut best = (0, f64::MAX, 0.0, 0.0);
+ for (i, pm) in self.planes.iter().enumerate() {
+ let (u, v) = pm.src_inv.apply(x, y);
+ if (-1e-9..=1.0 + 1e-9).contains(&u) && (-1e-9..=1.0 + 1e-9).contains(&v) {
+ return (i, u, v);
+ }
+ let d = dist_to_quad(&pm.quad, [x, y]);
+ if d < best.1 {
+ best = (i, d, u, v);
+ }
+ }
+ (best.0, best.2, best.3)
+ }
+
+ /// Maps a source point to the destination.
+ pub fn map(&self, x: f64, y: f64) -> (f64, f64) {
+ let (i, u, v) = self.locate(x, y);
+ let pm = &self.planes[i];
+ let (mut ox, mut oy) = pm.dst.apply(u, v);
+ if !ox.is_finite() || !oy.is_finite() {
+ return (x, y);
+ }
+ let (cu, cv) = (u.clamp(0.0, 1.0), v.clamp(0.0, 1.0));
+ for (k, sh) in pm.shared.iter().enumerate() {
+ let Some(j) = *sh else { continue };
+ let (e, w) = edge_uv(k, cu, cv);
+ if w <= 0.0 {
+ continue;
+ }
+ let mine = pm.dst.apply(e[0], e[1]);
+ let (qx, qy) = pm.src.apply(e[0], e[1]);
+ let other = &self.planes[j];
+ let (ou, ov) = other.src_inv.apply(qx, qy);
+ let theirs = other.dst.apply(ou, ov);
+ let target = ((mine.0 + theirs.0) / 2.0, (mine.1 + theirs.1) / 2.0);
+ ox += w * (target.0 - mine.0);
+ oy += w * (target.1 - mine.1);
+ }
+ (ox, oy)
+ }
+
+ /// Whether every plane maps onto itself (identity).
+ pub fn is_identity(planes: &[Plane]) -> bool {
+ planes.iter().all(|p| p.src.iter().zip(&p.dst).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9))
+ }
+}
+
+fn dist_to_quad(q: &[[f64; 2]; 4], p: [f64; 2]) -> f64 {
+ (0..4)
+ .map(|k| {
+ let (a, b) = (q[k], q[(k + 1) % 4]);
+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
+ let l2 = dx * dx + dy * dy;
+ let t = if l2 > 0.0 { (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
+ ((a[0] + t * dx - p[0]).powi(2) + (a[1] + t * dy - p[1]).powi(2)).sqrt()
+ })
+ .fold(f64::MAX, f64::min)
+}
+
+/// Corners of the unit square in plane order (for callers drawing plane grids).
+pub fn unit_corners() -> [[f64; 2]; 4] {
+ UNIT
+}
+
+/// A point of plane `p` at plane coordinates `(u, v)`, in source space.
+pub fn plane_point(p: &Plane, u: f64, v: f64, dst: bool) -> [f64; 2] {
+ let q = if dst { &p.dst } else { &p.src };
+ unit_to_quad(q).map(|h| {
+ let (x, y) = h.apply(u, v);
+ [x, y]
+ }).unwrap_or(q[0])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn close(a: (f64, f64), b: (f64, f64), tol: f64) -> bool {
+ (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol
+ }
+
+ #[test]
+ fn identity_and_a_known_homography() {
+ let q = [[10.0, 10.0], [90.0, 12.0], [85.0, 70.0], [12.0, 75.0]];
+ let m = PerspectiveMap::new(&[Plane::identity(q)]).unwrap();
+ for p in [(20.0, 20.0), (50.0, 40.0), (0.0, 0.0), (120.0, 90.0)] {
+ assert!(close(m.map(p.0, p.1), p, 1e-9), "{p:?} → {:?}", m.map(p.0, p.1));
+ }
+ // Square → trapezoid: corners land exactly, the centre lands where the homography says.
+ let src = [[0.0, 0.0], [100.0, 0.0], [100.0, 100.0], [0.0, 100.0]];
+ let dst = [[20.0, 0.0], [80.0, 0.0], [100.0, 100.0], [0.0, 100.0]];
+ let m = PerspectiveMap::new(&[Plane { src, dst }]).unwrap();
+ for (s, d) in src.iter().zip(&dst) {
+ assert!(close(m.map(s[0], s[1]), (d[0], d[1]), 1e-9));
+ }
+ let h = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], dst).unwrap();
+ assert!(close(m.map(50.0, 50.0), h.apply(50.0, 50.0), 1e-9));
+ // The diagonals' crossing stays the crossing: (50, 50) maps to the trapezoid's diagonal intersection.
+ let c = m.map(50.0, 50.0);
+ assert!((c.0 - 50.0).abs() < 1e-9 && c.1 < 50.0, "{c:?}");
+ }
+
+ #[test]
+ fn shared_edges_stay_continuous() {
+ // Two planes sharing the edge x = 50 (with slightly mismatched corners that get linked).
+ let a = Plane { src: [[0.0, 0.0], [50.0, 0.0], [50.0, 100.0], [0.0, 100.0]], dst: [[0.0, 10.0], [50.0, 0.0], [55.0, 100.0], [0.0, 90.0]] };
+ let b = Plane { src: [[50.2, 0.0], [100.0, 0.0], [100.0, 100.0], [50.0, 100.2]], dst: [[50.0, 0.0], [110.0, 20.0], [100.0, 80.0], [55.0, 100.0]] };
+ let m = PerspectiveMap::new(&[a, b]).unwrap();
+ // After linking, the shared edge runs from (50.1, 0) to (50, 100.1).
+ for t in [0.05, 0.25, 0.5, 0.77, 0.95] {
+ let (x, y) = (50.1 - 0.1 * t, 100.1 * t);
+ let l = m.map(x - 1e-6, y);
+ let r = m.map(x + 1e-6, y);
+ assert!(close(l, r, 1e-4), "t={t}: {l:?} vs {r:?}");
+ }
+ assert_eq!(linked_corners(&[Plane::identity([[0.0; 2]; 4])]).len(), 1);
+ }
+
+ #[test]
+ fn straighten_levels_and_plumbs_edges() {
+ let mut ps = vec![Plane { src: [[0.0, 0.0], [100.0, 0.0], [100.0, 100.0], [0.0, 100.0]], dst: [[0.0, 3.0], [100.0, -2.0], [96.0, 100.0], [4.0, 104.0]] }];
+ straighten(&mut ps, Straighten::Vertical);
+ assert_eq!(ps[0].dst[1][0], ps[0].dst[2][0]);
+ assert_eq!(ps[0].dst[0][0], ps[0].dst[3][0]);
+ assert_ne!(ps[0].dst[0][1], ps[0].dst[1][1]);
+ straighten(&mut ps, Straighten::Auto);
+ assert_eq!(ps[0].dst[0][1], ps[0].dst[1][1]);
+ assert_eq!(ps[0].dst[2][1], ps[0].dst[3][1]);
+ }
+}
diff --git a/crates/algo/src/pixelate.rs b/crates/algo/src/pixelate.rs
new file mode 100644
index 000000000..5114c5f3f
--- /dev/null
+++ b/crates/algo/src/pixelate.rs
@@ -0,0 +1,330 @@
+//! Pixelate: Color Halftone, Crystallize, Facet, Fragment, Mezzotint, Pointillize.
+//!
+//! Cell layouts are anchored at the reference bounds' origin and random
+//! choices hash document coordinates, so output is independent of tiling.
+
+use photocraft_geom::Rect;
+
+use crate::fxutil::{MAXC, cell_point, luma, native, ncol, rgba, set_rgba, subtractive, via_rgb, xy};
+use crate::image::Image;
+use crate::noise::hash01;
+use crate::{Ctx, MezzotintType};
+
+/// Colour Halftone: each channel is screened at its own angle into dots
+/// whose area follows the channel's ink (1 − value in additive models).
+pub(crate) fn color_halftone(src: &Image, out: Rect, ctx: &Ctx, max_radius: f32, angles: [f32; 4]) -> Vec<f32> {
+ let n = src.ch;
+ let cc = ncol(ctx, n);
+ let rmax = max_radius.max(1.0);
+ // Cell side such that a full-size dot just covers the cell's corners.
+ let cell = rmax * std::f32::consts::SQRT_2;
+ let sub = subtractive(ctx);
+ let rgb = via_rgb(ctx);
+ let mut res = src.crop(out);
+ let b = ctx.bounds;
+ let (ox, oy) = (b.x0 as f32, b.y0 as f32);
+ let rot: Vec<(f32, f32)> = (0..cc.max(3)).map(|c| angles[c.min(3)].to_radians().sin_cos()).collect();
+ let clip = b.intersect(&src.rect);
+ if clip.is_empty() {
+ return res;
+ }
+ // Channel value at a point averaged over five taps (for Lab, of the RGB conversion).
+ let value = |x: f32, y: f32, c: usize| -> f32 {
+ let d = cell * 0.25;
+ let mut acc = 0.0;
+ let mut px = [0.0f32; MAXC];
+ for (dx, dy) in [(0.0, 0.0), (-d, -d), (d, -d), (-d, d), (d, d)] {
+ // Clamp to the bounds so cells straddling the edge read real pixels.
+ let (ix, iy) = (((x + dx).floor() as i32).clamp(clip.x0, clip.x1 - 1), ((y + dy).floor() as i32).clamp(clip.y0, clip.y1 - 1));
+ if rgb {
+ for (k, p) in px.iter_mut().enumerate().take(n) {
+ *p = src.get(ix, iy, k);
+ }
+ acc += rgba(ctx, &px[..n])[c];
+ } else {
+ acc += src.get(ix, iy, c);
+ }
+ }
+ acc / 5.0
+ };
+ let w = out.width() as usize;
+ let chans = if rgb { 3 } else { cc };
+ let mut vals = [0.0f32; MAXC];
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = (out.x0 + (i % w) as i32, out.y0 + (i / w) as i32);
+ let (fx, fy) = (x as f32 + 0.5 - ox, y as f32 + 0.5 - oy);
+ for (c, v) in vals.iter_mut().enumerate().take(chans) {
+ let (s, co) = rot[c];
+ // Rotate into screen space.
+ let (u, w2) = (fx * co + fy * s, -fx * s + fy * co);
+ let (cu, cv) = ((u / cell).floor(), (w2 / cell).floor());
+ let mut cov: f32 = 0.0;
+ for dj in -1..=1 {
+ for di in -1..=1 {
+ let (mu, mv) = ((cu + di as f32 + 0.5) * cell, (cv + dj as f32 + 0.5) * cell);
+ let d = ((u - mu).powi(2) + (w2 - mv).powi(2)).sqrt();
+ if d >= rmax + 0.5 {
+ continue;
+ }
+ // Back to document space to read the cell's value.
+ let (dx, dy) = (mu * co - mv * s + ox, mu * s + mv * co + oy);
+ let raw = value(dx, dy, c).clamp(0.0, 1.0);
+ let ink = if sub && !rgb { raw } else { 1.0 - raw };
+ // Dot area tracks ink: πr² = ink·cell² until dots touch, then grow to cover the corners.
+ let touch = std::f32::consts::FRAC_PI_4;
+ let r = if ink <= touch { cell * (ink / std::f32::consts::PI).sqrt() } else { cell * (0.5 + (ink - touch) / (1.0 - touch) * (std::f32::consts::FRAC_1_SQRT_2 - 0.5)) };
+ // Tiny dots cannot cover more than their own area.
+ cov = cov.max((r - d + 0.5).clamp(0.0, 1.0).min(std::f32::consts::PI * r * r));
+ }
+ }
+ *v = if sub && !rgb { cov } else { 1.0 - cov };
+ }
+ if rgb {
+ let a = if ctx.alpha { px[n - 1] } else { 1.0 };
+ set_rgba(ctx, px, [vals[0], vals[1], vals[2], a]);
+ } else {
+ px[..cc].copy_from_slice(&vals[..cc]);
+ }
+ }
+ res
+}
+
+/// Crystallize: Voronoi cells around jittered points, each filled with the
+/// (premultiplied) average colour of its pixels.
+pub(crate) fn crystallize(src: &Image, out: Rect, ctx: &Ctx, cell_size: f32, seed: u32) -> Vec<f32> {
+ let n = src.ch;
+ let cell = cell_size.max(2.0);
+ let b = ctx.bounds;
+ let origin = (b.x0 as f32, b.y0 as f32);
+ // Cells whose territory can reach `out`, and the window holding all their pixels.
+ let c0 = (((out.x0 - b.x0) as f32 / cell).floor() as i32 - 2, ((out.y0 - b.y0) as f32 / cell).floor() as i32 - 2);
+ let c1 = (((out.x1 - b.x0) as f32 / cell).floor() as i32 + 2, ((out.y1 - b.y0) as f32 / cell).floor() as i32 + 2);
+ let (gw, gh) = ((c1.0 - c0.0 + 1) as usize, (c1.1 - c0.1 + 1) as usize);
+ let owner = |x: i32, y: i32| -> (i32, i32) {
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let (cx, cy) = (((fx - origin.0) / cell).floor() as i32, ((fy - origin.1) / cell).floor() as i32);
+ let mut best = (f32::MAX, (cx, cy));
+ for dy in -1..=1 {
+ for dx in -1..=1 {
+ let (px, py) = cell_point(cx + dx, cy + dy, cell, seed, origin);
+ let d = (px - fx).powi(2) + (py - fy).powi(2);
+ if d < best.0 {
+ best = (d, (cx + dx, cy + dy));
+ }
+ }
+ }
+ best.1
+ };
+ let mut acc = vec![0.0f32; gw * gh * (n + 1)];
+ let win = Rect::new(b.x0 + (c0.0 as f32 * cell).floor() as i32, b.y0 + (c0.1 as f32 * cell).floor() as i32, b.x0 + ((c1.0 + 1) as f32 * cell).ceil() as i32, b.y0 + ((c1.1 + 1) as f32 * cell).ceil() as i32)
+ .intersect(&src.rect)
+ .intersect(&b);
+ let mut owners = vec![(0i32, 0i32); out.width() as usize * out.height() as usize];
+ for y in win.y0..win.y1 {
+ for x in win.x0..win.x1 {
+ let (cx, cy) = owner(x, y);
+ if out.contains(x, y) {
+ owners[((y - out.y0) as usize) * out.width() as usize + (x - out.x0) as usize] = (cx, cy);
+ }
+ if cx < c0.0 || cy < c0.1 || cx > c1.0 || cy > c1.1 {
+ continue;
+ }
+ let k = ((cy - c0.1) as usize * gw + (cx - c0.0) as usize) * (n + 1);
+ let a = if ctx.alpha { src.get(x, y, n - 1) } else { 1.0 };
+ for c in 0..n {
+ let s = src.get(x, y, c);
+ acc[k + c] += if ctx.alpha && c < n - 1 { s * a } else { s };
+ }
+ acc[k + n] += 1.0;
+ }
+ }
+ // Pixels of `out` outside the bounds keep their own value; resolve owners for any missed.
+ let mut res = src.crop(out);
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ if !b.contains(x, y) {
+ continue;
+ }
+ let (cx, cy) = if win.contains(x, y) { owners[i] } else { owner(x, y) };
+ if cx < c0.0 || cy < c0.1 || cx > c1.0 || cy > c1.1 {
+ continue;
+ }
+ let k = ((cy - c0.1) as usize * gw + (cx - c0.0) as usize) * (n + 1);
+ let cnt = acc[k + n];
+ if cnt <= 0.0 {
+ continue;
+ }
+ for c in 0..n {
+ px[c] = acc[k + c] / cnt;
+ }
+ crate::fxutil::unpremul_px(px, ctx.alpha);
+ }
+ res
+}
+
+/// Facet: a Kuwahara filter (radius 2) — each pixel takes the mean of the
+/// least-varied of its four overlapping quadrants, clumping similar colours
+/// into flat facets while keeping edges.
+pub(crate) fn facet(src: &Image, out: Rect, ctx: &Ctx) -> Vec<f32> {
+ let n = src.ch;
+ let r = 2i32;
+ let mut res = src.crop(out);
+ let mut tmp = [0.0f32; MAXC];
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ let mut best = (f32::MAX, [0.0f32; MAXC]);
+ for (qx, qy) in [(-r, -r), (0, -r), (-r, 0), (0, 0)] {
+ let mut sum = [0.0f32; MAXC];
+ let (mut s, mut s2) = (0.0f32, 0.0f32);
+ for yy in y + qy..=y + qy + r {
+ for xx in x + qx..=x + qx + r {
+ for (c, t) in tmp.iter_mut().enumerate().take(n) {
+ *t = src.get(xx, yy, c);
+ sum[c] += *t;
+ }
+ let l = luma(ctx, &tmp[..n]);
+ s += l;
+ s2 += l * l;
+ }
+ }
+ let cnt = ((r + 1) * (r + 1)) as f32;
+ let var = s2 / cnt - (s / cnt).powi(2);
+ if var < best.0 {
+ for v in sum.iter_mut() {
+ *v /= cnt;
+ }
+ best = (var, sum);
+ }
+ }
+ px.copy_from_slice(&best.1[..n]);
+ }
+ res
+}
+
+/// Fragment: the average of four copies offset by 4 px (left, right, up, down).
+pub(crate) fn fragment(src: &Image, out: Rect, ctx: &Ctx) -> Vec<f32> {
+ let n = src.ch;
+ let mut res = Vec::with_capacity(out.width() as usize * out.height() as usize * n);
+ let mut acc = [0.0f32; MAXC];
+ for y in out.y0..out.y1 {
+ for x in out.x0..out.x1 {
+ acc[..n].fill(0.0);
+ for (dx, dy) in [(-4, 0), (4, 0), (0, -4), (0, 4)] {
+ let a = if ctx.alpha { src.get(x + dx, y + dy, n - 1) } else { 1.0 };
+ for (c, v) in acc.iter_mut().enumerate().take(n) {
+ let s = src.get(x + dx, y + dy, c);
+ *v += if ctx.alpha && c < n - 1 { s * a } else { s } * 0.25;
+ }
+ }
+ crate::fxutil::unpremul_px(&mut acc[..n], ctx.alpha);
+ res.extend_from_slice(&acc[..n]);
+ }
+ }
+ res
+}
+
+/// Random threshold for Mezzotint pattern `kind` at a pixel.
+fn mezzo_threshold(kind: MezzotintType, x: i32, y: i32, c: u32, seed: u32) -> f32 {
+ let lines = |len: i32| {
+ let phase = (hash01(0, y, c + 40, seed) * len as f32) as i32;
+ hash01((x + phase).div_euclid(len), y, c, seed)
+ };
+ let strokes = |len: i32| {
+ let d = x - y;
+ let phase = (hash01(d, 0, c + 50, seed) * len as f32) as i32;
+ hash01((x + y + phase).div_euclid(len), d, c + 60, seed)
+ };
+ match kind {
+ MezzotintType::FineDots => hash01(x, y, c, seed),
+ MezzotintType::MediumDots => hash01(x.div_euclid(2), y.div_euclid(2), c, seed),
+ MezzotintType::GrainyDots => 0.5 * hash01(x, y, c, seed) + 0.5 * hash01(x.div_euclid(3), y.div_euclid(3), c + 7, seed),
+ MezzotintType::CoarseDots => hash01(x.div_euclid(3), y.div_euclid(3), c, seed),
+ MezzotintType::ShortLines => lines(6),
+ MezzotintType::MediumLines => lines(14),
+ MezzotintType::LongLines => lines(32),
+ MezzotintType::ShortStrokes => strokes(5),
+ MezzotintType::MediumStrokes => strokes(10),
+ MezzotintType::LongStrokes => strokes(20),
+ }
+}
+
+/// Mezzotint: every colour channel is thresholded against a random pattern,
+/// giving pure channel values (fully saturated dots/lines in colour images).
+pub(crate) fn mezzotint(src: &Image, out: Rect, ctx: &Ctx, kind: MezzotintType, seed: u32) -> Vec<f32> {
+ let n = src.ch;
+ let cc = ncol(ctx, n);
+ let rgb = via_rgb(ctx);
+ let mut res = src.crop(out);
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ if rgb {
+ let mut c = rgba(ctx, px);
+ for (k, v) in c.iter_mut().enumerate().take(3) {
+ *v = if *v > mezzo_threshold(kind, x, y, k as u32, seed) { 1.0 } else { 0.0 };
+ }
+ set_rgba(ctx, px, c);
+ } else {
+ for (k, v) in px.iter_mut().enumerate().take(cc) {
+ *v = if *v > mezzo_threshold(kind, x, y, k as u32, seed) { 1.0 } else { 0.0 };
+ }
+ }
+ }
+ res
+}
+
+/// Pointillize: randomly sized dots, coloured from the image at their centre,
+/// on a canvas of the background colour.
+pub(crate) fn pointillize(src: &Image, out: Rect, ctx: &Ctx, cell_size: f32, seed: u32, background: [f32; 4]) -> Vec<f32> {
+ let n = src.ch;
+ let cell = cell_size.max(2.0);
+ let b = ctx.bounds;
+ let origin = (b.x0 as f32, b.y0 as f32);
+ let bg = native(ctx, background);
+ let mut res = src.crop(out);
+ let mut dot = [0.0f32; MAXC];
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let (cx, cy) = (((fx - origin.0) / cell).floor() as i32, ((fy - origin.1) / cell).floor() as i32);
+ // The dot whose edge the pixel is deepest inside wins.
+ let mut best: Option<(f32, i32, i32, f32, f32)> = None;
+ for dy in -1..=1 {
+ for dx in -1..=1 {
+ let (gx, gy) = (cx + dx, cy + dy);
+ let (px0, py0) = cell_point(gx, gy, cell, seed, origin);
+ let rad = cell * (0.45 + 0.35 * hash01(gx, gy, 13, seed));
+ let d = ((px0 - fx).powi(2) + (py0 - fy).powi(2)).sqrt();
+ let depth = rad - d;
+ if depth > -0.5 && best.is_none_or(|bb| depth > bb.0) {
+ best = Some((depth, gx, gy, px0, py0));
+ }
+ }
+ }
+ let a_orig = if ctx.alpha { px[n - 1] } else { 1.0 };
+ // Canvas first, then the dot over it with an anti-aliased edge.
+ let mut canvas = [0.0f32; MAXC];
+ canvas[..n].copy_from_slice(&bg[..n]);
+ if ctx.alpha {
+ canvas[n - 1] = a_orig.max(bg[n - 1].min(1.0));
+ }
+ if let Some((depth, gx, gy, px0, py0)) = best {
+ let (sx, sy) = (px0.floor() as i32, py0.floor() as i32);
+ for (c, d) in dot.iter_mut().enumerate().take(n) {
+ *d = src.get(sx, sy, c);
+ }
+ // Slight per-dot brightness jitter, as in pointillist strokes.
+ let j = (hash01(gx, gy, 17, seed) - 0.5) * 0.08;
+ let cc = ncol(ctx, n);
+ let sub = subtractive(ctx);
+ for d in dot.iter_mut().take(cc) {
+ *d = (*d + if sub { -j } else { j }).clamp(0.0, 1.0);
+ }
+ let k = (depth + 0.5).clamp(0.0, 1.0);
+ for c in 0..n {
+ canvas[c] += (dot[c] - canvas[c]) * k;
+ }
+ }
+ px.copy_from_slice(&canvas[..n]);
+ }
+ res
+}
diff --git a/crates/algo/src/puppet.rs b/crates/algo/src/puppet.rs
new file mode 100644
index 000000000..b998e81e0
--- /dev/null
+++ b/crates/algo/src/puppet.rs
@@ -0,0 +1,765 @@
+//! Edit › Puppet Warp: pins on a triangle mesh over the layer's opaque region, deformed
+//! as-rigidly-as-possible.
+//!
+//! * **Mesh.** The layer's coverage (alpha above a threshold, grown or shrunk by `expansion`) is
+//! rasterized onto a coarse block grid; a square grid at the density's spacing keeps every
+//! cell that touches covered blocks, split into two triangles (alternating diagonals). A
+//! grid-clipped mesh is simple, robust and uniform, which is all ARAP needs.
+//! * **Deformation.** The per-triangle ARAP energy of Liu et al. 2008 (the triangle form of
+//! Sorkine & Alexa 2007), `E = Σ_t Σ_(i,j)∈t w_ij |(v_i − v_j) − R_t (x_i − x_j)|²` with
+//! cotangent weights, minimized by alternating a local step (best rotation per triangle from
+//! the 2×2 covariance: `atan2(S10 − S01, S00 + S11)`) and a global step (one sparse SPD solve
+//! per axis, Jacobi-preconditioned conjugate gradients, warm-started). Pins are stiff soft
+//! constraints on the barycentric point under them. The first global step uses `R = I`
+//! (a harmonic deformation), which is the classic initialisation. Modes change the local
+//! step: Rigid fits rotations, Distort fits similarities (rotation × scale, i.e. ASAP), and
+//! Normal fits rotation × √scale, in between. A pin's rotation fixes `R` on the triangles
+//! around it. Mesh components without a pin stay where they are.
+//! * **Rendering.** Triangles are rasterized with [`crate::warp::warp_triangles`] (tile-parallel,
+//! premultiplied, bilinear/bicubic), back to front by the depth of their nearest pin.
+
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde::{Deserialize, Serialize};
+
+use crate::transform::Interp;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum PuppetMode {
+ Rigid,
+ #[default]
+ Normal,
+ Distort,
+}
+
+impl PuppetMode {
+ pub fn parse(s: &str) -> Option<Self> {
+ match s.to_ascii_lowercase().as_str() {
+ "rigid" => Some(PuppetMode::Rigid),
+ "normal" => Some(PuppetMode::Normal),
+ "distort" => Some(PuppetMode::Distort),
+ _ => None,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum PuppetDensity {
+ Fewer,
+ #[default]
+ Normal,
+ More,
+}
+
+impl PuppetDensity {
+ pub fn parse(s: &str) -> Option<Self> {
+ match s.to_ascii_lowercase().as_str() {
+ "fewer" | "fewerpoints" => Some(PuppetDensity::Fewer),
+ "normal" => Some(PuppetDensity::Normal),
+ "more" | "morepoints" => Some(PuppetDensity::More),
+ _ => None,
+ }
+ }
+
+ fn cells(self) -> f64 {
+ match self {
+ PuppetDensity::Fewer => 12.0,
+ PuppetDensity::Normal => 20.0,
+ PuppetDensity::More => 32.0,
+ }
+ }
+}
+
+/// A pin: where it was placed (`src`) and where it is now (`dst`), document pixels.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct PuppetPin {
+ pub src: [f64; 2],
+ pub dst: [f64; 2],
+ /// Fixed rotation of the mesh around the pin (degrees); `None` = automatic.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub rotate: Option<f64>,
+ /// Pin depth: where the mesh overlaps itself, triangles nearest a higher pin draw on top.
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub depth: i32,
+}
+
+fn is_zero(v: &i32) -> bool {
+ *v == 0
+}
+
+fn d_expansion() -> f64 {
+ 2.0
+}
+
+/// A complete puppet warp (the command's params and a smart filter's stored data).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct PuppetWarp {
+ #[serde(default)]
+ pub pins: Vec<PuppetPin>,
+ #[serde(default)]
+ pub mode: PuppetMode,
+ #[serde(default)]
+ pub density: PuppetDensity,
+ /// Grows (or with a negative value shrinks) the mesh beyond the opaque region, px.
+ #[serde(default = "d_expansion")]
+ pub expansion: f64,
+}
+
+impl PuppetWarp {
+ pub fn is_identity(&self) -> bool {
+ self.pins.iter().all(|p| p.src == p.dst && p.rotate.is_none_or(|r| r.rem_euclid(360.0) == 0.0))
+ }
+}
+
+/// A triangle mesh in document pixels.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct PuppetMesh {
+ pub verts: Vec<[f64; 2]>,
+ pub tris: Vec<[usize; 3]>,
+ /// Grid spacing (px).
+ pub spacing: f64,
+}
+
+/// Coverage threshold: alpha above this counts as part of the puppet.
+const ALPHA_MIN: f32 = 0.05;
+
+/// Builds the mesh over the covered part of `src` inside `bounds`.
+pub fn build_mesh(src: &Surface, bounds: Rect, density: PuppetDensity, expansion: f64) -> PuppetMesh {
+ if bounds.is_empty() {
+ return PuppetMesh::default();
+ }
+ let long = f64::from(bounds.width().max(bounds.height()));
+ let spacing = (long / density.cells()).max(2.0);
+ let e = expansion.clamp(-200.0, 200.0);
+ // Coverage on a block grid (block = a quarter cell or less).
+ let g = ((spacing / 4.0).floor() as i32).max(1);
+ let pad = e.max(0.0).ceil() as i32 + g;
+ let area = bounds.inflate(pad);
+ let bw = (area.width() as i32 + g - 1) / g;
+ let bh = (area.height() as i32 + g - 1) / g;
+ let (bw, bh) = (bw as usize, bh as usize);
+ let mut cov = vec![false; bw * bh];
+ let fmt = src.format();
+ let n = fmt.channels();
+ if !fmt.alpha {
+ for by in 0..bh {
+ for bx in 0..bw {
+ let r = Rect::new(area.x0 + bx as i32 * g, area.y0 + by as i32 * g, area.x0 + (bx as i32 + 1) * g, area.y0 + (by as i32 + 1) * g);
+ cov[by * bw + bx] = !r.intersect(&bounds).is_empty();
+ }
+ }
+ } else {
+ let mut row = Vec::new();
+ for by in 0..bh {
+ let r = Rect::new(area.x0, area.y0 + by as i32 * g, area.x0 + bw as i32 * g, area.y0 + (by as i32 + 1) * g).intersect(&bounds);
+ if r.is_empty() || !src.has_tiles_in(r) {
+ continue;
+ }
+ src.read_region_into(r, &mut row);
+ let rw = r.width() as usize;
+ for (i, p) in row.chunks_exact(n).enumerate() {
+ if p[n - 1] > ALPHA_MIN {
+ let x = r.x0 + (i % rw) as i32;
+ let bx = ((x - area.x0) / g) as usize;
+ cov[by * bw + bx] = true;
+ }
+ }
+ }
+ }
+ // Grow / shrink by the expansion (round stamp in block units).
+ let eb = (e.abs() / f64::from(g)).round() as i32;
+ if eb > 0 {
+ let src_cov = cov.clone();
+ let grow = e > 0.0;
+ for by in 0..bh as i32 {
+ for bx in 0..bw as i32 {
+ let mut hit = !grow;
+ 'stamp: for dy in -eb..=eb {
+ for dx in -eb..=eb {
+ if dx * dx + dy * dy > eb * eb {
+ continue;
+ }
+ let (x, y) = (bx + dx, by + dy);
+ let v = x >= 0 && y >= 0 && x < bw as i32 && y < bh as i32 && src_cov[y as usize * bw + x as usize];
+ if grow && v {
+ hit = true;
+ break 'stamp;
+ }
+ if !grow && !v {
+ hit = false;
+ break 'stamp;
+ }
+ }
+ }
+ cov[by as usize * bw + bx as usize] = hit;
+ }
+ }
+ }
+ // Grid cells touching covered blocks.
+ let ox = f64::from(area.x0);
+ let oy = f64::from(area.y0);
+ let cw = (f64::from(bw as i32 * g) / spacing).ceil() as usize;
+ let ch = (f64::from(bh as i32 * g) / spacing).ceil() as usize;
+ let mut index = vec![usize::MAX; (cw + 1) * (ch + 1)];
+ let mut mesh = PuppetMesh { spacing, ..Default::default() };
+ for cj in 0..ch {
+ for ci in 0..cw {
+ let bx0 = ((ci as f64 * spacing) / f64::from(g)).floor() as usize;
+ let by0 = ((cj as f64 * spacing) / f64::from(g)).floor() as usize;
+ let bx1 = (((ci + 1) as f64 * spacing) / f64::from(g)).ceil().min(bw as f64) as usize;
+ let by1 = (((cj + 1) as f64 * spacing) / f64::from(g)).ceil().min(bh as f64) as usize;
+ let any = (by0..by1).any(|y| (bx0..bx1).any(|x| cov[y * bw + x]));
+ if !any {
+ continue;
+ }
+ let mut v = |i: usize, j: usize| {
+ let k = j * (cw + 1) + i;
+ if index[k] == usize::MAX {
+ index[k] = mesh.verts.len();
+ mesh.verts.push([ox + i as f64 * spacing, oy + j as f64 * spacing]);
+ }
+ index[k]
+ };
+ let (a, b, c, d) = (v(ci, cj), v(ci + 1, cj), v(ci + 1, cj + 1), v(ci, cj + 1));
+ if (ci + cj) % 2 == 0 {
+ mesh.tris.push([a, b, c]);
+ mesh.tris.push([a, c, d]);
+ } else {
+ mesh.tris.push([a, b, d]);
+ mesh.tris.push([b, c, d]);
+ }
+ }
+ }
+ mesh
+}
+
+/// A compressed sparse row matrix (symmetric, used by CG).
+struct Csr {
+ rows: Vec<usize>,
+ cols: Vec<usize>,
+ vals: Vec<f64>,
+ diag: Vec<f64>,
+}
+
+impl Csr {
+ fn from_triplets(n: usize, mut t: Vec<(usize, usize, f64)>) -> Csr {
+ t.sort_by_key(|a| (a.0, a.1));
+ let mut rows = vec![0usize; n + 1];
+ let mut cols = Vec::with_capacity(t.len());
+ let mut vals: Vec<f64> = Vec::with_capacity(t.len());
+ let mut last = (usize::MAX, usize::MAX);
+ for (i, j, v) in t {
+ if (i, j) == last {
+ *vals.last_mut().unwrap_or(&mut 0.0) += v;
+ continue;
+ }
+ last = (i, j);
+ cols.push(j);
+ vals.push(v);
+ rows[i + 1] = cols.len();
+ }
+ for i in 0..n {
+ rows[i + 1] = rows[i + 1].max(rows[i]);
+ }
+ let mut diag = vec![1.0; n];
+ for (i, d) in diag.iter_mut().enumerate() {
+ for k in rows[i]..rows[i + 1] {
+ if cols[k] == i && vals[k] > 0.0 {
+ *d = vals[k];
+ }
+ }
+ }
+ Csr { rows, cols, vals, diag }
+ }
+
+ fn mul(&self, x: &[f64], out: &mut [f64]) {
+ for (i, o) in out.iter_mut().enumerate() {
+ let mut s = 0.0;
+ for k in self.rows[i]..self.rows[i + 1] {
+ s += self.vals[k] * x[self.cols[k]];
+ }
+ *o = s;
+ }
+ }
+
+ /// Jacobi-preconditioned conjugate gradients, warm-started from `x`.
+ fn solve(&self, b: &[f64], x: &mut [f64]) {
+ let n = b.len();
+ let mut r = vec![0.0; n];
+ self.mul(x, &mut r);
+ for i in 0..n {
+ r[i] = b[i] - r[i];
+ }
+ let bn: f64 = b.iter().map(|v| v * v).sum::<f64>().sqrt().max(1e-30);
+ let mut z: Vec<f64> = r.iter().zip(&self.diag).map(|(r, d)| r / d).collect();
+ let mut p = z.clone();
+ let mut rz: f64 = r.iter().zip(&z).map(|(a, b)| a * b).sum();
+ let mut ap = vec![0.0; n];
+ for _ in 0..(4 * n).clamp(50, 2000) {
+ if r.iter().map(|v| v * v).sum::<f64>().sqrt() <= 1e-12 * bn {
+ break;
+ }
+ self.mul(&p, &mut ap);
+ let pap: f64 = p.iter().zip(&ap).map(|(a, b)| a * b).sum();
+ if pap.abs() < 1e-300 {
+ break;
+ }
+ let alpha = rz / pap;
+ for i in 0..n {
+ x[i] += alpha * p[i];
+ r[i] -= alpha * ap[i];
+ }
+ for i in 0..n {
+ z[i] = r[i] / self.diag[i];
+ }
+ let rz2: f64 = r.iter().zip(&z).map(|(a, b)| a * b).sum();
+ let beta = rz2 / rz;
+ rz = rz2;
+ for i in 0..n {
+ p[i] = z[i] + beta * p[i];
+ }
+ }
+ }
+}
+
+/// A pin bound to the mesh: barycentric weights on a triangle's vertices.
+#[derive(Clone, Debug)]
+struct Bound {
+ verts: [usize; 3],
+ bary: [f64; 3],
+}
+
+/// Prepared ARAP solver for one mesh and a set of pin source positions.
+pub struct PuppetSolver {
+ pub mesh: PuppetMesh,
+ /// Cotangent weight of each triangle's edges: `w[t][k]` for the edge opposite corner `k`.
+ w: Vec<[f64; 3]>,
+ bound: Vec<Bound>,
+ /// Triangles whose rotation a pin fixes: (pin index, triangles).
+ pin_tris: Vec<Vec<usize>>,
+ /// Vertices of components without pins (held at rest).
+ anchored: Vec<bool>,
+ matrix: Csr,
+ pin_weight: f64,
+}
+
+fn cot(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> f64 {
+ // Cotangent of the angle at `a`.
+ let (u, v) = ([b[0] - a[0], b[1] - a[1]], [c[0] - a[0], c[1] - a[1]]);
+ let cross = (u[0] * v[1] - u[1] * v[0]).abs();
+ if cross < 1e-12 { 0.0 } else { (u[0] * v[0] + u[1] * v[1]) / cross }
+}
+
+fn locate(mesh: &PuppetMesh, p: [f64; 2]) -> Bound {
+ for t in &mesh.tris {
+ let [a, b, c] = t.map(|i| mesh.verts[i]);
+ let det = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
+ if det.abs() < 1e-12 {
+ continue;
+ }
+ let l1 = ((p[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (p[1] - a[1])) / det;
+ let l2 = ((b[0] - a[0]) * (p[1] - a[1]) - (p[0] - a[0]) * (b[1] - a[1])) / det;
+ let l0 = 1.0 - l1 - l2;
+ if l0 >= -1e-9 && l1 >= -1e-9 && l2 >= -1e-9 {
+ return Bound { verts: *t, bary: [l0, l1, l2] };
+ }
+ }
+ // Outside the mesh: the nearest vertex.
+ let i = (0..mesh.verts.len()).min_by(|&a, &b| dist2(mesh.verts[a], p).total_cmp(&dist2(mesh.verts[b], p))).unwrap_or(0);
+ Bound { verts: [i, i, i], bary: [1.0, 0.0, 0.0] }
+}
+
+fn dist2(a: [f64; 2], b: [f64; 2]) -> f64 {
+ (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)
+}
+
+impl PuppetSolver {
+ /// Prepares the solver for pins placed at `pin_src` (rotation-fixed pins listed in
+ /// `fixed_rotation`).
+ pub fn new(mesh: PuppetMesh, pin_src: &[[f64; 2]], fixed_rotation: &[bool]) -> Self {
+ let nv = mesh.verts.len();
+ let w: Vec<[f64; 3]> = mesh
+ .tris
+ .iter()
+ .map(|t| {
+ let [a, b, c] = t.map(|i| mesh.verts[i]);
+ [0.5 * cot(a, b, c), 0.5 * cot(b, c, a), 0.5 * cot(c, a, b)]
+ })
+ .collect();
+ let bound: Vec<Bound> = pin_src.iter().map(|p| locate(&mesh, *p)).collect();
+ // Connected components (union-find over triangle edges).
+ let mut parent: Vec<usize> = (0..nv).collect();
+ fn find(p: &mut [usize], mut i: usize) -> usize {
+ while p[i] != i {
+ p[i] = p[p[i]];
+ i = p[i];
+ }
+ i
+ }
+ for t in &mesh.tris {
+ for k in 1..3 {
+ let (a, b) = (find(&mut parent, t[0]), find(&mut parent, t[k]));
+ if a != b {
+ parent[a] = b;
+ }
+ }
+ }
+ let mut pinned_root = vec![false; nv];
+ for b in &bound {
+ for &v in &b.verts {
+ let r = find(&mut parent, v);
+ pinned_root[r] = true;
+ }
+ }
+ let anchored: Vec<bool> = (0..nv).map(|v| !pinned_root[find(&mut parent, v)]).collect();
+ // Rotation-fixed pins: the triangles around the pin's nearest vertex.
+ let pin_tris: Vec<Vec<usize>> = bound
+ .iter()
+ .zip(pin_src)
+ .enumerate()
+ .map(|(k, (b, p))| {
+ if !fixed_rotation.get(k).copied().unwrap_or(false) {
+ return Vec::new();
+ }
+ let v = *b.verts.iter().min_by(|&&a, &&c| dist2(mesh.verts[a], *p).total_cmp(&dist2(mesh.verts[c], *p))).unwrap_or(&0);
+ mesh.tris.iter().enumerate().filter(|(_, t)| t.contains(&v)).map(|(i, _)| i).collect()
+ })
+ .collect();
+ let mut trip: Vec<(usize, usize, f64)> = Vec::with_capacity(mesh.tris.len() * 12 + nv);
+ let mut diag_sum = 0.0;
+ for (t, wt) in mesh.tris.iter().zip(&w) {
+ for k in 0..3 {
+ let (i, j) = (t[(k + 1) % 3], t[(k + 2) % 3]);
+ let wk = wt[k];
+ trip.push((i, i, wk));
+ trip.push((j, j, wk));
+ trip.push((i, j, -wk));
+ trip.push((j, i, -wk));
+ diag_sum += 2.0 * wk;
+ }
+ }
+ let pin_weight = 1e4 * (diag_sum / nv.max(1) as f64).max(1.0);
+ for b in &bound {
+ for a in 0..3 {
+ for c in 0..3 {
+ trip.push((b.verts[a], b.verts[c], pin_weight * b.bary[a] * b.bary[c]));
+ }
+ }
+ }
+ for (v, &an) in anchored.iter().enumerate() {
+ if an {
+ trip.push((v, v, pin_weight));
+ }
+ }
+ let matrix = Csr::from_triplets(nv, trip);
+ PuppetSolver { mesh, w, bound, pin_tris, anchored, matrix, pin_weight }
+ }
+
+ /// The ARAP energy of `v` for the given per-triangle linear maps (plus the pin terms).
+ fn energy_with(&self, v: &[[f64; 2]], rots: &[[f64; 4]], pin_dst: &[[f64; 2]]) -> f64 {
+ let x = &self.mesh.verts;
+ let mut e = 0.0;
+ for ((t, wt), r) in self.mesh.tris.iter().zip(&self.w).zip(rots) {
+ for k in 0..3 {
+ let (i, j) = (t[(k + 1) % 3], t[(k + 2) % 3]);
+ let d = [v[i][0] - v[j][0], v[i][1] - v[j][1]];
+ let ex = [x[i][0] - x[j][0], x[i][1] - x[j][1]];
+ let re = [r[0] * ex[0] + r[1] * ex[1], r[2] * ex[0] + r[3] * ex[1]];
+ e += wt[k] * ((d[0] - re[0]).powi(2) + (d[1] - re[1]).powi(2));
+ }
+ }
+ for (b, d) in self.bound.iter().zip(pin_dst) {
+ let p = (0..3).fold([0.0, 0.0], |a, k| [a[0] + b.bary[k] * v[b.verts[k]][0], a[1] + b.bary[k] * v[b.verts[k]][1]]);
+ e += self.pin_weight * dist2(p, *d);
+ }
+ e
+ }
+
+ fn local(&self, v: &[[f64; 2]], mode: PuppetMode, fixed: &[Option<f64>]) -> Vec<[f64; 4]> {
+ let x = &self.mesh.verts;
+ let mut rots: Vec<[f64; 4]> = self
+ .mesh
+ .tris
+ .iter()
+ .zip(&self.w)
+ .map(|(t, wt)| {
+ let mut s = [0.0f64; 4];
+ let mut norm = 0.0;
+ for k in 0..3 {
+ let (i, j) = (t[(k + 1) % 3], t[(k + 2) % 3]);
+ let d = [v[i][0] - v[j][0], v[i][1] - v[j][1]];
+ let e = [x[i][0] - x[j][0], x[i][1] - x[j][1]];
+ s[0] += wt[k] * d[0] * e[0];
+ s[1] += wt[k] * d[0] * e[1];
+ s[2] += wt[k] * d[1] * e[0];
+ s[3] += wt[k] * d[1] * e[1];
+ norm += wt[k] * (e[0] * e[0] + e[1] * e[1]);
+ }
+ let (c, sn) = (s[0] + s[3], s[2] - s[1]);
+ let th = sn.atan2(c);
+ let scale = match mode {
+ PuppetMode::Rigid => 1.0,
+ PuppetMode::Normal => (c.hypot(sn) / norm.max(1e-12)).sqrt(),
+ PuppetMode::Distort => c.hypot(sn) / norm.max(1e-12),
+ };
+ let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
+ let (sth, cth) = th.sin_cos();
+ [scale * cth, -scale * sth, scale * sth, scale * cth]
+ })
+ .collect();
+ for (k, tris) in self.pin_tris.iter().enumerate() {
+ if let Some(Some(deg)) = fixed.get(k) {
+ let (s, c) = deg.to_radians().sin_cos();
+ for &t in tris {
+ rots[t] = [c, -s, s, c];
+ }
+ }
+ }
+ rots
+ }
+
+ fn global(&self, rots: &[[f64; 4]], pin_dst: &[[f64; 2]], v: &mut [[f64; 2]]) {
+ let nv = v.len();
+ let x = &self.mesh.verts;
+ let mut bx = vec![0.0; nv];
+ let mut by = vec![0.0; nv];
+ for ((t, wt), r) in self.mesh.tris.iter().zip(&self.w).zip(rots) {
+ for k in 0..3 {
+ let (i, j) = (t[(k + 1) % 3], t[(k + 2) % 3]);
+ let e = [x[i][0] - x[j][0], x[i][1] - x[j][1]];
+ let re = [r[0] * e[0] + r[1] * e[1], r[2] * e[0] + r[3] * e[1]];
+ bx[i] += wt[k] * re[0];
+ by[i] += wt[k] * re[1];
+ bx[j] -= wt[k] * re[0];
+ by[j] -= wt[k] * re[1];
+ }
+ }
+ for (b, d) in self.bound.iter().zip(pin_dst) {
+ for k in 0..3 {
+ bx[b.verts[k]] += self.pin_weight * b.bary[k] * d[0];
+ by[b.verts[k]] += self.pin_weight * b.bary[k] * d[1];
+ }
+ }
+ for (i, &an) in self.anchored.iter().enumerate() {
+ if an {
+ bx[i] += self.pin_weight * x[i][0];
+ by[i] += self.pin_weight * x[i][1];
+ }
+ }
+ let mut sx: Vec<f64> = v.iter().map(|p| p[0]).collect();
+ let mut sy: Vec<f64> = v.iter().map(|p| p[1]).collect();
+ self.matrix.solve(&bx, &mut sx);
+ self.matrix.solve(&by, &mut sy);
+ for (i, p) in v.iter_mut().enumerate() {
+ *p = [sx[i], sy[i]];
+ }
+ }
+
+ /// Deforms the mesh: `pin_dst` (one per pin given to [`Self::new`]), optional fixed pin
+ /// rotations (degrees), `iterations` local/global rounds, warm-started from `init` when
+ /// given. Returns the deformed vertices and the rigid ARAP energy after each round.
+ pub fn solve(&self, pin_dst: &[[f64; 2]], rotations: &[Option<f64>], mode: PuppetMode, iterations: usize, init: Option<&[[f64; 2]]>) -> (Vec<[f64; 2]>, Vec<f64>) {
+ let nv = self.mesh.verts.len();
+ let mut v: Vec<[f64; 2]> = match init {
+ Some(i) if i.len() == nv => i.to_vec(),
+ _ => self.mesh.verts.clone(),
+ };
+ if nv == 0 {
+ return (v, Vec::new());
+ }
+ if init.is_none_or(|i| i.len() != nv) {
+ let ident = vec![[1.0, 0.0, 0.0, 1.0]; self.mesh.tris.len()];
+ let mut r = ident;
+ for (k, tris) in self.pin_tris.iter().enumerate() {
+ if let Some(Some(deg)) = rotations.get(k) {
+ let (s, c) = deg.to_radians().sin_cos();
+ for &t in tris {
+ r[t] = [c, -s, s, c];
+ }
+ }
+ }
+ self.global(&r, pin_dst, &mut v);
+ }
+ let mut energies = Vec::with_capacity(iterations);
+ for _ in 0..iterations {
+ let rots = self.local(&v, mode, rotations);
+ self.global(&rots, pin_dst, &mut v);
+ let rigid = self.local(&v, PuppetMode::Rigid, rotations);
+ energies.push(self.energy_with(&v, &rigid, pin_dst));
+ }
+ (v, energies)
+ }
+
+ /// Energy of the current state with the rigid best fit (for monitoring).
+ pub fn energy(&self, v: &[[f64; 2]], pin_dst: &[[f64; 2]], rotations: &[Option<f64>]) -> f64 {
+ let rots = self.local(v, PuppetMode::Rigid, rotations);
+ self.energy_with(v, &rots, pin_dst)
+ }
+
+ /// Triangle draw order (back to front) for pins with depths.
+ pub fn draw_order(&self, depths: &[i32], pin_src: &[[f64; 2]]) -> Vec<usize> {
+ let mut order: Vec<usize> = (0..self.mesh.tris.len()).collect();
+ if depths.iter().all(|d| *d == 0) || pin_src.is_empty() {
+ return order;
+ }
+ let depth_of = |t: usize| {
+ let c = self.mesh.tris[t].iter().fold([0.0, 0.0], |a, &i| [a[0] + self.mesh.verts[i][0] / 3.0, a[1] + self.mesh.verts[i][1] / 3.0]);
+ let k = (0..pin_src.len()).min_by(|&a, &b| dist2(pin_src[a], c).total_cmp(&dist2(pin_src[b], c))).unwrap_or(0);
+ depths.get(k).copied().unwrap_or(0)
+ };
+ let d: Vec<i32> = order.iter().map(|&t| depth_of(t)).collect();
+ order.sort_by_key(|&t| d[t]);
+ order
+ }
+}
+
+/// Number of local/global rounds used by the command.
+pub const ITERATIONS: usize = 40;
+
+/// The deformed mesh of a puppet warp: (solver, deformed vertices, draw order).
+pub fn deform(src: &Surface, bounds: Rect, w: &PuppetWarp, iterations: usize) -> (PuppetSolver, Vec<[f64; 2]>, Vec<usize>) {
+ let mesh = build_mesh(src, bounds, w.density, w.expansion);
+ let pin_src: Vec<[f64; 2]> = w.pins.iter().map(|p| p.src).collect();
+ let fixed: Vec<bool> = w.pins.iter().map(|p| p.rotate.is_some()).collect();
+ let solver = PuppetSolver::new(mesh, &pin_src, &fixed);
+ let dst: Vec<[f64; 2]> = w.pins.iter().map(|p| p.dst).collect();
+ let rot: Vec<Option<f64>> = w.pins.iter().map(|p| p.rotate).collect();
+ let (v, _) = solver.solve(&dst, &rot, w.mode, iterations, None);
+ let depths: Vec<i32> = w.pins.iter().map(|p| p.depth).collect();
+ let order = solver.draw_order(&depths, &pin_src);
+ (solver, v, order)
+}
+
+/// Rasterizes the mesh deformation of `src` (inside `bounds`): the deformed triangles only, so
+/// pixels outside the mesh are dropped.
+pub fn render(src: &Surface, bounds: Rect, mesh: &PuppetMesh, deformed: &[[f64; 2]], order: &[usize], interp: Interp) -> Surface {
+ let verts: Vec<([f64; 2], [f64; 2])> = deformed.iter().zip(&mesh.verts).map(|(d, s)| (*d, *s)).collect();
+ let tris: Vec<[usize; 3]> = order.iter().map(|&t| mesh.tris[t]).collect();
+ crate::warp::warp_triangles(src, bounds, &verts, &tris, interp)
+}
+
+/// Applies a puppet warp to `src` (content inside `bounds`).
+pub fn puppet_warp(src: &Surface, bounds: Rect, w: &PuppetWarp, interp: Interp) -> Surface {
+ let (solver, v, order) = deform(src, bounds, w, ITERATIONS);
+ render(src, bounds, &solver.mesh, &v, &order, interp)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::{ColorMode, PixelFormat, SampleType};
+
+ fn blob(st: SampleType) -> Surface {
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true));
+ // An L shape: a vertical bar and a foot.
+ for y in 10..70 {
+ for x in 20..36 {
+ s.write_pixel(x, y, &[((x + y) % 7) as f32 / 6.0, 0.5, (y as f32) / 80.0, 1.0]);
+ }
+ }
+ for y in 56..70 {
+ for x in 36..70 {
+ s.write_pixel(x, y, &[0.2, ((x * 3) % 5) as f32 / 4.0, 0.8, 1.0]);
+ }
+ }
+ s
+ }
+
+ #[test]
+ fn mesh_covers_the_shape_only() {
+ let s = blob(SampleType::U8);
+ let b = s.content_bounds();
+ let m = build_mesh(&s, b, PuppetDensity::Normal, 2.0);
+ assert!(m.tris.len() > 20);
+ let inside = |p: [f64; 2]| m.tris.iter().any(|t| {
+ let xs = t.map(|i| m.verts[i]);
+ let (x0, x1) = (xs.iter().map(|v| v[0]).fold(f64::MAX, f64::min), xs.iter().map(|v| v[0]).fold(f64::MIN, f64::max));
+ let (y0, y1) = (xs.iter().map(|v| v[1]).fold(f64::MAX, f64::min), xs.iter().map(|v| v[1]).fold(f64::MIN, f64::max));
+ p[0] >= x0 && p[0] <= x1 && p[1] >= y0 && p[1] <= y1
+ });
+ assert!(inside([28.0, 30.0]) && inside([60.0, 62.0]));
+ assert!(!inside([60.0, 20.0]), "the empty corner of the L has no mesh");
+ let more = build_mesh(&s, b, PuppetDensity::More, 2.0);
+ let fewer = build_mesh(&s, b, PuppetDensity::Fewer, 2.0);
+ assert!(more.tris.len() > m.tris.len() && m.tris.len() > fewer.tris.len());
+ }
+
+ #[test]
+ fn no_pins_or_unmoved_pins_are_identity() {
+ for st in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let s = blob(st);
+ let b = s.content_bounds();
+ for pins in [vec![], vec![PuppetPin { src: [28.0, 20.0], dst: [28.0, 20.0], rotate: None, depth: 0 }, PuppetPin { src: [60.0, 62.0], dst: [60.0, 62.0], rotate: None, depth: 0 }]] {
+ let w = PuppetWarp { pins, mode: PuppetMode::Normal, density: PuppetDensity::Normal, expansion: 2.0 };
+ let out = puppet_warp(&s, b, &w, Interp::Bicubic);
+ let worst = s.read_region(b).iter().zip(out.read_region(b)).map(|(a, c)| (a - c).abs()).fold(0.0f32, f32::max);
+ assert!(worst <= 1.0 / 255.0 + 1e-6, "{st:?}: {worst}");
+ }
+ }
+ }
+
+ #[test]
+ fn a_single_pin_translates_rigidly() {
+ let s = blob(SampleType::U8);
+ let b = s.content_bounds();
+ let w = PuppetWarp { pins: vec![PuppetPin { src: [28.0, 30.0], dst: [38.0, 25.0], rotate: None, depth: 0 }], mode: PuppetMode::Rigid, density: PuppetDensity::Normal, expansion: 2.0 };
+ let (solver, v, _) = deform(&s, b, &w, ITERATIONS);
+ for (d, x) in v.iter().zip(&solver.mesh.verts) {
+ assert!((d[0] - x[0] - 10.0).abs() < 1e-3 && (d[1] - x[1] + 5.0).abs() < 1e-3, "{d:?} {x:?}");
+ }
+ let err = v.iter().zip(&solver.mesh.verts).map(|(d, x)| (d[0] - x[0] - 10.0).abs().max((d[1] - x[1] + 5.0).abs())).fold(0.0, f64::max);
+ eprintln!("max translation error {err:e}");
+ let out = puppet_warp(&s, b, &w, Interp::Bilinear);
+ assert_eq!(out.content_bounds(), b.translate(10, -5));
+ assert_eq!(out.pixel(30, 20), s.pixel(20, 25));
+ // A fixed rotation turns the whole mesh about the pin.
+ let w = PuppetWarp { pins: vec![PuppetPin { src: [28.0, 30.0], dst: [28.0, 30.0], rotate: Some(90.0), depth: 0 }], ..w };
+ let (solver, v, _) = deform(&s, b, &w, ITERATIONS);
+ let i = (0..v.len()).max_by(|&a, &c| solver.mesh.verts[a][0].total_cmp(&solver.mesh.verts[c][0])).unwrap();
+ let (x, d) = (solver.mesh.verts[i], v[i]);
+ // (dx, dy) → (−dy, dx) for +90° with y down.
+ let (dx, dy) = (x[0] - 28.0, x[1] - 30.0);
+ assert!((d[0] - (28.0 - dy)).abs() < 1.0 && (d[1] - (30.0 + dx)).abs() < 1.0, "{x:?} → {d:?}");
+ }
+
+ #[test]
+ fn arap_energy_decreases_and_modes_differ() {
+ let s = blob(SampleType::U8);
+ let b = s.content_bounds();
+ let mesh = build_mesh(&s, b, PuppetDensity::Normal, 2.0);
+ let src = [[28.0, 14.0], [64.0, 62.0], [28.0, 62.0]];
+ let dst = [[10.0, 30.0], [70.0, 50.0], [28.0, 62.0]];
+ let solver = PuppetSolver::new(mesh, &src, &[false; 3]);
+ let rot = [None; 3];
+ let (v, e) = solver.solve(&dst, &rot, PuppetMode::Rigid, 30, None);
+ assert!(e.len() == 30);
+ let start = solver.energy(&solver.solve(&dst, &rot, PuppetMode::Rigid, 0, None).0, &dst, &rot);
+ assert!(e[0] <= start * (1.0 + 1e-9), "{} vs {start}", e[0]);
+ for w in e.windows(2) {
+ assert!(w[1] <= w[0] * (1.0 + 1e-6) + 1e-9, "{w:?}");
+ }
+ assert!(e[29] < start);
+ // Pins are honoured closely.
+ for (b, d) in solver.bound.iter().zip(&dst) {
+ let p = (0..3).fold([0.0, 0.0], |a, k| [a[0] + b.bary[k] * v[b.verts[k]][0], a[1] + b.bary[k] * v[b.verts[k]][1]]);
+ assert!(dist2(p, *d) < 0.25, "{p:?} vs {d:?}");
+ }
+ let (vd, _) = solver.solve(&dst, &rot, PuppetMode::Distort, 30, None);
+ assert_ne!(v, vd);
+ }
+
+ #[test]
+ fn depth_orders_triangles() {
+ let s = blob(SampleType::U8);
+ let b = s.content_bounds();
+ let mesh = build_mesh(&s, b, PuppetDensity::Fewer, 2.0);
+ let pins = [[28.0, 14.0], [64.0, 62.0]];
+ let solver = PuppetSolver::new(mesh, &pins, &[false; 2]);
+ let order = solver.draw_order(&[1, 0], &pins);
+ let last = *order.last().unwrap();
+ let c = solver.mesh.tris[last].iter().fold(0.0, |a, &i| a + solver.mesh.verts[i][1] / 3.0);
+ assert!(c < 55.0, "triangles near the raised pin draw last");
+ }
+}
diff --git a/crates/algo/src/pyramid.rs b/crates/algo/src/pyramid.rs
new file mode 100644
index 000000000..89a1db10f
--- /dev/null
+++ b/crates/algo/src/pyramid.rs
@@ -0,0 +1,314 @@
+//! Multiresolution blending for Edit › Auto-Blend Layers.
+//!
+//! P. J. Burt, E. H. Adelson, *A Multiresolution Spline With Application to Image Mosaics*,
+//! ACM TOG 1983: each image is split into a Laplacian pyramid (band-pass levels plus a low-pass
+//! residual), the blend weights into a Gaussian pyramid, every level is blended with its own
+//! smoothed weights and the result collapsed, so seams are invisible at every scale.
+//!
+//! Weights come from [`stack_weights`] (focus stacking: per pixel, the sharpest image wins, by
+//! the smoothed magnitude of the luminance Laplacian) or [`panorama_weights`] (each pixel goes to
+//! the image whose opaque area it is deepest inside). Buffers are interleaved `w × h × ch`
+//! normalised floats of any colour model and depth; deterministic.
+
+/// One pyramid level.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Level {
+ pub w: usize,
+ pub h: usize,
+ pub px: Vec<f32>,
+}
+
+const K: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0];
+
+/// 5-tap binomial filter + decimation by two (Burt & Adelson's REDUCE).
+pub fn reduce(l: &Level, ch: usize) -> Level {
+ let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2));
+ // Horizontal pass on even columns, then vertical on even rows.
+ let mut tmp = vec![0.0f32; w * l.h * ch];
+ for y in 0..l.h {
+ for x in 0..w {
+ for (k, wt) in K.iter().enumerate() {
+ let sx = (2 * x as i64 + k as i64 - 2).clamp(0, l.w as i64 - 1) as usize;
+ for c in 0..ch {
+ tmp[(y * w + x) * ch + c] += wt * l.px[(y * l.w + sx) * ch + c];
+ }
+ }
+ }
+ }
+ let mut px = vec![0.0f32; w * h * ch];
+ for y in 0..h {
+ for (k, wt) in K.iter().enumerate() {
+ let sy = (2 * y as i64 + k as i64 - 2).clamp(0, l.h as i64 - 1) as usize;
+ for x in 0..w {
+ for c in 0..ch {
+ px[(y * w + x) * ch + c] += wt * tmp[(sy * w + x) * ch + c];
+ }
+ }
+ }
+ }
+ Level { w, h, px }
+}
+
+/// Upsample `l` to `w × h` (EXPAND: zero insertion + the same filter, ×4 gain).
+pub fn expand(l: &Level, ch: usize, w: usize, h: usize) -> Vec<f32> {
+ let mut tmp = vec![0.0f32; w * l.h * ch];
+ for y in 0..l.h {
+ for x in 0..w {
+ for (k, wt) in K.iter().enumerate() {
+ let t = x as i64 + k as i64 - 2;
+ if t.rem_euclid(2) != 0 {
+ continue;
+ }
+ let sx = (t / 2).clamp(0, l.w as i64 - 1) as usize;
+ for c in 0..ch {
+ tmp[(y * w + x) * ch + c] += 2.0 * wt * l.px[(y * l.w + sx) * ch + c];
+ }
+ }
+ }
+ }
+ let mut out = vec![0.0f32; w * h * ch];
+ for y in 0..h {
+ for (k, wt) in K.iter().enumerate() {
+ let t = y as i64 + k as i64 - 2;
+ if t.rem_euclid(2) != 0 {
+ continue;
+ }
+ let sy = (t / 2).clamp(0, l.h as i64 - 1) as usize;
+ for x in 0..w {
+ for c in 0..ch {
+ out[(y * w + x) * ch + c] += 2.0 * wt * tmp[(sy * w + x) * ch + c];
+ }
+ }
+ }
+ }
+ out
+}
+
+/// Gaussian pyramid with `levels` levels (level 0 = the input).
+pub fn gaussian(w: usize, h: usize, ch: usize, px: &[f32], levels: usize) -> Vec<Level> {
+ let mut out = vec![Level { w, h, px: px.to_vec() }];
+ while out.len() < levels.max(1) {
+ let last = out.last().expect("non-empty");
+ if last.w <= 1 && last.h <= 1 {
+ break;
+ }
+ let next = reduce(last, ch);
+ out.push(next);
+ }
+ out
+}
+
+/// Laplacian pyramid: band-pass levels, the last level is the low-pass residual.
+pub fn laplacian(w: usize, h: usize, ch: usize, px: &[f32], levels: usize) -> Vec<Level> {
+ let g = gaussian(w, h, ch, px, levels);
+ let mut out = Vec::with_capacity(g.len());
+ for i in 0..g.len() {
+ if i + 1 == g.len() {
+ out.push(g[i].clone());
+ } else {
+ let up = expand(&g[i + 1], ch, g[i].w, g[i].h);
+ out.push(Level { w: g[i].w, h: g[i].h, px: g[i].px.iter().zip(&up).map(|(a, b)| a - b).collect() });
+ }
+ }
+ out
+}
+
+/// Rebuild an image from its Laplacian pyramid.
+pub fn collapse(pyr: &[Level], ch: usize) -> Vec<f32> {
+ let mut cur = pyr.last().cloned().unwrap_or(Level { w: 0, h: 0, px: Vec::new() });
+ for l in pyr.iter().rev().skip(1) {
+ let up = expand(&cur, ch, l.w, l.h);
+ cur = Level { w: l.w, h: l.h, px: l.px.iter().zip(&up).map(|(a, b)| a + b).collect() };
+ }
+ cur.px
+}
+
+/// Number of levels so the coarsest level is a few pixels across.
+pub fn auto_levels(w: usize, h: usize) -> usize {
+ let mut n = 1;
+ let mut s = w.min(h);
+ while s > 8 && n < 10 {
+ s /= 2;
+ n += 1;
+ }
+ n
+}
+
+/// Blend `images` with per-pixel `weights` (any non-negative values; normalised per level).
+pub fn blend(w: usize, h: usize, ch: usize, images: &[&[f32]], weights: &[Vec<f32>], levels: usize) -> Vec<f32> {
+ assert_eq!(images.len(), weights.len());
+ let levels = levels.max(1);
+ let mut acc: Option<Vec<Level>> = None;
+ let mut wsum: Option<Vec<Level>> = None;
+ for (img, wt) in images.iter().zip(weights) {
+ let lp = laplacian(w, h, ch, img, levels);
+ let gp = gaussian(w, h, 1, wt, levels);
+ let a = acc.get_or_insert_with(|| lp.iter().map(|l| Level { w: l.w, h: l.h, px: vec![0.0; l.px.len()] }).collect());
+ let s = wsum.get_or_insert_with(|| gp.iter().map(|l| Level { w: l.w, h: l.h, px: vec![0.0; l.px.len()] }).collect());
+ for (li, (l, g)) in lp.iter().zip(&gp).enumerate() {
+ for i in 0..l.w * l.h {
+ let k = g.px[i];
+ s[li].px[i] += k;
+ for c in 0..ch {
+ a[li].px[i * ch + c] += k * l.px[i * ch + c];
+ }
+ }
+ }
+ }
+ let (Some(mut a), Some(s)) = (acc, wsum) else { return vec![0.0; w * h * ch] };
+ for (l, sl) in a.iter_mut().zip(&s) {
+ for i in 0..l.w * l.h {
+ let k = sl.px[i];
+ for c in 0..ch {
+ l.px[i * ch + c] = if k > 1e-6 { l.px[i * ch + c] / k } else { 0.0 };
+ }
+ }
+ }
+ collapse(&a, ch).into_iter().map(|v| v.clamp(0.0, 1.0)).collect()
+}
+
+fn box_blur1(w: usize, h: usize, v: &[f32], r: usize) -> Vec<f32> {
+ let pass = |src: &[f32], horizontal: bool| -> Vec<f32> {
+ let mut dst = vec![0.0f32; src.len()];
+ let (n, m) = if horizontal { (h, w) } else { (w, h) };
+ for line in 0..n {
+ let at = |k: i64| {
+ let k = k.clamp(0, m as i64 - 1) as usize;
+ if horizontal { src[line * w + k] } else { src[k * w + line] }
+ };
+ let mut s: f32 = (-(r as i64)..=r as i64).map(at).sum();
+ for k in 0..m {
+ let i = if horizontal { line * w + k } else { k * w + line };
+ dst[i] = s / (2 * r + 1) as f32;
+ s += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64);
+ }
+ }
+ dst
+ };
+ pass(&pass(v, true), false)
+}
+
+/// One-hot winner maps: weight 1 for the image with the largest score at each pixel.
+fn winner_take_all(scores: &[Vec<f32>], n: usize) -> Vec<Vec<f32>> {
+ let mut out = vec![vec![0.0f32; n]; scores.len()];
+ for i in 0..n {
+ let mut best = (0usize, f32::MIN);
+ for (k, s) in scores.iter().enumerate() {
+ if s[i] > best.1 {
+ best = (k, s[i]);
+ }
+ }
+ if best.1 > f32::MIN {
+ out[best.0][i] = 1.0;
+ }
+ }
+ out
+}
+
+/// Focus-stack weights: per pixel, the image with the most local detail (smoothed |∇²L|) wins.
+/// `luma[k]` is image k's luminance, `alpha[k]` its coverage.
+pub fn stack_weights(w: usize, h: usize, luma: &[Vec<f32>], alpha: &[Vec<f32>]) -> Vec<Vec<f32>> {
+ let radius = (w.min(h) / 64).clamp(2, 12);
+ let scores: Vec<Vec<f32>> = luma
+ .iter()
+ .zip(alpha)
+ .map(|(l, a)| {
+ let mut lap = vec![0.0f32; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ let p = |xx: usize, yy: usize| l[yy * w + xx];
+ let (xl, xr, yu, yd) = (x.saturating_sub(1), (x + 1).min(w - 1), y.saturating_sub(1), (y + 1).min(h - 1));
+ lap[y * w + x] = (p(xl, y) + p(xr, y) + p(x, yu) + p(x, yd) - 4.0 * p(x, y)).abs();
+ }
+ }
+ box_blur1(w, h, &lap, radius).iter().zip(a).map(|(s, a)| if *a > 0.5 { *s } else { -1.0 }).collect()
+ })
+ .collect();
+ winner_take_all(&scores, w * h)
+}
+
+/// Panorama weights: each pixel goes to the image whose opaque area it lies deepest inside
+/// (chamfer distance to that image's transparent pixels), so seams run through overlaps.
+pub fn panorama_weights(w: usize, h: usize, alpha: &[Vec<f32>]) -> Vec<Vec<f32>> {
+ let scores: Vec<Vec<f32>> = alpha
+ .iter()
+ .map(|a| {
+ // Two-pass 3-4 chamfer distance transform from transparent pixels / the border.
+ let inf = 1.0e9f32;
+ let mut d: Vec<f32> = a.iter().map(|v| if *v > 0.5 { inf } else { 0.0 }).collect();
+ let at = |d: &[f32], x: i64, y: i64| if x < 0 || y < 0 || x >= w as i64 || y >= h as i64 { 0.0 } else { d[y as usize * w + x as usize] };
+ for y in 0..h as i64 {
+ for x in 0..w as i64 {
+ let i = y as usize * w + x as usize;
+ let m = d[i].min(at(&d, x - 1, y) + 3.0).min(at(&d, x, y - 1) + 3.0).min(at(&d, x - 1, y - 1) + 4.0).min(at(&d, x + 1, y - 1) + 4.0);
+ d[i] = m;
+ }
+ }
+ for y in (0..h as i64).rev() {
+ for x in (0..w as i64).rev() {
+ let i = y as usize * w + x as usize;
+ let m = d[i].min(at(&d, x + 1, y) + 3.0).min(at(&d, x, y + 1) + 3.0).min(at(&d, x + 1, y + 1) + 4.0).min(at(&d, x - 1, y + 1) + 4.0);
+ d[i] = m;
+ }
+ }
+ d.iter().map(|v| if *v <= 0.0 { -1.0 } else { *v }).collect()
+ })
+ .collect();
+ winner_take_all(&scores, w * h)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn laplacian_round_trip_is_exact() {
+ let (w, h) = (37, 23);
+ let img: Vec<f32> = (0..w * h * 2).map(|i| ((i * 37 % 101) as f32) / 101.0).collect();
+ let pyr = laplacian(w, h, 2, &img, 5);
+ assert_eq!(pyr.len(), 5);
+ let back = collapse(&pyr, 2);
+ assert!(img.iter().zip(&back).all(|(a, b)| (a - b).abs() < 1e-4));
+ }
+
+ #[test]
+ fn blend_with_one_hot_weights_reproduces_each_side() {
+ let (w, h) = (64, 32);
+ let a = vec![0.2f32; w * h];
+ let b = vec![0.8f32; w * h];
+ let wa: Vec<f32> = (0..w * h).map(|i| if i % w < 32 { 1.0 } else { 0.0 }).collect();
+ let wb: Vec<f32> = wa.iter().map(|v| 1.0 - v).collect();
+ let out = blend(w, h, 1, &[&a, &b], &[wa, wb], auto_levels(w, h));
+ assert!((out[5 * w + 2] - 0.2).abs() < 1e-3);
+ assert!((out[5 * w + 61] - 0.8).abs() < 1e-3);
+ // The seam is a smooth ramp, not a step.
+ let mid = out[5 * w + 31];
+ assert!(mid > 0.3 && mid < 0.7, "{mid}");
+ }
+
+ #[test]
+ fn stack_picks_the_sharp_image() {
+ let (w, h) = (48, 48);
+ // Image 0 is sharp on the left (checker), image 1 on the right.
+ let checker = |x: usize, y: usize| if (x / 2 + y / 2).is_multiple_of(2) { 0.1 } else { 0.9 };
+ let i0: Vec<f32> = (0..w * h).map(|i| if i % w < 24 { checker(i % w, i / w) } else { 0.5 }).collect();
+ let i1: Vec<f32> = (0..w * h).map(|i| if i % w >= 24 { checker(i % w, i / w) } else { 0.5 }).collect();
+ let ones = vec![1.0f32; w * h];
+ let wts = stack_weights(w, h, &[i0, i1], &[ones.clone(), ones]);
+ assert_eq!(wts[0][20 * w + 4], 1.0);
+ assert_eq!(wts[1][20 * w + 44], 1.0);
+ }
+
+ #[test]
+ fn panorama_splits_the_overlap() {
+ let (w, h) = (60, 20);
+ let a: Vec<f32> = (0..w * h).map(|i| if i % w < 40 { 1.0 } else { 0.0 }).collect();
+ let b: Vec<f32> = (0..w * h).map(|i| if i % w >= 20 { 1.0 } else { 0.0 }).collect();
+ let wts = panorama_weights(w, h, &[a, b]);
+ assert_eq!(wts[0][10 * w + 5], 1.0);
+ assert_eq!(wts[1][10 * w + 55], 1.0);
+ // The seam falls inside the overlap (20..40), near its middle.
+ let seam = (0..w).find(|x| wts[1][10 * w + x] == 1.0).unwrap();
+ assert!((25..=35).contains(&seam), "{seam}");
+ }
+}
diff --git a/crates/algo/src/quantize.rs b/crates/algo/src/quantize.rs
new file mode 100644
index 000000000..b4b0d887a
--- /dev/null
+++ b/crates/algo/src/quantize.rs
@@ -0,0 +1,722 @@
+//! Colour reduction for Image › Mode › Indexed Color and Bitmap: palette construction (exact,
+//! system, web, uniform, perceptual, selective, adaptive), forced colours, and dithering
+//! (none, Floyd–Steinberg diffusion, ordered pattern, noise), plus 1-bit conversion methods.
+//!
+//! Buffers are straight RGBA in 0..=1, row-major. Median cut follows Heckbert (1982); k-means
+//! refinement is Lloyd's algorithm; error diffusion is Floyd & Steinberg (1976).
+
+use photocraft_color::convert::srgb_to_lab;
+use serde::{Deserialize, Serialize};
+
+pub type Rgb8 = [u8; 3];
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum PaletteKind {
+ /// Every colour of the image (fails above 256).
+ Exact,
+ SystemMac,
+ SystemWindows,
+ Web,
+ Uniform,
+ /// Lab median cut + k-means (perceptually weighted).
+ Perceptual,
+ /// Perceptual, with entries near web-safe colours snapped to them.
+ Selective,
+ /// RGB median cut weighted by frequency.
+ Adaptive,
+}
+
+impl PaletteKind {
+ pub fn from_id(s: &str) -> Option<Self> {
+ Some(match s {
+ "exact" => PaletteKind::Exact,
+ "system" | "systemMac" | "systemMacOs" => PaletteKind::SystemMac,
+ "systemWindows" => PaletteKind::SystemWindows,
+ "web" => PaletteKind::Web,
+ "uniform" => PaletteKind::Uniform,
+ "perceptual" | "localPerceptual" => PaletteKind::Perceptual,
+ "selective" | "localSelective" => PaletteKind::Selective,
+ "adaptive" | "localAdaptive" => PaletteKind::Adaptive,
+ _ => return None,
+ })
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum Forced {
+ None,
+ BlackWhite,
+ Primaries,
+ Web,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum Dither {
+ None,
+ Diffusion,
+ Pattern,
+ Noise,
+}
+
+fn to8(v: f32) -> u8 {
+ (v.clamp(0.0, 1.0) * 255.0).round() as u8
+}
+
+fn rgb8(p: &[f32; 4]) -> Rgb8 {
+ [to8(p[0]), to8(p[1]), to8(p[2])]
+}
+
+/// The 216-colour web-safe cube (0, 51, …, 255 per channel).
+pub fn web_palette() -> Vec<Rgb8> {
+ let mut v = Vec::with_capacity(216);
+ for r in 0..6u8 {
+ for g in 0..6u8 {
+ for b in 0..6u8 {
+ v.push([r * 51, g * 51, b * 51]);
+ }
+ }
+ }
+ v
+}
+
+/// Classic Mac OS system palette: the web cube plus 10-step red, green, blue and gray ramps.
+pub fn mac_palette() -> Vec<Rgb8> {
+ let mut v = web_palette();
+ // Ramps use the values between cube steps (17-unit spacing, skipping multiples of 51).
+ let steps: Vec<u8> = (1..=15u8).map(|k| k * 17).filter(|x| x % 51 != 0).collect();
+ for &s in steps.iter().rev() {
+ v.push([s, 0, 0]);
+ }
+ for &s in steps.iter().rev() {
+ v.push([0, s, 0]);
+ }
+ for &s in steps.iter().rev() {
+ v.push([0, 0, s]);
+ }
+ for &s in steps.iter().rev() {
+ v.push([s, s, s]);
+ }
+ v.truncate(256);
+ v
+}
+
+/// Windows default palette: the 20 static system colours plus the web cube and a gray ramp.
+pub fn windows_palette() -> Vec<Rgb8> {
+ let mut v: Vec<Rgb8> = vec![
+ [0, 0, 0],
+ [128, 0, 0],
+ [0, 128, 0],
+ [128, 128, 0],
+ [0, 0, 128],
+ [128, 0, 128],
+ [0, 128, 128],
+ [192, 192, 192],
+ [192, 220, 192],
+ [166, 202, 240],
+ [255, 251, 240],
+ [160, 160, 164],
+ [128, 128, 128],
+ [255, 0, 0],
+ [0, 255, 0],
+ [255, 255, 0],
+ [0, 0, 255],
+ [255, 0, 255],
+ [0, 255, 255],
+ [255, 255, 255],
+ ];
+ for c in web_palette() {
+ if !v.contains(&c) {
+ v.push(c);
+ }
+ }
+ let mut g = 8u8;
+ while v.len() < 256 {
+ if !v.contains(&[g, g, g]) {
+ v.push([g, g, g]);
+ }
+ g = g.wrapping_add(12);
+ }
+ v
+}
+
+/// Up to `n` colours on an equal-step RGB grid.
+pub fn uniform_palette(n: usize) -> Vec<Rgb8> {
+ let k = ((n as f32).cbrt().floor() as usize).max(2);
+ let lv = |i: usize| ((i as f32 / (k - 1) as f32) * 255.0).round() as u8;
+ let mut v = Vec::with_capacity(k * k * k);
+ for r in 0..k {
+ for g in 0..k {
+ for b in 0..k {
+ v.push([lv(r), lv(g), lv(b)]);
+ }
+ }
+ }
+ v
+}
+
+fn forced_colors(f: Forced) -> Vec<Rgb8> {
+ match f {
+ Forced::None => Vec::new(),
+ Forced::BlackWhite => vec![[0, 0, 0], [255, 255, 255]],
+ Forced::Primaries => vec![
+ [0, 0, 0],
+ [255, 255, 255],
+ [255, 0, 0],
+ [0, 255, 0],
+ [0, 0, 255],
+ [0, 255, 255],
+ [255, 0, 255],
+ [255, 255, 0],
+ ],
+ Forced::Web => web_palette(),
+ }
+}
+
+/// Unique 8-bit colours with counts (opaque pixels only).
+fn histogram(px: &[[f32; 4]]) -> Vec<(Rgb8, u32)> {
+ let mut m: std::collections::HashMap<Rgb8, u32> = std::collections::HashMap::new();
+ for p in px.iter().filter(|p| p[3] >= 0.5) {
+ *m.entry(rgb8(p)).or_default() += 1;
+ }
+ let mut v: Vec<(Rgb8, u32)> = m.into_iter().collect();
+ v.sort_unstable();
+ v
+}
+
+/// Median cut over `pts` (feature vectors + weights) into at most `n` boxes; returns box means.
+fn median_cut(pts: &[([f32; 3], u32)], n: usize) -> Vec<[f32; 3]> {
+ if pts.is_empty() || n == 0 {
+ return Vec::new();
+ }
+ let mut boxes: Vec<Vec<([f32; 3], u32)>> = vec![pts.to_vec()];
+ while boxes.len() < n {
+ // Split the box with the largest weighted extent.
+ let (bi, axis, score) = boxes
+ .iter()
+ .enumerate()
+ .filter(|(_, b)| b.len() > 1)
+ .map(|(i, b)| {
+ let mut best = (0usize, -1.0f32);
+ for a in 0..3 {
+ let (lo, hi) = b.iter().fold((f32::MAX, f32::MIN), |(lo, hi), p| {
+ (lo.min(p.0[a]), hi.max(p.0[a]))
+ });
+ if hi - lo > best.1 {
+ best = (a, hi - lo);
+ }
+ }
+ let w: f32 = b.iter().map(|p| p.1 as f32).sum();
+ (i, best.0, best.1 * w.sqrt())
+ })
+ .fold(
+ (usize::MAX, 0, -1.0f32),
+ |acc, x| if x.2 > acc.2 { x } else { acc },
+ );
+ if bi == usize::MAX || score <= 0.0 {
+ break;
+ }
+ let mut b = boxes.swap_remove(bi);
+ b.sort_by(|p, q| p.0[axis].total_cmp(&q.0[axis]));
+ let total: u64 = b.iter().map(|p| u64::from(p.1)).sum();
+ let mut acc = 0u64;
+ let mut cut = 1;
+ for (i, p) in b.iter().enumerate() {
+ acc += u64::from(p.1);
+ if acc * 2 >= total {
+ cut = (i + 1).clamp(1, b.len() - 1);
+ break;
+ }
+ }
+ let rest = b.split_off(cut);
+ boxes.push(b);
+ boxes.push(rest);
+ }
+ boxes
+ .iter()
+ .map(|b| {
+ let w: f64 = b.iter().map(|p| f64::from(p.1)).sum();
+ std::array::from_fn(|a| {
+ (b.iter()
+ .map(|p| f64::from(p.0[a]) * f64::from(p.1))
+ .sum::<f64>()
+ / w) as f32
+ })
+ })
+ .collect()
+}
+
+/// Lloyd refinement of `centers` over weighted points.
+fn kmeans(pts: &[([f32; 3], u32)], centers: &mut [[f32; 3]], iters: usize) {
+ for _ in 0..iters {
+ let mut sum = vec![[0.0f64; 3]; centers.len()];
+ let mut cnt = vec![0.0f64; centers.len()];
+ for (p, w) in pts {
+ let i = nearest_f(centers, *p);
+ for a in 0..3 {
+ sum[i][a] += f64::from(p[a]) * f64::from(*w);
+ }
+ cnt[i] += f64::from(*w);
+ }
+ for (i, c) in centers.iter_mut().enumerate() {
+ if cnt[i] > 0.0 {
+ *c = std::array::from_fn(|a| (sum[i][a] / cnt[i]) as f32);
+ }
+ }
+ }
+}
+
+fn nearest_f(centers: &[[f32; 3]], p: [f32; 3]) -> usize {
+ let mut best = (f32::MAX, 0);
+ for (i, c) in centers.iter().enumerate() {
+ let d = (c[0] - p[0]).powi(2) + (c[1] - p[1]).powi(2) + (c[2] - p[2]).powi(2);
+ if d < best.0 {
+ best = (d, i);
+ }
+ }
+ best.1
+}
+
+fn lab_to_rgb8(lab: [f32; 3]) -> Rgb8 {
+ photocraft_color::convert::lab_to_srgb(lab).map(to8)
+}
+
+/// Builds the palette for `px`. `colors` is the requested count (2..=256) for the computed
+/// kinds; forced colours are included first and count toward it.
+pub fn build_palette(
+ px: &[[f32; 4]],
+ kind: PaletteKind,
+ colors: usize,
+ forced: Forced,
+) -> Result<Vec<Rgb8>, String> {
+ let colors = colors.clamp(2, 256);
+ let mut pal = forced_colors(forced);
+ let room = colors.saturating_sub(pal.len());
+ let hist = histogram(px);
+ let computed: Vec<Rgb8> = match kind {
+ PaletteKind::Exact => {
+ if hist.len() > 256 {
+ return Err(format!(
+ "the image has {} colours; Exact needs 256 or fewer",
+ hist.len()
+ ));
+ }
+ hist.iter().map(|h| h.0).collect()
+ }
+ PaletteKind::SystemMac => mac_palette(),
+ PaletteKind::SystemWindows => windows_palette(),
+ PaletteKind::Web => web_palette(),
+ PaletteKind::Uniform => uniform_palette(room.max(8)),
+ PaletteKind::Adaptive => {
+ if hist.len() <= room {
+ hist.iter().map(|h| h.0).collect()
+ } else {
+ let pts: Vec<([f32; 3], u32)> =
+ hist.iter().map(|(c, n)| (c.map(f32::from), *n)).collect();
+ let mut centers = median_cut(&pts, room);
+ kmeans(&pts, &mut centers, 2);
+ centers
+ .iter()
+ .map(|c| c.map(|v| v.round().clamp(0.0, 255.0) as u8))
+ .collect()
+ }
+ }
+ PaletteKind::Perceptual | PaletteKind::Selective => {
+ if hist.len() <= room {
+ hist.iter().map(|h| h.0).collect()
+ } else {
+ let pts: Vec<([f32; 3], u32)> = hist
+ .iter()
+ .map(|(c, n)| (srgb_to_lab(c.map(|v| f32::from(v) / 255.0)), *n))
+ .collect();
+ let mut centers = median_cut(&pts, room);
+ kmeans(&pts, &mut centers, 4);
+ let mut v: Vec<Rgb8> = centers.iter().map(|c| lab_to_rgb8(*c)).collect();
+ if kind == PaletteKind::Selective {
+ // Favour web-safe colours: snap entries within ~10 levels of one.
+ for c in &mut v {
+ let snap = c.map(|x| ((f32::from(x) / 51.0).round() * 51.0) as u8);
+ if c.iter().zip(snap).all(|(a, b)| a.abs_diff(b) <= 10) {
+ *c = snap;
+ }
+ }
+ }
+ v
+ }
+ }
+ };
+ for c in computed {
+ if pal.len() >= 256 {
+ break;
+ }
+ if !pal.contains(&c) {
+ pal.push(c);
+ }
+ }
+ if matches!(
+ kind,
+ PaletteKind::Adaptive
+ | PaletteKind::Perceptual
+ | PaletteKind::Selective
+ | PaletteKind::Uniform
+ ) {
+ pal.truncate(colors.max(forced_colors(forced).len()));
+ }
+ if pal.is_empty() {
+ pal.push([0, 0, 0]);
+ }
+ Ok(pal)
+}
+
+fn nearest(pal: &[Rgb8], c: [f32; 3]) -> usize {
+ let mut best = (f32::MAX, 0);
+ for (i, e) in pal.iter().enumerate() {
+ let d: f32 = (0..3)
+ .map(|k| (c[k] * 255.0 - f32::from(e[k])).powi(2))
+ .sum();
+ if d < best.0 {
+ best = (d, i);
+ }
+ }
+ best.1
+}
+
+/// 8×8 Bayer threshold in -0.5..0.5.
+pub fn bayer8(x: usize, y: usize) -> f32 {
+ const M: [u8; 64] = [
+ 0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26, 12, 44, 4, 36, 14, 46, 6, 38,
+ 60, 28, 52, 20, 62, 30, 54, 22, 3, 35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57,
+ 25, 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21,
+ ];
+ (f32::from(M[(y % 8) * 8 + x % 8]) + 0.5) / 64.0 - 0.5
+}
+
+fn hash01(x: usize, y: usize, seed: u32) -> f32 {
+ let mut h = (x as u32).wrapping_mul(0x8da6_b343)
+ ^ (y as u32).wrapping_mul(0xd816_3841)
+ ^ seed.wrapping_mul(0xcb1a_b31f);
+ h ^= h >> 13;
+ h = h.wrapping_mul(0x5bd1_e995);
+ h ^= h >> 15;
+ (h & 0xffff) as f32 / 65535.0
+}
+
+/// Maps every opaque pixel to its palette entry (in place) with the chosen dither; returns the
+/// index per pixel. Pixels with alpha < ½ become index `transparent` (and alpha 0) when given;
+/// otherwise alpha is kept. `amount` (0..=1) scales diffusion / pattern / noise strength.
+pub fn quantize(
+ px: &mut [[f32; 4]],
+ w: usize,
+ pal: &[Rgb8],
+ dither: Dither,
+ amount: f32,
+ transparent: Option<usize>,
+) -> Vec<u8> {
+ let h = px.len().checked_div(w).unwrap_or(0);
+ let mut idx = vec![0u8; px.len()];
+ // Typical palette spacing sets the ordered/noise dither amplitude.
+ let spread = (1.0 / (pal.len() as f32).cbrt().max(1.0)).min(0.5) * amount.clamp(0.0, 1.0);
+ let mut err = vec![
+ [0.0f32; 3];
+ if dither == Dither::Diffusion {
+ 2 * (w + 2)
+ } else {
+ 0
+ }
+ ];
+ for y in 0..h {
+ if dither == Dither::Diffusion {
+ // Rows ping-pong: `cur` is row y, `next` row y + 1 (offset by one for x = -1).
+ let (cur, next) = err.split_at_mut(w + 2);
+ cur.copy_from_slice(next);
+ next.iter_mut().for_each(|e| *e = [0.0; 3]);
+ }
+ for x in 0..w {
+ let i = y * w + x;
+ let p = px[i];
+ if p[3] < 0.5 {
+ if let Some(t) = transparent {
+ idx[i] = t as u8;
+ px[i] = [0.0, 0.0, 0.0, 0.0];
+ continue;
+ }
+ if p[3] <= 0.0 {
+ continue;
+ }
+ }
+ let mut c = [p[0], p[1], p[2]];
+ match dither {
+ Dither::None => {}
+ Dither::Diffusion => {
+ for k in 0..3 {
+ c[k] += err[x + 1][k];
+ }
+ }
+ Dither::Pattern => {
+ let t = bayer8(x, y) * spread;
+ c = c.map(|v| v + t);
+ }
+ Dither::Noise => {
+ let t = (hash01(x, y, 7) - 0.5) * spread;
+ c = c.map(|v| v + t);
+ }
+ }
+ let c = c.map(|v| v.clamp(0.0, 1.0));
+ let k = nearest(pal, c);
+ idx[i] = k as u8;
+ let e = pal[k].map(|v| f32::from(v) / 255.0);
+ if dither == Dither::Diffusion {
+ let a = amount.clamp(0.0, 1.0);
+ let d: [f32; 3] = std::array::from_fn(|q| (c[q] - e[q]) * a);
+ let (cur, next) = err.split_at_mut(w + 2);
+ for q in 0..3 {
+ cur[x + 2][q] += d[q] * 7.0 / 16.0;
+ next[x][q] += d[q] * 3.0 / 16.0;
+ next[x + 1][q] += d[q] * 5.0 / 16.0;
+ next[x + 2][q] += d[q] / 16.0;
+ }
+ }
+ px[i] = [
+ e[0],
+ e[1],
+ e[2],
+ if transparent.is_some() { 1.0 } else { p[3] },
+ ];
+ }
+ }
+ idx
+}
+
+/// Image › Mode › Bitmap methods.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub enum BitmapMethod {
+ Threshold,
+ Pattern,
+ Diffusion,
+ /// Halftone screen: lines per pixel-cell size, angle in degrees, dot shape.
+ Halftone {
+ cell: f32,
+ angle: f32,
+ shape: HalftoneShape,
+ },
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum HalftoneShape {
+ Round,
+ Ellipse,
+ Line,
+ Square,
+ Diamond,
+ Cross,
+}
+
+impl HalftoneShape {
+ pub fn from_id(s: &str) -> Self {
+ match s {
+ "ellipse" => HalftoneShape::Ellipse,
+ "line" => HalftoneShape::Line,
+ "square" => HalftoneShape::Square,
+ "diamond" => HalftoneShape::Diamond,
+ "cross" => HalftoneShape::Cross,
+ _ => HalftoneShape::Round,
+ }
+ }
+}
+
+/// Spot function in 0..=1 for a position (u, v) in -1..1 within a halftone cell.
+fn spot(shape: HalftoneShape, u: f32, v: f32) -> f32 {
+ let s = match shape {
+ HalftoneShape::Round => 1.0 - (u * u + v * v) / 2.0,
+ HalftoneShape::Ellipse => 1.0 - (u * u + 0.6 * v * v) / 1.6,
+ HalftoneShape::Line => 1.0 - v.abs(),
+ HalftoneShape::Square => 1.0 - u.abs().max(v.abs()),
+ HalftoneShape::Diamond => 1.0 - (u.abs() + v.abs()) / 2.0,
+ HalftoneShape::Cross => 1.0 - u.abs().min(v.abs()),
+ };
+ s.clamp(0.0, 1.0)
+}
+
+/// Converts gray values (0..=1, row-major `w` wide) to 0/1 in place.
+pub fn to_bitmap(gray: &mut [f32], w: usize, method: BitmapMethod) {
+ let h = gray.len().checked_div(w).unwrap_or(0);
+ match method {
+ BitmapMethod::Threshold => gray
+ .iter_mut()
+ .for_each(|v| *v = if *v >= 0.5 { 1.0 } else { 0.0 }),
+ BitmapMethod::Pattern => {
+ for (i, v) in gray.iter_mut().enumerate() {
+ *v = if *v > bayer8(i % w, i / w) + 0.5 {
+ 1.0
+ } else {
+ 0.0
+ };
+ }
+ }
+ BitmapMethod::Diffusion => {
+ let mut buf: Vec<f32> = gray.to_vec();
+ for y in 0..h {
+ for x in 0..w {
+ let i = y * w + x;
+ let old = buf[i];
+ let new = if old >= 0.5 { 1.0 } else { 0.0 };
+ let e = old - new;
+ gray[i] = new;
+ if x + 1 < w {
+ buf[i + 1] += e * 7.0 / 16.0;
+ }
+ if y + 1 < h {
+ if x > 0 {
+ buf[i + w - 1] += e * 3.0 / 16.0;
+ }
+ buf[i + w] += e * 5.0 / 16.0;
+ if x + 1 < w {
+ buf[i + w + 1] += e / 16.0;
+ }
+ }
+ }
+ }
+ }
+ BitmapMethod::Halftone { cell, angle, shape } => {
+ let cell = cell.max(2.0);
+ let (s, c) = angle.to_radians().sin_cos();
+ // Rank the spot function over the cell so coverage is proportional to the tone.
+ let mut table: Vec<f32> = (0..32 * 32)
+ .map(|k| {
+ spot(
+ shape,
+ ((k % 32) as f32 + 0.5) / 16.0 - 1.0,
+ ((k / 32) as f32 + 0.5) / 16.0 - 1.0,
+ )
+ })
+ .collect();
+ table.sort_by(f32::total_cmp);
+ let cdf = |x: f32| table.partition_point(|t| *t < x) as f32 / table.len() as f32;
+ for (i, v) in gray.iter_mut().enumerate() {
+ let (x, y) = ((i % w) as f32 + 0.5, (i / w) as f32 + 0.5);
+ let (rx, ry) = (x * c + y * s, -x * s + y * c);
+ let u = (rx / cell).rem_euclid(1.0) * 2.0 - 1.0;
+ let vv = (ry / cell).rem_euclid(1.0) * 2.0 - 1.0;
+ // Ink (black) covers where the spot function exceeds the gray level.
+ *v = if cdf(spot(shape, u, vv)) >= *v {
+ 0.0
+ } else {
+ 1.0
+ };
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn gradient(w: usize, h: usize) -> Vec<[f32; 4]> {
+ (0..w * h)
+ .map(|i| {
+ [
+ (i % w) as f32 / (w - 1) as f32,
+ (i / w) as f32 / (h - 1) as f32,
+ 0.3,
+ 1.0,
+ ]
+ })
+ .collect()
+ }
+
+ #[test]
+ fn fixed_palettes_have_expected_sizes() {
+ assert_eq!(web_palette().len(), 216);
+ assert_eq!(mac_palette().len(), 256);
+ assert_eq!(windows_palette().len(), 256);
+ assert_eq!(uniform_palette(27).len(), 27);
+ let mut m = mac_palette();
+ m.sort_unstable();
+ m.dedup();
+ assert_eq!(m.len(), 256, "mac palette entries are unique");
+ }
+
+ #[test]
+ fn exact_palette_and_failure() {
+ let px = vec![
+ [1.0, 0.0, 0.0, 1.0],
+ [0.0, 0.0, 1.0, 1.0],
+ [1.0, 0.0, 0.0, 1.0],
+ ];
+ assert_eq!(
+ build_palette(&px, PaletteKind::Exact, 256, Forced::None)
+ .unwrap()
+ .len(),
+ 2
+ );
+ assert!(build_palette(&gradient(64, 64), PaletteKind::Exact, 256, Forced::None).is_err());
+ }
+
+ #[test]
+ fn adaptive_and_perceptual_respect_count_and_forced() {
+ let px = gradient(40, 40);
+ for kind in [
+ PaletteKind::Adaptive,
+ PaletteKind::Perceptual,
+ PaletteKind::Selective,
+ ] {
+ let pal = build_palette(&px, kind, 16, Forced::BlackWhite).unwrap();
+ assert!(pal.len() <= 16 && pal.len() >= 8, "{kind:?} {}", pal.len());
+ assert_eq!(&pal[..2], &[[0, 0, 0], [255, 255, 255]]);
+ }
+ }
+
+ #[test]
+ fn quantize_maps_to_palette_with_each_dither() {
+ let pal = vec![[0, 0, 0], [255, 255, 255]];
+ for d in [
+ Dither::None,
+ Dither::Diffusion,
+ Dither::Pattern,
+ Dither::Noise,
+ ] {
+ let mut px: Vec<[f32; 4]> = (0..64)
+ .map(|i| [i as f32 / 63.0; 4])
+ .map(|mut p| {
+ p[3] = 1.0;
+ p
+ })
+ .collect();
+ let idx = quantize(&mut px, 8, &pal, d, 1.0, None);
+ assert!(px.iter().all(|p| p[0] == 0.0 || p[0] == 1.0), "{d:?}");
+ assert_eq!(idx.len(), 64);
+ // Mean brightness is preserved by dithering (not by plain thresholding).
+ if d == Dither::Diffusion {
+ let mean = px.iter().map(|p| p[0]).sum::<f32>() / 64.0;
+ assert!((mean - 0.5).abs() < 0.08, "{mean}");
+ }
+ }
+ let mut px = vec![[1.0, 1.0, 1.0, 0.2]];
+ let idx = quantize(&mut px, 1, &pal, Dither::None, 1.0, Some(1));
+ assert_eq!((idx[0], px[0][3]), (1, 0.0));
+ }
+
+ #[test]
+ fn bitmap_methods_are_binary_and_track_tone() {
+ for m in [
+ BitmapMethod::Threshold,
+ BitmapMethod::Pattern,
+ BitmapMethod::Diffusion,
+ BitmapMethod::Halftone {
+ cell: 6.0,
+ angle: 45.0,
+ shape: HalftoneShape::Round,
+ },
+ ] {
+ let mut g = vec![0.25f32; 32 * 32];
+ to_bitmap(&mut g, 32, m);
+ assert!(g.iter().all(|v| *v == 0.0 || *v == 1.0));
+ let mean = g.iter().sum::<f32>() / g.len() as f32;
+ if m != BitmapMethod::Threshold {
+ assert!((mean - 0.25).abs() < 0.15, "{m:?} {mean}");
+ } else {
+ assert_eq!(mean, 0.0);
+ }
+ }
+ }
+}
diff --git a/crates/algo/src/render.rs b/crates/algo/src/render.rs
new file mode 100644
index 000000000..baba88f93
--- /dev/null
+++ b/crates/algo/src/render.rs
@@ -0,0 +1,278 @@
+//! Render: Fibers, Lens Flare, Lighting Effects.
+
+use photocraft_geom::Rect;
+
+use crate::fxutil::{MAXC, luma, rgba, set_rgba, smoothstep, xy};
+use crate::image::Image;
+use crate::noise::hash01;
+use crate::{Ctx, LensType, Light, LightKind, TextureChannel};
+
+/// Smooth value noise in [0, 1).
+fn value_noise(x: f32, y: f32, seed: u32) -> f32 {
+ let (ix, iy) = (x.floor() as i32, y.floor() as i32);
+ let (tx, ty) = (x - ix as f32, y - iy as f32);
+ let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty));
+ let h = |a: i32, b: i32| hash01(a, b, 0, seed);
+ let top = h(ix, iy) + (h(ix + 1, iy) - h(ix, iy)) * sx;
+ let bot = h(ix, iy + 1) + (h(ix + 1, iy + 1) - h(ix, iy + 1)) * sx;
+ top + (bot - top) * sy
+}
+
+/// Fibers: vertical fibrous streaks between the foreground and background
+/// colours. Variance sets how quickly the colour varies across fibres (and
+/// how short they are); strength stretches each fibre vertically.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn fibers(src: &Image, out: Rect, ctx: &Ctx, variance: f32, strength: f32, seed: u32, colours: ([f32; 4], [f32; 4])) -> Vec<f32> {
+ let n = src.ch;
+ let var = variance.clamp(1.0, 64.0);
+ let st = strength.clamp(1.0, 64.0);
+ let (fg, bg) = colours;
+ // Horizontal frequency rises with variance; vertical frequency falls with strength.
+ let fx = 0.08 + var / 64.0 * 0.6;
+ let fy = fx / (2.0 + st * 1.5) * (0.5 + var / 32.0);
+ let mut res = src.crop(out);
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ let (xf, yf) = (x as f32, y as f32);
+ let mut sum = 0.0;
+ let mut amp = 1.0;
+ let mut norm = 0.0;
+ let (mut ax, mut ay) = (fx, fy);
+ for o in 0..4u32 {
+ sum += value_noise(xf * ax, yf * ay, seed.wrapping_add(o * 977)) * amp;
+ norm += amp;
+ amp *= 0.55;
+ ax *= 2.0;
+ ay *= 2.0;
+ }
+ // Fine per-column grain gives the hairline texture.
+ let grain = value_noise(xf * 0.9, yf * fy * 0.25, seed ^ 0x5bd1) - 0.5;
+ let t = ((sum / norm - 0.5) * (1.6 + var / 40.0) + 0.5 + grain * 0.25).clamp(0.0, 1.0);
+ let c = [fg[0] + (bg[0] - fg[0]) * t, fg[1] + (bg[1] - fg[1]) * t, fg[2] + (bg[2] - fg[2]) * t, 1.0];
+ set_rgba(ctx, px, c);
+ }
+ res
+}
+
+/// One lens-flare ghost: position along the flare→centre axis, radius and tint.
+struct Ghost {
+ t: f32,
+ r: f32,
+ tint: [f32; 3],
+ k: f32,
+}
+
+/// Lens Flare: an additive (screen) glow, rays, halo ring and ghost discs
+/// along the line through the image centre. Lens types vary the elements.
+pub(crate) fn lens_flare(src: &Image, out: Rect, ctx: &Ctx, brightness: f32, centre: (f32, f32), lens: LensType) -> Vec<f32> {
+ let n = src.ch;
+ let b = ctx.bounds;
+ let (bw, bh) = (b.width() as f32, b.height() as f32);
+ let diag = bw.hypot(bh).max(1.0);
+ let (cx, cy) = (b.x0 as f32 + centre.0 * bw, b.y0 as f32 + centre.1 * bh);
+ let (mx, my) = (b.x0 as f32 + bw / 2.0, b.y0 as f32 + bh / 2.0);
+ let bright = brightness.clamp(10.0, 300.0) / 100.0;
+ let s = diag / 1000.0;
+ let (core, glow, ring_r, ring_w, rays, streak) = match lens {
+ LensType::Zoom => (14.0, 90.0, 0.0, 0.0, 0.5, 0.0),
+ LensType::Prime35 => (12.0, 70.0, 90.0, 6.0, 0.3, 0.0),
+ LensType::Prime105 => (22.0, 130.0, 0.0, 0.0, 0.8, 0.0),
+ LensType::MoviePrime => (10.0, 60.0, 0.0, 0.0, 0.2, 1.0),
+ };
+ let ghosts: Vec<Ghost> = match lens {
+ LensType::Zoom => vec![
+ Ghost { t: 0.35, r: 10.0, tint: [0.6, 0.8, 1.0], k: 0.18 },
+ Ghost { t: 0.6, r: 26.0, tint: [0.5, 1.0, 0.6], k: 0.10 },
+ Ghost { t: 0.85, r: 6.0, tint: [1.0, 0.7, 0.4], k: 0.25 },
+ Ghost { t: 1.25, r: 40.0, tint: [0.7, 0.5, 1.0], k: 0.08 },
+ Ghost { t: 1.5, r: 16.0, tint: [1.0, 0.6, 0.5], k: 0.15 },
+ Ghost { t: 1.9, r: 70.0, tint: [0.5, 0.7, 1.0], k: 0.06 },
+ ],
+ LensType::Prime35 => vec![Ghost { t: 0.7, r: 18.0, tint: [0.6, 1.0, 0.7], k: 0.12 }, Ghost { t: 1.4, r: 30.0, tint: [1.0, 0.7, 0.5], k: 0.09 }],
+ LensType::Prime105 => vec![Ghost { t: 0.5, r: 14.0, tint: [1.0, 0.8, 0.5], k: 0.12 }, Ghost { t: 1.6, r: 50.0, tint: [0.6, 0.7, 1.0], k: 0.07 }],
+ LensType::MoviePrime => vec![
+ Ghost { t: 0.4, r: 8.0, tint: [0.5, 0.7, 1.0], k: 0.2 },
+ Ghost { t: 1.0, r: 20.0, tint: [0.4, 0.6, 1.0], k: 0.12 },
+ Ghost { t: 1.6, r: 12.0, tint: [0.5, 0.8, 1.0], k: 0.16 },
+ ],
+ };
+ let mut res = src.crop(out);
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let (dx, dy) = (fx - cx, fy - cy);
+ let d = (dx * dx + dy * dy).sqrt();
+ let mut f = [0.0f32; 3];
+ // Hot core and wide glow (warm white).
+ let g = (-(d / (core * s)).powi(2)).exp() + 0.35 * (-d / (glow * s)).exp();
+ for (k, w) in [1.0, 0.95, 0.85].iter().enumerate() {
+ f[k] += g * w;
+ }
+ // Rays: angular modulation decaying with distance.
+ if rays > 0.0 {
+ let th = dy.atan2(dx);
+ let m = ((th * 12.0).sin() * 0.5 + 0.5).powi(8) + ((th * 7.0 + 1.3).sin() * 0.5 + 0.5).powi(12) * 0.6;
+ let rr = rays * m * (-d / (glow * 1.6 * s)).exp();
+ for v in f.iter_mut() {
+ *v += rr * 0.6;
+ }
+ }
+ // Anamorphic horizontal streak (movie prime).
+ if streak > 0.0 {
+ let st = (-(dy.abs() / (2.5 * s))).exp() * (-(dx.abs() / (450.0 * s))).exp();
+ f[0] += st * 0.5;
+ f[1] += st * 0.7;
+ f[2] += st;
+ }
+ // Halo ring with a slight chromatic spread.
+ if ring_r > 0.0 {
+ for (k, off) in [1.04f32, 1.0, 0.96].iter().enumerate() {
+ let rd = (d - ring_r * s * off) / (ring_w * s);
+ f[k] += 0.18 * (-rd * rd).exp();
+ }
+ }
+ // Ghosts along the axis through the centre.
+ for gh in &ghosts {
+ let (gx, gy) = (cx + (mx - cx) * gh.t * 2.0, cy + (my - cy) * gh.t * 2.0);
+ let gd = ((fx - gx).powi(2) + (fy - gy).powi(2)).sqrt() / (gh.r * s);
+ if gd < 1.2 {
+ // Soft-edged disc, slightly brighter at the rim.
+ let e = smoothstep(1.0, 0.85, gd) * (0.6 + 0.4 * gd);
+ for (fk, t) in f.iter_mut().zip(gh.tint) {
+ *fk += e * gh.k * t;
+ }
+ }
+ }
+ let mut c = rgba(ctx, px);
+ for k in 0..3 {
+ let a = (f[k] * bright).max(0.0);
+ // Screen keeps highlights below white for display-referred values.
+ c[k] = 1.0 - (1.0 - c[k]) * (1.0 - a.min(1.0));
+ }
+ set_rgba(ctx, px, c);
+ }
+ res
+}
+
+pub(crate) struct LightingSpec<'a> {
+ pub lights: &'a [Light],
+ pub gloss: f32,
+ pub metallic: f32,
+ pub exposure: f32,
+ pub ambience: f32,
+ pub texture: TextureChannel,
+ pub height: f32,
+ pub white_is_high: bool,
+}
+
+fn norm3(v: [f32; 3]) -> [f32; 3] {
+ let m = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-9);
+ [v[0] / m, v[1] / m, v[2] / m]
+}
+fn dot3(a: [f32; 3], b: [f32; 3]) -> f32 {
+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+}
+
+/// Lighting Effects: Blinn–Phong shading of the image as a surface (bumped by
+/// a texture channel) under spot, point and infinite lights.
+pub(crate) fn lighting(src: &Image, out: Rect, ctx: &Ctx, spec: &LightingSpec) -> Vec<f32> {
+ let n = src.ch;
+ let b = ctx.bounds;
+ let (bw, bh) = (b.width() as f32, b.height() as f32);
+ let short = bw.min(bh).max(1.0);
+ let hscale = spec.height.clamp(0.0, 100.0) / 100.0 * 0.06 * short;
+ let shininess = 2f32.powf(1.0 + (spec.gloss.clamp(-100.0, 100.0) + 100.0) / 200.0 * 7.0);
+ let spec_k = (spec.gloss.clamp(-100.0, 100.0) + 100.0) / 200.0 * 0.7;
+ let metal = (spec.metallic.clamp(-100.0, 100.0) + 100.0) / 200.0;
+ let expo = 2f32.powf(spec.exposure.clamp(-100.0, 100.0) / 50.0);
+ let ambient = spec.ambience.clamp(-100.0, 100.0) / 100.0 * 0.5;
+ let mut tmp = [0.0f32; MAXC];
+ let tex = |x: i32, y: i32, tmp: &mut [f32; MAXC]| -> f32 {
+ let xx = x.clamp(b.x0, b.x1 - 1);
+ let yy = y.clamp(b.y0, b.y1 - 1);
+ for (c, t) in tmp.iter_mut().enumerate().take(n) {
+ *t = src.get(xx, yy, c);
+ }
+ let v = match spec.texture {
+ TextureChannel::None => 0.0,
+ TextureChannel::Alpha => {
+ if ctx.alpha {
+ tmp[n - 1]
+ } else {
+ 1.0
+ }
+ }
+ TextureChannel::Luminance => luma(ctx, &tmp[..n]),
+ TextureChannel::Red | TextureChannel::Green | TextureChannel::Blue => {
+ let k = match spec.texture {
+ TextureChannel::Red => 0,
+ TextureChannel::Green => 1,
+ _ => 2,
+ };
+ if ctx.mode == photocraft_color::ColorMode::Rgb { tmp[k] } else { rgba(ctx, &tmp[..n])[k] }
+ }
+ };
+ if spec.white_is_high { v } else { 1.0 - v }
+ };
+ let lights: Vec<Light> = spec.lights.to_vec();
+ let mut res = src.crop(out);
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let nrm = if spec.texture == TextureChannel::None || hscale <= 0.0 {
+ [0.0, 0.0, 1.0]
+ } else {
+ let hx = (tex(x + 1, y, &mut tmp) - tex(x - 1, y, &mut tmp)) * 0.5 * hscale;
+ let hy = (tex(x, y + 1, &mut tmp) - tex(x, y - 1, &mut tmp)) * 0.5 * hscale;
+ norm3([-hx, -hy, 1.0])
+ };
+ let mut c = rgba(ctx, px);
+ let base = [c[0], c[1], c[2]];
+ let mut lit = [ambient; 3];
+ let mut spc = [0.0f32; 3];
+ for l in &lights {
+ let lpos = [b.x0 as f32 + l.x * bw, b.y0 as f32 + l.y * bh, l.z * short];
+ let (ldir, atten) = match l.kind {
+ LightKind::Infinite => {
+ let (s, co) = l.angle.to_radians().sin_cos();
+ let e = l.elevation.clamp(0.0, 90.0).to_radians();
+ (norm3([co * e.cos(), -s * e.cos(), e.sin()]), 1.0)
+ }
+ LightKind::Point => {
+ let v = [lpos[0] - fx, lpos[1] - fy, lpos[2]];
+ let dist = (v[0] * v[0] + v[1] * v[1]).sqrt();
+ let reach = (l.radius * short).max(1.0);
+ (norm3(v), (1.0 - dist / reach).clamp(0.0, 1.0).powi(2))
+ }
+ LightKind::Spot => {
+ let v = [lpos[0] - fx, lpos[1] - fy, lpos[2]];
+ let ld = norm3(v);
+ let tgt = [b.x0 as f32 + l.target_x * bw, b.y0 as f32 + l.target_y * bh, 0.0];
+ let axis = norm3([tgt[0] - lpos[0], tgt[1] - lpos[1], tgt[2] - lpos[2]]);
+ let cosang = -dot3(ld, axis);
+ let outer = l.cone.clamp(1.0, 89.0).to_radians().cos();
+ let inner = (l.cone.clamp(1.0, 89.0) * (l.hotspot.clamp(0.0, 100.0) / 100.0)).to_radians().cos();
+ (ld, smoothstep(outer, inner.max(outer + 1e-4), cosang))
+ }
+ };
+ if atten <= 0.0 {
+ continue;
+ }
+ let inten = l.intensity.clamp(-100.0, 100.0) / 50.0 * atten;
+ let ndl = dot3(nrm, ldir).max(0.0);
+ let hv = norm3([ldir[0], ldir[1], ldir[2] + 1.0]);
+ let s = dot3(nrm, hv).max(0.0).powf(shininess) * spec_k;
+ for k in 0..3 {
+ lit[k] += ndl * inten * l.color[k];
+ // Metallic highlights take the surface colour; plastic ones the light's.
+ let sc = l.color[k] * (1.0 - metal) + base[k] * metal;
+ spc[k] += s * inten.max(0.0) * sc;
+ }
+ }
+ for k in 0..3 {
+ c[k] = ((base[k] * lit[k] + spc[k]) * expo).max(0.0);
+ }
+ set_rgba(ctx, px, c);
+ }
+ res
+}
diff --git a/crates/algo/src/seam.rs b/crates/algo/src/seam.rs
new file mode 100644
index 000000000..bdd7edd3f
--- /dev/null
+++ b/crates/algo/src/seam.rs
@@ -0,0 +1,323 @@
+//! Content-aware scaling by seam carving (Edit › Content-Aware Scale).
+//!
+//! S. Avidan, A. Shamir, *Seam Carving for Content-Aware Image Resizing*, SIGGRAPH 2007:
+//! a seam is an 8-connected path of one pixel per row (vertical seam) found by dynamic
+//! programming over a gradient-magnitude energy map. Shrinking removes the lowest-energy seams one
+//! at a time; enlarging finds the `k` lowest seams on a shrinking copy and duplicates them
+//! (averaging each with its right neighbour) so the same seam is not stretched repeatedly.
+//! Heights are handled by transposing.
+//!
+//! A protect map (`0..=1`, e.g. an alpha channel or detected skin tones) adds a large energy so
+//! seams avoid protected pixels. Buffers are interleaved `w × h × ch` normalised floats of any
+//! colour model and depth (alpha is carried like any other channel). Deterministic.
+
+/// Energy added per unit of protection: far above any gradient magnitude.
+const PROTECT_ENERGY: f32 = 1.0e4;
+
+/// Gradient-magnitude energy (the paper's e1, `|∂x| + |∂y|` summed over channels). Forward and
+/// backward differences are both counted so one-pixel lines (whose central difference is zero)
+/// carry energy too.
+pub fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec<f32> {
+ let mut e = vec![0.0f32; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ let (xl, xr) = (x.saturating_sub(1), (x + 1).min(w - 1));
+ let (yu, yd) = (y.saturating_sub(1), (y + 1).min(h - 1));
+ let at = |xx: usize, yy: usize, c: usize| img[(yy * w + xx) * ch + c];
+ let mut s = 0.0;
+ for c in 0..ch {
+ let v = at(x, y, c);
+ s += (at(xr, y, c) - v).abs() + (v - at(xl, y, c)).abs();
+ s += (at(x, yd, c) - v).abs() + (v - at(x, yu, c)).abs();
+ }
+ e[y * w + x] = s * 0.5;
+ }
+ }
+ e
+}
+
+/// The lowest-energy vertical seam: one x per row.
+pub fn find_seam(w: usize, h: usize, energy: &[f32]) -> Vec<usize> {
+ let mut cost = energy[..w].to_vec();
+ let mut from = vec![0u8; w * h]; // 0 = up-left, 1 = up, 2 = up-right
+ let mut next = vec![0.0f32; w];
+ for y in 1..h {
+ for x in 0..w {
+ let mut best = (cost[x], 1u8);
+ if x > 0 && cost[x - 1] < best.0 {
+ best = (cost[x - 1], 0);
+ }
+ if x + 1 < w && cost[x + 1] < best.0 {
+ best = (cost[x + 1], 2);
+ }
+ next[x] = best.0 + energy[y * w + x];
+ from[y * w + x] = best.1;
+ }
+ std::mem::swap(&mut cost, &mut next);
+ }
+ let mut x = (0..w).min_by(|a, b| cost[*a].total_cmp(&cost[*b])).unwrap_or(0);
+ let mut seam = vec![0usize; h];
+ for y in (0..h).rev() {
+ seam[y] = x;
+ if y > 0 {
+ x = match from[y * w + x] {
+ 0 => x - 1,
+ 2 => x + 1,
+ _ => x,
+ };
+ }
+ }
+ seam
+}
+
+fn remove_seam(w: usize, h: usize, ch: usize, img: &[f32], seam: &[usize]) -> Vec<f32> {
+ let mut out = Vec::with_capacity((w - 1) * h * ch);
+ for (y, &sx) in seam.iter().enumerate().take(h) {
+ let row = &img[y * w * ch..(y + 1) * w * ch];
+ out.extend_from_slice(&row[..sx * ch]);
+ out.extend_from_slice(&row[(sx + 1) * ch..]);
+ }
+ out
+}
+
+fn remove_seam_1(w: usize, h: usize, v: &[f32], seam: &[usize]) -> Vec<f32> {
+ remove_seam(w, h, 1, v, seam)
+}
+
+fn transpose(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec<f32> {
+ let mut out = vec![0.0f32; img.len()];
+ for y in 0..h {
+ for x in 0..w {
+ let (s, d) = ((y * w + x) * ch, (x * h + y) * ch);
+ out[d..d + ch].copy_from_slice(&img[s..s + ch]);
+ }
+ }
+ out
+}
+
+/// Change the width of `img` to `new_w` by removing or duplicating vertical seams.
+pub fn carve_width(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize) -> Vec<f32> {
+ let new_w = new_w.max(1);
+ if new_w == w || w == 0 || h == 0 {
+ return img.to_vec();
+ }
+ let protect_e = |e: &mut [f32], p: Option<&Vec<f32>>| {
+ if let Some(p) = p {
+ for (e, p) in e.iter_mut().zip(p) {
+ *e += p.clamp(0.0, 1.0) * PROTECT_ENERGY;
+ }
+ }
+ };
+ if new_w < w {
+ let (mut cur, mut cw) = (img.to_vec(), w);
+ let mut prot = protect.map(<[f32]>::to_vec);
+ while cw > new_w {
+ let mut e = energy(cw, h, ch, &cur);
+ protect_e(&mut e, prot.as_ref());
+ let seam = find_seam(cw, h, &e);
+ cur = remove_seam(cw, h, ch, &cur, &seam);
+ prot = prot.map(|p| remove_seam_1(cw, h, &p, &seam));
+ cw -= 1;
+ }
+ return cur;
+ }
+ // Enlarge in rounds of at most half the current width, each duplicating the k lowest seams.
+ let (mut cur, mut cw) = (img.to_vec(), w);
+ let mut prot = protect.map(<[f32]>::to_vec);
+ while cw < new_w {
+ let k = (new_w - cw).min((cw / 2).max(1));
+ // Find k seams on a shrinking copy, mapping each back to original columns.
+ let mut idx: Vec<Vec<usize>> = (0..h).map(|_| (0..cw).collect()).collect();
+ let (mut tmp, mut tw) = (cur.clone(), cw);
+ let mut tprot = prot.clone();
+ let mut dup: Vec<Vec<usize>> = vec![Vec::with_capacity(k); h];
+ for _ in 0..k {
+ if tw <= 1 {
+ break;
+ }
+ let mut e = energy(tw, h, ch, &tmp);
+ protect_e(&mut e, tprot.as_ref());
+ let seam = find_seam(tw, h, &e);
+ for (y, &sx) in seam.iter().enumerate() {
+ dup[y].push(idx[y].remove(sx));
+ }
+ tmp = remove_seam(tw, h, ch, &tmp, &seam);
+ tprot = tprot.map(|p| remove_seam_1(tw, h, &p, &seam));
+ tw -= 1;
+ }
+ let added = dup[0].len();
+ if added == 0 {
+ break;
+ }
+ let nw = cw + added;
+ let mut out = Vec::with_capacity(nw * h * ch);
+ let mut nprot = prot.as_ref().map(|_| Vec::with_capacity(nw * h));
+ for (y, d) in dup.iter_mut().enumerate() {
+ d.sort_unstable();
+ let row = &cur[y * cw * ch..(y + 1) * cw * ch];
+ let mut di = 0;
+ for x in 0..cw {
+ out.extend_from_slice(&row[x * ch..(x + 1) * ch]);
+ if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) {
+ np.push(p[y * cw + x]);
+ }
+ while di < d.len() && d[di] == x {
+ let xr = (x + 1).min(cw - 1);
+ for c in 0..ch {
+ out.push((row[x * ch + c] + row[xr * ch + c]) * 0.5);
+ }
+ if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) {
+ np.push(p[y * cw + x]);
+ }
+ di += 1;
+ }
+ }
+ }
+ cur = out;
+ prot = nprot;
+ cw = nw;
+ }
+ cur
+}
+
+/// Content-aware resize of `img` to `new_w × new_h` (width first, then height by transposing).
+pub fn carve(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize, new_h: usize) -> Vec<f32> {
+ let (new_w, new_h) = (new_w.max(1), new_h.max(1));
+ let wide = carve_width(w, h, ch, img, protect, new_w);
+ if new_h == h {
+ return wide;
+ }
+ // Protection follows the width change by plain resampling (it only steers seams).
+ let prot_t = protect.map(|p| transpose(new_w, h, 1, &resize_bilinear(w, h, 1, p, new_w, h)));
+ let t = transpose(new_w, h, ch, &wide);
+ let tall = carve_width(h, new_w, ch, &t, prot_t.as_deref(), new_h);
+ transpose(new_h, new_w, ch, &tall)
+}
+
+/// Plain bilinear resize (the non-content-aware part of the Amount blend).
+pub fn resize_bilinear(w: usize, h: usize, ch: usize, img: &[f32], nw: usize, nh: usize) -> Vec<f32> {
+ let mut out = vec![0.0f32; nw * nh * ch];
+ if w == 0 || h == 0 {
+ return out;
+ }
+ for y in 0..nh {
+ let fy = ((y as f32 + 0.5) * h as f32 / nh as f32 - 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 x in 0..nw {
+ let fx = ((x as f32 + 0.5) * w as f32 / nw as f32 - 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);
+ for c in 0..ch {
+ let p = |xx: usize, yy: usize| img[(yy * w + xx) * ch + c];
+ let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx;
+ let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx;
+ out[(y * nw + x) * ch + c] = top + (bot - top) * ty;
+ }
+ }
+ }
+ out
+}
+
+/// Skin-tone protection map (1 = skin) for RGB(A) buffers: the explicit RGB rule of
+/// J. Kovač, P. Peer, F. Solina, *Human Skin Colour Clustering for Face Detection*, EUROCON 2003.
+pub fn skin_mask(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec<f32> {
+ let mut m = vec![0.0f32; w * h];
+ if ch < 3 {
+ return m;
+ }
+ for (i, v) in m.iter_mut().enumerate() {
+ let p = &img[i * ch..i * ch + 3];
+ let (r, g, b) = (p[0] * 255.0, p[1] * 255.0, p[2] * 255.0);
+ let (mx, mn) = (r.max(g).max(b), r.min(g).min(b));
+ if r > 95.0 && g > 40.0 && b > 20.0 && mx - mn > 15.0 && (r - g).abs() > 15.0 && r > g && r > b {
+ *v = 1.0;
+ }
+ }
+ m
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A flat grey image with a salient vertical bar at x = 10..14 (red/blue columns).
+ fn bar(w: usize, h: usize) -> Vec<f32> {
+ let mut v = vec![0.5f32; w * h * 3];
+ for y in 0..h {
+ for x in 10..14 {
+ let c = if x % 2 == 0 { [1.0, 0.0, 0.0] } else { [0.0, 0.0, 1.0] };
+ v[(y * w + x) * 3..(y * w + x) * 3 + 3].copy_from_slice(&c);
+ }
+ }
+ v
+ }
+
+ /// Columns that are pure red or pure blue top to bottom.
+ fn red_columns(w: usize, h: usize, img: &[f32]) -> usize {
+ let pure = |p: &[f32]| p[1] < 0.05 && ((p[0] > 0.95 && p[2] < 0.05) || (p[2] > 0.95 && p[0] < 0.05));
+ (0..w).filter(|x| (0..h).all(|y| pure(&img[(y * w + x) * 3..(y * w + x) * 3 + 3]))).count()
+ }
+
+ #[test]
+ fn seam_follows_low_energy() {
+ let (w, h) = (5, 4);
+ let mut e = vec![9.0f32; w * h];
+ for y in 0..h {
+ e[y * w + 2] = 0.0;
+ }
+ assert_eq!(find_seam(w, h, &e), vec![2; 4]);
+ }
+
+ #[test]
+ fn shrinking_keeps_the_salient_bar() {
+ let (w, h) = (40, 12);
+ let img = bar(w, h);
+ let out = carve(w, h, 3, &img, None, 24, h);
+ assert_eq!(out.len(), 24 * h * 3);
+ assert_eq!(red_columns(24, h, &out), 4, "the bar survives intact");
+ // Plain resampling squashes it instead.
+ let plain = resize_bilinear(w, h, 3, &img, 24, h);
+ assert!(red_columns(24, h, &plain) < 4);
+ }
+
+ #[test]
+ fn enlarging_duplicates_flat_areas() {
+ let (w, h) = (30, 8);
+ let img = bar(w, h);
+ let out = carve(w, h, 3, &img, None, 50, h);
+ assert_eq!(out.len(), 50 * h * 3);
+ assert_eq!(red_columns(50, h, &out), 4);
+ }
+
+ #[test]
+ fn height_and_protection() {
+ let (w, h) = (20, 30);
+ // Horizontal bar: carve height.
+ let mut img = vec![0.2f32; w * h];
+ for x in 0..w {
+ img[12 * w + x] = 1.0;
+ }
+ let out = carve(w, h, 1, &img, None, w, 18);
+ assert_eq!(out.len(), w * 18);
+ assert_eq!((0..18).filter(|y| (0..w).all(|x| out[y * w + x] > 0.9)).count(), 1);
+ // Protecting a flat region keeps it: the seams go elsewhere.
+ let flat = vec![0.5f32; 16 * 4];
+ let mut protect = vec![0.0f32; 16 * 4];
+ for y in 0..4 {
+ protect[y * 16 + 3] = 1.0;
+ }
+ let mut marked = flat.clone();
+ for y in 0..4 {
+ marked[y * 16 + 3] = 0.51;
+ }
+ let out = carve(16, 4, 1, &marked, Some(&protect), 8, 4);
+ assert!((0..4).all(|y| out[y * 8..y * 8 + 8].iter().any(|v| (*v - 0.51).abs() < 1e-6)));
+ }
+
+ #[test]
+ fn skin_rule() {
+ let px = [0.86f32, 0.62, 0.5, 0.2, 0.4, 0.8];
+ assert_eq!(skin_mask(2, 1, 3, &px), vec![1.0, 0.0]);
+ }
+}
diff --git a/crates/algo/src/stack.rs b/crates/algo/src/stack.rs
new file mode 100644
index 000000000..214240432
--- /dev/null
+++ b/crates/algo/src/stack.rs
@@ -0,0 +1,161 @@
+//! Image stack statistics (Layer › Smart Objects › Stack Mode): a per-pixel, per-channel
+//! statistic across N aligned images, e.g. median to remove passers-by or mean to reduce noise.
+//!
+//! Inputs are straight RGBA buffers of equal size. Only samples with alpha > 0 contribute; the
+//! output alpha is the largest input alpha. Moments use the population definitions; skewness and
+//! kurtosis are standardised (kurtosis is excess-free, a normal sample gives ≈ 3), scaled into
+//! 0..=1 for display; entropy is the Shannon entropy (bits) of the 8-bit values over log2(N).
+
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum Stat {
+ Entropy,
+ Kurtosis,
+ Maximum,
+ Mean,
+ Median,
+ Minimum,
+ Range,
+ Skewness,
+ StandardDeviation,
+ Summation,
+ Variance,
+}
+
+fn stat(v: &mut [f32], s: Stat) -> f32 {
+ let n = v.len() as f32;
+ if v.is_empty() {
+ return 0.0;
+ }
+ let mean = v.iter().sum::<f32>() / n;
+ let m = |k: i32| v.iter().map(|x| (x - mean).powi(k)).sum::<f32>() / n;
+ match s {
+ Stat::Mean => mean,
+ Stat::Summation => v.iter().sum::<f32>(),
+ Stat::Minimum => v.iter().copied().fold(f32::MAX, f32::min),
+ Stat::Maximum => v.iter().copied().fold(f32::MIN, f32::max),
+ Stat::Range => {
+ v.iter().copied().fold(f32::MIN, f32::max) - v.iter().copied().fold(f32::MAX, f32::min)
+ }
+ Stat::Median => {
+ v.sort_by(f32::total_cmp);
+ let k = v.len();
+ if k % 2 == 1 {
+ v[k / 2]
+ } else {
+ (v[k / 2 - 1] + v[k / 2]) / 2.0
+ }
+ }
+ Stat::Variance => m(2),
+ Stat::StandardDeviation => m(2).sqrt(),
+ Stat::Skewness => {
+ let sd = m(2).sqrt();
+ // Map −2..2 to 0..1 (0.5 = symmetric).
+ if sd < 1e-6 {
+ 0.5
+ } else {
+ (m(3) / sd.powi(3) / 4.0 + 0.5).clamp(0.0, 1.0)
+ }
+ }
+ Stat::Kurtosis => {
+ let var = m(2);
+ // 0..10 → 0..1.
+ if var < 1e-12 {
+ 0.0
+ } else {
+ (m(4) / (var * var) / 10.0).clamp(0.0, 1.0)
+ }
+ }
+ Stat::Entropy => {
+ if v.len() < 2 {
+ return 0.0;
+ }
+ let mut counts: std::collections::HashMap<u8, u32> = std::collections::HashMap::new();
+ for x in v.iter() {
+ *counts
+ .entry((x.clamp(0.0, 1.0) * 255.0).round() as u8)
+ .or_default() += 1;
+ }
+ let h: f32 = counts
+ .values()
+ .map(|&c| {
+ let p = c as f32 / n;
+ -p * p.log2()
+ })
+ .sum();
+ h / n.log2()
+ }
+ }
+}
+
+/// Combines `layers` (each `len` pixels) with statistic `s`.
+pub fn combine(layers: &[Vec<[f32; 4]>], s: Stat) -> Vec<[f32; 4]> {
+ let len = layers.iter().map(Vec::len).max().unwrap_or(0);
+ let mut out = vec![[0.0f32; 4]; len];
+ let mut samples: [Vec<f32>; 3] = Default::default();
+ for (i, o) in out.iter_mut().enumerate() {
+ for v in samples.iter_mut() {
+ v.clear();
+ }
+ let mut alpha = 0.0f32;
+ for l in layers {
+ if let Some(p) = l.get(i)
+ && p[3] > 0.0
+ {
+ for c in 0..3 {
+ samples[c].push(p[c]);
+ }
+ alpha = alpha.max(p[3]);
+ }
+ }
+ if alpha <= 0.0 {
+ continue;
+ }
+ for c in 0..3 {
+ o[c] = stat(&mut samples[c], s).clamp(0.0, 1.0);
+ }
+ o[3] = alpha;
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn px(v: f32) -> Vec<[f32; 4]> {
+ vec![[v, v, v, 1.0]]
+ }
+
+ #[test]
+ fn basic_statistics() {
+ let layers = vec![px(0.1), px(0.9), px(0.2), px(0.3), px(0.1)];
+ let at = |s| combine(&layers, s)[0][0];
+ assert!((at(Stat::Mean) - 0.32).abs() < 1e-6);
+ assert!((at(Stat::Median) - 0.2).abs() < 1e-6);
+ assert_eq!(at(Stat::Minimum), 0.1);
+ assert_eq!(at(Stat::Maximum), 0.9);
+ assert!((at(Stat::Range) - 0.8).abs() < 1e-6);
+ assert_eq!(at(Stat::Summation), 1.0); // clamped
+ let var = at(Stat::Variance);
+ assert!((at(Stat::StandardDeviation) - var.sqrt()).abs() < 1e-6);
+ assert!(at(Stat::Skewness) > 0.5, "right-skewed");
+ assert!(at(Stat::Entropy) > 0.0 && at(Stat::Entropy) <= 1.0);
+ assert!(at(Stat::Kurtosis) > 0.0);
+ }
+
+ #[test]
+ fn transparent_samples_are_ignored() {
+ let layers = vec![vec![[0.5, 0.5, 0.5, 1.0]], vec![[1.0, 1.0, 1.0, 0.0]]];
+ assert_eq!(combine(&layers, Stat::Mean)[0], [0.5, 0.5, 0.5, 1.0]);
+ let empty = vec![vec![[1.0, 1.0, 1.0, 0.0]]];
+ assert_eq!(combine(&empty, Stat::Mean)[0][3], 0.0);
+ }
+
+ #[test]
+ fn median_removes_outlier() {
+ let layers = vec![px(0.5), px(0.5), px(1.0)];
+ assert_eq!(combine(&layers, Stat::Median)[0][0], 0.5);
+ }
+}
diff --git a/crates/algo/src/stylize2.rs b/crates/algo/src/stylize2.rs
new file mode 100644
index 000000000..af1d58895
--- /dev/null
+++ b/crates/algo/src/stylize2.rs
@@ -0,0 +1,405 @@
+//! Stylize: Diffuse, Extrude, Tiles, Trace Contour, Wind.
+
+use photocraft_geom::Rect;
+
+use crate::fxutil::{MAXC, luma, native, ncol, subtractive, xy};
+use crate::image::Image;
+use crate::noise::hash01;
+use crate::{Ctx, DiffuseMode, ExtrudeType, TileFill, WindMethod};
+
+fn read_px(src: &Image, x: i32, y: i32, buf: &mut [f32]) {
+ for (c, v) in buf.iter_mut().enumerate() {
+ *v = src.get(x, y, c);
+ }
+}
+
+/// Diffuse: every pixel is swapped for a random neighbour (within 1 px);
+/// Darken/Lighten Only accept the neighbour only when darker/lighter;
+/// Anisotropic picks the most similar neighbour, softening noise.
+pub(crate) fn diffuse(src: &Image, out: Rect, ctx: &Ctx, mode: DiffuseMode, seed: u32) -> Vec<f32> {
+ let n = src.ch;
+ let mut res = src.crop(out);
+ let mut nb = [0.0f32; MAXC];
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ match mode {
+ DiffuseMode::Anisotropic => {
+ let me = luma(ctx, px);
+ let mut best = (f32::MAX, (0, 0));
+ // Random start so ties do not bias one direction.
+ let start = (hash01(x, y, 3, seed) * 8.0) as usize;
+ const RING: [(i32, i32); 8] = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)];
+ for k in 0..8 {
+ let (dx, dy) = RING[(start + k) % 8];
+ read_px(src, x + dx, y + dy, &mut nb[..n]);
+ let d = (luma(ctx, &nb[..n]) - me).abs();
+ if d < best.0 {
+ best = (d, (dx, dy));
+ }
+ }
+ let (dx, dy) = best.1;
+ read_px(src, x + dx, y + dy, &mut nb[..n]);
+ // Half-way move: anisotropic diffusion softens rather than shuffles.
+ for c in 0..n {
+ px[c] = 0.5 * (px[c] + nb[c]);
+ }
+ }
+ _ => {
+ let dx = (hash01(x, y, 1, seed) * 3.0) as i32 - 1;
+ let dy = (hash01(x, y, 2, seed) * 3.0) as i32 - 1;
+ read_px(src, x + dx, y + dy, &mut nb[..n]);
+ if ctx.alpha && nb[n - 1] <= 0.0 && px[n - 1] > 0.0 && mode != DiffuseMode::Normal {
+ continue;
+ }
+ let take = match mode {
+ DiffuseMode::DarkenOnly => luma(ctx, &nb[..n]) < luma(ctx, px),
+ DiffuseMode::LightenOnly => luma(ctx, &nb[..n]) > luma(ctx, px),
+ _ => true,
+ };
+ if take {
+ px.copy_from_slice(&nb[..n]);
+ }
+ }
+ }
+ }
+ res
+}
+
+/// Extrude parameters.
+pub(crate) struct ExtrudeSpec {
+ pub kind: ExtrudeType,
+ pub size: f32,
+ pub depth: f32,
+ pub level_based: bool,
+ pub solid_front: bool,
+ pub mask_incomplete: bool,
+ pub seed: u32,
+}
+
+/// Max on-screen displacement of an extruded block's front face, px.
+pub(crate) fn extrude_reach(depth: f32) -> f32 {
+ depth.clamp(0.0, 255.0) * 0.25
+}
+
+/// Extrude: the bounds are cut into square cells. Blocks are pushed toward
+/// the viewer (front faces shift away from the bounds' centre by their
+/// height, with shaded sides); Pyramids raise four shaded triangular faces.
+/// Heights are random or follow the cell's brightness.
+pub(crate) fn extrude(src: &Image, out: Rect, ctx: &Ctx, spec: &ExtrudeSpec) -> Vec<f32> {
+ let n = src.ch;
+ let cs = spec.size.clamp(2.0, 255.0).round() as i32;
+ let b = ctx.bounds;
+ let (bcx, bcy) = ((b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0);
+ let half_diag = ((b.width() as f32).hypot(b.height() as f32) / 2.0).max(1.0);
+ let reach = extrude_reach(spec.depth);
+ let mut res = src.crop(out);
+ let cell_rect = |gx: i32, gy: i32| Rect::new(b.x0 + gx * cs, b.y0 + gy * cs, b.x0 + (gx + 1) * cs, b.y0 + (gy + 1) * cs);
+ let incomplete = |r: &Rect| r.intersect(&b) != *r;
+ // Average colour and height of a cell (cached for the last cell queried per pixel row).
+ let cell_info = |gx: i32, gy: i32| -> ([f32; MAXC], f32) {
+ let r = cell_rect(gx, gy).intersect(&b);
+ let mut acc = [0.0f32; MAXC];
+ let mut cnt = 0.0;
+ // Sparse sampling keeps big cells cheap; the average only colours faces.
+ let step = (cs / 8).max(1);
+ let mut yy = r.y0;
+ while yy < r.y1 {
+ let mut xx = r.x0;
+ while xx < r.x1 {
+ let a = if ctx.alpha { src.get(xx, yy, n - 1) } else { 1.0 };
+ for (c, v) in acc.iter_mut().enumerate().take(n) {
+ let s = src.get(xx, yy, c);
+ *v += if ctx.alpha && c < n - 1 { s * a } else { s };
+ }
+ cnt += 1.0;
+ xx += step;
+ }
+ yy += step;
+ }
+ if cnt > 0.0 {
+ for v in acc.iter_mut().take(n) {
+ *v /= cnt;
+ }
+ }
+ crate::fxutil::unpremul_px(&mut acc[..n], ctx.alpha);
+ let h = if spec.level_based { luma(ctx, &acc[..n]).clamp(0.0, 1.0) } else { hash01(gx, gy, 21, spec.seed) };
+ (acc, h)
+ };
+ let shade = |px: &mut [f32], col: &[f32], k: f32| {
+ let cc = ncol(ctx, n);
+ let sub = subtractive(ctx);
+ for c in 0..cc {
+ px[c] = if sub { 1.0 - (1.0 - col[c]) * k } else { col[c] * k }.clamp(0.0, 1.0);
+ }
+ if ctx.alpha {
+ px[n - 1] = col[n - 1];
+ }
+ };
+ type CellInfo = ((i32, i32), ([f32; MAXC], f32));
+ let mut cache: Vec<CellInfo> = Vec::with_capacity(32);
+ let w = out.width() as usize;
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = (out.x0 + (i % w) as i32, out.y0 + (i / w) as i32);
+ if !b.contains(x, y) {
+ continue;
+ }
+ if i % w == 0 {
+ cache.clear();
+ }
+ let mut info = |gx: i32, gy: i32| -> ([f32; MAXC], f32) {
+ if let Some((_, v)) = cache.iter().find(|(k, _)| *k == (gx, gy)) {
+ return *v;
+ }
+ let v = cell_info(gx, gy);
+ if cache.len() >= 64 {
+ cache.remove(0);
+ }
+ cache.push(((gx, gy), v));
+ v
+ };
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let (gx, gy) = ((x - b.x0).div_euclid(cs), (y - b.y0).div_euclid(cs));
+ match spec.kind {
+ ExtrudeType::Pyramids => {
+ let r = cell_rect(gx, gy);
+ if spec.mask_incomplete && incomplete(&r) {
+ continue;
+ }
+ let (col, h) = info(gx, gy);
+ let (u, v) = (fx - (r.x0 as f32 + cs as f32 / 2.0), fy - (r.y0 as f32 + cs as f32 / 2.0));
+ // Face normals of a pyramid of height H over a cell of half-size s; light from the top-left.
+ let hgt = h * spec.depth.clamp(1.0, 255.0) / 255.0 * cs as f32;
+ let s = cs as f32 / 2.0;
+ let (nx, ny) = if u.abs() >= v.abs() { (u.signum() * hgt, 0.0) } else { (0.0, v.signum() * hgt) };
+ let norm = (nx * nx + ny * ny + s * s).sqrt();
+ let (lx, ly, lz) = (-0.5f32, -0.5f32, std::f32::consts::FRAC_1_SQRT_2);
+ let lambert = ((nx * lx + ny * ly + s * lz) / norm).max(0.0);
+ shade(px, &col, 0.35 + 0.9 * lambert);
+ }
+ ExtrudeType::Blocks => {
+ // Candidate blocks: own cell and the neighbours whose front faces can reach here.
+ let k = (reach / cs as f32).ceil() as i32 + 1;
+ let mut best: Option<(f32, i32, i32, u8)> = None; // (height, gx, gy, face: 0 front, 1..4 sides)
+ for dy in -k..=k {
+ for dx in -k..=k {
+ let (cx, cy) = (gx + dx, gy + dy);
+ let r = cell_rect(cx, cy);
+ if r.x1 <= b.x0 || r.y1 <= b.y0 || r.x0 >= b.x1 || r.y0 >= b.y1 {
+ continue;
+ }
+ if spec.mask_incomplete && incomplete(&r) {
+ continue;
+ }
+ let h = info(cx, cy).1;
+ if best.is_some_and(|bb| bb.0 >= h) {
+ continue;
+ }
+ // Front face offset grows with height and distance from the centre.
+ let (mx, my) = (r.x0 as f32 + cs as f32 / 2.0, r.y0 as f32 + cs as f32 / 2.0);
+ let off = reach * h / half_diag;
+ let (ox, oy) = ((mx - bcx) * off, (my - bcy) * off);
+ let half = cs as f32 / 2.0;
+ // Sweep t ∈ [0, 1] from base to front: inside if some t puts the pixel in the square.
+ let interval = |p: f32, m: f32, o: f32| -> Option<(f32, f32)> {
+ // |p − (m + o t)| ≤ half
+ if o.abs() < 1e-6 {
+ return ((p - m).abs() <= half).then_some((0.0, 1.0));
+ }
+ let (a, bb) = ((p - m - half) / o, (p - m + half) / o);
+ let (lo, hi) = (a.min(bb).max(0.0), a.max(bb).min(1.0));
+ (lo <= hi).then_some((lo, hi))
+ };
+ let (Some(ix), Some(iy)) = (interval(fx, mx, ox), interval(fy, my, oy)) else { continue };
+ let (lo, hi) = (ix.0.max(iy.0), ix.1.min(iy.1));
+ if lo > hi {
+ continue;
+ }
+ let face = if hi >= 1.0 {
+ 0
+ } else if ix.1 < iy.1 {
+ // Left the square through an x side first.
+ if ox > 0.0 { 1 } else { 2 }
+ } else if oy > 0.0 {
+ 3
+ } else {
+ 4
+ };
+ best = Some((h, cx, cy, face));
+ }
+ }
+ let Some((h, cx, cy, face)) = best else { continue };
+ let r = cell_rect(cx, cy);
+ let (mx, my) = (r.x0 as f32 + cs as f32 / 2.0, r.y0 as f32 + cs as f32 / 2.0);
+ let off = reach * h / half_diag;
+ let col = info(cx, cy).0;
+ if face == 0 {
+ if spec.solid_front {
+ shade(px, &col, 1.0);
+ } else {
+ // Image texture shifted with the face.
+ let (sx, sy) = ((fx - (mx - bcx) * off).floor() as i32, (fy - (my - bcy) * off).floor() as i32);
+ let (sx, sy) = (sx.clamp(r.x0, r.x1 - 1), sy.clamp(r.y0, r.y1 - 1));
+ for (c, v) in px.iter_mut().enumerate() {
+ *v = src.get(sx, sy, c);
+ }
+ }
+ } else {
+ // Light from the top-left: the left/top sides are lit.
+ let k = match face {
+ 1 => 0.85, // left side (block shifted right)
+ 2 => 0.55, // right side
+ 3 => 0.95, // top side
+ _ => 0.45, // bottom side
+ };
+ shade(px, &col, k);
+ }
+ }
+ }
+ }
+ res
+}
+
+/// Tiles: the bounds are cut into square tiles (`count` along the shorter
+/// side), each shifted randomly by up to `max_offset` % of its size; later
+/// tiles overlap earlier ones and gaps get the chosen fill.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn tiles(src: &Image, out: Rect, ctx: &Ctx, count: u32, max_offset: f32, fill: TileFill, colours: ([f32; 4], [f32; 4]), seed: u32) -> Vec<f32> {
+ let n = src.ch;
+ let b = ctx.bounds;
+ let ts = (b.width().min(b.height()) as f32 / count.clamp(1, 99) as f32).max(1.0);
+ let m = max_offset.clamp(0.0, 99.0) / 100.0 * ts;
+ let fg = native(ctx, colours.0);
+ let bg = native(ctx, colours.1);
+ let cc = ncol(ctx, n);
+ let mut res = src.crop(out);
+ let w = out.width() as usize;
+ let offset = |gx: i32, gy: i32| ((hash01(gx, gy, 31, seed) * 2.0 - 1.0) * m, (hash01(gx, gy, 32, seed) * 2.0 - 1.0) * m);
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = (out.x0 + (i % w) as i32, out.y0 + (i / w) as i32);
+ if !b.contains(x, y) {
+ continue;
+ }
+ let (fx, fy) = (x as f32 + 0.5 - b.x0 as f32, y as f32 + 0.5 - b.y0 as f32);
+ let (gx, gy) = ((fx / ts).floor() as i32, (fy / ts).floor() as i32);
+ // Topmost tile (drawn last = highest row-major index) covering the pixel.
+ let mut hit = None;
+ for dy in -1..=1 {
+ for dx in -1..=1 {
+ let (cx, cy) = (gx + dx, gy + dy);
+ let (ox, oy) = offset(cx, cy);
+ let (u, v) = (fx - ox - cx as f32 * ts, fy - oy - cy as f32 * ts);
+ if u >= 0.0 && v >= 0.0 && u < ts && v < ts && (cx as f32 * ts) < b.width() as f32 && (cy as f32 * ts) < b.height() as f32 && cx >= 0 && cy >= 0 {
+ let order = (cy, cx);
+ if hit.is_none_or(|(o, _, _)| order > o) {
+ hit = Some((order, ox, oy));
+ }
+ }
+ }
+ }
+ match hit {
+ Some((_, ox, oy)) => {
+ let (sx, sy) = ((x as f32 + 0.5 - ox).floor() as i32, (y as f32 + 0.5 - oy).floor() as i32);
+ let (sx, sy) = (sx.clamp(b.x0, b.x1 - 1), sy.clamp(b.y0, b.y1 - 1));
+ for (c, v) in px.iter_mut().enumerate() {
+ *v = src.get(sx, sy, c);
+ }
+ }
+ None => match fill {
+ TileFill::Background => px.copy_from_slice(&bg[..n]),
+ TileFill::Foreground => px.copy_from_slice(&fg[..n]),
+ TileFill::Inverse => {
+ for v in px.iter_mut().take(cc) {
+ *v = 1.0 - *v;
+ }
+ }
+ TileFill::Unaltered => {}
+ },
+ }
+ }
+ res
+}
+
+/// Trace Contour: per channel, outlines where values cross `level` (0–255)
+/// with a 1 px line (dark in additive models) on a white canvas.
+pub(crate) fn trace_contour(src: &Image, out: Rect, ctx: &Ctx, level: f32, upper: bool) -> Vec<f32> {
+ let n = src.ch;
+ let cc = ncol(ctx, n);
+ let sub = subtractive(ctx);
+ let t = level.clamp(0.0, 255.0) / 255.0;
+ let bright = |x: i32, y: i32, c: usize| {
+ let v = src.get_edge(x, y, c, crate::image::Edge::Repeat, ctx.bounds.intersect(&src.rect));
+ if sub { 1.0 - v } else { v }
+ };
+ let mut res = src.crop(out);
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ for (c, v) in px.iter_mut().enumerate().take(cc) {
+ let me = bright(x, y, c) > t;
+ let line = me == upper && [(1, 0), (-1, 0), (0, 1), (0, -1)].iter().any(|(dx, dy)| (bright(x + dx, y + dy, c) > t) != me);
+ let paper = if line { 0.0 } else { 1.0 };
+ *v = if sub { 1.0 - paper } else { paper };
+ }
+ }
+ res
+}
+
+/// Longest streak (or stagger shift) of a Wind method, px.
+pub(crate) fn wind_reach(method: WindMethod) -> f32 {
+ match method {
+ WindMethod::Wind => 16.0,
+ WindMethod::Blast => 40.0,
+ WindMethod::Stagger => 12.0,
+ }
+}
+
+/// Wind: streaks trail downwind from edges (Blast: longer and denser);
+/// Stagger shifts random row segments along the wind.
+pub(crate) fn wind(src: &Image, out: Rect, ctx: &Ctx, method: WindMethod, from_right: bool, seed: u32) -> Vec<f32> {
+ let n = src.ch;
+ let lmax = wind_reach(method) as i32;
+ // Streaks move downwind: from the left they extend to the right (+x).
+ let d = if from_right { -1 } else { 1 };
+ let mut res = src.crop(out);
+ let mut tmp = [0.0f32; MAXC];
+ let mut tmp2 = [0.0f32; MAXC];
+ let lum = |x: i32, y: i32, buf: &mut [f32; MAXC]| {
+ read_px(src, x, y, &mut buf[..n]);
+ luma(ctx, &buf[..n])
+ };
+ let w = out.width() as usize;
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = (out.x0 + (i % w) as i32, out.y0 + (i / w) as i32);
+ if method == WindMethod::Stagger {
+ // Rows split into segments of 8–40 px, each shifted downwind by 0–lmax px.
+ let seg_len = 8 + (hash01(0, y, 41, seed) * 32.0) as i32;
+ let phase = (hash01(1, y, 42, seed) * seg_len as f32) as i32;
+ let seg = (x * d + phase).div_euclid(seg_len);
+ let shift = (hash01(seg, y, 43, seed).powi(2) * lmax as f32) as i32;
+ read_px(src, x - d * shift, y, &mut tmp[..n]);
+ px.copy_from_slice(&tmp[..n]);
+ continue;
+ }
+ let strength = if method == WindMethod::Blast { 8.0 } else { 4.0 };
+ let mut best = (0.0f32, x);
+ for k in 1..=lmax {
+ let s = x - d * k;
+ // Each source pixel starts a streak of random length; only edges start visible ones.
+ let len = (hash01(s, y, 44, seed).powi(2) * lmax as f32).max(1.0);
+ if (k as f32) > len {
+ continue;
+ }
+ let edge = ((lum(s, y, &mut tmp) - lum(s - d, y, &mut tmp2)).abs() * strength).min(1.0);
+ let wgt = edge * (1.0 - k as f32 / (len + 1.0));
+ if wgt > best.0 {
+ best = (wgt, s);
+ }
+ }
+ if best.0 > 0.0 {
+ read_px(src, best.1, y, &mut tmp[..n]);
+ for c in 0..n {
+ px[c] += (tmp[c] - px[c]) * best.0;
+ }
+ }
+ }
+ res
+}
diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rs
index 389ef41a7..7a8871574 100644
--- a/crates/algo/src/tests.rs
+++ b/crates/algo/src/tests.rs
@@ -78,8 +78,8 @@ fn every_filter_is_tile_independent() {
let s = pattern(SampleType::U8, R);
for p in all_filters() {
let area = output_area(&p, s.content_bounds(), R, None);
- let a = apply_tiled(&s, &p, area, R, None, 256);
- let b = apply_tiled(&s, &p, area, R, None, 7);
+ let a = apply_tiled(&s, &p, area, R, None, 256, None);
+ let b = apply_tiled(&s, &p, area, R, None, 7, None);
let big = area.union(&R);
assert!(a.to_interleaved(big) == b.to_interleaved(big), "{} differs between tile sizes", p.label());
}
@@ -334,3 +334,24 @@ fn other_colour_modes_work() {
}
}
}
+
+#[test]
+fn layer_filters_repeat_the_canvas_edge() {
+ // A fully opaque layer covering the canvas stays opaque at the edge (no transparent fade-in)
+ // and doesn't grow past the canvas; without an extent, samples beyond the data are transparent.
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let canvas = Rect::new(0, 0, 40, 30);
+ let s = flat(depth, canvas, [0.2, 0.6, 0.4, 1.0]);
+ let p = FilterParams::GaussianBlur { radius: 6.0 };
+ let area = output_area(&p, s.content_bounds(), canvas, None);
+ let clamped = apply_in(&s, &p, area, canvas, None, canvas);
+ assert_eq!(clamped.content_bounds(), canvas, "{depth:?}: grew past the canvas");
+ for (x, y) in [(0, 0), (39, 0), (0, 29), (39, 29), (20, 0)] {
+ let px = clamped.pixel(x, y);
+ assert!((px[3] - 1.0).abs() < 1e-3, "{depth:?}: alpha faded at ({x},{y}): {}", px[3]);
+ assert!((px[1] - 0.6).abs() < 2e-3, "{depth:?}: colour changed at ({x},{y})");
+ }
+ let faded = apply(&s, &p, area, canvas, None);
+ assert!(faded.pixel(0, 0)[3] < 0.9, "{depth:?}: unclamped path should read transparency");
+ }
+}
diff --git a/crates/algo/src/tests_ext.rs b/crates/algo/src/tests_ext.rs
new file mode 100644
index 000000000..20ecc5fbf
--- /dev/null
+++ b/crates/algo/src/tests_ext.rs
@@ -0,0 +1,599 @@
+//! Tests for the second filter batch (pixelate, stylize, render, blur gallery, video…).
+
+use super::*;
+use photocraft_color::{PixelFormat, SampleType};
+use std::sync::Arc;
+
+fn fmt(s: SampleType) -> PixelFormat {
+ PixelFormat::new(ColorMode::Rgb, s, true)
+}
+
+const R: Rect = Rect { x0: 0, y0: 0, x1: 40, y1: 30 };
+
+fn pattern(s: SampleType, r: Rect) -> Surface {
+ let mut surf = Surface::new(fmt(s));
+ let mut v = Vec::new();
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ v.extend_from_slice(&[((x * 7 + y * 3) % 64) as f32 / 63.0, ((x * x + y) % 50) as f32 / 49.0, (y % 9) as f32 / 8.0, 1.0]);
+ }
+ }
+ surf.write_region(r, &v);
+ surf
+}
+
+fn flat(s: SampleType, r: Rect, px: [f32; 4]) -> Surface {
+ let mut surf = Surface::new(fmt(s));
+ surf.fill_rect(r, &px);
+ surf
+}
+
+fn run(s: &Surface, p: &FilterParams) -> Surface {
+ let area = output_area(p, s.content_bounds(), R, None);
+ apply(s, p, area, R, None)
+}
+
+fn map_image(v: [f32; 4]) -> Arc<Image> {
+ let r = Rect::new(0, 0, 8, 8);
+ Arc::new(Image { rect: r, ch: 4, data: (0..64).flat_map(|_| v).collect() })
+}
+
+const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
+const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
+
+fn new_filters() -> Vec<FilterParams> {
+ vec![
+ FilterParams::ColorHalftone { max_radius: 4.0, angles: [108.0, 162.0, 90.0, 45.0] },
+ FilterParams::Crystallize { cell_size: 6.0, seed: 1 },
+ FilterParams::Facet,
+ FilterParams::Fragment,
+ FilterParams::Mezzotint { kind: MezzotintType::MediumLines, seed: 2 },
+ FilterParams::Mezzotint { kind: MezzotintType::GrainyDots, seed: 2 },
+ FilterParams::Pointillize { cell_size: 5.0, seed: 3, background: WHITE },
+ FilterParams::Diffuse { mode: DiffuseMode::Normal, seed: 4 },
+ FilterParams::Diffuse { mode: DiffuseMode::Anisotropic, seed: 4 },
+ FilterParams::Extrude { kind: ExtrudeType::Blocks, size: 6.0, depth: 20.0, level_based: false, solid_front: false, mask_incomplete: false, seed: 5 },
+ FilterParams::Extrude { kind: ExtrudeType::Pyramids, size: 6.0, depth: 30.0, level_based: true, solid_front: false, mask_incomplete: true, seed: 5 },
+ FilterParams::OilPaint { stylization: 3.0, cleanliness: 4.0, scale: 1.0, bristle_detail: 5.0, lighting: true, angle: -60.0, shine: 2.0 },
+ FilterParams::Tiles { count: 4, max_offset: 20.0, fill: TileFill::Background, foreground: BLACK, background: WHITE, seed: 6 },
+ FilterParams::TraceContour { level: 128.0, upper: true },
+ FilterParams::Wind { method: WindMethod::Blast, from_right: false, seed: 7 },
+ FilterParams::Wind { method: WindMethod::Stagger, from_right: true, seed: 7 },
+ FilterParams::Displace { horizontal: 10.0, vertical: 10.0, stretch: true, undefined: UndefinedAreas::Wrap, map: Some(map_image([0.8, 0.3, 0.5, 1.0])) },
+ FilterParams::Shear { points: vec![[0.0, 0.0], [0.5, 0.3], [1.0, 0.0]], undefined: UndefinedAreas::Repeat },
+ FilterParams::ZigZag { amount: 50.0, ridges: 4.0, style: ZigZagStyle::PondRipples },
+ FilterParams::Fibers { variance: 16.0, strength: 4.0, seed: 8, foreground: BLACK, background: WHITE },
+ FilterParams::LensFlare { brightness: 100.0, center_x: 0.3, center_y: 0.3, lens: LensType::Zoom },
+ FilterParams::LightingEffects { lights: vec![Light::default()], gloss: 0.0, metallic: 0.0, exposure: 0.0, ambience: 10.0, texture: TextureChannel::Luminance, height: 50.0, white_is_high: true },
+ FilterParams::ReduceNoise { strength: 6.0, preserve_details: 60.0, reduce_color_noise: 45.0, sharpen_details: 25.0, remove_jpeg_artifact: true },
+ FilterParams::SmartBlur { radius: 3.0, threshold: 40.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal },
+ FilterParams::SmartBlur { radius: 3.0, threshold: 25.0, quality: BlurQuality::Low, mode: SmartBlurMode::OverlayEdge },
+ FilterParams::LensBlur {
+ radius: 4.0,
+ blades: 6,
+ curvature: 20.0,
+ rotation: 10.0,
+ depth: DepthSource::None,
+ focal_distance: 0.0,
+ invert_depth: false,
+ brightness: 30.0,
+ threshold: 200.0,
+ noise: 5.0,
+ distribution: Distribution::Uniform,
+ monochromatic: false,
+ seed: 9,
+ depth_map: None,
+ },
+ FilterParams::ShapeBlur { radius: 3.0, shape: BlurShape::Star },
+ FilterParams::TiltShift { blur: 6.0, center_x: 0.5, center_y: 0.5, angle: 0.0, focus: 0.1, transition: 0.2 },
+ FilterParams::IrisBlur { pins: vec![IrisPin { blur: 6.0, ..IrisPin::default() }] },
+ FilterParams::FieldBlur { pins: vec![FieldPin { x: 0.2, y: 0.2, blur: 0.0 }, FieldPin { x: 0.8, y: 0.8, blur: 6.0 }] },
+ FilterParams::SpinBlur { pins: vec![SpinPin { blur_angle: 30.0, ..SpinPin::default() }] },
+ FilterParams::PathBlur { paths: vec![BlurPath { points: vec![[0.1, 0.2], [0.9, 0.8]], speed: 8.0, taper: 30.0 }] },
+ FilterParams::Custom { kernel: vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, -1.0, 5.0, -1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], scale: 1.0, offset: 0.0 },
+ FilterParams::HsbHsl { input: HsbModel::Rgb, output: HsbModel::Hsl },
+ FilterParams::DeInterlace { eliminate_even: false, interpolate: true },
+ FilterParams::NtscColors,
+ ]
+}
+
+fn max_diff(a: &[f32], b: &[f32]) -> f32 {
+ a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max)
+}
+
+fn mean_diff(a: &[f32], b: &[f32]) -> f32 {
+ a.iter().zip(b).map(|(x, y)| (x - y).abs()).sum::<f32>() / a.len().max(1) as f32
+}
+
+#[test]
+fn new_filters_are_tile_independent() {
+ let s = pattern(SampleType::U8, R);
+ for p in new_filters() {
+ let area = output_area(&p, s.content_bounds(), R, None);
+ let a = apply_tiled(&s, &p, area, R, None, 256, None);
+ let b = apply_tiled(&s, &p, area, R, None, 7, None);
+ let big = area.union(&R);
+ // Running-sum blurs may round differently by one level depending on where a window starts.
+ let d = max_diff(&a.read_region(big), &b.read_region(big));
+ assert!(d <= 1.5 / 255.0, "{} differs between tile sizes by {d}", p.label());
+ }
+}
+
+#[test]
+fn new_filters_change_pixels_and_respect_empty_selection() {
+ let s = pattern(SampleType::U16, R);
+ let none = Surface::new(PixelFormat::GRAY8);
+ for p in new_filters() {
+ let out = run(&s, &p);
+ assert!(out != s, "{} did nothing", p.label());
+ let area = output_area(&p, s.content_bounds(), R, None);
+ let masked = apply(&s, &p, area, R, Some(&none));
+ assert_eq!(masked.read_region(area), s.read_region(area), "{} ignored an empty selection", p.label());
+ }
+}
+
+#[test]
+fn new_filters_agree_across_bit_depths() {
+ // Threshold-type filters flip where quantized inputs straddle a threshold; compare them on average only.
+ let thresholdy = |p: &FilterParams| {
+ matches!(p, FilterParams::Facet | FilterParams::OilPaint { .. } | FilterParams::Mezzotint { .. } | FilterParams::TraceContour { .. } | FilterParams::SmartBlur { .. } | FilterParams::ColorHalftone { .. } | FilterParams::Diffuse { .. } | FilterParams::Wind { .. })
+ || matches!(p, FilterParams::Extrude { level_based: true, .. })
+ };
+ for p in new_filters() {
+ let outs: Vec<Vec<f32>> = [SampleType::U8, SampleType::U16, SampleType::F32]
+ .iter()
+ .map(|&st| {
+ let s = pattern(st, R);
+ // Clamp float results the way integer storage does, so HDR overshoot does not count.
+ run(&s, &p).read_region(R).into_iter().map(|v| v.clamp(0.0, 1.0)).collect()
+ })
+ .collect();
+ for k in 1..3 {
+ let (mx, mn) = (max_diff(&outs[0], &outs[k]), mean_diff(&outs[0], &outs[k]));
+ if thresholdy(&p) {
+ assert!(mn < 0.06, "{}: mean depth difference {mn}", p.label());
+ } else {
+ assert!(mx < 0.06 && mn < 0.01, "{}: depth difference max {mx} mean {mn}", p.label());
+ }
+ }
+ }
+}
+
+#[test]
+fn new_filters_work_in_other_colour_modes() {
+ for mode in [ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
+ let f = PixelFormat::new(mode, SampleType::U8, true);
+ let mut s = Surface::new(f);
+ let src = pattern(SampleType::F32, R);
+ for y in R.y0..R.y1 {
+ for x in R.x0..R.x1 {
+ let px = photocraft_raster::from_rgba(&f, photocraft_raster::to_rgba(&src.format(), &src.pixel(x, y)));
+ s.write_pixel(x, y, &px);
+ }
+ }
+ for p in new_filters() {
+ let out = run(&s, &p);
+ assert_eq!(out.format(), f);
+ assert!(out.read_region(R).iter().all(|v| v.is_finite()), "{} {mode:?}", p.label());
+ }
+ }
+}
+
+#[test]
+fn new_params_serde_roundtrip() {
+ for p in new_filters() {
+ let j = serde_json::to_string(&p).unwrap();
+ let back: FilterParams = serde_json::from_str(&j).unwrap();
+ // Caller-supplied maps are not serialized.
+ let strip = |p: &FilterParams| match p.clone() {
+ FilterParams::Displace { horizontal, vertical, stretch, undefined, .. } => FilterParams::Displace { horizontal, vertical, stretch, undefined, map: None },
+ other => other,
+ };
+ assert_eq!(back, strip(&p), "{j}");
+ }
+}
+
+#[test]
+fn identities_at_zero_strength() {
+ let s = pattern(SampleType::U8, R);
+ let cases = vec![
+ FilterParams::Displace { horizontal: 0.0, vertical: 0.0, stretch: true, undefined: UndefinedAreas::Wrap, map: Some(map_image([0.9, 0.1, 0.0, 1.0])) },
+ FilterParams::Displace { horizontal: 50.0, vertical: 50.0, stretch: true, undefined: UndefinedAreas::Wrap, map: None },
+ FilterParams::Shear { points: vec![[0.0, 0.0], [1.0, 0.0]], undefined: UndefinedAreas::Wrap },
+ FilterParams::ZigZag { amount: 0.0, ridges: 5.0, style: ZigZagStyle::AroundCenter },
+ FilterParams::Custom { kernel: (0..25).map(|i| if i == 12 { 1.0 } else { 0.0 }).collect(), scale: 1.0, offset: 0.0 },
+ FilterParams::HsbHsl { input: HsbModel::Hsb, output: HsbModel::Hsb },
+ FilterParams::ReduceNoise { strength: 0.0, preserve_details: 60.0, reduce_color_noise: 0.0, sharpen_details: 0.0, remove_jpeg_artifact: false },
+ FilterParams::LensBlur {
+ radius: 0.0,
+ blades: 6,
+ curvature: 0.0,
+ rotation: 0.0,
+ depth: DepthSource::None,
+ focal_distance: 0.0,
+ invert_depth: false,
+ brightness: 0.0,
+ threshold: 255.0,
+ noise: 0.0,
+ distribution: Distribution::Uniform,
+ monochromatic: false,
+ seed: 0,
+ depth_map: None,
+ },
+ FilterParams::ShapeBlur { radius: 0.0, shape: BlurShape::Heart },
+ FilterParams::TiltShift { blur: 0.0, center_x: 0.5, center_y: 0.5, angle: 30.0, focus: 0.1, transition: 0.2 },
+ FilterParams::IrisBlur { pins: vec![IrisPin { blur: 0.0, ..IrisPin::default() }] },
+ FilterParams::FieldBlur { pins: vec![FieldPin { blur: 0.0, ..FieldPin::default() }] },
+ FilterParams::SpinBlur { pins: vec![SpinPin { blur_angle: 0.0, ..SpinPin::default() }] },
+ FilterParams::PathBlur { paths: vec![BlurPath { speed: 0.0, ..BlurPath::default() }] },
+ ];
+ for p in cases {
+ let out = run(&s, &p);
+ let d = max_diff(&out.read_region(R), &s.read_region(R));
+ assert!(d <= 0.5 / 255.0, "{} is not identity ({d})", p.label());
+ }
+}
+
+#[test]
+fn flat_images_stay_flat() {
+ let c = [0.3, 0.55, 0.8, 1.0];
+ let s = flat(SampleType::F32, R, c);
+ for p in [
+ FilterParams::Crystallize { cell_size: 6.0, seed: 1 },
+ FilterParams::Facet,
+ FilterParams::OilPaint { stylization: 3.0, cleanliness: 4.0, scale: 1.0, bristle_detail: 0.0, lighting: true, angle: -60.0, shine: 2.0 },
+ FilterParams::ReduceNoise { strength: 10.0, preserve_details: 0.0, reduce_color_noise: 100.0, sharpen_details: 0.0, remove_jpeg_artifact: false },
+ FilterParams::SmartBlur { radius: 3.0, threshold: 25.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal },
+ FilterParams::LensBlur {
+ radius: 5.0,
+ blades: 5,
+ curvature: 50.0,
+ rotation: 0.0,
+ depth: DepthSource::None,
+ focal_distance: 0.0,
+ invert_depth: false,
+ brightness: 0.0,
+ threshold: 255.0,
+ noise: 0.0,
+ distribution: Distribution::Uniform,
+ monochromatic: false,
+ seed: 0,
+ depth_map: None,
+ },
+ FilterParams::ShapeBlur { radius: 4.0, shape: BlurShape::Ring },
+ FilterParams::TiltShift { blur: 5.0, center_x: 0.5, center_y: 0.5, angle: 0.0, focus: 0.0, transition: 0.1 },
+ FilterParams::Wind { method: WindMethod::Blast, from_right: false, seed: 0 },
+ FilterParams::DeInterlace { eliminate_even: true, interpolate: true },
+ ] {
+ let out = run(&s, &p);
+ let px = out.pixel(20, 15);
+ for k in 0..4 {
+ assert!((px[k] - c[k]).abs() < 2e-3, "{}: {px:?}", p.label());
+ }
+ }
+}
+
+#[test]
+fn mezzotint_is_binary_and_tracks_brightness() {
+ let s = flat(SampleType::F32, R, [0.25, 0.5, 0.75, 1.0]);
+ let out = run(&s, &FilterParams::Mezzotint { kind: MezzotintType::FineDots, seed: 1 });
+ let v = out.read_region(R);
+ let mut mean = [0.0f32; 3];
+ for px in v.chunks_exact(4) {
+ for k in 0..3 {
+ assert!(px[k] == 0.0 || px[k] == 1.0);
+ mean[k] += px[k] / 1200.0;
+ }
+ }
+ assert!((mean[0] - 0.25).abs() < 0.06 && (mean[1] - 0.5).abs() < 0.06 && (mean[2] - 0.75).abs() < 0.06, "{mean:?}");
+}
+
+#[test]
+fn halftone_covers_by_ink() {
+ let angles = [108.0, 162.0, 90.0, 45.0];
+ let w = run(&flat(SampleType::F32, R, WHITE), &FilterParams::ColorHalftone { max_radius: 4.0, angles });
+ assert!(w.read_region(R).iter().all(|&v| (v - 1.0).abs() < 1e-6), "white paper stays white");
+ let b = run(&flat(SampleType::F32, R, BLACK), &FilterParams::ColorHalftone { max_radius: 4.0, angles });
+ let mean_b: f32 = b.read_region(R).chunks_exact(4).map(|p| p[0]).sum::<f32>() / 1200.0;
+ assert!(mean_b < 0.05, "black is fully inked: {mean_b}");
+ let g = run(&flat(SampleType::F32, R, [0.5, 0.5, 0.5, 1.0]), &FilterParams::ColorHalftone { max_radius: 4.0, angles });
+ let mean_g: f32 = g.read_region(R).chunks_exact(4).map(|p| p[1]).sum::<f32>() / 1200.0;
+ assert!((mean_g - 0.5).abs() < 0.12, "mid gray ≈ half coverage: {mean_g}");
+}
+
+#[test]
+fn pointillize_shows_canvas() {
+ let s = flat(SampleType::F32, R, [0.0, 0.0, 1.0, 1.0]);
+ let out = run(&s, &FilterParams::Pointillize { cell_size: 10.0, seed: 3, background: [1.0, 0.0, 0.0, 1.0] });
+ let v = out.read_region(R);
+ assert!(v.chunks_exact(4).any(|p| p[0] > 0.99 && p[2] < 0.01), "canvas visible between dots");
+ assert!(v.chunks_exact(4).any(|p| p[2] > 0.9), "dots take the image colour");
+}
+
+#[test]
+fn diffuse_only_moves_pixels_locally() {
+ let s = pattern(SampleType::F32, R);
+ let out = run(&s, &FilterParams::Diffuse { mode: DiffuseMode::Normal, seed: 1 });
+ for y in 1..29 {
+ for x in 1..39 {
+ let p = out.pixel(x, y);
+ let found = (-1..=1).any(|dy| (-1..=1).any(|dx| s.pixel(x + dx, y + dy) == p));
+ assert!(found, "({x},{y})");
+ }
+ }
+ let dark = run(&s, &FilterParams::Diffuse { mode: DiffuseMode::DarkenOnly, seed: 1 });
+ let l = |p: Vec<f32>| 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2];
+ for y in 1..29 {
+ for x in 1..39 {
+ assert!(l(dark.pixel(x, y)) <= l(s.pixel(x, y)) + 1e-6);
+ }
+ }
+}
+
+#[test]
+fn trace_contour_draws_line_at_level_crossing() {
+ let mut s = flat(SampleType::F32, R, [0.2, 0.2, 0.2, 1.0]);
+ s.fill_rect(Rect::new(20, 0, 40, 30), &[0.8, 0.8, 0.8, 1.0]);
+ let up = run(&s, &FilterParams::TraceContour { level: 128.0, upper: true });
+ assert_eq!(up.pixel(20, 10)[0], 0.0, "line on the bright side");
+ assert_eq!(up.pixel(19, 10)[0], 1.0);
+ assert_eq!(up.pixel(30, 10)[0], 1.0);
+ let lo = run(&s, &FilterParams::TraceContour { level: 128.0, upper: false });
+ assert_eq!(lo.pixel(19, 10)[0], 0.0, "line on the dark side");
+}
+
+#[test]
+fn tiles_leave_gaps_with_fill() {
+ let s = flat(SampleType::F32, R, [0.0, 0.0, 1.0, 1.0]);
+ let out = run(&s, &FilterParams::Tiles { count: 3, max_offset: 40.0, fill: TileFill::Foreground, foreground: [0.0, 1.0, 0.0, 1.0], background: WHITE, seed: 2 });
+ let v = out.read_region(R);
+ assert!(v.chunks_exact(4).any(|p| p[1] > 0.99), "foreground gaps");
+ assert!(v.chunks_exact(4).filter(|p| p[2] > 0.99).count() > 600, "mostly tiles");
+}
+
+#[test]
+fn extrude_blocks_and_pyramids_shade_cells() {
+ let s = pattern(SampleType::F32, R);
+ let blocks = run(&s, &FilterParams::Extrude { kind: ExtrudeType::Blocks, size: 8.0, depth: 40.0, level_based: false, solid_front: true, mask_incomplete: false, seed: 1 });
+ // A solid front face is uniform: find two equal neighbours somewhere in the middle.
+ let same = (5..35).any(|x| blocks.pixel(x, 12) == blocks.pixel(x + 1, 12));
+ assert!(same);
+ let flat_s = flat(SampleType::F32, R, [0.5, 0.5, 0.5, 1.0]);
+ let pyr = run(&flat_s, &FilterParams::Extrude { kind: ExtrudeType::Pyramids, size: 10.0, depth: 100.0, level_based: false, solid_front: false, mask_incomplete: false, seed: 1 });
+ // Light from the top-left: the left face is brighter than the right face.
+ assert!(pyr.pixel(11, 15)[0] > pyr.pixel(18, 15)[0], "{:?} {:?}", pyr.pixel(11, 15), pyr.pixel(18, 15));
+}
+
+#[test]
+fn fibers_lie_between_colours_and_are_seeded() {
+ let s = flat(SampleType::F32, R, WHITE);
+ let p = FilterParams::Fibers { variance: 16.0, strength: 4.0, seed: 1, foreground: [1.0, 0.0, 0.0, 1.0], background: [0.0, 0.0, 1.0, 1.0] };
+ let a = run(&s, &p);
+ assert_eq!(a, run(&s, &p));
+ for px in a.read_region(R).chunks_exact(4) {
+ assert!((px[0] + px[2] - 1.0).abs() < 1e-5 && px[1].abs() < 1e-6);
+ }
+ let b = run(&s, &FilterParams::Fibers { variance: 16.0, strength: 4.0, seed: 2, foreground: [1.0, 0.0, 0.0, 1.0], background: [0.0, 0.0, 1.0, 1.0] });
+ assert_ne!(a, b);
+}
+
+#[test]
+fn lens_flare_is_brightest_at_its_centre() {
+ let s = flat(SampleType::F32, R, [0.2, 0.2, 0.2, 1.0]);
+ let out = run(&s, &FilterParams::LensFlare { brightness: 100.0, center_x: 0.25, center_y: 0.5, lens: LensType::Prime105 });
+ assert!(out.pixel(10, 15)[0] > 0.9);
+ assert!(out.pixel(10, 15)[0] > out.pixel(38, 2)[0]);
+ assert!(out.pixel(38, 2)[0] >= 0.2 - 1e-6, "screen never darkens");
+}
+
+#[test]
+fn lighting_point_light_falls_off() {
+ let s = flat(SampleType::F32, R, [0.8, 0.8, 0.8, 1.0]);
+ let light = Light { kind: LightKind::Point, x: 0.1, y: 0.5, z: 0.2, radius: 1.0, intensity: 50.0, ..Light::default() };
+ let out = run(&s, &FilterParams::LightingEffects { lights: vec![light], gloss: -100.0, metallic: 0.0, exposure: 0.0, ambience: 0.0, texture: TextureChannel::None, height: 0.0, white_is_high: true });
+ assert!(out.pixel(4, 15)[0] > out.pixel(36, 15)[0] + 0.1, "{:?} {:?}", out.pixel(4, 15), out.pixel(36, 15));
+ // A spot light does not reach outside its cone.
+ let spot = Light { kind: LightKind::Spot, x: 0.5, y: 0.5, z: 0.3, target_x: 0.5, target_y: 0.5, cone: 20.0, ..Light::default() };
+ let out = run(&s, &FilterParams::LightingEffects { lights: vec![spot], gloss: 0.0, metallic: 0.0, exposure: 0.0, ambience: 0.0, texture: TextureChannel::None, height: 0.0, white_is_high: true });
+ assert!(out.pixel(20, 15)[0] > 0.3 && out.pixel(1, 1)[0] < 1e-4, "{:?} {:?}", out.pixel(20, 15), out.pixel(1, 1));
+}
+
+fn variance(s: &Surface, r: Rect, c: usize) -> f32 {
+ let v: Vec<f32> = s.read_region(r).chunks_exact(4).map(|p| p[c]).collect();
+ let m = v.iter().sum::<f32>() / v.len() as f32;
+ v.iter().map(|x| (x - m).powi(2)).sum::<f32>() / v.len() as f32
+}
+
+fn noisy(st: SampleType) -> Surface {
+ let s = flat(st, R, [0.5, 0.5, 0.5, 1.0]);
+ run(&s, &FilterParams::AddNoise { amount: 20.0, distribution: Distribution::Gaussian, monochromatic: false, seed: 4 })
+}
+
+#[test]
+fn reduce_noise_lowers_noise() {
+ let s = noisy(SampleType::F32);
+ let inner = Rect::new(8, 8, 32, 22);
+ let out = run(&s, &FilterParams::ReduceNoise { strength: 10.0, preserve_details: 0.0, reduce_color_noise: 100.0, sharpen_details: 0.0, remove_jpeg_artifact: false });
+ for c in 0..3 {
+ assert!(variance(&out, inner, c) < variance(&s, inner, c) * 0.5, "channel {c}");
+ }
+}
+
+#[test]
+fn smart_blur_keeps_edges_and_smooths_noise() {
+ let mut s = noisy(SampleType::F32);
+ s.fill_rect(Rect::new(20, 0, 40, 30), &[1.0, 1.0, 1.0, 1.0]);
+ let out = run(&s, &FilterParams::SmartBlur { radius: 3.0, threshold: 60.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal });
+ assert!((out.pixel(20, 15)[0] - 1.0).abs() < 1e-5 && out.pixel(19, 15)[0] < 0.8, "edge kept");
+ assert!(variance(&out, Rect::new(4, 4, 16, 26), 0) < variance(&s, Rect::new(4, 4, 16, 26), 0));
+ let edges = run(&s, &FilterParams::SmartBlur { radius: 3.0, threshold: 60.0, quality: BlurQuality::High, mode: SmartBlurMode::EdgeOnly });
+ assert_eq!(edges.pixel(20, 15)[0], 1.0);
+ assert_eq!(edges.pixel(30, 15)[0], 0.0);
+}
+
+#[test]
+fn shaped_blurs_spread_a_point_into_the_shape() {
+ let mut s = Surface::new(fmt(SampleType::F32));
+ s.fill_rect(R, &BLACK);
+ s.write_pixel(20, 15, &WHITE);
+ let ring = run(&s, &FilterParams::ShapeBlur { radius: 6.0, shape: BlurShape::Ring });
+ assert_eq!(ring.pixel(20, 15)[0], 0.0, "ring has a hole");
+ assert!(ring.pixel(25, 15)[0] > 0.0);
+ let lb = run(
+ &s,
+ &FilterParams::LensBlur {
+ radius: 6.0,
+ blades: 3,
+ curvature: 0.0,
+ rotation: 0.0,
+ depth: DepthSource::None,
+ focal_distance: 0.0,
+ invert_depth: false,
+ brightness: 100.0,
+ threshold: 200.0,
+ noise: 0.0,
+ distribution: Distribution::Uniform,
+ monochromatic: false,
+ seed: 0,
+ depth_map: None,
+ },
+ );
+ // A triangle iris pointing up: the bokeh reaches farther below the point than above it... and specular boost brightens.
+ let sum: f32 = lb.read_region(R).chunks_exact(4).map(|p| p[0]).sum();
+ assert!(sum > 1.5, "highlight bloomed: {sum}");
+ assert!(lb.pixel(20, 15 + 5)[0] != lb.pixel(20, 15 - 5)[0], "triangular, not circular");
+}
+
+#[test]
+fn lens_blur_depth_map_keeps_focal_plane_sharp() {
+ let s = pattern(SampleType::F32, R);
+ // Depth: left half 0 (in focus at focal 0), right half 1.
+ let mut d = Image::new(R, 1);
+ for y in 0..30 {
+ for x in 20..40 {
+ d.data[(y * 40 + x) as usize] = 1.0;
+ }
+ }
+ let p = FilterParams::LensBlur {
+ radius: 5.0,
+ blades: 6,
+ curvature: 100.0,
+ rotation: 0.0,
+ depth: DepthSource::LayerMask,
+ focal_distance: 0.0,
+ invert_depth: false,
+ brightness: 0.0,
+ threshold: 255.0,
+ noise: 0.0,
+ distribution: Distribution::Uniform,
+ monochromatic: false,
+ seed: 0,
+ depth_map: Some(Arc::new(d)),
+ };
+ let out = run(&s, &p);
+ assert_eq!(out.pixel(5, 10), s.pixel(5, 10), "focal plane untouched");
+ assert_ne!(out.pixel(30, 10), s.pixel(30, 10), "far plane blurred");
+}
+
+#[test]
+fn gallery_blurs_follow_their_geometry() {
+ let s = pattern(SampleType::F32, R);
+ let ts = run(&s, &FilterParams::TiltShift { blur: 6.0, center_x: 0.5, center_y: 0.5, angle: 0.0, focus: 0.1, transition: 0.2 });
+ assert_eq!(ts.pixel(10, 15), s.pixel(10, 15), "band centre sharp");
+ assert_ne!(ts.pixel(10, 1), s.pixel(10, 1), "far rows blurred");
+ let ir = run(&s, &FilterParams::IrisBlur { pins: vec![IrisPin { blur: 6.0, radius_x: 0.3, radius_y: 0.3, ..IrisPin::default() }] });
+ assert_eq!(ir.pixel(20, 15), s.pixel(20, 15));
+ assert_ne!(ir.pixel(1, 1), s.pixel(1, 1));
+ let sp = run(&s, &FilterParams::SpinBlur { pins: vec![SpinPin { radius_x: 0.3, radius_y: 0.3, blur_angle: 40.0, ..SpinPin::default() }] });
+ assert_eq!(sp.pixel(1, 1), s.pixel(1, 1), "outside the spin ellipse");
+ assert_ne!(sp.pixel(24, 15), s.pixel(24, 15));
+ // Horizontal path: vertical stripes get blurred, horizontal ones survive.
+ let mut stripes = Surface::new(fmt(SampleType::F32));
+ for y in 0..30 {
+ for x in 0..40 {
+ let v = if y % 2 == 0 { 1.0 } else { 0.0 };
+ stripes.write_pixel(x, y, &[v, v, v, 1.0]);
+ }
+ }
+ let pb = run(&stripes, &FilterParams::PathBlur { paths: vec![BlurPath { points: vec![[0.0, 0.5], [1.0, 0.5]], speed: 6.0, taper: 0.0 }] });
+ assert!((pb.pixel(20, 10)[0] - 1.0).abs() < 1e-5 && pb.pixel(20, 11)[0] < 1e-5);
+}
+
+#[test]
+fn custom_kernel_shifts_and_offsets() {
+ let s = pattern(SampleType::F32, R);
+ let mut k = vec![0.0; 25];
+ k[13] = 2.0; // right neighbour
+ let out = run(&s, &FilterParams::Custom { kernel: k, scale: 2.0, offset: 0.0 });
+ assert_eq!(out.pixel(10, 10)[0], s.pixel(11, 10)[0]);
+ let mut id = vec![0.0; 25];
+ id[12] = 1.0;
+ let off = run(&flat(SampleType::F32, R, [0.2, 0.2, 0.2, 1.0]), &FilterParams::Custom { kernel: id, scale: 1.0, offset: 51.0 });
+ assert!((off.pixel(5, 5)[0] - 0.4).abs() < 1e-5);
+}
+
+#[test]
+fn hsb_filter_encodes_and_decodes() {
+ let s = flat(SampleType::F32, R, [1.0, 0.0, 0.0, 1.0]);
+ let hsb = run(&s, &FilterParams::HsbHsl { input: HsbModel::Rgb, output: HsbModel::Hsb });
+ assert_eq!(hsb.pixel(3, 3), vec![0.0, 1.0, 1.0, 1.0]);
+ let back = run(&hsb, &FilterParams::HsbHsl { input: HsbModel::Hsb, output: HsbModel::Rgb });
+ assert_eq!(back.pixel(3, 3), s.pixel(3, 3));
+}
+
+#[test]
+fn deinterlace_rebuilds_a_field() {
+ let mut s = Surface::new(fmt(SampleType::F32));
+ for y in 0..30 {
+ let v = if y % 2 == 0 { 0.8 } else { 0.2 };
+ s.fill_rect(Rect::new(0, y, 40, y + 1), &[v, v, v, 1.0]);
+ }
+ // Eliminate odd lines (offsets 0, 2…): the kept 0.2 lines fill in.
+ let out = run(&s, &FilterParams::DeInterlace { eliminate_even: false, interpolate: false });
+ for y in 0..30 {
+ assert!((out.pixel(10, y)[0] - 0.2).abs() < 1e-6, "y={y}");
+ }
+ let even = run(&s, &FilterParams::DeInterlace { eliminate_even: true, interpolate: true });
+ assert!((even.pixel(10, 5)[0] - 0.8).abs() < 1e-6);
+}
+
+#[test]
+fn ntsc_limits_saturated_colours_only() {
+ let gray = flat(SampleType::F32, R, [0.5, 0.5, 0.5, 1.0]);
+ assert_eq!(run(&gray, &FilterParams::NtscColors).pixel(3, 3), gray.pixel(3, 3));
+ let yellow = flat(SampleType::F32, R, [1.0, 1.0, 0.0, 1.0]);
+ let y = run(&yellow, &FilterParams::NtscColors).pixel(3, 3);
+ assert!(y[2] > 0.05, "yellow desaturated: {y:?}");
+ let l = |p: &[f32]| 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2];
+ assert!((l(&y) - l(&[1.0, 1.0, 0.0])).abs() < 1e-3, "luma kept");
+}
+
+#[test]
+fn displace_shifts_by_map_and_shear_by_curve() {
+ let s = pattern(SampleType::F32, R);
+ let v = 0.5 + 3.0 / 64.0;
+ let out = run(&s, &FilterParams::Displace { horizontal: 25.0, vertical: 0.0, stretch: false, undefined: UndefinedAreas::Wrap, map: Some(map_image([v, 0.5, 0.5, 1.0])) });
+ for x in 0..30 {
+ assert_eq!(out.pixel(x, 7), s.pixel(x + 3, 7), "x={x}");
+ }
+ let sh = run(&s, &FilterParams::Shear { points: vec![[0.0, 0.1], [1.0, 0.1]], undefined: UndefinedAreas::Wrap });
+ assert_eq!(sh.pixel(10, 4), s.pixel(8, 4));
+}
+
+#[test]
+fn wind_streaks_downwind_from_edges() {
+ let mut s = flat(SampleType::F32, R, BLACK);
+ s.fill_rect(Rect::new(10, 0, 12, 30), &WHITE);
+ let right = run(&s, &FilterParams::Wind { method: WindMethod::Blast, from_right: false, seed: 1 });
+ let left_side: f32 = (0..30).map(|y| right.pixel(8, y)[0]).sum();
+ let right_side: f32 = (0..30).map(|y| right.pixel(14, y)[0]).sum();
+ assert!(right_side > left_side + 0.5, "{left_side} {right_side}");
+}
+
+#[test]
+fn oil_paint_smooths_along_strokes() {
+ let s = noisy(SampleType::F32);
+ let out = run(&s, &FilterParams::OilPaint { stylization: 5.0, cleanliness: 5.0, scale: 2.0, bristle_detail: 0.0, lighting: false, angle: 0.0, shine: 0.0 });
+ let inner = Rect::new(8, 8, 32, 22);
+ assert!(variance(&out, inner, 0) < variance(&s, inner, 0) * 0.5);
+}
diff --git a/crates/algo/src/tone.rs b/crates/algo/src/tone.rs
new file mode 100644
index 000000000..23166f350
--- /dev/null
+++ b/crates/algo/src/tone.rs
@@ -0,0 +1,552 @@
+//! Destructive tone and colour adjustments that need more than a per-pixel formula:
+//! Shadows/Highlights, Replace Color, Match Color and HDR Toning (Image › Adjustments).
+//!
+//! All work on straight (non-premultiplied) RGBA buffers in 0..=1, row-major `w × h`, so callers
+//! convert any colour model / bit depth to RGBA first (as `Image › Adjustments` does for the
+//! per-pixel adjustments). Formulas are documented approximations of Photoshop's behaviour,
+//! derived from its manual and observation, not from its implementation.
+
+use photocraft_color::convert::{lab_to_srgb, srgb_to_lab};
+use serde::{Deserialize, Serialize};
+
+use crate::fxutil::gauss_blur_n;
+use crate::other2::{hsl_to_rgb, rgb_to_hsl};
+
+fn luma(c: [f32; 3]) -> f32 {
+ 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]
+}
+
+fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
+ let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+/// Blurred luminance (Gaussian, `radius` px ≈ 2σ like Photoshop's radius fields).
+fn blurred_luma(px: &[[f32; 4]], w: usize, h: usize, radius: f32) -> Vec<f32> {
+ let mut l: Vec<f32> = px.iter().map(|p| luma([p[0], p[1], p[2]])).collect();
+ gauss_blur_n(&mut l, w, h, 1, radius.max(0.0) / 2.0);
+ l
+}
+
+/// Image › Adjustments › Shadows/Highlights parameters (Photoshop's dialog, percentages as 0..=100).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct ShadowsHighlights {
+ pub shadow_amount: f32,
+ pub shadow_tone: f32,
+ pub shadow_radius: f32,
+ pub highlight_amount: f32,
+ pub highlight_tone: f32,
+ pub highlight_radius: f32,
+ /// Colour (saturation) correction in -100..=100, applied where tones were changed.
+ pub color: f32,
+ /// Midtone contrast in -100..=100.
+ pub midtone: f32,
+ /// Percent of pixels clipped to black / white (0..=50).
+ pub black_clip: f32,
+ pub white_clip: f32,
+}
+
+impl Default for ShadowsHighlights {
+ fn default() -> Self {
+ ShadowsHighlights {
+ shadow_amount: 35.0,
+ shadow_tone: 50.0,
+ shadow_radius: 30.0,
+ highlight_amount: 0.0,
+ highlight_tone: 50.0,
+ highlight_radius: 30.0,
+ color: 20.0,
+ midtone: 0.0,
+ black_clip: 0.01,
+ white_clip: 0.01,
+ }
+ }
+}
+
+/// Local tone mapping: a blurred-luminance mask selects shadows (dark neighbourhoods, up to the
+/// tonal width) and highlights; shadows are lifted and highlights pulled down by a gain that
+/// preserves hue, then saturation is corrected where the gain moved tones, midtone contrast is
+/// applied, and the result is stretched by the clip percentages.
+pub fn shadows_highlights(px: &mut [[f32; 4]], w: usize, h: usize, p: &ShadowsHighlights) {
+ if px.is_empty() {
+ return;
+ }
+ let ls = blurred_luma(px, w, h, p.shadow_radius);
+ let lh = if (p.highlight_radius - p.shadow_radius).abs() < 1e-3 {
+ ls.clone()
+ } else {
+ blurred_luma(px, w, h, p.highlight_radius)
+ };
+ let (sa, ha) = (p.shadow_amount / 100.0, p.highlight_amount / 100.0);
+ let (st, ht) = (
+ (p.shadow_tone / 100.0).max(0.01),
+ (p.highlight_tone / 100.0).max(0.01),
+ );
+ let color = p.color / 100.0;
+ let mid = p.midtone / 100.0;
+ for (i, q) in px.iter_mut().enumerate() {
+ if q[3] <= 0.0 {
+ continue;
+ }
+ let c = [q[0], q[1], q[2]];
+ // Mask weights: 1 in deep shadows (resp. bright highlights), fading out at the tonal width.
+ let ms = 1.0 - smoothstep(0.0, st, ls[i]);
+ let mh = smoothstep(1.0 - ht, 1.0, lh[i]);
+ let mut out = c;
+ if sa > 0.0 && ms > 0.0 {
+ // Lift: a gamma-like curve on the pixel, stronger for darker neighbourhoods.
+ let g = 1.0 / (1.0 + 2.0 * sa * ms);
+ out = out.map(|v| v.max(0.0).powf(g));
+ }
+ if ha > 0.0 && mh > 0.0 {
+ let g = 1.0 / (1.0 + 2.0 * ha * mh);
+ out = out.map(|v| 1.0 - (1.0 - v.min(1.0)).powf(g));
+ }
+ if mid != 0.0 {
+ let k = 1.0 + mid * (1.0 - ms - mh).clamp(0.0, 1.0);
+ out = out.map(|v| (v - 0.5) * k + 0.5);
+ }
+ let changed = (ms * sa + mh * ha).min(1.0);
+ if color != 0.0 && changed > 0.0 {
+ let l1 = luma(out);
+ let s = 1.0 + color * changed;
+ out = out.map(|v| l1 + (v - l1) * s);
+ }
+ q[0] = out[0].clamp(0.0, 1.0);
+ q[1] = out[1].clamp(0.0, 1.0);
+ q[2] = out[2].clamp(0.0, 1.0);
+ }
+ clip_stretch(px, p.black_clip, p.white_clip);
+}
+
+/// Stretches levels so `black`% of pixels clip to 0 and `white`% to 1 (luminance histogram).
+fn clip_stretch(px: &mut [[f32; 4]], black: f32, white: f32) {
+ if black <= 0.0 && white <= 0.0 {
+ return;
+ }
+ let mut hist = [0u32; 1024];
+ let mut n = 0u32;
+ for q in px.iter().filter(|q| q[3] > 0.0) {
+ hist[((luma([q[0], q[1], q[2]]).clamp(0.0, 1.0)) * 1023.0).round() as usize] += 1;
+ n += 1;
+ }
+ if n == 0 {
+ return;
+ }
+ let find = |pct: f32, rev: bool| -> f32 {
+ let target = (pct.clamp(0.0, 50.0) / 100.0 * n as f32) as u32;
+ let mut acc = 0;
+ for k in 0..1024 {
+ let i = if rev { 1023 - k } else { k };
+ acc += hist[i];
+ if acc > target {
+ return i as f32 / 1023.0;
+ }
+ }
+ if rev { 0.0 } else { 1.0 }
+ };
+ let lo = find(black, false);
+ let hi = find(white, true);
+ if hi - lo < 1e-3 {
+ return;
+ }
+ for q in px.iter_mut().filter(|q| q[3] > 0.0) {
+ for v in &mut q[..3] {
+ *v = ((*v - lo) / (hi - lo)).clamp(0.0, 1.0);
+ }
+ }
+}
+
+/// Image › Adjustments › Replace Color: Color Range-style selection (fuzziness in 0..=200 levels)
+/// around `color`, then a hue (±180°), saturation and lightness (±100) shift weighted by it.
+/// Returns the selection mask (what the dialog previews).
+pub fn replace_color(
+ px: &mut [[f32; 4]],
+ color: [f32; 3],
+ fuzziness: f32,
+ hue: f32,
+ saturation: f32,
+ lightness: f32,
+) -> Vec<f32> {
+ let mask = crate::selection::color_range(px, color, fuzziness);
+ for (q, &k) in px.iter_mut().zip(&mask) {
+ if k <= 0.0 {
+ continue;
+ }
+ let c = [q[0], q[1], q[2]];
+ let [hh, ss, ll] = rgb_to_hsl(c);
+ let s = if saturation >= 0.0 {
+ ss + (1.0 - ss) * saturation / 100.0
+ } else {
+ ss * (1.0 + saturation / 100.0)
+ };
+ let l = if lightness >= 0.0 {
+ ll + (1.0 - ll) * lightness / 100.0
+ } else {
+ ll * (1.0 + lightness / 100.0)
+ };
+ let o = hsl_to_rgb([
+ (hh + hue / 360.0).rem_euclid(1.0),
+ s.clamp(0.0, 1.0),
+ l.clamp(0.0, 1.0),
+ ]);
+ for i in 0..3 {
+ q[i] = (c[i] + (o[i] - c[i]) * k).clamp(0.0, 1.0);
+ }
+ }
+ mask
+}
+
+/// Lab mean and standard deviation of the opaque pixels, `[L, a, b]` each.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct LabStats {
+ pub mean: [f32; 3],
+ pub std: [f32; 3],
+}
+
+/// Statistics for Match Color (pixels weighted by alpha × optional mask).
+pub fn lab_stats(px: &[[f32; 4]], mask: Option<&[f32]>) -> Option<LabStats> {
+ let mut sum = [0.0f64; 3];
+ let mut sq = [0.0f64; 3];
+ let mut wsum = 0.0f64;
+ for (i, q) in px.iter().enumerate() {
+ let w = f64::from(q[3] * mask.map_or(1.0, |m| m.get(i).copied().unwrap_or(0.0)));
+ if w <= 0.0 {
+ continue;
+ }
+ let lab = srgb_to_lab([q[0], q[1], q[2]]);
+ for k in 0..3 {
+ sum[k] += w * f64::from(lab[k]);
+ sq[k] += w * f64::from(lab[k]) * f64::from(lab[k]);
+ }
+ wsum += w;
+ }
+ if wsum <= 0.0 {
+ return None;
+ }
+ let mean: [f32; 3] = std::array::from_fn(|k| (sum[k] / wsum) as f32);
+ let std =
+ std::array::from_fn(|k| ((sq[k] / wsum - (sum[k] / wsum).powi(2)).max(0.0).sqrt()) as f32);
+ Some(LabStats { mean, std })
+}
+
+/// Image › Adjustments › Match Color options (Photoshop ranges).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct MatchColor {
+ /// 1..=200 (100 = matched luminance).
+ pub luminance: f32,
+ /// Color intensity 1..=200 (100 = matched chroma; 1 ≈ gray).
+ pub intensity: f32,
+ /// 0..=100: blend back toward the original.
+ pub fade: f32,
+ /// Remove the colour cast (target a/b means → 0).
+ pub neutralize: bool,
+}
+
+impl Default for MatchColor {
+ fn default() -> Self {
+ MatchColor {
+ luminance: 100.0,
+ intensity: 100.0,
+ fade: 0.0,
+ neutralize: false,
+ }
+ }
+}
+
+/// Reinhard-style colour transfer in Lab: shift and scale each channel of `px` (statistics
+/// `target`) toward `source`'s statistics; with no source only Neutralize / intensity / luminance
+/// act on the image's own statistics.
+pub fn match_color(
+ px: &mut [[f32; 4]],
+ target: &LabStats,
+ source: Option<&LabStats>,
+ o: &MatchColor,
+) {
+ let src = source.copied().unwrap_or(*target);
+ let lum = o.luminance / 100.0;
+ let inten = o.intensity / 100.0;
+ let fade = (o.fade / 100.0).clamp(0.0, 1.0);
+ let scale = |k: usize| {
+ if target.std[k] > 1e-4 {
+ src.std[k] / target.std[k]
+ } else {
+ 1.0
+ }
+ };
+ let mut dst_mean = src.mean;
+ if o.neutralize {
+ dst_mean[1] = 0.0;
+ dst_mean[2] = 0.0;
+ }
+ for q in px.iter_mut().filter(|q| q[3] > 0.0) {
+ let c = [q[0], q[1], q[2]];
+ let lab = srgb_to_lab(c);
+ let l = ((lab[0] - target.mean[0]) * scale(0) + dst_mean[0]) * lum;
+ let a = ((lab[1] - target.mean[1]) * scale(1) + dst_mean[1]) * inten;
+ let b = ((lab[2] - target.mean[2]) * scale(2) + dst_mean[2]) * inten;
+ let o = lab_to_srgb([l.clamp(0.0, 100.0), a, b]);
+ for i in 0..3 {
+ q[i] = (o[i] + (c[i] - o[i]) * fade).clamp(0.0, 1.0);
+ }
+ }
+}
+
+/// Image › Adjustments › HDR Toning ("Local Adaptation" method) parameters.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct HdrToning {
+ /// Edge glow radius in px (1..=500).
+ pub radius: f32,
+ /// Edge glow strength 0.1..=4.
+ pub strength: f32,
+ /// 0.1..=2 (1 = neutral; lower = more contrast).
+ pub gamma: f32,
+ /// -5..=5 stops.
+ pub exposure: f32,
+ /// -100..=300 %.
+ pub detail: f32,
+ pub shadow: f32,
+ pub highlight: f32,
+ /// -100..=100.
+ pub vibrance: f32,
+ pub saturation: f32,
+ /// Toning curve on luminance, (input, output) in 0..=1; empty = identity.
+ pub curve: Vec<(f32, f32)>,
+}
+
+impl Default for HdrToning {
+ fn default() -> Self {
+ HdrToning {
+ radius: 30.0,
+ strength: 0.5,
+ gamma: 1.0,
+ exposure: 0.0,
+ detail: 30.0,
+ shadow: 0.0,
+ highlight: 0.0,
+ vibrance: 0.0,
+ saturation: 20.0,
+ curve: Vec::new(),
+ }
+ }
+}
+
+fn curve_eval(pts: &[(f32, f32)], x: f32) -> f32 {
+ if pts.len() < 2 {
+ return x;
+ }
+ if x <= pts[0].0 {
+ return pts[0].1;
+ }
+ for w in pts.windows(2) {
+ if x <= w[1].0 {
+ let span = (w[1].0 - w[0].0).max(1e-6);
+ return w[0].1 + (w[1].1 - w[0].1) * (x - w[0].0) / span;
+ }
+ }
+ pts[pts.len() - 1].1
+}
+
+/// Local adaptation tone mapping (Durand–Dorsey style base/detail split in log luminance): the
+/// blurred log luminance (radius) is the base layer, compressed toward its mean by `strength`;
+/// detail is boosted; then exposure, gamma, shadow/highlight lift, the toning curve, and
+/// vibrance/saturation. Like Photoshop the result is a flattened, low-dynamic-range image.
+pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) {
+ if px.is_empty() {
+ return;
+ }
+ const EPS: f32 = 1e-4;
+ let logl: Vec<f32> = px
+ .iter()
+ .map(|q| (luma([q[0], q[1], q[2]]).max(0.0) + EPS).ln())
+ .collect();
+ let mut base = logl.clone();
+ gauss_blur_n(&mut base, w, h, 1, p.radius.max(1.0) / 2.0);
+ let n = px.iter().filter(|q| q[3] > 0.0).count().max(1) as f32;
+ let mean = base
+ .iter()
+ .zip(px.iter())
+ .filter(|(_, q)| q[3] > 0.0)
+ .map(|(b, _)| *b)
+ .sum::<f32>()
+ / n;
+ let compress = 1.0 / (1.0 + p.strength.max(0.0));
+ let detail = 1.0 + p.detail / 100.0;
+ let exposure = 2f32.powf(p.exposure);
+ let gamma = p.gamma.clamp(0.1, 4.0);
+ let mut sorted = p.curve.clone();
+ sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
+ for (i, q) in px.iter_mut().enumerate() {
+ if q[3] <= 0.0 {
+ continue;
+ }
+ let c = [q[0], q[1], q[2]];
+ let l0 = luma(c).max(0.0) + EPS;
+ let new_log = mean + (base[i] - mean) * compress + (logl[i] - base[i]) * detail;
+ let mut l1 = (new_log.exp() * exposure).max(0.0).powf(gamma);
+ l1 += p.shadow / 100.0 * (1.0 - l1).powi(3) * 0.5 - p.highlight / 100.0 * l1.powi(3) * 0.5;
+ l1 = curve_eval(&sorted, l1.clamp(0.0, 1.0));
+ let ratio = l1 / l0;
+ let mut out = c.map(|v| v * ratio);
+ // Saturation then vibrance (less saturated colours move more), around the new luminance.
+ let ll = luma(out);
+ let sat_now = {
+ let (mx, mn) = (
+ out[0].max(out[1]).max(out[2]),
+ out[0].min(out[1]).min(out[2]),
+ );
+ if mx > 0.0 { (mx - mn) / mx } else { 0.0 }
+ };
+ let s = 1.0 + p.saturation / 100.0 + p.vibrance / 100.0 * (1.0 - sat_now);
+ out = out.map(|v| ll + (v - ll) * s.max(0.0));
+ q[0] = out[0].clamp(0.0, 1.0);
+ q[1] = out[1].clamp(0.0, 1.0);
+ q[2] = out[2].clamp(0.0, 1.0);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ramp(w: usize, h: usize) -> Vec<[f32; 4]> {
+ (0..w * h)
+ .map(|i| {
+ let x = (i % w) as f32 / (w - 1) as f32;
+ [x, x * 0.8, x * 0.6 + 0.1, 1.0]
+ })
+ .collect()
+ }
+
+ #[test]
+ fn shadows_lift_dark_pixels_more_than_bright() {
+ let mut px = ramp(32, 8);
+ let orig = px.clone();
+ shadows_highlights(
+ &mut px,
+ 32,
+ 8,
+ &ShadowsHighlights {
+ black_clip: 0.0,
+ white_clip: 0.0,
+ ..Default::default()
+ },
+ );
+ let gain = |i: usize| {
+ luma([px[i][0], px[i][1], px[i][2]]) - luma([orig[i][0], orig[i][1], orig[i][2]])
+ };
+ assert!(gain(3) > 0.02, "{}", gain(3));
+ assert!(gain(3) > gain(30), "{} {}", gain(3), gain(30));
+ // Zero amounts and no clipping: identity.
+ let mut px2 = orig.clone();
+ let id = ShadowsHighlights {
+ shadow_amount: 0.0,
+ highlight_amount: 0.0,
+ color: 0.0,
+ black_clip: 0.0,
+ white_clip: 0.0,
+ ..Default::default()
+ };
+ shadows_highlights(&mut px2, 32, 8, &id);
+ assert_eq!(px2, orig);
+ }
+
+ #[test]
+ fn highlights_darken_bright_pixels() {
+ let mut px = ramp(32, 8);
+ let orig = px.clone();
+ let p = ShadowsHighlights {
+ shadow_amount: 0.0,
+ highlight_amount: 80.0,
+ black_clip: 0.0,
+ white_clip: 0.0,
+ ..Default::default()
+ };
+ shadows_highlights(&mut px, 32, 8, &p);
+ assert!(px[30][0] < orig[30][0]);
+ assert!((px[1][0] - orig[1][0]).abs() < 1e-6);
+ }
+
+ #[test]
+ fn replace_color_only_touches_matching_pixels() {
+ let mut px = vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]];
+ let m = replace_color(&mut px, [1.0, 0.0, 0.0], 40.0, 120.0, 0.0, 0.0);
+ assert_eq!(m[1], 0.0);
+ assert!(px[0][1] > 0.9 && px[0][0] < 0.1, "{:?}", px[0]);
+ assert_eq!(px[1], [0.0, 0.0, 1.0, 1.0]);
+ }
+
+ #[test]
+ fn match_color_moves_statistics_toward_source() {
+ let src: Vec<[f32; 4]> = (0..64)
+ .map(|i| [0.8, 0.4 + (i % 8) as f32 * 0.02, 0.2, 1.0])
+ .collect();
+ let mut tgt: Vec<[f32; 4]> = (0..64)
+ .map(|i| [0.2, 0.3, 0.6 + (i % 8) as f32 * 0.03, 1.0])
+ .collect();
+ let s = lab_stats(&src, None).unwrap();
+ let t = lab_stats(&tgt, None).unwrap();
+ match_color(&mut tgt, &t, Some(&s), &MatchColor::default());
+ let after = lab_stats(&tgt, None).unwrap();
+ for k in 0..3 {
+ assert!(
+ (after.mean[k] - s.mean[k]).abs() < (t.mean[k] - s.mean[k]).abs() * 0.2 + 1.0,
+ "{k}: {after:?} vs {s:?}"
+ );
+ }
+ // Neutralize with no source: the mean colour goes gray.
+ let mut tint: Vec<[f32; 4]> = (0..16)
+ .map(|i| [0.7, 0.5, 0.3 + i as f32 * 0.01, 1.0])
+ .collect();
+ let t = lab_stats(&tint, None).unwrap();
+ match_color(
+ &mut tint,
+ &t,
+ None,
+ &MatchColor {
+ neutralize: true,
+ ..Default::default()
+ },
+ );
+ let n = lab_stats(&tint, None).unwrap();
+ assert!(n.mean[1].abs() < 2.0 && n.mean[2].abs() < 2.0, "{n:?}");
+ }
+
+ #[test]
+ fn hdr_toning_compresses_range_and_keeps_bounds() {
+ let mut px = ramp(40, 10);
+ hdr_toning(
+ &mut px,
+ 40,
+ 10,
+ &HdrToning {
+ strength: 2.0,
+ detail: 0.0,
+ saturation: 0.0,
+ ..Default::default()
+ },
+ );
+ let l0 = luma([px[2][0], px[2][1], px[2][2]]);
+ let l1 = luma([px[38][0], px[38][1], px[38][2]]);
+ assert!(l1 > l0);
+ assert!(
+ px.iter()
+ .all(|q| q[..3].iter().all(|v| (0.0..=1.0).contains(v)))
+ );
+ // A toning curve that inverts luminance flips the order.
+ let mut px = ramp(40, 10);
+ hdr_toning(
+ &mut px,
+ 40,
+ 10,
+ &HdrToning {
+ strength: 0.0,
+ detail: 0.0,
+ saturation: 0.0,
+ curve: vec![(0.0, 1.0), (1.0, 0.0)],
+ ..Default::default()
+ },
+ );
+ assert!(luma([px[2][0], px[2][1], px[2][2]]) > luma([px[38][0], px[38][1], px[38][2]]));
+ }
+}
diff --git a/crates/algo/src/video.rs b/crates/algo/src/video.rs
new file mode 100644
index 000000000..8653d9533
--- /dev/null
+++ b/crates/algo/src/video.rs
@@ -0,0 +1,90 @@
+//! Filter › Video: De-Interlace and NTSC Colors.
+
+use photocraft_color::ColorMode;
+use photocraft_geom::Rect;
+
+use crate::fxutil::{MAXC, rgba, set_rgba, xy};
+use crate::image::Image;
+use crate::Ctx;
+
+/// De-Interlace: removes one field (odd = lines 1, 3, 5… counted from the
+/// bounds' top, i.e. even offsets) and rebuilds it from the neighbouring
+/// kept lines by duplication or (premultiplied) interpolation.
+pub(crate) fn deinterlace(src: &Image, out: Rect, ctx: &Ctx, eliminate_even: bool, interpolate: bool) -> Vec<f32> {
+ let n = src.ch;
+ let b = ctx.bounds;
+ let mut res = src.crop(out);
+ let mut acc = [0.0f32; MAXC];
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ if !b.contains(x, y) {
+ continue;
+ }
+ // 1-based line number parity: offset 0 is line 1 (odd).
+ let odd_line = (y - b.y0) % 2 == 0;
+ if odd_line == eliminate_even {
+ continue;
+ }
+ let above = (y > b.y0).then_some(y - 1);
+ let below = (y + 1 < b.y1).then_some(y + 1);
+ let (rows, cnt) = match (interpolate, above, below) {
+ (true, Some(a), Some(c)) => ([a, c], 2),
+ (_, Some(a), _) => ([a, a], 1),
+ (_, None, Some(c)) => ([c, c], 1),
+ _ => continue,
+ };
+ acc[..n].fill(0.0);
+ let k = 1.0 / cnt as f32;
+ for &yy in &rows[..cnt] {
+ let a = if ctx.alpha { src.get(x, yy, n - 1) } else { 1.0 };
+ for (c, v) in acc.iter_mut().enumerate().take(n) {
+ let s = src.get(x, yy, c);
+ *v += if ctx.alpha && c < n - 1 { s * a } else { s } * k;
+ }
+ }
+ crate::fxutil::unpremul_px(&mut acc[..n], ctx.alpha);
+ px.copy_from_slice(&acc[..n]);
+ }
+ res
+}
+
+/// Composite-signal limits (fractions of the 7.5–100 IRE luma range): broadcast-safe
+/// is −20…120 IRE, i.e. Y ± C within these bounds.
+const NTSC_MAX: f32 = (120.0 - 7.5) / 92.5;
+const NTSC_MIN: f32 = (-20.0 - 7.5) / 92.5;
+
+/// NTSC Colors: scales chroma (in YIQ) so the composite signal Y ± C stays
+/// within broadcast limits; hue and luma are kept.
+pub(crate) fn ntsc(src: &Image, out: Rect, ctx: &Ctx) -> Vec<f32> {
+ let n = src.ch;
+ let native = ctx.mode == ColorMode::Rgb;
+ let mut res = src.crop(out);
+ for px in res.chunks_exact_mut(n) {
+ let c = if native { [px[0], px[1], px[2], 1.0] } else { rgba(ctx, px) };
+ let yy = 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2];
+ let ii = 0.595_716 * c[0] - 0.274_453 * c[1] - 0.321_263 * c[2];
+ let qq = 0.211_456 * c[0] - 0.522_591 * c[1] + 0.311_135 * c[2];
+ let chroma = (ii * ii + qq * qq).sqrt();
+ if chroma <= 1e-7 {
+ continue;
+ }
+ let mut k: f32 = 1.0;
+ if yy + chroma > NTSC_MAX {
+ k = k.min(((NTSC_MAX - yy) / chroma).max(0.0));
+ }
+ if yy - chroma < NTSC_MIN {
+ k = k.min(((yy - NTSC_MIN) / chroma).max(0.0));
+ }
+ if k >= 1.0 {
+ continue;
+ }
+ let (i2, q2) = (ii * k, qq * k);
+ let rgb = [yy + 0.956_3 * i2 + 0.621_0 * q2, yy - 0.272_1 * i2 - 0.647_4 * q2, yy - 1.107_0 * i2 + 1.704_6 * q2];
+ if native {
+ px[..3].copy_from_slice(&rgb);
+ } else {
+ set_rgba(ctx, px, [rgb[0], rgb[1], rgb[2], c[3]]);
+ }
+ }
+ res
+}
diff --git a/crates/algo/src/warp.rs b/crates/algo/src/warp.rs
new file mode 100644
index 000000000..67682010e
--- /dev/null
+++ b/crates/algo/src/warp.rs
@@ -0,0 +1,350 @@
+//! Mesh warps (Edit › Transform › Warp, smart-object warps): resampling a surface through any
+//! forward map, such as a [`photocraft_geom::warp::Warp`] (bicubic Bezier patches or a preset).
+//!
+//! The source rectangle is subdivided into a fine grid whose vertices are mapped forward; each
+//! cell's two triangles are rasterized in destination space with the source position
+//! interpolated barycentrically, then the source is sampled there (premultiplied, nearest /
+//! bilinear / Catmull-Rom bicubic, like Free Transform). Cells are a few source pixels across, so
+//! the piecewise-affine inverse is within a small fraction of a pixel of the true one; affine
+//! maps (the identity included) are reproduced exactly. Where the warp folds over itself the
+//! later (lower-right) cell wins. Work is split per destination tile (parallel on native).
+
+use photocraft_color::PixelFormat;
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+
+use crate::transform::Interp;
+
+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]
+}
+
+/// Grid cell size (source px) used to approximate the map.
+const CELL: f64 = 4.0;
+/// Most cells along one axis (bounds memory and time on huge layers).
+const MAX_CELLS: usize = 512;
+
+/// Warps the content of `src` inside `src_rect` through the forward map `f` (source document
+/// coordinates → destination document coordinates). Output has `src`'s format with alpha
+/// added; pixels outside the warped area are transparent.
+pub fn warp_mesh_surface(src: &Surface, src_rect: Rect, f: &(dyn Fn(f64, f64) -> (f64, f64) + Sync), interp: Interp) -> Surface {
+ if src_rect.is_empty() {
+ let fmt = src.format();
+ return Surface::new(PixelFormat::new(fmt.mode, fmt.sample, true));
+ }
+ let (sw, sh) = (f64::from(src_rect.width()), f64::from(src_rect.height()));
+ let nx = ((sw / CELL).ceil() as usize).clamp(1, MAX_CELLS);
+ let ny = ((sh / CELL).ceil() as usize).clamp(1, MAX_CELLS);
+ // Forward-mapped vertices (and their source positions).
+ let mut verts = Vec::with_capacity((nx + 1) * (ny + 1));
+ for j in 0..=ny {
+ for i in 0..=nx {
+ let sx = f64::from(src_rect.x0) + sw * i as f64 / nx as f64;
+ let sy = f64::from(src_rect.y0) + sh * j as f64 / ny as f64;
+ let (dx, dy) = f(sx, sy);
+ verts.push(([dx, dy], [sx, sy]));
+ }
+ }
+ let w1 = nx + 1;
+ let mut tris = Vec::with_capacity(nx * ny * 2);
+ for j in 0..ny {
+ for i in 0..nx {
+ let a = j * w1 + i;
+ tris.push([a, a + 1, a + w1 + 1]);
+ tris.push([a, a + w1 + 1, a + w1]);
+ }
+ }
+ warp_triangles(src, src_rect, &verts, &tris, interp)
+}
+
+/// Rasterizes textured triangles: each vertex is `(destination, source)` in document pixels and
+/// each triangle samples `src` (restricted to `src_rect`) through the barycentric
+/// interpolation of its source positions. Later triangles in `tris` draw over earlier ones (the
+/// order is the depth order). Output has `src`'s format with alpha added.
+pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2])], tris: &[[usize; 3]], interp: Interp) -> Surface {
+ let mut fmt = src.format();
+ let converted;
+ let 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() || tris.is_empty() {
+ return out;
+ }
+ if verts.iter().any(|v| !v.0[0].is_finite() || !v.0[1].is_finite()) {
+ return out;
+ }
+ let lim = f64::from(1 << 20);
+ let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
+ for v in tris.iter().flatten().map(|&i| &verts[i]) {
+ x0 = x0.min(v.0[0]);
+ y0 = y0.min(v.0[1]);
+ x1 = x1.max(v.0[0]);
+ y1 = y1.max(v.0[1]);
+ }
+ let dst = Rect::new(x0.max(-lim).floor() as i32 - 1, y0.max(-lim).floor() as i32 - 1, x1.min(lim).ceil() as i32 + 1, y1.min(lim).ceil() as i32 + 1);
+ // Triangles: (vertex indices), binned per destination tile.
+ let tiles: Vec<Rect> = dst.tiles().map(|tc| tc.rect().intersect(&dst)).filter(|r| !r.is_empty()).collect();
+ let mut bins: Vec<Vec<[usize; 3]>> = vec![Vec::new(); tiles.len()];
+ let tx0 = tiles.iter().map(|t| t.x0).min().unwrap_or(0);
+ let ty0 = tiles.iter().map(|t| t.y0).min().unwrap_or(0);
+ let ts = photocraft_geom::TILE_SIZE;
+ let cols = tiles.iter().map(|t| (t.x0 - tx0) / ts).max().unwrap_or(0) as usize + 1;
+ let grid_of = |t: &Rect| ((t.y0 - ty0) / ts) as usize * cols + ((t.x0 - tx0) / ts) as usize;
+ let mut lookup = vec![usize::MAX; cols * (tiles.iter().map(|t| (t.y0 - ty0) / ts).max().unwrap_or(0) as usize + 1)];
+ for (k, t) in tiles.iter().enumerate() {
+ lookup[grid_of(t)] = k;
+ }
+ for &tri in tris {
+ let ps = tri.map(|v| verts[v].0);
+ let bx0 = ps.iter().map(|p| p[0]).fold(f64::MAX, f64::min).floor() as i32;
+ let by0 = ps.iter().map(|p| p[1]).fold(f64::MAX, f64::min).floor() as i32;
+ let bx1 = ps.iter().map(|p| p[0]).fold(f64::MIN, f64::max).ceil() as i32;
+ let by1 = ps.iter().map(|p| p[1]).fold(f64::MIN, f64::max).ceil() as i32;
+ let (cx0, cy0) = ((bx0.max(dst.x0) - tx0).div_euclid(ts), (by0.max(dst.y0) - ty0).div_euclid(ts));
+ let (cx1, cy1) = ((bx1.min(dst.x1 - 1) - tx0).div_euclid(ts), (by1.min(dst.y1 - 1) - ty0).div_euclid(ts));
+ for cy in cy0.max(0)..=cy1 {
+ for cx in cx0.max(0)..=cx1 {
+ let g = cy as usize * cols + cx as usize;
+ if let Some(&k) = lookup.get(g)
+ && k != usize::MAX
+ {
+ bins[k].push(tri);
+ }
+ }
+ }
+ }
+ let n = fmt.channels();
+ let a = n - 1;
+ let work = |(t, tris): (&Rect, &Vec<[usize; 3]>)| -> Option<(Rect, Vec<f32>)> {
+ if tris.is_empty() {
+ return None;
+ }
+ let w = t.width() as usize;
+ let h = t.height() as usize;
+ // Source position per destination pixel (NaN = not covered).
+ let mut uv = vec![[f64::NAN; 2]; w * h];
+ for tri in tris {
+ let [(p0, s0), (p1, s1), (p2, s2)] = tri.map(|v| verts[v]);
+ let det = (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]);
+ if det.abs() < 1e-12 {
+ continue;
+ }
+ let bx0 = (p0[0].min(p1[0]).min(p2[0]) - 0.5).floor().max(f64::from(t.x0)) as i32;
+ let by0 = (p0[1].min(p1[1]).min(p2[1]) - 0.5).floor().max(f64::from(t.y0)) as i32;
+ let bx1 = (p0[0].max(p1[0]).max(p2[0]) + 0.5).ceil().min(f64::from(t.x1)) as i32;
+ let by1 = (p0[1].max(p1[1]).max(p2[1]) + 0.5).ceil().min(f64::from(t.y1)) as i32;
+ let eps = -1e-9;
+ for y in by0..by1 {
+ let py = f64::from(y) + 0.5;
+ for x in bx0..bx1 {
+ let px = f64::from(x) + 0.5;
+ let l1 = ((px - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (py - p0[1])) / det;
+ let l2 = ((p1[0] - p0[0]) * (py - p0[1]) - (px - p0[0]) * (p1[1] - p0[1])) / det;
+ let l0 = 1.0 - l1 - l2;
+ if l0 < eps || l1 < eps || l2 < eps {
+ continue;
+ }
+ let o = (y - t.y0) as usize * w + (x - t.x0) as usize;
+ uv[o] = [l0 * s0[0] + l1 * s1[0] + l2 * s2[0], l0 * s0[1] + l1 * s1[1] + l2 * s2[1]];
+ }
+ }
+ }
+ // Source footprint of the covered pixels.
+ let (mut fx0, mut fy0, mut fx1, mut fy1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
+ for q in uv.iter().filter(|q| !q[0].is_nan()) {
+ fx0 = fx0.min(q[0]);
+ fy0 = fy0.min(q[1]);
+ fx1 = fx1.max(q[0]);
+ fy1 = fy1.max(q[1]);
+ }
+ if fx0 > fx1 {
+ return None;
+ }
+ let foot = Rect::new(fx0.floor() as i32 - 3, fy0.floor() as i32 - 3, fx1.ceil() as i32 + 3, fy1.ceil() as i32 + 3).intersect(&src_rect);
+ if foot.is_empty() || !src.has_tiles_in(foot) {
+ return None;
+ }
+ let mut px = src.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 { f64::from(px[((y - foot.y0) as usize * fw + (x - foot.x0) as usize) * n + c]) }
+ };
+ let mut outp = vec![0.0f32; w * h * n];
+ let mut any = false;
+ let mut acc = [0.0f64; 8];
+ for (o, q) in uv.iter().enumerate() {
+ if q[0].is_nan() {
+ continue;
+ }
+ let (u, v) = (q[0] - 0.5, q[1] - 0.5);
+ 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 - f64::from(ix), v - f64::from(iy));
+ 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 => {
+ // Snap to the pixel grid when within float noise, so identity is exact.
+ let snap = |t: f64| if (t - t.round()).abs() < 1e-7 { t.round() } else { t };
+ let (u, v) = (snap(u), snap(v));
+ let (ix, iy) = (u.floor() as i32, v.floor() as i32);
+ let (wx, wy) = (catmull_rom(u - f64::from(ix)), catmull_rom(v - f64::from(iy)));
+ for (j, wyj) in wy.iter().enumerate() {
+ for (i, wxi) in wx.iter().enumerate() {
+ let k = wxi * wyj;
+ if k == 0.0 {
+ continue;
+ }
+ 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 b = o * n;
+ for c in 0..a {
+ outp[b + c] = (acc[c] / al).clamp(0.0, 1.0) as f32;
+ }
+ outp[b + 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().zip(bins.par_iter()).filter_map(work).collect()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let done: Vec<(Rect, Vec<f32>)> = tiles.iter().zip(bins.iter()).filter_map(work).collect();
+ for (r, v) in done {
+ out.write_region(r, &v);
+ }
+ out.prune();
+ out
+}
+
+/// [`warp_mesh_surface`] for single-channel surfaces whose outside reads as their default value
+/// (layer masks, selections): the content is warped with alpha and flattened back onto the
+/// default.
+pub fn warp_mesh_gray(s: &Surface, f: &(dyn Fn(f64, f64) -> (f64, f64) + Sync), 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;
+ }
+ 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_mesh_surface(&tmp, src, f, interp);
+ let cover = src.union(&w.content_bounds());
+ out.write_region(cover, &vec![default; cover.width() as usize * cover.height() as usize]);
+ 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
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::{ColorMode, SampleType};
+ use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};
+
+ fn sample(s: SampleType) -> Surface {
+ let mut surf = Surface::new(PixelFormat::new(ColorMode::Rgb, s, true));
+ for y in 0..24 {
+ for x in 0..40 {
+ let v = ((x * 7 + y * 13) % 17) as f32 / 16.0;
+ surf.write_pixel(x + 5, y + 3, &[v, 1.0 - v, (x as f32) / 40.0, 1.0]);
+ }
+ }
+ surf
+ }
+
+ #[test]
+ fn identity_warp_is_a_no_op_at_every_depth() {
+ for s in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let src = sample(s);
+ let r = src.content_bounds();
+ let b = [f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)];
+ for w in [Warp::none(b), Warp::custom(BezierMesh::identity(b, 1, 1), b), Warp::preset(WarpStyle::Arc, 0.0, b)] {
+ for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] {
+ let out = warp_mesh_surface(&src, r, &|x, y| w.map(x, y), interp);
+ assert_eq!(out.content_bounds(), r, "{s:?} {interp:?}");
+ let (a, o) = (src.read_region(r), out.read_region(r));
+ let worst = a.iter().zip(&o).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);
+ assert!(worst <= 1.0 / 255.0, "{s:?} {interp:?}: {worst}");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn translation_and_known_arc_points() {
+ let src = sample(SampleType::U8);
+ let r = src.content_bounds();
+ let out = warp_mesh_surface(&src, r, &|x, y| (x + 10.0, y - 2.0), Interp::Bilinear);
+ assert_eq!(out.content_bounds(), r.translate(10, -2));
+ assert_eq!(out.pixel(20, 10), src.pixel(10, 12));
+ // Arc 50 %: the centre column keeps its pixels, the ends drop.
+ let b = [f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)];
+ let w = Warp::preset(WarpStyle::Arc, 50.0, b);
+ let arc = warp_mesh_surface(&src, r, &|x, y| w.map(x, y), Interp::Bilinear);
+ let cx = (r.x0 + r.x1) / 2;
+ let (p, q) = (arc.pixel(cx, 10), src.pixel(cx, 10));
+ assert!(p.iter().zip(&q).all(|(a, b)| (a - b).abs() < 0.05), "{p:?} vs {q:?}");
+ let (ex, ey) = w.map(f64::from(r.x0) + 2.5, f64::from(r.y0) + 2.5);
+ let e = arc.pixel(ex.floor() as i32, ey.floor() as i32);
+ assert!(e[3] > 0.2, "a point near the top-left corner lands at its mapped position: {e:?}");
+ assert!(arc.content_bounds().y1 > r.y1 + 2, "ends drop below the original box");
+ }
+
+ #[test]
+ fn gray_masks_keep_their_default() {
+ let mut m = Surface::with_default(PixelFormat::GRAY8, &[1.0]);
+ m.fill_rect(Rect::new(4, 4, 10, 10), &[0.0]);
+ let o = warp_mesh_gray(&m, &|x, y| (x + 5.0, y), Interp::Bilinear);
+ assert_eq!(o.pixel(0, 0), vec![1.0]);
+ assert_eq!(o.pixel(12, 6), vec![0.0]);
+ assert_eq!(o.pixel(5, 6), vec![1.0]);
+ }
+}
diff --git a/crates/automation/tests/agent_tasks.rs b/crates/automation/tests/agent_tasks.rs
new file mode 100644
index 000000000..34a4dc758
--- /dev/null
+++ b/crates/automation/tests/agent_tasks.rs
@@ -0,0 +1,213 @@
+//! M11 acceptance: an agent completes 10 scripted edit tasks over MCP (roadmap M11 DoD).
+//!
+//! Each task uses only MCP tools (`doc_*`, `command_run`) the way an agent would, and checks the
+//! outcome through `doc_inspect`, `document.pixel` or the exported files, never engine internals.
+
+use std::io::Write;
+
+use photocraft_automation::PhotocraftMcp;
+use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig};
+use rmcp::service::RunningService;
+use rmcp::{ClientHandler, RoleClient, ServiceExt};
+use serde_json::{Value, json};
+
+#[derive(Clone, Default)]
+struct Client;
+impl ClientHandler for Client {
+ fn get_info(&self) -> ClientConfig {
+ ClientConfig::default()
+ }
+}
+
+type Conn = RunningService<RoleClient, Client>;
+
+async fn connect() -> Conn {
+ let (s, c) = tokio::io::duplex(1 << 20);
+ tokio::spawn(async move {
+ if let Ok(running) = PhotocraftMcp::headless().serve(s).await {
+ let _ = running.waiting().await;
+ }
+ });
+ Client.serve(c).await.expect("client init")
+}
+
+fn text(r: &CallToolResult) -> String {
+ r.content.iter().filter_map(|c| c.as_text()).map(|t| t.text.clone()).collect::<Vec<_>>().join("\n")
+}
+
+/// Call a tool and parse its JSON result, failing the test on a tool error.
+async fn tool(c: &Conn, name: &str, args: Value) -> Value {
+ let mut p = CallToolRequestParams::new(name.to_owned());
+ if let Value::Object(m) = args {
+ p = p.with_arguments(m);
+ }
+ let r = c.call_tool(p).await.expect("call_tool transport");
+ assert_ne!(r.is_error, Some(true), "{name} failed: {}", text(&r));
+ serde_json::from_str(&text(&r)).unwrap_or(Value::String(text(&r)))
+}
+
+async fn run(c: &Conn, id: &str, params: Value) -> Value {
+ tool(c, "command_run", json!({"id": id, "params": params})).await
+}
+
+async fn inspect(c: &Conn) -> Value {
+ tool(c, "doc_inspect", json!({})).await
+}
+
+/// Composite RGBA at (x, y), whatever envelope `command_run` wraps the result in.
+async fn pixel(c: &Conn, x: i32, y: i32) -> Vec<f64> {
+ let v = run(c, "document.pixel", json!({"x": x, "y": y})).await;
+ let arr = if v.is_array() { v } else { v.get("result").cloned().unwrap_or(v) };
+ arr.as_array().unwrap_or_else(|| panic!("pixel: {arr}")).iter().map(|x| x.as_f64().unwrap()).collect()
+}
+
+fn top_layer(doc: &Value) -> &Value {
+ &doc["layers"][0]
+}
+
+fn tmp(name: &str) -> std::path::PathBuf {
+ let d = std::env::temp_dir().join(format!("pc-agent-{}-{name}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+/// A 64×48 RGB gradient PNG (red ramps across, green down).
+fn gradient_png(dir: &std::path::Path) -> String {
+ let (w, h) = (64u32, 48u32);
+ let mut px = Vec::with_capacity((w * h * 3) as usize);
+ for y in 0..h {
+ for x in 0..w {
+ px.extend_from_slice(&[(x * 4) as u8, (y * 5) as u8, 128]);
+ }
+ }
+ let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, px).unwrap();
+ let path = dir.join("gradient.png");
+ std::fs::File::create(&path)
+ .unwrap()
+ .write_all(&photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap())
+ .unwrap();
+ path.to_string_lossy().into_owned()
+}
+
+fn close(a: &[f64], b: &[f64], tol: f64) -> bool {
+ a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol)
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn agent_completes_ten_scripted_tasks() {
+ let dir = tmp("tasks");
+ let png = gradient_png(&dir);
+ let c = connect().await;
+
+ // 1. Make a title card: type layer with a drop shadow, exported as PNG.
+ tool(&c, "doc_new", json!({"width": 200, "height": 120, "background": "white"})).await;
+ run(&c, "type.create", json!({"x": 20, "y": 70, "text": "Hello", "size": 36})).await;
+ run(&c, "layer.layerStyle.dropShadow", json!({"distance": 4, "size": 3})).await;
+ let doc = inspect(&c).await;
+ let t = top_layer(&doc);
+ assert_eq!(t["kind"], "Type", "task 1: {t}");
+ assert_eq!(t["text"]["text"], "Hello", "task 1: {t}");
+ assert_eq!(t["effects"]["items"][0]["kind"], "Drop Shadow", "task 1: {t}");
+ let out = dir.join("card.png");
+ tool(&c, "doc_export", json!({"path": out.to_string_lossy()})).await;
+ let card = photocraft_codecs::decode(&std::fs::read(&out).unwrap()).unwrap();
+ assert_eq!(card.dimensions(), (200, 120), "task 1");
+ tool(&c, "doc_close", json!({})).await;
+
+ // 2. Colour grade a photo non-destructively: Curves brightens the midtones, Vibrance on top.
+ tool(&c, "doc_open", json!({"path": png})).await;
+ let before = pixel(&c, 16, 24).await;
+ run(&c, "layer.newAdjustmentLayer.curves", json!({"points": [[0, 0], [128, 200], [255, 255]]})).await;
+ run(&c, "layer.newAdjustmentLayer.vibrance", json!({"vibrance": 40, "saturation": 0})).await;
+ let after = pixel(&c, 16, 24).await;
+ assert!(after[1] > before[1] + 0.05, "task 2: curves should brighten green {before:?} -> {after:?}");
+ let doc = inspect(&c).await;
+ let kinds: Vec<&str> = doc["layers"].as_array().unwrap().iter().filter_map(|l| l["kind"].as_str()).collect();
+ assert_eq!(kinds, ["Adjustment", "Adjustment", "Pixel"], "task 2");
+
+ // 3. Undo/redo: remove both adjustments, restore one.
+ run(&c, "edit.undo", json!({})).await;
+ run(&c, "edit.undo", json!({})).await;
+ assert!(close(&pixel(&c, 16, 24).await, &before, 1e-6), "task 3: undo should restore the original");
+ run(&c, "edit.redo", json!({})).await;
+ assert_eq!(inspect(&c).await["layers"].as_array().unwrap().len(), 2, "task 3: redo restores Curves");
+ run(&c, "edit.undo", json!({})).await;
+
+ // 4. Editable blur: smart object + Gaussian Blur, retune the radius, then hide the filter.
+ run(&c, "layer.smartObjects.convertToSmartObject", json!({})).await;
+ run(&c, "filter.blur.gaussianBlur", json!({"radius": 2})).await;
+ run(&c, "layer.smartFilter.setParams", json!({"index": 0, "params": {"radius": 6}})).await;
+ let t = inspect(&c).await;
+ let sf = &top_layer(&t)["smartFilters"][0];
+ assert_eq!(sf["command"], "filter.blur.gaussianBlur", "task 4: {t}");
+ assert_eq!(sf["params"]["radius"].as_f64(), Some(6.0), "task 4: {sf}");
+ run(&c, "layer.smartFilter.setVisible", json!({"index": 0, "visible": false})).await;
+ assert!(close(&pixel(&c, 16, 24).await, &before, 1.0 / 255.0), "task 4: hiding the filter restores the pixels");
+
+ // 5. Selection → layer mask: an elliptical reveal on a red layer.
+ run(&c, "layer.new.layer", json!({"name": "Red"})).await;
+ run(&c, "select.all", json!({})).await;
+ run(&c, "edit.fill", json!({"color": "#ff0000"})).await;
+ run(&c, "select.rect", json!({"x": 16, "y": 12, "width": 32, "height": 24, "ellipse": true})).await;
+ run(&c, "layer.layerMask.revealSelection", json!({})).await;
+ assert_eq!(top_layer(&inspect(&c).await)["hasMask"], true, "task 5");
+ let inside = pixel(&c, 32, 24).await;
+ let outside = pixel(&c, 1, 1).await;
+ assert!(inside[0] > 0.99 && inside[1] < 0.01, "task 5: centre is red {inside:?}");
+ assert!(outside[0] < 0.1, "task 5: corner shows the photo {outside:?}");
+ run(&c, "select.deselect", json!({})).await;
+
+ // 6. Save a selection to a channel and load it back.
+ run(&c, "select.rect", json!({"x": 4, "y": 6, "width": 20, "height": 10})).await;
+ run(&c, "select.saveSelection", json!({"name": "Keep"})).await;
+ run(&c, "select.deselect", json!({})).await;
+ assert_eq!(inspect(&c).await["hasSelection"], false, "task 6");
+ run(&c, "select.loadSelection", json!({"channel": "Keep"})).await;
+ let doc = inspect(&c).await;
+ assert_eq!(doc["selectionBounds"], json!([4, 6, 20, 10]), "task 6: {}", doc["selectionBounds"]);
+ assert_eq!(doc["channels"]["alpha"][0]["name"], "Keep", "task 6");
+ run(&c, "select.deselect", json!({})).await;
+ tool(&c, "doc_close", json!({})).await;
+
+ // 7. Lay out three swatches and align their left edges.
+ tool(&c, "doc_new", json!({"width": 120, "height": 90, "background": "white"})).await;
+ for (i, x) in [10, 40, 70].into_iter().enumerate() {
+ run(&c, "layer.new.layer", json!({"name": format!("S{i}")})).await;
+ run(&c, "select.rect", json!({"x": x, "y": 10 + 25 * i as i32, "width": 20, "height": 15})).await;
+ run(&c, "edit.fill", json!({"color": "#3366cc"})).await;
+ }
+ run(&c, "select.deselect", json!({})).await;
+ run(&c, "select.allLayers", json!({})).await;
+ run(&c, "layer.align.leftEdges", json!({})).await;
+ let doc = inspect(&c).await;
+ let xs: Vec<i64> = doc["layers"].as_array().unwrap().iter().filter(|l| l["name"].as_str().is_some_and(|n| n.starts_with('S'))).map(|l| l["bounds"][0].as_i64().unwrap()).collect();
+ assert_eq!(xs, [10, 10, 10], "task 7: {}", doc["layers"]);
+
+ // 8. Export every layer to its own file.
+ let layers_dir = dir.join("layers");
+ std::fs::create_dir_all(&layers_dir).unwrap();
+ run(&c, "file.export.layersToFiles", json!({"dir": layers_dir.to_string_lossy(), "format": "png", "prefix": "swatch"})).await;
+ let n = std::fs::read_dir(&layers_dir).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.path().extension().is_some_and(|x| x == "png"))).count();
+ assert_eq!(n, 4, "task 8: three swatches plus the background");
+
+ // 9. Resize, then crop to a square.
+ run(&c, "image.imageSize", json!({"width": 60, "height": 45})).await;
+ run(&c, "image.crop", json!({"x": 5, "y": 0, "width": 45, "height": 45})).await;
+ let doc = inspect(&c).await;
+ assert_eq!((doc["width"].as_u64(), doc["height"].as_u64()), (Some(45), Some(45)), "task 9");
+
+ // 10. Prepare for print: convert to CMYK and save natively, then reopen.
+ run(&c, "image.mode.cmyk", json!({"intent": "perceptual"})).await;
+ assert_eq!(inspect(&c).await["mode"], "Cmyk", "task 10");
+ let saved = dir.join("print.pcraft");
+ tool(&c, "doc_save", json!({"path": saved.to_string_lossy()})).await;
+ tool(&c, "doc_close", json!({})).await;
+ tool(&c, "doc_open", json!({"path": saved.to_string_lossy()})).await;
+ let doc = inspect(&c).await;
+ assert_eq!((doc["mode"].as_str(), doc["width"].as_u64()), (Some("Cmyk"), Some(45)), "task 10");
+ assert_eq!(doc["layers"].as_array().unwrap().len(), 4, "task 10");
+
+ c.cancel().await.unwrap();
+ std::fs::remove_dir_all(dir).unwrap();
+}
diff --git a/crates/cms/README.md b/crates/cms/README.md
new file mode 100644
index 000000000..815ca1831
--- /dev/null
+++ b/crates/cms/README.md
@@ -0,0 +1,80 @@
+# photocraft-cms
+
+Pure-Rust ICC colour management for Photocraft. No workspace dependencies (L0, publishable),
+no C, no `unsafe`. Implemented from the public ICC.1:2010 (v4.3) and ICC.1:2001-04 (v2)
+specifications, CIE 15, and Adobe's published black point compensation paper.
+
+## API
+
+```rust
+use photocraft_cms::{Builtin, Intent, Profile, Transform};
+
+let src = Profile::parse(&icc_bytes)?; // v2/v4: matrix/TRC, gray TRC, mft1/mft2/mAB/mBA
+let dst = Builtin::CoatedCmyk.profile();
+let t = Transform::new(&src, dst, Intent::RelativeColorimetric, /*bpc*/ true)?;
+t.convert_u8(&rgba8, 4, &mut cmyka8, 5, /*copy alpha*/ true); // also convert_u16 / convert_f32 / apply (in place)
+let mut out = [0.0; 4];
+t.eval(&[1.0, 0.0, 0.0], &mut out); // exact single colour
+```
+
+* `Transform::proof(src, proof, display, intent, bpc, simulate_paper)`: soft-proof chain.
+* `GamutCheck::new(src, proof, ΔE)`: out-of-gamut test (gamut warning).
+* `Lut3d::from_transform(&t, 33).to_rgba16f_bytes()`: display transform as a 3D texture.
+* `transform::cached(src, dst, opts)`: process-wide transform cache.
+* `Profile::to_bytes()`: original bytes of parsed profiles (byte-exact), or an ICC v4.3 encoding.
+
+### Evaluation
+
+* Exact path: a float stage pipeline (curves, matrices, CLUTs, Lab↔XYZ, PCS encodings, BPC /
+ absolute scaling). Float buffers use it by default (`TransformOptions::precise_float`).
+* Integer buffers: matrix/TRC chains use per-code input tables + matrix + output tables indexed
+ by `x^(1/4)` (accurate near black even for pure gamma curves); chains containing a CLUT are
+ sampled into a device link (33³ for 3 inputs, 17⁴ for 4, 4096 for 1) evaluated with
+ tetrahedral interpolation (4D: linear on the first input between two tetrahedra); purely
+ analytic chains (e.g. Lab ↔ RGB) are evaluated exactly. Buffers ≥ 16k pixels run on rayon
+ (native only).
+* Rendering intents: AToB0/1/2 and BToA0/1/2 by intent with AToB0/BToA0 fallback; absolute
+ colorimetric scales by media white (`wtpt`; v2 display profiles treated as D50); BPC uses
+ neutral black points (Y only) mapped linearly in XYZ.
+
+## Built-in profiles (all CC0-1.0, generated by this crate)
+
+| id | description |
+|---|---|
+| `srgb` | sRGB IEC61966-2.1 (Rec. 709 primaries, D65 Bradford-adapted, sRGB TRC) |
+| `display-p3` | Display P3 |
+| `adobe-rgb-compat` | Adobe RGB (1998)-compatible (published primaries, gamma 563/256) |
+| `prophoto-compat` | ProPhoto-compatible (ROMM primaries, D50, gamma 1.8) |
+| `linear-srgb` | sRGB primaries, linear |
+| `rec2020` | Rec. 2020 primaries, Rec. 709 OETF |
+| `gray-gamma-2.2`, `sgray` | gray gamma 2.2; gray with the sRGB curve (default gray working space) |
+| `lab-d50` | Lab identity (v4 encoding) |
+| `coated-cmyk` | **Photocraft Coated CMYK (synthetic, 300% TAC, medium GCR)** — default CMYK |
+
+### The CMYK profile
+
+Adobe's CMYK profiles (U.S. Web Coated SWOP, Coated FOGRA39) are proprietary, and the freely
+downloadable characterisation-based profiles (ECI/FOGRA, colord, Ghostscript) carry
+redistribution conditions or unclear licences, so Photocraft generates its own
+(`src/synth.rs`): a Yule–Nielsen modified Neugebauer model (n = 2) over the 16 overprints with
+ISO 12647-2 coated-paper Lab aims for paper/C/M/Y/RGB overprints, parabolic dot gain (14 % CMY,
+17 % K at 50 %), GCR black generation (starts at 20 % gray component, K max 95 %), total ink
+limit 300 %, perceptual tables with L* black-point scaling and soft chroma compression against a
+sampled gamut boundary. `profiles/photocraft-coated-cmyk.icc` (237 KB, AToB 11⁴ lut16, BToA
+21³ lut16) is that output, dedicated to the public domain (CC0-1.0). Regenerate with
+
+```sh
+PHOTOCRAFT_REGEN_PROFILES=1 cargo test -p photocraft-cms --release --test regen
+```
+
+It is a plausible coated-offset profile, not a measured characterisation: use your printer's
+profile for production print.
+
+## Not implemented / approximate
+
+* v4.4 `mpet` (multiProcessElements, D2Bx/B2Dx) tags, named colour, device link and abstract
+ profiles as transform endpoints, `chad`-based adaptation of v2 absolute colorimetry.
+* BPC destination black uses the BToA/AToB round trip directly (Adobe's curve fit for
+ ill-behaved LUT profiles is not implemented); v2/v4 perceptual reference black mixing is not
+ modelled beyond the PRMG black for v4 LUT profiles.
+* Profile ID (MD5) is not computed when writing (left zero, which the spec allows).
diff --git a/crates/cms/profiles/photocraft-coated-cmyk.icc b/crates/cms/profiles/photocraft-coated-cmyk.icc
new file mode 100644
index 000000000..0d2d1da16
Binary files /dev/null and b/crates/cms/profiles/photocraft-coated-cmyk.icc differ
diff --git a/crates/cms/src/builtin.rs b/crates/cms/src/builtin.rs
new file mode 100644
index 000000000..9d3f6ee37
--- /dev/null
+++ b/crates/cms/src/builtin.rs
@@ -0,0 +1,263 @@
+//! Built-in profiles. All are generated by this crate from published colorimetric definitions
+//! (primaries, white points, transfer functions) and dedicated to the public domain (CC0-1.0),
+//! so documents that embed them carry no licence obligations. See the crate README.
+
+use std::sync::OnceLock;
+
+use crate::curve::{Curve, srgb_trc};
+use crate::math::{self, Mat3};
+use crate::pipeline::Stage;
+use crate::profile::{ColorSpace, Lut, LutKind, Pcs, Profile, ProfileClass};
+use crate::Intent;
+
+/// Copyright tag text of every built-in profile.
+pub const COPYRIGHT: &str = "No copyright: CC0-1.0 public domain dedication. Generated by photocraft-cms.";
+
+/// Identifiers of the built-in profiles.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Builtin {
+ /// sRGB IEC 61966-2.1 (Rec. 709 primaries, D65, sRGB transfer function).
+ Srgb,
+ /// Display P3 (DCI-P3 primaries, D65, sRGB transfer function).
+ DisplayP3,
+ /// Adobe RGB (1998)-compatible: its published primaries, D65, gamma 563/256.
+ AdobeRgbCompat,
+ /// ProPhoto-compatible: ROMM RGB primaries, D50, gamma 1.8.
+ ProPhotoCompat,
+ /// sRGB primaries with a linear transfer function.
+ LinearSrgb,
+ /// Rec. 2020 primaries, D65, Rec. 709 transfer function.
+ Rec2020,
+ /// Gray, gamma 2.2.
+ GrayGamma22,
+ /// Gray with the sRGB transfer function (sGray): gray `v` looks like RGB `(v, v, v)` in sRGB.
+ SGray,
+ /// CIE L*a*b* D50 identity (device Lab = PCS Lab, ICC v4 encoding).
+ LabD50,
+ /// Synthetic coated-offset CMYK (300 % total ink, medium GCR); see [`crate::synth`].
+ CoatedCmyk,
+}
+
+impl Builtin {
+ pub const ALL: [Builtin; 10] = [
+ Builtin::Srgb,
+ Builtin::DisplayP3,
+ Builtin::AdobeRgbCompat,
+ Builtin::ProPhotoCompat,
+ Builtin::LinearSrgb,
+ Builtin::Rec2020,
+ Builtin::GrayGamma22,
+ Builtin::SGray,
+ Builtin::LabD50,
+ Builtin::CoatedCmyk,
+ ];
+
+ /// Stable identifier used by commands and settings.
+ pub fn id(self) -> &'static str {
+ match self {
+ Builtin::Srgb => "srgb",
+ Builtin::DisplayP3 => "display-p3",
+ Builtin::AdobeRgbCompat => "adobe-rgb-compat",
+ Builtin::ProPhotoCompat => "prophoto-compat",
+ Builtin::LinearSrgb => "linear-srgb",
+ Builtin::Rec2020 => "rec2020",
+ Builtin::GrayGamma22 => "gray-gamma-2.2",
+ Builtin::SGray => "sgray",
+ Builtin::LabD50 => "lab-d50",
+ Builtin::CoatedCmyk => "coated-cmyk",
+ }
+ }
+
+ /// Profile description (the `desc` tag).
+ pub fn description(self) -> &'static str {
+ match self {
+ Builtin::Srgb => "sRGB IEC61966-2.1",
+ Builtin::DisplayP3 => "Display P3",
+ Builtin::AdobeRgbCompat => "Adobe RGB (1998)-compatible (Photocraft)",
+ Builtin::ProPhotoCompat => "ProPhoto RGB-compatible (ROMM primaries, Photocraft)",
+ Builtin::LinearSrgb => "Linear sRGB (Photocraft)",
+ Builtin::Rec2020 => "Rec. ITU-R BT.2020 (Photocraft)",
+ Builtin::GrayGamma22 => "Gray Gamma 2.2 (Photocraft)",
+ Builtin::SGray => "sGray (sRGB tone curve, Photocraft)",
+ Builtin::LabD50 => "Lab D50 identity (Photocraft)",
+ Builtin::CoatedCmyk => crate::synth::DESCRIPTION,
+ }
+ }
+
+ /// Looks up an id (case-insensitive; a few aliases and the descriptions are accepted).
+ pub fn from_id(s: &str) -> Option<Builtin> {
+ let n: String = s.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();
+ let alias = match n.as_str() {
+ "srgb" | "srgbiec6196621" | "srgbiec61966" => Some(Builtin::Srgb),
+ "p3" | "displayp3" => Some(Builtin::DisplayP3),
+ "adobergb" | "adobergb1998" | "adobergbcompat" | "clayrgb" => Some(Builtin::AdobeRgbCompat),
+ "prophoto" | "prophotorgb" | "prophotocompat" | "romm" | "rommrgb" => Some(Builtin::ProPhotoCompat),
+ "linearsrgb" | "srgblinear" | "linear" => Some(Builtin::LinearSrgb),
+ "rec2020" | "bt2020" => Some(Builtin::Rec2020),
+ "gray" | "graygamma22" | "gamma22" => Some(Builtin::GrayGamma22),
+ "sgray" | "graysrgb" => Some(Builtin::SGray),
+ "lab" | "labd50" | "cielab" => Some(Builtin::LabD50),
+ "cmyk" | "coatedcmyk" | "defaultcmyk" | "photocraftcoatedcmyk" => Some(Builtin::CoatedCmyk),
+ _ => None,
+ };
+ alias.or_else(|| Builtin::ALL.into_iter().find(|b| b.description().eq_ignore_ascii_case(s)))
+ }
+
+ /// The profile (built once per process).
+ pub fn profile(self) -> &'static Profile {
+ static CELLS: [OnceLock<Profile>; 10] = [const { OnceLock::new() }; 10];
+ let i = Builtin::ALL.iter().position(|b| *b == self).expect("listed");
+ CELLS[i].get_or_init(|| build(self))
+ }
+}
+
+/// The default profile for a colour space: sRGB, sGray, the coated CMYK profile, Lab D50.
+pub fn default_for(cs: ColorSpace) -> Option<&'static Profile> {
+ Some(match cs {
+ ColorSpace::Rgb => Builtin::Srgb.profile(),
+ ColorSpace::Gray => Builtin::SGray.profile(),
+ ColorSpace::Cmyk => Builtin::CoatedCmyk.profile(),
+ ColorSpace::Lab => Builtin::LabD50.profile(),
+ _ => return None,
+ })
+}
+
+pub fn srgb() -> &'static Profile {
+ Builtin::Srgb.profile()
+}
+
+/// The ICC D65 used for the RGB spaces (chromaticity 0.3127, 0.3290).
+fn d65() -> [f64; 3] {
+ math::xy_to_xyz(math::D65_XY)
+}
+
+/// Colorant matrix adapted to D50 and quantized to s15Fixed16, with each row nudged so that
+/// RGB (1, 1, 1) maps exactly to the stored D50 white (keeps neutrals neutral).
+fn colorants(r: [f64; 2], g: [f64; 2], b: [f64; 2], white: [f64; 3]) -> (Mat3, Option<Mat3>) {
+ let m = math::rgb_to_xyz_matrix(r, g, b, white);
+ let d50 = math::d50_quantized();
+ let adapt = if (white[0] - math::D50[0]).abs() < 1e-3 && (white[2] - math::D50[2]).abs() < 1e-3 { None } else { Some(math::bradford(white, math::D50)) };
+ let m50 = match &adapt {
+ Some(a) => math::mul(a, &m),
+ None => {
+ // White already (nearly) D50: scale rows onto the exact PCS white.
+ let s = math::apply(&m, [1.0, 1.0, 1.0]);
+ let mut o = m;
+ for (i, row) in o.iter_mut().enumerate() {
+ for v in row.iter_mut() {
+ *v *= math::D50[i] / s[i];
+ }
+ }
+ o
+ }
+ };
+ let mut q = m50.map(|row| row.map(math::s15f16_round));
+ for (i, row) in q.iter_mut().enumerate() {
+ let err = d50[i] - row.iter().sum::<f64>();
+ let k = (0..3).max_by(|a, b| row[*a].abs().total_cmp(&row[*b].abs())).unwrap_or(0);
+ row[k] = math::s15f16_round(row[k] + err);
+ }
+ (q, adapt.map(|a| a.map(|row| row.map(math::s15f16_round))))
+}
+
+fn rgb(desc: &str, prim: [[f64; 2]; 3], white: [f64; 3], trc: Curve) -> Profile {
+ let (m, chad) = colorants(prim[0], prim[1], prim[2], white);
+ Profile {
+ version: (4, 0x30),
+ class: ProfileClass::Display,
+ color_space: ColorSpace::Rgb,
+ pcs: Pcs::Xyz,
+ rendering_intent: Intent::Perceptual,
+ description: desc.into(),
+ copyright: COPYRIGHT.into(),
+ white_point: math::d50_quantized(),
+ black_point: None,
+ chad,
+ matrix: Some(m),
+ trc: Some([trc.clone(), trc.clone(), trc]),
+ gray_trc: None,
+ a2b: [None, None, None],
+ b2a: [None, None, None],
+ bytes: None,
+ hash: Default::default(),
+ }
+ .with_encoded_bytes()
+}
+
+fn gray(desc: &str, trc: Curve) -> Profile {
+ Profile {
+ version: (4, 0x30),
+ class: ProfileClass::Display,
+ color_space: ColorSpace::Gray,
+ pcs: Pcs::Xyz,
+ rendering_intent: Intent::Perceptual,
+ description: desc.into(),
+ copyright: COPYRIGHT.into(),
+ white_point: math::d50_quantized(),
+ black_point: None,
+ chad: None,
+ matrix: None,
+ trc: None,
+ gray_trc: Some(trc),
+ a2b: [None, None, None],
+ b2a: [None, None, None],
+ bytes: None,
+ hash: Default::default(),
+ }
+ .with_encoded_bytes()
+}
+
+fn lab() -> Profile {
+ let ident = || Lut { kind: LutKind::Ab, inputs: 3, outputs: 3, stages: vec![Stage::Curves(vec![Curve::Identity; 3])] };
+ Profile {
+ version: (4, 0x30),
+ class: ProfileClass::ColorSpace,
+ color_space: ColorSpace::Lab,
+ pcs: Pcs::Lab,
+ rendering_intent: Intent::Perceptual,
+ description: Builtin::LabD50.description().into(),
+ copyright: COPYRIGHT.into(),
+ white_point: math::d50_quantized(),
+ black_point: None,
+ chad: None,
+ matrix: None,
+ trc: None,
+ gray_trc: None,
+ a2b: [Some(ident()), None, None],
+ b2a: [Some(ident()), None, None],
+ bytes: None,
+ hash: Default::default(),
+ }
+ .with_encoded_bytes()
+}
+
+/// The shipped synthetic CMYK profile (generated by [`crate::synth::coated_cmyk`]; regenerate
+/// with `PHOTOCRAFT_REGEN_PROFILES=1 cargo test -p photocraft-cms --release regen`).
+pub const COATED_CMYK_ICC: &[u8] = include_bytes!("../profiles/photocraft-coated-cmyk.icc");
+
+fn build(b: Builtin) -> Profile {
+ let (srgb_p, p3, adobe, romm, bt2020) = (
+ [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06]],
+ [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]],
+ [[0.64, 0.33], [0.21, 0.71], [0.15, 0.06]],
+ [[0.7347, 0.2653], [0.1596, 0.8404], [0.0366, 0.0001]],
+ [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]],
+ );
+ match b {
+ Builtin::Srgb => rgb(b.description(), srgb_p, d65(), srgb_trc()),
+ Builtin::DisplayP3 => rgb(b.description(), p3, d65(), srgb_trc()),
+ Builtin::AdobeRgbCompat => rgb(b.description(), adobe, d65(), Curve::Gamma(563.0 / 256.0)),
+ Builtin::ProPhotoCompat => rgb(b.description(), romm, math::D50, Curve::Gamma(1.8)),
+ Builtin::LinearSrgb => rgb(b.description(), srgb_p, d65(), Curve::Gamma(1.0)),
+ Builtin::Rec2020 => {
+ // Rec. 709 OETF inverse: V = 1.099 L^0.45 − 0.099 (L ≥ 0.018), 4.5 L below.
+ let a = 1.099;
+ let trc = Curve::Parametric { kind: 3, p: [1.0 / 0.45, 1.0 / a, (a - 1.0) / a, 1.0 / 4.5, 0.081, 0.0, 0.0] };
+ rgb(b.description(), bt2020, d65(), trc)
+ }
+ Builtin::GrayGamma22 => gray(b.description(), Curve::Gamma(2.2)),
+ Builtin::SGray => gray(b.description(), srgb_trc()),
+ Builtin::LabD50 => lab(),
+ Builtin::CoatedCmyk => Profile::parse(COATED_CMYK_ICC).expect("shipped CMYK profile parses"),
+ }
+}
diff --git a/crates/cms/src/clut.rs b/crates/cms/src/clut.rs
index 0606f1d1a..186cd3f9f 100644
--- a/crates/cms/src/clut.rs
+++ b/crates/cms/src/clut.rs
@@ -186,8 +186,8 @@ impl Clut {
if w == 0.0 {
continue;
}
- for k in 0..o {
- out[k] += w * self.data[off + k];
+ for (k, v) in out[..o].iter_mut().enumerate() {
+ *v += w * self.data[off + k];
}
}
}
diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs
new file mode 100644
index 000000000..8b1abe1dd
--- /dev/null
+++ b/crates/cms/src/gamut.rs
@@ -0,0 +1,78 @@
+//! Gamut checks against a proof (output) profile: Photoshop's View › Gamut Warning.
+
+use crate::clut::Clut;
+use crate::pipeline::{Pipeline, Stage};
+use crate::profile::Profile;
+use crate::transform::link_stages;
+use crate::{CmsError, Intent};
+
+/// Default ΔE76 threshold above which a colour counts as out of gamut.
+pub const DEFAULT_THRESHOLD: f32 = 4.0;
+
+/// Precomputed out-of-gamut test for colours of `src` against `proof`.
+///
+/// A colour is out of gamut when sending it to the proof device (relative colorimetric,
+/// clipping) and back to Lab moves it by more than the threshold (ΔE76). The ΔE is tabulated
+/// over the source device space (33³ grid for 3 channels, 17⁴ for 4, exact otherwise).
+#[derive(Debug)]
+pub struct GamutCheck {
+ inputs: usize,
+ grid: Option<Clut>,
+ exact: (Pipeline, Pipeline),
+ pub threshold: f32,
+}
+
+impl GamutCheck {
+ pub fn new(src: &Profile, proof: &Profile, threshold: f32) -> Result<GamutCheck, CmsError> {
+ let lab = crate::Builtin::LabD50.profile();
+ let direct = Pipeline::new(src.channels(), link_stages(src, lab, Intent::RelativeColorimetric, false)?);
+ let mut via = link_stages(src, proof, Intent::RelativeColorimetric, false)?;
+ via.push(Stage::Clamp01);
+ via.extend(link_stages(proof, lab, Intent::RelativeColorimetric, false)?);
+ let via = Pipeline::new(src.channels(), via);
+ let de = |p: &[f32], o: &mut [f32]| {
+ let (mut a, mut b) = ([0.0f32; 16], [0.0f32; 16]);
+ direct.eval(p, &mut a);
+ via.eval(p, &mut b);
+ let d = |i: usize, s: f32| (a[i] - b[i]) * s;
+ o[0] = (d(0, 100.0).powi(2) + d(1, 255.0).powi(2) + d(2, 255.0).powi(2)).sqrt();
+ };
+ let n = src.channels();
+ let grid = match n {
+ 1 => Some(Clut::sample(vec![256], 1, de)),
+ 3 => Some(Clut::sample(vec![33; 3], 1, de)),
+ 4 => Some(Clut::sample(vec![17; 4], 1, de)),
+ _ => None,
+ };
+ Ok(GamutCheck { inputs: n, grid, exact: (direct, via), threshold })
+ }
+
+ pub fn inputs(&self) -> usize {
+ self.inputs
+ }
+
+ /// ΔE76 between the colour and its proof round trip.
+ pub fn delta_e(&self, px: &[f32]) -> f32 {
+ let mut o = [0.0f32; 1];
+ match &self.grid {
+ Some(g) => {
+ let mut c = [0.0f32; 16];
+ for (d, s) in c.iter_mut().zip(&px[..self.inputs]) {
+ *d = s.clamp(0.0, 1.0);
+ }
+ g.eval(&c[..self.inputs], &mut o);
+ }
+ None => {
+ let (mut a, mut b) = ([0.0f32; 16], [0.0f32; 16]);
+ self.exact.0.eval(px, &mut a);
+ self.exact.1.eval(px, &mut b);
+ o[0] = ((a[0] - b[0]) * 100.0).hypot((a[1] - b[1]) * 255.0).hypot((a[2] - b[2]) * 255.0);
+ }
+ }
+ o[0]
+ }
+
+ pub fn out_of_gamut(&self, px: &[f32]) -> bool {
+ self.delta_e(px) > self.threshold
+ }
+}
diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs
index 4c1a0dafc..ba2761367 100644
--- a/crates/cms/src/lib.rs
+++ b/crates/cms/src/lib.rs
@@ -1,2 +1,105 @@
-//! Photocraft colour management (placeholder while the crate is being written).
+//! Photocraft colour management: a pure-Rust ICC v2/v4 colour management module.
+//!
+//! * [`Profile`] parses ICC profiles (matrix/TRC RGB, gray TRC, `mft1`/`mft2`/`mAB `/`mBA `
+//! LUT profiles incl. CMYK↔Lab, `curv`/`para` curves) and writes ICC v4 profiles.
+//! * [`Transform`] connects two profiles through the PCS (XYZ/Lab D50) with a rendering
+//! [`Intent`] and optional black point compensation, and converts 8/16-bit and float pixel
+//! buffers through precomputed tables (tetrahedral 3D/4D interpolation, rayon on native).
+//! * [`builtin`] ships sRGB, Display P3, Adobe RGB (1998)-compatible, ProPhoto-compatible,
+//! linear sRGB, Rec. 2020, Gray 2.2, sGray, Lab D50 and a synthetic coated CMYK profile.
+//! * [`Lut3d`] samples a display transform into a 3D texture for the GPU canvas.
+//!
+//! Implemented from the public ICC.1:2010 (v4.3) and ICC.1:2001-04 (v2) specifications,
+//! CIE 15, and Adobe's published black point compensation paper. This crate depends on no
+//! other workspace crate.
#![forbid(unsafe_code)]
+
+pub mod builtin;
+pub mod clut;
+pub mod curve;
+pub mod gamut;
+pub mod lut3d;
+pub mod lutfile;
+pub mod math;
+pub mod pipeline;
+pub mod profile;
+pub mod synth;
+pub mod transform;
+mod write;
+
+pub use builtin::Builtin;
+pub use clut::Clut;
+pub use curve::Curve;
+pub use gamut::GamutCheck;
+pub use lut3d::Lut3d;
+pub use profile::{ColorSpace, Pcs, Profile, ProfileClass};
+pub use transform::{SampleKind, Transform, TransformOptions, black_point, cached};
+
+/// ICC rendering intent.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
+pub enum Intent {
+ Perceptual = 0,
+ #[default]
+ RelativeColorimetric = 1,
+ Saturation = 2,
+ AbsoluteColorimetric = 3,
+}
+
+impl Intent {
+ pub const ALL: [Intent; 4] = [Intent::Perceptual, Intent::RelativeColorimetric, Intent::Saturation, Intent::AbsoluteColorimetric];
+
+ pub fn from_u32(v: u32) -> Option<Intent> {
+ Some(match v {
+ 0 => Intent::Perceptual,
+ 1 => Intent::RelativeColorimetric,
+ 2 => Intent::Saturation,
+ 3 => Intent::AbsoluteColorimetric,
+ _ => return None,
+ })
+ }
+
+ /// Parses `perceptual`, `relative`/`relativeColorimetric`, `saturation`,
+ /// `absolute`/`absoluteColorimetric` (case-insensitive).
+ pub fn parse(s: &str) -> Option<Intent> {
+ let n: String = s.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();
+ Some(match n.as_str() {
+ "perceptual" | "0" => Intent::Perceptual,
+ "relative" | "relativecolorimetric" | "colorimetric" | "1" => Intent::RelativeColorimetric,
+ "saturation" | "2" => Intent::Saturation,
+ "absolute" | "absolutecolorimetric" | "3" => Intent::AbsoluteColorimetric,
+ _ => return None,
+ })
+ }
+
+ pub fn id(self) -> &'static str {
+ match self {
+ Intent::Perceptual => "perceptual",
+ Intent::RelativeColorimetric => "relative",
+ Intent::Saturation => "saturation",
+ Intent::AbsoluteColorimetric => "absolute",
+ }
+ }
+}
+
+/// Errors from parsing profiles or building transforms.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum CmsError {
+ Truncated,
+ /// Missing `acsp` signature: not an ICC profile.
+ BadSignature,
+ Invalid(String),
+ Unsupported(String),
+}
+
+impl std::fmt::Display for CmsError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ CmsError::Truncated => write!(f, "ICC profile is truncated"),
+ CmsError::BadSignature => write!(f, "not an ICC profile (missing 'acsp' signature)"),
+ CmsError::Invalid(m) => write!(f, "invalid ICC profile: {m}"),
+ CmsError::Unsupported(m) => write!(f, "unsupported ICC feature: {m}"),
+ }
+ }
+}
+
+impl std::error::Error for CmsError {}
diff --git a/crates/cms/src/lut3d.rs b/crates/cms/src/lut3d.rs
new file mode 100644
index 000000000..f38112ff4
--- /dev/null
+++ b/crates/cms/src/lut3d.rs
@@ -0,0 +1,143 @@
+//! 3D lookup tables for applying a display transform on the GPU.
+
+use crate::Transform;
+
+/// An `size³` RGBA lookup table: entry `r + g·size + b·size²` holds the output for input
+/// `(r, g, b) / (size − 1)`, alpha 1. This is the memory order of a 3D texture whose x axis is
+/// red, so it uploads directly (sample at `(c·(size−1) + 0.5) / size` with linear filtering).
+#[derive(Clone, Debug, PartialEq)]
+pub struct Lut3d {
+ pub size: usize,
+ pub data: Vec<[f32; 4]>,
+}
+
+impl Lut3d {
+ /// Samples a 3-input transform (1-output transforms are replicated to gray).
+ pub fn from_transform(t: &Transform, size: usize) -> Lut3d {
+ assert!(t.inputs() == 3 && (t.outputs() == 3 || t.outputs() == 1), "display LUTs need a 3→3 or 3→1 transform");
+ assert!(size >= 2, "LUT size");
+ let mut data = vec![[0.0f32, 0.0, 0.0, 1.0]; size * size * size];
+ let s = (size - 1) as f32;
+ let mut out = [0.0f32; 16];
+ for b in 0..size {
+ for g in 0..size {
+ for r in 0..size {
+ t.eval(&[r as f32 / s, g as f32 / s, b as f32 / s], &mut out);
+ let v = if t.outputs() == 1 { [out[0]; 3] } else { [out[0], out[1], out[2]] };
+ data[r + g * size + b * size * size] = [v[0], v[1], v[2], 1.0];
+ }
+ }
+ }
+ Lut3d { size, data }
+ }
+
+ /// Trilinear lookup (what GPU filtering computes).
+ pub fn sample(&self, rgb: [f32; 3]) -> [f32; 3] {
+ let n = self.size;
+ let loc = |v: f32| {
+ let p = v.clamp(0.0, 1.0) * (n - 1) as f32;
+ let i = (p as usize).min(n - 2);
+ (i, p - i as f32)
+ };
+ let (r0, fr) = loc(rgb[0]);
+ let (g0, fg) = loc(rgb[1]);
+ let (b0, fb) = loc(rgb[2]);
+ let at = |r: usize, g: usize, b: usize| self.data[r + g * n + b * n * n];
+ let mut o = [0.0f32; 3];
+ for (k, ov) in o.iter_mut().enumerate() {
+ let c = |r, g, b| at(r, g, b)[k];
+ let x00 = c(r0, g0, b0) + (c(r0 + 1, g0, b0) - c(r0, g0, b0)) * fr;
+ let x10 = c(r0, g0 + 1, b0) + (c(r0 + 1, g0 + 1, b0) - c(r0, g0 + 1, b0)) * fr;
+ let x01 = c(r0, g0, b0 + 1) + (c(r0 + 1, g0, b0 + 1) - c(r0, g0, b0 + 1)) * fr;
+ let x11 = c(r0, g0 + 1, b0 + 1) + (c(r0 + 1, g0 + 1, b0 + 1) - c(r0, g0 + 1, b0 + 1)) * fr;
+ let y0 = x00 + (x10 - x00) * fg;
+ let y1 = x01 + (x11 - x01) * fg;
+ *ov = y0 + (y1 - y0) * fb;
+ }
+ o
+ }
+
+ /// Little-endian RGBA16F texels (8 bytes each), e.g. for `wgpu::TextureFormat::Rgba16Float`.
+ pub fn to_rgba16f_bytes(&self) -> Vec<u8> {
+ let mut o = Vec::with_capacity(self.data.len() * 8);
+ for px in &self.data {
+ for v in px {
+ o.extend_from_slice(&f32_to_f16(*v).to_le_bytes());
+ }
+ }
+ o
+ }
+
+ /// RGBA8 texels (for backends without float 3D textures).
+ pub fn to_rgba8(&self) -> Vec<u8> {
+ self.data.iter().flat_map(|p| p.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)).collect()
+ }
+}
+
+/// IEEE 754 binary16 bits of `v` (round to nearest even; overflow → ±inf, NaN kept).
+pub fn f32_to_f16(v: f32) -> u16 {
+ let x = v.to_bits();
+ let sign = ((x >> 16) & 0x8000) as u16;
+ let exp = ((x >> 23) & 0xFF) as i32;
+ let man = x & 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 rem = m & ((1 << shift) - 1);
+ let mut r = m >> shift;
+ if rem > half || (rem == half && r & 1 == 1) {
+ r += 1;
+ }
+ return sign | r as u16;
+ }
+ let mut r = ((e as u32) << 10) | (man >> 13);
+ let rem = man & 0x1FFF;
+ if rem > 0x1000 || (rem == 0x1000 && r & 1 == 1) {
+ r += 1;
+ }
+ sign | r as u16
+}
+
+/// binary16 bits → f32.
+pub fn f16_to_f32(h: u16) -> f32 {
+ let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 };
+ let e = ((h >> 10) & 0x1F) as i32;
+ let m = (h & 0x3FF) as f32;
+ match e {
+ 0 => sign * m * 2f32.powi(-24),
+ 0x1F => {
+ if m == 0.0 {
+ sign * f32::INFINITY
+ } else {
+ f32::NAN
+ }
+ }
+ _ => sign * (1.0 + m / 1024.0) * 2f32.powi(e - 15),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn half_float_roundtrip() {
+ for v in [0.0f32, 1.0, 0.5, 0.333, 1e-5, 65504.0, -2.25, 0.1] {
+ let back = f16_to_f32(f32_to_f16(v));
+ assert!((back - v).abs() <= v.abs() * 1e-3 + 1e-7, "{v} -> {back}");
+ }
+ assert_eq!(f32_to_f16(1.0), 0x3C00);
+ assert_eq!(f32_to_f16(1e6), 0x7C00);
+ }
+}
diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs
new file mode 100644
index 000000000..4e81cafae
--- /dev/null
+++ b/crates/cms/src/lutfile.rs
@@ -0,0 +1,421 @@
+//! Creative 3D LUT files for Image › Adjustments › Color Lookup: `.cube` (Adobe/Resolve), `.3dl`
+//! (Autodesk Lustre / Flame) and `.look` (SpeedGrade XML), plus a few generated (CC0) looks.
+//!
+//! Every table is normalised to [`LutFile`]: `size`³ RGB triplets in 0..=1, **red varying
+//! fastest** (`((b·size + g)·size + r)·3`). Formats follow their public descriptions: the Adobe
+//! "Cube LUT Specification 1.0", the Lustre 3DL layout as documented by OpenColorIO, and the
+//! SpeedGrade `.look` XML (hex-encoded little-endian float32 RGB triplets).
+
+/// A parsed 3D LUT.
+#[derive(Clone, Debug, PartialEq)]
+pub struct LutFile {
+ pub title: String,
+ pub size: usize,
+ /// `size`³ × 3 values, red fastest.
+ pub data: Vec<f32>,
+}
+
+/// Largest edge length accepted (64³ is Photoshop's practical maximum; 129 leaves headroom while
+/// keeping the GPU table within texture limits).
+pub const MAX_SIZE: usize = 129;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct LutError(pub String);
+
+impl std::fmt::Display for LutError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+impl std::error::Error for LutError {}
+
+fn err<T>(msg: impl Into<String>) -> Result<T, LutError> {
+ Err(LutError(msg.into()))
+}
+
+impl LutFile {
+ /// The identity table of edge `size`.
+ pub fn identity(size: usize) -> Self {
+ Self::from_fn("Identity", size, |c| c)
+ }
+
+ /// Samples `f` on an `size`³ grid.
+ pub fn from_fn(title: &str, size: usize, f: impl Fn([f32; 3]) -> [f32; 3]) -> Self {
+ let m = (size.max(2) - 1) as f32;
+ let mut data = Vec::with_capacity(size * size * size * 3);
+ for b in 0..size {
+ for g in 0..size {
+ for r in 0..size {
+ let o = f([r as f32 / m, g as f32 / m, b as f32 / m]);
+ data.extend(o.map(|v| v.clamp(0.0, 1.0)));
+ }
+ }
+ }
+ LutFile {
+ title: title.to_string(),
+ size,
+ data,
+ }
+ }
+
+ fn check(self) -> Result<Self, LutError> {
+ if self.size < 2 || self.size > MAX_SIZE {
+ return err(format!("unsupported LUT size {}", self.size));
+ }
+ if self.data.len() != self.size.pow(3) * 3 {
+ return err(format!(
+ "expected {} entries, found {}",
+ self.size.pow(3),
+ self.data.len() / 3
+ ));
+ }
+ if self.data.iter().any(|v| !v.is_finite()) {
+ return err("non-finite LUT value");
+ }
+ Ok(self)
+ }
+}
+
+/// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing).
+pub fn parse(file_name: &str, bytes: &[u8]) -> Result<LutFile, LutError> {
+ let lower = file_name.to_ascii_lowercase();
+ let text = String::from_utf8_lossy(bytes);
+ if lower.ends_with(".3dl") {
+ parse_3dl(&text)
+ } else if lower.ends_with(".look") || text.trim_start().starts_with('<') {
+ parse_look(&text)
+ } else {
+ parse_cube(&text)
+ }
+}
+
+/// Adobe / Resolve `.cube`. 1D LUTs (`LUT_1D_SIZE`) are expanded to a 33³ table.
+pub fn parse_cube(text: &str) -> Result<LutFile, LutError> {
+ let mut title = String::new();
+ let (mut size3, mut size1) = (0usize, 0usize);
+ let (mut dmin, mut dmax) = ([0.0f32; 3], [1.0f32; 3]);
+ let mut rows: Vec<f32> = Vec::new();
+ for line in text.lines() {
+ let line = line.split('#').next().unwrap_or("").trim();
+ if line.is_empty() {
+ continue;
+ }
+ let mut it = line.split_whitespace();
+ let key = it.next().unwrap_or("");
+ let nums = |it: std::str::SplitWhitespace<'_>| -> Result<[f32; 3], LutError> {
+ let v: Vec<f32> = it.filter_map(|s| s.parse().ok()).collect();
+ if v.len() == 3 {
+ Ok([v[0], v[1], v[2]])
+ } else {
+ err(format!("bad line `{line}`"))
+ }
+ };
+ match key {
+ "TITLE" => title = line[5..].trim().trim_matches('"').to_string(),
+ "LUT_3D_SIZE" => {
+ size3 = it
+ .next()
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| LutError("bad LUT_3D_SIZE".into()))?
+ }
+ "LUT_1D_SIZE" => {
+ size1 = it
+ .next()
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| LutError("bad LUT_1D_SIZE".into()))?
+ }
+ "DOMAIN_MIN" => dmin = nums(it)?,
+ "DOMAIN_MAX" => dmax = nums(it)?,
+ "LUT_3D_INPUT_RANGE" | "LUT_1D_INPUT_RANGE" => {
+ let v: Vec<f32> = it.filter_map(|s| s.parse().ok()).collect();
+ if v.len() == 2 {
+ dmin = [v[0]; 3];
+ dmax = [v[1]; 3];
+ }
+ }
+ k if k
+ .starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '+' || c == '.') =>
+ {
+ let mut v = vec![
+ k.parse::<f32>()
+ .map_err(|_| LutError(format!("bad number in `{line}`")))?,
+ ];
+ v.extend(it.filter_map(|s| s.parse::<f32>().ok()));
+ if v.len() != 3 {
+ return err(format!("bad data line `{line}`"));
+ }
+ rows.extend(v);
+ }
+ // Unknown keywords (e.g. Resolve's LUT_IN_VIDEO_RANGE) are ignored, as the spec allows.
+ _ => {}
+ }
+ }
+ let _ = (dmin, dmax); // Domain other than 0..1 only shifts input sampling; we assume 0..1 inputs.
+ if size3 > 0 {
+ return LutFile {
+ title,
+ size: size3,
+ data: rows,
+ }
+ .check();
+ }
+ if size1 >= 2 && rows.len() == size1 * 3 {
+ let curve = |ch: usize, v: f32| {
+ let x = v.clamp(0.0, 1.0) * (size1 - 1) as f32;
+ let i = (x.floor() as usize).min(size1 - 2);
+ let f = x - i as f32;
+ rows[i * 3 + ch] * (1.0 - f) + rows[(i + 1) * 3 + ch] * f
+ };
+ let mut l = LutFile::from_fn(&title, 33, |c| {
+ [curve(0, c[0]), curve(1, c[1]), curve(2, c[2])]
+ });
+ l.title = title;
+ return l.check();
+ }
+ err("no LUT_3D_SIZE in .cube file")
+}
+
+/// Lustre `.3dl`: an optional shaper line of input values, then integer RGB rows with **blue**
+/// varying fastest; the output bit depth is inferred from the largest value.
+pub fn parse_3dl(text: &str) -> Result<LutFile, LutError> {
+ let mut rows: Vec<[f64; 3]> = Vec::new();
+ for line in text.lines() {
+ let line = line.split('#').next().unwrap_or("").trim();
+ if line.is_empty() || line.starts_with(|c: char| c.is_ascii_alphabetic()) {
+ continue;
+ }
+ let v: Vec<f64> = line
+ .split_whitespace()
+ .filter_map(|s| s.parse().ok())
+ .collect();
+ if v.len() == 3 {
+ rows.push([v[0], v[1], v[2]]);
+ }
+ // Lines with more than three numbers are the input shaper; it is assumed linear.
+ }
+ let n = (rows.len() as f64).cbrt().round() as usize;
+ if n < 2 || n * n * n != rows.len() {
+ return err(format!("{} rows is not a cube", rows.len()));
+ }
+ let max = rows.iter().flatten().fold(0.0f64, |a, &b| a.max(b));
+ let scale = if max <= 1.0 {
+ 1.0
+ } else {
+ [1023.0, 4095.0, 16383.0, 65535.0]
+ .into_iter()
+ .find(|&s| max <= s)
+ .unwrap_or(max)
+ };
+ let mut data = vec![0.0f32; n * n * n * 3];
+ for (i, row) in rows.iter().enumerate() {
+ let (r, g, b) = (i / (n * n), (i / n) % n, i % n);
+ let at = ((b * n + g) * n + r) * 3;
+ for k in 0..3 {
+ data[at + k] = (row[k] / scale) as f32;
+ }
+ }
+ LutFile {
+ title: String::new(),
+ size: n,
+ data,
+ }
+ .check()
+}
+
+/// SpeedGrade `.look`: `<size>` and a hex `<data>` string of little-endian float32 RGB triplets
+/// (red fastest).
+pub fn parse_look(text: &str) -> Result<LutFile, LutError> {
+ let tag = |name: &str| -> Option<String> {
+ let open = format!("<{name}>");
+ let start = text.find(&open)? + open.len();
+ let end = text[start..].find(&format!("</{name}>"))? + start;
+ Some(text[start..end].trim().trim_matches('"').trim().to_string())
+ };
+ let size: usize = tag("size")
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| LutError("no <size> in .look".into()))?;
+ let hex: Vec<u8> = tag("data")
+ .ok_or_else(|| LutError("no <data> in .look".into()))?
+ .bytes()
+ .filter(u8::is_ascii_hexdigit)
+ .collect();
+ let nib = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8;
+ let bytes: Vec<u8> = hex
+ .chunks_exact(2)
+ .map(|p| nib(p[0]) << 4 | nib(p[1]))
+ .collect();
+ let floats: Vec<f32> = bytes
+ .chunks_exact(4)
+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
+ .collect();
+ let n3 = size.pow(3);
+ let data = if floats.len() == n3 * 4 {
+ floats
+ .chunks_exact(4)
+ .flat_map(|c| [c[0], c[1], c[2]])
+ .collect()
+ } else {
+ floats
+ };
+ LutFile {
+ title: tag("title").unwrap_or_default(),
+ size,
+ data,
+ }
+ .check()
+}
+
+/// Writes a `.cube` file (what Photoshop embeds in a Color Lookup layer).
+pub fn write_cube(l: &LutFile) -> String {
+ let mut s = String::new();
+ if !l.title.is_empty() {
+ s.push_str(&format!("TITLE \"{}\"\n", l.title.replace('"', "'")));
+ }
+ s.push_str(&format!("LUT_3D_SIZE {}\n", l.size));
+ for c in l.data.chunks_exact(3) {
+ s.push_str(&format!("{:.6} {:.6} {:.6}\n", c[0], c[1], c[2]));
+ }
+ s
+}
+
+fn luma(c: [f32; 3]) -> f32 {
+ 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]
+}
+
+fn smooth(x: f32) -> f32 {
+ let x = x.clamp(0.0, 1.0);
+ x * x * (3.0 - 2.0 * x)
+}
+
+/// Generated looks shipped with Photocraft (procedural, CC0): `(id, label)`.
+pub const BUILTIN: [(&str, &str); 8] = [
+ ("warm", "Warm Filter"),
+ ("cool", "Cool Filter"),
+ ("tealOrange", "Teal & Orange"),
+ ("bleachBypass", "Bleach Bypass"),
+ ("fadedFilm", "Faded Film"),
+ ("dayForNight", "Day for Night"),
+ ("monoContrast", "Mono High Contrast"),
+ ("crossProcess", "Cross Process"),
+];
+
+/// A built-in look by id (33³), or None.
+pub fn builtin(id: &str) -> Option<LutFile> {
+ let label = BUILTIN.iter().find(|b| b.0 == id)?.1;
+ let f: Box<dyn Fn([f32; 3]) -> [f32; 3]> = match id {
+ "warm" => Box::new(|c: [f32; 3]| [c[0] * 0.92 + 0.08, c[1] * 0.97 + 0.02, c[2] * 0.85]),
+ "cool" => Box::new(|c: [f32; 3]| [c[0] * 0.86, c[1] * 0.97 + 0.01, c[2] * 0.9 + 0.1]),
+ "tealOrange" => Box::new(|c: [f32; 3]| {
+ // Shadows toward teal, highlights toward orange, skin-ish midtones kept.
+ let l = luma(c);
+ let t = smooth(l);
+ let teal = [0.0, 0.5, 0.55];
+ let orange = [1.0, 0.62, 0.3];
+ std::array::from_fn(|k| {
+ let tint = teal[k] * (1.0 - t) + orange[k] * t;
+ c[k] * 0.75 + (tint * l * 1.1).min(1.0) * 0.25 + (smooth(c[k]) - c[k]) * 0.3
+ })
+ }),
+ "bleachBypass" => Box::new(|c: [f32; 3]| {
+ let l = luma(c);
+ let s = smooth(l);
+ std::array::from_fn(|k| {
+ let desat = c[k] * 0.45 + l * 0.55;
+ desat * 0.5 + s * 0.5
+ })
+ }),
+ "fadedFilm" => Box::new(|c: [f32; 3]| {
+ let l = luma(c);
+ let tint = [1.0, 0.96, 0.88];
+ std::array::from_fn(|k| (0.08 + (c[k] * 0.8 + l * 0.2) * 0.84) * tint[k] + 0.02)
+ }),
+ "dayForNight" => Box::new(|c: [f32; 3]| {
+ let l = luma(c);
+ [l * 0.35, l * 0.45 + c[1] * 0.05, l * 0.65 + c[2] * 0.15]
+ }),
+ "monoContrast" => Box::new(|c: [f32; 3]| [smooth(smooth(luma(c))); 3]),
+ _ /* crossProcess */ => Box::new(|c: [f32; 3]| [smooth(c[0]) * 1.05, c[1] * 1.1 - 0.03, c[2] * 0.7 + 0.15]),
+ };
+ Some(LutFile::from_fn(label, 33, f))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cube_roundtrip_and_identity() {
+ let id = LutFile::identity(5);
+ let text = write_cube(&LutFile {
+ title: "Id".into(),
+ ..id.clone()
+ });
+ let back = parse_cube(&text).unwrap();
+ assert_eq!(back.size, 5);
+ assert_eq!(back.title, "Id");
+ for (a, b) in back.data.iter().zip(&id.data) {
+ assert!((a - b).abs() < 1e-5);
+ }
+ // Red varies fastest: entry 1 is (0.25, 0, 0).
+ assert_eq!(&back.data[3..6], &[0.25, 0.0, 0.0]);
+ }
+
+ #[test]
+ fn cube_1d_expands() {
+ let text = "LUT_1D_SIZE 2\n0 0 0\n0.5 1 1\n";
+ let l = parse_cube(text).unwrap();
+ assert_eq!(l.size, 33);
+ let last = &l.data[l.data.len() - 3..];
+ assert!((last[0] - 0.5).abs() < 1e-6 && (last[1] - 1.0).abs() < 1e-6);
+ }
+
+ #[test]
+ fn three_dl_blue_fastest_and_bit_depth() {
+ let mut text = String::from("0 1023\n");
+ for r in 0..2 {
+ for g in 0..2 {
+ for b in 0..2 {
+ text.push_str(&format!("{} {} {}\n", r * 4095, g * 4095, b * 4095));
+ }
+ }
+ }
+ let l = parse_3dl(&text).unwrap();
+ assert_eq!(l.size, 2);
+ assert_eq!(l.data, LutFile::identity(2).data);
+ }
+
+ #[test]
+ fn look_hex_floats() {
+ let id = LutFile::identity(2);
+ let hex: String = id
+ .data
+ .iter()
+ .flat_map(|v| v.to_le_bytes())
+ .map(|b| format!("{b:02X}"))
+ .collect();
+ let xml = format!(
+ "<?xml version=\"1.0\"?><look><LUT><size>\"2\"</size><data>\"{hex}\"</data></LUT></look>"
+ );
+ assert_eq!(parse("a.look", xml.as_bytes()).unwrap().data, id.data);
+ }
+
+ #[test]
+ fn malformed_rejected() {
+ assert!(parse_cube("LUT_3D_SIZE 2\n0 0 0\n").is_err());
+ assert!(parse_cube("garbage").is_err());
+ assert!(parse_cube("LUT_3D_SIZE 99999\n").is_err());
+ assert!(parse_3dl("1 2 3\n4 5 6\n").is_err());
+ assert!(parse_look("<look></look>").is_err());
+ }
+
+ #[test]
+ fn builtins_exist_and_are_in_range() {
+ for (id, _) in BUILTIN {
+ let l = builtin(id).unwrap();
+ assert_eq!(l.data.len(), 33 * 33 * 33 * 3);
+ assert!(l.data.iter().all(|v| (0.0..=1.0).contains(v)), "{id}");
+ }
+ assert!(builtin("nope").is_none());
+ }
+}
diff --git a/crates/cms/src/profile.rs b/crates/cms/src/profile.rs
new file mode 100644
index 000000000..d509805d6
--- /dev/null
+++ b/crates/cms/src/profile.rs
@@ -0,0 +1,732 @@
+//! ICC profiles: the parsed model, the reader (ICC.1:2001-04 v2 and ICC.1:2010 v4) and the
+//! connection of a profile to the PCS as evaluation stages.
+
+use std::sync::Arc;
+
+use crate::clut::Clut;
+use crate::curve::Curve;
+use crate::math::{self, Mat3};
+use crate::pipeline::Stage;
+use crate::{CmsError, Intent};
+
+/// Profile/device class (header bytes 12..16).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum ProfileClass {
+ Input,
+ Display,
+ Output,
+ DeviceLink,
+ ColorSpace,
+ Abstract,
+ NamedColor,
+ Unknown(u32),
+}
+
+impl ProfileClass {
+ pub fn from_sig(s: u32) -> Self {
+ match &s.to_be_bytes() {
+ b"scnr" => Self::Input,
+ b"mntr" => Self::Display,
+ b"prtr" => Self::Output,
+ b"link" => Self::DeviceLink,
+ b"spac" => Self::ColorSpace,
+ b"abst" => Self::Abstract,
+ b"nmcl" => Self::NamedColor,
+ _ => Self::Unknown(s),
+ }
+ }
+ pub fn sig(self) -> u32 {
+ u32::from_be_bytes(*match self {
+ Self::Input => b"scnr",
+ Self::Display => b"mntr",
+ Self::Output => b"prtr",
+ Self::DeviceLink => b"link",
+ Self::ColorSpace => b"spac",
+ Self::Abstract => b"abst",
+ Self::NamedColor => b"nmcl",
+ Self::Unknown(s) => return s,
+ })
+ }
+}
+
+/// Data colour space (header bytes 16..20).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum ColorSpace {
+ Xyz,
+ Lab,
+ Luv,
+ YCbCr,
+ Yxy,
+ Rgb,
+ Gray,
+ Hsv,
+ Hls,
+ Cmyk,
+ Cmy,
+ /// `nCLR` spaces with n = 2..=15 colorants.
+ Color(u8),
+ Unknown(u32),
+}
+
+impl ColorSpace {
+ pub fn from_sig(s: u32) -> Self {
+ let b = s.to_be_bytes();
+ match &b {
+ b"XYZ " => Self::Xyz,
+ b"Lab " => Self::Lab,
+ b"Luv " => Self::Luv,
+ b"YCbr" => Self::YCbCr,
+ b"Yxy " => Self::Yxy,
+ b"RGB " => Self::Rgb,
+ b"GRAY" => Self::Gray,
+ b"HSV " => Self::Hsv,
+ b"HLS " => Self::Hls,
+ b"CMYK" => Self::Cmyk,
+ b"CMY " => Self::Cmy,
+ [d, b'C', b'L', b'R'] => match *d {
+ b'2'..=b'9' => Self::Color(d - b'0'),
+ b'A'..=b'F' => Self::Color(d - b'A' + 10),
+ _ => Self::Unknown(s),
+ },
+ _ => Self::Unknown(s),
+ }
+ }
+ pub fn sig(self) -> u32 {
+ u32::from_be_bytes(match self {
+ Self::Xyz => *b"XYZ ",
+ Self::Lab => *b"Lab ",
+ Self::Luv => *b"Luv ",
+ Self::YCbCr => *b"YCbr",
+ Self::Yxy => *b"Yxy ",
+ Self::Rgb => *b"RGB ",
+ Self::Gray => *b"GRAY",
+ Self::Hsv => *b"HSV ",
+ Self::Hls => *b"HLS ",
+ Self::Cmyk => *b"CMYK",
+ Self::Cmy => *b"CMY ",
+ Self::Color(n) => [if n < 10 { b'0' + n } else { b'A' + n - 10 }, b'C', b'L', b'R'],
+ Self::Unknown(s) => return s,
+ })
+ }
+ /// Number of channels of the space.
+ pub fn channels(self) -> usize {
+ match self {
+ Self::Gray => 1,
+ Self::Cmyk => 4,
+ Self::Color(n) => n as usize,
+ Self::Unknown(_) => 0,
+ _ => 3,
+ }
+ }
+}
+
+/// Which PCS a stage list ends in (float values: XYZ with Y = 1 for the white, or Lab L 0–100).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Pcs {
+ Xyz,
+ Lab,
+}
+
+/// Encoding family of a LUT tag, which fixes how its PCS side is encoded.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum LutKind {
+ /// `mft1` (8-bit), v4-style Lab encoding.
+ Lut8,
+ /// `mft2` (16-bit), legacy v2 Lab encoding.
+ Lut16,
+ /// `mAB ` / `mBA ` (v4), v4 Lab encoding.
+ Ab,
+}
+
+/// A parsed `AToB`/`BToA` tag: device-side and PCS-side values are normalised to `[0, 1]`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Lut {
+ pub kind: LutKind,
+ pub inputs: usize,
+ pub outputs: usize,
+ pub stages: Vec<Stage>,
+}
+
+/// A parsed ICC profile.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Profile {
+ /// Major version and minor.bugfix byte (e.g. `(4, 0x30)` for 4.3, `(2, 0x10)` for 2.1).
+ pub version: (u8, u8),
+ pub class: ProfileClass,
+ pub color_space: ColorSpace,
+ pub pcs: Pcs,
+ pub rendering_intent: Intent,
+ pub description: String,
+ pub copyright: String,
+ /// `wtpt` as stored (XYZ; D50 when absent).
+ pub white_point: [f64; 3],
+ /// `bkpt` when present.
+ pub black_point: Option<[f64; 3]>,
+ /// `chad` chromatic adaptation matrix when present.
+ pub chad: Option<Mat3>,
+ /// Colorant matrix (columns rXYZ, gXYZ, bXYZ), D50-adapted.
+ pub matrix: Option<Mat3>,
+ pub trc: Option<[Curve; 3]>,
+ pub gray_trc: Option<Curve>,
+ /// A2B0/A2B1/A2B2 (perceptual, colorimetric, saturation).
+ pub a2b: [Option<Lut>; 3],
+ pub b2a: [Option<Lut>; 3],
+ /// The bytes this profile was parsed from (or encoded to), kept for byte-exact embedding.
+ pub(crate) bytes: Option<Arc<Vec<u8>>>,
+ pub(crate) hash: std::sync::OnceLock<u64>,
+}
+
+impl Profile {
+ /// Parses ICC profile bytes.
+ pub fn parse(bytes: &[u8]) -> Result<Profile, CmsError> {
+ let mut p = parse_profile(bytes)?;
+ p.bytes = Some(Arc::new(bytes.to_vec()));
+ Ok(p)
+ }
+
+ /// The ICC bytes of this profile: the original bytes when it was parsed, otherwise a fresh
+ /// ICC v4 encoding.
+ pub fn to_bytes(&self) -> Arc<Vec<u8>> {
+ match &self.bytes {
+ Some(b) => b.clone(),
+ None => Arc::new(crate::write::encode(self)),
+ }
+ }
+
+ /// Re-encodes the model as ICC v4 bytes and caches them (used for built-in profiles).
+ pub fn with_encoded_bytes(mut self) -> Profile {
+ self.bytes = None;
+ self.hash = Default::default();
+ let b = crate::write::encode(&self);
+ self.bytes = Some(Arc::new(b));
+ self
+ }
+
+ pub fn channels(&self) -> usize {
+ self.color_space.channels()
+ }
+
+ /// Hash of the profile's ICC bytes (stable within a process; used as a cache key).
+ pub fn content_hash(&self) -> u64 {
+ *self.hash.get_or_init(|| {
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ self.to_bytes().hash(&mut h);
+ h.finish()
+ })
+ }
+
+ /// Media white point used for ICC-absolute colorimetry: `wtpt`, except for v2 display
+ /// profiles whose `wtpt` records the (unadapted) display white; those are treated as D50.
+ pub fn media_white(&self) -> [f64; 3] {
+ if self.version.0 < 4 && self.class == ProfileClass::Display {
+ return math::D50;
+ }
+ self.white_point
+ }
+
+ /// An RGB view of a gray TRC profile: each of R, G, B carries the gray curve and maps to a
+ /// third of the white, so `(v, v, v)` has exactly the colour of gray `v`. Used for
+ /// composites of gray documents, which are stored as replicated RGB.
+ pub fn gray_as_rgb(&self) -> Option<Profile> {
+ let c = self.gray_trc.clone()?;
+ if self.pcs != Pcs::Xyz {
+ return None;
+ }
+ let w = math::D50;
+ let m = [[w[0] / 3.0; 3], [w[1] / 3.0; 3], [w[2] / 3.0; 3]];
+ let mut p = self.clone();
+ p.color_space = ColorSpace::Rgb;
+ p.description = format!("{} (as RGB)", self.description);
+ p.matrix = Some(m);
+ p.trc = Some([c.clone(), c.clone(), c]);
+ p.gray_trc = None;
+ p.bytes = None;
+ p.hash = Default::default();
+ Some(p)
+ }
+
+ /// `true` for matrix/TRC RGB or gray TRC profiles without LUTs.
+ pub fn is_matrix_shaper(&self) -> bool {
+ self.a2b.iter().all(Option::is_none) && (self.matrix.is_some() && self.trc.is_some() || self.gray_trc.is_some())
+ }
+
+ fn lut_for(luts: &[Option<Lut>; 3], intent: Intent) -> Option<&Lut> {
+ let i = match intent {
+ Intent::Perceptual => 0,
+ Intent::RelativeColorimetric | Intent::AbsoluteColorimetric => 1,
+ Intent::Saturation => 2,
+ };
+ luts[i].as_ref().or(luts[0].as_ref())
+ }
+
+ /// Whether the profile has a dedicated table for `intent` (matrix profiles support every
+ /// intent colorimetrically).
+ pub fn supports_intent(&self, intent: Intent, input: bool) -> bool {
+ let luts = if input { &self.a2b } else { &self.b2a };
+ let i = match intent {
+ Intent::Perceptual => 0,
+ Intent::RelativeColorimetric | Intent::AbsoluteColorimetric => 1,
+ Intent::Saturation => 2,
+ };
+ luts[i].is_some() || luts.iter().all(Option::is_none)
+ }
+
+ /// Stages mapping normalised device values to the float PCS.
+ pub fn device_to_pcs(&self, intent: Intent) -> Result<(Vec<Stage>, Pcs), CmsError> {
+ if let Some(l) = Self::lut_for(&self.a2b, intent) {
+ let mut st = l.stages.clone();
+ st.push(decode_pcs(self.pcs, l.kind));
+ return Ok((st, self.pcs));
+ }
+ match self.color_space {
+ ColorSpace::Rgb => {
+ let (Some(m), Some(trc)) = (&self.matrix, &self.trc) else {
+ return Err(CmsError::Unsupported("RGB profile without matrix/TRC or AToB tags".into()));
+ };
+ Ok((vec![Stage::Curves(trc.to_vec()), Stage::matrix3(m)], Pcs::Xyz))
+ }
+ ColorSpace::Gray => {
+ let c = self.gray_trc.clone().ok_or_else(|| CmsError::Unsupported("gray profile without kTRC".into()))?;
+ if self.pcs == Pcs::Lab {
+ // The curve yields L*/100.
+ let m = Stage::Matrix { rows: 3, cols: 1, m: vec![100.0, 0.0, 0.0], offset: vec![0.0; 3] };
+ Ok((vec![Stage::Curves(vec![c]), m], Pcs::Lab))
+ } else {
+ let w = math::D50;
+ let m = Stage::Matrix { rows: 3, cols: 1, m: w.to_vec(), offset: vec![0.0; 3] };
+ Ok((vec![Stage::Curves(vec![c]), m], Pcs::Xyz))
+ }
+ }
+ ColorSpace::Lab => Ok((vec![Stage::DecodeLabV4], Pcs::Lab)),
+ ColorSpace::Xyz => Ok((vec![Stage::DecodeXyz], Pcs::Xyz)),
+ cs => Err(CmsError::Unsupported(format!("{cs:?} profile without AToB tags"))),
+ }
+ }
+
+ /// Stages mapping the float PCS (of the returned kind) to normalised device values.
+ pub fn pcs_to_device(&self, intent: Intent) -> Result<(Vec<Stage>, Pcs), CmsError> {
+ if let Some(l) = Self::lut_for(&self.b2a, intent) {
+ let mut st = vec![encode_pcs(self.pcs, l.kind)];
+ st.extend(l.stages.iter().cloned());
+ return Ok((st, self.pcs));
+ }
+ match self.color_space {
+ ColorSpace::Rgb => {
+ let (Some(m), Some(trc)) = (&self.matrix, &self.trc) else {
+ return Err(CmsError::Unsupported("RGB profile without matrix/TRC or BToA tags".into()));
+ };
+ let inv = math::invert(m).ok_or_else(|| CmsError::Invalid("singular colorant matrix".into()))?;
+ Ok((vec![Stage::matrix3(&inv), Stage::InvCurves(trc.to_vec())], Pcs::Xyz))
+ }
+ ColorSpace::Gray => {
+ let c = self.gray_trc.clone().ok_or_else(|| CmsError::Unsupported("gray profile without kTRC".into()))?;
+ if self.pcs == Pcs::Lab {
+ let m = Stage::Matrix { rows: 1, cols: 3, m: vec![0.01, 0.0, 0.0], offset: vec![0.0] };
+ Ok((vec![m, Stage::InvCurves(vec![c])], Pcs::Lab))
+ } else {
+ let m = Stage::Matrix { rows: 1, cols: 3, m: vec![0.0, 1.0, 0.0], offset: vec![0.0] };
+ Ok((vec![m, Stage::InvCurves(vec![c])], Pcs::Xyz))
+ }
+ }
+ ColorSpace::Lab => Ok((vec![Stage::EncodeLabV4], Pcs::Lab)),
+ ColorSpace::Xyz => Ok((vec![Stage::EncodeXyz], Pcs::Xyz)),
+ cs => Err(CmsError::Unsupported(format!("{cs:?} profile without BToA tags"))),
+ }
+ }
+}
+
+fn decode_pcs(pcs: Pcs, kind: LutKind) -> Stage {
+ match (pcs, kind) {
+ (Pcs::Xyz, _) => Stage::DecodeXyz,
+ (Pcs::Lab, LutKind::Lut16) => Stage::DecodeLabV2,
+ (Pcs::Lab, _) => Stage::DecodeLabV4,
+ }
+}
+
+fn encode_pcs(pcs: Pcs, kind: LutKind) -> Stage {
+ match (pcs, kind) {
+ (Pcs::Xyz, _) => Stage::EncodeXyz,
+ (Pcs::Lab, LutKind::Lut16) => Stage::EncodeLabV2,
+ (Pcs::Lab, _) => Stage::EncodeLabV4,
+ }
+}
+
+// ---------------------------------------------------------------- reader
+
+struct Reader<'a> {
+ b: &'a [u8],
+}
+
+impl<'a> Reader<'a> {
+ fn slice(&self, off: usize, len: usize) -> Result<&'a [u8], CmsError> {
+ off.checked_add(len).and_then(|end| self.b.get(off..end)).ok_or(CmsError::Truncated)
+ }
+ fn u8(&self, off: usize) -> Result<u8, CmsError> {
+ self.b.get(off).copied().ok_or(CmsError::Truncated)
+ }
+ fn u16(&self, off: usize) -> Result<u16, CmsError> {
+ let s = self.slice(off, 2)?;
+ Ok(u16::from_be_bytes([s[0], s[1]]))
+ }
+ fn u32(&self, off: usize) -> Result<u32, CmsError> {
+ let s = self.slice(off, 4)?;
+ Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
+ }
+ fn s15f16(&self, off: usize) -> Result<f64, CmsError> {
+ Ok(self.u32(off)? as i32 as f64 / 65536.0)
+ }
+ fn xyz(&self, off: usize) -> Result<[f64; 3], CmsError> {
+ Ok([self.s15f16(off)?, self.s15f16(off + 4)?, self.s15f16(off + 8)?])
+ }
+}
+
+fn sig(s: &[u8; 4]) -> u32 {
+ u32::from_be_bytes(*s)
+}
+
+/// Upper bound on CLUT nodes × outputs we accept, to reject hostile files.
+const MAX_CLUT_VALUES: usize = 16 * 1024 * 1024;
+
+fn parse_profile(bytes: &[u8]) -> Result<Profile, CmsError> {
+ let r = Reader { b: bytes };
+ if bytes.len() < 132 {
+ return Err(CmsError::Truncated);
+ }
+ if r.slice(36, 4)? != b"acsp" {
+ return Err(CmsError::BadSignature);
+ }
+ let declared = r.u32(0)? as usize;
+ // Some writers pad or truncate; trust the smaller of the two.
+ let end = if declared >= 132 && declared <= bytes.len() { declared } else { bytes.len() };
+ let r = Reader { b: &bytes[..end] };
+ let version = (r.u8(8)?, r.u8(9)?);
+ let class = ProfileClass::from_sig(r.u32(12)?);
+ let color_space = ColorSpace::from_sig(r.u32(16)?);
+ let pcs = match &r.u32(20)?.to_be_bytes() {
+ b"Lab " => Pcs::Lab,
+ _ => Pcs::Xyz,
+ };
+ let rendering_intent = Intent::from_u32(r.u32(64)? & 0xFFFF).unwrap_or(Intent::Perceptual);
+ let count = r.u32(128)? as usize;
+ if count > 1024 {
+ return Err(CmsError::Invalid(format!("{count} tags")));
+ }
+ let mut tags: Vec<(u32, usize, usize)> = Vec::with_capacity(count);
+ for i in 0..count {
+ let o = 132 + i * 12;
+ let (s, off, len) = (r.u32(o)?, r.u32(o + 4)? as usize, r.u32(o + 8)? as usize);
+ tags.push((s, off, len));
+ }
+ let find = |s: &[u8; 4]| tags.iter().find(|t| t.0 == sig(s)).map(|t| (t.1, t.2));
+ let tag_data = |s: &[u8; 4]| -> Result<Option<&[u8]>, CmsError> {
+ match find(s) {
+ Some((off, len)) => Ok(Some(r.slice(off, len)?)),
+ None => Ok(None),
+ }
+ };
+
+ let xyz_tag = |s: &[u8; 4]| -> Result<Option<[f64; 3]>, CmsError> {
+ match tag_data(s)? {
+ Some(d) if d.len() >= 20 && &d[..4] == b"XYZ " => Ok(Some(Reader { b: d }.xyz(8)?)),
+ Some(_) => Err(CmsError::Invalid(format!("tag {} is not XYZType", String::from_utf8_lossy(s)))),
+ None => Ok(None),
+ }
+ };
+ let curve_tag = |s: &[u8; 4]| -> Result<Option<Curve>, CmsError> {
+ match tag_data(s)? {
+ Some(d) => Ok(Some(parse_curve(d)?.0)),
+ None => Ok(None),
+ }
+ };
+
+ let white_point = xyz_tag(b"wtpt")?.unwrap_or(math::D50);
+ let black_point = xyz_tag(b"bkpt").ok().flatten();
+ let chad = match tag_data(b"chad")? {
+ Some(d) if d.len() >= 44 && &d[..4] == b"sf32" => {
+ let rd = Reader { b: d };
+ let mut m = [[0.0; 3]; 3];
+ for (i, row) in m.iter_mut().enumerate() {
+ for (j, v) in row.iter_mut().enumerate() {
+ *v = rd.s15f16(8 + (i * 3 + j) * 4)?;
+ }
+ }
+ Some(m)
+ }
+ _ => None,
+ };
+ let matrix = match (xyz_tag(b"rXYZ")?, xyz_tag(b"gXYZ")?, xyz_tag(b"bXYZ")?) {
+ (Some(rr), Some(g), Some(b)) => Some([[rr[0], g[0], b[0]], [rr[1], g[1], b[1]], [rr[2], g[2], b[2]]]),
+ _ => None,
+ };
+ let trc = match (curve_tag(b"rTRC")?, curve_tag(b"gTRC")?, curve_tag(b"bTRC")?) {
+ (Some(a), Some(b), Some(c)) => Some([a, b, c]),
+ _ => None,
+ };
+ let gray_trc = curve_tag(b"kTRC")?;
+ let lut = |s: &[u8; 4], a2b: bool| -> Result<Option<Lut>, CmsError> {
+ match tag_data(s)? {
+ Some(d) => parse_lut(d, a2b).map(Some),
+ None => Ok(None),
+ }
+ };
+ let a2b = [lut(b"A2B0", true)?, lut(b"A2B1", true)?, lut(b"A2B2", true)?];
+ let b2a = [lut(b"B2A0", false)?, lut(b"B2A1", false)?, lut(b"B2A2", false)?];
+ let description = tag_data(b"desc")?.map(parse_text).unwrap_or_default();
+ let copyright = tag_data(b"cprt")?.map(parse_text).unwrap_or_default();
+
+ let p = Profile {
+ version,
+ class,
+ color_space,
+ pcs,
+ rendering_intent,
+ description,
+ copyright,
+ white_point,
+ black_point,
+ chad,
+ matrix,
+ trc,
+ gray_trc,
+ a2b,
+ b2a,
+ bytes: None,
+ hash: Default::default(),
+ };
+ // Validate channel counts of LUTs against the header.
+ let dev = p.color_space.channels();
+ for l in p.a2b.iter().flatten() {
+ if dev != 0 && l.inputs != dev || l.outputs != 3 {
+ return Err(CmsError::Invalid(format!("AToB tag has {}→{} channels for a {:?} profile", l.inputs, l.outputs, p.color_space)));
+ }
+ }
+ for l in p.b2a.iter().flatten() {
+ if l.inputs != 3 || dev != 0 && l.outputs != dev {
+ return Err(CmsError::Invalid(format!("BToA tag has {}→{} channels for a {:?} profile", l.inputs, l.outputs, p.color_space)));
+ }
+ }
+ Ok(p)
+}
+
+/// Parses a `curv` or `para` element; returns the curve and the element's byte length
+/// (unpadded).
+fn parse_curve(d: &[u8]) -> Result<(Curve, usize), CmsError> {
+ let r = Reader { b: d };
+ match r.slice(0, 4)? {
+ b"curv" => {
+ let n = r.u32(8)? as usize;
+ let len = 12 + n * 2;
+ match n {
+ 0 => Ok((Curve::Identity, len)),
+ 1 => Ok((Curve::Gamma(r.u16(12)? as f64 / 256.0), len)),
+ _ => {
+ if n > 1 << 20 {
+ return Err(CmsError::Invalid("curve too long".into()));
+ }
+ let s = r.slice(12, n * 2)?;
+ let t = s.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect();
+ Ok((Curve::Table(t), len))
+ }
+ }
+ }
+ b"para" => {
+ let kind = r.u16(8)?;
+ if kind > 4 {
+ return Err(CmsError::Unsupported(format!("parametric curve type {kind}")));
+ }
+ let n = Curve::param_count(kind);
+ let mut p = [0.0f64; 7];
+ for (i, v) in p.iter_mut().enumerate().take(n) {
+ *v = r.s15f16(12 + i * 4)?;
+ }
+ let len = 12 + n * 4;
+ let c = if kind == 0 { Curve::Gamma(p[0]) } else { Curve::Parametric { kind, p } };
+ Ok((c, len))
+ }
+ other => Err(CmsError::Unsupported(format!("curve type {:?}", String::from_utf8_lossy(other)))),
+ }
+}
+
+fn parse_curves_at(d: &[u8], off: usize, n: usize) -> Result<Vec<Curve>, CmsError> {
+ let mut out = Vec::with_capacity(n);
+ let mut o = off;
+ for _ in 0..n {
+ let sub = d.get(o..).ok_or(CmsError::Truncated)?;
+ let (c, len) = parse_curve(sub)?;
+ out.push(c);
+ o += (len + 3) & !3;
+ }
+ Ok(out)
+}
+
+fn parse_lut(d: &[u8], a2b: bool) -> Result<Lut, CmsError> {
+ let r = Reader { b: d };
+ let ty = r.slice(0, 4)?;
+ match ty {
+ b"mft1" | b"mft2" => {
+ let wide = ty == b"mft2";
+ let (i, o, g) = (r.u8(8)? as usize, r.u8(9)? as usize, r.u8(10)? as usize);
+ if !(1..=15).contains(&i) || !(1..=15).contains(&o) || g == 0 {
+ return Err(CmsError::Invalid("bad lut dimensions".into()));
+ }
+ let mut m = [[0.0; 3]; 3];
+ for (a, row) in m.iter_mut().enumerate() {
+ for (b, v) in row.iter_mut().enumerate() {
+ *v = r.s15f16(12 + (a * 3 + b) * 4)?;
+ }
+ }
+ let (n_in, n_out, mut off) = if wide { (r.u16(48)? as usize, r.u16(50)? as usize, 52) } else { (256, 256, 48) };
+ if wide && (!(2..=4096).contains(&n_in) || !(2..=4096).contains(&n_out)) {
+ return Err(CmsError::Invalid("bad lut16 table size".into()));
+ }
+ let bps = if wide { 2 } else { 1 };
+ let read_tables = |off: &mut usize, count: usize, len: usize| -> Result<Vec<Curve>, CmsError> {
+ let mut v = Vec::with_capacity(count);
+ for _ in 0..count {
+ let s = r.slice(*off, len * bps)?;
+ let t: Vec<f32> =
+ if wide { s.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect() } else { s.iter().map(|b| *b as f32 / 255.0).collect() };
+ *off += len * bps;
+ v.push(Curve::Table(t));
+ }
+ Ok(v)
+ };
+ let in_curves = read_tables(&mut off, i, n_in)?;
+ let nodes = (g as u64).checked_pow(i as u32).unwrap_or(u64::MAX);
+ if nodes as u128 * o as u128 > MAX_CLUT_VALUES as u128 {
+ return Err(CmsError::Invalid("CLUT too large".into()));
+ }
+ let total = nodes as usize * o;
+ let s = r.slice(off, total * bps)?;
+ let data: Vec<f32> =
+ if wide { s.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect() } else { s.iter().map(|b| *b as f32 / 255.0).collect() };
+ off += total * bps;
+ let out_curves = read_tables(&mut off, o, n_out)?;
+ let mut stages = Vec::new();
+ // The matrix only applies when the input is XYZ (BToA with an XYZ PCS).
+ let ident = m.iter().enumerate().all(|(a, row)| row.iter().enumerate().all(|(b, v)| (v - if a == b { 1.0 } else { 0.0 }).abs() < 1e-6));
+ if !a2b && i == 3 && !ident {
+ // Only meaningful for an XYZ PCS; the caller decides (we cannot know the PCS here),
+ // so keep it: for Lab PCS writers are required to store the identity.
+ stages.push(Stage::matrix3(&m));
+ }
+ stages.push(Stage::Curves(in_curves));
+ stages.push(Stage::Clut(Clut::new(vec![g; i], o, data)));
+ stages.push(Stage::Curves(out_curves));
+ Ok(Lut { kind: if wide { LutKind::Lut16 } else { LutKind::Lut8 }, inputs: i, outputs: o, stages })
+ }
+ b"mAB " | b"mBA " => {
+ let (i, o) = (r.u8(8)? as usize, r.u8(9)? as usize);
+ if !(1..=15).contains(&i) || !(1..=15).contains(&o) {
+ return Err(CmsError::Invalid("bad lutAB dimensions".into()));
+ }
+ let (ob, om, omc, oc, oa) = (r.u32(12)? as usize, r.u32(16)? as usize, r.u32(20)? as usize, r.u32(24)? as usize, r.u32(28)? as usize);
+ let matrix = |off: usize| -> Result<Stage, CmsError> {
+ let mut m = vec![0.0; 9];
+ for (k, v) in m.iter_mut().enumerate() {
+ *v = r.s15f16(off + k * 4)?;
+ }
+ let offset = vec![r.s15f16(off + 36)?, r.s15f16(off + 40)?, r.s15f16(off + 44)?];
+ Ok(Stage::Matrix { rows: 3, cols: 3, m, offset })
+ };
+ let clut = |off: usize, cin: usize, cout: usize| -> Result<Stage, CmsError> {
+ let mut grid = Vec::with_capacity(cin);
+ for k in 0..cin {
+ let g = r.u8(off + k)? as usize;
+ if g < 1 {
+ return Err(CmsError::Invalid("zero grid points".into()));
+ }
+ grid.push(g);
+ }
+ let prec = r.u8(off + 16)? as usize;
+ let nodes: u128 = grid.iter().map(|g| *g as u128).product();
+ if nodes * cout as u128 > MAX_CLUT_VALUES as u128 {
+ return Err(CmsError::Invalid("CLUT too large".into()));
+ }
+ let total = nodes as usize * cout;
+ let data: Vec<f32> = match prec {
+ 1 => r.slice(off + 20, total)?.iter().map(|b| *b as f32 / 255.0).collect(),
+ 2 => r.slice(off + 20, total * 2)?.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect(),
+ _ => return Err(CmsError::Invalid(format!("CLUT precision {prec}"))),
+ };
+ Ok(Stage::Clut(Clut::new(grid, cout, data)))
+ };
+ let mut stages = Vec::new();
+ if ty == b"mAB " {
+ // A curves → CLUT → M curves → matrix → B curves.
+ if oc != 0 {
+ if oa == 0 {
+ return Err(CmsError::Invalid("lutAtoB with CLUT but no A curves".into()));
+ }
+ stages.push(Stage::Curves(parse_curves_at(d, oa, i)?));
+ stages.push(clut(oc, i, o)?);
+ } else if i != o {
+ return Err(CmsError::Invalid("lutAtoB without CLUT changes channel count".into()));
+ }
+ if om != 0 {
+ stages.push(Stage::Curves(parse_curves_at(d, omc, o)?));
+ stages.push(matrix(om)?);
+ }
+ if ob == 0 {
+ return Err(CmsError::Invalid("lutAtoB without B curves".into()));
+ }
+ stages.push(Stage::Curves(parse_curves_at(d, ob, o)?));
+ } else {
+ // B curves → matrix → M curves → CLUT → A curves.
+ if ob == 0 {
+ return Err(CmsError::Invalid("lutBtoA without B curves".into()));
+ }
+ stages.push(Stage::Curves(parse_curves_at(d, ob, i)?));
+ if om != 0 {
+ stages.push(matrix(om)?);
+ stages.push(Stage::Curves(parse_curves_at(d, omc, i)?));
+ }
+ if oc != 0 {
+ if oa == 0 {
+ return Err(CmsError::Invalid("lutBtoA with CLUT but no A curves".into()));
+ }
+ stages.push(clut(oc, i, o)?);
+ stages.push(Stage::Curves(parse_curves_at(d, oa, o)?));
+ } else if i != o {
+ return Err(CmsError::Invalid("lutBtoA without CLUT changes channel count".into()));
+ }
+ }
+ Ok(Lut { kind: LutKind::Ab, inputs: i, outputs: o, stages })
+ }
+ other => Err(CmsError::Unsupported(format!("LUT type {:?}", String::from_utf8_lossy(other)))),
+ }
+}
+
+/// Text from `desc` (textDescriptionType), `mluc` (English or first record) or `text`.
+fn parse_text(d: &[u8]) -> String {
+ let r = Reader { b: d };
+ let Ok(ty) = r.slice(0, 4) else { return String::new() };
+ let ascii = |s: &[u8]| String::from_utf8_lossy(s.split(|b| *b == 0).next().unwrap_or(&[])).trim().to_string();
+ match ty {
+ b"desc" => {
+ let n = r.u32(8).unwrap_or(0) as usize;
+ r.slice(12, n).map(ascii).unwrap_or_default()
+ }
+ b"text" => ascii(d.get(8..).unwrap_or(&[])),
+ b"mluc" => {
+ let (Ok(n), Ok(size)) = (r.u32(8), r.u32(12)) else { return String::new() };
+ let mut best: Option<(usize, usize)> = None;
+ for k in 0..(n as usize).min(256) {
+ let o = 16 + k * size as usize;
+ let (Ok(lang), Ok(len), Ok(off)) = (r.u16(o), r.u32(o + 4), r.u32(o + 8)) else { break };
+ if best.is_none() || lang == u16::from_be_bytes(*b"en") {
+ best = Some((off as usize, len as usize));
+ if lang == u16::from_be_bytes(*b"en") {
+ break;
+ }
+ }
+ }
+ let Some((off, len)) = best else { return String::new() };
+ let Ok(s) = r.slice(off, len) else { return String::new() };
+ let units: Vec<u16> = s.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
+ String::from_utf16_lossy(&units).trim_end_matches('\0').trim().to_string()
+ }
+ _ => String::new(),
+ }
+}
diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs
new file mode 100644
index 000000000..f96f28d2b
--- /dev/null
+++ b/crates/cms/src/synth.rs
@@ -0,0 +1,488 @@
+//! Synthetic CMYK output profiles.
+//!
+//! Adobe's CMYK profiles (U.S. Web Coated SWOP, Coated FOGRA39 …) are proprietary, and the
+//! freely downloadable characterisation-based profiles come with redistribution conditions, so
+//! Photocraft ships a CMYK profile it generates itself from a documented printer model:
+//!
+//! * **Forward model** (CMYK → XYZ): Yule–Nielsen modified Neugebauer (n = 2) over the 16
+//! ink overprints, with Demichel coverage weights and a parabolic tone value increase (dot
+//! gain) per ink. The eight K-free primaries use the published ISO 12647-2 coated-paper Lab
+//! aim values (paper, C, M, Y, the three two-colour overprints) and an estimated three-colour
+//! black; overprints with black are derived multiplicatively with a first-surface reflection
+//! floor.
+//! * **AToB** (all intents): 11⁴ `lut16` table of the forward model, relative colorimetric
+//! (paper → L* 100).
+//! * **BToA1** (colorimetric): for every Lab node, black generation (GCR) from the gray
+//! component of the K-free solution, then a bounded least-squares solve for C, M, Y with the
+//! total ink limit; out-of-gamut colours land on the closest reachable colour (clipping).
+//! * **BToA0/BToA2** (perceptual/saturation): the target is first compressed into the gamut —
+//! L* is scaled onto the device black, chroma is softly compressed against a gamut boundary
+//! descriptor sampled from the forward model — then solved as above.
+//!
+//! The model is plausible for coated offset, not a measured characterisation: use a real
+//! profile from your print provider for production print.
+
+use crate::clut::Clut;
+use crate::curve::Curve;
+use crate::math;
+use crate::pipeline::Stage;
+use crate::profile::{ColorSpace, Lut, LutKind, Pcs, Profile, ProfileClass};
+use crate::Intent;
+
+pub const DESCRIPTION: &str = "Photocraft Coated CMYK (synthetic, 300% TAC, medium GCR)";
+
+/// Parameters of the synthetic profile.
+#[derive(Clone, Debug)]
+pub struct CmykParams {
+ pub description: String,
+ /// Total area coverage limit (3.0 = 300 %).
+ pub tac: f64,
+ /// Gray component (min of C, M, Y of the K-free solution) where black generation starts.
+ pub gcr_start: f64,
+ /// Maximum black.
+ pub k_max: f64,
+ /// Exponent of the black generation curve above `gcr_start`.
+ pub gcr_gamma: f64,
+ /// Tone value increase at 50 % for C, M, Y, K.
+ pub tvi: [f64; 4],
+ /// Grid points of the AToB (4D) and BToA (3D) tables.
+ pub grid_a2b: usize,
+ pub grid_b2a: usize,
+}
+
+impl Default for CmykParams {
+ fn default() -> Self {
+ CmykParams {
+ description: DESCRIPTION.into(),
+ tac: 3.0,
+ gcr_start: 0.2,
+ k_max: 0.95,
+ gcr_gamma: 1.1,
+ tvi: [0.14, 0.14, 0.14, 0.17],
+ grid_a2b: 11,
+ grid_b2a: 21,
+ }
+ }
+}
+
+/// The printer model.
+#[derive(Clone, Debug)]
+pub struct CmykModel {
+ /// Absolute XYZ (D50) of the 16 overprints, indexed by ink bit mask (C=1, M=2, Y=4, K=8),
+ /// stored as `X^(1/n)` for the Yule–Nielsen sum.
+ prim_n: [[f64; 3]; 16],
+ /// Absolute XYZ of the paper.
+ pub paper: [f64; 3],
+ tvi: [f64; 4],
+}
+
+const YN: f64 = 2.0;
+
+impl CmykModel {
+ pub fn coated(tvi: [f64; 4]) -> Self {
+ let lab = |l: f64, a: f64, b: f64| math::lab_to_xyz([l, a, b], math::D50);
+ // ISO 12647-2 (coated, paper type 1/2) Lab aims, D50/2°; CMY overprint estimated.
+ let w = lab(95.0, 0.0, -2.0);
+ let base: [[f64; 3]; 8] = [
+ w, // paper
+ lab(55.0, -37.0, -50.0), // C
+ lab(48.0, 74.0, -3.0), // M
+ lab(24.0, 22.0, -46.0), // C+M (blue)
+ lab(89.0, -5.0, 93.0), // Y
+ lab(50.0, -65.0, 27.0), // C+Y (green)
+ lab(47.0, 68.0, 48.0), // M+Y (red)
+ lab(23.0, 0.0, 0.0), // C+M+Y
+ ];
+ let k = lab(16.0, 0.0, 0.0);
+ // Overprints with black: multiplicative in reflectance above a first-surface floor.
+ let floor = 0.006;
+ let mut prim = [[0.0; 3]; 16];
+ for m in 0..16 {
+ let p = base[m & 7];
+ prim[m] = if m & 8 == 0 {
+ p
+ } else {
+ std::array::from_fn(|i| {
+ let s = floor * w[i];
+ s + (p[i] - s) * (k[i] - s) / (w[i] - s)
+ })
+ };
+ }
+ let prim_n = prim.map(|p| p.map(|v| v.max(0.0).powf(1.0 / YN)));
+ CmykModel { prim_n, paper: w, tvi }
+ }
+
+ /// Absolute XYZ of an ink combination (each coverage in `[0, 1]`).
+ pub fn xyz(&self, cmyk: [f64; 4]) -> [f64; 3] {
+ let a: [f64; 4] = std::array::from_fn(|i| {
+ let v = cmyk[i].clamp(0.0, 1.0);
+ (v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0)
+ });
+ let mut s = [0.0; 3];
+ for m in 0..16 {
+ let mut w = 1.0;
+ for (i, ai) in a.iter().enumerate() {
+ w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai };
+ }
+ if w == 0.0 {
+ continue;
+ }
+ for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) {
+ *acc += w * p;
+ }
+ }
+ s.map(|v| v.powf(YN))
+ }
+
+ /// ICC-relative Lab (paper = L* 100).
+ pub fn lab(&self, cmyk: [f64; 4]) -> [f64; 3] {
+ let x = self.xyz(cmyk);
+ let rel = [x[0] * math::D50[0] / self.paper[0], x[1] * math::D50[1] / self.paper[1], x[2] * math::D50[2] / self.paper[2]];
+ math::xyz_to_lab(rel, math::D50)
+ }
+}
+
+/// Bounded least-squares solve for C, M, Y given K, minimising ΔE76 to `target`, subject to
+/// `C + M + Y ≤ limit` (projected Levenberg–Marquardt with a numerical Jacobian).
+fn solve_cmy(model: &CmykModel, target: [f64; 3], k: f64, limit: f64, seeds: &[[f64; 3]]) -> ([f64; 3], f64) {
+ let project = |mut x: [f64; 3]| {
+ for _ in 0..4 {
+ for v in &mut x {
+ *v = v.clamp(0.0, 1.0);
+ }
+ let s: f64 = x.iter().sum();
+ if s <= limit + 1e-12 {
+ break;
+ }
+ let active = x.iter().filter(|v| **v > 0.0).count().max(1) as f64;
+ let d = (s - limit) / active;
+ for v in &mut x {
+ if *v > 0.0 {
+ *v -= d;
+ }
+ }
+ }
+ x
+ };
+ let err = |x: [f64; 3]| {
+ let l = model.lab([x[0], x[1], x[2], k]);
+ [l[0] - target[0], l[1] - target[1], l[2] - target[2]]
+ };
+ let norm2 = |e: [f64; 3]| e[0] * e[0] + e[1] * e[1] + e[2] * e[2];
+ let mut best = ([0.0; 3], f64::INFINITY);
+ for seed in seeds {
+ let mut x = project(*seed);
+ let mut e = err(x);
+ let mut f = norm2(e);
+ let mut lambda = 1e-3;
+ for _ in 0..60 {
+ // Jacobian (3×3) by forward differences.
+ let h = 1e-5;
+ let mut j = [[0.0; 3]; 3];
+ for c in 0..3 {
+ let mut xp = x;
+ xp[c] += h;
+ let ep = err(xp);
+ for r in 0..3 {
+ j[r][c] = (ep[r] - e[r]) / h;
+ }
+ }
+ // (JᵀJ + λ diag) δ = −Jᵀe
+ let mut a = [[0.0; 3]; 3];
+ let mut g = [0.0; 3];
+ for r in 0..3 {
+ for c in 0..3 {
+ a[r][c] = (0..3).map(|k| j[k][r] * j[k][c]).sum();
+ }
+ g[r] = -(0..3).map(|k| j[k][r] * e[k]).sum::<f64>();
+ }
+ let mut improved = false;
+ for _ in 0..8 {
+ let mut al = a;
+ for (d, row) in al.iter_mut().enumerate() {
+ row[d] += lambda * (1.0 + a[d][d]);
+ }
+ let Some(inv) = math::invert(&al) else {
+ lambda *= 10.0;
+ continue;
+ };
+ let step = math::apply(&inv, g);
+ let xn = project([x[0] + step[0], x[1] + step[1], x[2] + step[2]]);
+ let en = err(xn);
+ let fnew = norm2(en);
+ if fnew < f {
+ let moved = (0..3).map(|i| (xn[i] - x[i]).abs()).fold(0.0, f64::max);
+ x = xn;
+ e = en;
+ f = fnew;
+ lambda = (lambda * 0.3).max(1e-9);
+ improved = moved > 1e-9;
+ break;
+ }
+ lambda *= 10.0;
+ }
+ if !improved || f < 1e-10 {
+ break;
+ }
+ }
+ if f < best.1 {
+ best = (x, f);
+ }
+ if best.1 < 1e-6 {
+ break;
+ }
+ }
+ (best.0, best.1.sqrt())
+}
+
+const SEEDS: [[f64; 3]; 5] = [[0.3, 0.3, 0.3], [0.05, 0.05, 0.05], [0.8, 0.8, 0.8], [0.9, 0.2, 0.2], [0.2, 0.9, 0.9]];
+
+/// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve.
+pub fn separate(model: &CmykModel, p: &CmykParams, target: [f64; 3], warm: Option<[f64; 4]>) -> ([f64; 4], f64) {
+ let mut seeds: Vec<[f64; 3]> = warm.map(|w| vec![[w[0], w[1], w[2]]]).unwrap_or_default();
+ seeds.extend_from_slice(&SEEDS);
+ let (cmy0, _) = solve_cmy(model, target, 0.0, 3.0, &seeds);
+ let g = cmy0[0].min(cmy0[1]).min(cmy0[2]);
+ let k = if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) };
+ let mut seeds2 = vec![[(cmy0[0] - k).max(0.0), (cmy0[1] - k).max(0.0), (cmy0[2] - k).max(0.0)], cmy0];
+ seeds2.extend_from_slice(&seeds);
+ let (cmy, de) = solve_cmy(model, target, k, (p.tac - k).max(0.0), &seeds2);
+ ([cmy[0], cmy[1], cmy[2], k], de)
+}
+
+/// Gamut boundary descriptor: maximum chroma per (L*, hue) bin, sampled from the model.
+struct Gbd {
+ l_bins: usize,
+ h_bins: usize,
+ cmax: Vec<f64>,
+ black_l: f64,
+}
+
+impl Gbd {
+ fn new(model: &CmykModel, p: &CmykParams) -> Self {
+ let (l_bins, h_bins) = (41usize, 72usize);
+ let mut cmax = vec![0.0f64; l_bins * h_bins];
+ let n = 21;
+ let mut black_l = 100.0f64;
+ for ci in 0..n {
+ for mi in 0..n {
+ for yi in 0..n {
+ for ki in 0..11 {
+ let v = [ci as f64 / (n - 1) as f64, mi as f64 / (n - 1) as f64, yi as f64 / (n - 1) as f64, ki as f64 / 10.0];
+ if v.iter().sum::<f64>() > p.tac + 1e-9 {
+ continue;
+ }
+ let lab = model.lab(v);
+ black_l = black_l.min(lab[0]);
+ let c = lab[1].hypot(lab[2]);
+ let h = lab[2].atan2(lab[1]).rem_euclid(std::f64::consts::TAU);
+ let li = ((lab[0] / 100.0) * (l_bins - 1) as f64).round().clamp(0.0, (l_bins - 1) as f64) as usize;
+ let hi = ((h / std::f64::consts::TAU) * h_bins as f64).round() as usize % h_bins;
+ let e = &mut cmax[li * h_bins + hi];
+ *e = e.max(c);
+ }
+ }
+ }
+ }
+ // Fill holes and smooth: max over a 3×3 neighbourhood, then a box blur.
+ let get = |v: &Vec<f64>, l: isize, h: isize| {
+ let l = l.clamp(0, l_bins as isize - 1) as usize;
+ let h = h.rem_euclid(h_bins as isize) as usize;
+ v[l * h_bins + h]
+ };
+ let mut filled = cmax.clone();
+ for l in 0..l_bins as isize {
+ for h in 0..h_bins as isize {
+ let mut m = 0.0f64;
+ for dl in -1..=1 {
+ for dh in -1..=1 {
+ m = m.max(get(&cmax, l + dl, h + dh));
+ }
+ }
+ filled[l as usize * h_bins + h as usize] = m;
+ }
+ }
+ let mut smooth = filled.clone();
+ for l in 0..l_bins as isize {
+ for h in 0..h_bins as isize {
+ let mut s = 0.0;
+ for dl in -1..=1 {
+ for dh in -1..=1 {
+ s += get(&filled, l + dl, h + dh);
+ }
+ }
+ smooth[l as usize * h_bins + h as usize] = s / 9.0;
+ }
+ }
+ Gbd { l_bins, h_bins, cmax: smooth, black_l }
+ }
+
+ fn max_chroma(&self, l: f64, h: f64) -> f64 {
+ let lp = (l / 100.0).clamp(0.0, 1.0) * (self.l_bins - 1) as f64;
+ let hp = (h.rem_euclid(std::f64::consts::TAU) / std::f64::consts::TAU) * self.h_bins as f64;
+ let (l0, h0) = (lp.floor() as usize, hp.floor() as usize);
+ let (fl, fh) = (lp - l0 as f64, hp - h0 as f64);
+ let l1 = (l0 + 1).min(self.l_bins - 1);
+ let (h0m, h1m) = (h0 % self.h_bins, (h0 + 1) % self.h_bins);
+ let v = |l: usize, h: usize| self.cmax[l * self.h_bins + h];
+ let a = v(l0, h0m) + (v(l0, h1m) - v(l0, h0m)) * fh;
+ let b = v(l1, h0m) + (v(l1, h1m) - v(l1, h0m)) * fh;
+ a + (b - a) * fl
+ }
+
+ /// Perceptual gamut compression of a relative Lab colour.
+ fn compress(&self, lab: [f64; 3]) -> [f64; 3] {
+ let l = self.black_l + lab[0].clamp(0.0, 100.0) * (100.0 - self.black_l) / 100.0;
+ let c = lab[1].hypot(lab[2]);
+ if c < 1e-9 {
+ return [l, 0.0, 0.0];
+ }
+ let h = lab[2].atan2(lab[1]);
+ let cm = self.max_chroma(l, h).max(1e-3);
+ let knee = 0.8 * cm;
+ let c2 = if c <= knee { c } else { knee + (cm - knee) * ((c - knee) / (cm - knee)).tanh() };
+ [l, c2 * h.cos(), c2 * h.sin()]
+ }
+}
+
+fn lab_node_legacy(i: usize, n: usize) -> f64 {
+ i as f64 / (n - 1) as f64
+}
+
+/// Decodes a legacy (lut16) Lab node coordinate triple.
+fn decode_v2(v: [f64; 3]) -> [f64; 3] {
+ [v[0] * 100.0 * 65535.0 / 65280.0, v[1] * 65535.0 / 256.0 - 128.0, v[2] * 65535.0 / 256.0 - 128.0]
+}
+
+fn encode_v2(lab: [f64; 3]) -> [f32; 3] {
+ [
+ (lab[0] / (100.0 * 65535.0 / 65280.0)).clamp(0.0, 1.0) as f32,
+ ((lab[1] + 128.0) * 256.0 / 65535.0).clamp(0.0, 1.0) as f32,
+ ((lab[2] + 128.0) * 256.0 / 65535.0).clamp(0.0, 1.0) as f32,
+ ]
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn par_map<T: Send>(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Vec<T> {
+ use rayon::prelude::*;
+ (0..n).into_par_iter().map(f).collect()
+}
+
+#[cfg(target_arch = "wasm32")]
+fn par_map<T: Send>(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Vec<T> {
+ (0..n).map(f).collect()
+}
+
+fn b2a_table(model: &CmykModel, p: &CmykParams, gbd: Option<&Gbd>) -> Clut {
+ let n = p.grid_b2a;
+ let nodes = n * n * n;
+ let vals = par_map(n * n, |row| {
+ // One (L, a) row along b, warm-starting each solve from its neighbour.
+ let (li, ai) = (row / n, row % n);
+ let mut warm = None;
+ let mut out = Vec::with_capacity(n * 4);
+ for bi in 0..n {
+ let lab = decode_v2([lab_node_legacy(li, n), lab_node_legacy(ai, n), lab_node_legacy(bi, n)]);
+ let target = match gbd {
+ Some(g) => g.compress(lab),
+ None => lab,
+ };
+ let (cmyk, _) = separate(model, p, target, warm);
+ warm = Some(cmyk);
+ out.extend(cmyk.map(|v| v as f32));
+ }
+ out
+ });
+ let data: Vec<f32> = vals.into_iter().flatten().collect();
+ debug_assert_eq!(data.len(), nodes * 4);
+ Clut::new(vec![n; 3], 4, data)
+}
+
+fn lut16(clut: Clut) -> Lut {
+ let (i, o) = (clut.inputs, clut.outputs);
+ Lut {
+ kind: LutKind::Lut16,
+ inputs: i,
+ outputs: o,
+ stages: vec![Stage::Curves(vec![Curve::Table(vec![0.0, 1.0]); i]), Stage::Clut(clut), Stage::Curves(vec![Curve::Table(vec![0.0, 1.0]); o])],
+ }
+}
+
+/// Generates a synthetic CMYK profile.
+pub fn cmyk_profile(p: &CmykParams) -> Profile {
+ let model = CmykModel::coated(p.tvi);
+ let g = p.grid_a2b;
+ let a2b = Clut::sample(vec![g; 4], 3, |inp, out| {
+ let lab = model.lab([inp[0] as f64, inp[1] as f64, inp[2] as f64, inp[3] as f64]);
+ out.copy_from_slice(&encode_v2(lab));
+ });
+ let gbd = Gbd::new(&model, p);
+ let colorimetric = b2a_table(&model, p, None);
+ let perceptual = b2a_table(&model, p, Some(&gbd));
+ let a2b = lut16(a2b);
+ let (b0, b1) = (lut16(perceptual), lut16(colorimetric));
+ Profile {
+ version: (4, 0x30),
+ class: ProfileClass::Output,
+ color_space: ColorSpace::Cmyk,
+ pcs: Pcs::Lab,
+ rendering_intent: Intent::Perceptual,
+ description: p.description.clone(),
+ copyright: crate::builtin::COPYRIGHT.into(),
+ white_point: model.paper.map(math::s15f16_round),
+ black_point: None,
+ chad: None,
+ matrix: None,
+ trc: None,
+ gray_trc: None,
+ a2b: [Some(a2b.clone()), Some(a2b.clone()), Some(a2b)],
+ b2a: [Some(b0.clone()), Some(b1), Some(b0)],
+ bytes: None,
+ hash: Default::default(),
+ }
+ .with_encoded_bytes()
+}
+
+/// The default coated profile (what `profiles/photocraft-coated-cmyk.icc` contains).
+pub fn coated_cmyk() -> Profile {
+ cmyk_profile(&CmykParams::default())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn model_anchors() {
+ let m = CmykModel::coated(CmykParams::default().tvi);
+ let w = m.lab([0.0; 4]);
+ assert!((w[0] - 100.0).abs() < 1e-9 && w[1].abs() < 1e-9 && w[2].abs() < 1e-9, "{w:?}");
+ let k = m.lab([0.0, 0.0, 0.0, 1.0]);
+ assert!(k[0] > 12.0 && k[0] < 22.0, "{k:?}");
+ let rich = m.lab([0.75, 0.65, 0.6, 0.9]);
+ assert!(rich[0] < k[0], "{rich:?}");
+ // Monotonic in each ink.
+ for ink in 0..4 {
+ let mut prev = 101.0;
+ for i in 0..=20 {
+ let mut v = [0.2, 0.2, 0.2, 0.2];
+ v[ink] = i as f64 / 20.0;
+ let l = m.lab(v)[0];
+ assert!(l < prev + 1e-9, "ink {ink} step {i}: {l} >= {prev}");
+ prev = l;
+ }
+ }
+ }
+
+ #[test]
+ fn separation_hits_in_gamut_targets() {
+ let m = CmykModel::coated(CmykParams::default().tvi);
+ let p = CmykParams::default();
+ let reachable = [[0.3, 0.4, 0.1, 0.1], [0.6, 0.1, 0.5, 0.0], [0.05, 0.1, 0.7, 0.0], [0.5, 0.45, 0.45, 0.4]].map(|v| m.lab(v));
+ for target in [[50.0, 0.0, 0.0]].into_iter().chain(reachable) {
+ let (cmyk, de) = separate(&m, &p, target, None);
+ assert!(de < 1.5, "{target:?} -> {cmyk:?} ΔE {de}");
+ assert!(cmyk.iter().sum::<f64>() <= p.tac + 1e-6);
+ }
+ }
+}
diff --git a/crates/cms/src/transform.rs b/crates/cms/src/transform.rs
new file mode 100644
index 000000000..b11063e3d
--- /dev/null
+++ b/crates/cms/src/transform.rs
@@ -0,0 +1,729 @@
+//! Colour transforms between profiles through the PCS, with rendering intents, black point
+//! compensation, soft-proofing chains, and fast lookup-table evaluation of pixel buffers.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock};
+
+use crate::clut::{Clut, MAX_CHANNELS};
+use crate::curve::Curve;
+use crate::math;
+use crate::pipeline::{Pipeline, Stage};
+use crate::profile::{ColorSpace, Pcs, Profile, ProfileClass};
+use crate::{CmsError, Intent};
+
+/// Sample storage of a byte buffer for [`Transform::convert_bytes_many`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SampleKind {
+ U8,
+ U16,
+ F32,
+}
+
+/// Options for building a [`Transform`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct TransformOptions {
+ pub intent: Intent,
+ /// Adobe-style black point compensation (ignored for absolute colorimetric).
+ pub bpc: bool,
+ /// `true`: float buffers go through the exact pipeline (default). `false`: float buffers use
+ /// the same lookup tables as integer buffers (faster, for previews).
+ pub precise_float: bool,
+}
+
+impl Default for TransformOptions {
+ fn default() -> Self {
+ Self { intent: Intent::RelativeColorimetric, bpc: true, precise_float: true }
+ }
+}
+
+/// Grid sizes of the device-link tables built for integer (and fast float) evaluation.
+pub const GRID_3D: usize = 33;
+pub const GRID_4D: usize = 17;
+const TABLE_1D: usize = 4096;
+/// Resolution of output shaper tables (indexed by `x^(1/4)`).
+const OUT_TABLE: usize = 4096;
+
+/// ICC v4 perceptual reference medium black (ICC.1:2010 §6.3.4.4), XYZ.
+const PERCEPTUAL_BLACK: [f64; 3] = [0.00336, 0.0034731, 0.00287];
+
+/// Accelerated representation of a transform.
+#[derive(Debug)]
+enum Core {
+ /// Input curves (sampled per input channel over `[0, 1]`, 4096+1 entries; 256 exact
+ /// entries for 8-bit input) followed by an optional matrix.
+ Shaper { curves8: Vec<[f32; 256]>, curves: Vec<Vec<f32>>, matrix: Option<(usize, usize, Vec<f32>, Vec<f32>)> },
+ /// Device link table over the input space.
+ Grid(Clut),
+ /// No acceleration possible: use the exact pipeline.
+ Exact,
+}
+
+/// Output inverse-curve tables indexed by `x^(1/4)` (accurate near black even for pure gamma
+/// curves, whose slope is infinite at zero).
+#[derive(Debug)]
+struct Post {
+ tables: Vec<Vec<f32>>,
+}
+
+impl Post {
+ #[inline]
+ fn eval(&self, c: usize, x: f32) -> f32 {
+ let t = &self.tables[c];
+ let u = x.clamp(0.0, 1.0).sqrt().sqrt() * (OUT_TABLE - 1) as f32;
+ let i = (u as usize).min(OUT_TABLE - 2);
+ let f = u - i as f32;
+ t[i] + (t[i + 1] - t[i]) * f
+ }
+}
+
+/// A colour transform from one profile's device space to another's.
+///
+/// Build once (it precomputes lookup tables) and apply to any number of buffers from any
+/// thread. Buffers are interleaved; colour channels come first in each pixel and any further
+/// channels (alpha, spot) are copied or left alone.
+#[derive(Debug)]
+pub struct Transform {
+ inputs: usize,
+ outputs: usize,
+ opts: TransformOptions,
+ pipeline: Pipeline,
+ core: Core,
+ post: Option<Post>,
+ /// Pre-located grid coordinates per 8-bit code: (offset contribution, fraction) per input.
+ grid8: Vec<[(u32, f32); 256]>,
+}
+
+impl Transform {
+ /// Transform from `src` to `dst` with `intent`, optionally with black point compensation.
+ pub fn new(src: &Profile, dst: &Profile, intent: Intent, bpc: bool) -> Result<Transform, CmsError> {
+ Self::with_options(src, dst, TransformOptions { intent, bpc, ..Default::default() })
+ }
+
+ pub fn with_options(src: &Profile, dst: &Profile, opts: TransformOptions) -> Result<Transform, CmsError> {
+ let stages = link_stages(src, dst, opts.intent, opts.bpc)?;
+ let mut t = Self::from_pipeline(Pipeline::new(src.channels(), stages), opts);
+ if opts.intent != Intent::AbsoluteColorimetric {
+ t.fix_white(src.color_space, dst.color_space);
+ }
+ Ok(t)
+ }
+
+ /// Soft-proof transform `src → proof → dst` (Photoshop View › Proof Setup): `intent`/`bpc`
+ /// apply to the document → proof step; the proof → display step is relative colorimetric
+ /// with BPC, or absolute colorimetric without BPC when `simulate_paper` is set (paper
+ /// colour and black ink simulated).
+ pub fn proof(src: &Profile, proof: &Profile, dst: &Profile, intent: Intent, bpc: bool, simulate_paper: bool) -> Result<Transform, CmsError> {
+ let mut stages = link_stages(src, proof, intent, bpc)?;
+ stages.push(Stage::Clamp01);
+ let (i2, b2) = if simulate_paper { (Intent::AbsoluteColorimetric, false) } else { (Intent::RelativeColorimetric, true) };
+ stages.extend(link_stages(proof, dst, i2, b2)?);
+ Ok(Self::from_pipeline(Pipeline::new(src.channels(), stages), TransformOptions { intent, bpc, precise_float: true }))
+ }
+
+ /// Builds a transform from an arbitrary pipeline over normalised values.
+ pub fn from_pipeline(mut pipeline: Pipeline, opts: TransformOptions) -> Transform {
+ pipeline.optimize();
+ let (inputs, outputs) = (pipeline.inputs, pipeline.outputs);
+ // Split trailing inverse curves into accurate output tables.
+ let mut head = pipeline.stages.clone();
+ let mut post = None;
+ if let Some(Stage::InvCurves(cs)) = head.last()
+ && cs.len() == outputs
+ {
+ let tables = cs
+ .iter()
+ .map(|c| {
+ (0..OUT_TABLE)
+ .map(|i| {
+ let u = i as f64 / (OUT_TABLE - 1) as f64;
+ c.eval_inverse64(u * u * u * u).clamp(0.0, 1.0) as f32
+ })
+ .collect()
+ })
+ .collect();
+ post = Some(Post { tables });
+ head.pop();
+ if matches!(head.last(), Some(Stage::Clamp01)) {
+ head.pop();
+ }
+ }
+ let head_pipe = Pipeline::new(inputs, head.clone());
+ let mid = head_pipe.outputs;
+ let core = match head.as_slice() {
+ [] => Core::Shaper { curves8: Vec::new(), curves: Vec::new(), matrix: None },
+ [Stage::Curves(cs)] if cs.len() == inputs => shaper(cs, None),
+ [Stage::Matrix { rows, cols, m, offset }] => shaper(&[], Some((*rows, *cols, m, offset))),
+ [Stage::Curves(cs), Stage::Matrix { rows, cols, m, offset }] if cs.len() == inputs => shaper(cs, Some((*rows, *cols, m, offset))),
+ // Purely analytic heads (Lab/XYZ maths, matrices, curves) are evaluated exactly:
+ // a grid would amplify interpolation error through steep output curves.
+ _ if !head.iter().any(|s| matches!(s, Stage::Clut(_))) => Core::Exact,
+ _ => match inputs {
+ 1 => Core::Grid(Clut::sample(vec![TABLE_1D], mid, |i, o| head_pipe.eval(i, o))),
+ 3 => Core::Grid(Clut::sample(vec![GRID_3D; 3], mid, |i, o| head_pipe.eval(i, o))),
+ 4 => Core::Grid(Clut::sample(vec![GRID_4D; 4], mid, |i, o| head_pipe.eval(i, o))),
+ 2 => Core::Grid(Clut::sample(vec![GRID_3D; 2], mid, |i, o| head_pipe.eval(i, o))),
+ _ => Core::Exact,
+ },
+ };
+ let grid8 = match &core {
+ Core::Grid(c) if c.inputs >= 2 => (0..c.inputs)
+ .map(|d| {
+ let n = c.grid[d];
+ let stride = c.data.len() / c.outputs / c.grid[..=d].iter().product::<usize>() * c.outputs;
+ std::array::from_fn(|v| {
+ let p = v as f32 / 255.0 * (n - 1) as f32;
+ let i = (p as usize).min(n - 2);
+ ((i * stride) as u32, p - i as f32)
+ })
+ })
+ .collect(),
+ _ => Vec::new(),
+ };
+ Transform { inputs, outputs, opts, pipeline, core, post, grid8 }
+ }
+
+ /// White preservation: the device-link node at the source's device white gets exactly the
+ /// destination's device white, so paper/white survive table quantization (e.g. the PCS
+ /// white is not a node of a legacy-encoded Lab grid).
+ fn fix_white(&mut self, src: ColorSpace, dst: ColorSpace) {
+ let (Some(sw), Some(mut dw)) = (device_white(src), device_white(dst)) else { return };
+ if self.post.is_some() {
+ // Output curves map 1 → 1 for additive spaces; the grid holds pre-curve values.
+ if !matches!(dst, ColorSpace::Rgb | ColorSpace::Gray) {
+ return;
+ }
+ dw.iter_mut().for_each(|v| *v = 1.0);
+ }
+ let Core::Grid(c) = &mut self.core else { return };
+ if c.inputs != sw.len() || c.outputs != dw.len() {
+ return;
+ }
+ let mut off = 0usize;
+ let mut stride = c.outputs;
+ for d in (0..c.inputs).rev() {
+ let n = c.grid[d];
+ let pos = sw[d] * (n - 1) as f32;
+ if (pos - pos.round()).abs() > 1e-6 {
+ return;
+ }
+ off += pos.round() as usize * stride;
+ stride *= n;
+ }
+ c.data[off..off + c.outputs].copy_from_slice(&dw);
+ }
+
+ pub fn inputs(&self) -> usize {
+ self.inputs
+ }
+ pub fn outputs(&self) -> usize {
+ self.outputs
+ }
+ pub fn options(&self) -> TransformOptions {
+ self.opts
+ }
+ /// The exact evaluation pipeline.
+ pub fn pipeline(&self) -> &Pipeline {
+ &self.pipeline
+ }
+
+ /// Exact evaluation of one colour (`inputs` → `outputs` normalised values).
+ #[inline]
+ pub fn eval(&self, input: &[f32], out: &mut [f32]) {
+ self.pipeline.eval(input, out);
+ }
+
+ /// Lookup-table evaluation of one colour (what integer buffers use).
+ #[inline]
+ pub fn eval_fast(&self, input: &[f32], out: &mut [f32]) {
+ let mut mid = [0.0f32; 16];
+ match &self.core {
+ Core::Exact => return self.pipeline.eval(input, out),
+ Core::Grid(c) => {
+ let mut inp = [0.0f32; 16];
+ for (d, s) in inp.iter_mut().zip(&input[..self.inputs]) {
+ *d = s.clamp(0.0, 1.0);
+ }
+ c.eval(&inp[..self.inputs], &mut mid[..c.outputs]);
+ }
+ Core::Shaper { curves, matrix, .. } => {
+ let mut v = [0.0f32; 16];
+ for k in 0..self.inputs {
+ v[k] = if curves.is_empty() { input[k] } else { table(&curves[k], input[k]) };
+ }
+ apply_matrix(matrix, &v, &mut mid, self.inputs);
+ }
+ }
+ self.finish(&mid, out);
+ }
+
+ #[inline]
+ fn finish(&self, mid: &[f32], out: &mut [f32]) {
+ match &self.post {
+ Some(p) => {
+ for k in 0..self.outputs {
+ out[k] = p.eval(k, mid[k]);
+ }
+ }
+ None => out[..self.outputs].copy_from_slice(&mid[..self.outputs]),
+ }
+ }
+
+ /// Converts float pixels. `src`/`dst` hold whole pixels of `src_stride`/`dst_stride`
+ /// values; colour channels come first. Trailing channels are copied when `copy_extra`.
+ pub fn convert_f32(&self, src: &[f32], src_stride: usize, dst: &mut [f32], dst_stride: usize, copy_extra: bool) {
+ self.check(src_stride, dst_stride);
+ let extra = extra_channels(self, src_stride, dst_stride, copy_extra);
+ par_rows(src, src_stride, dst, dst_stride, |s, d| self.run_f32(s, src_stride, d, dst_stride, extra));
+ }
+
+ fn run_f32(&self, s: &[f32], ss: usize, d: &mut [f32], ds: usize, extra: usize) {
+ let precise = self.opts.precise_float || matches!(self.core, Core::Exact);
+ for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
+ if precise {
+ self.pipeline.eval(sp, dp);
+ } else {
+ self.eval_fast(sp, dp);
+ }
+ for e in 0..extra {
+ dp[self.outputs + e] = sp[self.inputs + e];
+ }
+ }
+ }
+
+ /// In-place float conversion; `stride ≥ max(inputs, outputs)`.
+ pub fn apply(&self, buf: &mut [f32], stride: usize) {
+ assert!(stride >= self.inputs.max(self.outputs), "stride too small");
+ let precise = self.opts.precise_float || matches!(self.core, Core::Exact);
+ let body = |chunk: &mut [f32]| {
+ let mut out = [0.0f32; 16];
+ for p in chunk.chunks_exact_mut(stride) {
+ if precise {
+ self.pipeline.eval(p, &mut out);
+ } else {
+ self.eval_fast(p, &mut out);
+ }
+ p[..self.outputs].copy_from_slice(&out[..self.outputs]);
+ }
+ };
+ par_inplace(buf, stride, body);
+ }
+
+ /// Converts 8-bit pixels (see [`Transform::convert_f32`] for the layout).
+ pub fn convert_u8(&self, src: &[u8], src_stride: usize, dst: &mut [u8], dst_stride: usize, copy_extra: bool) {
+ self.check(src_stride, dst_stride);
+ let extra = extra_channels(self, src_stride, dst_stride, copy_extra);
+ par_rows(src, src_stride, dst, dst_stride, |s, d| self.run_u8(s, src_stride, d, dst_stride, extra));
+ }
+
+ fn run_u8(&self, s: &[u8], ss: usize, d: &mut [u8], ds: usize, extra: usize) {
+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
+ let mut mid = [0.0f32; 16];
+ let mut out = [0.0f32; 16];
+ match &self.core {
+ Core::Grid(c) if c.inputs == 3 => {
+ let (g0, g1, g2) = (&self.grid8[0], &self.grid8[1], &self.grid8[2]);
+ let s1 = c.outputs * c.grid[2];
+ let s0 = s1 * c.grid[1];
+ for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
+ let (a, b, cc) = (g0[sp[0] as usize], g1[sp[1] as usize], g2[sp[2] as usize]);
+ c.tetra_pub(
+ (a.0 + b.0 + cc.0) as usize,
+ [s0, s1, c.outputs],
+ [a.1, b.1, cc.1],
+ &mut mid,
+ );
+ self.finish(&mid, &mut out);
+ for k in 0..self.outputs {
+ dp[k] = q(out[k]);
+ }
+ for e in 0..extra {
+ dp[self.outputs + e] = sp[self.inputs + e];
+ }
+ }
+ }
+ Core::Grid(c) if c.inputs == 4 => {
+ let g = &self.grid8;
+ let s3 = c.outputs;
+ let s2 = s3 * c.grid[3];
+ let s1 = s2 * c.grid[2];
+ let s0 = s1 * c.grid[1];
+ let mut hi = [0.0f32; 16];
+ for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
+ let (a, b, cc, k4) = (g[0][sp[0] as usize], g[1][sp[1] as usize], g[2][sp[2] as usize], g[3][sp[3] as usize]);
+ let base = (a.0 + b.0 + cc.0 + k4.0) as usize;
+ c.tetra_pub(base, [s1, s2, s3], [b.1, cc.1, k4.1], &mut mid);
+ if a.1 > 0.0 {
+ c.tetra_pub(base + s0, [s1, s2, s3], [b.1, cc.1, k4.1], &mut hi);
+ for k in 0..c.outputs {
+ mid[k] += (hi[k] - mid[k]) * a.1;
+ }
+ }
+ self.finish(&mid, &mut out);
+ for k in 0..self.outputs {
+ dp[k] = q(out[k]);
+ }
+ for e in 0..extra {
+ dp[self.outputs + e] = sp[self.inputs + e];
+ }
+ }
+ }
+ Core::Shaper { curves8, matrix, .. } => {
+ let mut v = [0.0f32; 16];
+ for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
+ for k in 0..self.inputs {
+ v[k] = if curves8.is_empty() { sp[k] as f32 / 255.0 } else { curves8[k][sp[k] as usize] };
+ }
+ apply_matrix(matrix, &v, &mut mid, self.inputs);
+ self.finish(&mid, &mut out);
+ for k in 0..self.outputs {
+ dp[k] = q(out[k]);
+ }
+ for e in 0..extra {
+ dp[self.outputs + e] = sp[self.inputs + e];
+ }
+ }
+ }
+ _ => {
+ let mut inp = [0.0f32; 16];
+ for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
+ for k in 0..self.inputs {
+ inp[k] = sp[k] as f32 / 255.0;
+ }
+ self.eval_fast(&inp, &mut out);
+ for k in 0..self.outputs {
+ dp[k] = q(out[k]);
+ }
+ for e in 0..extra {
+ dp[self.outputs + e] = sp[self.inputs + e];
+ }
+ }
+ }
+ }
+ }
+
+ /// Converts 16-bit pixels (see [`Transform::convert_f32`] for the layout).
+ pub fn convert_u16(&self, src: &[u16], src_stride: usize, dst: &mut [u16], dst_stride: usize, copy_extra: bool) {
+ self.check(src_stride, dst_stride);
+ let extra = extra_channels(self, src_stride, dst_stride, copy_extra);
+ par_rows(src, src_stride, dst, dst_stride, |s, d| self.run_u16(s, src_stride, d, dst_stride, extra));
+ }
+
+ fn run_u16(&self, s: &[u16], ss: usize, d: &mut [u16], ds: usize, extra: usize) {
+ let mut inp = [0.0f32; 16];
+ let mut out = [0.0f32; 16];
+ for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
+ for k in 0..self.inputs {
+ inp[k] = sp[k] as f32 / 65535.0;
+ }
+ self.eval_fast(&inp, &mut out);
+ for k in 0..self.outputs {
+ dp[k] = (out[k].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;
+ }
+ for e in 0..extra {
+ dp[self.outputs + e] = sp[self.inputs + e];
+ }
+ }
+ }
+
+ /// Converts many independent buffers of native-endian samples in one parallel pass (e.g.
+ /// all tiles of a surface): far cheaper than one parallel call per small buffer. Each job
+ /// is `(src bytes, dst bytes)` holding whole pixels of `src_stride`/`dst_stride` samples.
+ pub fn convert_bytes_many(&self, sample: SampleKind, jobs: Vec<(&[u8], &mut [u8])>, src_stride: usize, dst_stride: usize, copy_extra: bool) {
+ self.check(src_stride, dst_stride);
+ let extra = extra_channels(self, src_stride, dst_stride, copy_extra);
+ let run = |(s, d): (&[u8], &mut [u8])| match sample {
+ SampleKind::U8 => self.run_u8(s, src_stride, d, dst_stride, extra),
+ SampleKind::U16 => {
+ let a: Vec<u16> = s.chunks_exact(2).map(|b| u16::from_ne_bytes([b[0], b[1]])).collect();
+ let mut o: Vec<u16> = d.chunks_exact(2).map(|b| u16::from_ne_bytes([b[0], b[1]])).collect();
+ self.run_u16(&a, src_stride, &mut o, dst_stride, extra);
+ for (b, v) in d.chunks_exact_mut(2).zip(o) {
+ b.copy_from_slice(&v.to_ne_bytes());
+ }
+ }
+ SampleKind::F32 => {
+ let a: Vec<f32> = s.chunks_exact(4).map(|b| f32::from_ne_bytes([b[0], b[1], b[2], b[3]])).collect();
+ let mut o: Vec<f32> = d.chunks_exact(4).map(|b| f32::from_ne_bytes([b[0], b[1], b[2], b[3]])).collect();
+ self.run_f32(&a, src_stride, &mut o, dst_stride, extra);
+ for (b, v) in d.chunks_exact_mut(4).zip(o) {
+ b.copy_from_slice(&v.to_ne_bytes());
+ }
+ }
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ jobs.into_par_iter().for_each(run);
+ }
+ #[cfg(target_arch = "wasm32")]
+ jobs.into_iter().for_each(run);
+ }
+
+ fn check(&self, ss: usize, ds: usize) {
+ assert!(ss >= self.inputs && ds >= self.outputs, "pixel stride smaller than the channel count");
+ }
+}
+
+fn device_white(cs: ColorSpace) -> Option<Vec<f32>> {
+ Some(match cs {
+ ColorSpace::Rgb => vec![1.0; 3],
+ ColorSpace::Gray => vec![1.0],
+ ColorSpace::Cmyk => vec![0.0; 4],
+ ColorSpace::Cmy => vec![0.0; 3],
+ ColorSpace::Lab => vec![1.0, 0.5, 0.5],
+ _ => return None,
+ })
+}
+
+fn extra_channels(t: &Transform, ss: usize, ds: usize, copy: bool) -> usize {
+ if copy { (ss - t.inputs).min(ds - t.outputs) } else { 0 }
+}
+
+fn shaper(cs: &[Curve], matrix: Option<(usize, usize, &Vec<f64>, &Vec<f64>)>) -> Core {
+ let curves8 = cs.iter().map(|c| std::array::from_fn(|i| c.eval64(i as f64 / 255.0) as f32)).collect();
+ let curves = cs.iter().map(|c| (0..=TABLE_1D).map(|i| c.eval64(i as f64 / TABLE_1D as f64) as f32).collect()).collect();
+ let matrix = matrix.map(|(r, c, m, o)| (r, c, m.iter().map(|v| *v as f32).collect(), o.iter().map(|v| *v as f32).collect()));
+ Core::Shaper { curves8, curves, matrix }
+}
+
+#[inline]
+fn table(t: &[f32], x: f32) -> f32 {
+ // Sampled over [0, 1] with TABLE_1D segments; values outside extrapolate linearly from
+ // the end segments so HDR floats stay usable in the fast path.
+ let n = t.len() - 1;
+ let p = x * n as f32;
+ let i = (p.floor().max(0.0) as usize).min(n - 1);
+ let f = p - i as f32;
+ t[i] + (t[i + 1] - t[i]) * f
+}
+
+#[inline]
+fn apply_matrix(m: &Option<(usize, usize, Vec<f32>, Vec<f32>)>, v: &[f32; 16], out: &mut [f32; 16], n: usize) {
+ match m {
+ None => out[..n].copy_from_slice(&v[..n]),
+ Some((rows, cols, m, off)) => {
+ for r in 0..*rows {
+ let mut s = off[r];
+ for c in 0..*cols {
+ s += m[r * cols + c] * v[c];
+ }
+ out[r] = s;
+ }
+ }
+ }
+}
+
+// ------------------------------------------------------------ parallel helpers
+
+const PAR_MIN_PIXELS: usize = 16 * 1024;
+const PAR_CHUNK_PIXELS: usize = 8 * 1024;
+
+#[cfg(not(target_arch = "wasm32"))]
+fn par_rows<S: Sync, D: Send>(src: &[S], ss: usize, dst: &mut [D], ds: usize, f: impl Fn(&[S], &mut [D]) + Sync) {
+ use rayon::prelude::*;
+ let n = (src.len() / ss).min(dst.len() / ds);
+ let (src, dst) = (&src[..n * ss], &mut dst[..n * ds]);
+ if n < PAR_MIN_PIXELS {
+ return f(src, dst);
+ }
+ src.par_chunks(PAR_CHUNK_PIXELS * ss).zip(dst.par_chunks_mut(PAR_CHUNK_PIXELS * ds)).for_each(|(s, d)| f(s, d));
+}
+
+#[cfg(target_arch = "wasm32")]
+fn par_rows<S: Sync, D: Send>(src: &[S], ss: usize, dst: &mut [D], ds: usize, f: impl Fn(&[S], &mut [D]) + Sync) {
+ let n = (src.len() / ss).min(dst.len() / ds);
+ f(&src[..n * ss], &mut dst[..n * ds]);
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn par_inplace(buf: &mut [f32], stride: usize, f: impl Fn(&mut [f32]) + Sync) {
+ use rayon::prelude::*;
+ if buf.len() / stride < PAR_MIN_PIXELS {
+ return f(buf);
+ }
+ buf.par_chunks_mut(PAR_CHUNK_PIXELS * stride).for_each(&f);
+}
+
+#[cfg(target_arch = "wasm32")]
+fn par_inplace(buf: &mut [f32], _stride: usize, f: impl Fn(&mut [f32]) + Sync) {
+ f(buf)
+}
+
+// ------------------------------------------------------------ linking
+
+/// Stages from `src` device values to `dst` device values.
+pub(crate) fn link_stages(src: &Profile, dst: &Profile, intent: Intent, bpc: bool) -> Result<Vec<Stage>, CmsError> {
+ for p in [src, dst] {
+ if matches!(p.class, ProfileClass::DeviceLink | ProfileClass::NamedColor | ProfileClass::Abstract) && p.color_space != ColorSpace::Lab {
+ return Err(CmsError::Unsupported(format!("{:?} profiles cannot be used as a source or destination", p.class)));
+ }
+ }
+ let (mut stages, s_pcs) = src.device_to_pcs(intent)?;
+ let (d_stages, d_pcs) = dst.pcs_to_device(intent)?;
+ let adjust = connection(src, dst, intent, bpc)?;
+ match adjust {
+ Some((scale, offset)) => {
+ if s_pcs == Pcs::Lab {
+ stages.push(Stage::LabToXyz);
+ }
+ stages.push(Stage::Matrix {
+ rows: 3,
+ cols: 3,
+ m: vec![scale[0], 0.0, 0.0, 0.0, scale[1], 0.0, 0.0, 0.0, scale[2]],
+ offset: offset.to_vec(),
+ });
+ if d_pcs == Pcs::Lab {
+ stages.push(Stage::XyzToLab);
+ }
+ }
+ None => match (s_pcs, d_pcs) {
+ (Pcs::Lab, Pcs::Xyz) => stages.push(Stage::LabToXyz),
+ (Pcs::Xyz, Pcs::Lab) => stages.push(Stage::XyzToLab),
+ _ => {}
+ },
+ }
+ stages.extend(d_stages);
+ Ok(stages)
+}
+
+/// Per-component XYZ scale and offset applied in the PCS: absolute colorimetric media-white
+/// scaling or black point compensation. `None` = identity.
+/// Per-component XYZ `(scale, offset)`.
+type Affine3 = ([f64; 3], [f64; 3]);
+
+fn connection(src: &Profile, dst: &Profile, intent: Intent, bpc: bool) -> Result<Option<Affine3>, CmsError> {
+ if intent == Intent::AbsoluteColorimetric {
+ let (ws, wd) = (src.media_white(), dst.media_white());
+ let s = [ws[0] / wd[0], ws[1] / wd[1], ws[2] / wd[2]];
+ if s.iter().all(|v| (v - 1.0).abs() < 1e-6) {
+ return Ok(None);
+ }
+ return Ok(Some((s, [0.0; 3])));
+ }
+ if !bpc {
+ return Ok(None);
+ }
+ let bs = black_point(src, intent, true)?;
+ let bd = black_point(dst, intent, false)?;
+ if (bs - bd).abs() < 1e-6 {
+ return Ok(None);
+ }
+ // Neutral black points (luminance only, as in Adobe's BPC), mapped linearly in XYZ so that
+ // the source black lands on the destination black and the white stays fixed.
+ let w = math::D50;
+ let mut scale = [1.0; 3];
+ let mut offset = [0.0; 3];
+ for i in 0..3 {
+ let (s, d) = (bs * w[i], bd * w[i]);
+ let a = (w[i] - d) / (w[i] - s);
+ scale[i] = a;
+ offset[i] = w[i] * (1.0 - a);
+ }
+ Ok(Some((scale, offset)))
+}
+
+/// Luminance (Y, D50-relative) of the profile's black point for `intent`.
+///
+/// Follows the structure of Adobe's published BPC algorithm: matrix/TRC profiles use device
+/// zero; v4 LUT profiles in perceptual/saturation use the perceptual reference black; other LUT
+/// profiles use the darkest colour the device reaches (Lab 0 round-tripped through BToA/AToB,
+/// or device black for additive spaces). The destination-side curve fitting of the paper is
+/// not implemented; the round-trip black is used directly.
+pub fn black_point(p: &Profile, intent: Intent, _input: bool) -> Result<f64, CmsError> {
+ if matches!(p.color_space, ColorSpace::Lab | ColorSpace::Xyz) {
+ return Ok(0.0);
+ }
+ let lut_based = p.a2b.iter().any(Option::is_some);
+ if lut_based && p.version.0 >= 4 && matches!(intent, Intent::Perceptual | Intent::Saturation) {
+ return Ok(PERCEPTUAL_BLACK[1]);
+ }
+ let pcs_y = |st: Vec<Stage>, pcs: Pcs, dev: &[f32]| -> f64 {
+ let pipe = Pipeline::new(p.channels(), st);
+ let mut o = [0.0f32; 16];
+ pipe.eval(dev, &mut o);
+ let y = match pcs {
+ Pcs::Xyz => o[1] as f64,
+ Pcs::Lab => math::lab_to_xyz([o[0] as f64, 0.0, 0.0], math::D50)[1],
+ };
+ y.clamp(0.0, 0.5)
+ };
+ let (to_pcs, pcs) = p.device_to_pcs(intent)?;
+ let additive = matches!(p.color_space, ColorSpace::Rgb | ColorSpace::Gray);
+ if additive || !lut_based {
+ let zero = vec![0.0f32; p.channels()];
+ return Ok(pcs_y(to_pcs, pcs, &zero));
+ }
+ // Subtractive LUT profile: darkest reachable colour.
+ let colorimetric = if intent == Intent::Saturation { Intent::Saturation } else { Intent::RelativeColorimetric };
+ match p.pcs_to_device(colorimetric) {
+ Ok((from_pcs, fpcs)) => {
+ let mut st = Vec::new();
+ if fpcs == Pcs::Xyz {
+ st.push(Stage::LabToXyz);
+ }
+ st.extend(from_pcs);
+ let pipe = Pipeline::new(3, st);
+ let mut dev = [0.0f32; 16];
+ pipe.eval(&[0.0, 0.0, 0.0], &mut dev);
+ Ok(pcs_y(to_pcs, pcs, &dev[..p.channels()]))
+ }
+ Err(_) => {
+ let ones = vec![1.0f32; p.channels()];
+ Ok(pcs_y(to_pcs, pcs, &ones))
+ }
+ }
+}
+
+// ------------------------------------------------------------ cache
+
+type Key = (u64, u64, TransformOptions);
+
+/// Process-wide cache of transforms keyed by profile content and options.
+pub fn cached(src: &Profile, dst: &Profile, opts: TransformOptions) -> Result<Arc<Transform>, CmsError> {
+ static CACHE: OnceLock<Mutex<HashMap<Key, Arc<Transform>>>> = OnceLock::new();
+ let key = (src.content_hash(), dst.content_hash(), opts);
+ let cache = CACHE.get_or_init(Default::default);
+ if let Some(t) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
+ return Ok(t.clone());
+ }
+ let t = Arc::new(Transform::with_options(src, dst, opts)?);
+ let mut c = cache.lock().unwrap_or_else(|e| e.into_inner());
+ if c.len() > 64 {
+ c.clear();
+ }
+ c.insert(key, t.clone());
+ Ok(t)
+}
+
+impl Clut {
+ /// Tetrahedral interpolation in one cube (crate-internal fast paths).
+ #[inline]
+ pub(crate) fn tetra_pub(&self, base: usize, s: [usize; 3], r: [f32; 3], out: &mut [f32; 16]) {
+ let d = &self.data;
+ let [rx, ry, rz] = r;
+ let [sx, sy, sz] = s;
+ let (p1, p2, p3, w1, w2, w3) = if rx >= ry {
+ if ry >= rz {
+ (sx, sx + sy, sx + sy + sz, rx, ry, rz)
+ } else if rx >= rz {
+ (sx, sx + sz, sx + sy + sz, rx, rz, ry)
+ } else {
+ (sz, sx + sz, sx + sy + sz, rz, rx, ry)
+ }
+ } else if rx >= rz {
+ (sy, sx + sy, sx + sy + sz, ry, rx, rz)
+ } else if ry >= rz {
+ (sy, sy + sz, sx + sy + sz, ry, rz, rx)
+ } else {
+ (sz, sy + sz, sx + sy + sz, rz, ry, rx)
+ };
+ let o = self.outputs.min(MAX_CHANNELS);
+ for k in 0..o {
+ let v0 = d[base + k];
+ let v1 = d[base + p1 + k];
+ let v2 = d[base + p2 + k];
+ let v3 = d[base + p3 + k];
+ out[k] = v0 + (v1 - v0) * w1 + (v2 - v1) * w2 + (v3 - v2) * w3;
+ }
+ }
+}
diff --git a/crates/cms/src/write.rs b/crates/cms/src/write.rs
new file mode 100644
index 000000000..cdb86d082
--- /dev/null
+++ b/crates/cms/src/write.rs
@@ -0,0 +1,337 @@
+//! ICC v4.3 profile writer (ICC.1:2010), used for built-in and synthetic profiles.
+
+use crate::clut::Clut;
+use crate::curve::Curve;
+use crate::math;
+use crate::pipeline::Stage;
+use crate::profile::{LutKind, Pcs, Profile};
+
+fn s15(v: f64) -> [u8; 4] {
+ ((v * 65536.0).round() as i32).to_be_bytes()
+}
+
+fn xyz_type(v: [f64; 3]) -> Vec<u8> {
+ let mut o = b"XYZ \0\0\0\0".to_vec();
+ for c in v {
+ o.extend_from_slice(&s15(c));
+ }
+ o
+}
+
+fn mluc(text: &str) -> Vec<u8> {
+ let units: Vec<u16> = text.encode_utf16().collect();
+ let mut o = b"mluc\0\0\0\0".to_vec();
+ o.extend_from_slice(&1u32.to_be_bytes());
+ o.extend_from_slice(&12u32.to_be_bytes());
+ o.extend_from_slice(b"enUS");
+ o.extend_from_slice(&((units.len() * 2) as u32).to_be_bytes());
+ o.extend_from_slice(&28u32.to_be_bytes());
+ for u in units {
+ o.extend_from_slice(&u.to_be_bytes());
+ }
+ o
+}
+
+fn u16q(v: f32) -> u16 {
+ (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16
+}
+
+/// `curv` or `para` element for a curve.
+fn curve_elem(c: &Curve) -> Vec<u8> {
+ match c {
+ Curve::Identity => {
+ let mut o = b"curv\0\0\0\0".to_vec();
+ o.extend_from_slice(&0u32.to_be_bytes());
+ o
+ }
+ Curve::Gamma(g) => {
+ let mut o = b"para\0\0\0\0".to_vec();
+ o.extend_from_slice(&[0, 0, 0, 0]);
+ o.extend_from_slice(&s15(*g));
+ o
+ }
+ Curve::Parametric { kind, p } => {
+ let mut o = b"para\0\0\0\0".to_vec();
+ o.extend_from_slice(&kind.to_be_bytes());
+ o.extend_from_slice(&[0, 0]);
+ for v in p.iter().take(Curve::param_count(*kind)) {
+ o.extend_from_slice(&s15(*v));
+ }
+ o
+ }
+ Curve::Table(t) => {
+ let mut o = b"curv\0\0\0\0".to_vec();
+ o.extend_from_slice(&(t.len() as u32).to_be_bytes());
+ for v in t {
+ o.extend_from_slice(&u16q(*v).to_be_bytes());
+ }
+ o
+ }
+ }
+}
+
+fn pad4(v: &mut Vec<u8>) {
+ while !v.len().is_multiple_of(4) {
+ v.push(0);
+ }
+}
+
+fn curve_table(c: &Curve, n: usize) -> Vec<f32> {
+ match c {
+ Curve::Table(t) if t.len() == n => t.clone(),
+ _ => c.sample(n),
+ }
+}
+
+fn table_len(cs: &[Curve]) -> usize {
+ cs.iter()
+ .map(|c| match c {
+ Curve::Table(t) => t.len(),
+ Curve::Identity => 2,
+ _ => 1024,
+ })
+ .max()
+ .unwrap_or(2)
+ .clamp(2, 4096)
+}
+
+/// Splits a LUT's stages into `(matrix, input curves, clut, output curves)` for `mft1`/`mft2`.
+type LutParts<'a> = (Option<Vec<f64>>, &'a [Curve], &'a Clut, &'a [Curve]);
+
+fn lut_parts(stages: &[Stage]) -> Option<LutParts<'_>> {
+ let mut i = 0;
+ let mut mat = None;
+ if let Some(Stage::Matrix { rows: 3, cols: 3, m, .. }) = stages.first() {
+ mat = Some(m.clone());
+ i = 1;
+ }
+ match &stages[i..] {
+ [Stage::Curves(a), Stage::Clut(c), Stage::Curves(b)] => Some((mat, a, c, b)),
+ _ => None,
+ }
+}
+
+fn encode_mft(stages: &[Stage], wide: bool) -> Vec<u8> {
+ let (mat, a, clut, b) = lut_parts(stages).expect("lut8/lut16 stages are [matrix?] curves, clut, curves");
+ let g = clut.grid[0];
+ assert!(clut.grid.iter().all(|x| *x == g), "lut8/lut16 need a uniform grid");
+ let mut o = if wide { b"mft2\0\0\0\0".to_vec() } else { b"mft1\0\0\0\0".to_vec() };
+ o.extend_from_slice(&[clut.inputs as u8, clut.outputs as u8, g as u8, 0]);
+ let m = mat.unwrap_or_else(|| vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
+ for v in &m {
+ o.extend_from_slice(&s15(*v));
+ }
+ let (n_in, n_out) = if wide { (table_len(a), table_len(b)) } else { (256, 256) };
+ if wide {
+ o.extend_from_slice(&(n_in as u16).to_be_bytes());
+ o.extend_from_slice(&(n_out as u16).to_be_bytes());
+ }
+ let put = |o: &mut Vec<u8>, v: f32| {
+ if wide {
+ o.extend_from_slice(&u16q(v).to_be_bytes());
+ } else {
+ o.push((v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
+ }
+ };
+ for c in a {
+ for v in curve_table(c, n_in) {
+ put(&mut o, v);
+ }
+ }
+ for v in &clut.data {
+ put(&mut o, *v);
+ }
+ for c in b {
+ for v in curve_table(c, n_out) {
+ put(&mut o, v);
+ }
+ }
+ o
+}
+
+fn encode_ab(stages: &[Stage], a2b: bool, inputs: usize, outputs: usize) -> Vec<u8> {
+ let mut a_curves: Option<&[Curve]> = None;
+ let mut clut: Option<&Clut> = None;
+ let mut m_curves: Option<&[Curve]> = None;
+ let mut matrix: Option<(&Vec<f64>, &Vec<f64>)> = None;
+ let mut b_curves: Option<&[Curve]> = None;
+ let mut it = stages.iter().peekable();
+ if a2b {
+ // [A, CLUT] [M, matrix] B
+ if let (Some(Stage::Curves(a)), Some(Stage::Clut(_))) = (stages.first(), stages.get(1)) {
+ a_curves = Some(a);
+ it.next();
+ if let Some(Stage::Clut(c)) = it.next() {
+ clut = Some(c);
+ }
+ }
+ let rest: Vec<&Stage> = it.collect();
+ match rest.as_slice() {
+ [Stage::Curves(m), Stage::Matrix { m: mm, offset, .. }, Stage::Curves(b)] => {
+ m_curves = Some(m.as_slice());
+ matrix = Some((mm, offset));
+ b_curves = Some(b.as_slice());
+ }
+ [Stage::Curves(b)] => b_curves = Some(b.as_slice()),
+ _ => panic!("unsupported lutAtoB stage layout"),
+ }
+ } else {
+ // B [matrix, M] [CLUT, A]
+ let v: Vec<&Stage> = it.collect();
+ let mut k = 0;
+ if let Some(Stage::Curves(b)) = v.first() {
+ b_curves = Some(b.as_slice());
+ k = 1;
+ }
+ if let (Some(Stage::Matrix { m: mm, offset, .. }), Some(Stage::Curves(m))) = (v.get(k), v.get(k + 1)) {
+ matrix = Some((mm, offset));
+ m_curves = Some(m.as_slice());
+ k += 2;
+ }
+ if let (Some(Stage::Clut(c)), Some(Stage::Curves(a))) = (v.get(k), v.get(k + 1)) {
+ clut = Some(c);
+ a_curves = Some(a.as_slice());
+ k += 2;
+ }
+ assert_eq!(k, v.len(), "unsupported lutBtoA stage layout");
+ }
+ let mut o = if a2b { b"mAB \0\0\0\0".to_vec() } else { b"mBA \0\0\0\0".to_vec() };
+ o.extend_from_slice(&[inputs as u8, outputs as u8, 0, 0]);
+ o.extend_from_slice(&[0u8; 20]); // offsets, patched below
+ let mut offs = [0u32; 5]; // B, matrix, M, CLUT, A
+ let curves = |o: &mut Vec<u8>, cs: &[Curve]| {
+ for c in cs {
+ o.extend_from_slice(&curve_elem(c));
+ pad4(o);
+ }
+ };
+ let b = b_curves.expect("B curves are required");
+ offs[0] = o.len() as u32;
+ curves(&mut o, b);
+ if let Some((mm, off)) = matrix {
+ offs[1] = o.len() as u32;
+ for v in mm.iter() {
+ o.extend_from_slice(&s15(*v));
+ }
+ for v in off.iter() {
+ o.extend_from_slice(&s15(*v));
+ }
+ offs[2] = o.len() as u32;
+ curves(&mut o, m_curves.expect("M curves accompany the matrix"));
+ }
+ if let Some(c) = clut {
+ offs[3] = o.len() as u32;
+ let mut g = [0u8; 16];
+ for (k, n) in c.grid.iter().enumerate() {
+ g[k] = *n as u8;
+ }
+ o.extend_from_slice(&g);
+ o.extend_from_slice(&[2, 0, 0, 0]);
+ for v in &c.data {
+ o.extend_from_slice(&u16q(*v).to_be_bytes());
+ }
+ pad4(&mut o);
+ offs[4] = o.len() as u32;
+ curves(&mut o, a_curves.expect("A curves accompany the CLUT"));
+ }
+ for (k, v) in offs.iter().enumerate() {
+ o[12 + k * 4..16 + k * 4].copy_from_slice(&v.to_be_bytes());
+ }
+ o
+}
+
+/// Encodes `p` as ICC v4.3 bytes (identical tag data is shared between tags).
+pub fn encode(p: &Profile) -> Vec<u8> {
+ let mut tags: Vec<([u8; 4], Vec<u8>)> = Vec::new();
+ tags.push((*b"desc", mluc(&p.description)));
+ tags.push((*b"cprt", mluc(&p.copyright)));
+ tags.push((*b"wtpt", xyz_type(p.white_point)));
+ if let Some(bk) = p.black_point {
+ tags.push((*b"bkpt", xyz_type(bk)));
+ }
+ if let Some(c) = &p.chad {
+ let mut o = b"sf32\0\0\0\0".to_vec();
+ for v in c.iter().flatten() {
+ o.extend_from_slice(&s15(*v));
+ }
+ tags.push((*b"chad", o));
+ }
+ if let Some(m) = &p.matrix {
+ tags.push((*b"rXYZ", xyz_type([m[0][0], m[1][0], m[2][0]])));
+ tags.push((*b"gXYZ", xyz_type([m[0][1], m[1][1], m[2][1]])));
+ tags.push((*b"bXYZ", xyz_type([m[0][2], m[1][2], m[2][2]])));
+ }
+ if let Some([r, g, b]) = &p.trc {
+ tags.push((*b"rTRC", curve_elem(r)));
+ tags.push((*b"gTRC", curve_elem(g)));
+ tags.push((*b"bTRC", curve_elem(b)));
+ }
+ if let Some(k) = &p.gray_trc {
+ tags.push((*b"kTRC", curve_elem(k)));
+ }
+ for (luts, names, a2b) in [(&p.a2b, [b"A2B0", b"A2B1", b"A2B2"], true), (&p.b2a, [b"B2A0", b"B2A1", b"B2A2"], false)] {
+ for (l, name) in luts.iter().zip(names) {
+ if let Some(l) = l {
+ let data = match l.kind {
+ LutKind::Lut16 => encode_mft(&l.stages, true),
+ LutKind::Lut8 => encode_mft(&l.stages, false),
+ LutKind::Ab => encode_ab(&l.stages, a2b, l.inputs, l.outputs),
+ };
+ tags.push((*name, data));
+ }
+ }
+ }
+
+ // Layout: header, tag table, then data (identical payloads share one copy).
+ let table_len = 4 + tags.len() * 12;
+ let mut data: Vec<u8> = Vec::new();
+ let mut entries: Vec<([u8; 4], u32, u32)> = Vec::new();
+ let mut placed: Vec<(usize, u32, u32)> = Vec::new(); // (tag index, offset, len)
+ for (i, (sig, d)) in tags.iter().enumerate() {
+ if let Some((_, off, len)) = placed.iter().find(|(j, _, _)| tags[*j].1 == *d) {
+ entries.push((*sig, *off, *len));
+ continue;
+ }
+ let off = (128 + table_len + data.len()) as u32;
+ data.extend_from_slice(d);
+ pad4(&mut data);
+ entries.push((*sig, off, d.len() as u32));
+ placed.push((i, off, d.len() as u32));
+ }
+ let size = 128 + table_len + data.len();
+ let mut o = Vec::with_capacity(size);
+ o.extend_from_slice(&(size as u32).to_be_bytes());
+ o.extend_from_slice(&[0, 0, 0, 0]); // preferred CMM
+ o.extend_from_slice(&[4, 0x30, 0, 0]); // version 4.3
+ o.extend_from_slice(&p.class.sig().to_be_bytes());
+ o.extend_from_slice(&p.color_space.sig().to_be_bytes());
+ o.extend_from_slice(match p.pcs {
+ Pcs::Xyz => b"XYZ ",
+ Pcs::Lab => b"Lab ",
+ });
+ for v in [2026u16, 1, 1, 0, 0, 0] {
+ o.extend_from_slice(&v.to_be_bytes());
+ }
+ o.extend_from_slice(b"acsp");
+ o.extend_from_slice(&[0; 4]); // platform
+ o.extend_from_slice(&[0; 4]); // flags
+ o.extend_from_slice(&[0; 4]); // manufacturer
+ o.extend_from_slice(&[0; 4]); // model
+ o.extend_from_slice(&[0; 8]); // attributes
+ o.extend_from_slice(&(p.rendering_intent as u32).to_be_bytes());
+ for v in math::D50 {
+ o.extend_from_slice(&s15(v));
+ }
+ o.extend_from_slice(&[0; 4]); // creator
+ o.extend_from_slice(&[0; 16]); // profile id (not computed)
+ o.resize(128, 0);
+ o.extend_from_slice(&(entries.len() as u32).to_be_bytes());
+ for (sig, off, len) in &entries {
+ o.extend_from_slice(sig);
+ o.extend_from_slice(&off.to_be_bytes());
+ o.extend_from_slice(&len.to_be_bytes());
+ }
+ o.extend_from_slice(&data);
+ debug_assert_eq!(o.len(), size);
+ o
+}
diff --git a/crates/cms/tests/bench.rs b/crates/cms/tests/bench.rs
new file mode 100644
index 000000000..e0b9628a5
--- /dev/null
+++ b/crates/cms/tests/bench.rs
@@ -0,0 +1,29 @@
+//! Throughput check: `cargo test -p photocraft-cms --release --test bench -- --ignored --nocapture`.
+
+use photocraft_cms::{Builtin, Intent, Transform};
+
+#[test]
+#[ignore]
+fn bench_srgb8_to_cmyk8() {
+ let t0 = std::time::Instant::now();
+ let t = Transform::new(Builtin::Srgb.profile(), Builtin::CoatedCmyk.profile(), Intent::RelativeColorimetric, true).unwrap();
+ eprintln!("build: {:?}", t0.elapsed());
+ let n = 6016 * 6016;
+ let mut src = vec![0u8; n * 4];
+ let mut x = 1u32;
+ for v in src.iter_mut() {
+ x ^= x << 13;
+ x ^= x >> 17;
+ x ^= x << 5;
+ *v = x as u8;
+ }
+ let mut dst = vec![0u8; n * 5];
+ let t1 = std::time::Instant::now();
+ t.convert_u8(&src, 4, &mut dst, 5, true);
+ eprintln!("convert 6016² RGBA8 → CMYKA8 (one buffer): {:?}", t1.elapsed());
+ let t2 = std::time::Instant::now();
+ for (s, d) in src.chunks(65536 * 4).zip(dst.chunks_mut(65536 * 5)) {
+ t.convert_u8(s, 4, d, 5, true);
+ }
+ eprintln!("convert per 256² tile: {:?}", t2.elapsed());
+}
diff --git a/crates/cms/tests/cms.rs b/crates/cms/tests/cms.rs
new file mode 100644
index 000000000..2a1ab9d60
--- /dev/null
+++ b/crates/cms/tests/cms.rs
@@ -0,0 +1,496 @@
+//! Integration tests: built-in profiles, known colorimetric values, round trips, CMYK
+//! behaviour, intents, BPC, interpolation accuracy, real-world profiles and an independent
+//! oracle (moxcms, dev-dependency only).
+
+use photocraft_cms::math::{self, delta_e76};
+use photocraft_cms::{Builtin, Clut, ColorSpace, Intent, Lut3d, Profile, Transform, TransformOptions};
+
+fn lab() -> &'static Profile {
+ Builtin::LabD50.profile()
+}
+fn srgb() -> &'static Profile {
+ Builtin::Srgb.profile()
+}
+fn cmyk() -> &'static Profile {
+ Builtin::CoatedCmyk.profile()
+}
+
+/// Normalised device Lab (v4 encoding) → float Lab.
+fn dec(o: &[f32]) -> [f64; 3] {
+ [o[0] as f64 * 100.0, o[1] as f64 * 255.0 - 128.0, o[2] as f64 * 255.0 - 128.0]
+}
+fn enc(l: [f64; 3]) -> [f32; 3] {
+ [(l[0] / 100.0) as f32, ((l[1] + 128.0) / 255.0) as f32, ((l[2] + 128.0) / 255.0) as f32]
+}
+
+fn to_lab(p: &Profile, dev: &[f32], intent: Intent) -> [f64; 3] {
+ let t = Transform::new(p, lab(), intent, false).unwrap();
+ let mut o = [0.0f32; 3];
+ t.eval(dev, &mut o);
+ dec(&o)
+}
+
+#[test]
+fn builtins_encode_and_reparse() {
+ for b in Builtin::ALL {
+ let p = b.profile();
+ let bytes = p.to_bytes();
+ let q = Profile::parse(&bytes).unwrap_or_else(|e| panic!("{b:?}: {e}"));
+ assert_eq!(q.description, b.description(), "{b:?}");
+ assert_eq!(q.color_space, p.color_space);
+ assert_eq!(&*q.to_bytes(), &*bytes, "{b:?} bytes are kept verbatim");
+ assert_eq!(Builtin::from_id(b.id()), Some(b));
+ // Every builtin converts to Lab and back.
+ Transform::new(p, lab(), Intent::RelativeColorimetric, false).unwrap();
+ Transform::new(lab(), p, Intent::RelativeColorimetric, false).unwrap();
+ }
+ assert_eq!(Builtin::from_id("Adobe RGB (1998)"), Some(Builtin::AdobeRgbCompat));
+}
+
+#[test]
+fn srgb_known_lab_values() {
+ let w = to_lab(srgb(), &[1.0, 1.0, 1.0], Intent::RelativeColorimetric);
+ assert!((w[0] - 100.0).abs() < 0.01 && w[1].abs() < 0.01 && w[2].abs() < 0.01, "white {w:?}");
+ let k = to_lab(srgb(), &[0.0, 0.0, 0.0], Intent::RelativeColorimetric);
+ assert!(k[0].abs() < 0.01, "black {k:?}");
+ // ICC PCS is D50: sRGB red Bradford-adapted to D50 is L*a*b* ≈ (54.29, 80.80, 69.89).
+ // (53.24, 80.09, 67.20) is the same colour referenced to D65 without adaptation.
+ let r = to_lab(srgb(), &[1.0, 0.0, 0.0], Intent::RelativeColorimetric);
+ assert!(delta_e76(r, [54.29, 80.80, 69.89]) < 0.15, "red {r:?}");
+ let g = to_lab(srgb(), &[0.0, 1.0, 0.0], Intent::RelativeColorimetric);
+ assert!(delta_e76(g, [87.82, -79.29, 80.99]) < 0.3, "green {g:?}");
+ let b = to_lab(srgb(), &[0.0, 0.0, 1.0], Intent::RelativeColorimetric);
+ assert!(delta_e76(b, [29.57, 68.30, -112.03]) < 0.3, "blue {b:?}");
+ // Grays are neutral in every RGB builtin.
+ for bi in [Builtin::Srgb, Builtin::DisplayP3, Builtin::AdobeRgbCompat, Builtin::ProPhotoCompat, Builtin::LinearSrgb, Builtin::Rec2020] {
+ let m = to_lab(bi.profile(), &[0.5, 0.5, 0.5], Intent::RelativeColorimetric);
+ assert!(m[1].abs() < 0.02 && m[2].abs() < 0.02, "{bi:?} gray {m:?}");
+ }
+}
+
+#[test]
+fn rgb_lab_rgb_roundtrip_8bit_and_float() {
+ let to = Transform::new(srgb(), lab(), Intent::RelativeColorimetric, false).unwrap();
+ let back = Transform::new(lab(), srgb(), Intent::RelativeColorimetric, false).unwrap();
+ // 8-bit RGB through a float Lab intermediate: exact to the 8-bit level.
+ let mut src8 = Vec::new();
+ for r in (0..256).step_by(5) {
+ for g in (0..256).step_by(7) {
+ for b in (0..256).step_by(9) {
+ src8.extend_from_slice(&[r as u8, g as u8, b as u8]);
+ }
+ }
+ }
+ let f: Vec<f32> = src8.iter().map(|v| *v as f32 / 255.0).collect();
+ let mut labf = vec![0.0f32; f.len()];
+ to.convert_f32(&f, 3, &mut labf, 3, false);
+ let mut rgbf = vec![0.0f32; f.len()];
+ back.convert_f32(&labf, 3, &mut rgbf, 3, false);
+ for (a, b) in src8.iter().zip(&rgbf) {
+ assert!((*a as f32 - b * 255.0).abs() <= 1.0, "{a} vs {}", b * 255.0);
+ }
+ // 8-bit RGB stored as 16-bit Lab then back to 8-bit through the lookup tables.
+ let lab16: Vec<u16> = labf.iter().map(|v| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16).collect();
+ let mut rgb16 = vec![0u16; lab16.len()];
+ back.convert_u16(&lab16, 3, &mut rgb16, 3, false);
+ for (a, b) in src8.iter().zip(&rgb16) {
+ assert!((*a as f32 - *b as f32 / 257.0).abs() <= 1.0, "{a} vs {}", *b as f32 / 257.0);
+ }
+ // Float: 1e-4.
+ for (a, b) in f.iter().zip(&rgbf) {
+ assert!((a - b).abs() < 1e-4, "{a} vs {b}");
+ }
+ // Fast 8-bit path: RGB8 → Lab8-grid → compare with exact within 1 level of Lab encoding.
+ let mut lab8 = vec![0u8; src8.len()];
+ to.convert_u8(&src8, 3, &mut lab8, 3, false);
+ for (q, e) in lab8.iter().zip(&labf) {
+ assert!((*q as f32 - e * 255.0).abs() <= 1.0);
+ }
+}
+
+#[test]
+fn rgb_to_rgb_matrix_shaper_paths_agree() {
+ // Integer lookup path vs exact pipeline for pure-gamma destinations (hard near black).
+ for dst in [Builtin::AdobeRgbCompat, Builtin::ProPhotoCompat, Builtin::DisplayP3, Builtin::LinearSrgb] {
+ let t = Transform::new(srgb(), dst.profile(), Intent::RelativeColorimetric, false).unwrap();
+ let src: Vec<u8> = (0..=255u8).flat_map(|v| [v, v / 2, 255 - v]).collect();
+ let mut out = vec![0u8; src.len()];
+ t.convert_u8(&src, 3, &mut out, 3, false);
+ for (px, o) in src.chunks(3).zip(out.chunks(3)) {
+ let mut e = [0.0f32; 3];
+ t.eval(&[px[0] as f32 / 255.0, px[1] as f32 / 255.0, px[2] as f32 / 255.0], &mut e);
+ for k in 0..3 {
+ assert!((o[k] as f32 - e[k].clamp(0.0, 1.0) * 255.0).abs() <= 0.6, "{dst:?} {px:?}: {o:?} vs {e:?}");
+ }
+ }
+ }
+}
+
+#[test]
+fn identity_transform_is_identity() {
+ let t = Transform::new(srgb(), srgb(), Intent::RelativeColorimetric, true).unwrap();
+ let src: Vec<u8> = (0..=255u8).flat_map(|v| [v, 255 - v, v / 3, 77]).collect();
+ let mut out = vec![0u8; src.len()];
+ t.convert_u8(&src, 4, &mut out, 4, true);
+ assert_eq!(src, out);
+}
+
+#[test]
+fn cmyk_profile_is_monotonic_and_in_range() {
+ let p = cmyk();
+ assert_eq!(p.color_space, ColorSpace::Cmyk);
+ // CMYK → Lab: L* decreases with every ink.
+ for ink in 0..4 {
+ let mut prev = f64::INFINITY;
+ for i in 0..=32 {
+ let mut v = [0.1f32, 0.1, 0.1, 0.1];
+ v[ink] = i as f32 / 32.0;
+ let l = to_lab(p, &v, Intent::RelativeColorimetric)[0];
+ assert!(l <= prev + 0.05, "ink {ink} at {i}: {l} > {prev}");
+ prev = l;
+ }
+ }
+ // Paper is L* 100 (relative).
+ let w = to_lab(p, &[0.0; 4], Intent::RelativeColorimetric);
+ assert!(delta_e76(w, [100.0, 0.0, 0.0]) < 0.5, "{w:?}");
+ // sRGB gray ramp → CMYK: in range, K never decreases, total ink within the limit.
+ for intent in [Intent::Perceptual, Intent::RelativeColorimetric] {
+ let t = Transform::new(srgb(), p, intent, true).unwrap();
+ let mut prev_k = -1.0f32;
+ let mut prev_l = f64::INFINITY;
+ let back = Transform::new(p, lab(), Intent::RelativeColorimetric, false).unwrap();
+ for v in (0..=255).rev().step_by(5) {
+ let g = v as f32 / 255.0;
+ let mut o = [0.0f32; 4];
+ t.eval(&[g, g, g], &mut o);
+ assert!(o.iter().all(|c| (-1e-6..=1.0 + 1e-6).contains(c)), "{o:?}");
+ assert!(o.iter().sum::<f32>() <= 3.0 + 0.02, "TAC {o:?}");
+ assert!(o[3] >= prev_k - 0.01, "{intent:?} K not monotonic at {v}: {o:?}");
+ prev_k = o[3];
+ let mut l = [0.0f32; 3];
+ back.eval(&o, &mut l);
+ let lab = dec(&l);
+ assert!(lab[0] <= prev_l + 0.3, "{intent:?} L* not monotonic at {v}: {lab:?}");
+ assert!(lab[1].abs() < 3.0 && lab[2].abs() < 3.0, "{intent:?} gray {v} not neutral: {lab:?}");
+ prev_l = lab[0];
+ }
+ }
+ // Arbitrary colours: CMYK outputs in range for u8 and float paths.
+ let t = Transform::new(srgb(), p, Intent::RelativeColorimetric, true).unwrap();
+ let src: Vec<u8> = (0..4096u32).flat_map(|i| [(i * 37 % 256) as u8, (i * 91 % 256) as u8, (i * 13 % 256) as u8]).collect();
+ let mut out = vec![0u8; 4096 * 4];
+ t.convert_u8(&src, 3, &mut out, 4, false);
+ for px in out.chunks(4) {
+ assert!(px.iter().map(|v| *v as u32).sum::<u32>() <= 3 * 255 + 8, "{px:?}");
+ }
+}
+
+#[test]
+fn in_gamut_colours_survive_cmyk_roundtrip() {
+ let to = Transform::new(lab(), cmyk(), Intent::RelativeColorimetric, false).unwrap();
+ let back = Transform::new(cmyk(), lab(), Intent::RelativeColorimetric, false).unwrap();
+ for target in [[50.0, 0.0, 0.0], [70.0, 10.0, 10.0], [60.0, -20.0, -20.0], [80.0, 0.0, 40.0], [40.0, 30.0, -10.0]] {
+ let mut c = [0.0f32; 4];
+ to.eval(&enc(target), &mut c);
+ let mut l = [0.0f32; 3];
+ back.eval(&c, &mut l);
+ assert!(delta_e76(dec(&l), target) < 2.0, "{target:?} -> {c:?} -> {:?}", dec(&l));
+ }
+}
+
+#[test]
+fn intents_differ_as_expected() {
+ let per = Transform::new(srgb(), cmyk(), Intent::Perceptual, false).unwrap();
+ let rel = Transform::new(srgb(), cmyk(), Intent::RelativeColorimetric, false).unwrap();
+ let sat = Transform::new(srgb(), cmyk(), Intent::Saturation, false).unwrap();
+ let (mut a, mut b, mut s) = ([0.0f32; 4], [0.0f32; 4], [0.0f32; 4]);
+ // Out-of-gamut sRGB blue: perceptual compresses, relative clips: different separations.
+ per.eval(&[0.0, 0.2, 1.0], &mut a);
+ rel.eval(&[0.0, 0.2, 1.0], &mut b);
+ sat.eval(&[0.0, 0.2, 1.0], &mut s);
+ let d: f32 = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).sum();
+ assert!(d > 0.03, "perceptual {a:?} vs relative {b:?}");
+ assert_eq!(a, s, "saturation shares the perceptual table");
+ // Relative vs absolute on CMYK paper white shown in sRGB: relative is white, absolute shows
+ // the paper tint (darker, slightly blue: paper Lab 95/0/−2).
+ let rel = Transform::new(cmyk(), srgb(), Intent::RelativeColorimetric, false).unwrap();
+ let abs = Transform::new(cmyk(), srgb(), Intent::AbsoluteColorimetric, false).unwrap();
+ let (mut w1, mut w2) = ([0.0f32; 3], [0.0f32; 3]);
+ rel.eval(&[0.0; 4], &mut w1);
+ abs.eval(&[0.0; 4], &mut w2);
+ assert!(w1.iter().all(|v| *v > 0.995), "{w1:?}");
+ assert!(w2[0] < 0.97 && w2[2] > w2[0], "{w2:?}");
+ let l = to_lab(cmyk(), &[0.0; 4], Intent::AbsoluteColorimetric);
+ assert!(delta_e76(l, [95.0, 0.0, -2.0]) < 0.6, "absolute paper {l:?}");
+}
+
+#[test]
+fn black_point_compensation() {
+ let bp = photocraft_cms::black_point(cmyk(), Intent::RelativeColorimetric, false).unwrap();
+ let bl = math::xyz_to_lab([bp * 0.9642, bp, bp * 0.8249], math::D50)[0];
+ assert!(bl > 4.0 && bl < 20.0, "CMYK black L* {bl}");
+ assert_eq!(photocraft_cms::black_point(srgb(), Intent::RelativeColorimetric, true).unwrap(), 0.0);
+ // sRGB → CMYK: without BPC, deep shadows below the paper's black clip together; with BPC
+ // they stay distinct.
+ let with = Transform::new(srgb(), cmyk(), Intent::RelativeColorimetric, true).unwrap();
+ let without = Transform::new(srgb(), cmyk(), Intent::RelativeColorimetric, false).unwrap();
+ let back = Transform::new(cmyk(), lab(), Intent::RelativeColorimetric, false).unwrap();
+ let l_of = |t: &Transform, v: f32| {
+ let mut c = [0.0f32; 4];
+ t.eval(&[v, v, v], &mut c);
+ let mut l = [0.0f32; 3];
+ back.eval(&c, &mut l);
+ dec(&l)[0]
+ };
+ let (w0, w1) = (l_of(&with, 0.0), l_of(&with, 0.08));
+ let (n0, n1) = (l_of(&without, 0.0), l_of(&without, 0.08));
+ assert!(w1 - w0 > 1.5, "BPC keeps shadow detail: {w0} {w1}");
+ assert!((n1 - n0).abs() < w1 - w0, "no BPC compresses shadows: {n0} {n1}");
+ // CMYK → sRGB: with BPC the darkest CMYK maps to (near) sRGB black.
+ let dark = {
+ let mut c = [0.0f32; 4];
+ with.eval(&[0.0, 0.0, 0.0], &mut c);
+ c
+ };
+ let rgb_with = Transform::new(cmyk(), srgb(), Intent::RelativeColorimetric, true).unwrap();
+ let rgb_without = Transform::new(cmyk(), srgb(), Intent::RelativeColorimetric, false).unwrap();
+ let (mut a, mut b) = ([0.0f32; 3], [0.0f32; 3]);
+ rgb_with.eval(&dark, &mut a);
+ rgb_without.eval(&dark, &mut b);
+ assert!(a[1] < 0.03 && b[1] > a[1] + 0.03, "with {a:?} without {b:?}");
+}
+
+#[test]
+fn tetrahedral_beats_trilinear() {
+ // Sample sRGB → Lab on a coarse grid and compare interpolation against the exact pipeline.
+ let exact = Transform::new(srgb(), lab(), Intent::RelativeColorimetric, false).unwrap();
+ let clut = Clut::sample(vec![9, 9, 9], 3, |i, o| exact.eval(i, o));
+ let (mut tet_max, mut tri_max, mut tet_sum, mut tri_sum, mut tet_neutral, mut tri_neutral) = (0.0f64, 0.0f64, 0.0, 0.0, 0.0f64, 0.0f64);
+ let mut n = 0.0;
+ let mut seed = 12345u32;
+ let mut rnd = || {
+ seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
+ (seed >> 8) as f32 / (1 << 24) as f32
+ };
+ for i in 0..4000 {
+ let p = if i < 200 {
+ let v = i as f32 / 199.0;
+ [v, v, v]
+ } else {
+ [rnd(), rnd(), rnd()]
+ };
+ let (mut e, mut a, mut b) = ([0.0f32; 3], [0.0f32; 3], [0.0f32; 3]);
+ exact.eval(&p, &mut e);
+ clut.eval(&p, &mut a);
+ clut.eval_trilinear(&p, &mut b);
+ let (da, db) = (delta_e76(dec(&a), dec(&e)), delta_e76(dec(&b), dec(&e)));
+ if i < 200 {
+ tet_neutral = tet_neutral.max(dec(&a)[1].abs().max(dec(&a)[2].abs()));
+ tri_neutral = tri_neutral.max(dec(&b)[1].abs().max(dec(&b)[2].abs()));
+ }
+ tet_max = tet_max.max(da);
+ tri_max = tri_max.max(db);
+ tet_sum += da;
+ tri_sum += db;
+ n += 1.0;
+ }
+ eprintln!("tetra mean {:.4} max {:.4} | trilinear mean {:.4} max {:.4}", tet_sum / n, tet_max, tri_sum / n, tri_max);
+ assert!(tet_neutral < 0.01, "tetrahedral keeps neutrals neutral: {tet_neutral}");
+ assert!(tet_sum <= tri_sum * 1.05, "tetrahedral mean error {} vs trilinear {}", tet_sum / n, tri_sum / n);
+ assert!(tet_max < 4.0);
+ let _ = tri_neutral;
+}
+
+#[test]
+fn proof_and_display_lut() {
+ let p = Transform::proof(srgb(), cmyk(), srgb(), Intent::RelativeColorimetric, true, false).unwrap();
+ let mut o = [0.0f32; 3];
+ // Neutral gray stays (nearly) neutral through the proof.
+ p.eval(&[0.5, 0.5, 0.5], &mut o);
+ assert!((o[0] - o[1]).abs() < 0.02 && (o[1] - o[2]).abs() < 0.03, "{o:?}");
+ // Saturated blue is desaturated by the CMYK gamut.
+ p.eval(&[0.0, 0.0, 1.0], &mut o);
+ assert!(o[0] > 0.1 || o[1] > 0.1, "{o:?}");
+ // Paper simulation darkens white.
+ let sim = Transform::proof(srgb(), cmyk(), srgb(), Intent::RelativeColorimetric, true, true).unwrap();
+ sim.eval(&[1.0, 1.0, 1.0], &mut o);
+ assert!(o[0] < 0.97, "{o:?}");
+
+ let t = Transform::new(srgb(), Builtin::DisplayP3.profile(), Intent::RelativeColorimetric, false).unwrap();
+ let lut = Lut3d::from_transform(&t, 33);
+ assert_eq!(lut.to_rgba16f_bytes().len(), 33 * 33 * 33 * 8);
+ let mut worst = 0.0f32;
+ for i in 0..500u32 {
+ let c = [(i * 7 % 101) as f32 / 100.0, (i * 13 % 101) as f32 / 100.0, (i * 29 % 101) as f32 / 100.0];
+ let mut e = [0.0f32; 3];
+ t.eval(&c, &mut e);
+ let s = lut.sample(c);
+ for k in 0..3 {
+ worst = worst.max((s[k] - e[k]).abs());
+ }
+ }
+ assert!(worst < 2.0 / 255.0, "display LUT error {worst}");
+}
+
+#[test]
+fn gray_profiles() {
+ let t = Transform::new(Builtin::SGray.profile(), srgb(), Intent::RelativeColorimetric, false).unwrap();
+ for v in [0.0f32, 0.2, 0.5, 0.9, 1.0] {
+ let mut o = [0.0f32; 3];
+ t.eval(&[v], &mut o);
+ for c in o {
+ assert!((c - v).abs() < 1e-3, "sGray {v} -> {o:?}");
+ }
+ }
+ let t = Transform::new(srgb(), Builtin::GrayGamma22.profile(), Intent::RelativeColorimetric, false).unwrap();
+ let mut o = [0.0f32; 1];
+ t.eval(&[1.0, 1.0, 1.0], &mut o);
+ assert!((o[0] - 1.0).abs() < 1e-3);
+ t.eval(&[0.0, 0.0, 0.0], &mut o);
+ assert!(o[0].abs() < 1e-3);
+}
+
+#[test]
+fn hdr_floats_survive_matrix_transforms() {
+ let lin = Builtin::LinearSrgb.profile();
+ let t = Transform::with_options(lin, Builtin::Rec2020.profile(), TransformOptions { intent: Intent::RelativeColorimetric, bpc: false, precise_float: true }).unwrap();
+ let back = Transform::new(Builtin::Rec2020.profile(), lin, Intent::RelativeColorimetric, false).unwrap();
+ let src = [4.0f32, 2.0, 0.5];
+ let mut mid = [0.0f32; 3];
+ let mut out = [0.0f32; 3];
+ t.eval(&src, &mut mid);
+ back.eval(&mid, &mut out);
+ for k in 0..3 {
+ assert!((out[k] - src[k]).abs() < 1e-3 * src[k].max(1.0), "{src:?} -> {mid:?} -> {out:?}");
+ }
+}
+
+#[test]
+fn malformed_profiles_are_rejected_without_panicking() {
+ assert!(Profile::parse(&[]).is_err());
+ assert!(Profile::parse(&[0u8; 200]).is_err());
+ let good = srgb().to_bytes();
+ for cut in [100, 131, 140, 200, good.len() - 20] {
+ let _ = Profile::parse(&good[..cut]);
+ }
+ let mut bad = good.to_vec();
+ for i in (128..bad.len()).step_by(7) {
+ bad[i] ^= 0x5A;
+ let _ = Profile::parse(&bad);
+ }
+ let c = cmyk().to_bytes();
+ let mut bad = c.to_vec();
+ for i in (128..400).step_by(3) {
+ bad[i] = 0xFF;
+ if let Ok(p) = Profile::parse(&bad) {
+ let _ = Transform::new(&p, srgb(), Intent::Perceptual, true);
+ }
+ }
+}
+
+/// Parses every profile the OS ships (macOS ColorSync; read-only, nothing is copied) and
+/// converts through each.
+#[test]
+fn system_profiles() {
+ let dirs = ["/System/Library/ColorSync/Profiles", "/Library/ColorSync/Profiles", "/usr/share/color/icc", "/usr/share/color/icc/colord"];
+ let mut seen = 0;
+ for d in dirs {
+ let Ok(rd) = std::fs::read_dir(d) else { continue };
+ for e in rd.flatten() {
+ let path = e.path();
+ if !matches!(path.extension().and_then(|x| x.to_str()), Some("icc" | "icm" | "ICC" | "ICM")) {
+ continue;
+ }
+ let Ok(bytes) = std::fs::read(&path) else { continue };
+ let p = Profile::parse(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
+ seen += 1;
+ if !matches!(p.class, photocraft_cms::ProfileClass::Input | photocraft_cms::ProfileClass::Display | photocraft_cms::ProfileClass::Output | photocraft_cms::ProfileClass::ColorSpace) {
+ continue;
+ }
+ assert!(!p.description.is_empty(), "{}", path.display());
+ if matches!(p.color_space, ColorSpace::Rgb | ColorSpace::Gray | ColorSpace::Cmyk | ColorSpace::Lab) {
+ for intent in Intent::ALL {
+ let t = Transform::new(&p, lab(), intent, true).unwrap_or_else(|e| panic!("{} {intent:?}: {e}", path.display()));
+ let n = p.channels();
+ let mut o = [0.0f32; 3];
+ t.eval(&vec![0.5; n], &mut o);
+ assert!(o.iter().all(|v| v.is_finite()), "{}", path.display());
+ }
+ // Additive white is (near) L* 100 for display profiles in relative colorimetric.
+ if p.color_space == ColorSpace::Rgb {
+ let w = to_lab(&p, &[1.0, 1.0, 1.0], Intent::RelativeColorimetric);
+ assert!((w[0] - 100.0).abs() < 1.5, "{} white {w:?}", path.display());
+ }
+ }
+ if p.color_space == ColorSpace::Cmyk {
+ // Real CMYK profile: paper lighter than 100 % K.
+ let w = to_lab(&p, &[0.0; 4], Intent::RelativeColorimetric);
+ let k = to_lab(&p, &[0.0, 0.0, 0.0, 1.0], Intent::RelativeColorimetric);
+ assert!(w[0] > 90.0 && k[0] < 40.0, "{}: {w:?} {k:?}", path.display());
+ // And it round-trips through its own BToA.
+ if p.b2a[1].is_some() {
+ let to = Transform::new(lab(), &p, Intent::RelativeColorimetric, false).unwrap();
+ let back = Transform::new(&p, lab(), Intent::RelativeColorimetric, false).unwrap();
+ let mut c = [0.0f32; 4];
+ to.eval(&enc([60.0, 10.0, -10.0]), &mut c);
+ let mut l = [0.0f32; 3];
+ back.eval(&c, &mut l);
+ assert!(delta_e76(dec(&l), [60.0, 10.0, -10.0]) < 3.0, "{}: {:?}", path.display(), dec(&l));
+ }
+ }
+ }
+ }
+ eprintln!("parsed {seen} system profiles");
+}
+
+/// Independent oracle: moxcms (BSD-3/Apache-2.0, dev-dependency only) converting with the same
+/// profile bytes.
+#[test]
+fn oracle_moxcms_rgb() {
+ use moxcms::{ColorProfile, Layout, TransformOptions as MoxOpts};
+ for dst in [Builtin::DisplayP3, Builtin::AdobeRgbCompat, Builtin::ProPhotoCompat] {
+ let s = ColorProfile::new_from_slice(&srgb().to_bytes()).unwrap();
+ let d = ColorProfile::new_from_slice(&dst.profile().to_bytes()).unwrap();
+ let mt = s.create_transform_8bit(Layout::Rgb, &d, Layout::Rgb, MoxOpts::default()).unwrap();
+ let src: Vec<u8> = (0..4096u32).flat_map(|i| [(i * 37 % 256) as u8, (i * 91 % 256) as u8, (i * 13 % 256) as u8]).collect();
+ let mut theirs = vec![0u8; src.len()];
+ mt.transform(&src, &mut theirs).unwrap();
+ let ours_t = Transform::new(srgb(), dst.profile(), Intent::RelativeColorimetric, false).unwrap();
+ let mut ours = vec![0u8; src.len()];
+ ours_t.convert_u8(&src, 3, &mut ours, 3, false);
+ let worst = ours.iter().zip(&theirs).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap();
+ assert!(worst <= 2, "{dst:?}: max diff {worst}");
+ }
+}
+
+#[test]
+fn oracle_moxcms_system_cmyk() {
+ use moxcms::{ColorProfile, Layout, RenderingIntent, TransformOptions as MoxOpts};
+ let path = "/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc";
+ let Ok(bytes) = std::fs::read(path) else { return };
+ let ours_p = Profile::parse(&bytes).unwrap();
+ let theirs_p = ColorProfile::new_from_slice(&bytes).unwrap();
+ let s = ColorProfile::new_from_slice(&srgb().to_bytes()).unwrap();
+ let opts = MoxOpts { rendering_intent: RenderingIntent::RelativeColorimetric, ..Default::default() };
+ let Ok(mt) = theirs_p.create_transform_8bit(Layout::Rgba, &s, Layout::Rgb, opts) else { return };
+ let src: Vec<u8> = (0..2048u32).flat_map(|i| [(i * 37 % 256) as u8, (i * 91 % 256) as u8, (i * 13 % 256) as u8, (i * 57 % 256) as u8]).collect();
+ let mut theirs = vec![0u8; 2048 * 3];
+ mt.transform(&src, &mut theirs).unwrap();
+ let t = Transform::new(&ours_p, srgb(), Intent::RelativeColorimetric, false).unwrap();
+ let mut ours = vec![0u8; 2048 * 3];
+ t.convert_u8(&src, 4, &mut ours, 3, false);
+ let diffs: Vec<i32> = ours.iter().zip(&theirs).map(|(a, b)| (*a as i32 - *b as i32).abs()).collect();
+ let worst = *diffs.iter().max().unwrap();
+ let mean = diffs.iter().sum::<i32>() as f64 / diffs.len() as f64;
+ eprintln!("Generic CMYK → sRGB vs moxcms: max {worst}, mean {mean:.3}");
+ let wi = diffs.iter().position(|d| *d == worst).unwrap() / 3;
+ eprintln!("worst px cmyk {:?}: ours {:?} theirs {:?}", &src[wi * 4..wi * 4 + 4], &ours[wi * 3..wi * 3 + 3], &theirs[wi * 3..wi * 3 + 3]);
+ // Outliers sit at the sRGB toe (slope 12.92) on near-gamut-edge colours, where moxcms's
+ // own output interpolation differs; an independent float computation of one such pixel
+ // (Lab 48.45/−32.55/−4.90 → sRGB red 0.86) matches ours (0.73), not moxcms (19).
+ let mut sorted = diffs.clone();
+ sorted.sort_unstable();
+ let p99 = sorted[sorted.len() * 99 / 100];
+ assert!(mean < 1.5 && p99 <= 6, "max {worst} p99 {p99} mean {mean}");
+}
+
diff --git a/crates/cms/tests/regen.rs b/crates/cms/tests/regen.rs
new file mode 100644
index 000000000..54db9b4e2
--- /dev/null
+++ b/crates/cms/tests/regen.rs
@@ -0,0 +1,44 @@
+//! Regenerates the shipped synthetic CMYK profile when `PHOTOCRAFT_REGEN_PROFILES=1`:
+//!
+//! ```sh
+//! PHOTOCRAFT_REGEN_PROFILES=1 cargo test -p photocraft-cms --release --test regen
+//! ```
+//!
+//! Without the variable the test only checks that the generator's model still matches the
+//! shipped AToB table (cheap), so model edits are not forgotten.
+
+use photocraft_cms::synth::{CmykModel, CmykParams};
+use photocraft_cms::{Builtin, Intent, Profile, Transform};
+
+#[test]
+fn regen_or_check_coated_cmyk() {
+ let path = concat!(env!("CARGO_MANIFEST_DIR"), "/profiles/photocraft-coated-cmyk.icc");
+ if std::env::var_os("PHOTOCRAFT_REGEN_PROFILES").is_some() {
+ let t = std::time::Instant::now();
+ let p = photocraft_cms::synth::coated_cmyk();
+ let bytes = p.to_bytes();
+ std::fs::write(path, &*bytes).unwrap();
+ eprintln!("wrote {} bytes in {:?}", bytes.len(), t.elapsed());
+ return;
+ }
+ // The shipped AToB (colorimetric) must reproduce the model.
+ let shipped = Profile::parse(&std::fs::read(path).unwrap()).unwrap();
+ let lab = Builtin::LabD50.profile();
+ let t = Transform::new(&shipped, lab, Intent::RelativeColorimetric, false).unwrap();
+ let model = CmykModel::coated(CmykParams::default().tvi);
+ let mut worst = 0.0f64;
+ for c in [0.0, 0.3, 0.7, 1.0] {
+ for m in [0.0, 0.45, 1.0] {
+ for y in [0.0, 0.55, 1.0] {
+ for k in [0.0, 0.5, 1.0] {
+ let mut o = [0.0f32; 3];
+ t.eval(&[c as f32, m as f32, y as f32, k as f32], &mut o);
+ let got = [o[0] as f64 * 100.0, o[1] as f64 * 255.0 - 128.0, o[2] as f64 * 255.0 - 128.0];
+ let want = model.lab([c, m, y, k]);
+ worst = worst.max(photocraft_cms::math::delta_e76(got, want));
+ }
+ }
+ }
+ }
+ assert!(worst < 1.0, "shipped CMYK profile is stale (max ΔE {worst}); regenerate it");
+}
diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs
index 517b58dad..0f8cd1e34 100644
--- a/crates/codecs/src/codecs/png.rs
+++ b/crates/codecs/src/codecs/png.rs
@@ -255,3 +255,50 @@ fn adam7_idat(
z.write_all(&raw).map_err(|e| CodecError::encode(F, e))?;
z.finish().map_err(|e| CodecError::encode(F, e))
}
+
+/// Writes an 8-bit palette PNG (PNG-8): `indices` row-major, `palette` RGB entries (≤ 256),
+/// optional fully transparent entry (`tRNS`). Used for Indexed Color documents.
+pub fn encode_indexed(width: u32, height: u32, indices: &[u8], palette: &[[u8; 3]], transparent: Option<u8>) -> Result<Vec<u8>, CodecError> {
+ if width == 0 || height == 0 || indices.len() != width as usize * height as usize {
+ return Err(CodecError::InvalidImage("index data does not match the size".into()));
+ }
+ if palette.is_empty() || palette.len() > 256 || indices.iter().any(|&i| usize::from(i) >= palette.len()) {
+ return Err(CodecError::InvalidImage("palette must have 1..=256 entries covering every index".into()));
+ }
+ let mut info = png::Info::with_size(width, height);
+ info.color_type = png::ColorType::Indexed;
+ info.bit_depth = png::BitDepth::Eight;
+ info.palette = Some(palette.iter().flatten().copied().collect::<Vec<u8>>().into());
+ if let Some(t) = transparent.filter(|&t| usize::from(t) < palette.len()) {
+ let mut trns = vec![255u8; usize::from(t) + 1];
+ trns[usize::from(t)] = 0;
+ info.trns = Some(trns.into());
+ }
+ let mut out = Vec::new();
+ {
+ let encoder = png::Encoder::with_info(&mut out, info).map_err(|e| CodecError::encode(F, e))?;
+ let mut writer = encoder.write_header().map_err(|e| CodecError::encode(F, e))?;
+ writer.write_image_data(indices).map_err(|e| CodecError::encode(F, e))?;
+ writer.finish().map_err(|e| CodecError::encode(F, e))?;
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod indexed_tests {
+ use super::*;
+
+ #[test]
+ fn png8_roundtrips_through_the_decoder() {
+ let pal = [[255, 0, 0], [0, 0, 255], [0, 0, 0]];
+ let idx = [0u8, 1, 2, 1, 0, 2];
+ let bytes = encode_indexed(3, 2, &idx, &pal, Some(2)).unwrap();
+ let img = decode(&bytes, &Limits::default()).unwrap();
+ assert_eq!(img.dimensions(), (3, 2));
+ let px = img.convert(ChannelLayout::Rgba, SampleType::U8);
+ assert_eq!(&px.data()[..8], &[255, 0, 0, 255, 0, 0, 255, 255]);
+ assert_eq!(px.data()[11], 0, "transparent entry");
+ assert!(encode_indexed(3, 2, &[9; 6], &pal, None).is_err());
+ assert!(encode_indexed(3, 3, &idx, &pal, None).is_err());
+ }
+}
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 2a5bd44db..337a6d1c0 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -27,6 +27,7 @@ pub use crate::options::{
DecodeOptions, EncodeOptions, ExrCompression, Limits, PngCompression, TiffCompression,
};
pub use half::f16;
+pub use crate::codecs::png::encode_indexed as encode_png_indexed;
use crate::codecs::{exr, jpeg, png, pnm, tiff, via_image, webp};
diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml
index 253601de8..6ee0d2ab8 100644
--- a/crates/color/Cargo.toml
+++ b/crates/color/Cargo.toml
@@ -8,4 +8,5 @@ license.workspace = true
workspace = true
[dependencies]
+photocraft-cms = { workspace = true }
serde = { workspace = true }
diff --git a/crates/color/src/convert.rs b/crates/color/src/convert.rs
index 0e248ce7d..2c24daac9 100644
--- a/crates/color/src/convert.rs
+++ b/crates/color/src/convert.rs
@@ -1,5 +1,41 @@
-//! Colour conversions that don't need ICC profiles.
-//! Full ICC colour management (moxcms) comes in milestone M8; these are the building blocks.
+//! Colour conversions between the document colour models.
+//!
+//! CMYK ↔ RGB goes through the ICC colour management module (`photocraft-cms`) with the
+//! built-in coated CMYK profile and sRGB (relative colorimetric with black point
+//! compensation, Photoshop's default), so CMYK pixels display and accept painted colours the
+//! way a colour-managed editor does. Document-specific profiles are applied by the engine's
+//! mode/profile conversions; these per-pixel helpers always assume the built-in profiles.
+//! Lab uses the exact D50 formulas; gray is treated as sGray (gray `v` = sRGB `(v, v, v)`).
+
+use std::sync::OnceLock;
+
+use photocraft_cms::{Builtin, Intent, Transform};
+
+fn cmyk_to_srgb_transform() -> &'static Transform {
+ static T: OnceLock<Transform> = OnceLock::new();
+ T.get_or_init(|| Transform::new(Builtin::CoatedCmyk.profile(), Builtin::Srgb.profile(), Intent::RelativeColorimetric, true).expect("built-in profiles link"))
+}
+
+fn srgb_to_cmyk_transform() -> &'static Transform {
+ static T: OnceLock<Transform> = OnceLock::new();
+ T.get_or_init(|| Transform::new(Builtin::Srgb.profile(), Builtin::CoatedCmyk.profile(), Intent::RelativeColorimetric, true).expect("built-in profiles link"))
+}
+
+/// Colour-managed CMYK → sRGB (built-in coated CMYK profile, relative colorimetric + BPC).
+#[inline]
+pub fn cmyk_to_rgb(c: [f32; 4]) -> [f32; 3] {
+ let mut o = [0.0f32; 3];
+ cmyk_to_srgb_transform().eval_fast(&c, &mut o);
+ o
+}
+
+/// Colour-managed sRGB → CMYK (built-in coated CMYK profile, relative colorimetric + BPC).
+#[inline]
+pub fn rgb_to_cmyk(rgb: [f32; 3]) -> [f32; 4] {
+ let mut o = [0.0f32; 4];
+ srgb_to_cmyk_transform().eval_fast(&[rgb[0].clamp(0.0, 1.0), rgb[1].clamp(0.0, 1.0), rgb[2].clamp(0.0, 1.0)], &mut o);
+ o
+}
/// sRGB transfer function: encoded → linear.
#[inline]
@@ -13,7 +49,7 @@ pub fn linear_to_srgb(v: f32) -> f32 {
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
}
-/// Naive CMYK → RGB (no profile). Used only for previews until ICC is wired in.
+/// Naive CMYK → RGB (no profile): `(1 − c)(1 − k)`. Kept for reference and tests.
pub fn cmyk_to_rgb_naive(c: [f32; 4]) -> [f32; 3] {
let k = 1.0 - c[3];
[(1.0 - c[0]) * k, (1.0 - c[1]) * k, (1.0 - c[2]) * k]
@@ -97,6 +133,22 @@ mod tests {
}
}
+ #[test]
+ fn managed_cmyk() {
+ let white = cmyk_to_rgb([0.0; 4]);
+ assert!(white.iter().all(|v| *v > 0.99), "{white:?}");
+ // 100 % K alone is a dark neutral, not pure black (as in any real CMYK profile).
+ let k = cmyk_to_rgb([0.0, 0.0, 0.0, 1.0]);
+ assert!(k[0] < 0.3 && (k[0] - k[2]).abs() < 0.05, "{k:?}");
+ // Round trip of in-gamut colours.
+ for rgb in [[0.5, 0.5, 0.5], [0.6, 0.4, 0.3], [0.3, 0.5, 0.6]] {
+ let back = cmyk_to_rgb(rgb_to_cmyk(rgb));
+ for i in 0..3 {
+ assert!((back[i] - rgb[i]).abs() < 0.03, "{rgb:?} -> {back:?}");
+ }
+ }
+ }
+
#[test]
fn lab_roundtrip_and_anchors() {
let white = srgb_to_lab([1.0, 1.0, 1.0]);
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs
index bd9095142..d8fb0140a 100644
--- a/crates/color/src/lib.rs
+++ b/crates/color/src/lib.rs
@@ -148,12 +148,12 @@ impl Color {
pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0);
pub const TRANSPARENT: Color = Color::rgba(0.0, 0.0, 0.0, 0.0);
- /// Convert to display RGB (naive, non-ICC conversion; ICC comes via `convert` later).
+ /// Convert to sRGB (CMYK through the built-in CMYK profile, Lab via D50 formulas).
pub fn to_rgb(&self) -> [f32; 3] {
match self.mode {
ColorMode::Rgb | ColorMode::Indexed | ColorMode::Multichannel => [self.c[0], self.c[1], self.c[2]],
ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => [self.c[0]; 3],
- ColorMode::Cmyk => convert::cmyk_to_rgb_naive([self.c[0], self.c[1], self.c[2], self.c[3]]),
+ ColorMode::Cmyk => convert::cmyk_to_rgb([self.c[0], self.c[1], self.c[2], self.c[3]]),
ColorMode::Lab => convert::lab_to_srgb([self.c[0] * 100.0, self.c[1] * 255.0 - 128.0, self.c[2] * 255.0 - 128.0]),
}
}
@@ -214,7 +214,9 @@ mod tests {
fn color_to_rgba8() {
assert_eq!(Color::WHITE.to_rgba8(), [255, 255, 255, 255]);
assert_eq!(Color::gray(0.5).to_rgba8(), [128, 128, 128, 255]);
- let k = Color { mode: ColorMode::Cmyk, c: [0.0, 0.0, 0.0, 1.0], alpha: 1.0 };
- assert_eq!(k.to_rgba8(), [0, 0, 0, 255]);
+ let w = Color { mode: ColorMode::Cmyk, c: [0.0; 4], alpha: 1.0 };
+ assert_eq!(w.to_rgba8(), [255, 255, 255, 255]);
+ let k = Color { mode: ColorMode::Cmyk, c: [0.75, 0.68, 0.67, 0.9], alpha: 1.0 };
+ assert!(k.to_rgba8()[..3].iter().all(|v| *v < 20), "{:?}", k.to_rgba8());
}
}
diff --git a/crates/compose/benches/compose.rs b/crates/compose/benches/compose.rs
index 00ce91004..d3b666d9e 100644
--- a/crates/compose/benches/compose.rs
+++ b/crates/compose/benches/compose.rs
@@ -58,7 +58,7 @@ fn benches(c: &mut Criterion) {
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(),
+ points: (0..500).map(|i| photocraft_paint::StrokePoint::new(100.0 + i as f64 * 7.0, 1000.0 + (i as f64 * 0.05).sin() * 400.0, 1.0)).collect(),
};
let base = filled(4096, 5);
let mut sel = Surface::with_default(PixelFormat::GRAY8, &[1.0]);
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs
index 5639bdb10..b6ac92df5 100644
--- a/crates/compose/src/adjust.rs
+++ b/crates/compose/src/adjust.rs
@@ -188,11 +188,113 @@ pub fn apply_with(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer) {
out
}
}),
- // Not yet evaluated: identity (still round-trips through PSD).
- Adjustment::SelectiveColor { .. } | Adjustment::ColorLookup { .. } | Adjustment::Unsupported { .. } => {}
+ Adjustment::SelectiveColor { relative, adjustments } => map_rgb(buf, |c| selective_color(c, *relative, adjustments)),
+ Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if *size >= 2 && table.len() >= (*size as usize).pow(3) * 3 => {
+ let (n, w, x0, y0) = (*size as usize, buf.rect.width().max(1) as usize, buf.rect.x0, buf.rect.y0);
+ for (i, p) in buf.px.iter_mut().enumerate() {
+ if p[3] <= 0.0 {
+ continue;
+ }
+ let mut o = lut3d_sample(table, n, [p[0], p[1], p[2]], *tetrahedral);
+ if *dither {
+ let d = bayer4(x0 + (i % w) as i32, y0 + (i / w) as i32) / 255.0;
+ o = o.map(|v| (v + d).clamp(0.0, 1.0));
+ }
+ p[..3].copy_from_slice(&o);
+ }
+ }
+ // Not evaluated: identity (still round-trips through PSD).
+ Adjustment::ColorLookup { .. } | Adjustment::Unsupported { .. } => {}
+ }
+}
+
+/// Ordered-dither offset in -0.5..0.5 (4×4 Bayer matrix) for document pixel (x, y).
+pub fn bayer4(x: i32, y: i32) -> f32 {
+ const M: [f32; 16] = [0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0];
+ (M[((y & 3) * 4 + (x & 3)) as usize] + 0.5) / 16.0 - 0.5
+}
+
+/// Samples a 3D LUT (`n`³ RGB triplets, red fastest) at `c`, trilinear or tetrahedral.
+pub fn lut3d_sample(lut: &[f32], n: usize, c: [f32; 3], tetrahedral: bool) -> [f32; 3] {
+ let m = (n - 1) as f32;
+ let pos = c.map(|v| v.clamp(0.0, 1.0) * m);
+ let i0 = pos.map(|p| (p.floor() as usize).min(n - 2));
+ let f: [f32; 3] = std::array::from_fn(|k| pos[k] - i0[k] as f32);
+ let at = |dr: usize, dg: usize, db: usize| -> [f32; 3] {
+ let idx = (((i0[2] + db) * n + i0[1] + dg) * n + i0[0] + dr) * 3;
+ [lut[idx], lut[idx + 1], lut[idx + 2]]
+ };
+ let mix = |w: &[(f32, [f32; 3])]| -> [f32; 3] { std::array::from_fn(|k| w.iter().map(|(a, v)| a * v[k]).sum()) };
+ let (fr, fg, fb) = (f[0], f[1], f[2]);
+ if tetrahedral {
+ let (c000, c111) = (at(0, 0, 0), at(1, 1, 1));
+ if fr > fg {
+ if fg > fb {
+ mix(&[(1.0 - fr, c000), (fr - fg, at(1, 0, 0)), (fg - fb, at(1, 1, 0)), (fb, c111)])
+ } else if fr > fb {
+ mix(&[(1.0 - fr, c000), (fr - fb, at(1, 0, 0)), (fb - fg, at(1, 0, 1)), (fg, c111)])
+ } else {
+ mix(&[(1.0 - fb, c000), (fb - fr, at(0, 0, 1)), (fr - fg, at(1, 0, 1)), (fg, c111)])
+ }
+ } else if fb > fg {
+ mix(&[(1.0 - fb, c000), (fb - fg, at(0, 0, 1)), (fg - fr, at(0, 1, 1)), (fr, c111)])
+ } else if fb > fr {
+ mix(&[(1.0 - fg, c000), (fg - fb, at(0, 1, 0)), (fb - fr, at(0, 1, 1)), (fr, c111)])
+ } else {
+ mix(&[(1.0 - fg, c000), (fg - fr, at(0, 1, 0)), (fr - fb, at(1, 1, 0)), (fb, c111)])
+ }
+ } else {
+ let lerp = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] { std::array::from_fn(|k| a[k] + (b[k] - a[k]) * t) };
+ let c00 = lerp(at(0, 0, 0), at(1, 0, 0), fr);
+ let c10 = lerp(at(0, 1, 0), at(1, 1, 0), fr);
+ let c01 = lerp(at(0, 0, 1), at(1, 0, 1), fr);
+ let c11 = lerp(at(0, 1, 1), at(1, 1, 1), fr);
+ lerp(lerp(c00, c10, fg), lerp(c01, c11, fg), fb)
}
}
+/// How much a colour belongs to each Selective Color range: reds, yellows, greens, cyans,
+/// blues, magentas (by chroma within the hue sector), whites, neutrals and blacks (by lightness).
+pub fn selective_color_weights(c: [f32; 3]) -> [f32; 9] {
+ let max = c[0].max(c[1]).max(c[2]);
+ let min = c[0].min(c[1]).min(c[2]);
+ let mid = c[0] + c[1] + c[2] - max - min;
+ let top = |i: usize| if c[i] >= max { max - mid } else { 0.0 };
+ let bottom = |i: usize| if c[i] <= min { mid - min } else { 0.0 };
+ [
+ top(0),
+ bottom(2),
+ top(1),
+ bottom(0),
+ top(2),
+ bottom(1),
+ ((min - 0.5) * 2.0).max(0.0),
+ (1.0 - (max - 0.5).abs() - (min - 0.5).abs()).clamp(0.0, 1.0),
+ ((0.5 - max) * 2.0).max(0.0),
+ ]
+}
+
+/// Photoshop Selective Color (approximation): each range shifts the cyan, magenta and yellow ink
+/// (1 − R, G, B) by its percentage, plus its black percentage on every ink, weighted by how much
+/// the colour belongs to the range. Relative mode scales the shift by the ink already present
+/// (so it can't tint pure white); absolute adds it outright.
+pub fn selective_color(c: [f32; 3], relative: bool, adj: &[[f32; 4]; 9]) -> [f32; 3] {
+ let w = selective_color_weights(c);
+ let mut delta = [0.0f32; 3];
+ for (r, wr) in w.iter().enumerate() {
+ if *wr <= 0.0 {
+ continue;
+ }
+ let a = adj[r].map(|v| v / 100.0);
+ for i in 0..3 {
+ let ink = 1.0 - c[i];
+ let d = if relative { (a[i] + a[3]) * ink } else { a[i] + a[3] };
+ delta[i] += d * wr;
+ }
+ }
+ std::array::from_fn(|i| (c[i] - delta[i]).clamp(0.0, 1.0))
+}
+
const LUT_SIZE: usize = 4096;
fn map_rgb(buf: &mut Buffer, f: impl Fn([f32; 3]) -> [f32; 3]) {
@@ -343,3 +445,52 @@ pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] {
};
[f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)]
}
+
+#[cfg(test)]
+mod lookup_tests {
+ use super::*;
+
+ fn identity(n: usize) -> Vec<f32> {
+ let m = (n - 1) as f32;
+ (0..n * n * n).flat_map(|i| [(i % n) as f32 / m, ((i / n) % n) as f32 / m, (i / (n * n)) as f32 / m]).collect()
+ }
+
+ #[test]
+ fn identity_lut_is_identity_both_interpolations() {
+ let t = identity(5);
+ for c in [[0.1, 0.5, 0.9], [0.33, 0.77, 0.0], [1.0, 1.0, 1.0]] {
+ for tet in [false, true] {
+ let o = lut3d_sample(&t, 5, c, tet);
+ for k in 0..3 {
+ assert!((o[k] - c[k]).abs() < 1e-5, "{c:?} {tet} {o:?}");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn selective_color_zero_is_identity_and_ranges_are_local() {
+ let zero = [[0.0f32; 4]; 9];
+ for c in [[0.9, 0.1, 0.1], [0.5, 0.5, 0.5], [0.2, 0.4, 0.8]] {
+ assert_eq!(selective_color(c, true, &zero), c);
+ }
+ // +100 % cyan on reds only: red loses red, blue is untouched.
+ let mut a = zero;
+ a[0][0] = 100.0;
+ let red = selective_color([0.9, 0.1, 0.1], false, &a);
+ assert!(red[0] < 0.2, "{red:?}");
+ assert_eq!(selective_color([0.1, 0.1, 0.9], false, &a), [0.1, 0.1, 0.9]);
+ // Relative mode can't tint pure white; absolute can (via whites).
+ let mut w = zero;
+ w[6] = [0.0, 0.0, 50.0, 0.0];
+ assert_eq!(selective_color([1.0; 3], true, &w), [1.0; 3]);
+ assert!(selective_color([1.0; 3], false, &w)[2] < 0.6);
+ }
+
+ #[test]
+ fn dither_offsets_are_balanced() {
+ let sum: f32 = (0..4).flat_map(|y| (0..4).map(move |x| bayer4(x, y))).sum();
+ assert!(sum.abs() < 1e-5);
+ assert_eq!(bayer4(-4, -4), bayer4(0, 0));
+ }
+}
diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs
index 12b858579..840af7c3e 100644
--- a/crates/compose/src/effects.rs
+++ b/crates/compose/src/effects.rs
@@ -17,8 +17,10 @@ use photocraft_doc::{
Bevel, BevelStyle, Contour, Effect, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Layer, Shadow,
StrokePosition,
};
+use photocraft_doc::Pattern;
use photocraft_geom::Rect;
+use crate::pattern::{Placement, Tile};
use crate::{Buffer, psblend};
/// `true` if the layer has at least one enabled effect and the master switch is on.
@@ -436,7 +438,26 @@ fn glow_map(shape: &Map, g: &Glow, inner: bool) -> Map {
m
}
-fn paint_fx(dst: &mut Buffer, m: &Map, p: &FxPaint, shape_bounds: Rect, big: Rect, blend: BlendMode, opacity: f32) {
+/// Paints a pattern (looked up in `patterns`) through coverage `m`; missing patterns paint nothing.
+#[allow(clippy::too_many_arguments)]
+fn paint_pattern(dst: &mut Buffer, m: &Map, patterns: &[Pattern], name: &str, id: &str, place: Placement, big: Rect, blend: BlendMode, opacity: f32) {
+ let Some(tile) = photocraft_doc::pattern::find(patterns, id, name).and_then(Tile::new) else { return };
+ let w = big.width() as usize;
+ paint(
+ dst,
+ m,
+ |i| {
+ let (x, y) = (f64::from(big.x0 + (i % w) as i32) + 0.5, f64::from(big.y0 + (i / w) as i32) + 0.5);
+ let (u, v) = place.map(x, y);
+ tile.sample(u, v)
+ },
+ blend,
+ opacity,
+ );
+}
+
+#[allow(clippy::too_many_arguments)]
+fn paint_fx(dst: &mut Buffer, m: &Map, p: &FxPaint, shape_bounds: Rect, big: Rect, blend: BlendMode, opacity: f32, patterns: &[Pattern]) {
match p {
FxPaint::Color(c) => paint_color(dst, m, rgb(c), blend, opacity),
FxPaint::Gradient(g) => {
@@ -452,7 +473,9 @@ fn paint_fx(dst: &mut Buffer, m: &Map, p: &FxPaint, shape_bounds: Rect, big: Rec
opacity,
)
}
- FxPaint::Pattern { .. } => {}
+ FxPaint::Pattern { name, id, scale } => {
+ paint_pattern(dst, m, patterns, name, id, Placement::new(shape_bounds, true, (0.0, 0.0), *scale, 0.0), big, blend, opacity)
+ }
}
}
@@ -598,7 +621,7 @@ const FAR: f32 = 1.0e9;
/// Composites `content` (the layer's own pixels over `big`, alpha already
/// masked, clipped layers applied) plus its effects into `backdrop`.
-pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Buffer, maps: &FxMaps, layer_bounds: Rect) {
+pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Buffer, maps: &FxMaps, layer_bounds: Rect, patterns: &[Pattern]) {
let big = content.rect;
let (w, h) = (big.width() as usize, big.height() as usize);
let shape = Map { w, h, v: content.px.iter().map(|p| p[3]).collect() };
@@ -634,7 +657,7 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
for (i, e) in rev() {
if let Effect::OuterGlow(g) = e {
let m = fx(i, 0);
- paint_fx(&mut work, &m, &g.paint, sb, big, g.common.blend, g.common.opacity);
+ paint_fx(&mut work, &m, &g.paint, sb, big, g.common.blend, g.common.opacity, patterns);
}
}
@@ -642,9 +665,14 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
let fill = layer.fill_opacity;
let mut lay = Buffer { rect: big, px: content.px.iter().map(|p| [p[0], p[1], p[2], p[3] * fill]).collect() };
let full = shape.clone();
+ for (_, e) in rev() {
+ if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e {
+ paint_pattern(&mut lay, &full, patterns, name, id, Placement::new(sb, *link, *phase, *scale, *angle), big, common.blend, common.opacity);
+ }
+ }
for (_, e) in rev() {
if let Effect::GradientOverlay { common, gradient, .. } = e {
- paint_fx(&mut lay, &full, &FxPaint::Gradient(gradient.clone()), sb, big, common.blend, common.opacity)
+ paint_fx(&mut lay, &full, &FxPaint::Gradient(gradient.clone()), sb, big, common.blend, common.opacity, patterns)
}
}
for (_, e) in rev() {
@@ -661,7 +689,7 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
for (i, e) in rev() {
if let Effect::InnerGlow(g) = e {
let m = fx(i, 0);
- paint_fx(&mut lay, &m, &g.paint, sb, big, g.common.blend, g.common.opacity);
+ paint_fx(&mut lay, &m, &g.paint, sb, big, g.common.blend, g.common.opacity, patterns);
}
}
for (i, e) in rev() {
@@ -701,7 +729,7 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
};
}
let mut under = Buffer::transparent(big);
- paint_fx(&mut under, &m, &st.paint, sb, big, BlendMode::Normal, st.common.opacity);
+ paint_fx(&mut under, &m, &st.paint, sb, big, BlendMode::Normal, st.common.opacity, patterns);
for (u, l) in under.px.iter_mut().zip(&lay.px) {
*u = psblend::composite(BlendMode::Normal, *u, *l, 1.0);
}
@@ -716,7 +744,7 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&din) {
*mv = (in_w + 0.5 - dv).clamp(0.0, 1.0) * a;
}
- paint_fx(&mut lay, &m, &st.paint, sb, big, st.common.blend, st.common.opacity);
+ paint_fx(&mut lay, &m, &st.paint, sb, big, st.common.blend, st.common.opacity, patterns);
}
for (i, e) in rev() {
if let Effect::BevelEmboss(b) = e {
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 09b194f86..fe7e3e791 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -15,11 +15,12 @@
pub mod adjust;
pub mod effects;
+pub mod pattern;
pub mod psblend;
use photocraft_color::blend::BlendMode;
use psblend as blend;
-use photocraft_doc::{Document, Fill, Layer, LayerContent};
+use photocraft_doc::{Document, Fill, Layer, LayerContent, Pattern};
use photocraft_geom::Rect;
use photocraft_raster::{Rgba8Image, Surface};
@@ -75,7 +76,7 @@ pub fn render(doc: &Document, rect: Rect) -> Buffer {
/// [`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 };
+ let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::for_mode(doc.mode), light: doc.global_light, patterns: &doc.patterns };
if rect.width() as i32 <= tile && rect.height() as i32 <= tile {
let mut buf = Buffer::transparent(rect);
composite_stack(&doc.layers, &mut buf, &cx);
@@ -123,7 +124,7 @@ pub fn flatten(doc: &Document) -> Buffer {
/// Render an arbitrary subset: a single layer (e.g. for thumbnails), isolated.
pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
let mut buf = Buffer::transparent(rect);
- composite_stack(std::slice::from_ref(layer), &mut buf, &Ctx { canvas: rect, transfer: adjust::Transfer::Srgb, light: photocraft_doc::GlobalLight::default() });
+ composite_stack(std::slice::from_ref(layer), &mut buf, &Ctx { canvas: rect, transfer: adjust::Transfer::Srgb, light: photocraft_doc::GlobalLight::default(), patterns: &[] });
buf
}
@@ -167,13 +168,15 @@ pub fn thumbnail(doc: &Document, max_side: u32) -> Rgba8Image {
/// Composite a sibling list (bottom→top) onto `backdrop`.
/// Rendering context shared down the tree.
-struct Ctx {
+struct Ctx<'a> {
/// Document canvas: fill layers and gradients are laid out relative to it, never to the render rect.
canvas: Rect,
/// Tone transfer used by adjustments that work in linear light.
transfer: adjust::Transfer,
/// Global light for layer effects.
light: photocraft_doc::GlobalLight,
+ /// The document's patterns (pattern fills and overlays).
+ patterns: &'a [Pattern],
}
fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {
@@ -207,6 +210,7 @@ fn dissolve_noise(x: i32, y: i32) -> f32 {
/// for fill layers).
fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect {
match &layer.content {
+ LayerContent::Group(g) if g.artboard.is_some() => g.artboard.as_ref().map_or(Rect::EMPTY, |a| a.rect),
LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| {
let b = layer_bounds(c, canvas);
if b.is_empty() { acc } else if acc.is_empty() { b } else { acc.union(&b) }
@@ -248,7 +252,7 @@ fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buffer> {
LayerContent::Fill(f) => match &layer.fill_cache {
// Photoshop's own rendering, valid while the fill is unchanged.
Some(c) if c.fill == *f => surface_to_buffer(&c.surface, rect),
- _ => render_fill(f, rect, fill_frame(layer, cx.canvas)),
+ _ => render_fill(f, rect, fill_frame(layer, cx.canvas), cx.patterns),
},
LayerContent::Adjustment(_) => return None,
_ => match layer.surface() {
@@ -297,7 +301,7 @@ pub fn fill_frame(layer: &Layer, canvas: Rect) -> Rect {
frame
}
-fn render_fill(f: &Fill, rect: Rect, canvas: Rect) -> Buffer {
+fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &[Pattern]) -> Buffer {
match f {
Fill::Solid(c) => {
let rgb = c.to_rgb();
@@ -315,8 +319,11 @@ fn render_fill(f: &Fill, rect: Rect, canvas: Rect) -> Buffer {
}
b
}
- // Patterns render once the pattern library lands; transparent until then.
- Fill::Pattern { .. } => Buffer::transparent(rect),
+ // Laid out from the layer's frame when linked; transparent if the pattern is missing.
+ Fill::Pattern { name, scale, id, angle, link, phase } => match photocraft_doc::pattern::find(patterns, id, name).and_then(pattern::Tile::new) {
+ Some(tile) => Buffer { rect, px: pattern::render(&tile, &pattern::Placement::new(canvas, *link, *phase, *scale, *angle), rect) },
+ None => Buffer::transparent(rect),
+ },
}
}
@@ -364,6 +371,42 @@ fn empty_in(layer: &Layer, rect: Rect) -> bool {
/// Composite `layer` (plus its clipping group) onto `backdrop`.
fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {
+ if let LayerContent::Group(g) = &layer.content
+ && let Some(ab) = &g.artboard
+ {
+ composite_artboard(layer, ab, clipped, backdrop, cx);
+ return;
+ }
+ composite_layer_plain(layer, clipped, backdrop, cx);
+}
+
+/// An artboard: its background and the group, composited only inside the board (contents and
+/// effects outside it are clipped away; the backdrop there is untouched).
+fn composite_artboard(layer: &Layer, ab: &photocraft_doc::Artboard, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {
+ let board = ab.rect.intersect(&backdrop.rect);
+ if board.is_empty() {
+ return;
+ }
+ let (bw, w) = (board.width() as usize, backdrop.rect.width() as usize);
+ let row0 = |y: i32| (y - backdrop.rect.y0) as usize * w + (board.x0 - backdrop.rect.x0) as usize;
+ let mut sub = Buffer::transparent(board);
+ for y in board.y0..board.y1 {
+ let o = row0(y);
+ let so = (y - board.y0) as usize * bw;
+ sub.px[so..so + bw].copy_from_slice(&backdrop.px[o..o + bw]);
+ }
+ if let Some(bg) = ab.background.rgba() {
+ blend_into(&mut sub, &Buffer::filled(board, bg), BlendMode::Normal, 1.0);
+ }
+ composite_layer_plain(layer, clipped, &mut sub, cx);
+ for y in board.y0..board.y1 {
+ let o = row0(y);
+ let so = (y - board.y0) as usize * bw;
+ backdrop.px[o..o + bw].copy_from_slice(&sub.px[so..so + bw]);
+ }
+}
+
+fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {
let rect = backdrop.rect;
if empty_in(layer, rect) {
return;
@@ -456,7 +499,7 @@ fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx:
composite_atop(c, &mut content, cx);
}
let maps = effect_maps(layer, cx);
- effects::composite_with_effects(layer, &content, backdrop, &maps, layer_bounds(layer, cx.canvas));
+ effects::composite_with_effects(layer, &content, backdrop, &maps, layer_bounds(layer, cx.canvas), cx.patterns);
return;
}
if let Some((mut content, stroke)) = shape_parts(layer, clipped, rect, cx) {
@@ -522,6 +565,7 @@ fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map::DefaultHash
for c in &g.children {
layer_identity(c, h);
}
+ format!("{:?}", g.artboard).hash(h);
}
LayerContent::Fill(f) => format!("{f:?}").hash(h),
LayerContent::Adjustment(a) => format!("{a:?}").hash(h),
@@ -552,7 +596,35 @@ struct FxCache {
bytes: usize,
}
-const FX_CACHE_BUDGET: usize = 768 << 20;
+/// Default effect-cache budget (Preferences › Performance can change it).
+pub const DEFAULT_FX_CACHE_BUDGET: usize = 768 << 20;
+static FX_CACHE_BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(DEFAULT_FX_CACHE_BUDGET);
+
+/// Set the memory budget (bytes) of the layer-effect map cache; entries over it are evicted
+/// oldest-first on the next build.
+pub fn set_effect_cache_budget(bytes: usize) {
+ FX_CACHE_BUDGET.store(bytes.max(1 << 20), std::sync::atomic::Ordering::Relaxed);
+}
+
+/// The current effect-cache budget in bytes.
+pub fn effect_cache_budget() -> usize {
+ FX_CACHE_BUDGET.load(std::sync::atomic::Ordering::Relaxed)
+}
+
+/// Bytes currently held by the effect-map cache.
+pub fn effect_cache_bytes() -> usize {
+ fx_cache().lock().unwrap_or_else(|e| e.into_inner()).bytes
+}
+
+/// Drop every cached effect map (Edit › Purge › All). Returns the bytes released.
+pub fn purge_effect_cache() -> usize {
+ let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner());
+ let freed = c.bytes;
+ c.map.clear();
+ c.order.clear();
+ c.bytes = 0;
+ freed
+}
fn fx_cache() -> &'static std::sync::Mutex<FxCache> {
static C: std::sync::OnceLock<std::sync::Mutex<FxCache>> = std::sync::OnceLock::new();
@@ -600,7 +672,8 @@ fn effect_maps(layer: &Layer, cx: &Ctx) -> std::sync::Arc<effects::FxMaps> {
let maps = entry.maps.clone();
// Evict the oldest entries over budget (never the one just used).
let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner());
- while c.bytes > FX_CACHE_BUDGET && c.order.len() > 1 {
+ let budget = effect_cache_budget();
+ while c.bytes > budget && c.order.len() > 1 {
let Some(old) = c.order.pop_front() else { break };
if old == key {
c.order.push_back(old);
@@ -637,7 +710,7 @@ fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
let Some(content) = render_content(layer, big, cx) else { return };
let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() };
let maps = effect_maps(layer, cx);
- effects::composite_with_effects(layer, &content, &mut opaque, &maps, layer_bounds(layer, cx.canvas));
+ effects::composite_with_effects(layer, &content, &mut opaque, &maps, layer_bounds(layer, cx.canvas), cx.patterns);
for (p, o) in base.px.iter_mut().zip(&opaque.px) {
if p[3] > 0.0 {
*p = [o[0], o[1], o[2], p[3]];
diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs
new file mode 100644
index 000000000..d5e445d3a
--- /dev/null
+++ b/crates/compose/src/pattern.rs
@@ -0,0 +1,154 @@
+//! Pattern paint: Pattern Overlay, pattern strokes and pattern fill layers.
+//!
+//! A pattern tiles the plane from an origin (the layer's frame when linked, else the canvas
+//! origin, plus the phase), scaled and rotated about that origin. Samples are bilinear with
+//! wrap-around on premultiplied colour, so integer placements at 100 % reproduce the tile
+//! exactly and scaled ones stay seamless.
+
+use photocraft_doc::{Pattern, Rect};
+
+/// A pattern converted once to straight-alpha RGBA for sampling.
+pub struct Tile {
+ w: usize,
+ h: usize,
+ /// Premultiplied RGBA.
+ px: Vec<[f32; 4]>,
+}
+
+impl Tile {
+ pub fn new(p: &Pattern) -> Option<Tile> {
+ if p.is_empty() {
+ return None;
+ }
+ let (w, h) = (p.width as usize, p.height as usize);
+ let mut px = vec![[0.0f32; 4]; w * h];
+ p.surface.read_rgba_into(p.rect(), &mut px);
+ for q in &mut px {
+ for c in 0..3 {
+ q[c] *= q[3];
+ }
+ }
+ Some(Tile { w, h, px })
+ }
+
+ #[inline]
+ fn at(&self, x: i64, y: i64) -> [f32; 4] {
+ let xi = x.rem_euclid(self.w as i64) as usize;
+ let yi = y.rem_euclid(self.h as i64) as usize;
+ self.px[yi * self.w + xi]
+ }
+
+ /// Bilinear, wrapping sample at continuous tile coordinates (pixel centres at `i + 0.5`).
+ /// Returns straight alpha.
+ pub fn sample(&self, u: f64, v: f64) -> [f32; 4] {
+ let (u, v) = (u - 0.5, v - 0.5);
+ let (x0, y0) = (u.floor(), v.floor());
+ let (fx, fy) = ((u - x0) as f32, (v - y0) as f32);
+ let (x0, y0) = (x0 as i64, y0 as i64);
+ let mut acc = [0.0f32; 4];
+ for (dy, wy) in [(0, 1.0 - fy), (1, fy)] {
+ if wy == 0.0 {
+ continue;
+ }
+ for (dx, wx) in [(0, 1.0 - fx), (1, fx)] {
+ if wx == 0.0 {
+ continue;
+ }
+ let p = self.at(x0 + dx, y0 + dy);
+ let k = wx * wy;
+ for c in 0..4 {
+ acc[c] += p[c] * k;
+ }
+ }
+ }
+ if acc[3] <= 0.0 {
+ return [0.0; 4];
+ }
+ [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)]
+ }
+}
+
+/// Where a pattern sits: document point → tile coordinates.
+#[derive(Clone, Copy, Debug)]
+pub struct Placement {
+ origin: (f64, f64),
+ /// Inverse rotation (cos, sin) and inverse scale.
+ cs: (f64, f64),
+ inv_scale: f64,
+}
+
+impl Placement {
+ /// `frame`: the layer's frame (used when `link`); `phase` in pixels; `scale` as a fraction;
+ /// `angle` in degrees counter-clockwise.
+ pub fn new(frame: Rect, link: bool, phase: (f32, f32), scale: f32, angle: f32) -> Placement {
+ let base = if link && !frame.is_empty() { (f64::from(frame.x0), f64::from(frame.y0)) } else { (0.0, 0.0) };
+ let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1));
+ let s = f64::from(scale);
+ let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 };
+ let a = f64::from(angle).to_radians();
+ Placement { origin, cs: (a.cos(), a.sin()), inv_scale }
+ }
+
+ /// Tile coordinates of the document point `(x, y)`.
+ #[inline]
+ pub fn map(&self, x: f64, y: f64) -> (f64, f64) {
+ let (dx, dy) = (x - self.origin.0, y - self.origin.1);
+ // Undo a counter-clockwise rotation (y points down on screen).
+ let (c, s) = self.cs;
+ let (rx, ry) = (dx * c - dy * s, dx * s + dy * c);
+ (rx * self.inv_scale, ry * self.inv_scale)
+ }
+}
+
+/// Renders `tile` over `rect` (row-major straight RGBA).
+pub fn render(tile: &Tile, place: &Placement, rect: Rect) -> Vec<[f32; 4]> {
+ let mut out = 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 (u, v) = place.map(f64::from(x) + 0.5, f64::from(y) + 0.5);
+ out.push(tile.sample(u, v));
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::{PixelFormat, Surface};
+
+ fn checker() -> Pattern {
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ s.fill_rect(Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]);
+ s.fill_rect(Rect::new(0, 0, 2, 2), &[0.0, 0.0, 1.0, 1.0]);
+ s.fill_rect(Rect::new(2, 2, 4, 4), &[0.0, 0.0, 1.0, 1.0]);
+ Pattern::new("checker", s, 4, 4)
+ }
+
+ #[test]
+ fn identity_placement_tiles_exactly() {
+ let t = Tile::new(&checker()).unwrap();
+ let p = Placement::new(Rect::new(0, 0, 10, 10), false, (0.0, 0.0), 1.0, 0.0);
+ let px = render(&t, &p, Rect::new(-4, 0, 8, 1));
+ assert_eq!(px[0], [0.0, 0.0, 1.0, 1.0]); // x = -4 wraps to 0
+ assert_eq!(px[6], [1.0, 0.0, 0.0, 1.0]); // x = 2
+ assert_eq!(px[8], [0.0, 0.0, 1.0, 1.0]); // x = 4
+ }
+
+ #[test]
+ fn link_phase_scale_and_angle_move_the_origin() {
+ let t = Tile::new(&checker()).unwrap();
+ let linked = Placement::new(Rect::new(2, 0, 10, 10), true, (0.0, 0.0), 1.0, 0.0);
+ assert_eq!(render(&t, &linked, Rect::new(2, 0, 3, 1))[0], [0.0, 0.0, 1.0, 1.0]);
+ let phased = Placement::new(Rect::EMPTY, false, (2.0, 0.0), 1.0, 0.0);
+ assert_eq!(render(&t, &phased, Rect::new(2, 0, 3, 1))[0], [0.0, 0.0, 1.0, 1.0]);
+ let scaled = Placement::new(Rect::EMPTY, false, (0.0, 0.0), 2.0, 0.0);
+ let row = render(&t, &scaled, Rect::new(0, 1, 8, 2));
+ assert_eq!(row[2], [0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(row[6], [1.0, 0.0, 0.0, 1.0]);
+ // 90°: x and y swap roles.
+ let rot = Placement::new(Rect::EMPTY, false, (0.0, 0.0), 1.0, 90.0);
+ let (u, v) = rot.map(1.0, 3.0);
+ assert!((u - -3.0).abs() < 1e-9 && (v - 1.0).abs() < 1e-9, "{u},{v}");
+ }
+}
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index c38070993..ae276649f 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -104,7 +104,10 @@ fn disabled_mask_is_ignored() {
m.enabled = false;
l.mask = Some(m);
d.layers.push(l);
- assert!(close4(px(&d, 0, 0), [0.0, 0.0, 0.0, 1.0]));
+ // CMYK displays through the built-in CMYK profile: 100 % K alone is a dark neutral
+ // (as in any real CMYK profile), not pure black.
+ let p = px(&d, 0, 0);
+ assert!(p[0] < 0.3 && (p[0] - p[1]).abs() < 0.05 && (p[1] - p[2]).abs() < 0.05 && p[3] == 1.0, "{p:?}");
}
#[test]
@@ -258,9 +261,9 @@ fn solid_and_gradient_fill_layers() {
assert!(close4(px(&d, 5, 0), [0.0, 0.0, 1.0, 1.0]));
let g = 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 };
- let buf = render_fill(&g, Rect::new(0, 0, 10, 1), Rect::new(0, 0, 10, 1));
+ let buf = render_fill(&g, Rect::new(0, 0, 10, 1), Rect::new(0, 0, 10, 1), &[]);
// tile independence: a 1px render of the right edge equals the full render
- let one = render_fill(&g, Rect::new(9, 0, 10, 1), Rect::new(0, 0, 10, 1));
+ let one = render_fill(&g, Rect::new(9, 0, 10, 1), Rect::new(0, 0, 10, 1), &[]);
assert_eq!(one.px[0], buf.px[9]);
assert!(buf.px[0][0] < buf.px[9][0], "left dark, right light");
}
@@ -301,7 +304,10 @@ fn cmyk_document_renders_via_rgb() {
let mut l = Layer::raster("k", d.pixel_format());
l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 2), &[0.0, 0.0, 0.0, 1.0, 1.0]);
d.layers.push(l);
- assert!(close4(px(&d, 0, 0), [0.0, 0.0, 0.0, 1.0]));
+ // CMYK displays through the built-in CMYK profile: 100 % K alone is a dark neutral
+ // (as in any real CMYK profile), not pure black.
+ let p = px(&d, 0, 0);
+ assert!(p[0] < 0.3 && (p[0] - p[1]).abs() < 0.05 && (p[1] - p[2]).abs() < 0.05 && p[3] == 1.0, "{p:?}");
}
#[test]
@@ -636,7 +642,7 @@ fn effect_maps_are_cached_and_invalidated_by_pixel_changes() {
let mut l = solid_layer("fx", Rect::new(16, 16, 48, 48), [1.0, 0.0, 0.0, 1.0]);
l.effects.items.push(photocraft_doc::Effect::default_drop_shadow());
doc.layers.push(l);
- let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::Srgb, light: doc.global_light };
+ let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::Srgb, light: doc.global_light, patterns: &doc.patterns };
let a = effect_maps(&doc.layers[1], &cx);
let b = effect_maps(&doc.layers[1], &cx);
assert!(std::sync::Arc::ptr_eq(&a, &b), "second request hits the cache");
diff --git a/crates/doc/src/adjust.rs b/crates/doc/src/adjust.rs
index cd37c2f24..cd8cc9b4e 100644
--- a/crates/doc/src/adjust.rs
+++ b/crates/doc/src/adjust.rs
@@ -39,11 +39,25 @@ pub enum Adjustment {
BlackWhite { weights: [f32; 6], tint: Option<[f32; 3]> },
PhotoFilter { color: [f32; 3], density: f32, preserve_luminosity: bool },
ChannelMixer { matrix: [[f32; 4]; 3], monochrome: bool },
- ColorLookup { name: String, lut: Option<Arc<Vec<f32>>>, size: u32 },
+ /// A 3D LUT: `size`³ RGB triplets, red varying fastest (`((b·size + g)·size + r)·3`), in 0..=1.
+ /// `lut` is None for a lookup Photoshop stores as an ICC profile (identity here).
+ ColorLookup {
+ name: String,
+ lut: Option<Arc<Vec<f32>>>,
+ size: u32,
+ /// Tetrahedral instead of trilinear interpolation.
+ #[serde(default)]
+ tetrahedral: bool,
+ /// Ordered dither of ±½ an 8-bit step to hide banding (Photoshop's "Dither").
+ #[serde(default)]
+ dither: bool,
+ },
Invert,
Posterize { levels: u32 },
Threshold { level: f32 },
GradientMap { stops: Vec<(f32, [f32; 3])>, reverse: bool },
+ /// Per range (reds, yellows, greens, cyans, blues, magentas, whites, neutrals, blacks) the
+ /// cyan, magenta, yellow and black change in percent (-100..=100), as in Photoshop.
SelectiveColor { relative: bool, adjustments: [[f32; 4]; 9] },
/// A PSD adjustment we can't evaluate yet; preserved raw for round-trip.
Unsupported { psd_key: String, raw: Vec<u8> },
diff --git a/crates/doc/src/comps.rs b/crates/doc/src/comps.rs
new file mode 100644
index 000000000..347139c38
--- /dev/null
+++ b/crates/doc/src/comps.rs
@@ -0,0 +1,271 @@
+//! Layer comps (Window › Layer Comps) and artboards: pure data plus capture/apply helpers that need
+//! nothing beyond the document model.
+//!
+//! A layer comp records, per layer, its visibility, position and appearance (blend mode, opacity,
+//! fill opacity, layer style). Three flags choose which of those [`apply`](LayerComp) restores,
+//! like the checkboxes of Photoshop's Layer Comp Options. Position is the top-left of the layer's
+//! content bounds (artboards: of the board), so applying a comp moves a layer by the difference
+//! between that and where it is now.
+
+use photocraft_color::{BlendMode, Color};
+use photocraft_geom::Rect;
+use serde::{Deserialize, Serialize};
+
+use crate::{Document, Effects, Layer, LayerContent, LayerId};
+
+/// One layer's state as captured by a comp. `None` = not recorded (PSD comps record only what
+/// their capture flags asked for).
+#[derive(Clone, Debug, PartialEq)]
+pub struct CompLayerState {
+ pub layer: LayerId,
+ pub visible: Option<bool>,
+ /// Top-left of the content bounds (or artboard rect). None for layers without a position
+ /// (adjustment and fill layers, empty layers, plain groups).
+ pub position: Option<(i32, i32)>,
+ pub appearance: Option<CompAppearance>,
+}
+
+/// Layer › Layer Style state captured by "Appearance".
+#[derive(Clone, Debug, PartialEq)]
+pub struct CompAppearance {
+ pub blend: BlendMode,
+ pub opacity: f32,
+ pub fill_opacity: f32,
+ pub effects: Effects,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct LayerComp {
+ /// Stable id (the PSD `compID`). Never 0: Photoshop uses 0 for the Last Document State.
+ pub id: u32,
+ pub name: String,
+ pub comment: String,
+ pub apply_visibility: bool,
+ pub apply_position: bool,
+ pub apply_appearance: bool,
+ /// Per-layer state, in document walk order.
+ pub states: Vec<CompLayerState>,
+}
+
+impl LayerComp {
+ /// PSD `capturedInfo` bit flags: 1 visibility, 2 position, 4 appearance.
+ pub fn captured_info(&self) -> i32 {
+ i32::from(self.apply_visibility) | i32::from(self.apply_position) << 1 | i32::from(self.apply_appearance) << 2
+ }
+ pub fn set_captured_info(&mut self, v: i32) {
+ self.apply_visibility = v & 1 != 0;
+ self.apply_position = v & 2 != 0;
+ self.apply_appearance = v & 4 != 0;
+ }
+ pub fn state(&self, id: LayerId) -> Option<&CompLayerState> {
+ self.states.iter().find(|s| s.layer == id)
+ }
+ /// Ids of recorded layers that no longer exist in `doc` (Photoshop's warning triangle).
+ pub fn missing_layers(&self, doc: &Document) -> Vec<LayerId> {
+ let live: std::collections::HashSet<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ self.states.iter().map(|s| s.layer).filter(|id| !live.contains(id)).collect()
+ }
+}
+
+/// Content bounds used for comp positions: pixels (or the rendered cache) of a layer, the board of
+/// an artboard. Empty for adjustment/fill layers and plain groups.
+pub fn position_bounds(l: &Layer) -> Rect {
+ match &l.content {
+ LayerContent::Group(g) => g.artboard.as_ref().map_or(Rect::EMPTY, |a| a.rect),
+ LayerContent::Adjustment(_) | LayerContent::Fill(_) => Rect::EMPTY,
+ _ => l.surface().map_or(Rect::EMPTY, |s| s.content_bounds()),
+ }
+}
+
+/// Comp position of a layer (see [`position_bounds`]).
+pub fn layer_position(l: &Layer) -> Option<(i32, i32)> {
+ let r = position_bounds(l);
+ (!r.is_empty()).then_some((r.x0, r.y0))
+}
+
+/// Capture the full state of every layer.
+pub fn capture_states(doc: &Document) -> Vec<CompLayerState> {
+ doc.walk()
+ .into_iter()
+ .map(|(_, _, l)| CompLayerState {
+ layer: l.id,
+ visible: Some(l.visible),
+ position: layer_position(l),
+ appearance: Some(CompAppearance { blend: l.blend, opacity: l.opacity, fill_opacity: l.fill_opacity, effects: l.effects.clone() }),
+ })
+ .collect()
+}
+
+/// A fresh comp id, unique among `doc`'s comps (never 0).
+pub fn next_comp_id(doc: &Document) -> u32 {
+ // Photoshop uses large pseudo-random ids; any unique non-zero value round-trips.
+ let mut id = doc.layer_comps.iter().map(|c| c.id).max().unwrap_or(0).wrapping_add(1).max(1);
+ while doc.layer_comps.iter().any(|c| c.id == id) {
+ id = id.wrapping_add(1).max(1);
+ }
+ id
+}
+
+/// What an artboard paints behind its contents.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ArtboardBackground {
+ #[default]
+ White,
+ Black,
+ Transparent,
+ Custom(Color),
+}
+
+impl ArtboardBackground {
+ /// sRGB colour painted under the contents (None = transparent).
+ pub fn rgba(&self) -> Option<[f32; 4]> {
+ match self {
+ ArtboardBackground::White => Some([1.0, 1.0, 1.0, 1.0]),
+ ArtboardBackground::Black => Some([0.0, 0.0, 0.0, 1.0]),
+ ArtboardBackground::Transparent => None,
+ ArtboardBackground::Custom(c) => {
+ let [r, g, b] = c.to_rgb();
+ (c.alpha > 0.0).then_some([r, g, b, c.alpha])
+ }
+ }
+ }
+ /// PSD `artboardBackgroundType`: 1 white, 2 black, 3 transparent, 4 other.
+ pub fn psd_type(&self) -> i32 {
+ match self {
+ ArtboardBackground::White => 1,
+ ArtboardBackground::Black => 2,
+ ArtboardBackground::Transparent => 3,
+ ArtboardBackground::Custom(_) => 4,
+ }
+ }
+ pub fn name(&self) -> &'static str {
+ match self {
+ ArtboardBackground::White => "white",
+ ArtboardBackground::Black => "black",
+ ArtboardBackground::Transparent => "transparent",
+ ArtboardBackground::Custom(_) => "custom",
+ }
+ }
+}
+
+/// An artboard: a top-level group that clips its children to `rect` and paints `background`
+/// behind them (Layer › New › Artboard).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Artboard {
+ /// The board in document pixels.
+ pub rect: Rect,
+ pub background: ArtboardBackground,
+ /// Size preset the board was made from ("" = custom).
+ #[serde(default)]
+ pub preset: String,
+}
+
+impl Artboard {
+ pub fn new(rect: Rect) -> Self {
+ Self { rect, background: ArtboardBackground::White, preset: String::new() }
+ }
+}
+
+impl Document {
+ /// Top-level artboards, bottom to top: (layer id, name, artboard).
+ pub fn artboards(&self) -> Vec<(LayerId, &str, &Artboard)> {
+ self.layers
+ .iter()
+ .filter_map(|l| match &l.content {
+ LayerContent::Group(g) => g.artboard.as_ref().map(|a| (l.id, l.name.as_str(), a)),
+ _ => None,
+ })
+ .collect()
+ }
+ pub fn has_artboards(&self) -> bool {
+ self.layers.iter().any(|l| l.artboard().is_some())
+ }
+ pub fn comp(&self, id: u32) -> Option<&LayerComp> {
+ self.layer_comps.iter().find(|c| c.id == id)
+ }
+ /// The artboard containing layer `id` (itself, or its top-level ancestor).
+ pub fn artboard_of(&self, id: LayerId) -> Option<LayerId> {
+ let path = self.path_of(id)?;
+ let top = self.layers.get(*path.first()?)?;
+ top.artboard().map(|_| top.id)
+ }
+}
+
+impl Layer {
+ pub fn artboard(&self) -> Option<&Artboard> {
+ match &self.content {
+ LayerContent::Group(g) => g.artboard.as_ref(),
+ _ => None,
+ }
+ }
+ pub fn artboard_mut(&mut self) -> Option<&mut Artboard> {
+ match &mut self.content {
+ LayerContent::Group(g) => g.artboard.as_mut(),
+ _ => None,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{ColorMode, PixelFormat, SampleType, Size};
+
+ fn doc() -> Document {
+ let mut d = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+ let mut l = Layer::raster("A", PixelFormat::RGBA8);
+ l.surface_mut().unwrap().fill_rect(Rect::new(10, 12, 20, 22), &[1.0, 0.0, 0.0, 1.0]);
+ d.layers.push(l);
+ d
+ }
+
+ #[test]
+ fn capture_records_every_layer() {
+ let d = doc();
+ let s = capture_states(&d);
+ assert_eq!(s.len(), 2);
+ assert_eq!(s[1].position, Some((10, 12)));
+ assert_eq!(s[1].visible, Some(true));
+ assert!(s[1].appearance.is_some());
+ }
+
+ #[test]
+ fn captured_info_bits() {
+ let mut c = LayerComp { id: 1, name: "c".into(), comment: String::new(), apply_visibility: false, apply_position: false, apply_appearance: false, states: vec![] };
+ c.set_captured_info(5);
+ assert!(c.apply_visibility && !c.apply_position && c.apply_appearance);
+ assert_eq!(c.captured_info(), 5);
+ }
+
+ #[test]
+ fn missing_layers_and_ids() {
+ let mut d = doc();
+ let states = capture_states(&d);
+ d.layer_comps.push(LayerComp { id: next_comp_id(&d), name: "c".into(), comment: String::new(), apply_visibility: true, apply_position: true, apply_appearance: true, states });
+ assert_eq!(d.layer_comps[0].id, 1);
+ assert_eq!(next_comp_id(&d), 2);
+ let gone = d.layers[1].id;
+ d.layers.pop();
+ assert_eq!(d.layer_comps[0].missing_layers(&d), vec![gone]);
+ }
+
+ #[test]
+ fn artboards_listed_and_found() {
+ let mut d = doc();
+ let child = Layer::raster("in", PixelFormat::RGBA8);
+ let cid = child.id;
+ let mut g = Layer::group("Artboard 1", vec![child]);
+ if let LayerContent::Group(gr) = &mut g.content {
+ gr.artboard = Some(Artboard::new(Rect::new(0, 0, 32, 32)));
+ }
+ let gid = g.id;
+ d.layers.push(g);
+ assert!(d.has_artboards());
+ assert_eq!(d.artboards().len(), 1);
+ assert_eq!(d.artboard_of(cid), Some(gid));
+ assert_eq!(layer_position(d.layer(gid).unwrap()), Some((0, 0)));
+ assert_eq!(ArtboardBackground::Black.rgba(), Some([0.0, 0.0, 0.0, 1.0]));
+ assert_eq!(ArtboardBackground::Transparent.rgba(), None);
+ }
+}
diff --git a/crates/doc/src/effects.rs b/crates/doc/src/effects.rs
index 35810f9fd..8bfc5f97c 100644
--- a/crates/doc/src/effects.rs
+++ b/crates/doc/src/effects.rs
@@ -209,7 +209,21 @@ pub enum Effect {
Stroke(StrokeFx),
ColorOverlay { common: FxCommon, color: Color },
GradientOverlay { common: FxCommon, gradient: Gradient, dither: bool },
- PatternOverlay { common: FxCommon, name: String, id: String, scale: f32 },
+ PatternOverlay {
+ common: FxCommon,
+ name: String,
+ id: String,
+ scale: f32,
+ /// Rotation in degrees (counter-clockwise).
+ #[serde(default)]
+ angle: f32,
+ /// "Link with Layer": the pattern origin follows the layer (else the canvas).
+ #[serde(default = "yes")]
+ link: bool,
+ /// Phase (origin offset) in pixels.
+ #[serde(default)]
+ phase: (f32, f32),
+ },
Satin(Satin),
BevelEmboss(Bevel),
}
@@ -263,6 +277,11 @@ impl Effect {
}
}
+/// Serde default for flags that start on.
+pub fn yes() -> bool {
+ true
+}
+
/// Document-wide light used by effects with `use_global_light`.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct GlobalLight {
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index d1efb6681..cbbae72b5 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -8,7 +8,10 @@
#![forbid(unsafe_code)]
pub mod adjust;
+pub mod comps;
pub mod effects;
+pub mod mode;
+pub mod pattern;
pub mod text;
pub mod vector;
@@ -16,6 +19,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
pub use adjust::Adjustment;
+pub use comps::{Artboard, ArtboardBackground, CompAppearance, CompLayerState, LayerComp};
pub use effects::{
Bevel, BevelStyle, BevelTechnique, Contour, Effect, FxCommon, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient,
GradientStyle, Satin, Shadow, StrokeFx, StrokePosition,
@@ -23,6 +27,8 @@ 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 mode::{ColorTable, Duotone, DuotoneInk, StackMode};
+pub use pattern::Pattern;
pub use vector::{
ClippingPath, FillRule, Knot, LineCap, LineJoin, LiveShape, NamedPath, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath,
VectorMask,
@@ -145,6 +151,8 @@ pub struct Effects {
pub struct Group {
pub children: Vec<Layer>,
pub expanded: bool,
+ /// Set when this (top-level) group is an artboard: children are clipped to its rect.
+ pub artboard: Option<Artboard>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -152,7 +160,22 @@ pub enum Fill {
Solid(Color),
/// Gradient between stops at `angle` degrees (`style` geometry, optionally reversed).
Gradient { stops: Vec<(f32, Color)>, angle: f32, scale: f32, style: GradientStyle, reverse: bool },
- Pattern { name: String, scale: f32 },
+ /// A pattern from [`Document::patterns`] (looked up by `id`, then `name`).
+ Pattern {
+ name: String,
+ scale: f32,
+ #[serde(default)]
+ id: String,
+ /// Rotation in degrees (counter-clockwise).
+ #[serde(default)]
+ angle: f32,
+ /// "Link with Layer": the pattern origin follows the layer's frame (else the canvas).
+ #[serde(default = "effects::yes")]
+ link: bool,
+ /// Phase (origin offset) in pixels.
+ #[serde(default)]
+ phase: (f32, f32),
+ },
}
#[derive(Clone, Debug, PartialEq)]
@@ -176,7 +199,7 @@ pub struct TextLayer {
pub shape: text::TextShape,
pub orientation: text::Orientation,
pub antialias: text::AntiAlias,
- /// Warp settings (stored; not rendered yet).
+ /// Warp Text settings (applied to the glyph outlines when rendering).
pub warp: Option<text::TextWarp>,
}
@@ -271,6 +294,25 @@ pub struct SmartObject {
/// Data of the PSD placed-layer block (`SoLd`, `PlLd` or `SoLE`). On export
/// it replaces that entry in [`Layer::psd_blocks`].
pub psd_raw: Option<Arc<Vec<u8>>>,
+ /// Layer › Smart Filter › Disable Smart Filters turns the whole stack off
+ /// without touching each filter's own visibility.
+ pub filters_enabled: bool,
+ /// The smart filter mask (one per smart object, as in Photoshop): where the
+ /// filter stack's result shows over the unfiltered content.
+ pub filter_mask: Option<LayerMask>,
+ /// Edit › Transform › Warp on the smart object, in source-image coordinates; applied before
+ /// `transform` when re-rendering from the source, so warping stays lossless.
+ pub warp: Option<photocraft_geom::warp::Warp>,
+ /// Layer › Smart Objects › Stack Mode: when set, the source's top-level layers are combined
+ /// per pixel with this statistic instead of composited.
+ pub stack_mode: Option<StackMode>,
+}
+
+impl SmartObject {
+ /// A smart object with no filters and no PSD data.
+ pub fn new(source: SmartSource, transform: Affine, cache: Option<Surface>) -> Self {
+ Self { source, transform, smart_filters: Vec::new(), cache, psd_raw: None, filters_enabled: true, filter_mask: None, warp: None, stack_mode: None }
+ }
}
#[derive(Clone, Debug, PartialEq)]
@@ -360,6 +402,8 @@ pub struct Layer {
pub psd_id: Option<u32>,
/// Photoshop-rendered pixels for fill layers (see [`FillCache`]).
pub fill_cache: Option<FillCache>,
+ /// Layer › Link Layers: layers sharing a link group move together. `None` = not linked.
+ pub link_group: Option<u64>,
}
impl Layer {
@@ -381,13 +425,14 @@ impl Layer {
psd_blocks: Vec::new(),
psd_id: None,
fill_cache: None,
+ link_group: None,
}
}
pub fn raster(name: impl Into<String>, format: PixelFormat) -> Self {
Self::new(name, LayerContent::Raster(Surface::new(format)))
}
pub fn group(name: impl Into<String>, children: Vec<Layer>) -> Self {
- let mut l = Self::new(name, LayerContent::Group(Group { children, expanded: true }));
+ let mut l = Self::new(name, LayerContent::Group(Group { children, expanded: true, artboard: None }));
l.blend = BlendMode::PassThrough;
l
}
@@ -444,12 +489,46 @@ pub struct Guides {
pub vertical: Vec<f32>,
}
+/// Which areas an alpha channel's overlay colour marks (Channel Options › Color Indicates).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ColorIndicates {
+ /// Colour shows over black (unselected) pixels: Photoshop's default.
+ #[default]
+ MaskedAreas,
+ /// Colour shows over white (selected) pixels.
+ SelectedAreas,
+}
+
+/// An extra (alpha or spot) channel, also used for the temporary Quick Mask channel.
+///
+/// The surface is grayscale at the document depth; white = selected (1.0), black = masked.
#[derive(Clone, Debug, PartialEq)]
pub struct AlphaChannel {
pub name: String,
pub surface: Surface,
/// Spot colour channels carry their ink colour and solidity.
pub spot: Option<(Color, f32)>,
+ /// Overlay colour shown when the channel is viewed together with the composite.
+ pub color: Color,
+ /// Overlay opacity (0..1).
+ pub opacity: f32,
+ pub indicates: ColorIndicates,
+}
+
+impl AlphaChannel {
+ /// Photoshop's default overlay: red at 50% over masked areas.
+ pub const DEFAULT_COLOR: Color = Color::rgb(1.0, 0.0, 0.0);
+
+ pub fn new(name: impl Into<String>, surface: Surface) -> Self {
+ Self { name: name.into(), surface, spot: None, color: Self::DEFAULT_COLOR, opacity: 0.5, indicates: ColorIndicates::MaskedAreas }
+ }
+
+ /// Overlay coverage (0..1, before opacity) for channel value `v`: spot channels show ink
+ /// where the channel is white, alpha channels follow [`ColorIndicates`].
+ pub fn overlay_coverage(&self, v: f32) -> f32 {
+ if self.spot.is_some() || self.indicates == ColorIndicates::SelectedAreas { v } else { 1.0 - v }
+ }
}
/// A raw PSD global tagged block: (signature, key, data).
@@ -490,6 +569,23 @@ pub struct Document {
pub work_path: Option<Path>,
/// Clipping path used on export (names one of `paths`).
pub clipping_path: Option<ClippingPath>,
+ /// Select › Edit in Quick Mask Mode: the temporary "Quick Mask" channel while the mode is on.
+ /// Part of the document so entering and leaving are history steps (as in Photoshop).
+ pub quick_mask: Option<AlphaChannel>,
+ /// Patterns stored with the document (PSD `Patt`/`Pat2`/`Pat3`): those its layers use, plus
+ /// any imported with it.
+ pub patterns: Vec<Pattern>,
+ /// Indexed Color palette (Image › Mode › Color Table). Set while `mode` is Indexed.
+ pub color_table: Option<ColorTable>,
+ /// Duotone inks. Set while `mode` is Duotone.
+ pub duotone: Option<Duotone>,
+ /// Window › Layer Comps, top to bottom as listed in the panel.
+ pub layer_comps: Vec<LayerComp>,
+ /// Id of the comp applied last (PSD `lastAppliedComp`); None = the document's own state.
+ pub last_applied_comp: Option<u32>,
+ /// "Last Document State": layer state saved when a comp is applied over the document's own
+ /// state, restored by `layerComp.restoreLastDocumentState`. Its id is 0.
+ pub last_document_state: Option<LayerComp>,
}
/// Where a layer lives in the tree: indices from the root down.
@@ -514,6 +610,13 @@ impl Document {
paths: Vec::new(),
work_path: None,
clipping_path: None,
+ quick_mask: None,
+ patterns: Vec::new(),
+ color_table: None,
+ duotone: None,
+ layer_comps: Vec::new(),
+ last_applied_comp: None,
+ last_document_state: None,
}
}
diff --git a/crates/doc/src/mode.rs b/crates/doc/src/mode.rs
new file mode 100644
index 000000000..8b0bd4166
--- /dev/null
+++ b/crates/doc/src/mode.rs
@@ -0,0 +1,243 @@
+//! Colour-mode side data: the Indexed Color table, Duotone inks, and smart-object stack modes.
+//!
+//! Indexed, Bitmap and Duotone documents keep their pixels expanded (RGB / Gray, see
+//! [`crate::Document::pixel_format`]); these structs carry what the mode adds on top.
+
+use serde::{Deserialize, Serialize};
+
+use crate::adjust::CurvePoint;
+
+/// Image › Mode › Color Table: the palette of an Indexed Color document (at most 256 entries).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ColorTable {
+ /// sRGB 8-bit entries.
+ pub colors: Vec<[u8; 3]>,
+ /// Index of the entry shown as transparent (Indexed Color › Transparency).
+ #[serde(default)]
+ pub transparent: Option<u8>,
+}
+
+impl ColorTable {
+ /// Nearest palette index for an RGB colour in 0..=1 (squared distance, ties to the lower index).
+ pub fn nearest(&self, c: [f32; 3]) -> usize {
+ let mut best = (f32::MAX, 0);
+ for (i, e) in self.colors.iter().enumerate() {
+ let d: f32 = (0..3)
+ .map(|k| (c[k] - f32::from(e[k]) / 255.0).powi(2))
+ .sum();
+ if d < best.0 {
+ best = (d, i);
+ }
+ }
+ best.1
+ }
+
+ /// Entry `i` as RGB in 0..=1 (black past the end).
+ pub fn rgb(&self, i: usize) -> [f32; 3] {
+ self.colors
+ .get(i)
+ .map_or([0.0; 3], |e| e.map(|v| f32::from(v) / 255.0))
+ }
+}
+
+/// One Duotone ink: its display colour and the curve mapping gray density to ink density.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct DuotoneInk {
+ pub name: String,
+ /// Display colour of the solid ink (sRGB 0..=1).
+ pub color: [f32; 3],
+ /// Ink density curve, input = gray *density* (0 = paper, 1 = solid), output = ink density.
+ pub curve: Vec<CurvePoint>,
+}
+
+impl DuotoneInk {
+ pub fn new(name: impl Into<String>, color: [f32; 3]) -> Self {
+ DuotoneInk {
+ name: name.into(),
+ color,
+ curve: vec![
+ CurvePoint {
+ input: 0.0,
+ output: 0.0,
+ },
+ CurvePoint {
+ input: 1.0,
+ output: 1.0,
+ },
+ ],
+ }
+ }
+}
+
+/// Image › Mode › Duotone: 1–4 inks (Monotone, Duotone, Tritone, Quadtone) printed over paper.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Duotone {
+ pub inks: Vec<DuotoneInk>,
+ /// The PSD colour-mode data this came from, written back unchanged while the inks are unedited.
+ #[serde(default)]
+ pub psd_raw: Option<Vec<u8>>,
+}
+
+impl Duotone {
+ /// Simulated print colour of a gray value (0 = black, 1 = white): inks multiply over white paper.
+ pub fn render(&self, gray: f32) -> [f32; 3] {
+ let density = 1.0 - gray.clamp(0.0, 1.0);
+ let mut out = [1.0f32; 3];
+ for ink in &self.inks {
+ let d = curve_eval(&ink.curve, density);
+ for (o, c) in out.iter_mut().zip(ink.color) {
+ // Each ink filters light: full density transmits the ink colour.
+ *o *= 1.0 - d * (1.0 - c);
+ }
+ }
+ out
+ }
+}
+
+impl Duotone {
+ /// A Gradient Map that turns the gray composite into the printed look; displays and flat
+ /// exports put it on top of a copy of the document.
+ pub fn display_adjustment(&self) -> crate::Adjustment {
+ let stops = (0..=32).map(|i| {
+ let t = i as f32 / 32.0;
+ (t, self.render(t))
+ });
+ crate::Adjustment::GradientMap {
+ stops: stops.collect(),
+ reverse: false,
+ }
+ }
+}
+
+/// Piecewise-linear evaluation (Photoshop's duotone curves are 13-point linear transfer curves).
+fn curve_eval(pts: &[CurvePoint], x: f32) -> f32 {
+ match pts {
+ [] => x,
+ [p] => p.output,
+ _ => {
+ if x <= pts[0].input {
+ return pts[0].output;
+ }
+ for w in pts.windows(2) {
+ if x <= w[1].input {
+ let span = (w[1].input - w[0].input).max(1e-6);
+ return w[0].output + (w[1].output - w[0].output) * (x - w[0].input) / span;
+ }
+ }
+ pts[pts.len() - 1].output
+ }
+ }
+}
+
+/// Layer › Smart Objects › Stack Mode: a per-pixel statistic over the smart object's layers.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum StackMode {
+ Entropy,
+ Kurtosis,
+ Maximum,
+ Mean,
+ Median,
+ Minimum,
+ Range,
+ Skewness,
+ StandardDeviation,
+ Summation,
+ Variance,
+}
+
+impl StackMode {
+ pub const ALL: [StackMode; 11] = [
+ StackMode::Entropy,
+ StackMode::Kurtosis,
+ StackMode::Maximum,
+ StackMode::Mean,
+ StackMode::Median,
+ StackMode::Minimum,
+ StackMode::Range,
+ StackMode::Skewness,
+ StackMode::StandardDeviation,
+ StackMode::Summation,
+ StackMode::Variance,
+ ];
+
+ /// The menu-id suffix (`layer.smartObjects.stackMode.<id>`).
+ pub fn id(self) -> &'static str {
+ match self {
+ StackMode::Entropy => "entropy",
+ StackMode::Kurtosis => "kurtosis",
+ StackMode::Maximum => "maximum",
+ StackMode::Mean => "mean",
+ StackMode::Median => "median",
+ StackMode::Minimum => "minimum",
+ StackMode::Range => "range",
+ StackMode::Skewness => "skewness",
+ StackMode::StandardDeviation => "standardDeviation",
+ StackMode::Summation => "summation",
+ StackMode::Variance => "variance",
+ }
+ }
+
+ pub fn from_id(id: &str) -> Option<Self> {
+ Self::ALL.into_iter().find(|m| m.id() == id)
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ StackMode::Entropy => "Entropy",
+ StackMode::Kurtosis => "Kurtosis",
+ StackMode::Maximum => "Maximum",
+ StackMode::Mean => "Mean",
+ StackMode::Median => "Median",
+ StackMode::Minimum => "Minimum",
+ StackMode::Range => "Range",
+ StackMode::Skewness => "Skewness",
+ StackMode::StandardDeviation => "Standard Deviation",
+ StackMode::Summation => "Summation",
+ StackMode::Variance => "Variance",
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn color_table_nearest() {
+ let t = ColorTable {
+ colors: vec![[0, 0, 0], [255, 255, 255], [255, 0, 0]],
+ transparent: None,
+ };
+ assert_eq!(t.nearest([0.9, 0.1, 0.1]), 2);
+ assert_eq!(t.nearest([0.6, 0.6, 0.6]), 1);
+ assert_eq!(t.rgb(2), [1.0, 0.0, 0.0]);
+ }
+
+ #[test]
+ fn duotone_render_black_ink_is_gray() {
+ let d = Duotone {
+ inks: vec![DuotoneInk::new("Black", [0.0; 3])],
+ psd_raw: None,
+ };
+ for g in [0.0, 0.25, 1.0] {
+ let c = d.render(g);
+ assert!((c[0] - g).abs() < 1e-6 && c[0] == c[2]);
+ }
+ let d = Duotone {
+ inks: vec![
+ DuotoneInk::new("Black", [0.0; 3]),
+ DuotoneInk::new("Orange", [1.0, 0.5, 0.0]),
+ ],
+ psd_raw: None,
+ };
+ let c = d.render(0.5);
+ assert!(c[0] > c[2], "{c:?}");
+ }
+
+ #[test]
+ fn stack_mode_ids_roundtrip() {
+ for m in StackMode::ALL {
+ assert_eq!(StackMode::from_id(m.id()), Some(m));
+ }
+ }
+}
diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs
new file mode 100644
index 000000000..731dcb435
--- /dev/null
+++ b/crates/doc/src/pattern.rs
@@ -0,0 +1,114 @@
+//! Patterns: tiles used by Pattern Overlay, pattern fill layers, pattern strokes, Edit › Fill
+//! and brush textures. Pure data; rendering lives in `photocraft-compose`, the PSD mapping
+//! (`Patt`/`Pat2`/`Pat3` global blocks) in `photocraft-io`.
+
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+
+/// One pattern tile. Pixels cover `0..width × 0..height` of `surface`, in any pixel format
+/// (depth and colour model are the pattern's own, as in Photoshop).
+#[derive(Clone, Debug, PartialEq)]
+pub struct Pattern {
+ /// Unique id (a UUID string, as Photoshop's `Idnt`).
+ pub id: String,
+ /// Name as stored (Photoshop's built-ins use `$$$/Patterns/…=Display Name`; see
+ /// [`Pattern::display_name`]).
+ pub name: String,
+ pub width: u32,
+ pub height: u32,
+ pub surface: Surface,
+}
+
+/// 64-bit FNV-1a, used for deterministic pattern ids.
+fn fnv(h: u64, bytes: &[u8]) -> u64 {
+ bytes.iter().fold(h, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
+}
+
+impl Pattern {
+ /// A pattern with an id derived from its name and pixels (same content → same id, so
+ /// defining a pattern is deterministic and replayable).
+ pub fn new(name: impl Into<String>, surface: Surface, width: u32, height: u32) -> Pattern {
+ let name = name.into();
+ let r = Rect::new(0, 0, width as i32, height as i32);
+ let px = surface.read_region(r);
+ let mut h1 = fnv(0xcbf2_9ce4_8422_2325, name.as_bytes());
+ h1 = fnv(h1, &width.to_le_bytes());
+ h1 = fnv(h1, &height.to_le_bytes());
+ for v in &px {
+ h1 = fnv(h1, &v.to_bits().to_le_bytes());
+ }
+ let h2 = fnv(h1 ^ 0x9e37_79b9_7f4a_7c15, format!("{:?}", surface.format()).as_bytes());
+ let id = format!(
+ "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
+ (h1 >> 32) as u32,
+ (h1 >> 16) as u16,
+ h1 as u16,
+ (h2 >> 48) as u16,
+ h2 & 0xffff_ffff_ffff
+ );
+ Pattern { id, name, width, height, surface }
+ }
+
+ /// The name shown in UIs: Photoshop's localisation keys (`$$$/Patterns/…=Water`) show
+ /// the text after `=`; trailing NULs are dropped.
+ pub fn display_name(&self) -> &str {
+ display_name(&self.name)
+ }
+
+ /// The tile's rectangle.
+ pub fn rect(&self) -> Rect {
+ Rect::new(0, 0, self.width as i32, self.height as i32)
+ }
+
+ /// Whether the tile has pixels.
+ pub fn is_empty(&self) -> bool {
+ self.width == 0 || self.height == 0
+ }
+}
+
+/// Display form of a stored pattern name (see [`Pattern::display_name`]).
+pub fn display_name(name: &str) -> &str {
+ let n = name.trim_end_matches('\0');
+ match n.strip_prefix("$$$/").and_then(|r| r.split_once('=')) {
+ Some((_, shown)) => shown,
+ None => n,
+ }
+}
+
+/// Finds a pattern by id, else by stored name, else by display name (case-insensitive).
+pub fn find<'a>(patterns: &'a [Pattern], id: &str, name: &str) -> Option<&'a Pattern> {
+ if !id.is_empty()
+ && let Some(p) = patterns.iter().find(|p| p.id == id)
+ {
+ return Some(p);
+ }
+ if name.is_empty() {
+ return None;
+ }
+ patterns
+ .iter()
+ .find(|p| p.name == name)
+ .or_else(|| patterns.iter().find(|p| p.display_name().eq_ignore_ascii_case(display_name(name))))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::PixelFormat;
+
+ #[test]
+ fn ids_are_deterministic_and_lookup_falls_back_to_names() {
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ s.fill_rect(Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]);
+ let a = Pattern::new("$$$/Patterns/Defaults/Water=Water", s.clone(), 4, 4);
+ let b = Pattern::new("$$$/Patterns/Defaults/Water=Water", s.clone(), 4, 4);
+ assert_eq!(a.id, b.id);
+ assert_eq!(a.id.len(), 36);
+ assert_ne!(Pattern::new("Other", s, 4, 4).id, a.id);
+ assert_eq!(a.display_name(), "Water");
+ let list = vec![a.clone()];
+ assert!(find(&list, &a.id, "").is_some());
+ assert!(find(&list, "nope", "water").is_some());
+ assert!(find(&list, "nope", "").is_none());
+ }
+}
diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs
index ba9037c37..4fd5236f1 100644
--- a/crates/doc/src/text.rs
+++ b/crates/doc/src/text.rs
@@ -228,10 +228,15 @@ pub enum AntiAlias {
Strong,
#[default]
Smooth,
+ /// Photoshop's "Windows" (platform grayscale) anti-aliasing; rendered like `Sharp`.
+ Windows,
+ /// Photoshop's "Windows LCD" (platform subpixel) anti-aliasing; rendered like `Sharp` (we
+ /// never produce colour-fringed subpixel text in document pixels).
+ WindowsLcd,
}
-/// Warp text settings (Photoshop `warp` descriptor). Placeholder: stored and round-tripped,
-/// not yet applied by the renderer.
+/// Warp text settings (Photoshop `warp` descriptor), applied to the glyph outlines by
+/// `photocraft-text` (see its `warp` module) and round-tripped through PSD.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct TextWarp {
/// `warpNone`, `warpArc`, `warpFlag`, …
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 61a9b8b8a..6a2b7d3b1 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -10,6 +10,7 @@ workspace = true
[dependencies]
photocraft-geom = { workspace = true }
photocraft-color = { workspace = true }
+photocraft-cms = { workspace = true }
photocraft-raster = { workspace = true }
photocraft-doc = { workspace = true }
photocraft-ops = { workspace = true }
@@ -21,3 +22,6 @@ photocraft-paint = { workspace = true }
photocraft-algo = { workspace = true }
photocraft-text = { workspace = true }
photocraft-vector = { workspace = true }
+photocraft-io = { workspace = true }
+photocraft-format = { workspace = true }
+blake3 = { version = "1.8", default-features = false, features = ["pure"] }
diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs
new file mode 100644
index 000000000..5e4188cc0
--- /dev/null
+++ b/crates/engine/src/adjust_cmds.rs
@@ -0,0 +1,504 @@
+//! Image › Adjustments beyond the per-pixel adjustment-layer kinds:
+//!
+//! * parameter parsing for Selective Color and Color Lookup (both also adjustment layers; their
+//! commands are generated with the other kinds in `commands.rs`),
+//! * the destructive-only adjustments: Shadows/Highlights, Replace Color, Match Color and HDR
+//! Toning (maths in `photocraft_algo::tone`).
+//!
+//! Destructive adjustments convert the target (layer pixels, or a targeted alpha channel /
+//! Quick Mask) to straight RGBA, so every colour model and bit depth is handled, and blend the
+//! result through the selection like the other Image › Adjustments commands.
+
+use photocraft_algo::tone::{self, HdrToning, MatchColor, ShadowsHighlights};
+use photocraft_doc::{Adjustment, Document, Layer, LayerContent, Rect};
+use photocraft_raster::{Surface, from_rgba_into, to_rgba};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+/// Built-in Color Lookup looks `(id, label)`.
+pub use photocraft_cms::lutfile::BUILTIN as LOOKS;
+
+/// Selective Color range keys in storage order.
+pub const RANGES: [&str; 9] = [
+ "reds", "yellows", "greens", "cyans", "blues", "magentas", "whites", "neutrals", "blacks",
+];
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams {
+ cmd: cmd.into(),
+ msg: msg.into(),
+ }
+}
+
+fn num(p: &Value, key: &str, default: f32) -> f32 {
+ p.get(key)
+ .and_then(Value::as_f64)
+ .map_or(default, |v| v as f32)
+}
+
+/// Selective Color from params. Accepts per-range arrays (`"reds":[c,m,y,k]` in percent) and the
+/// dialog's single-range form (`"colors":"reds","cyan":…,"magenta":…,"yellow":…,"black":…`);
+/// `"method":"relative|absolute"`. Unspecified ranges keep `base`'s values.
+pub fn selective_from_params(p: &Value, base: Option<&Adjustment>) -> Adjustment {
+ let (mut relative, mut adj) = match base {
+ Some(Adjustment::SelectiveColor {
+ relative,
+ adjustments,
+ }) => (*relative, *adjustments),
+ _ => (true, [[0.0; 4]; 9]),
+ };
+ if let Some(m) = p.get("method").and_then(Value::as_str) {
+ relative = m != "absolute";
+ }
+ if let Some(b) = p.get("relative").and_then(Value::as_bool) {
+ relative = b;
+ }
+ for (i, key) in RANGES.iter().enumerate() {
+ if let Some(a) = p.get(*key).and_then(Value::as_array) {
+ for (k, v) in a.iter().take(4).enumerate() {
+ adj[i][k] = (v.as_f64().unwrap_or(0.0) as f32).clamp(-100.0, 100.0);
+ }
+ }
+ }
+ let range = p
+ .get("colors")
+ .and_then(Value::as_str)
+ .and_then(|c| RANGES.iter().position(|r| *r == c));
+ if let Some(i) = range {
+ for (k, key) in ["cyan", "magenta", "yellow", "black"].iter().enumerate() {
+ if let Some(v) = p.get(*key).and_then(Value::as_f64) {
+ adj[i][k] = (v as f32).clamp(-100.0, 100.0);
+ }
+ }
+ }
+ Adjustment::SelectiveColor {
+ relative,
+ adjustments: adj,
+ }
+}
+
+/// Color Lookup from params: `"lut"` (a built-in look id or `"none"`), `"file"` (a .cube / .3dl /
+/// .look path, native only) or `"data"` (the file's text, with `"fileName"` naming its format),
+/// `"interpolation":"trilinear|tetrahedral"`, `"dither":bool`. The table is embedded in the
+/// layer, as Photoshop does. Unspecified fields keep `base`'s values.
+pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjustment> {
+ const CMD: &str = "colorLookup";
+ let (mut name, mut lut, mut size, mut tetrahedral, mut dither) = match base {
+ Some(Adjustment::ColorLookup {
+ name,
+ lut,
+ size,
+ tetrahedral,
+ dither,
+ }) => (name.clone(), lut.clone(), *size, *tetrahedral, *dither),
+ _ => (String::new(), None, 0, false, false),
+ };
+ let mut loaded: Option<(photocraft_cms::lutfile::LutFile, String)> = None;
+ if let Some(id) = p.get("lut").and_then(Value::as_str) {
+ if id == "none" || id.is_empty() {
+ name.clear();
+ lut = None;
+ size = 0;
+ } else {
+ let f = photocraft_cms::lutfile::builtin(id).ok_or_else(|| {
+ bad(
+ CMD,
+ format!("unknown look `{id}` (built-ins: {})", builtin_ids()),
+ )
+ })?;
+ let label = f.title.clone();
+ loaded = Some((f, label));
+ }
+ }
+ if let Some(text) = p.get("data").and_then(Value::as_str) {
+ let file_name = p
+ .get("fileName")
+ .and_then(Value::as_str)
+ .unwrap_or("lut.cube");
+ let f = photocraft_cms::lutfile::parse(file_name, text.as_bytes())
+ .map_err(|e| bad(CMD, e.0))?;
+ loaded = Some((f, base_name(file_name)));
+ }
+ if let Some(path) = p
+ .get("file")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ {
+ let bytes = read_file(path).ok_or_else(|| bad(CMD, format!("can't read {path}")))?;
+ let f = photocraft_cms::lutfile::parse(path, &bytes)
+ .map_err(|e| bad(CMD, format!("{path}: {}", e.0)))?;
+ loaded = Some((f, base_name(path)));
+ }
+ if let Some((f, label)) = loaded {
+ name = label;
+ size = f.size as u32;
+ lut = Some(std::sync::Arc::new(f.data));
+ }
+ if let Some(i) = p.get("interpolation").and_then(Value::as_str) {
+ tetrahedral = i == "tetrahedral";
+ }
+ if let Some(b) = p.get("tetrahedral").and_then(Value::as_bool) {
+ tetrahedral = b;
+ }
+ if let Some(b) = p.get("dither").and_then(Value::as_bool) {
+ dither = b;
+ }
+ Ok(Adjustment::ColorLookup {
+ name,
+ lut,
+ size,
+ tetrahedral,
+ dither,
+ })
+}
+
+fn builtin_ids() -> String {
+ photocraft_cms::lutfile::BUILTIN
+ .iter()
+ .map(|b| b.0)
+ .collect::<Vec<_>>()
+ .join(", ")
+}
+
+fn base_name(path: &str) -> String {
+ path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn read_file(path: &str) -> Option<Vec<u8>> {
+ std::fs::read(path).ok()
+}
+#[cfg(target_arch = "wasm32")]
+fn read_file(_: &str) -> Option<Vec<u8>> {
+ None
+}
+
+/// `layer.setAdjustment` for the kinds edited one range / option at a time: params merge into the
+/// current values; a call with no parameters resets to defaults.
+pub fn update_adjustment(existing: &Adjustment, p: &Value) -> Option<Result<Adjustment>> {
+ let empty = p.as_object().is_none_or(|o| {
+ o.keys()
+ .all(|k| matches!(k.as_str(), "layer" | "coalesce" | "__kind"))
+ });
+ match existing {
+ Adjustment::SelectiveColor { .. } => {
+ Some(Ok(selective_from_params(p, (!empty).then_some(existing))))
+ }
+ Adjustment::ColorLookup { .. } => Some(lookup_from_params(p, (!empty).then_some(existing))),
+ _ => None,
+ }
+}
+
+// ---------- destructive helpers ----------
+
+/// Runs `f` on the target surface's content as straight RGBA (`w × h` = content bounds), blending
+/// the result through the selection.
+fn process_surface(
+ surf: &mut Surface,
+ selection: Option<&Surface>,
+ f: &mut dyn FnMut(&mut Vec<[f32; 4]>, Rect),
+) {
+ let r = surf.content_bounds();
+ if r.is_empty() {
+ return;
+ }
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let raw = surf.read_region(r);
+ let mut px: Vec<[f32; 4]> = raw.chunks_exact(n).map(|q| to_rgba(&fmt, q)).collect();
+ let orig = px.clone();
+ let w = r.width() as usize;
+ f(&mut px, r);
+ let mut out = Vec::with_capacity(raw.len());
+ for (i, (a, o)) in px.iter().zip(&orig).enumerate() {
+ 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);
+ let mut enc = [0.0f32; 8];
+ let m = from_rgba_into(&fmt, mixed, &mut enc);
+ out.extend_from_slice(&enc[..m]);
+ }
+ surf.write_region(r, &out);
+}
+
+/// One history step running `f` on the active pixel layer (or targeted channel).
+fn rgba_edit(
+ s: &mut Session,
+ label: &str,
+ p: &Value,
+ mut f: impl FnMut(&mut Vec<[f32; 4]>, Rect),
+) -> Result<Value> {
+ if crate::channel_cmds::is_channel_target(p) {
+ return s.edit(label, |doc, _| {
+ let sel = doc.selection.clone();
+ if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, p)? {
+ process_surface(surf, sel.as_ref(), &mut f);
+ surf.prune();
+ }
+ Ok(Value::Null)
+ });
+ }
+ let id = crate::commands::layer_param(s, &Value::Null)?;
+ s.edit(label, |doc, _| {
+ let sel = doc.selection.clone();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let surf = crate::commands::paint_surface(l, &Value::Null)?;
+ process_surface(surf, sel.as_ref(), &mut f);
+ Ok(Value::Null)
+ })
+}
+
+fn has_pixels(s: &Session) -> std::result::Result<(), String> {
+ if crate::channel_cmds::edits_channel(s) {
+ return Ok(());
+ }
+ 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 has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active()
+ .map(|_| ())
+ .ok_or_else(|| "no document open".into())
+}
+
+// ---------- commands ----------
+
+fn shadows_highlights(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = ShadowsHighlights::default();
+ let sh = ShadowsHighlights {
+ shadow_amount: num(p, "shadowAmount", d.shadow_amount).clamp(0.0, 100.0),
+ shadow_tone: num(p, "shadowTone", d.shadow_tone).clamp(0.0, 100.0),
+ shadow_radius: num(p, "shadowRadius", d.shadow_radius).clamp(0.0, 2500.0),
+ highlight_amount: num(p, "highlightAmount", d.highlight_amount).clamp(0.0, 100.0),
+ highlight_tone: num(p, "highlightTone", d.highlight_tone).clamp(0.0, 100.0),
+ highlight_radius: num(p, "highlightRadius", d.highlight_radius).clamp(0.0, 2500.0),
+ color: num(p, "color", d.color).clamp(-100.0, 100.0),
+ midtone: num(p, "midtone", d.midtone).clamp(-100.0, 100.0),
+ black_clip: num(p, "blackClip", d.black_clip).clamp(0.0, 50.0),
+ white_clip: num(p, "whiteClip", d.white_clip).clamp(0.0, 50.0),
+ };
+ rgba_edit(s, "Shadows/Highlights", p, |px, r| {
+ tone::shadows_highlights(px, r.width() as usize, r.height() as usize, &sh)
+ })
+}
+
+fn replace_color(s: &mut Session, p: &Value) -> Result<Value> {
+ let c = crate::commands::color_param(p, "color", s.tools.foreground);
+ let fuzz = num(p, "fuzziness", 40.0).clamp(0.0, 200.0);
+ let (h, sat, l) = (
+ num(p, "hue", 0.0).clamp(-180.0, 180.0),
+ num(p, "saturation", 0.0).clamp(-100.0, 100.0),
+ num(p, "lightness", 0.0).clamp(-100.0, 100.0),
+ );
+ rgba_edit(s, "Replace Color", p, |px, _| {
+ tone::replace_color(px, [c[0], c[1], c[2]], fuzz, h, sat, l);
+ })
+}
+
+/// Straight RGBA pixels and an optional coverage mask for a document's layer (or its composite).
+/// Pixels plus an optional coverage mask.
+type Sample = (Vec<[f32; 4]>, Option<Vec<f32>>);
+
+fn stats_pixels(doc: &Document, layer: Option<u64>, use_selection: bool) -> Result<Sample> {
+ let area = doc.bounds();
+ let px: Vec<[f32; 4]> = match layer {
+ Some(id) => {
+ let l = doc
+ .layer(photocraft_doc::LayerId(id))
+ .ok_or(EngineError::NoLayer(photocraft_doc::LayerId(id)))?;
+ photocraft_compose::render_layer(l, area).px
+ }
+ None => photocraft_compose::flatten(doc).px,
+ };
+ let mask = doc
+ .selection
+ .as_ref()
+ .filter(|_| use_selection)
+ .map(|sel| photocraft_algo::selection::mask_from_surface(Some(sel), area));
+ Ok((px, mask))
+}
+
+fn match_color(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.adjustments.matchColor";
+ let o = MatchColor {
+ luminance: num(p, "luminance", 100.0).clamp(1.0, 200.0),
+ intensity: num(p, "intensity", 100.0).clamp(1.0, 200.0),
+ fade: num(p, "fade", 0.0).clamp(0.0, 100.0),
+ neutralize: p
+ .get("neutralize")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ };
+ let source = match p.get("source").and_then(Value::as_i64) {
+ Some(i) if i >= 0 => {
+ let d = s
+ .documents()
+ .get(i as usize)
+ .ok_or_else(|| bad(CMD, format!("no document {i}")))?;
+ let layer = p.get("sourceLayer").and_then(Value::as_u64);
+ let (px, mask) = stats_pixels(
+ &d.doc,
+ layer,
+ p.get("useSelectionInSource")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ )?;
+ Some(
+ tone::lab_stats(&px, mask.as_deref())
+ .ok_or_else(|| bad(CMD, "the source has no opaque pixels"))?,
+ )
+ }
+ _ => None,
+ };
+ // Source "None" with default options matches the image to its own statistics: a no-op, as in
+ // Photoshop (Neutralize / Luminance / Color Intensity still act).
+ // Target statistics: the layer itself, restricted to the selection when asked.
+ let target_sel = p
+ .get("useSelectionInTarget")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ let sel = s.active().and_then(|d| d.doc.selection.clone());
+ rgba_edit(s, "Match Color", p, |px, r| {
+ let mask: Option<Vec<f32>> = sel
+ .as_ref()
+ .filter(|_| target_sel)
+ .map(|sel| photocraft_algo::selection::mask_from_surface(Some(sel), r));
+ let Some(target) = tone::lab_stats(px, mask.as_deref()) else {
+ return;
+ };
+ tone::match_color(px, &target, source.as_ref(), &o);
+ })
+}
+
+fn hdr_toning(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = HdrToning::default();
+ let curve: Vec<(f32, f32)> = p
+ .get("curve")
+ .and_then(Value::as_array)
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| {
+ Some((
+ v.get(0)?.as_f64()? as f32 / 255.0,
+ v.get(1)?.as_f64()? as f32 / 255.0,
+ ))
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ let h = HdrToning {
+ radius: num(p, "radius", d.radius).clamp(1.0, 500.0),
+ strength: num(p, "strength", d.strength).clamp(0.1, 4.0),
+ gamma: num(p, "gamma", d.gamma).clamp(0.1, 2.0),
+ exposure: num(p, "exposure", d.exposure).clamp(-5.0, 5.0),
+ detail: num(p, "detail", d.detail).clamp(-100.0, 300.0),
+ shadow: num(p, "shadow", d.shadow).clamp(-100.0, 100.0),
+ highlight: num(p, "highlight", d.highlight).clamp(-100.0, 100.0),
+ vibrance: num(p, "vibrance", d.vibrance).clamp(-100.0, 100.0),
+ saturation: num(p, "saturation", d.saturation).clamp(-100.0, 100.0),
+ curve,
+ };
+ // Like Photoshop, HDR Toning flattens the image first (one history step).
+ s.edit("HDR Toning", |doc, active| {
+ let buf = photocraft_compose::flatten(doc).over_background([1.0, 1.0, 1.0]);
+ let (w, hgt) = (buf.rect.width() as usize, buf.rect.height() as usize);
+ let mut px = buf.px;
+ tone::hdr_toning(&mut px, w, hgt, &h);
+ let fmt = doc.pixel_format();
+ let data: Vec<f32> = px
+ .iter()
+ .flat_map(|q| photocraft_raster::from_rgba(&fmt, *q))
+ .collect();
+ let mut bg = Layer::raster("Background", fmt);
+ bg.locks.transparency = true;
+ bg.surface_mut()
+ .expect("raster")
+ .write_region(doc.bounds(), &data);
+ *active = Some(bg.id);
+ doc.layers = vec![bg];
+ doc.selection = None;
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+/// The Color Lookup built-ins (id, label) for UIs and agents.
+fn list_looks(_: &mut Session, _: &Value) -> Result<Value> {
+ Ok(json!(
+ photocraft_cms::lutfile::BUILTIN
+ .iter()
+ .map(|(id, label)| json!({"id": id, "label": label}))
+ .collect::<Vec<_>>()
+ ))
+}
+
+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 }
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!(
+ "image.adjustments.shadowsHighlights",
+ "Shadows/Highlights…",
+ ["Image", "Adjustments"],
+ r##"{"shadowAmount":0..100=35,"shadowTone":0..100=50,"shadowRadius":0..2500=30,"highlightAmount":0..100=0,"highlightTone":0..100=50,"highlightRadius":0..2500=30,"color":-100..100=20,"midtone":-100..100=0,"blackClip":0..50=0.01,"whiteClip":0..50=0.01}"##,
+ has_pixels,
+ shadows_highlights
+ ),
+ spec!(
+ "image.adjustments.replaceColor",
+ "Replace Color…",
+ ["Image", "Adjustments"],
+ r##"{"color":json,"fuzziness":0..200=40,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0} (color: "#rrggbb", default the foreground colour)"##,
+ has_pixels,
+ replace_color
+ ),
+ spec!(
+ "image.adjustments.matchColor",
+ "Match Color…",
+ ["Image", "Adjustments"],
+ r##"{"source":doc,"sourceLayer":json,"luminance":1..200=100,"intensity":1..200=100,"fade":0..100=0,"neutralize":bool=false,"useSelectionInSource":bool=false,"useSelectionInTarget":bool=false} (source: document index; sourceLayer: layer id, default the merged image)"##,
+ has_pixels,
+ match_color
+ ),
+ spec!(
+ "image.adjustments.hdrToning",
+ "HDR Toning…",
+ ["Image", "Adjustments"],
+ r##"{"radius":1..500=30,"strength":0.1..4=0.5,"gamma":0.1..2=1,"exposure":-5..5=0,"detail":-100..300=30,"shadow":-100..100=0,"highlight":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=20,"curve":[[in,out],…] 0..255} (flattens the image)"##,
+ has_doc,
+ hdr_toning
+ ),
+ CommandSpec {
+ id: "image.adjustments.colorLookup.list",
+ label: "List Color Lookup Looks",
+ menu: &[],
+ shortcut: None,
+ params: "{}",
+ enabled: |_| Ok(()),
+ run: list_looks,
+ journal: false,
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs
new file mode 100644
index 000000000..2a431db7b
--- /dev/null
+++ b/crates/engine/src/adjust_cmds/tests.rs
@@ -0,0 +1,362 @@
+use super::*;
+
+const DEPTHS: [u64; 3] = [8, 16, 32];
+const MODES: [&str; 4] = ["rgb", "gray", "cmyk", "lab"];
+
+fn session(depth: u64, mode: &str) -> Session {
+ let mut s = Session::new();
+ s.execute(
+ "file.new",
+ json!({"width": 48, "height": 32, "depth": depth, "mode": mode}),
+ )
+ .unwrap();
+ paint(&mut s, |x, y| {
+ [
+ 0.1 + x as f32 / 60.0,
+ 0.2 + y as f32 / 50.0,
+ 0.6 - x as f32 / 120.0,
+ 1.0,
+ ]
+ });
+ s
+}
+
+fn paint(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 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 changed(a: [f32; 4], b: [f32; 4]) -> f32 {
+ (0..3).map(|c| (a[c] - b[c]).abs()).fold(0.0, f32::max)
+}
+
+fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+}
+
+#[test]
+fn destructive_adjustments_all_depths_and_modes_one_undo_step() {
+ let cases: [(&str, Value); 4] = [
+ (
+ "image.adjustments.shadowsHighlights",
+ json!({"shadowAmount": 80, "blackClip": 0, "whiteClip": 0}),
+ ),
+ (
+ "image.adjustments.replaceColor",
+ json!({"color": "#4d66cc", "fuzziness": 200, "hue": 90, "saturation": 30}),
+ ),
+ (
+ "image.adjustments.matchColor",
+ json!({"neutralize": true, "intensity": 50}),
+ ),
+ (
+ "image.adjustments.hdrToning",
+ json!({"strength": 2, "exposure": 0.5}),
+ ),
+ ];
+ for (id, params) in &cases {
+ for depth in DEPTHS {
+ for mode in MODES {
+ let mut s = session(depth, mode);
+ let before = rgba(&s, 3, 3);
+ let steps = s.active().unwrap().history.past_len();
+ s.execute(id, params.clone())
+ .unwrap_or_else(|e| panic!("{id} {depth} {mode}: {e}"));
+ let after = rgba(&s, 3, 3);
+ // Gray documents can't show hue changes from Replace Color at a gray pixel.
+ if !(mode == "gray" && (id.ends_with("replaceColor") || id.ends_with("matchColor")))
+ {
+ assert!(
+ changed(before, after) > 1e-3,
+ "{id} {depth} {mode}: {before:?} → {after:?}"
+ );
+ }
+ assert_eq!(
+ s.active().unwrap().history.past_len(),
+ steps + 1,
+ "{id}: one history step"
+ );
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(changed(before, rgba(&s, 3, 3)) < 1e-6, "{id} undo");
+ }
+ }
+ }
+}
+
+#[test]
+fn destructive_adjustments_respect_selection() {
+ let mut s = session(8, "rgb");
+ s.execute("select.all", json!({})).ok();
+ s.edit("sel", |doc, _| {
+ let mut sel = Surface::new(photocraft_color::PixelFormat::GRAY8);
+ sel.write_region(Rect::new(0, 0, 10, 32), &vec![1.0; 320]);
+ doc.selection = Some(sel);
+ Ok(())
+ })
+ .unwrap();
+ let outside = rgba(&s, 30, 5);
+ let inside = rgba(&s, 5, 5);
+ s.execute(
+ "image.adjustments.shadowsHighlights",
+ json!({"shadowAmount": 100, "blackClip": 0, "whiteClip": 0}),
+ )
+ .unwrap();
+ assert!(changed(inside, rgba(&s, 5, 5)) > 1e-3);
+ assert_eq!(outside, rgba(&s, 30, 5));
+}
+
+#[test]
+fn match_color_from_another_document() {
+ let mut s = session(8, "rgb");
+ s.execute(
+ "file.new",
+ json!({"width": 16, "height": 16, "background": "#e05010"}),
+ )
+ .unwrap();
+ // The target is document 0.
+ s.execute("document.activate", json!({"document": 0}))
+ .unwrap();
+ let before = rgba(&s, 10, 10);
+ s.execute("image.adjustments.matchColor", json!({"source": 1}))
+ .unwrap();
+ let after = rgba(&s, 10, 10);
+ assert!(
+ after[0] > before[0] && after[2] < before[2],
+ "{before:?} → {after:?}"
+ );
+ // Fade 100 is a no-op; a bad source index is an error.
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute(
+ "image.adjustments.matchColor",
+ json!({"source": 1, "fade": 100}),
+ )
+ .unwrap();
+ assert!(changed(before, rgba(&s, 10, 10)) < 2.0 / 255.0);
+ assert!(
+ s.execute("image.adjustments.matchColor", json!({"source": 7}))
+ .is_err()
+ );
+ // Source "None" with default options is a no-op.
+ let now = rgba(&s, 10, 10);
+ s.execute("image.adjustments.matchColor", json!({}))
+ .unwrap();
+ assert!(changed(now, rgba(&s, 10, 10)) < 2.0 / 255.0);
+}
+
+#[test]
+fn hdr_toning_flattens() {
+ let mut s = session(16, "rgb");
+ s.execute("layer.new.layer", json!({})).unwrap();
+ assert_eq!(doc(&s).layers.len(), 2);
+ s.execute("image.adjustments.hdrToning", json!({})).unwrap();
+ assert_eq!(doc(&s).layers.len(), 1);
+ assert_eq!(doc(&s).layers[0].name, "Background");
+}
+
+#[test]
+fn disabled_without_pixels() {
+ let mut s = session(8, "rgb");
+ s.execute("layer.newAdjustmentLayer.invert", json!({}))
+ .unwrap();
+ for id in [
+ "image.adjustments.shadowsHighlights",
+ "image.adjustments.replaceColor",
+ "image.adjustments.matchColor",
+ ] {
+ assert!(!s.is_enabled(id), "{id}");
+ }
+ assert!(s.is_enabled("image.adjustments.hdrToning"));
+ assert!(!Session::new().is_enabled("image.adjustments.hdrToning"));
+}
+
+#[test]
+fn selective_color_layer_and_destructive() {
+ for depth in DEPTHS {
+ for mode in ["rgb", "cmyk", "lab"] {
+ let mut s = session(depth, mode);
+ paint(&mut s, |_, _| [0.9, 0.1, 0.1, 1.0]);
+ let before = rgba(&s, 1, 1);
+ // Reds: −100 % cyan (absolute) makes red redder; +100 % black darkens.
+ s.execute(
+ "image.adjustments.selectiveColor",
+ json!({"method": "absolute", "reds": [0, 0, 0, 60]}),
+ )
+ .unwrap();
+ let after = rgba(&s, 1, 1);
+ assert!(
+ after[0] < before[0] - 0.05,
+ "{depth} {mode}: {before:?} → {after:?}"
+ );
+ }
+ }
+ let mut s = session(8, "rgb");
+ let r = s
+ .execute(
+ "layer.newAdjustmentLayer.selectiveColor",
+ json!({"colors": "blues", "yellow": 40}),
+ )
+ .unwrap();
+ let id = photocraft_doc::LayerId(r["layer"].as_u64().unwrap());
+ let get = |s: &Session| match &doc(s).layer(id).unwrap().content {
+ LayerContent::Adjustment(Adjustment::SelectiveColor {
+ relative,
+ adjustments,
+ }) => (*relative, *adjustments),
+ other => panic!("{other:?}"),
+ };
+ assert_eq!(get(&s).1[4], [0.0, 0.0, 40.0, 0.0]);
+ // Properties edits merge one range at a time.
+ s.execute(
+ "layer.setAdjustment",
+ json!({"layer": id.0, "colors": "neutrals", "black": -20, "method": "absolute"}),
+ )
+ .unwrap();
+ let (rel, a) = get(&s);
+ assert!(!rel);
+ assert_eq!(a[4][2], 40.0);
+ assert_eq!(a[7][3], -20.0);
+ // No parameters: reset.
+ s.execute("layer.setAdjustment", json!({"layer": id.0}))
+ .unwrap();
+ assert_eq!(get(&s), (true, [[0.0; 4]; 9]));
+}
+
+#[test]
+fn color_lookup_builtin_data_and_errors() {
+ let mut s = session(8, "rgb");
+ let r = s
+ .execute(
+ "layer.newAdjustmentLayer.colorLookup",
+ json!({"lut": "dayForNight"}),
+ )
+ .unwrap();
+ let id = photocraft_doc::LayerId(r["layer"].as_u64().unwrap());
+ let px = photocraft_compose::render(doc(&s), Rect::from_xywh(40, 30, 1, 1)).px[0];
+ assert!(px[2] > px[0], "night is blue: {px:?}");
+ // Switching interpolation keeps the table.
+ s.execute(
+ "layer.setAdjustment",
+ json!({"layer": id.0, "interpolation": "tetrahedral", "dither": true}),
+ )
+ .unwrap();
+ match &doc(&s).layer(id).unwrap().content {
+ LayerContent::Adjustment(Adjustment::ColorLookup {
+ lut: Some(_),
+ size: 33,
+ tetrahedral: true,
+ dither: true,
+ name,
+ }) => assert_eq!(name, "Day for Night"),
+ other => panic!("{other:?}"),
+ }
+ // Embedded .cube text (an inverting LUT) applied destructively, at every depth.
+ let mut cube = String::from("LUT_3D_SIZE 2\n");
+ for b in 0..2 {
+ for g in 0..2 {
+ for r in 0..2 {
+ cube.push_str(&format!("{} {} {}\n", 1 - r, 1 - g, 1 - b));
+ }
+ }
+ }
+ for depth in DEPTHS {
+ let mut s = session(depth, "rgb");
+ let before = rgba(&s, 5, 5);
+ s.execute(
+ "image.adjustments.colorLookup",
+ json!({"data": cube, "fileName": "invert.cube"}),
+ )
+ .unwrap();
+ let after = rgba(&s, 5, 5);
+ for c in 0..3 {
+ assert!(
+ (after[c] - (1.0 - before[c])).abs() < 2.0 / 255.0,
+ "{depth}: {before:?} {after:?}"
+ );
+ }
+ }
+ assert!(
+ s.execute("image.adjustments.colorLookup", json!({"lut": "nope"}))
+ .is_err()
+ );
+ assert!(
+ s.execute(
+ "image.adjustments.colorLookup",
+ json!({"data": "LUT_3D_SIZE 3\n0 0 0\n"})
+ )
+ .is_err()
+ );
+ assert!(
+ s.execute(
+ "layer.newAdjustmentLayer.colorLookup",
+ json!({"file": "/nonexistent/x.cube"})
+ )
+ .is_err()
+ );
+ let looks = s
+ .execute("image.adjustments.colorLookup.list", json!({}))
+ .unwrap();
+ assert_eq!(
+ looks.as_array().unwrap().len(),
+ photocraft_cms::lutfile::BUILTIN.len()
+ );
+}
+
+#[test]
+fn new_kinds_round_trip_through_psd_and_pcraft() {
+ let mut s = session(8, "rgb");
+ s.execute(
+ "layer.newAdjustmentLayer.selectiveColor",
+ json!({"reds": [10, -20, 30, -40], "method": "absolute"}),
+ )
+ .unwrap();
+ s.execute(
+ "layer.newAdjustmentLayer.colorLookup",
+ json!({"lut": "warm", "dither": true}),
+ )
+ .unwrap();
+ let d = doc(&s).clone();
+ let bytes = photocraft_io::export(&d, "x.psd", &Default::default())
+ .unwrap()
+ .bytes;
+ let back = photocraft_io::import("x.psd", &bytes).unwrap().document;
+ let kinds: Vec<&str> = back
+ .layers
+ .iter()
+ .filter_map(|l| match &l.content {
+ LayerContent::Adjustment(a) => Some(crate::commands::adjustment_kind(a)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(kinds, ["selectiveColor", "colorLookup"]);
+ let pc = photocraft_format::save_to_bytes(&d, &Default::default()).unwrap();
+ let again = photocraft_format::load_from_bytes(&pc).unwrap();
+ for (a, b) in d.layers.iter().zip(&again.layers) {
+ assert_eq!(a.content, b.content);
+ }
+}
diff --git a/crates/engine/src/align_cmds.rs b/crates/engine/src/align_cmds.rs
new file mode 100644
index 000000000..fb6059a95
--- /dev/null
+++ b/crates/engine/src/align_cmds.rs
@@ -0,0 +1,386 @@
+//! Edit › Auto-Align Layers and Auto-Blend Layers, on the selected pixel layers.
+//!
+//! Auto-Align registers every selected layer onto a reference layer with Harris corners,
+//! steered-BRIEF descriptors and RANSAC ([`photocraft_algo::features`]) and warps it with the
+//! Free Transform resampler. Projections: Reposition (translation), Collage (rotation, uniform
+//! scale, translation), Perspective (homography) and Auto (perspective when it is well
+//! supported, otherwise collage). Cylindrical and spherical projections are not implemented.
+//!
+//! Auto-Blend gives each selected layer a mask so the composite shows, per pixel, the sharpest
+//! layer (Stack Images, for focus stacking) or the layer whose content the pixel lies deepest in
+//! (Panorama). With Seamless Tones and Colors it also adds a merged layer blended with Laplacian
+//! pyramids ([`photocraft_algo::pyramid`]) so transitions are invisible.
+
+use photocraft_algo::features::{Model, register};
+use photocraft_algo::pyramid;
+use photocraft_algo::transform::{Homography, Interp, warp_surface};
+use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerMask};
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, to_rgba};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+/// Longest side images are registered at (larger layers are downsampled for detection).
+const REGISTER_SIDE: usize = 1024;
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+/// The selected raster layers, bottom to top.
+fn selected_pixel_layers(s: &Session) -> Vec<LayerId> {
+ let Some(st) = s.active() else { return Vec::new() };
+ st.selected_layers().into_iter().filter(|id| st.doc.layer(*id).is_some_and(|l| matches!(l.content, LayerContent::Raster(_)))).collect()
+}
+
+fn two_layers(s: &Session) -> std::result::Result<(), String> {
+ s.active().ok_or("no document open")?;
+ if selected_pixel_layers(s).len() < 2 { Err("select two or more pixel layers in the Layers panel".into()) } else { Ok(()) }
+}
+
+/// Luminance and opacity of a surface over `area`, downsampled by the integer factor `k`.
+fn luma_alpha(surf: &Surface, area: Rect, k: usize) -> (usize, usize, Vec<f32>, Vec<f32>) {
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let raw = surf.read_region(area);
+ let (w, h) = (area.width() as usize, area.height() as usize);
+ let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
+ let (mut l, mut a, mut cnt) = (vec![0.0f32; sw * sh], vec![0.0f32; sw * sh], vec![0.0f32; sw * sh]);
+ for y in 0..h {
+ for x in 0..w {
+ let p = to_rgba(&fmt, &raw[(y * w + x) * n..(y * w + x + 1) * n]);
+ let i = (y / k) * sw + x / k;
+ l[i] += 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2];
+ a[i] += p[3];
+ cnt[i] += 1.0;
+ }
+ }
+ for i in 0..sw * sh {
+ l[i] /= cnt[i].max(1.0);
+ a[i] /= cnt[i].max(1.0);
+ }
+ (sw, sh, l, a)
+}
+
+fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.autoAlignLayers";
+ let ids = selected_pixel_layers(s);
+ if ids.len() < 2 {
+ return Err(bad(cmd, "select two or more pixel layers"));
+ }
+ let projection = p.get("projection").and_then(Value::as_str).unwrap_or("auto");
+ let models: Vec<Model> = match projection {
+ "auto" => vec![Model::Homography, Model::Similarity, Model::Translation],
+ "perspective" => vec![Model::Homography],
+ "collage" => vec![Model::Similarity],
+ "reposition" => vec![Model::Translation],
+ "cylindrical" | "spherical" => return Err(bad(cmd, format!("the {projection} projection is not supported (auto|perspective|collage|reposition)"))),
+ other => return Err(bad(cmd, format!("unknown projection `{other}` (auto|perspective|collage|reposition)"))),
+ };
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = st.doc.clone();
+ let reference = match p.get("reference").and_then(Value::as_u64) {
+ Some(r) if ids.contains(&LayerId(r)) => LayerId(r),
+ Some(r) => return Err(bad(cmd, format!("reference {r} is not a selected pixel layer"))),
+ None => ids[0],
+ };
+ let area = doc.bounds();
+ let k = (area.width().max(area.height()) as usize).div_ceil(REGISTER_SIDE).max(1);
+ let prep = |id: LayerId| -> Option<(usize, usize, Vec<f32>, Vec<bool>)> {
+ let surf = doc.layer(id)?.surface()?;
+ let (w, h, l, a) = luma_alpha(surf, area, k);
+ Some((w, h, l, a.iter().map(|v| *v > 0.5).collect()))
+ };
+ let (w, h, ref_l, ref_ok) = prep(reference).ok_or(EngineError::NoLayer(reference))?;
+ let scale = k as f64;
+ let mut moves: Vec<(LayerId, Homography, &'static str, usize)> = Vec::new();
+ let mut failed: Vec<u64> = Vec::new();
+ for &id in ids.iter().filter(|id| **id != reference) {
+ let Some((_, _, l, ok)) = prep(id) else { continue };
+ let mut found = None;
+ for &m in &models {
+ if let Some((hm, n)) = register(w, h, &ref_l, &l, Some(&ref_ok), Some(&ok), m) {
+ // Auto: a perspective fit must be well supported and not wildly projective.
+ let wild = m == Model::Homography && (hm.0[6].abs() + hm.0[7].abs()) * (w.max(h) as f64) > 0.5;
+ if projection == "auto" && m == Model::Homography && (n < 20 || wild) {
+ continue;
+ }
+ found = Some((hm, m, n));
+ break;
+ }
+ }
+ match found {
+ Some((hm, m, n)) => {
+ // Registration ran on a k× downsampled grid: conjugate by the scale.
+ let up = Homography([scale, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, 1.0]);
+ let down = Homography([1.0 / scale, 0.0, 0.0, 0.0, 1.0 / scale, 0.0, 0.0, 0.0, 1.0]);
+ let full = up.mul(&hm).mul(&down);
+ let name = match m {
+ Model::Translation => "reposition",
+ Model::Similarity => "collage",
+ Model::Homography => "perspective",
+ };
+ moves.push((id, full, name, n));
+ }
+ None => failed.push(id.0),
+ }
+ }
+ if moves.is_empty() {
+ return Err(EngineError::Other("Auto-Align couldn't find enough matching detail between the layers".into()));
+ }
+ let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic"));
+ s.edit("Auto-Align Layers", |doc, _| {
+ for (id, hm, _, _) in &moves {
+ let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
+ let surf = l.surface_mut().ok_or(EngineError::NoLayer(*id))?;
+ let b = surf.content_bounds();
+ if b.is_empty() {
+ continue;
+ }
+ *surf = warp_surface(surf, b, hm, interp);
+ if let Some(m) = &mut l.mask {
+ let mb = m.surface.content_bounds();
+ if !mb.is_empty() {
+ m.surface = warp_surface(&m.surface, mb, hm, Interp::Bilinear);
+ }
+ }
+ }
+ Ok(())
+ })?;
+ let aligned: Vec<Value> = moves.iter().map(|(id, hm, model, n)| json!({"layer": id.0, "model": model, "matches": n, "matrix": hm.0})).collect();
+ Ok(json!({"reference": reference.0, "aligned": aligned, "failed": failed}))
+}
+
+/// Native-channel pixels of a layer over `area` (transparent outside its content).
+fn pixels(l: &Layer, area: Rect) -> Option<(Vec<f32>, photocraft_color::PixelFormat)> {
+ let s = l.surface()?;
+ Some((s.read_region(area), s.format()))
+}
+
+fn auto_blend(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.autoBlendLayers";
+ let ids = selected_pixel_layers(s);
+ if ids.len() < 2 {
+ return Err(bad(cmd, "select two or more pixel layers"));
+ }
+ let method = p.get("method").and_then(Value::as_str).unwrap_or("panorama");
+ if !matches!(method, "panorama" | "stack") {
+ return Err(bad(cmd, "`method` must be panorama|stack"));
+ }
+ let seamless = p.get("seamlessTones").and_then(Value::as_bool).unwrap_or(true);
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let doc: std::sync::Arc<Document> = st.doc.clone();
+ let mut area = Rect::EMPTY;
+ for id in &ids {
+ if let Some(b) = doc.layer(*id).and_then(|l| l.surface()).map(|s| s.content_bounds()) {
+ area = area.union(&b);
+ }
+ }
+ let area = area.intersect(&doc.bounds());
+ if area.is_empty() {
+ return Err(EngineError::Other("the selected layers are empty".into()));
+ }
+ let (w, h) = (area.width() as usize, area.height() as usize);
+ let mut imgs: Vec<Vec<f32>> = Vec::new();
+ let mut luma: Vec<Vec<f32>> = Vec::new();
+ let mut alpha: Vec<Vec<f32>> = Vec::new();
+ let mut fmt = None;
+ for id in &ids {
+ let l = doc.layer(*id).ok_or(EngineError::NoLayer(*id))?;
+ let (px, f) = pixels(l, area).ok_or(EngineError::NoLayer(*id))?;
+ let n = f.channels();
+ let (mut lv, mut av) = (vec![0.0f32; w * h], vec![0.0f32; w * h]);
+ for i in 0..w * h {
+ let c = to_rgba(&f, &px[i * n..(i + 1) * n]);
+ lv[i] = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
+ av[i] = c[3];
+ }
+ if fmt.is_some_and(|g: photocraft_color::PixelFormat| g != f) {
+ return Err(EngineError::Other("the layers have different pixel formats".into()));
+ }
+ fmt = Some(f);
+ imgs.push(px);
+ luma.push(lv);
+ alpha.push(av);
+ }
+ let fmt = fmt.ok_or(EngineError::NoDocument)?;
+ let weights = if method == "stack" { pyramid::stack_weights(w, h, &luma, &alpha) } else { pyramid::panorama_weights(w, h, &alpha) };
+ let blended = seamless.then(|| {
+ let refs: Vec<&[f32]> = imgs.iter().map(Vec::as_slice).collect();
+ pyramid::blend(w, h, fmt.channels(), &refs, &weights, pyramid::auto_levels(w, h))
+ });
+ let top = *ids.last().expect("two or more");
+ let label = "Auto-Blend Layers";
+ let new_layer = s.edit(label, |doc, active| {
+ for (id, wt) in ids.iter().zip(&weights) {
+ let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
+ let mut mask = LayerMask::hide_all();
+ mask.surface.write_region(area, wt);
+ mask.surface.prune();
+ l.mask = Some(mask);
+ }
+ let Some(px) = &blended else { return Ok(None) };
+ let mut l = Layer::raster(doc.next_layer_name("Blended"), fmt);
+ if let Some(surf) = l.surface_mut() {
+ surf.write_region(area, px);
+ surf.prune();
+ }
+ let nid = doc.insert_above(Some(top), l);
+ *active = Some(nid);
+ Ok(Some(nid))
+ })?;
+ Ok(json!({"method": method, "layers": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "blended": new_layer.map(|l| l.0)}))
+}
+
+macro_rules! spec {
+ ($id:literal, $label:literal, $params:literal, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: &["Edit"], shortcut: None, params: $params, enabled: two_layers, run: $run, journal: true }
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!("edit.autoAlignLayers", "Auto-Align Layers…", r##"{"projection":"auto|perspective|collage|reposition","reference":layer id?=bottom selected layer,"interpolation":"bicubic|bilinear|nearest"}"##, auto_align),
+ spec!("edit.autoBlendLayers", "Auto-Blend Layers…", r##"{"method":"panorama|stack","seamlessTones":bool=true}"##, auto_blend),
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Deterministic texture written into a layer at offset (dx, dy).
+ fn texture_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId {
+ s.execute("layer.new.layer", json!({"name": name})).unwrap();
+ s.edit("tex", |doc, active| {
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ let mut seed = 99u64;
+ let mut rnd = || {
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ (seed >> 33) as f64 / (1u64 << 31) as f64
+ };
+ surf.fill_rect(Rect::new(dx, dy, dx + 240, dy + 180), &[0.4, 0.4, 0.4, 1.0]);
+ for _ in 0..120 {
+ let (x, y) = ((rnd() * 220.0) as i32, (rnd() * 160.0) as i32);
+ let (sw, sh) = (4 + (rnd() * 14.0) as i32, 4 + (rnd() * 10.0) as i32);
+ let v = rnd() as f32;
+ surf.fill_rect(Rect::new(dx + x, dy + y, dx + x + sw, dy + y + sh), &[v, 1.0 - v, v * 0.5, 1.0]);
+ }
+ Ok(())
+ })
+ .unwrap();
+ s.active().unwrap().active_layer.unwrap()
+ }
+
+ fn select(s: &mut Session, ids: &[LayerId]) {
+ s.execute("layer.select", json!({"layer": ids[0].0})).unwrap();
+ for id in &ids[1..] {
+ s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap();
+ }
+ }
+
+ #[test]
+ fn auto_align_repositions_at_all_depths() {
+ for depth in [8, 16, 32] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 300, "height": 240, "depth": depth, "background": "transparent"})).unwrap();
+ let a = texture_layer(&mut s, "A", 20, 20);
+ let b = texture_layer(&mut s, "B", 31, 13);
+ assert!(!s.is_enabled("edit.autoAlignLayers"), "one layer selected");
+ select(&mut s, &[a, b]);
+ assert!(s.is_enabled("edit.autoAlignLayers"));
+ let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap();
+ assert_eq!(r["reference"], a.0);
+ let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds();
+ assert!((bb.x0 - 20).abs() <= 1 && (bb.y0 - 20).abs() <= 1, "depth {depth}: {bb:?} {r}");
+ s.undo();
+ let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds();
+ assert_eq!((bb.x0, bb.y0), (31, 13));
+ }
+ }
+
+ #[test]
+ fn auto_align_auto_projection_and_errors() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap();
+ let a = texture_layer(&mut s, "A", 20, 20);
+ let b = texture_layer(&mut s, "B", 26, 25);
+ select(&mut s, &[a, b]);
+ let r = s.execute("edit.autoAlignLayers", json!({})).unwrap();
+ let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>();
+ assert!((m[2] + 6.0).abs() < 1.0 && (m[5] + 5.0).abs() < 1.0, "{r}");
+ assert!(s.execute("edit.autoAlignLayers", json!({"projection": "cylindrical"})).is_err());
+ assert!(s.execute("edit.autoAlignLayers", json!({"reference": 9999})).is_err());
+ }
+
+ #[test]
+ fn auto_blend_panorama_masks_and_seamless_layer() {
+ for depth in [8, 16, 32] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 200, "height": 60, "depth": depth, "background": "transparent"})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "left"})).unwrap();
+ s.edit("l", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 130, 60), &[0.2, 0.3, 0.8, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let left = s.active().unwrap().active_layer.unwrap();
+ s.execute("layer.new.layer", json!({"name": "right"})).unwrap();
+ s.edit("r", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(70, 0, 200, 60), &[0.9, 0.6, 0.2, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let right = s.active().unwrap().active_layer.unwrap();
+ select(&mut s, &[left, right]);
+ let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap();
+ let doc = &s.active().unwrap().doc;
+ let ml = doc.layer(left).unwrap().mask.as_ref().unwrap();
+ let mr = doc.layer(right).unwrap().mask.as_ref().unwrap();
+ assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0), "depth {depth}");
+ assert_eq!((ml.value(190, 30), mr.value(190, 30)), (0.0, 1.0));
+ let blended = LayerId(r["blended"].as_u64().unwrap());
+ let px = doc.layer(blended).unwrap().surface().unwrap().pixel(5, 30);
+ assert!((px[2] - 0.8).abs() < 0.02, "{px:?}");
+ s.undo();
+ assert!(s.active().unwrap().doc.layer(left).unwrap().mask.is_none());
+ }
+ }
+
+ #[test]
+ fn auto_blend_stack_without_seamless() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "sharp"})).unwrap();
+ s.edit("checker", |doc, active| {
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ for y in (0..64).step_by(2) {
+ for x in (0..64).step_by(2) {
+ let v = if (x / 2 + y / 2) % 2 == 0 { 0.1 } else { 0.9 };
+ surf.fill_rect(Rect::new(x, y, x + 2, y + 2), &[v, v, v, 1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ let a = s.active().unwrap().active_layer.unwrap();
+ s.execute("layer.new.layer", json!({"name": "flat"})).unwrap();
+ s.edit("flat", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 64), &[0.5, 0.5, 0.5, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let flat = s.active().unwrap().active_layer.unwrap();
+ select(&mut s, &[a, flat]);
+ let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": false})).unwrap();
+ assert!(r["blended"].is_null());
+ let doc = &s.active().unwrap().doc;
+ // The detailed layer is sharper everywhere.
+ let shown = (0..64).filter(|x| doc.layer(a).unwrap().mask.as_ref().unwrap().value(*x, 32) > 0.5).count();
+ assert_eq!(shown, 64);
+ assert_eq!(doc.layer(flat).unwrap().mask.as_ref().unwrap().value(10, 10), 0.0);
+ assert!(s.execute("edit.autoBlendLayers", json!({"method": "sideways"})).is_err());
+ }
+}
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs
new file mode 100644
index 000000000..7a30a3c4f
--- /dev/null
+++ b/crates/engine/src/brush_cmds.rs
@@ -0,0 +1,439 @@
+//! Brush engine commands: the Brush/Pencil/Mixer Brush/Color Replacement tools, brush presets and
+//! the session brush (`tools.setBrush`). The UI's options bar and Brush Settings panel call these.
+//!
+//! Brushes are [`BrushSettings`] serialised as camelCase JSON; any command taking a `"brush"`
+//! object deep-merges it onto the session brush, so partial objects work
+//! (`{"scattering": {"enabled": true}}`). Strokes are deterministic: the jitter seed is the `seed`
+//! param or a hash of the points, so a journaled command replays to identical pixels.
+
+use photocraft_doc::LayerContent;
+use photocraft_geom::Rect;
+use photocraft_paint::mixer::{MixerSettings, apply_mixer_stroke};
+use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement};
+use photocraft_paint::{BrushPreset, BrushSettings, GrayTile, Stroke, StrokePoint, TipShape, render_stroke};
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, has_paintable, is_mask_target, paint_surface};
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+fn num(p: &Value, k: &str) -> Option<f32> {
+ p.get(k).and_then(Value::as_f64).map(|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 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)) if h.len() == 6 || h.len() == 8 => [r, g, b, c(6).unwrap_or(1.0)],
+ _ => d,
+ }
+ }
+ _ => d,
+ }
+}
+fn always(_: &Session) -> std::result::Result<(), String> {
+ Ok(())
+}
+
+/// Parse `points`: arrays `[x, y, pressure?, tiltX?, tiltY?, rotation?, timeMs?, wheel?]` or
+/// objects `{"x":…, "y":…, "pressure":…, "tiltX":…, …, "time":…}`.
+pub fn parse_points(p: &Value, cmd: &str) -> Result<Vec<StrokePoint>> {
+ let arr = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing `points`"))?;
+ let pts: Vec<StrokePoint> = arr
+ .iter()
+ .filter_map(|v| match v {
+ Value::Array(a) => {
+ let g = |i: usize| a.get(i).and_then(Value::as_f64);
+ let mut sp = StrokePoint::new(g(0)?, g(1)?, g(2).unwrap_or(1.0) as f32);
+ sp.tilt_x = g(3).unwrap_or(0.0) as f32;
+ sp.tilt_y = g(4).unwrap_or(0.0) as f32;
+ sp.rotation = g(5).unwrap_or(0.0) as f32;
+ sp.time = g(6).unwrap_or(0.0);
+ sp.wheel = g(7).unwrap_or(1.0) as f32;
+ Some(sp)
+ }
+ Value::Object(_) => serde_json::from_value(v.clone()).ok(),
+ _ => None,
+ })
+ .collect();
+ if pts.is_empty() {
+ return Err(bad(cmd, "`points` is empty"));
+ }
+ Ok(pts)
+}
+
+/// Deep-merge `patch` into `base` (objects merge key by key; anything else replaces).
+fn merge(base: &mut Value, patch: &Value) {
+ match (base, patch) {
+ (Value::Object(b), Value::Object(p)) => {
+ for (k, v) in p {
+ match b.get_mut(k) {
+ Some(bv) if bv.is_object() && v.is_object() => merge(bv, v),
+ _ => {
+ b.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ }
+ (b, p) => *b = p.clone(),
+ }
+}
+
+/// Apply a JSON brush patch onto a brush.
+pub fn merge_brush(base: &BrushSettings, patch: &Value, cmd: &str) -> Result<BrushSettings> {
+ let mut v = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?;
+ merge(&mut v, patch);
+ serde_json::from_value(v).map_err(|e| bad(cmd, format!("invalid brush: {e}")))
+}
+
+fn find_preset<'a>(s: &'a Session, name: &str, cmd: &str) -> Result<&'a BrushPreset> {
+ photocraft_paint::presets::find(&s.tools.presets, name).ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`")))
+}
+
+/// Resolve the brush for a stroke command: session brush ← `preset` ← `brush` ← legacy scalar
+/// params; colours from the session; seed from `seed` or the points.
+pub fn resolve_brush(s: &Session, p: &Value, cmd: &str) -> Result<BrushSettings> {
+ let mut b = s.tools.brush.clone();
+ if let Some(name) = p.get("preset").and_then(Value::as_str) {
+ b = find_preset(s, name, cmd)?.brush.clone().with_protected_texture(&s.tools.brush);
+ }
+ if let Some(patch) = p.get("brush").filter(|v| v.is_object()) {
+ b = merge_brush(&b, patch, cmd)?;
+ }
+ if let Some(v) = num(p, "size") {
+ b.size = v.max(0.5);
+ }
+ if let Some(v) = num(p, "hardness") {
+ b.hardness = v.clamp(0.0, 1.0);
+ }
+ if let Some(v) = num(p, "opacity") {
+ b.opacity = v.clamp(0.0, 1.0);
+ }
+ if let Some(v) = num(p, "flow") {
+ b.flow = v.clamp(0.0, 1.0);
+ }
+ if let Some(v) = num(p, "spacing") {
+ b.spacing = v.clamp(0.01, 10.0);
+ }
+ if let Some(v) = num(p, "smoothing") {
+ b.smoothing.amount = v.clamp(0.0, 1.0);
+ }
+ b.color = color(p.get("color"), s.tools.foreground);
+ b.background = s.tools.background;
+ b.erase = flag(p, "erase", false);
+ b.seed = match p.get("seed").and_then(Value::as_u64) {
+ Some(v) => v,
+ None => photocraft_paint::rng::seed_from_bytes(p.get("points").map(|v| v.to_string()).unwrap_or_default().as_bytes()),
+ };
+ Ok(b)
+}
+
+fn layer_id(s: &Session, p: &Value) -> Result<photocraft_doc::LayerId> {
+ match p.get("layer").and_then(Value::as_u64) {
+ Some(id) => Ok(photocraft_doc::LayerId(id)),
+ None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())),
+ }
+}
+
+fn damage_json(s: &mut Session, dmg: Rect) -> Value {
+ if let Some(st) = s.active_mut() {
+ st.last_damage = Some(dmg);
+ }
+ json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] })
+}
+
+/// Stroke with a resolved brush onto the target layer (pixels or mask).
+fn stroke_with(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pts: Vec<StrokePoint>, auto_erase: bool) -> Result<Value> {
+ let gray = is_mask_target(p) || crate::channel_cmds::is_channel_target(p);
+ let id = if crate::channel_cmds::is_channel_target(p) { None } else { Some(layer_id(s, p)?) };
+ let zoom = num(p, "zoom").unwrap_or(1.0);
+ let bg = s.tools.background;
+ let fg = brush.color;
+ // On a mask or channel the eraser paints the background colour (Photoshop).
+ let brush = if gray && brush.erase { BrushSettings { erase: false, color: bg, ..brush } } else { brush };
+ let dmg = s.edit(label, |doc, _| {
+ let sel = doc.selection.clone();
+ let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
+ let mut brush = brush;
+ if auto_erase {
+ // Pencil Auto Erase: starting on foreground-coloured pixels paints the background colour.
+ let c = surf.rgba(pts[0].x.floor() as i32, pts[0].y.floor() as i32);
+ if c[3] > 0.0 && (0..3).all(|i| (c[i] - fg[i]).abs() < 1.5 / 255.0) {
+ brush.color = bg;
+ }
+ }
+ Ok(render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom))
+ })?;
+ Ok(damage_json(s, dmg))
+}
+
+/// `paint.stroke`: the Brush (and Eraser) tool.
+pub fn paint_stroke(s: &mut Session, p: &Value) -> Result<Value> {
+ let pts = parse_points(p, "paint.stroke")?;
+ let brush = resolve_brush(s, p, "paint.stroke")?;
+ let label = if brush.erase { "Eraser" } else { "Brush Tool" };
+ stroke_with(s, p, label, brush, pts, false)
+}
+
+fn pencil(s: &mut Session, p: &Value) -> Result<Value> {
+ let pts = parse_points(p, "paint.pencil")?;
+ let mut brush = resolve_brush(s, p, "paint.pencil")?;
+ brush.aliased = true;
+ if num(p, "hardness").is_none() {
+ brush.hardness = 1.0;
+ }
+ let label = if brush.erase { "Eraser" } else { "Pencil" };
+ stroke_with(s, p, label, brush, pts, flag(p, "autoErase", false))
+}
+
+fn pct(p: &Value, k: &str, d: f32) -> f32 {
+ num(p, k).unwrap_or(d).clamp(0.0, 100.0) / 100.0
+}
+
+fn mixer_brush(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "paint.mixerBrush";
+ let pts = parse_points(p, cmd)?;
+ let brush = resolve_brush(s, p, cmd)?;
+ let m = MixerSettings { wet: pct(p, "wet", 50.0), load: pct(p, "load", 50.0), mix: pct(p, "mix", 50.0), flow: pct(p, "flow", 100.0) };
+ let sample_all = flag(p, "sampleAllLayers", false);
+ let (clean, load_after) = (flag(p, "cleanAfterStroke", true), flag(p, "loadAfterStroke", true));
+ let mut state = s.tools.mixer.clone();
+ if load_after || state.reservoir.is_none() {
+ state.load(color(p.get("color"), s.tools.foreground));
+ }
+ let id = if crate::channel_cmds::is_channel_target(p) { None } else { Some(layer_id(s, p)?) };
+ let stroke = Stroke { brush, points: pts };
+ let dmg = s.edit("Mixer Brush", |doc, _| {
+ let sel = doc.selection.clone();
+ let sample = if sample_all {
+ let ds = photocraft_paint::dabs(&stroke);
+ let ctx = photocraft_paint::BrushContext::new(&stroke.brush);
+ let area = ds.iter().fold(Rect::EMPTY, |r, d| r.union(&ctx.dab_rect(d, false)));
+ let buf = photocraft_compose::render(doc, area);
+ let mut surf = Surface::new(photocraft_color::PixelFormat::RGBA32F);
+ let flat: Vec<f32> = buf.px.iter().flatten().copied().collect();
+ if !area.is_empty() {
+ surf.write_region(area, &flat);
+ }
+ Some(surf)
+ } else {
+ None
+ };
+ let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
+ Ok(apply_mixer_stroke(surf, sample.as_ref(), &stroke, &m, &mut state, sel.as_ref(), lock))
+ })?;
+ if clean {
+ state.clean();
+ }
+ s.tools.mixer = state;
+ Ok(damage_json(s, dmg))
+}
+
+fn color_replacement(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "paint.colorReplacement";
+ let pts = parse_points(p, cmd)?;
+ let brush = resolve_brush(s, p, cmd)?;
+ fn parse<T: serde::de::DeserializeOwned>(p: &Value, cmd: &str, k: &str) -> Result<Option<T>> {
+ p.get(k).cloned().map(serde_json::from_value).transpose().map_err(|e| bad(cmd, format!("`{k}`: {e}")))
+ }
+ let rs = ReplaceSettings {
+ mode: parse(p, cmd, "mode")?.unwrap_or(ReplaceMode::Color),
+ sampling: parse(p, cmd, "sampling")?.unwrap_or(Sampling::Continuous),
+ limits: parse(p, cmd, "limits")?.unwrap_or(Limits::Contiguous),
+ tolerance: pct(p, "tolerance", 30.0),
+ anti_alias: flag(p, "antiAlias", true),
+ color: brush.color,
+ background: s.tools.background,
+ };
+ let id = layer_id(s, p)?;
+ let stroke = Stroke { brush, points: pts };
+ let dmg = s.edit("Color Replacement", |doc, _| {
+ let sel = doc.selection.clone();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let lock = l.locks.transparency;
+ let surf = paint_surface(l, &json!({}))?;
+ Ok(apply_color_replacement(surf, &stroke, &rs, sel.as_ref(), lock))
+ })?;
+ Ok(damage_json(s, dmg))
+}
+
+fn brush_json(b: &BrushSettings) -> Value {
+ serde_json::to_value(b).unwrap_or(Value::Null)
+}
+
+fn presets_list(s: &mut Session, p: &Value) -> Result<Value> {
+ let full = flag(p, "full", false);
+ Ok(json!({
+ "presets": s.tools.presets.iter().map(|pr| {
+ let mut v = json!({
+ "name": pr.name,
+ "builtin": pr.builtin,
+ "size": pr.brush.size,
+ "hardness": pr.brush.hardness,
+ "tip": match &pr.brush.tip { TipShape::Round => "round", TipShape::Sampled(_) => "sampled" },
+ });
+ if full {
+ v["brush"] = brush_json(&pr.brush);
+ }
+ v
+ }).collect::<Vec<_>>()
+ }))
+}
+
+fn name_param(p: &Value, cmd: &str) -> Result<String> {
+ p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).ok_or_else(|| bad(cmd, "missing `name`"))
+}
+
+fn upsert(s: &mut Session, preset: BrushPreset) {
+ match s.tools.presets.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&preset.name)) {
+ Some(x) => *x = preset,
+ None => s.tools.presets.push(preset),
+ }
+}
+
+fn presets_save(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "brush.presets.save";
+ let name = name_param(p, cmd)?;
+ let brush = match p.get("brush").filter(|v| v.is_object()) {
+ Some(patch) => merge_brush(&s.tools.brush, patch, cmd)?,
+ None => s.tools.brush.clone(),
+ };
+ upsert(s, BrushPreset { name: name.clone(), brush, builtin: false });
+ Ok(json!({ "name": name, "count": s.tools.presets.len() }))
+}
+
+fn presets_delete(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "brush.presets.delete";
+ let name = name_param(p, cmd)?;
+ let before = s.tools.presets.len();
+ s.tools.presets.retain(|x| !x.name.eq_ignore_ascii_case(&name));
+ if s.tools.presets.len() == before {
+ return Err(bad(cmd, format!("no brush preset named `{name}`")));
+ }
+ Ok(json!({ "count": s.tools.presets.len() }))
+}
+
+fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document")?;
+ if d.doc.selection.is_none() {
+ return Err("no selection".into());
+ }
+ 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("active layer is not a pixel layer".into()) }
+}
+
+/// Largest sampled tip side (like Photoshop's 5000 px limit, kept smaller for preset size).
+pub const MAX_TIP: u32 = 2500;
+
+fn define_from_selection(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "brush.defineFromSelection";
+ let name = name_param(p, cmd)?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let sel = d.doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?;
+ let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?;
+ let surf = d.doc.layer(id).and_then(|l| l.surface()).ok_or_else(|| bad(cmd, "not a pixel layer"))?;
+ let area = sel.content_bounds().intersect(&d.doc.bounds());
+ if area.is_empty() {
+ return Err(bad(cmd, "the selection is empty"));
+ }
+ // Paint amount = darkness × alpha × selection (black = full paint, like Photoshop).
+ let (w, h) = (area.width() as usize, area.height() as usize);
+ let mut v = vec![0.0f32; w * h];
+ let sc = sel.channels();
+ let sv = sel.read_region(area);
+ for y in 0..h {
+ for x in 0..w {
+ let c = surf.rgba(area.x0 + x as i32, area.y0 + y as i32);
+ let l = photocraft_color::blend::lum([c[0], c[1], c[2]]);
+ v[y * w + x] = ((1.0 - l) * c[3] * sv[(y * w + x) * sc]).clamp(0.0, 1.0);
+ }
+ }
+ // Crop to the painted extent.
+ let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
+ for y in 0..h {
+ for x in 0..w {
+ if v[y * w + x] > 1e-4 {
+ x0 = x0.min(x);
+ y0 = y0.min(y);
+ x1 = x1.max(x + 1);
+ y1 = y1.max(y + 1);
+ }
+ }
+ }
+ if x1 <= x0 || y1 <= y0 {
+ return Err(bad(cmd, "the selected pixels contain no paint (all white or transparent)"));
+ }
+ let (tw, th) = ((x1 - x0) as u32, (y1 - y0) as u32);
+ if tw.max(th) > MAX_TIP {
+ return Err(bad(cmd, format!("selection too large for a brush tip ({tw}×{th}; max {MAX_TIP} px)")));
+ }
+ let mut data = Vec::with_capacity((tw * th) as usize);
+ for y in y0..y1 {
+ data.extend_from_slice(&v[y * w + x0..y * w + x1]);
+ }
+ let tip = GrayTile::from_f32(tw, th, &data);
+ let brush = BrushSettings { tip: TipShape::Sampled(tip), size: tw.max(th) as f32, spacing: 0.25, pressure_size: false, ..BrushSettings::default() };
+ upsert(s, BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false });
+ s.tools.brush = brush;
+ Ok(json!({ "name": name, "width": tw, "height": th }))
+}
+
+fn set_brush(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "tools.setBrush";
+ let mut b = s.tools.brush.clone();
+ if let Some(name) = p.get("preset").and_then(Value::as_str) {
+ b = find_preset(s, name, cmd)?.brush.clone().with_protected_texture(&s.tools.brush);
+ }
+ if flag(p, "reset", false) {
+ b = BrushSettings::default();
+ }
+ let mut patch = p.clone();
+ if let Some(o) = patch.as_object_mut() {
+ for k in ["preset", "reset", "coalesce"] {
+ o.remove(k);
+ }
+ if let Some(inner) = o.remove("brush") {
+ let tmp = merge_brush(&b, &inner, cmd)?;
+ b = tmp;
+ }
+ }
+ b = merge_brush(&b, &patch, cmd)?;
+ s.tools.brush = b;
+ Ok(brush_json(&s.tools.brush))
+}
+
+macro_rules! spec {
+ ($id:literal, $label:literal, $params:literal, $en:expr, $run:expr, $journal:expr) => {
+ CommandSpec { id: $id, label: $label, menu: &[], shortcut: None, params: $params, enabled: $en, run: $run, journal: $journal }
+ };
+}
+
+/// Brush command specs.
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!("paint.pencil", "Pencil", r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…}?,"preset":name?,"size":px?,"opacity":0..1?,"color":"#rrggbb"?=foreground,"erase":bool?,"autoErase":bool=false,"seed":u64?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##, has_paintable, pencil, true),
+ spec!("paint.mixerBrush", "Mixer Brush", r##"{"points":[…],"brush":{…}?,"preset":name?,"size":px?,"wet":0..100=50,"load":0..100=50,"mix":0..100=50,"flow":0..100=100,"color":"#rrggbb"?=foreground,"sampleAllLayers":bool=false,"cleanAfterStroke":bool=true,"loadAfterStroke":bool=true,"seed":u64?}"##, has_paintable, mixer_brush, true),
+ spec!("paint.colorReplacement", "Color Replacement", r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":0..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"seed":u64?}"##, crate::commands::has_paintable, color_replacement, true),
+ spec!("brush.presets.list", "List Brush Presets", r##"{"full":bool=false}"##, always, presets_list, false),
+ spec!("brush.presets.save", "Save Brush Preset", r##"{"name":string,"brush":{…BrushSettings}?=current brush}"##, always, presets_save, true),
+ spec!("brush.presets.delete", "Delete Brush Preset", r##"{"name":string}"##, always, presets_delete, true),
+ spec!("brush.defineFromSelection", "Define Brush Preset…", r##"{"name":string}"##, has_selection_and_pixels, define_from_selection, true),
+ spec!("brush.get", "Get Brush", "{}", always, |s, _| Ok(brush_json(&s.tools.brush)), false),
+ spec!("tools.setBrush", "Set Brush", r##"{"preset":name?,"reset":bool?,…BrushSettings fields (camelCase, deep-merged)}"##, always, set_brush, true),
+ ]
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rs
new file mode 100644
index 000000000..85426bf5c
--- /dev/null
+++ b/crates/engine/src/brush_cmds/tests.rs
@@ -0,0 +1,205 @@
+use super::*;
+
+fn session(w: u32, h: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": w, "height": h, "background": "transparent"})).unwrap();
+ s
+}
+
+fn surface(s: &Session) -> Surface {
+ let d = s.active().unwrap();
+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().clone()
+}
+
+fn rgba(s: &Session, x: i32, y: i32) -> [f32; 4] {
+ surface(s).rgba(x, y)
+}
+
+fn same_pixels(a: &Surface, b: &Surface, r: Rect) -> bool {
+ (r.y0..r.y1).all(|y| (r.x0..r.x1).all(|x| a.pixel(x, y) == b.pixel(x, y)))
+}
+
+#[test]
+fn stroke_backwards_compatible() {
+ let mut s = session(80, 40);
+ let r = s.execute("paint.stroke", json!({"points": [[4, 20], [60, 20]], "size": 6, "color": "#0000ff"})).unwrap();
+ assert_eq!(r["damage"].as_array().unwrap().len(), 4);
+ assert_eq!(rgba(&s, 30, 20), [0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(rgba(&s, 30, 30)[3], 0.0);
+ // [x, y, pressure] with the default pressure-size brush: light pressure → thinner line.
+ s.execute("paint.stroke", json!({"points": [[4, 5, 0.2], [60, 5, 0.2]], "size": 10})).unwrap();
+ assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01);
+}
+
+#[test]
+fn stroke_accepts_full_points_brush_and_preset() {
+ let mut s = session(200, 100);
+ // 7-tuples plus a brush object with tilt-driven angle on a flat tip.
+ let brush = json!({"size": 30, "roundness": 0.2, "pressureSize": false, "spacing": 0.1,
+ "shapeDynamics": {"enabled": true, "angle": {"control": "penTilt"}}});
+ s.execute("paint.stroke", json!({"points": [[50, 50, 1, 0, -45, 0, 0], [52, 50, 1, 0, -45, 0, 16]], "brush": brush})).unwrap();
+ // Tilt up = 90°: the flat tip stands vertically.
+ assert!(rgba(&s, 50, 40)[3] > 0.9 && rgba(&s, 50, 60)[3] > 0.9 && rgba(&s, 60, 50)[3] < 0.01);
+ // Object points.
+ s.execute("paint.stroke", json!({"points": [{"x": 150, "y": 20}, {"x": 180, "y": 20, "pressure": 1.0}], "size": 4, "brush": {"pressureSize": false}})).unwrap();
+ assert!(rgba(&s, 165, 20)[3] > 0.9);
+ // Presets by name.
+ s.execute("paint.stroke", json!({"points": [[20, 80], [120, 80]], "preset": "Hard Round"})).unwrap();
+ assert!(rgba(&s, 70, 80)[3] > 0.99);
+ assert!(s.execute("paint.stroke", json!({"points": [[1, 1]], "preset": "Nope"})).is_err());
+ assert!(s.execute("paint.stroke", json!({"points": [[1, 1]], "brush": {"size": "big"}})).is_err());
+}
+
+#[test]
+fn replay_is_deterministic() {
+ let params = json!({"points": [[10, 50], [60, 30, 0.7], [120, 60, 0.9], [180, 40]], "preset": "Spatter", "color": "#ff8800"});
+ let run = || {
+ let mut s = session(200, 100);
+ s.execute("paint.stroke", params.clone()).unwrap();
+ s.execute("tools.setBrush", json!({"preset": "Confetti"})).unwrap();
+ s.execute("paint.stroke", json!({"points": [[10, 80], [190, 80]]})).unwrap();
+ s
+ };
+ let (a, b) = (run(), run());
+ let r = Rect::new(0, 0, 200, 100);
+ assert!(same_pixels(&surface(&a), &surface(&b), r));
+ // Replaying the journal into a fresh session reproduces the pixels.
+ let mut c = session(200, 100);
+ for (id, p) in a.journal.iter().skip(1) {
+ c.execute(id, p.clone()).unwrap();
+ }
+ assert!(same_pixels(&surface(&a), &surface(&c), r));
+ // A different explicit seed changes the scatter.
+ let mut d = session(200, 100);
+ let mut p2 = params.clone();
+ p2["seed"] = json!(12345);
+ d.execute("paint.stroke", p2).unwrap();
+ let mut e = session(200, 100);
+ e.execute("paint.stroke", params).unwrap();
+ assert!(!same_pixels(&surface(&d), &surface(&e), r));
+}
+
+#[test]
+fn pencil_is_aliased_and_auto_erases() {
+ let mut s = session(60, 30);
+ s.execute("paint.pencil", json!({"points": [[5, 10.3], [50, 10.3]], "size": 5, "color": "#000000"})).unwrap();
+ let surf = surface(&s);
+ for y in 0..30 {
+ for x in 0..60 {
+ let a = surf.rgba(x, y)[3];
+ assert!(a == 0.0 || a == 1.0);
+ }
+ }
+ s.execute("tools.setColors", json!({"foreground": "#000000", "background": "#ffffff"})).unwrap();
+ // Starting on a foreground pixel: paints background.
+ s.execute("paint.pencil", json!({"points": [[20, 10], [20, 25]], "size": 3, "autoErase": true})).unwrap();
+ assert_eq!(rgba(&s, 20, 22), [1.0, 1.0, 1.0, 1.0]);
+ // Starting elsewhere: paints foreground.
+ s.execute("paint.pencil", json!({"points": [[40, 25], [40, 28]], "size": 3, "autoErase": true})).unwrap();
+ assert_eq!(rgba(&s, 40, 26), [0.0, 0.0, 0.0, 1.0]);
+}
+
+#[test]
+fn mixer_brush_reservoir_and_cleaning() {
+ let mut s = session(200, 30);
+ s.execute("tools.setColors", json!({"foreground": "#ff0000"})).unwrap();
+ s.execute("paint.mixerBrush", json!({"points": [[5, 15], [195, 15]], "size": 8, "wet": 0, "load": 0, "mix": 0, "brush": {"pressureSize": false, "spacing": 0.25}})).unwrap();
+ assert!(rgba(&s, 10, 15)[3] > 0.95 && rgba(&s, 190, 15)[3] < 0.5, "low load dries out");
+ assert!(s.tools.mixer.pickup.is_none(), "cleaned after stroke");
+ // Wet, not cleaned: the pickup persists into the session.
+ s.execute("paint.mixerBrush", json!({"points": [[5, 5], [100, 5]], "size": 8, "wet": 100, "mix": 80, "cleanAfterStroke": false})).unwrap();
+ assert!(s.tools.mixer.pickup.is_some());
+ // Sample All Layers path runs.
+ s.execute("paint.mixerBrush", json!({"points": [[5, 25], [50, 25]], "size": 6, "sampleAllLayers": true})).unwrap();
+}
+
+#[test]
+fn color_replacement_modes() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 60, "height": 40, "background": "#33993f"})).unwrap();
+ s.execute("tools.setColors", json!({"foreground": "#ff0000"})).unwrap();
+ let before = rgba(&s, 30, 20);
+ s.execute("paint.colorReplacement", json!({"points": [[10, 20], [50, 20]], "size": 20, "mode": "color", "tolerance": 20})).unwrap();
+ let c = rgba(&s, 30, 20);
+ let lum = |c: [f32; 4]| photocraft_color::blend::lum([c[0], c[1], c[2]]);
+ assert!(c[0] > c[1], "{c:?}");
+ assert!((lum(c) - lum(before)).abs() < 0.02);
+ s.execute("paint.colorReplacement", json!({"points": [[10, 5], [50, 5]], "size": 6, "mode": "luminosity", "sampling": "once", "limits": "discontiguous"})).unwrap();
+ assert!((lum(rgba(&s, 30, 5)) - 0.3).abs() < 0.02);
+ assert!(s.execute("paint.colorReplacement", json!({"points": [[1, 1]], "mode": "bogus"})).is_err());
+}
+
+#[test]
+fn presets_save_load_delete_round_trip() {
+ let mut s = session(10, 10);
+ let n0 = s.execute("brush.presets.list", json!({})).unwrap()["presets"].as_array().unwrap().len();
+ assert!(n0 >= 12);
+ s.execute("brush.presets.save", json!({"name": "Mine", "brush": {"size": 77, "scattering": {"enabled": true, "count": 3}}})).unwrap();
+ let list = s.execute("brush.presets.list", json!({"full": true})).unwrap();
+ let mine = list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Mine").unwrap().clone();
+ assert_eq!(mine["brush"]["size"], 77.0);
+ assert_eq!(mine["brush"]["scattering"]["count"], 3);
+ // Round trip: select it, read it back.
+ let b = s.execute("tools.setBrush", json!({"preset": "mine"})).unwrap();
+ assert_eq!(b["size"], 77.0);
+ let back: BrushSettings = serde_json::from_value(s.execute("brush.get", json!({})).unwrap()).unwrap();
+ assert_eq!(back, s.tools.brush);
+ // Overwrite, then delete.
+ s.execute("brush.presets.save", json!({"name": "Mine"})).unwrap();
+ assert_eq!(s.tools.presets.len(), n0 + 1);
+ s.execute("brush.presets.delete", json!({"name": "Mine"})).unwrap();
+ assert_eq!(s.tools.presets.len(), n0);
+ assert!(s.execute("brush.presets.delete", json!({"name": "Mine"})).is_err());
+ assert!(s.execute("brush.presets.save", json!({})).is_err());
+}
+
+#[test]
+fn set_brush_merges_fields() {
+ let mut s = session(10, 10);
+ s.execute("tools.setBrush", json!({"size": 55, "shapeDynamics": {"enabled": true, "size": {"jitter": 0.5}}})).unwrap();
+ s.execute("tools.setBrush", json!({"shapeDynamics": {"angle": {"jitter": 0.25}}})).unwrap();
+ let b = &s.tools.brush;
+ assert_eq!(b.size, 55.0);
+ assert!(b.shape_dynamics.enabled && b.shape_dynamics.size.jitter == 0.5 && b.shape_dynamics.angle.jitter == 0.25);
+ s.execute("tools.setBrush", json!({"reset": true})).unwrap();
+ assert_eq!(s.tools.brush, BrushSettings::default());
+ // Protect texture carries the pattern across textured presets.
+ s.execute("tools.setBrush", json!({"preset": "Chalk", "protectTexture": true})).unwrap();
+ let chalk_pattern = s.tools.brush.texture.pattern.clone();
+ s.execute("tools.setBrush", json!({"preset": "Canvas Texture"})).unwrap();
+ assert_eq!(s.tools.brush.texture.pattern, chalk_pattern);
+}
+
+#[test]
+fn define_brush_from_selection() {
+ let mut s = session(40, 40);
+ assert!(s.execute("brush.defineFromSelection", json!({"name": "Blob"})).is_err(), "needs a selection");
+ // A black 6×4 block inside a larger selection.
+ s.edit("setup", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 12, 16, 16), &[0.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("select.rect", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap();
+ let r = s.execute("brush.defineFromSelection", json!({"name": "Blob"})).unwrap();
+ assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(6), Some(4)));
+ assert_eq!(s.tools.brush.size, 6.0);
+ assert!(matches!(&s.tools.brush.tip, TipShape::Sampled(t) if t.width == 6 && t.height == 4 && t.get(0, 0) == 1.0));
+ assert!(s.tools.presets.iter().any(|p| p.name == "Blob"));
+ // Paint with it.
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("paint.stroke", json!({"points": [[30, 32]], "color": "#ff0000"})).unwrap();
+ assert!(rgba(&s, 30, 32)[3] > 0.9);
+}
+
+#[test]
+fn works_on_cmyk_and_16_bit() {
+ for (mode, depth) in [("cmyk", 8), ("rgb", 16), ("grayscale", 32)] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 60, "height": 30, "mode": mode, "depth": depth})).unwrap();
+ s.execute("paint.stroke", json!({"points": [[5, 15], [55, 15]], "preset": "Chalk", "color": "#000000"})).unwrap();
+ s.execute("paint.pencil", json!({"points": [[5, 5], [55, 5]], "size": 2, "color": "#000000"})).unwrap();
+ assert!(rgba(&s, 30, 5)[0] < 0.2, "{mode}/{depth}: {:?}", rgba(&s, 30, 5));
+ }
+}
+
diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs
new file mode 100644
index 000000000..b1665a789
--- /dev/null
+++ b/crates/engine/src/channel_cmds.rs
@@ -0,0 +1,1450 @@
+//! Channels: alpha and spot channels, Select › Save / Load Selection, Quick Mask, channel
+//! targeting and visibility (the Channels panel), Image › Apply Image / Calculations, and the
+//! Channels panel menu (Split / Merge Channels, Merge Spot Channel).
+//!
+//! Alpha channels live in [`Document::channels`] (white = selected). Quick Mask is a temporary
+//! channel in [`Document::quick_mask`], so entering and leaving it are history steps like in
+//! Photoshop. Which channel is targeted and which are visible is view state on
+//! [`DocState::channel_view`] (not history), like the active layer.
+//!
+//! Pixel commands (`paint.*`, `filter.*`, `image.adjustments.*`, `edit.fill`) take
+//! `"target": {"channel": i}` or `"target": "quickMask"`; [`Session::execute`] fills that in from the
+//! targeted channel when the caller didn't pass a target. Targeting a single colour channel keeps
+//! those commands from touching the other colour channels of the layer ([`restrict_to_color`]).
+
+use photocraft_algo::selection::{self as sel, SelectionMode};
+use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, blend::blend_channel};
+use photocraft_doc::{AlphaChannel, ColorIndicates, Document, Layer, LayerContent, LayerId};
+use photocraft_geom::{Rect, TileCoord};
+use photocraft_raster::{Surface, from_rgba, to_rgba};
+use serde::Serialize;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{DocState, EngineError, Result, Session};
+
+#[cfg(test)]
+mod tests;
+
+// ---------------------------------------------------------------------------------------------
+// View state
+
+/// What pixel commands edit (Channels panel click / ⌘2…⌘9).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase", tag = "kind", content = "index")]
+pub enum ChannelTarget {
+ /// The layers (all colour channels). In Quick Mask mode this edits the Quick Mask.
+ #[default]
+ Composite,
+ /// One colour channel of the active layer (index into the pixel format's colour channels).
+ Color(usize),
+ /// An alpha or spot channel (index into [`Document::channels`]).
+ Alpha(usize),
+}
+
+/// Per-document Channels panel state: the target and the eye toggles. Not part of history.
+#[derive(Clone, Debug, Default, PartialEq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ChannelView {
+ pub target: ChannelTarget,
+ /// Hidden colour channels (missing entries are visible).
+ pub color_hidden: Vec<bool>,
+ /// Visible alpha channels (missing entries are hidden).
+ pub alpha_visible: Vec<bool>,
+ pub quick_mask_hidden: bool,
+}
+
+impl ChannelView {
+ pub fn color_visible(&self, k: usize) -> bool {
+ !self.color_hidden.get(k).copied().unwrap_or(false)
+ }
+ pub fn alpha_shown(&self, i: usize) -> bool {
+ self.alpha_visible.get(i).copied().unwrap_or(false)
+ }
+ pub fn set_color_visible(&mut self, k: usize, v: bool) {
+ if self.color_hidden.len() <= k {
+ self.color_hidden.resize(k + 1, false);
+ }
+ self.color_hidden[k] = !v;
+ }
+ pub fn set_alpha_visible(&mut self, i: usize, v: bool) {
+ if self.alpha_visible.len() <= i {
+ self.alpha_visible.resize(i + 1, false);
+ }
+ self.alpha_visible[i] = v;
+ }
+ /// Number of visible colour channels out of `colors`.
+ pub fn visible_colors(&self, colors: usize) -> usize {
+ (0..colors).filter(|k| self.color_visible(*k)).count()
+ }
+ /// True when the canvas shows just the normal composite (nothing extra to draw).
+ pub fn is_plain(&self, doc: &Document) -> bool {
+ let colors = color_count(doc);
+ self.visible_colors(colors) == colors
+ && !(0..doc.channels.len()).any(|i| self.alpha_shown(i))
+ && (doc.quick_mask.is_none() || self.quick_mask_hidden)
+ }
+}
+
+/// Session-wide Quick Mask Options (double-click the Quick Mask button in Photoshop).
+#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct QuickMaskOptions {
+ pub color: Color,
+ pub opacity: f32,
+ pub indicates: ColorIndicates,
+}
+
+impl Default for QuickMaskOptions {
+ fn default() -> Self {
+ Self { color: AlphaChannel::DEFAULT_COLOR, opacity: 0.5, indicates: ColorIndicates::MaskedAreas }
+ }
+}
+
+/// Keep the view valid after the document changed (undo, deleted channels, mode changes).
+pub(crate) fn fix_view(st: &mut DocState) {
+ let n = st.doc.channels.len();
+ let colors = color_count(&st.doc);
+ let v = &mut st.channel_view;
+ v.alpha_visible.truncate(n);
+ v.color_hidden.truncate(colors);
+ match v.target {
+ ChannelTarget::Alpha(i) if i >= n => v.target = ChannelTarget::Composite,
+ ChannelTarget::Color(k) if k >= colors || colors < 2 => v.target = ChannelTarget::Composite,
+ _ => {}
+ }
+ // Never leave the canvas showing nothing at all.
+ if v.visible_colors(colors) == 0 && !(0..n).any(|i| v.alpha_shown(i)) {
+ v.color_hidden.clear();
+ }
+}
+
+/// Bump the revision for a view-only change without dirtying a clean document.
+fn touch(st: &mut DocState) {
+ let clean = st.saved_revision == st.revision;
+ st.revision += 1;
+ if clean {
+ st.saved_revision = st.revision;
+ }
+ st.last_damage = None;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Channel names and formats
+
+/// Colour channel names of a document mode (the rows under the composite).
+pub fn color_names(mode: ColorMode) -> &'static [&'static str] {
+ match mode {
+ ColorMode::Cmyk => &["Cyan", "Magenta", "Yellow", "Black"],
+ ColorMode::Lab => &["Lightness", "a", "b"],
+ ColorMode::Grayscale => &["Gray"],
+ _ => &["Red", "Green", "Blue"],
+ }
+}
+
+/// Name of the composite row.
+pub fn composite_name(mode: ColorMode) -> &'static str {
+ match mode {
+ ColorMode::Cmyk => "CMYK",
+ ColorMode::Lab => "Lab",
+ ColorMode::Grayscale => "Gray",
+ _ => "RGB",
+ }
+}
+
+fn edit_mode(doc: &Document) -> ColorMode {
+ doc.pixel_format().mode
+}
+
+pub fn color_count(doc: &Document) -> usize {
+ edit_mode(doc).color_channels()
+}
+
+/// Pixel format of alpha channels: grayscale at the document depth, no transparency.
+pub fn channel_format(doc: &Document) -> PixelFormat {
+ PixelFormat::new(ColorMode::Grayscale, doc.depth, false)
+}
+
+/// Next free "Alpha N" name.
+fn next_alpha_name(doc: &Document, base: &str) -> String {
+ (1..).map(|n| format!("{base} {n}")).find(|n| !doc.channels.iter().any(|c| &c.name == n)).expect("infinite")
+}
+
+// ---------------------------------------------------------------------------------------------
+// Planes: one grayscale value per canvas pixel
+
+fn read_plane(s: &Surface, r: Rect) -> Vec<f32> {
+ let mut v = Vec::new();
+ s.read_region_into(r, &mut v);
+ let ch = s.channels();
+ if ch > 1 { v.chunks_exact(ch).map(|p| p[0]).collect() } else { v }
+}
+
+fn plane_surface(vals: &[f32], r: Rect, fmt: PixelFormat) -> Surface {
+ let mut s = Surface::new(fmt);
+ let clamped: Vec<f32> = vals.iter().map(|v| v.clamp(0.0, 1.0)).collect();
+ s.write_region(r, &clamped);
+ s.prune();
+ s
+}
+
+/// Make every canvas pixel of `s` explicit so filters and adjustments that work on the content
+/// bounds also see the untouched (default-valued) parts of a channel.
+fn materialize(s: &mut Surface, r: Rect) {
+ let v = s.read_region(r);
+ s.write_region(r, &v);
+}
+
+fn luminosity(rgba: [f32; 4]) -> f32 {
+ 0.299 * rgba[0] + 0.587 * rgba[1] + 0.114 * rgba[2]
+}
+
+// ---------------------------------------------------------------------------------------------
+// Channel references
+
+/// A channel named in params: `"composite"`, a colour name (`"red"`, `"cyan"`, `"lightness"`…),
+/// an alpha index (number) or name, `"quickMask"`, `"selection"`, `"transparency"`, `"mask"`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ChanRef {
+ Composite,
+ Color(usize),
+ Alpha(usize),
+ QuickMask,
+ Selection,
+ Transparency,
+ LayerMask,
+}
+
+pub fn parse_ref(v: &Value, doc: &Document) -> Option<ChanRef> {
+ let mode = edit_mode(doc);
+ match v {
+ Value::Number(n) => n.as_u64().map(|i| ChanRef::Alpha(i as usize)),
+ Value::Object(o) => {
+ if let Some(k) = o.get("color").and_then(Value::as_u64) {
+ Some(ChanRef::Color(k as usize))
+ } else {
+ o.get("alpha").and_then(Value::as_u64).map(|i| ChanRef::Alpha(i as usize))
+ }
+ }
+ Value::String(s) => {
+ let l = s.to_ascii_lowercase();
+ match l.as_str() {
+ "composite" | "merged" => return Some(ChanRef::Composite),
+ "quickmask" | "quick mask" => return Some(ChanRef::QuickMask),
+ "selection" => return Some(ChanRef::Selection),
+ "transparency" => return Some(ChanRef::Transparency),
+ "mask" | "layermask" => return Some(ChanRef::LayerMask),
+ _ => {}
+ }
+ if l == composite_name(mode).to_ascii_lowercase() {
+ return Some(ChanRef::Composite);
+ }
+ if let Some(k) = color_names(mode).iter().position(|n| n.eq_ignore_ascii_case(&l)) {
+ return Some(if color_names(mode).len() == 1 { ChanRef::Composite } else { ChanRef::Color(k) });
+ }
+ doc.channels.iter().position(|c| c.name == *s).map(ChanRef::Alpha)
+ }
+ _ => None,
+ }
+}
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn doc_index(s: &Session, p: &Value, key: &str) -> Result<usize> {
+ match crate::commands::int(p, key).and_then(|v| u64::try_from(v).ok()) {
+ Some(i) if (i as usize) < s.documents().len() => Ok(i as usize),
+ Some(i) => Err(EngineError::Other(format!("no open document {i}"))),
+ None => s.active_index().ok_or(EngineError::NoDocument),
+ }
+}
+
+/// Alpha channel index from `p[key]` (number or name), checked against the document.
+fn alpha_index(doc: &Document, p: &Value, key: &str, cmd: &str) -> Result<usize> {
+ match p.get(key).and_then(|v| parse_ref(v, doc)) {
+ Some(ChanRef::Alpha(i)) if i < doc.channels.len() => Ok(i),
+ Some(ChanRef::Alpha(i)) => Err(bad(cmd, format!("no alpha channel {i} (document has {})", doc.channels.len()))),
+ _ => Err(bad(cmd, format!("`{key}` must name an alpha channel (index or name)"))),
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Sources (Load Selection, Apply Image, Calculations)
+
+/// Native pixel values of a layer or of the merged image over the canvas.
+fn native_pixels(doc: &Document, layer: Option<LayerId>) -> Result<(Vec<f32>, usize)> {
+ let r = doc.bounds();
+ let fmt = doc.pixel_format();
+ let n = fmt.channels();
+ match layer {
+ Some(id) => {
+ let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let s = l.surface().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no pixels", l.name)))?;
+ if s.format() == fmt {
+ return Ok((s.read_region(r), n));
+ }
+ let raw = s.read_region(r);
+ let sf = s.format();
+ Ok((raw.chunks_exact(sf.channels()).flat_map(|p| from_rgba(&fmt, to_rgba(&sf, p))).collect(), n))
+ }
+ None => {
+ let buf = photocraft_compose::render(doc, r);
+ Ok((buf.px.iter().flat_map(|p| from_rgba(&fmt, *p)).collect(), n))
+ }
+ }
+}
+
+/// `"layer"` param of a source: a layer id, or `"merged"` (default).
+fn source_layer(p: &Value) -> Option<LayerId> {
+ p.get("layer").and_then(Value::as_u64).map(LayerId)
+}
+
+/// Planes of channel `r` from document `doc` (`layer` = None: merged). A composite gives one
+/// plane per colour channel; everything else gives one plane.
+fn ref_planes(doc: &Document, layer: Option<LayerId>, active: Option<LayerId>, r: ChanRef) -> Result<Vec<Vec<f32>>> {
+ let area = doc.bounds();
+ let colors = color_count(doc);
+ Ok(match r {
+ ChanRef::Composite | ChanRef::Color(_) => {
+ let (px, n) = native_pixels(doc, layer)?;
+ let planes: Vec<Vec<f32>> = (0..colors).map(|c| px.chunks_exact(n).map(|p| p[c]).collect()).collect();
+ match r {
+ ChanRef::Color(k) => vec![planes.get(k).cloned().ok_or_else(|| EngineError::Other(format!("no colour channel {k}")))?],
+ _ => planes,
+ }
+ }
+ ChanRef::Alpha(i) => vec![read_plane(&doc.channels.get(i).ok_or_else(|| EngineError::Other(format!("no alpha channel {i}")))?.surface, area)],
+ ChanRef::QuickMask => vec![read_plane(&doc.quick_mask.as_ref().ok_or_else(|| EngineError::Other("not in Quick Mask mode".into()))?.surface, area)],
+ ChanRef::Selection => vec![sel::mask_from_surface(doc.selection.as_ref(), area)],
+ ChanRef::Transparency => {
+ let id = layer.or(active).ok_or_else(|| EngineError::Other("transparency needs a layer".into()))?;
+ let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ match l.surface() {
+ Some(s) => {
+ let mut px = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize];
+ s.read_rgba_into(area, &mut px);
+ vec![px.iter().map(|p| p[3]).collect()]
+ }
+ // Adjustment and fill layers cover the whole canvas.
+ None => vec![vec![1.0; area.width() as usize * area.height() as usize]],
+ }
+ }
+ ChanRef::LayerMask => {
+ let id = layer.or(active).ok_or_else(|| EngineError::Other("layer mask needs a layer".into()))?;
+ let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let m = l.mask.as_ref().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no mask", l.name)))?;
+ vec![read_plane(&m.surface, area)]
+ }
+ })
+}
+
+/// One grayscale plane (composites reduce to luminosity, as in Calculations).
+fn gray_plane(doc: &Document, layer: Option<LayerId>, active: Option<LayerId>, r: ChanRef) -> Result<Vec<f32>> {
+ let planes = ref_planes(doc, layer, active, r)?;
+ if planes.len() == 1 {
+ return Ok(planes.into_iter().next().expect("one plane"));
+ }
+ let fmt = doc.pixel_format();
+ let n = planes[0].len();
+ let mut px = vec![0.0f32; fmt.channels()];
+ Ok((0..n)
+ .map(|i| {
+ for (c, p) in planes.iter().enumerate() {
+ px[c] = p[i];
+ }
+ if fmt.alpha {
+ px[planes.len()] = 1.0;
+ }
+ luminosity(to_rgba(&fmt, &px))
+ })
+ .collect())
+}
+
+/// A source spec `{document?, layer?, channel, invert?}`, reduced to planes over the canvas of
+/// the active document (sizes must match, as in Photoshop).
+fn source(s: &Session, p: &Value, cmd: &str, gray: bool) -> Result<Vec<Vec<f32>>> {
+ let di = doc_index(s, p, "document")?;
+ let st = &s.documents()[di];
+ let target = s.active().ok_or(EngineError::NoDocument)?;
+ if st.doc.size != target.doc.size {
+ return Err(bad(cmd, format!("source document \"{}\" is {}×{}; it must match the target size", st.doc.name, st.doc.size.width, st.doc.size.height)));
+ }
+ let r = p.get("channel").map_or(Some(ChanRef::Composite), |v| parse_ref(v, &st.doc)).ok_or_else(|| bad(cmd, "unknown `channel`"))?;
+ let layer = source_layer(p);
+ let mut planes = if gray { vec![gray_plane(&st.doc, layer, st.active_layer, r)?] } else { ref_planes(&st.doc, layer, st.active_layer, r)? };
+ if p.get("invert").and_then(Value::as_bool).unwrap_or(false) {
+ for pl in &mut planes {
+ for v in pl.iter_mut() {
+ *v = 1.0 - *v;
+ }
+ }
+ }
+ Ok(planes)
+}
+
+// ---------------------------------------------------------------------------------------------
+// Blending (Apply Image / Calculations)
+
+/// Apply Image / Calculations blending: the separable layer modes plus Add and Subtract with
+/// scale and offset.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Blending {
+ Mode(BlendMode),
+ Add { scale: f32, offset: f32 },
+ Subtract { scale: f32, offset: f32 },
+}
+
+impl Blending {
+ pub fn parse(p: &Value) -> std::result::Result<Self, String> {
+ let name = p.get("blending").and_then(Value::as_str).unwrap_or("multiply");
+ let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0).clamp(1.0, 2.0) as f32;
+ let offset = p.get("offset").and_then(Value::as_f64).unwrap_or(0.0).clamp(-255.0, 255.0) as f32 / 255.0;
+ match name.to_ascii_lowercase().as_str() {
+ "add" => Ok(Blending::Add { scale, offset }),
+ "subtract" => Ok(Blending::Subtract { scale, offset }),
+ other => match crate::commands::blend_from_str(other) {
+ Some(m) if m.is_separable() && !matches!(m, BlendMode::Dissolve | BlendMode::PassThrough) => Ok(Blending::Mode(m)),
+ _ => Err(format!("unsupported blending `{other}`")),
+ },
+ }
+ }
+
+ /// Blend `top` (the source) onto `base` (the target).
+ pub fn apply(self, base: f32, top: f32) -> f32 {
+ match self {
+ Blending::Mode(m) => blend_channel(m, base, top),
+ Blending::Add { scale, offset } => (base + top) / scale + offset,
+ Blending::Subtract { scale, offset } => (base - top) / scale + offset,
+ }
+ .clamp(0.0, 1.0)
+ }
+}
+
+/// A source spec from `p[key]`, or from flat `<prefix>Document` / `<prefix>Layer` /
+/// `<prefix>Channel` / `<prefix>Invert` keys (what the generic dialog form sends).
+fn source_spec(p: &Value, key: &str, prefix: &str) -> Option<Value> {
+ if let Some(v) = p.get(key) {
+ return Some(v.clone());
+ }
+ let mut m = serde_json::Map::new();
+ for (k, field) in [("document", "Document"), ("layer", "Layer"), ("channel", "Channel"), ("invert", "Invert")] {
+ match p.get(format!("{prefix}{field}")) {
+ None | Some(Value::Null) => {}
+ Some(Value::String(s)) if s.is_empty() || (k == "layer" && s == "merged") => {}
+ Some(v) => {
+ m.insert(k.into(), v.clone());
+ }
+ }
+ }
+ (!m.is_empty()).then_some(Value::Object(m))
+}
+
+fn mask_plane(s: &Session, p: &Value, cmd: &str) -> Result<Option<Vec<f32>>> {
+ match source_spec(p, "mask", "mask") {
+ None | Some(Value::Null) | Some(Value::Bool(false)) => Ok(None),
+ Some(m) if m.get("channel").is_none_or(|c| c == "none") => Ok(None),
+ Some(m) => Ok(Some(source(s, &m, cmd, true)?.remove(0))),
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Targets for pixel commands
+
+/// Where a pixel command writes, from its `"target"` param.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Target {
+ Pixels,
+ Mask,
+ Alpha(usize),
+ QuickMask,
+}
+
+pub(crate) fn target_of(p: &Value) -> Target {
+ match p.get("target") {
+ Some(Value::String(s)) => match s.as_str() {
+ "mask" => Target::Mask,
+ "quickMask" => Target::QuickMask,
+ _ => Target::Pixels,
+ },
+ Some(Value::Object(o)) => o.get("channel").and_then(Value::as_u64).map_or(Target::Pixels, |i| Target::Alpha(i as usize)),
+ _ => Target::Pixels,
+ }
+}
+
+/// The target is an alpha channel or the Quick Mask (no layer involved).
+pub(crate) fn is_channel_target(p: &Value) -> bool {
+ matches!(target_of(p), Target::Alpha(_) | Target::QuickMask)
+}
+
+/// The surface a pixel command writes to and whether the layer's transparency is locked.
+pub(crate) fn target_surface<'a>(doc: &'a mut Document, layer: Option<LayerId>, p: &Value) -> Result<(&'a mut Surface, bool)> {
+ match target_of(p) {
+ Target::Alpha(i) => {
+ let n = doc.channels.len();
+ doc.channels.get_mut(i).map(|c| (&mut c.surface, false)).ok_or_else(|| EngineError::Other(format!("no alpha channel {i} (document has {n})")))
+ }
+ Target::QuickMask => doc.quick_mask.as_mut().map(|c| (&mut c.surface, false)).ok_or_else(|| EngineError::Other("not in Quick Mask mode".into())),
+ t => {
+ let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?;
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let lock = l.locks.transparency && t == Target::Pixels;
+ Ok((crate::commands::paint_surface(l, p)?, lock))
+ }
+ }
+}
+
+/// Channel surface for filters and adjustments (made explicit over the canvas), if the params
+/// target a channel.
+pub(crate) fn channel_surface_for_filter<'a>(doc: &'a mut Document, p: &Value) -> Result<Option<&'a mut Surface>> {
+ if !is_channel_target(p) {
+ return Ok(None);
+ }
+ let b = doc.bounds();
+ let (surf, _) = target_surface(doc, None, p)?;
+ materialize(surf, b);
+ Ok(Some(surf))
+}
+
+/// Commands whose target follows the Channels panel.
+fn routed(id: &str) -> bool {
+ id.starts_with("filter.") || id.starts_with("image.adjustments.") || matches!(id, "paint.stroke" | "paint.pencil" | "paint.bucket" | "paint.gradient" | "paint.mixerBrush" | "edit.fill" | "image.applyImage")
+}
+
+/// Fill in `"target"` from the targeted channel (or Quick Mask mode) when the caller gave none.
+pub(crate) fn inject_target(s: &Session, id: &str, params: Value) -> Value {
+ if !routed(id) || params.get("target").is_some() {
+ return params;
+ }
+ let Some(st) = s.active() else { return params };
+ let t = match st.channel_view.target {
+ ChannelTarget::Alpha(i) if i < st.doc.channels.len() => json!({ "channel": i }),
+ ChannelTarget::Composite if st.doc.quick_mask.is_some() => json!("quickMask"),
+ _ => return params,
+ };
+ match params {
+ Value::Object(mut m) => {
+ m.insert("target".into(), t);
+ Value::Object(m)
+ }
+ _ => json!({ "target": t }),
+ }
+}
+
+/// The colour channel pixel commands are limited to, if a single colour channel is targeted.
+pub(crate) fn color_restriction(s: &Session, id: &str, params: &Value) -> Option<usize> {
+ if !routed(id) || is_channel_target(params) || crate::commands::is_mask_target(params) {
+ return None;
+ }
+ match s.active()?.channel_view.target {
+ ChannelTarget::Color(k) => Some(k),
+ _ => None,
+ }
+}
+
+/// After a pixel edit with colour channel `k` targeted, put the other channels (and the layer's
+/// transparency) of layer `id` back as they were. Only changed tiles are touched.
+pub(crate) fn restrict_to_color(before: &Document, after: &mut Document, id: LayerId, k: usize) {
+ let Some(old) = before.layer(id).and_then(Layer::surface) else { return };
+ let Some(new) = after.layer_mut(id).and_then(Layer::surface_mut) else { return };
+ if old.format() != new.format() {
+ return;
+ }
+ let mut coords: Vec<TileCoord> = new.tiles().filter(|(c, t)| old.tile(**c).is_none_or(|o| !std::sync::Arc::ptr_eq(o, t))).map(|(c, _)| *c).collect();
+ coords.extend(old.tiles().filter(|(c, _)| new.tile(**c).is_none()).map(|(c, _)| *c));
+ let n = new.channels();
+ for c in coords {
+ let r = c.rect();
+ let o = old.read_region(r);
+ let mut v = new.read_region(r);
+ for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) {
+ for ch in 0..n {
+ if ch != k {
+ pn[ch] = po[ch];
+ }
+ }
+ }
+ new.write_region(r, &v);
+ }
+ new.prune();
+}
+
+/// The active document targets an alpha channel or is in Quick Mask mode, so pixel commands
+/// work without a pixel layer.
+pub(crate) fn edits_channel(s: &Session) -> bool {
+ s.active().is_some_and(|st| st.doc.quick_mask.is_some() && st.channel_view.target == ChannelTarget::Composite || matches!(st.channel_view.target, ChannelTarget::Alpha(i) if i < st.doc.channels.len()))
+}
+
+// ---------------------------------------------------------------------------------------------
+// Enabled predicates
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+fn has_channels(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ if s.active().is_some_and(|d| !d.doc.channels.is_empty()) { Ok(()) } else { Err("the document has no alpha channels".into()) }
+}
+fn has_selection(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ if s.active().is_some_and(|d| d.doc.selection.is_some()) { Ok(()) } else { Err("no selection".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_spot(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ if s.active().is_some_and(|d| d.doc.channels.iter().any(|c| c.spot.is_some())) { Ok(()) } else { Err("the document has no spot channels".into()) }
+}
+fn can_split(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ let d = s.active().expect("checked");
+ if color_count(&d.doc) + d.doc.channels.len() < 2 { Err("only one channel to split".into()) } else { Ok(()) }
+}
+fn can_merge(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ if mergeable(s).len() >= 2 { Ok(()) } else { Err("Merge Channels needs at least two open grayscale documents of the same size".into()) }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Save / Load Selection
+
+fn operation<'a>(p: &'a Value, key: &str) -> &'a str {
+ p.get(key).and_then(Value::as_str).unwrap_or("new")
+}
+
+fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "select.saveSelection";
+ let op = p.get("operation").and_then(Value::as_str).unwrap_or("new").to_string();
+ if !matches!(op.as_str(), "new" | "replace" | "add" | "subtract" | "intersect") {
+ return Err(bad(cmd, format!("unknown operation `{op}`")));
+ }
+ let di = doc_index(s, p, "document")?;
+ let src = s.active().ok_or(EngineError::NoDocument)?;
+ let area = src.doc.bounds();
+ let selection = sel::mask_from_surface(src.doc.selection.as_ref(), area);
+ if s.documents()[di].doc.size != src.doc.size {
+ return Err(bad(cmd, "the destination document must have the same size"));
+ }
+ let channel = p.get("channel").cloned().unwrap_or(Value::Null);
+ let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
+ let prev = s.active_index();
+ s.set_active(di);
+ let r = s.edit("Save Selection", |doc, _| {
+ let fmt = channel_format(doc);
+ let existing = match &channel {
+ Value::Null => None,
+ Value::String(x) if x == "new" => None,
+ v => match parse_ref(v, doc) {
+ Some(ChanRef::Alpha(i)) if i < doc.channels.len() => Some(i),
+ _ => return Err(bad(cmd, "`channel` must be \"new\" or an existing alpha channel")),
+ },
+ };
+ match (existing, op.as_str()) {
+ (None, _) | (_, "new") => {
+ let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha"));
+ doc.channels.push(AlphaChannel::new(name, plane_surface(&selection, area, fmt)));
+ Ok(doc.channels.len() - 1)
+ }
+ (Some(i), op) => {
+ let old = read_plane(&doc.channels[i].surface, area);
+ let vals: Vec<f32> = match op {
+ "add" => old.iter().zip(&selection).map(|(a, b)| a.max(*b)).collect(),
+ "subtract" => old.iter().zip(&selection).map(|(a, b)| (a - b).max(0.0)).collect(),
+ "intersect" => old.iter().zip(&selection).map(|(a, b)| a.min(*b)).collect(),
+ _ => selection.clone(),
+ };
+ doc.channels[i].surface = plane_surface(&vals, area, fmt);
+ if let Some(n) = &name {
+ doc.channels[i].name = n.clone();
+ }
+ Ok(i)
+ }
+ }
+ });
+ if let Some(i) = prev {
+ s.set_active(i);
+ }
+ let i = r?;
+ let name = s.documents()[di].doc.channels[i].name.clone();
+ Ok(json!({ "channel": i, "name": name, "document": di }))
+}
+
+fn load_selection(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "select.loadSelection";
+ let mode = match operation(p, "operation") {
+ "new" | "replace" => SelectionMode::Replace,
+ "add" => SelectionMode::Add,
+ "subtract" => SelectionMode::Subtract,
+ "intersect" => SelectionMode::Intersect,
+ other => return Err(bad(cmd, format!("unknown operation `{other}`"))),
+ };
+ if p.get("channel").is_none() {
+ return Err(bad(cmd, "missing `channel`"));
+ }
+ // Composite and colour channels load their luminosity / values, as ⌘-clicking them does.
+ let plane = source(s, p, cmd, true)?.remove(0);
+ let label = match p.get("channel").and_then(|v| parse_ref(v, &s.active().expect("source checked").doc)) {
+ Some(ChanRef::Transparency) => "Load Transparency",
+ Some(ChanRef::LayerMask) => "Load Layer Mask",
+ _ => "Load Selection",
+ };
+ let selected = s.edit(label, |doc, _| {
+ doc.selection = sel::combine(doc.selection.as_ref(), &plane, doc.bounds(), mode);
+ Ok(doc.selection.is_some())
+ })?;
+ Ok(json!({ "selected": selected }))
+}
+
+// ---------------------------------------------------------------------------------------------
+// Quick Mask
+
+/// Quick Mask channel for the current selection: white where selected; no selection = an empty
+/// mask (nothing masked), as in Photoshop.
+fn quick_mask_from(doc: &Document, o: &QuickMaskOptions) -> AlphaChannel {
+ let area = doc.bounds();
+ let fmt = channel_format(doc);
+ let surface = match &doc.selection {
+ Some(s) => plane_surface(&sel::mask_from_surface(Some(s), area), area, fmt),
+ None => {
+ let mut s = Surface::new(fmt);
+ s.fill_rect(area, &[1.0]);
+ s
+ }
+ };
+ AlphaChannel { color: o.color, opacity: o.opacity, indicates: o.indicates, ..AlphaChannel::new("Quick Mask", surface) }
+}
+
+/// The selection a Quick Mask channel turns back into (an untouched or all-white mask = none).
+fn selection_from(doc: &Document, ch: &AlphaChannel) -> Option<Surface> {
+ let area = doc.bounds();
+ let vals = read_plane(&ch.surface, area);
+ if vals.iter().all(|v| *v >= 1.0 - 0.5 / 255.0) {
+ return None;
+ }
+ sel::combine(None, &vals, area, SelectionMode::Replace)
+}
+
+fn quick_mask(s: &mut Session, p: &Value) -> Result<Value> {
+ let on = s.active().ok_or(EngineError::NoDocument)?.doc.quick_mask.is_some();
+ let want = p.get("on").and_then(Value::as_bool).unwrap_or(!on);
+ if want == on {
+ return Ok(json!({ "quickMask": on }));
+ }
+ let opts = s.quick_mask_options;
+ if want {
+ s.edit("Edit in Quick Mask", |doc, _| {
+ doc.quick_mask = Some(quick_mask_from(doc, &opts));
+ doc.selection = None;
+ Ok(())
+ })?;
+ if let Some(st) = s.active_mut() {
+ st.channel_view.target = ChannelTarget::Composite;
+ st.channel_view.quick_mask_hidden = false;
+ }
+ } else {
+ s.edit("Exit Quick Mask", |doc, _| {
+ if let Some(q) = doc.quick_mask.take() {
+ doc.selection = selection_from(doc, &q);
+ }
+ Ok(())
+ })?;
+ }
+ Ok(json!({ "quickMask": want }))
+}
+
+// ---------------------------------------------------------------------------------------------
+// Channel management
+
+fn indicates_param(v: Option<&Value>) -> Option<ColorIndicates> {
+ match v?.as_str()? {
+ "masked" | "maskedAreas" => Some(ColorIndicates::MaskedAreas),
+ "selected" | "selectedAreas" => Some(ColorIndicates::SelectedAreas),
+ _ => None,
+ }
+}
+
+fn color_value(p: &Value, key: &str) -> Option<Color> {
+ p.get(key)?;
+ let c = crate::commands::color_param(p, key, [1.0, 0.0, 0.0, 1.0]);
+ Some(Color::rgb(c[0], c[1], c[2]))
+}
+
+fn new_channel(s: &mut Session, p: &Value) -> Result<Value> {
+ let fill = p.get("fill").and_then(Value::as_str).unwrap_or("black").to_string();
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);
+ let indicates = indicates_param(p.get("indicates"));
+ let color = color_value(p, "color");
+ let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
+ let i = s.edit("New Channel", |doc, _| {
+ let area = doc.bounds();
+ let fmt = channel_format(doc);
+ let surface = match fill.as_str() {
+ "white" => plane_surface(&vec![1.0; area.width() as usize * area.height() as usize], area, fmt),
+ "selection" => plane_surface(&sel::mask_from_surface(doc.selection.as_ref(), area), area, fmt),
+ _ => Surface::new(fmt),
+ };
+ let mut ch = AlphaChannel::new(name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha")), surface);
+ if let Some(v) = indicates {
+ ch.indicates = v;
+ }
+ if let Some(c) = color {
+ ch.color = c;
+ }
+ if let Some(o) = opacity {
+ ch.opacity = o;
+ }
+ doc.channels.push(ch);
+ Ok(doc.channels.len() - 1)
+ })?;
+ // Photoshop targets and shows a new channel on its own.
+ target(s, ChannelTarget::Alpha(i));
+ Ok(json!({ "channel": i }))
+}
+
+fn new_spot(s: &mut Session, p: &Value) -> Result<Value> {
+ let color = color_value(p, "color").unwrap_or(Color::rgb(1.0, 0.0, 0.0));
+ let solidity = p.get("solidity").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 100.0) as f32 / 100.0;
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);
+ let from_sel = p.get("fromSelection").and_then(Value::as_bool).unwrap_or(true);
+ let i = s.edit("New Spot Channel", |doc, _| {
+ let area = doc.bounds();
+ let fmt = channel_format(doc);
+ let surface = if from_sel && doc.selection.is_some() { plane_surface(&sel::mask_from_surface(doc.selection.as_ref(), area), area, fmt) } else { Surface::new(fmt) };
+ let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Spot Color"));
+ doc.channels.push(AlphaChannel { spot: Some((color, solidity)), ..AlphaChannel::new(name, surface) });
+ Ok(doc.channels.len() - 1)
+ })?;
+ if let Some(st) = s.active_mut() {
+ st.channel_view.set_alpha_visible(i, true);
+ touch(st);
+ }
+ Ok(json!({ "channel": i }))
+}
+
+fn duplicate_channel(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "channel.duplicate";
+ let src = s.active().ok_or(EngineError::NoDocument)?;
+ let area = src.doc.bounds();
+ let r = p.get("channel").and_then(|v| parse_ref(v, &src.doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?;
+ let mut ch = match r {
+ ChanRef::Alpha(i) => src.doc.channels.get(i).cloned().ok_or_else(|| bad(cmd, format!("no alpha channel {i}")))?,
+ ChanRef::QuickMask => src.doc.quick_mask.clone().ok_or_else(|| bad(cmd, "not in Quick Mask mode"))?,
+ other => {
+ let plane = gray_plane(&src.doc, None, src.active_layer, other)?;
+ AlphaChannel::new(String::new(), plane_surface(&plane, area, channel_format(&src.doc)))
+ }
+ };
+ let base = match r {
+ ChanRef::Alpha(_) | ChanRef::QuickMask => ch.name.clone(),
+ ChanRef::Color(k) => color_names(edit_mode(&src.doc))[k].to_string(),
+ _ => composite_name(edit_mode(&src.doc)).to_string(),
+ };
+ ch.name = p.get("name").and_then(Value::as_str).map_or_else(|| format!("{base} copy"), str::to_string);
+ if p.get("invert").and_then(Value::as_bool).unwrap_or(false) {
+ let v: Vec<f32> = read_plane(&ch.surface, area).into_iter().map(|v| 1.0 - v).collect();
+ ch.surface = plane_surface(&v, area, ch.surface.format());
+ }
+ match p.get("document") {
+ Some(Value::String(x)) if x == "new" => {
+ // Photoshop makes a multichannel document; ours is grayscale with the channel as pixels.
+ let doc = gray_document(&ch.name, &src.doc, &read_plane(&ch.surface, area));
+ let i = s.add_document(doc, None);
+ Ok(json!({ "document": i }))
+ }
+ _ => {
+ let di = doc_index(s, p, "document")?;
+ if s.documents()[di].doc.size != src.doc.size {
+ return Err(bad(cmd, "the destination document must have the same size"));
+ }
+ let prev = s.active_index();
+ s.set_active(di);
+ let r = s.edit("Duplicate Channel", |doc, _| {
+ let fmt = channel_format(doc);
+ if ch.surface.format() != fmt {
+ ch.surface = ch.surface.convert(fmt);
+ }
+ doc.channels.push(ch);
+ Ok(doc.channels.len() - 1)
+ });
+ if let Some(i) = prev {
+ s.set_active(i);
+ }
+ Ok(json!({ "channel": r?, "document": di }))
+ }
+ }
+}
+
+/// A one-layer grayscale document whose pixels are `plane` (Split Channels, Duplicate Channel
+/// to a new document).
+fn gray_document(name: &str, like: &Document, plane: &[f32]) -> Document {
+ let mut d = Document::new(name, like.size, ColorMode::Grayscale, like.depth);
+ d.resolution_dpi = like.resolution_dpi;
+ let fmt = d.pixel_format();
+ let mut bg = Layer::raster("Background", fmt);
+ bg.locks.transparency = true;
+ bg.locks.position = true;
+ if let Some(s) = bg.surface_mut() {
+ let data: Vec<f32> = plane.iter().flat_map(|v| [v.clamp(0.0, 1.0), 1.0]).collect();
+ s.write_region(like.bounds(), &data);
+ s.prune();
+ }
+ d.layers.push(bg);
+ d
+}
+
+fn delete_channel(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "channel.delete";
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let i = match p.get("channel") {
+ Some(_) => alpha_index(doc, p, "channel", cmd)?,
+ None => match s.active().expect("checked").channel_view.target {
+ ChannelTarget::Alpha(i) => i,
+ _ => return Err(bad(cmd, "missing `channel`")),
+ },
+ };
+ s.edit("Delete Channel", |doc, _| {
+ doc.channels.remove(i);
+ Ok(())
+ })?;
+ if let Some(st) = s.active_mut() {
+ let v = &mut st.channel_view;
+ if i < v.alpha_visible.len() {
+ v.alpha_visible.remove(i);
+ }
+ v.target = match v.target {
+ ChannelTarget::Alpha(t) if t == i => {
+ v.color_hidden.clear();
+ ChannelTarget::Composite
+ }
+ ChannelTarget::Alpha(t) if t > i => ChannelTarget::Alpha(t - 1),
+ t => t,
+ };
+ fix_view_now(st);
+ }
+ Ok(Value::Null)
+}
+
+fn fix_view_now(st: &mut DocState) {
+ fix_view(st);
+ touch(st);
+}
+
+fn rename_channel(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "channel.rename";
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let i = alpha_index(doc, p, "channel", cmd)?;
+ let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `name`"))?.to_string();
+ s.edit("Rename Channel", |doc, _| {
+ doc.channels[i].name = name;
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn move_channel(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "channel.move";
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let n = doc.channels.len();
+ let i = alpha_index(doc, p, "channel", cmd)?;
+ let to = p.get("to").and_then(Value::as_u64).map(|v| (v as usize).min(n - 1)).ok_or_else(|| bad(cmd, "missing `to`"))?;
+ if to == i {
+ return Ok(json!({ "channel": i }));
+ }
+ s.edit("Channel Order", |doc, _| {
+ let c = doc.channels.remove(i);
+ doc.channels.insert(to, c);
+ Ok(())
+ })?;
+ if let Some(st) = s.active_mut() {
+ let v = &mut st.channel_view;
+ v.alpha_visible.resize(n, false);
+ let vis = v.alpha_visible.remove(i);
+ v.alpha_visible.insert(to, vis);
+ let remap = |t: usize| if t == i { to } else if i < t && t <= to { t - 1 } else if to <= t && t < i { t + 1 } else { t };
+ if let ChannelTarget::Alpha(t) = v.target {
+ v.target = ChannelTarget::Alpha(remap(t));
+ }
+ touch(st);
+ }
+ Ok(json!({ "channel": to }))
+}
+
+/// Make `t` the edit target and show it the way Photoshop does when its row is clicked.
+fn target(s: &mut Session, t: ChannelTarget) {
+ let Some(st) = s.active_mut() else { return };
+ let colors = color_count(&st.doc);
+ let n = st.doc.channels.len();
+ let v = &mut st.channel_view;
+ v.target = t;
+ match t {
+ ChannelTarget::Composite => v.color_hidden.clear(),
+ ChannelTarget::Color(k) => {
+ v.color_hidden = (0..colors).map(|c| c != k).collect();
+ v.alpha_visible.clear();
+ }
+ ChannelTarget::Alpha(i) => {
+ v.color_hidden = vec![true; colors];
+ v.alpha_visible = (0..n).map(|c| c == i).collect();
+ }
+ }
+ fix_view_now(st);
+}
+
+fn parse_target(s: &Session, p: &Value, cmd: &str) -> Result<ChannelTarget> {
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ match p.get("channel").map_or(Some(ChanRef::Composite), |v| parse_ref(v, doc)) {
+ Some(ChanRef::Composite) => Ok(ChannelTarget::Composite),
+ Some(ChanRef::Color(k)) if k < color_count(doc) && color_count(doc) > 1 => Ok(ChannelTarget::Color(k)),
+ Some(ChanRef::Alpha(i)) if i < doc.channels.len() => Ok(ChannelTarget::Alpha(i)),
+ _ => Err(bad(cmd, "`channel` must be \"composite\", a colour channel name or an alpha channel")),
+ }
+}
+
+fn target_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ let t = parse_target(s, p, "channel.target")?;
+ target(s, t);
+ Ok(list(s))
+}
+
+/// ⌘2 composite, ⌘3… colour channels then alpha channels (Photoshop CC defaults).
+fn target_slot(s: &mut Session, slot: usize) -> Result<Value> {
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let colors = color_count(doc);
+ let shown_colors = if colors > 1 { colors } else { 0 };
+ let t = match slot {
+ 2 => ChannelTarget::Composite,
+ n if n - 3 < shown_colors => ChannelTarget::Color(n - 3),
+ n if n - 3 - shown_colors < doc.channels.len() => ChannelTarget::Alpha(n - 3 - shown_colors),
+ _ => return Err(EngineError::Other(format!("no channel for ⌘{slot}"))),
+ };
+ target(s, t);
+ Ok(list(s))
+}
+
+fn set_visible(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "channel.setVisible";
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let r = p.get("channel").and_then(|v| parse_ref(v, doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?;
+ let colors = color_count(doc);
+ let n = doc.channels.len();
+ let st = s.active_mut().expect("checked");
+ let v = &mut st.channel_view;
+ let visible = |cur: bool| p.get("visible").and_then(Value::as_bool).unwrap_or(!cur);
+ match r {
+ ChanRef::Composite => {
+ let all = v.visible_colors(colors) == colors;
+ let on = visible(all);
+ v.color_hidden = vec![!on; colors];
+ }
+ ChanRef::Color(k) if k < colors => {
+ let on = visible(v.color_visible(k));
+ v.set_color_visible(k, on);
+ }
+ ChanRef::Alpha(i) if i < n => {
+ let on = visible(v.alpha_shown(i));
+ v.set_alpha_visible(i, on);
+ }
+ ChanRef::QuickMask => v.quick_mask_hidden = !visible(!v.quick_mask_hidden),
+ _ => return Err(bad(cmd, "that channel has no visibility")),
+ }
+ fix_view_now(st);
+ Ok(list(s))
+}
+
+fn options(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "channel.options";
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let r = p.get("channel").and_then(|v| parse_ref(v, doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?;
+ let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
+ let color = color_value(p, "color");
+ let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
+ let solidity = p.get("solidity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
+ let kind = p.get("indicates").and_then(Value::as_str).map(str::to_string);
+ let apply = move |ch: &mut AlphaChannel| -> Result<()> {
+ if let Some(n) = &name {
+ ch.name = n.clone();
+ }
+ match kind.as_deref() {
+ Some("spot") => {
+ let (c, sol) = ch.spot.unwrap_or((ch.color, 0.0));
+ ch.spot = Some((color.unwrap_or(c), solidity.unwrap_or(sol)));
+ return Ok(());
+ }
+ Some(k) => {
+ ch.indicates = indicates_param(Some(&json!(k))).ok_or_else(|| bad(cmd, format!("unknown `indicates` {k}")))?;
+ ch.spot = None;
+ }
+ None => {}
+ }
+ match &mut ch.spot {
+ Some((c, sol)) => {
+ *c = color.unwrap_or(*c);
+ *sol = solidity.or(opacity).unwrap_or(*sol);
+ }
+ None => {
+ ch.color = color.unwrap_or(ch.color);
+ ch.opacity = opacity.unwrap_or(ch.opacity);
+ }
+ }
+ Ok(())
+ };
+ match r {
+ ChanRef::Alpha(i) if i < doc.channels.len() => {
+ s.edit("Channel Options", |doc, _| apply(&mut doc.channels[i]))?;
+ }
+ ChanRef::QuickMask => {
+ // Quick Mask Options persist for the session; the live Quick Mask follows them.
+ let mut probe = AlphaChannel { color: s.quick_mask_options.color, opacity: s.quick_mask_options.opacity, indicates: s.quick_mask_options.indicates, ..AlphaChannel::new("Quick Mask", Surface::new(PixelFormat::GRAY8)) };
+ apply(&mut probe)?;
+ if probe.spot.is_some() {
+ return Err(bad(cmd, "Quick Mask can't be a spot channel"));
+ }
+ s.quick_mask_options = QuickMaskOptions { color: probe.color, opacity: probe.opacity, indicates: probe.indicates };
+ if s.active().is_some_and(|d| d.doc.quick_mask.is_some()) {
+ let o = s.quick_mask_options;
+ s.edit("Quick Mask Options", |doc, _| {
+ if let Some(q) = &mut doc.quick_mask {
+ q.color = o.color;
+ q.opacity = o.opacity;
+ q.indicates = o.indicates;
+ }
+ Ok(())
+ })?;
+ }
+ }
+ _ => return Err(bad(cmd, "`channel` must be an alpha/spot channel or \"quickMask\"")),
+ }
+ Ok(list(s))
+}
+
+/// Merge Spot Channel: flattens the image and prints the spot ink into the colour channels.
+fn merge_spot(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "channel.mergeSpot";
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let i = match p.get("channel") {
+ Some(_) => alpha_index(doc, p, "channel", cmd)?,
+ None => match s.active().expect("checked").channel_view.target {
+ ChannelTarget::Alpha(i) => i,
+ _ => doc.channels.iter().position(|c| c.spot.is_some()).ok_or_else(|| bad(cmd, "no spot channel"))?,
+ },
+ };
+ let (ink, solidity) = doc.channels[i].spot.ok_or_else(|| bad(cmd, "not a spot channel"))?;
+ s.edit("Merge Spot Channel", |doc, active| {
+ let area = doc.bounds();
+ let fmt = doc.pixel_format();
+ let comp = photocraft_compose::render(doc, area);
+ let k = read_plane(&doc.channels[i].surface, area);
+ let ink = ink.to_rgb();
+ // Ink over the image: opaque at 100% solidity, multiplied (transparent ink) at 0%.
+ let data: Vec<f32> = comp
+ .px
+ .iter()
+ .zip(&k)
+ .flat_map(|(c, &v)| {
+ let rgb: [f32; 3] = std::array::from_fn(|j| {
+ let over = solidity * ink[j] + (1.0 - solidity) * c[j] * ink[j];
+ c[j] + (over - c[j]) * v.clamp(0.0, 1.0)
+ });
+ from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0])
+ })
+ .collect();
+ let mut bg = Layer::raster("Background", fmt);
+ bg.locks.transparency = true;
+ bg.locks.position = true;
+ if let Some(sf) = bg.surface_mut() {
+ sf.write_region(area, &data);
+ sf.prune();
+ }
+ let id = bg.id;
+ doc.layers = vec![bg];
+ doc.channels.remove(i);
+ *active = Some(id);
+ Ok(())
+ })?;
+ if let Some(st) = s.active_mut() {
+ st.channel_view = ChannelView::default();
+ fix_view_now(st);
+ }
+ Ok(Value::Null)
+}
+
+/// Split Channels: one grayscale document per colour and alpha channel; closes the original.
+fn split(s: &mut Session, p: &Value) -> Result<Value> {
+ let idx = s.active_index().ok_or(EngineError::NoDocument)?;
+ let doc = s.documents()[idx].doc.clone();
+ let area = doc.bounds();
+ let (px, n) = native_pixels(&doc, None)?;
+ let mode = edit_mode(&doc);
+ let names = color_names(mode);
+ let short = |name: &str| name.chars().next().map(|c| c.to_ascii_uppercase().to_string()).unwrap_or_default();
+ let mut docs: Vec<Document> = Vec::new();
+ for (c, name) in names.iter().enumerate() {
+ let plane: Vec<f32> = px.chunks_exact(n).map(|p| p[c]).collect();
+ docs.push(gray_document(&format!("{}_{}", doc.name, short(name)), &doc, &plane));
+ }
+ for ch in &doc.channels {
+ docs.push(gray_document(&format!("{}_{}", doc.name, ch.name), &doc, &read_plane(&ch.surface, area)));
+ }
+ if p.get("closeOriginal").and_then(Value::as_bool).unwrap_or(true) {
+ s.close(idx);
+ }
+ let made: Vec<usize> = docs.into_iter().map(|d| s.add_document(d, None)).collect();
+ Ok(json!({ "documents": made }))
+}
+
+/// Open grayscale documents with the active document's size, active first.
+fn mergeable(s: &Session) -> Vec<usize> {
+ let Some(a) = s.active() else { return Vec::new() };
+ let ok = |d: &DocState| d.doc.mode == ColorMode::Grayscale && d.doc.size == a.doc.size;
+ let mut v: Vec<usize> = s.active_index().into_iter().filter(|_| ok(a)).collect();
+ v.extend(s.documents().iter().enumerate().filter(|(i, d)| Some(*i) != s.active_index() && ok(d)).map(|(i, _)| i));
+ v
+}
+
+/// Merge Channels: grayscale documents of one size become the channels of an RGB, CMYK or Lab
+/// document (extra documents become alpha channels); the sources close.
+fn merge(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "channel.merge";
+ let mode = match p.get("mode").and_then(Value::as_str).unwrap_or("rgb") {
+ "rgb" => ColorMode::Rgb,
+ "cmyk" => ColorMode::Cmyk,
+ "lab" => ColorMode::Lab,
+ other => return Err(bad(cmd, format!("unknown mode `{other}`"))),
+ };
+ let srcs: Vec<usize> = match p.get("documents").and_then(Value::as_array) {
+ Some(a) => a.iter().map(|v| v.as_u64().map(|i| i as usize).filter(|i| *i < s.documents().len()).ok_or_else(|| bad(cmd, "bad document index"))).collect::<Result<_>>()?,
+ None => mergeable(s).into_iter().take(mode.color_channels()).collect(),
+ };
+ if srcs.len() < mode.color_channels() {
+ return Err(bad(cmd, format!("{mode:?} needs {} grayscale documents, got {}", mode.color_channels(), srcs.len())));
+ }
+ let first = s.documents()[srcs[0]].doc.clone();
+ let mut planes = Vec::new();
+ for &i in &srcs {
+ let d = &s.documents()[i].doc;
+ if d.size != first.size || d.mode != ColorMode::Grayscale {
+ return Err(bad(cmd, format!("\"{}\" is not a grayscale document of the same size", d.name)));
+ }
+ planes.push(gray_plane(d, None, None, ChanRef::Composite)?);
+ }
+ let mut out = Document::new(p.get("name").and_then(Value::as_str).unwrap_or("Untitled"), first.size, mode, first.depth);
+ out.resolution_dpi = first.resolution_dpi;
+ let fmt = out.pixel_format();
+ let cc = mode.color_channels();
+ let npx = planes[0].len();
+ let mut data = Vec::with_capacity(npx * fmt.channels());
+ for i in 0..npx {
+ for pl in &planes[..cc] {
+ data.push(pl[i].clamp(0.0, 1.0));
+ }
+ data.push(1.0);
+ }
+ let mut bg = Layer::raster("Background", fmt);
+ bg.locks.transparency = true;
+ bg.locks.position = true;
+ if let Some(sf) = bg.surface_mut() {
+ sf.write_region(out.bounds(), &data);
+ sf.prune();
+ }
+ out.layers.push(bg);
+ let area = out.bounds();
+ let cf = channel_format(&out);
+ for (k, pl) in planes[cc..].iter().enumerate() {
+ out.channels.push(AlphaChannel::new(format!("Alpha {}", k + 1), plane_surface(pl, area, cf)));
+ }
+ let mut close: Vec<usize> = srcs.clone();
+ close.sort_unstable();
+ for i in close.into_iter().rev() {
+ s.close(i);
+ }
+ let i = s.add_document(out, None);
+ Ok(json!({ "document": i }))
+}
+
+// ---------------------------------------------------------------------------------------------
+// Apply Image / Calculations
+
+fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "image.applyImage";
+ let blending = Blending::parse(p).map_err(|e| bad(cmd, e))?;
+ let opacity = p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) as f32 / 100.0;
+ let preserve = p.get("preserveTransparency").and_then(Value::as_bool).unwrap_or(false);
+ let src_spec = source_spec(p, "source", "source").unwrap_or_else(|| json!({}));
+ let src = source(s, &src_spec, cmd, false)?;
+ let mask = mask_plane(s, p, cmd)?;
+ let layer = s.active().and_then(|d| d.active_layer);
+ s.edit("Apply Image", |doc, _| {
+ let area = doc.bounds();
+ let selection = doc.selection.as_ref().map(|m| sel::mask_from_surface(Some(m), area));
+ let weight = |i: usize| opacity * mask.as_ref().map_or(1.0, |m| m[i]) * selection.as_ref().map_or(1.0, |m| m[i]);
+ if is_channel_target(p) {
+ // A grayscale target gets the luminosity of a colour source (one plane).
+ let srcp = if src.len() == 1 { src[0].clone() } else { (0..src[0].len()).map(|i| src.iter().map(|pl| pl[i]).sum::<f32>() / src.len() as f32).collect() };
+ let (surf, _) = target_surface(doc, None, p)?;
+ let base = read_plane(surf, area);
+ let out: Vec<f32> = base.iter().enumerate().map(|(i, &b)| b + (blending.apply(b, srcp[i]) - b) * weight(i)).collect();
+ *surf = plane_surface(&out, area, surf.format());
+ return Ok(());
+ }
+ let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?;
+ let fmt = doc.pixel_format();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let surf = crate::commands::paint_surface(l, &Value::Null)?;
+ let sf = surf.format();
+ if sf != fmt {
+ return Err(EngineError::Other("the target layer's format doesn't match the document".into()));
+ }
+ let n = sf.channels();
+ let colors = sf.mode.color_channels();
+ let mut v = surf.read_region(area);
+ for (i, px) in v.chunks_exact_mut(n).enumerate() {
+ let mut w = weight(i);
+ if preserve && sf.alpha {
+ w *= px[colors].clamp(0.0, 1.0);
+ }
+ if w <= 0.0 {
+ continue;
+ }
+ for (c, b) in px[..colors].iter_mut().enumerate() {
+ let top = src.get(c).unwrap_or(&src[0])[i];
+ *b += (blending.apply(*b, top) - *b) * w;
+ }
+ // Painting a transparent pixel makes it opaque, as Apply Image does on layers.
+ if !preserve && sf.alpha {
+ px[colors] = px[colors].max(w);
+ }
+ }
+ surf.write_region(area, &v);
+ surf.prune();
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn calculations(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "image.calculations";
+ let blending = Blending::parse(p).map_err(|e| bad(cmd, e))?;
+ let opacity = p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) as f32 / 100.0;
+ let s1 = source(s, &source_spec(p, "source1", "source1").unwrap_or_else(|| json!({})), cmd, true)?.remove(0);
+ let s2 = source(s, &source_spec(p, "source2", "source2").unwrap_or_else(|| json!({})), cmd, true)?.remove(0);
+ let mask = mask_plane(s, p, cmd)?;
+ // Source 1 is blended onto Source 2.
+ let out: Vec<f32> = s2.iter().zip(&s1).enumerate().map(|(i, (&b, &t))| b + (blending.apply(b, t) - b) * opacity * mask.as_ref().map_or(1.0, |m| m[i])).collect();
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);
+ match p.get("result").and_then(Value::as_str).unwrap_or("newChannel") {
+ "newChannel" => {
+ let i = s.edit("Calculations", |doc, _| {
+ let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha"));
+ let area = doc.bounds();
+ let fmt = channel_format(doc);
+ doc.channels.push(AlphaChannel::new(name, plane_surface(&out, area, fmt)));
+ Ok(doc.channels.len() - 1)
+ })?;
+ Ok(json!({ "channel": i }))
+ }
+ "newDocument" => {
+ let like = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ let d = gray_document(name.as_deref().unwrap_or("Untitled"), &like, &out);
+ let i = s.add_document(d, None);
+ Ok(json!({ "document": i }))
+ }
+ "selection" => {
+ let selected = s.edit("Calculations", |doc, _| {
+ doc.selection = sel::combine(None, &out, doc.bounds(), SelectionMode::Replace);
+ Ok(doc.selection.is_some())
+ })?;
+ Ok(json!({ "selected": selected }))
+ }
+ other => Err(bad(cmd, format!("unknown result `{other}` (newChannel|newDocument|selection)"))),
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// State as JSON
+
+/// The Channels panel rows and view state of a document (also part of `inspect`).
+pub fn channels_json(st: &DocState) -> Value {
+ let doc = &st.doc;
+ let mode = edit_mode(doc);
+ let v = &st.channel_view;
+ let colors = color_count(doc);
+ json!({
+ "composite": composite_name(mode),
+ "colors": color_names(mode).iter().enumerate().map(|(k, n)| json!({ "name": n, "visible": v.color_visible(k) })).collect::<Vec<_>>(),
+ "alpha": doc.channels.iter().enumerate().map(|(i, c)| json!({
+ "index": i,
+ "name": c.name,
+ "visible": v.alpha_shown(i),
+ "spot": c.spot.map(|(col, sol)| json!({ "color": col.to_rgb(), "solidity": sol })),
+ "color": c.color.to_rgb(),
+ "opacity": c.opacity,
+ "indicates": c.indicates,
+ })).collect::<Vec<_>>(),
+ "quickMask": doc.quick_mask.as_ref().map(|q| json!({ "visible": !v.quick_mask_hidden, "color": q.color.to_rgb(), "opacity": q.opacity, "indicates": q.indicates })),
+ "target": v.target,
+ "compositeVisible": v.visible_colors(colors) == colors,
+ })
+}
+
+fn list(s: &Session) -> Value {
+ s.active().map(channels_json).unwrap_or(Value::Null)
+}
+
+// ---------------------------------------------------------------------------------------------
+// Registry
+
+macro_rules! spec {
+ ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true }
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!("select.saveSelection", "Save Selection…", ["Select"], None, r##"{"name":str?,"channel":"new"|index|name="new","document":index?,"operation":"new|replace|add|subtract|intersect"="new"}"##, has_selection, save_selection),
+ spec!("select.loadSelection", "Load Selection…", ["Select"], None, r##"{"channel":index|name|"composite"|"red|green|blue|…"|"transparency"|"mask"|"quickMask"|"selection","layer":id?,"document":index?,"invert":bool=false,"operation":"new|add|subtract|intersect"="new"}"##, has_doc, load_selection),
+ spec!("select.editInQuickMaskMode", "Edit in Quick Mask Mode", ["Select"], Some("Q"), r##"{"on":bool?=toggle}"##, has_doc, quick_mask),
+ spec!("image.applyImage", "Apply Image…", ["Image"], None, r##"{"source":{"document":index?,"layer":id|"merged"="merged","channel":"composite"|"red|…"|index|"selection"|"transparency"|"mask"="composite","invert":bool=false},"blending":"normal|multiply|screen|overlay|softLight|hardLight|colorDodge|colorBurn|darken|lighten|difference|exclusion|linearBurn|linearDodge|add|subtract|…"="multiply","opacity":0..100=100,"scale":1..2=1,"offset":-255..255=0,"preserveTransparency":bool=false,"mask":{"document","layer","channel","invert"}?,"sourceChannel|sourceDocument|sourceLayer|sourceInvert|maskChannel|…":flat form of source/mask?}"##, has_apply_target, apply_image),
+ spec!("image.calculations", "Calculations…", ["Image"], None, r##"{"source1":{"document","layer","channel","invert"},"source2":{…},"blending":"multiply|…"="multiply","opacity":0..100=100,"scale":1..2=1,"offset":-255..255=0,"mask":{…}?,"result":"newChannel|newDocument|selection"="newChannel","name":str?}"##, has_doc, calculations),
+ spec!("channel.new", "New Channel…", [], None, r##"{"name":str?,"fill":"black|white|selection"="black","color":"#rrggbb"="#ff0000","opacity":0..100=50,"indicates":"masked|selected"="masked"}"##, has_doc, new_channel),
+ spec!("channel.newSpot", "New Spot Channel…", [], None, r##"{"name":str?,"color":"#rrggbb"="#ff0000","solidity":0..100=0,"fromSelection":bool=true}"##, has_doc, new_spot),
+ spec!("channel.duplicate", "Duplicate Channel…", [], None, r##"{"channel":index|name|"red|…"|"composite"|"quickMask","name":str?,"document":index|"new"?=active,"invert":bool=false}"##, has_doc, duplicate_channel),
+ spec!("channel.delete", "Delete Channel", [], None, r##"{"channel":index|name?=targeted}"##, has_channels, delete_channel),
+ spec!("channel.rename", "Rename Channel", [], None, r##"{"channel":index|name,"name":str}"##, has_channels, rename_channel),
+ spec!("channel.move", "Reorder Channel", [], None, r##"{"channel":index|name,"to":index}"##, has_channels, move_channel),
+ spec!("channel.target", "Target Channel", [], None, r##"{"channel":"composite"|"red|green|blue|…"|index|name="composite"}"##, has_doc, target_cmd),
+ spec!("channel.setVisible", "Channel Visibility", [], None, r##"{"channel":"composite"|"red|…"|index|name|"quickMask","visible":bool?=toggle}"##, has_doc, set_visible),
+ spec!("channel.options", "Channel Options…", [], None, r##"{"channel":index|name|"quickMask","name":str?,"indicates":"masked|selected|spot"?,"color":"#rrggbb"?,"opacity":0..100?,"solidity":0..100?}"##, has_doc, options),
+ spec!("channel.mergeSpot", "Merge Spot Channel", [], None, r##"{"channel":index|name?=targeted or first spot}"##, has_spot, merge_spot),
+ spec!("channel.split", "Split Channels", [], None, r##"{"closeOriginal":bool=true}"##, can_split, split),
+ spec!("channel.merge", "Merge Channels…", [], None, r##"{"mode":"rgb|cmyk|lab"="rgb","documents":[index,…]?=open grayscale docs of the active size,"name":str?}"##, can_merge, merge),
+ CommandSpec { id: "channel.list", label: "Channels", menu: &[], shortcut: None, params: "{}", enabled: has_doc, run: |s, _| Ok(list(s)), journal: false },
+ spec!("channel.target.composite", "Target Composite Channel", [], Some("Cmd+2"), "{}", has_doc, |s, _| target_slot(s, 2)),
+ spec!("channel.target.slot3", "Target Channel 3", [], Some("Cmd+3"), "{}", slot_ok::<3>, |s, _| target_slot(s, 3)),
+ spec!("channel.target.slot4", "Target Channel 4", [], Some("Cmd+4"), "{}", slot_ok::<4>, |s, _| target_slot(s, 4)),
+ spec!("channel.target.slot5", "Target Channel 5", [], Some("Cmd+5"), "{}", slot_ok::<5>, |s, _| target_slot(s, 5)),
+ spec!("channel.target.slot6", "Target Channel 6", [], Some("Cmd+6"), "{}", slot_ok::<6>, |s, _| target_slot(s, 6)),
+ spec!("channel.target.slot7", "Target Channel 7", [], Some("Cmd+7"), "{}", slot_ok::<7>, |s, _| target_slot(s, 7)),
+ spec!("channel.target.slot8", "Target Channel 8", [], Some("Cmd+8"), "{}", slot_ok::<8>, |s, _| target_slot(s, 8)),
+ spec!("channel.target.slot9", "Target Channel 9", [], Some("Cmd+9"), "{}", slot_ok::<9>, |s, _| target_slot(s, 9)),
+ ]
+}
+
+fn slot_ok<const N: usize>(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ let colors = color_count(&d.doc);
+ let shown = if colors > 1 { colors } else { 0 };
+ if N - 3 < shown + d.doc.channels.len() { Ok(()) } else { Err(format!("no channel for ⌘{N}")) }
+}
+
+fn has_apply_target(s: &Session) -> std::result::Result<(), String> {
+ if edits_channel(s) {
+ return Ok(());
+ }
+ has_layer(s)?;
+ let d = s.active().expect("checked");
+ let l = d.doc.layer(d.active_layer.expect("checked")).expect("checked");
+ if matches!(l.content, LayerContent::Raster(_)) { Ok(()) } else { Err(format!("Apply Image needs a pixel layer (active layer is a {} layer)", l.content.kind_name())) }
+}
diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs
new file mode 100644
index 000000000..f2391c3cf
--- /dev/null
+++ b/crates/engine/src/channel_cmds/tests.rs
@@ -0,0 +1,444 @@
+use super::*;
+use photocraft_color::SampleType;
+
+fn session_depth(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth})).unwrap();
+ s
+}
+
+fn session() -> Session {
+ session_depth(8)
+}
+
+fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+}
+
+fn chan(s: &Session, i: usize, x: i32, y: i32) -> f32 {
+ doc(s).channels[i].surface.sample_channel(x, y, 0)
+}
+
+fn sel_at(s: &Session, x: i32, y: i32) -> f32 {
+ doc(s).selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0))
+}
+
+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)
+}
+
+fn rect(s: &mut Session, x: i32, y: i32, w: u32, h: u32, mode: &str) {
+ s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h, "mode": mode})).unwrap();
+}
+
+#[test]
+fn specs_are_documented_and_registered() {
+ for sp in specs() {
+ assert!(crate::commands::find(sp.id).is_some(), "{} not registered", sp.id);
+ assert!(sp.params.starts_with('{'), "{}", sp.id);
+ }
+}
+
+#[test]
+fn save_selection_new_and_operations() {
+ for depth in [8, 16, 32] {
+ let mut s = session_depth(depth);
+ assert!(s.execute("select.saveSelection", json!({})).is_err(), "needs a selection");
+ rect(&mut s, 0, 0, 10, 20, "replace");
+ let r = s.execute("select.saveSelection", json!({})).unwrap();
+ assert_eq!(r["channel"], 0);
+ assert_eq!(r["name"], "Alpha 1");
+ let d = doc(&s);
+ assert_eq!(d.channels[0].surface.format(), channel_format(d));
+ assert_eq!(d.channels[0].surface.format().sample, SampleType::ALL[[8, 16, 32].iter().position(|v| *v == depth).unwrap()]);
+ assert_eq!(chan(&s, 0, 5, 5), 1.0);
+ assert_eq!(chan(&s, 0, 15, 5), 0.0);
+
+ // add / subtract / intersect / replace into the existing channel
+ rect(&mut s, 5, 0, 10, 20, "replace");
+ s.execute("select.saveSelection", json!({"channel": 0, "operation": "add"})).unwrap();
+ assert_eq!((chan(&s, 0, 2, 5), chan(&s, 0, 12, 5), chan(&s, 0, 20, 5)), (1.0, 1.0, 0.0));
+ rect(&mut s, 0, 0, 3, 20, "replace");
+ s.execute("select.saveSelection", json!({"channel": 0, "operation": "subtract"})).unwrap();
+ assert_eq!((chan(&s, 0, 1, 5), chan(&s, 0, 5, 5)), (0.0, 1.0));
+ rect(&mut s, 10, 0, 30, 20, "replace");
+ s.execute("select.saveSelection", json!({"channel": "Alpha 1", "operation": "intersect"})).unwrap();
+ assert_eq!((chan(&s, 0, 5, 5), chan(&s, 0, 12, 5)), (0.0, 1.0));
+ s.execute("select.saveSelection", json!({"channel": 0, "operation": "replace", "name": "Mine"})).unwrap();
+ assert_eq!((chan(&s, 0, 5, 5), chan(&s, 0, 30, 5)), (0.0, 1.0));
+ assert_eq!(doc(&s).channels[0].name, "Mine");
+ assert!(s.execute("select.saveSelection", json!({"operation": "bogus"})).is_err());
+ assert!(s.execute("select.saveSelection", json!({"channel": 7, "operation": "add"})).is_err());
+ }
+}
+
+#[test]
+fn load_selection_operations_and_invert() {
+ let mut s = session();
+ rect(&mut s, 0, 0, 20, 20, "replace");
+ s.execute("select.saveSelection", json!({})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("select.loadSelection", json!({"channel": 0})).unwrap();
+ assert_eq!((sel_at(&s, 5, 5), sel_at(&s, 25, 5)), (1.0, 0.0));
+ s.execute("select.loadSelection", json!({"channel": 0, "invert": true})).unwrap();
+ assert_eq!((sel_at(&s, 5, 5), sel_at(&s, 25, 5)), (0.0, 1.0));
+ rect(&mut s, 10, 0, 20, 20, "replace");
+ s.execute("select.loadSelection", json!({"channel": 0, "operation": "add"})).unwrap();
+ assert_eq!((sel_at(&s, 5, 5), sel_at(&s, 25, 5), sel_at(&s, 35, 5)), (1.0, 1.0, 0.0));
+ rect(&mut s, 10, 0, 20, 20, "replace");
+ s.execute("select.loadSelection", json!({"channel": 0, "operation": "subtract"})).unwrap();
+ assert_eq!((sel_at(&s, 15, 5), sel_at(&s, 25, 5)), (0.0, 1.0));
+ rect(&mut s, 10, 0, 20, 20, "replace");
+ s.execute("select.loadSelection", json!({"channel": "Alpha 1", "operation": "intersect"})).unwrap();
+ assert_eq!((sel_at(&s, 15, 5), sel_at(&s, 25, 5)), (1.0, 0.0));
+ assert!(s.execute("select.loadSelection", json!({})).is_err());
+ assert!(s.execute("select.loadSelection", json!({"channel": 0, "operation": "xor"})).is_err());
+ // undo restores the previous selection
+ s.undo();
+ assert_eq!(sel_at(&s, 25, 5), 1.0);
+}
+
+#[test]
+fn load_transparency_mask_and_composite() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 20, "height": 10, "background": "transparent"})).unwrap();
+ rect(&mut s, 0, 0, 5, 10, "replace");
+ s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("select.loadSelection", json!({"channel": "transparency"})).unwrap();
+ assert_eq!((sel_at(&s, 2, 2), sel_at(&s, 10, 2)), (1.0, 0.0));
+ // Composite luminosity: white = selected; transparent over nothing = black.
+ s.execute("select.loadSelection", json!({"channel": "composite"})).unwrap();
+ assert!(sel_at(&s, 2, 2) > 0.99);
+ s.execute("select.loadSelection", json!({"channel": "red"})).unwrap();
+ assert!(sel_at(&s, 2, 2) > 0.99);
+ // Layer mask
+ assert!(s.execute("select.loadSelection", json!({"channel": "mask"})).is_err());
+ s.execute("layer.layerMask.hideAll", json!({})).unwrap();
+ s.execute("select.loadSelection", json!({"channel": "mask", "invert": true})).unwrap();
+ assert_eq!(sel_at(&s, 10, 5), 1.0);
+}
+
+#[test]
+fn channel_management_and_view_state() {
+ let mut s = session();
+ let r = s.execute("channel.new", json!({"fill": "white", "name": "W"})).unwrap();
+ assert_eq!(r["channel"], 0);
+ assert_eq!(chan(&s, 0, 3, 3), 1.0);
+ // A new channel is targeted and shown alone.
+ let st = s.active().unwrap();
+ assert_eq!(st.channel_view.target, ChannelTarget::Alpha(0));
+ assert!(st.channel_view.alpha_shown(0) && st.channel_view.visible_colors(3) == 0);
+ s.execute("channel.new", json!({})).unwrap();
+ assert_eq!(doc(&s).channels[1].name, "Alpha 1");
+ s.execute("channel.duplicate", json!({"channel": 0})).unwrap();
+ assert_eq!(doc(&s).channels[2].name, "W copy");
+ s.execute("channel.duplicate", json!({"channel": "red", "invert": true})).unwrap();
+ assert_eq!(doc(&s).channels[3].name, "Red copy");
+ assert_eq!(chan(&s, 3, 1, 1), 0.0, "white image, inverted");
+ s.execute("channel.rename", json!({"channel": 1, "name": "Renamed"})).unwrap();
+ assert!(s.execute("channel.rename", json!({"channel": 1, "name": " "})).is_err());
+ s.execute("channel.move", json!({"channel": "Renamed", "to": 0})).unwrap();
+ let names: Vec<_> = doc(&s).channels.iter().map(|c| c.name.clone()).collect();
+ assert_eq!(names, ["Renamed", "W", "W copy", "Red copy"]);
+ s.execute("channel.target", json!({"channel": 1})).unwrap();
+ s.execute("channel.delete", json!({"channel": 0})).unwrap();
+ assert_eq!(s.active().unwrap().channel_view.target, ChannelTarget::Alpha(0), "target follows its channel");
+ s.execute("channel.delete", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().channel_view.target, ChannelTarget::Composite);
+ assert_eq!(doc(&s).channels.len(), 2);
+ // Visibility toggles (eye) for colour, composite, alpha.
+ s.execute("channel.setVisible", json!({"channel": "blue", "visible": false})).unwrap();
+ assert!(!s.active().unwrap().channel_view.color_visible(2));
+ s.execute("channel.setVisible", json!({"channel": "composite"})).unwrap();
+ assert_eq!(s.active().unwrap().channel_view.visible_colors(3), 3);
+ s.execute("channel.setVisible", json!({"channel": 1})).unwrap();
+ assert!(s.active().unwrap().channel_view.alpha_shown(1));
+ assert!(!s.active().unwrap().channel_view.is_plain(doc(&s)));
+ // Viewing state doesn't dirty or add history.
+ let hist = s.active().unwrap().history.entries().len();
+ s.execute("channel.target", json!({"channel": "green"})).unwrap();
+ assert_eq!(s.active().unwrap().history.entries().len(), hist);
+ let j = s.execute("channel.list", json!({})).unwrap();
+ assert_eq!(j["target"]["kind"], "color");
+ assert_eq!(j["alpha"].as_array().unwrap().len(), 2);
+ // Undo of the delete brings the channel back; the view stays valid.
+ s.undo();
+ assert_eq!(doc(&s).channels.len(), 3);
+}
+
+#[test]
+fn shortcut_slots_target_channels() {
+ let mut s = session();
+ s.execute("channel.new", json!({})).unwrap();
+ s.execute("channel.target.slot3", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().channel_view.target, ChannelTarget::Color(0));
+ s.execute("channel.target.slot6", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().channel_view.target, ChannelTarget::Alpha(0));
+ assert!(!s.is_enabled("channel.target.slot7"));
+ s.execute("channel.target.composite", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().channel_view.target, ChannelTarget::Composite);
+ // Grayscale: ⌘3 is the first alpha channel.
+ let mut g = Session::new();
+ g.execute("file.new", json!({"width": 4, "height": 4, "mode": "gray"})).unwrap();
+ g.execute("channel.new", json!({})).unwrap();
+ g.execute("channel.target.slot3", json!({})).unwrap();
+ assert_eq!(g.active().unwrap().channel_view.target, ChannelTarget::Alpha(0));
+}
+
+#[test]
+fn painting_filtering_and_adjusting_into_an_alpha_channel() {
+ for depth in [8, 16, 32] {
+ let mut s = session_depth(depth);
+ s.execute("channel.new", json!({})).unwrap();
+ let before = px(&s, 10, 10);
+ // Targeted channel: the stroke goes into the channel, not the layer.
+ s.execute("paint.stroke", json!({"points": [[10, 10]], "size": 8, "hardness": 1.0, "color": "#ffffff"})).unwrap();
+ assert!(chan(&s, 0, 10, 10) > 0.99, "depth {depth}");
+ assert_eq!(chan(&s, 0, 30, 10), 0.0);
+ assert_eq!(px(&s, 10, 10), before);
+ // Erasing paints the background colour (white) on channels; use black foreground fill.
+ s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
+ assert!((chan(&s, 0, 30, 10) - 0.5).abs() < 0.01);
+ // Adjustments apply to the channel (also where it was untouched).
+ s.execute("image.adjustments.invert", json!({})).unwrap();
+ assert!((chan(&s, 0, 30, 10) - 0.5).abs() < 0.01);
+ assert_eq!(px(&s, 10, 10), before, "layer untouched by the adjustment");
+ // Filters too, limited by the selection.
+ s.execute("channel.new", json!({})).unwrap();
+ s.execute("paint.stroke", json!({"points": [[20, 10]], "size": 6, "hardness": 1.0, "color": "#ffffff"})).unwrap();
+ rect(&mut s, 0, 0, 20, 20, "replace");
+ s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap();
+ assert!(chan(&s, 1, 16, 10) > 0.0, "blurred inside the selection");
+ assert_eq!(chan(&s, 1, 26, 10), 0.0, "outside the selection untouched");
+ // Explicit targets work without targeting the channel.
+ s.execute("channel.target", json!({"channel": "composite"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("paint.bucket", json!({"x": 1, "y": 1, "color": "#ffffff", "target": {"channel": 1}, "tolerance": 0})).unwrap();
+ assert_eq!(chan(&s, 1, 1, 1), 1.0);
+ assert!(s.execute("paint.stroke", json!({"points": [[1, 1]], "target": {"channel": 9}})).is_err());
+ // Undo restores the channel.
+ s.undo();
+ assert_eq!(chan(&s, 1, 1, 1), 0.0);
+ }
+}
+
+#[test]
+fn single_colour_channel_target_limits_edits() {
+ let mut s = session();
+ s.execute("channel.target", json!({"channel": "red"})).unwrap();
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ assert_eq!(px(&s, 5, 5), vec![0.0, 1.0, 1.0, 1.0]);
+ s.execute("channel.target", json!({"channel": "blue"})).unwrap();
+ s.execute("paint.stroke", json!({"points": [[20, 10]], "size": 6, "hardness": 1.0, "color": "#000000"})).unwrap();
+ assert_eq!(px(&s, 20, 10), vec![0.0, 1.0, 0.0, 1.0]);
+ s.execute("channel.target", json!({"channel": "composite"})).unwrap();
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ assert_eq!(px(&s, 5, 5), vec![0.0, 0.0, 0.0, 1.0]);
+}
+
+#[test]
+fn quick_mask_enter_paint_exit() {
+ let mut s = session();
+ rect(&mut s, 0, 0, 20, 20, "replace");
+ s.execute("select.editInQuickMaskMode", json!({})).unwrap();
+ let d = doc(&s);
+ let q = d.quick_mask.as_ref().unwrap();
+ assert!(d.selection.is_none());
+ assert_eq!((q.surface.sample_channel(5, 5, 0), q.surface.sample_channel(30, 5, 0)), (1.0, 0.0));
+ assert_eq!((q.opacity, q.indicates), (0.5, ColorIndicates::MaskedAreas));
+ // Painting black masks; white unmasks. The layer is untouched.
+ let before = px(&s, 5, 5);
+ s.execute("paint.stroke", json!({"points": [[5, 5]], "size": 4, "hardness": 1.0, "color": "#000000"})).unwrap();
+ s.execute("paint.stroke", json!({"points": [[30, 10]], "size": 4, "hardness": 1.0, "color": "#ffffff"})).unwrap();
+ assert_eq!(px(&s, 5, 5), before);
+ s.execute("select.editInQuickMaskMode", json!({})).unwrap();
+ assert!(doc(&s).quick_mask.is_none());
+ assert_eq!(sel_at(&s, 5, 5), 0.0, "painted black: masked");
+ assert_eq!(sel_at(&s, 12, 12), 1.0);
+ assert_eq!(sel_at(&s, 30, 10), 1.0, "painted white: selected");
+ assert_eq!(sel_at(&s, 35, 2), 0.0);
+ // History: enter and exit are steps; undo goes back into Quick Mask with the paint.
+ let labels: Vec<String> = s.active().unwrap().history.entries().iter().map(|e| e.to_string()).collect();
+ assert!(labels.iter().any(|l| l.contains("Edit in Quick Mask")) && labels.iter().any(|l| l.contains("Exit Quick Mask")), "{labels:?}");
+ s.undo();
+ assert!(doc(&s).quick_mask.is_some());
+ assert!(doc(&s).selection.is_none());
+ s.redo();
+ assert!(doc(&s).quick_mask.is_none());
+ assert_eq!(sel_at(&s, 30, 10), 1.0);
+}
+
+#[test]
+fn quick_mask_without_selection_and_options() {
+ let mut s = session();
+ s.execute("channel.options", json!({"channel": "quickMask", "color": "#0000ff", "opacity": 30})).unwrap();
+ s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
+ let q = doc(&s).quick_mask.clone().unwrap();
+ assert_eq!(q.color, Color::rgb(0.0, 0.0, 1.0));
+ assert!((q.opacity - 0.3).abs() < 1e-6);
+ // Leaving an untouched Quick Mask leaves no selection.
+ s.execute("select.editInQuickMaskMode", json!({"on": false})).unwrap();
+ assert!(doc(&s).selection.is_none());
+ // A filter in Quick Mask edits the mask.
+ s.execute("select.editInQuickMaskMode", json!({})).unwrap();
+ s.execute("paint.stroke", json!({"points": [[10, 10]], "size": 12, "hardness": 1.0, "color": "#000000"})).unwrap();
+ s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap();
+ let v = doc(&s).quick_mask.as_ref().unwrap().surface.sample_channel(16, 10, 0);
+ assert!(v > 0.0 && v < 1.0, "feathered edge {v}");
+ s.execute("select.editInQuickMaskMode", json!({})).unwrap();
+ assert!(sel_at(&s, 10, 10) < 0.05 && sel_at(&s, 30, 10) > 0.99, "{} {}", sel_at(&s, 10, 10), sel_at(&s, 30, 10));
+}
+
+#[test]
+fn channel_options_and_spot_channels() {
+ let mut s = session();
+ rect(&mut s, 0, 0, 10, 10, "replace");
+ s.execute("channel.new", json!({"fill": "selection"})).unwrap();
+ s.execute("channel.options", json!({"channel": 0, "name": "Opt", "color": "#00ff00", "opacity": 25, "indicates": "selected"})).unwrap();
+ let c = &doc(&s).channels[0];
+ assert_eq!((c.name.as_str(), c.color, c.indicates), ("Opt", Color::rgb(0.0, 1.0, 0.0), ColorIndicates::SelectedAreas));
+ assert!((c.opacity - 0.25).abs() < 1e-6);
+ assert_eq!(c.overlay_coverage(1.0), 1.0);
+ s.execute("channel.options", json!({"channel": 0, "indicates": "spot", "solidity": 40})).unwrap();
+ assert_eq!(doc(&s).channels[0].spot.map(|x| x.1), Some(0.4));
+ let r = s.execute("channel.newSpot", json!({"color": "#ff00ff", "solidity": 100})).unwrap();
+ let i = r["channel"].as_u64().unwrap() as usize;
+ assert_eq!(doc(&s).channels[i].name, "Spot Color 1");
+ assert_eq!(chan(&s, i, 5, 5), 1.0, "from the selection");
+ // Merge spot: flattens and prints the ink (solid magenta) into the image.
+ s.execute("channel.mergeSpot", json!({"channel": i})).unwrap();
+ let d = doc(&s);
+ assert_eq!(d.layers.len(), 1);
+ assert_eq!(d.channels.len(), 1);
+ let p = px(&s, 5, 5);
+ assert!((p[0] - 1.0).abs() < 0.01 && p[1] < 0.01 && (p[2] - 1.0).abs() < 0.01, "{p:?}");
+ assert_eq!(px(&s, 20, 15)[..3], [1.0, 1.0, 1.0]);
+}
+
+#[test]
+fn apply_image_hand_computed() {
+ let mut s = session();
+ // Target: 50% gray. Source: a second document, red #ff0000 / 50% gray.
+ s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
+ s.execute("file.new", json!({"width": 40, "height": 20})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff4000"})).unwrap();
+ s.set_active(0);
+ let g = 128.0 / 255.0;
+ s.execute("image.applyImage", json!({"source": {"document": 1}, "blending": "multiply"})).unwrap();
+ let p = px(&s, 3, 3);
+ assert!((p[0] - g).abs() < 0.003 && (p[1] - g * 64.0 / 255.0).abs() < 0.003 && p[2].abs() < 0.003, "{p:?}");
+ s.undo();
+ // Single source channel applied to every target channel, screen at 50% opacity, inverted.
+ s.execute("image.applyImage", json!({"source": {"document": 1, "channel": "green", "invert": true}, "blending": "screen", "opacity": 50})).unwrap();
+ let top = 1.0 - 64.0 / 255.0;
+ let screen = 1.0 - (1.0 - g) * (1.0 - top);
+ let want = g + (screen - g) * 0.5;
+ let p = px(&s, 3, 3);
+ assert!(p[..3].iter().all(|v| (v - want).abs() < 0.003), "{p:?} vs {want}");
+ s.undo();
+ // Add with scale and offset; masked by an alpha channel; limited to the selection.
+ s.execute("channel.new", json!({"fill": "white"})).unwrap();
+ s.execute("channel.target", json!({"channel": "composite"})).unwrap();
+ rect(&mut s, 0, 0, 20, 20, "replace");
+ s.execute("image.applyImage", json!({"source": {"document": 1, "channel": "red"}, "blending": "add", "scale": 2, "offset": -10, "mask": {"channel": 0}})).unwrap();
+ let want = ((g + 1.0) / 2.0 - 10.0 / 255.0).clamp(0.0, 1.0);
+ assert!((px(&s, 3, 3)[1] - want).abs() < 0.003);
+ assert!((px(&s, 30, 3)[1] - g).abs() < 0.003, "outside the selection");
+ // Size mismatch is refused.
+ s.execute("file.new", json!({"width": 5, "height": 5})).unwrap();
+ s.set_active(0);
+ assert!(s.execute("image.applyImage", json!({"source": {"document": 2}})).is_err());
+ assert!(s.execute("image.applyImage", json!({"blending": "hue"})).is_err());
+}
+
+#[test]
+fn apply_image_into_alpha_channel() {
+ let mut s = session();
+ s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap();
+ s.execute("channel.new", json!({"fill": "white"})).unwrap();
+ // Targeted channel: Normal blend of the inverted composite → black.
+ s.execute("image.applyImage", json!({"source": {"channel": "composite", "invert": true}, "blending": "normal"})).unwrap();
+ assert!(chan(&s, 0, 3, 3) < 0.01);
+}
+
+#[test]
+fn calculations_results() {
+ let mut s = session();
+ rect(&mut s, 0, 0, 20, 20, "replace");
+ s.execute("select.saveSelection", json!({})).unwrap();
+ rect(&mut s, 10, 0, 20, 20, "replace");
+ s.execute("select.saveSelection", json!({})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ // Multiply = intersection of the two masks.
+ let r = s.execute("image.calculations", json!({"source1": {"channel": 0}, "source2": {"channel": 1}, "blending": "multiply", "name": "X"})).unwrap();
+ let i = r["channel"].as_u64().unwrap() as usize;
+ assert_eq!(doc(&s).channels[i].name, "X");
+ assert_eq!((chan(&s, i, 5, 5), chan(&s, i, 15, 5), chan(&s, i, 25, 5)), (0.0, 1.0, 0.0));
+ // Screen = union, at 50% opacity; source 1 inverted.
+ s.execute("image.calculations", json!({"source1": {"channel": 0, "invert": true}, "source2": {"channel": 1}, "blending": "difference", "result": "selection"})).unwrap();
+ // |s2 - (1 - s1)|: x=5: |0-0|=0, x=15: |1-0|=1, x=35: |0-1|=1
+ assert_eq!((sel_at(&s, 5, 5), sel_at(&s, 15, 5), sel_at(&s, 35, 5)), (0.0, 1.0, 1.0));
+ let r = s.execute("image.calculations", json!({"source1": {"channel": "composite"}, "source2": {"channel": 1}, "blending": "normal", "opacity": 50, "result": "newDocument"})).unwrap();
+ assert_eq!(r["document"], 1);
+ let d = doc(&s);
+ assert_eq!(d.mode, ColorMode::Grayscale);
+ let v = d.layers[0].surface().unwrap().pixel(5, 5)[0];
+ assert!((v - 0.5).abs() < 0.01, "{v}");
+ s.set_active(0);
+ assert!(s.execute("image.calculations", json!({"source1": {"channel": 0}, "source2": {"channel": 1}, "result": "x"})).is_err());
+}
+
+#[test]
+fn split_and_merge_channels() {
+ let mut s = session();
+ s.execute("edit.fill", json!({"color": "#ff8000"})).unwrap();
+ s.execute("channel.new", json!({"fill": "white", "name": "A"})).unwrap();
+ let r = s.execute("channel.split", json!({})).unwrap();
+ assert_eq!(r["documents"].as_array().unwrap().len(), 4);
+ assert_eq!(s.documents().len(), 4, "original closed");
+ let names: Vec<_> = s.documents().iter().map(|d| d.doc.name.clone()).collect();
+ assert_eq!(names, ["Untitled_R", "Untitled_G", "Untitled_B", "Untitled_A"]);
+ let v = |s: &Session, i: usize| s.documents()[i].doc.layers[0].surface().unwrap().pixel(1, 1)[0];
+ assert_eq!(v(&s, 0), 1.0);
+ assert!((v(&s, 1) - 128.0 / 255.0).abs() < 0.003);
+ assert_eq!(v(&s, 2), 0.0);
+ // Merge the three colour docs back (order: active first, then the rest).
+ s.set_active(0);
+ let r = s.execute("channel.merge", json!({"mode": "rgb", "documents": [0, 1, 2]})).unwrap();
+ assert_eq!(s.documents().len(), 2);
+ assert_eq!(r["document"], 1);
+ let p = px(&s, 1, 1);
+ assert!((p[0] - 1.0).abs() < 0.003 && (p[1] - 128.0 / 255.0).abs() < 0.003 && p[2].abs() < 0.003, "{p:?}");
+ assert!(s.execute("channel.merge", json!({"mode": "cmyk"})).is_err());
+}
+
+#[test]
+fn duplicate_to_other_document() {
+ let mut s = session();
+ rect(&mut s, 0, 0, 5, 5, "replace");
+ s.execute("select.saveSelection", json!({"name": "S"})).unwrap();
+ s.execute("file.new", json!({"width": 40, "height": 20, "depth": 16})).unwrap();
+ s.set_active(0);
+ s.execute("channel.duplicate", json!({"channel": "S", "document": 1, "name": "S2"})).unwrap();
+ let d1 = &s.documents()[1].doc;
+ assert_eq!(d1.channels[0].name, "S2");
+ assert_eq!(d1.channels[0].surface.format().sample, SampleType::U16);
+ assert_eq!(d1.channels[0].surface.sample_channel(2, 2, 0), 1.0);
+ let r = s.execute("channel.duplicate", json!({"channel": 0, "document": "new"})).unwrap();
+ assert_eq!(s.documents()[r["document"].as_u64().unwrap() as usize].doc.mode, ColorMode::Grayscale);
+}
+
+#[test]
+fn image_size_and_rotate_carry_channels_and_quick_mask() {
+ let mut s = session();
+ rect(&mut s, 0, 0, 10, 20, "replace");
+ s.execute("select.saveSelection", json!({})).unwrap();
+ s.execute("select.editInQuickMaskMode", json!({})).unwrap();
+ s.execute("image.imageRotation.180", json!({})).unwrap();
+ s.execute("image.mode.bits16", json!({})).unwrap();
+ let d = doc(&s);
+ assert_eq!(d.channels[0].surface.format().sample, SampleType::U16);
+ assert_eq!(d.quick_mask.as_ref().unwrap().surface.format().sample, SampleType::U16);
+}
diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs
new file mode 100644
index 000000000..3108bb094
--- /dev/null
+++ b/crates/engine/src/color_cmds.rs
@@ -0,0 +1,1146 @@
+//! Colour management commands and helpers: document profiles (Edit › Assign / Convert to
+//! Profile), CMS-based Image › Mode conversions, soft proofing (View › Proof Setup / Proof
+//! Colors / Gamut Warning) and the display transform the canvas applies.
+//!
+//! Document space: `Document::icc_profile` holds the document's ICC bytes (kept byte-exact
+//! from PSD resource 1039 / PNG iCCP / JPEG APP2 / TIFF). `None` means untagged: the working
+//! profile of the mode is assumed (sRGB, sGray, the built-in coated CMYK, Lab D50).
+//!
+//! Compositing stays in document space for RGB and gray documents. CMYK and Lab documents are
+//! composited in sRGB after a per-layer conversion with the built-in profiles (see
+//! `photocraft_color::convert`), so their [`composite_profile`] is sRGB; documents tagged with
+//! a different CMYK profile therefore display approximately until compositing is mode-native.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, Weak};
+
+use photocraft_cms::{Builtin, ColorSpace, GamutCheck, Intent, Lut3d, Profile, SampleKind, Transform};
+use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
+use photocraft_doc::{DocId, Document, Effect, Fill, FxPaint, Layer, LayerContent};
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+// ------------------------------------------------------------------ state
+
+/// View › Proof Setup settings.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ProofSetup {
+ /// What the user asked for (built-in id or path), for display.
+ pub name: String,
+ pub profile: Arc<Profile>,
+ pub intent: Intent,
+ pub bpc: bool,
+ /// Simulate paper colour (absolute colorimetric proof → display, black ink simulated).
+ pub simulate_paper: bool,
+}
+
+impl Default for ProofSetup {
+ fn default() -> Self {
+ ProofSetup {
+ name: Builtin::CoatedCmyk.id().into(),
+ profile: Arc::new(Builtin::CoatedCmyk.profile().clone()),
+ intent: Intent::RelativeColorimetric,
+ bpc: true,
+ simulate_paper: false,
+ }
+ }
+}
+
+/// Per-document proofing state the UI reads (see [`ColorState::proof`]).
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct ProofView {
+ pub setup: ProofSetup,
+ /// View › Proof Colors.
+ pub enabled: bool,
+ /// View › Gamut Warning.
+ pub gamut_warning: bool,
+ pub gamut_threshold: f32,
+}
+
+type DisplayKey = (u64, u64, Option<(u64, Intent, bool, bool)>);
+
+/// Colour management policy for documents whose embedded profile differs from the working
+/// space (Edit › Color Settings).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Policy {
+ /// Keep the embedded profile.
+ #[default]
+ Preserve,
+ /// Convert the pixels to the working space.
+ Convert,
+ /// Discard the embedded profile (the document is assumed to be in the working space).
+ Off,
+}
+
+impl Policy {
+ pub fn id(self) -> &'static str {
+ match self {
+ Policy::Preserve => "preserve",
+ Policy::Convert => "convert",
+ Policy::Off => "off",
+ }
+ }
+ pub fn parse(s: &str) -> Option<Policy> {
+ match s {
+ "preserve" | "preserveEmbedded" => Some(Policy::Preserve),
+ "convert" | "convertToWorking" => Some(Policy::Convert),
+ "off" => Some(Policy::Off),
+ _ => None,
+ }
+ }
+}
+
+/// Edit › Color Settings: working spaces, colour management policies and conversion options.
+/// Honoured when files are opened ([`Session::open_document`]), by Image › Mode conversions
+/// and by "working" profile specs (Convert to Profile, Proof Setup).
+#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct ColorSettings {
+ /// Working spaces: built-in profile ids (see `edit.profileInfo`) or `.icc` paths.
+ pub working_rgb: String,
+ pub working_cmyk: String,
+ pub working_gray: String,
+ pub policy_rgb: Policy,
+ pub policy_cmyk: Policy,
+ pub policy_gray: Policy,
+ /// Ask what to do when an opened file's embedded profile differs from the working space.
+ pub ask_on_mismatch: bool,
+ pub ask_on_paste: bool,
+ /// Ask when an opened file has no profile.
+ pub ask_on_missing: bool,
+ /// Conversion options: rendering intent and black point compensation.
+ pub intent: String,
+ pub bpc: bool,
+ pub dither: bool,
+}
+
+impl Default for ColorSettings {
+ fn default() -> Self {
+ Self {
+ working_rgb: Builtin::Srgb.id().into(),
+ working_cmyk: Builtin::CoatedCmyk.id().into(),
+ working_gray: Builtin::SGray.id().into(),
+ policy_rgb: Policy::Preserve,
+ policy_cmyk: Policy::Preserve,
+ policy_gray: Policy::Preserve,
+ ask_on_mismatch: true,
+ ask_on_paste: true,
+ ask_on_missing: false,
+ intent: Intent::RelativeColorimetric.id().into(),
+ bpc: true,
+ dither: true,
+ }
+ }
+}
+
+impl ColorSettings {
+ pub fn intent(&self) -> Intent {
+ Intent::parse(&self.intent).unwrap_or(Intent::RelativeColorimetric)
+ }
+ /// Policy for documents in `mode`'s colour space (Lab documents are never converted).
+ pub fn policy(&self, mode: ColorMode) -> Policy {
+ match mode_space(mode) {
+ ColorSpace::Cmyk => self.policy_cmyk,
+ ColorSpace::Gray => self.policy_gray,
+ ColorSpace::Rgb => self.policy_rgb,
+ _ => Policy::Preserve,
+ }
+ }
+ fn working_spec(&self, space: ColorSpace) -> Option<&str> {
+ Some(match space {
+ ColorSpace::Rgb => &self.working_rgb,
+ ColorSpace::Cmyk => &self.working_cmyk,
+ ColorSpace::Gray => &self.working_gray,
+ _ => return None,
+ })
+ }
+}
+
+/// Check that each working space resolves to a profile of the right colour space.
+pub fn validate_settings(c: &ColorSettings) -> std::result::Result<(), String> {
+ for (space, spec) in [(ColorSpace::Rgb, &c.working_rgb), (ColorSpace::Cmyk, &c.working_cmyk), (ColorSpace::Gray, &c.working_gray)] {
+ let p = resolve_profile(spec, None, space_mode(space)).map_err(|e| e.to_string())?;
+ if p.color_space != space {
+ return Err(format!("working space `{spec}` is {:?}, not {space:?}", p.color_space));
+ }
+ }
+ if Intent::parse(&c.intent).is_none() {
+ return Err(format!("unknown intent `{}` (perceptual|relative|saturation|absolute)", c.intent));
+ }
+ Ok(())
+}
+
+/// Session-wide colour settings and caches (`Session::color`).
+#[derive(Default)]
+pub struct ColorState {
+ /// Edit › Color Settings (persisted with the preferences).
+ pub settings: ColorSettings,
+ proofs: HashMap<DocId, ProofView>,
+ /// Monitor profile bytes supplied by the platform (`None` = sRGB display).
+ pub monitor_profile: Option<Arc<Vec<u8>>>,
+ display_cache: Mutex<HashMap<DisplayKey, Arc<Transform>>>,
+}
+
+impl ColorState {
+ /// The working profile of a mode from Color Settings (the built-in default when the
+ /// setting does not resolve).
+ pub fn working(&self, mode: ColorMode) -> Arc<Profile> {
+ let space = mode_space(mode);
+ self.settings
+ .working_spec(space)
+ .and_then(|spec| resolve_profile(spec, None, Some(mode)).ok())
+ .filter(|p| p.color_space == space)
+ .unwrap_or_else(|| working_profile(mode))
+ }
+
+ /// Resolve a profile spec, reading "working…" specs from Color Settings.
+ pub fn resolve(&self, spec: &str, doc: Option<&Document>, mode: Option<ColorMode>) -> Result<Arc<Profile>> {
+ match spec {
+ "working" | "default" => Ok(self.working(mode.or(doc.map(|d| d.mode)).unwrap_or(ColorMode::Rgb))),
+ "working-cmyk" | "workingCmyk" => Ok(self.working(ColorMode::Cmyk)),
+ "working-rgb" | "workingRgb" => Ok(self.working(ColorMode::Rgb)),
+ "working-gray" | "workingGray" => Ok(self.working(ColorMode::Grayscale)),
+ _ => resolve_profile(spec, doc, mode),
+ }
+ }
+
+ /// Apply the colour management policy to a document being opened. Returns what happened
+ /// (`action`: kept|converted|discarded|assigned|untagged) and whether to ask the user.
+ pub fn open_policy(&self, doc: &mut Document) -> Value {
+ let space = mode_space(doc.mode);
+ if !matches!(space, ColorSpace::Rgb | ColorSpace::Cmyk | ColorSpace::Gray) {
+ return json!({"action": "kept"});
+ }
+ let working = self.working(doc.mode);
+ let policy = self.settings.policy(doc.mode);
+ let embedded = doc.icc_profile.as_ref().and_then(|b| profile_from_bytes(b).ok()).filter(|p| p.color_space == space);
+ match embedded {
+ Some(emb) => {
+ let mismatch = emb.content_hash() != working.content_hash();
+ let base = json!({"embedded": emb.description, "working": working.description, "mismatch": mismatch, "policy": policy.id()});
+ if !mismatch {
+ return merge(base, json!({"action": "kept"}));
+ }
+ let action = match policy {
+ Policy::Preserve => "kept",
+ Policy::Off => {
+ doc.icc_profile = None;
+ "discarded"
+ }
+ Policy::Convert => match convert_document(doc, &working, self.settings.intent(), self.settings.bpc) {
+ Ok(()) => "converted",
+ Err(_) => "kept",
+ },
+ };
+ merge(base, json!({"action": action, "ask": self.settings.ask_on_mismatch}))
+ }
+ None => {
+ // Untagged files are assumed to be in the working space; tag them when it is not
+ // the built-in default so they display (and save) as intended.
+ let default = working_profile(doc.mode);
+ let assign = policy != Policy::Off && working.content_hash() != default.content_hash();
+ if assign {
+ doc.icc_profile = Some(working.to_bytes());
+ }
+ json!({"action": if assign { "assigned" } else { "untagged" }, "working": working.description, "policy": policy.id(), "ask": self.settings.ask_on_missing, "missing": true})
+ }
+ }
+ }
+
+ /// Proofing state of a document (defaults: coated CMYK, relative colorimetric + BPC, off).
+ pub fn proof(&self, doc: DocId) -> ProofView {
+ self.proofs.get(&doc).cloned().unwrap_or_else(|| ProofView { gamut_threshold: photocraft_cms::gamut::DEFAULT_THRESHOLD, ..Default::default() })
+ }
+
+ fn proof_mut(&mut self, doc: DocId) -> &mut ProofView {
+ self.proofs.entry(doc).or_insert_with(|| ProofView { gamut_threshold: photocraft_cms::gamut::DEFAULT_THRESHOLD, ..Default::default() })
+ }
+
+ /// The monitor profile (sRGB when none was supplied or it does not parse as RGB).
+ pub fn monitor(&self) -> Arc<Profile> {
+ self.monitor_profile
+ .as_ref()
+ .and_then(|b| profile_from_bytes(b).ok())
+ .filter(|p| p.color_space == ColorSpace::Rgb)
+ .unwrap_or_else(|| Arc::new(Builtin::Srgb.profile().clone()))
+ }
+
+ /// Transform from the document's composite (what `photocraft_compose::flatten` returns) to
+ /// the monitor, including the soft proof when View › Proof Colors is on. Cached per
+ /// profile pair and proof settings.
+ pub fn display_transform(&self, doc: &Document) -> Result<Arc<Transform>> {
+ let src = composite_profile(doc);
+ let dst = self.monitor();
+ let pv = self.proof(doc.id);
+ let proof = pv.enabled.then(|| (pv.setup.profile.content_hash(), pv.setup.intent, pv.setup.bpc, pv.setup.simulate_paper));
+ let key = (src.content_hash(), dst.content_hash(), proof);
+ if let Some(t) = self.display_cache.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
+ return Ok(t.clone());
+ }
+ let t = if pv.enabled {
+ Transform::proof(&src, &pv.setup.profile, &dst, pv.setup.intent, pv.setup.bpc, pv.setup.simulate_paper)
+ } else {
+ Transform::new(&src, &dst, Intent::RelativeColorimetric, true)
+ }
+ .map_err(cms_err)?;
+ let t = Arc::new(t);
+ let mut c = self.display_cache.lock().unwrap_or_else(|e| e.into_inner());
+ if c.len() > 32 {
+ c.clear();
+ }
+ c.insert(key, t.clone());
+ Ok(t)
+ }
+
+ /// The display transform as an `size³` RGBA 3D LUT (upload with
+ /// [`Lut3d::to_rgba16f_bytes`] and apply in the canvas shader).
+ pub fn display_lut(&self, doc: &Document, size: usize) -> Result<Lut3d> {
+ let t = self.display_transform(doc)?;
+ Ok(Lut3d::from_transform(&t, size))
+ }
+
+ /// What the canvas should do for `doc`: `None` when neither Proof Colors nor Gamut Warning is
+ /// on, else an RGBA8 display LUT (`size`³, red fastest) whose alpha is 255 where the colour is
+ /// out of the proof gamut (only with Gamut Warning on).
+ pub fn canvas_lut(&self, doc: &Document, size: usize) -> Result<Option<Vec<u8>>> {
+ let pv = self.proof(doc.id);
+ if !pv.enabled && !pv.gamut_warning {
+ return Ok(None);
+ }
+ let lut = self.display_lut(doc, size)?;
+ let mut bytes = lut.to_rgba8();
+ let check = if pv.gamut_warning { Some(GamutCheck::new(&composite_profile(doc), &pv.setup.profile, pv.gamut_threshold).map_err(cms_err)?) } else { None };
+ let s = (size - 1) as f32;
+ for (i, px) in bytes.chunks_exact_mut(4).enumerate() {
+ let rgb = [(i % size) as f32 / s, ((i / size) % size) as f32 / s, (i / (size * size)) as f32 / s];
+ px[3] = if check.as_ref().is_some_and(|c| c.out_of_gamut(&rgb)) { 255 } else { 0 };
+ }
+ Ok(Some(bytes))
+ }
+}
+
+fn merge(mut a: Value, b: Value) -> Value {
+ if let (Value::Object(a), Value::Object(b)) = (&mut a, b) {
+ a.extend(b);
+ }
+ a
+}
+
+fn cms_err(e: photocraft_cms::CmsError) -> EngineError {
+ EngineError::Other(format!("colour management: {e}"))
+}
+
+// ------------------------------------------------------------------ profiles
+
+/// ICC colour space of a document mode.
+pub fn mode_space(mode: ColorMode) -> ColorSpace {
+ match mode {
+ ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => ColorSpace::Gray,
+ ColorMode::Cmyk => ColorSpace::Cmyk,
+ ColorMode::Lab => ColorSpace::Lab,
+ _ => ColorSpace::Rgb,
+ }
+}
+
+fn space_mode(cs: ColorSpace) -> Option<ColorMode> {
+ Some(match cs {
+ ColorSpace::Rgb => ColorMode::Rgb,
+ ColorSpace::Gray => ColorMode::Grayscale,
+ ColorSpace::Cmyk => ColorMode::Cmyk,
+ ColorSpace::Lab => ColorMode::Lab,
+ _ => return None,
+ })
+}
+
+/// Working (default) profile of a mode.
+pub fn working_profile(mode: ColorMode) -> Arc<Profile> {
+ Arc::new(photocraft_cms::builtin::default_for(mode_space(mode)).unwrap_or(Builtin::Srgb.profile()).clone())
+}
+
+/// Parses ICC bytes, caching by allocation so repeated lookups for the same document are free.
+pub fn profile_from_bytes(bytes: &Arc<Vec<u8>>) -> std::result::Result<Arc<Profile>, photocraft_cms::CmsError> {
+ type Cache = Mutex<Vec<(Weak<Vec<u8>>, Arc<Profile>)>>;
+ static CACHE: std::sync::OnceLock<Cache> = std::sync::OnceLock::new();
+ let cache = CACHE.get_or_init(Default::default);
+ {
+ let mut c = cache.lock().unwrap_or_else(|e| e.into_inner());
+ c.retain(|(w, _)| w.strong_count() > 0);
+ if let Some((_, p)) = c.iter().find(|(w, _)| w.as_ptr() == Arc::as_ptr(bytes)) {
+ return Ok(p.clone());
+ }
+ }
+ let p = Arc::new(Profile::parse(bytes)?);
+ cache.lock().unwrap_or_else(|e| e.into_inner()).push((Arc::downgrade(bytes), p.clone()));
+ Ok(p)
+}
+
+/// The document's profile: its embedded profile when it parses and matches the mode,
+/// otherwise the mode's working profile.
+pub fn document_profile(doc: &Document) -> Arc<Profile> {
+ doc.icc_profile
+ .as_ref()
+ .and_then(|b| profile_from_bytes(b).ok())
+ .filter(|p| p.color_space == mode_space(doc.mode))
+ .unwrap_or_else(|| working_profile(doc.mode))
+}
+
+/// Profile describing the compositor's RGB output for this document (see the module docs).
+pub fn composite_profile(doc: &Document) -> Arc<Profile> {
+ match mode_space(doc.mode) {
+ ColorSpace::Rgb => document_profile(doc),
+ ColorSpace::Gray => {
+ let p = document_profile(doc);
+ p.gray_as_rgb().map(Arc::new).unwrap_or_else(|| Arc::new(Builtin::SGray.profile().gray_as_rgb().expect("sGray is a TRC profile")))
+ }
+ _ => Arc::new(Builtin::Srgb.profile().clone()),
+ }
+}
+
+/// Resolves a profile parameter: a built-in id/alias/description, `"working"` (with `mode`),
+/// `"document"`, or a path to an `.icc`/`.icm` file.
+pub fn resolve_profile(spec: &str, doc: Option<&Document>, mode: Option<ColorMode>) -> Result<Arc<Profile>> {
+ match spec {
+ "working" | "default" => {
+ let m = mode.or(doc.map(|d| d.mode)).unwrap_or(ColorMode::Rgb);
+ return Ok(working_profile(m));
+ }
+ "working-cmyk" | "workingCmyk" => return Ok(working_profile(ColorMode::Cmyk)),
+ "working-rgb" | "workingRgb" => return Ok(working_profile(ColorMode::Rgb)),
+ "working-gray" | "workingGray" => return Ok(working_profile(ColorMode::Grayscale)),
+ "document" => return doc.map(document_profile).ok_or(EngineError::NoDocument),
+ _ => {}
+ }
+ if let Some(b) = Builtin::from_id(spec) {
+ return Ok(Arc::new(b.profile().clone()));
+ }
+ let lower = spec.to_ascii_lowercase();
+ if lower.ends_with(".icc") || lower.ends_with(".icm") || spec.contains('/') || spec.contains('\\') {
+ let bytes = std::fs::read(spec).map_err(|e| EngineError::Other(format!("cannot read profile `{spec}`: {e}")))?;
+ return Profile::parse(&bytes).map(Arc::new).map_err(cms_err);
+ }
+ let ids: Vec<&str> = Builtin::ALL.iter().map(|b| b.id()).collect();
+ Err(EngineError::Other(format!("unknown profile `{spec}` (built-ins: {}, or a path to an .icc file)", ids.join(", "))))
+}
+
+fn intent_param(p: &Value) -> Result<Intent> {
+ intent_or(p, Intent::RelativeColorimetric)
+}
+
+fn intent_or(p: &Value, default: Intent) -> Result<Intent> {
+ match p.get("intent").and_then(Value::as_str) {
+ None => Ok(default),
+ Some(s) => Intent::parse(s).ok_or_else(|| EngineError::Other(format!("unknown intent `{s}` (perceptual|relative|saturation|absolute)"))),
+ }
+}
+
+fn bool_param(p: &Value, k: &str, d: bool) -> bool {
+ p.get(k).and_then(Value::as_bool).unwrap_or(d)
+}
+
+fn profile_json(p: &Profile) -> Value {
+ json!({
+ "description": p.description,
+ "colorSpace": format!("{:?}", p.color_space),
+ "class": format!("{:?}", p.class),
+ "version": format!("{}.{}", p.version.0, p.version.1 >> 4),
+ "bytes": p.to_bytes().len(),
+ "lut": p.a2b.iter().any(Option::is_some),
+ "intents": Intent::ALL.iter().filter(|i| p.supports_intent(**i, false)).map(|i| i.id()).collect::<Vec<_>>(),
+ })
+}
+
+// ------------------------------------------------------------------ conversion
+
+/// Converts one surface's colour channels with `t` into `to` (alpha copied). Surfaces whose
+/// model is not `from` fall back to the generic per-pixel conversion.
+pub fn convert_surface(s: &Surface, from: ColorMode, to: PixelFormat, t: &Transform) -> Surface {
+ let sf = s.format();
+ if sf.mode != from || t.inputs() != sf.mode.color_channels() || t.outputs() != to.mode.color_channels() || sf.alpha != to.alpha {
+ return s.convert(to);
+ }
+ let (ss, ds) = (sf.channels(), to.channels());
+ let to = PixelFormat { sample: sf.sample, ..to };
+ // Default (untouched) pixel.
+ let dp = s.default_pixel();
+ let mut dpo = vec![0.0f32; ds];
+ t.convert_f32(&dp, ss, &mut dpo, ds, true);
+ let mut out = Surface::with_default(to, &dpo);
+ // Convert all tiles in one parallel pass into a staging buffer, then store them.
+ let tiles: Vec<_> = s.tiles().map(|(c, t)| (*c, t.clone())).collect();
+ let tile_px = (photocraft_geom::TILE_SIZE * photocraft_geom::TILE_SIZE) as usize;
+ let dst_len = tile_px * to.bytes_per_pixel();
+ let mut staging = vec![0u8; dst_len * tiles.len()];
+ let jobs: Vec<(&[u8], &mut [u8])> = tiles.iter().map(|(_, t)| t.bytes()).zip(staging.chunks_mut(dst_len.max(1))).collect();
+ let kind = match sf.sample {
+ SampleType::U8 => SampleKind::U8,
+ SampleType::U16 => SampleKind::U16,
+ SampleType::F32 => SampleKind::F32,
+ };
+ t.convert_bytes_many(kind, jobs, ss, ds, true);
+ for ((c, _), bytes) in tiles.iter().zip(staging.chunks(dst_len.max(1))) {
+ out.tile_mut(*c).bytes_mut().copy_from_slice(bytes);
+ }
+ out
+}
+
+/// Converts a colour value that is in `from` (the document's old mode) to the new mode.
+fn convert_color(c: &mut Color, from: ColorMode, to: ColorMode, t: &Transform) {
+ if c.mode != from {
+ return;
+ }
+ let n = from.color_channels();
+ let mut o = [0.0f32; 16];
+ t.eval(&c.c[..n], &mut o);
+ let m = to.color_channels();
+ let mut nc = [0.0f32; 4];
+ for (d, v) in nc.iter_mut().zip(&o[..m.min(4)]) {
+ *d = v.clamp(0.0, 1.0);
+ }
+ c.mode = to;
+ c.c = nc;
+}
+
+fn convert_fill(f: &mut Fill, from: ColorMode, to: ColorMode, t: &Transform) {
+ match f {
+ Fill::Solid(c) => convert_color(c, from, to, t),
+ Fill::Gradient { stops, .. } => stops.iter_mut().for_each(|s| convert_color(&mut s.1, from, to, t)),
+ Fill::Pattern { .. } => {}
+ }
+}
+
+fn convert_layer_colors(l: &mut Layer, from: ColorMode, to: ColorMode, t: &Transform) {
+ let mut cc = |c: &mut Color| convert_color(c, from, to, t);
+ let mut touched_fx = false;
+ for e in &mut l.effects.items {
+ touched_fx = true;
+ match e {
+ Effect::DropShadow(s) | Effect::InnerShadow(s) => cc(&mut s.color),
+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => paint_colors(&mut g.paint, &mut cc),
+ Effect::Stroke(s) => paint_colors(&mut s.paint, &mut cc),
+ Effect::ColorOverlay { color, .. } => cc(color),
+ Effect::GradientOverlay { gradient, .. } => gradient.stops.iter_mut().for_each(|s| cc(&mut s.1)),
+ Effect::Satin(s) => cc(&mut s.color),
+ Effect::BevelEmboss(b) => {
+ cc(&mut b.highlight_color);
+ cc(&mut b.shadow_color);
+ }
+ Effect::PatternOverlay { .. } => {}
+ }
+ }
+ let _ = touched_fx;
+ match &mut l.content {
+ LayerContent::Fill(f) => convert_fill(f, from, to, t),
+ LayerContent::Text(tx) => {
+ cc(&mut tx.color);
+ for r in &mut tx.runs {
+ cc(&mut r.style.color);
+ }
+ }
+ LayerContent::Shape(sh) => {
+ if let Some(f) = &mut sh.fill {
+ convert_fill(f, from, to, t);
+ }
+ if let Some(s) = &mut sh.stroke {
+ convert_fill(&mut s.paint, from, to, t);
+ }
+ }
+ LayerContent::Group(g) => {
+ for c in &mut g.children {
+ convert_layer_colors(c, from, to, t);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn paint_colors(p: &mut FxPaint, cc: &mut impl FnMut(&mut Color)) {
+ match p {
+ FxPaint::Color(c) => cc(c),
+ FxPaint::Gradient(g) => g.stops.iter_mut().for_each(|s| cc(&mut s.1)),
+ FxPaint::Pattern { .. } => {}
+ }
+}
+
+/// Converts every pixel layer (and cached text/shape/smart pixels and fill caches) of `doc`
+/// from its profile to `dst`, switching the mode to `dst`'s colour space. Masks, alpha
+/// channels and the selection are untouched; fill, text, shape and effect colours are
+/// converted. The document is tagged with `dst`.
+pub fn convert_document(doc: &mut Document, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> {
+ let to_mode = space_mode(dst.color_space).ok_or_else(|| EngineError::Other(format!("cannot convert to a {:?} profile", dst.color_space)))?;
+ let src = document_profile(doc);
+ let from_mode = doc.pixel_format().mode;
+ let t = Transform::new(&src, dst, intent, bpc).map_err(cms_err)?;
+ let fmt = PixelFormat::new(to_mode, doc.depth, true);
+ crate::image_cmds::for_each_surface(&mut doc.layers, false, &mut |surf, _| {
+ let f = PixelFormat { alpha: surf.format().alpha, ..fmt };
+ *surf = convert_surface(surf, from_mode, f, &t);
+ });
+ for l in &mut doc.layers {
+ convert_layer_colors(l, from_mode, to_mode, &t);
+ // Preserved PSD blocks describing colours in the old mode no longer apply.
+ }
+ doc.mode = to_mode;
+ doc.icc_profile = Some(dst.to_bytes());
+ // Leaving Indexed / Duotone: the palette and inks no longer apply.
+ doc.color_table = None;
+ doc.duotone = None;
+ Ok(())
+}
+
+/// Image › Mode › RGB/Grayscale/CMYK/Lab through the CMS. Params: `profile` (destination,
+/// default the mode's working profile), `intent` (default relative), `bpc` (default true).
+pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value> {
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ if doc.mode == mode && p.get("profile").is_none() {
+ return Ok(Value::Null);
+ }
+ let dst = match p.get("profile").and_then(Value::as_str) {
+ Some(spec) => s.color.resolve(spec, Some(doc), Some(mode))?,
+ None => s.color.working(mode),
+ };
+ if space_mode(dst.color_space) != Some(match mode {
+ ColorMode::Bitmap | ColorMode::Duotone => ColorMode::Grayscale,
+ ColorMode::Indexed | ColorMode::Multichannel => ColorMode::Rgb,
+ m => m,
+ }) {
+ return Err(EngineError::Other(format!("profile `{}` is {:?}, not {mode:?}", dst.description, dst.color_space)));
+ }
+ let intent = intent_or(p, s.color.settings.intent())?;
+ let bpc = bool_param(p, "bpc", s.color.settings.bpc);
+ s.edit("Mode Change", |doc, _| convert_document(doc, &dst, intent, bpc))?;
+ Ok(json!({ "profile": dst.description, "intent": intent.id(), "bpc": bpc }))
+}
+
+// ------------------------------------------------------------------ gamut
+
+/// Out-of-gamut mask of the document composite against `setup`'s profile: one byte per
+/// canvas pixel (255 = out of gamut, transparent pixels never are), plus the count.
+pub fn gamut_mask(doc: &Document, setup: &ProofSetup, threshold: f32) -> Result<(Vec<u8>, usize)> {
+ let check = GamutCheck::new(&composite_profile(doc), &setup.profile, threshold).map_err(cms_err)?;
+ let buf = photocraft_compose::flatten(doc);
+ let mut count = 0;
+ let mask = buf
+ .px
+ .iter()
+ .map(|p| {
+ if p[3] > 0.0 && check.out_of_gamut(&p[..3]) {
+ count += 1;
+ 255
+ } else {
+ 0
+ }
+ })
+ .collect();
+ Ok((mask, count))
+}
+
+// ------------------------------------------------------------------ commands
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn always(_: &Session) -> std::result::Result<(), String> {
+ Ok(())
+}
+
+fn assign_profile(s: &mut Session, p: &Value) -> Result<Value> {
+ let spec = p.get("profile").and_then(Value::as_str).ok_or_else(|| EngineError::BadParams { cmd: "edit.assignProfile".into(), msg: "missing `profile`".into() })?;
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let bytes = if spec == "none" {
+ None
+ } else {
+ let prof = s.color.resolve(spec, Some(doc), None)?;
+ if prof.color_space != mode_space(doc.mode) {
+ return Err(EngineError::Other(format!("profile `{}` is {:?}; the document is {:?}", prof.description, prof.color_space, doc.mode)));
+ }
+ Some(prof.to_bytes())
+ };
+ let desc = match &bytes {
+ Some(b) => profile_from_bytes(b).map(|p| p.description.clone()).unwrap_or_default(),
+ None => "none".into(),
+ };
+ s.edit("Assign Profile", |doc, _| {
+ doc.icc_profile = bytes;
+ Ok(())
+ })?;
+ Ok(json!({ "profile": desc }))
+}
+
+fn convert_to_profile(s: &mut Session, p: &Value) -> Result<Value> {
+ let spec = p.get("profile").and_then(Value::as_str).ok_or_else(|| EngineError::BadParams { cmd: "edit.convertToProfile".into(), msg: "missing `profile`".into() })?;
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let dst = s.color.resolve(spec, Some(doc), None)?;
+ let intent = intent_or(p, s.color.settings.intent())?;
+ let bpc = bool_param(p, "bpc", s.color.settings.bpc);
+ s.edit("Convert to Profile", |doc, _| convert_document(doc, &dst, intent, bpc))?;
+ let d = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ Ok(json!({ "profile": dst.description, "mode": format!("{:?}", d.mode), "intent": intent.id(), "bpc": bpc }))
+}
+
+fn profile_info(s: &mut Session, p: &Value) -> Result<Value> {
+ let builtins: Vec<Value> = Builtin::ALL
+ .iter()
+ .map(|b| json!({ "id": b.id(), "description": b.description(), "colorSpace": format!("{:?}", b.profile().color_space) }))
+ .collect();
+ let doc = s.active().map(|d| d.doc.clone());
+ let info = match p.get("profile").and_then(Value::as_str) {
+ Some(spec) => {
+ let prof = resolve_profile(spec, doc.as_deref(), None)?;
+ Some(profile_json(&prof))
+ }
+ None => doc.as_deref().map(|d| {
+ let mut j = profile_json(&document_profile(d));
+ j["embedded"] = json!(d.icc_profile.is_some());
+ j
+ }),
+ };
+ Ok(json!({ "profile": info, "builtins": builtins }))
+}
+
+fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let (id, doc) = (st.doc.id, st.doc.clone());
+ let name = p.get("profile").and_then(Value::as_str).unwrap_or("working-cmyk").to_string();
+ let profile = s.color.resolve(&name, Some(&doc), Some(ColorMode::Cmyk))?;
+ let intent = intent_param(p)?;
+ let setup = ProofSetup { name, profile, intent, bpc: bool_param(p, "bpc", true), simulate_paper: bool_param(p, "simulatePaper", false) };
+ let pv = s.color.proof_mut(id);
+ pv.setup = setup.clone();
+ Ok(json!({ "profile": setup.profile.description, "intent": setup.intent.id(), "bpc": setup.bpc, "simulatePaper": setup.simulate_paper, "proofColors": pv.enabled }))
+}
+
+fn proof_colors(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = s.active().ok_or(EngineError::NoDocument)?.doc.id;
+ let pv = s.color.proof_mut(id);
+ pv.enabled = p.get("on").and_then(Value::as_bool).unwrap_or(!pv.enabled);
+ Ok(json!({ "on": pv.enabled, "profile": pv.setup.profile.description }))
+}
+
+fn gamut_warning(s: &mut Session, p: &Value) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = st.doc.clone();
+ let pv = s.color.proof_mut(doc.id);
+ pv.gamut_warning = p.get("on").and_then(Value::as_bool).unwrap_or(!pv.gamut_warning);
+ if let Some(t) = p.get("threshold").and_then(Value::as_f64) {
+ pv.gamut_threshold = t.max(0.0) as f32;
+ }
+ let mut setup = pv.setup.clone();
+ let (on, threshold) = (pv.gamut_warning, pv.gamut_threshold);
+ if let Some(spec) = p.get("profile").and_then(Value::as_str) {
+ setup.profile = resolve_profile(spec, Some(&doc), Some(ColorMode::Cmyk))?;
+ }
+ let (_, count) = gamut_mask(&doc, &setup, threshold)?;
+ let total = doc.size.width as usize * doc.size.height as usize;
+ Ok(json!({ "on": on, "profile": setup.profile.description, "threshold": threshold, "outOfGamut": count, "fraction": count as f64 / total.max(1) as f64 }))
+}
+
+/// Edit › Color Settings: read or change working spaces, policies and conversion options.
+fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.colorSettings";
+ let mut next = s.color.settings.clone();
+ if p.get("reset").and_then(Value::as_bool) == Some(true) {
+ next = ColorSettings::default();
+ }
+ let str_of = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string);
+ if let Some(v) = str_of("workingRgb") {
+ next.working_rgb = v;
+ }
+ if let Some(v) = str_of("workingCmyk") {
+ next.working_cmyk = v;
+ }
+ if let Some(v) = str_of("workingGray") {
+ next.working_gray = v;
+ }
+ for (k, slot) in [("policyRgb", &mut next.policy_rgb), ("policyCmyk", &mut next.policy_cmyk), ("policyGray", &mut next.policy_gray)] {
+ if let Some(v) = p.get(k).and_then(Value::as_str) {
+ *slot = Policy::parse(v).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`{k}` must be preserve|convert|off") })?;
+ }
+ }
+ for (k, slot) in [("askOnMismatch", &mut next.ask_on_mismatch), ("askOnPaste", &mut next.ask_on_paste), ("askOnMissing", &mut next.ask_on_missing), ("bpc", &mut next.bpc), ("dither", &mut next.dither)] {
+ if let Some(v) = p.get(k).and_then(Value::as_bool) {
+ *slot = v;
+ }
+ }
+ if let Some(v) = str_of("intent") {
+ next.intent = Intent::parse(&v).map(|i| i.id().to_string()).unwrap_or(v);
+ }
+ validate_settings(&next).map_err(|msg| EngineError::BadParams { cmd: cmd.into(), msg })?;
+ if next != s.color.settings {
+ s.color.settings = next;
+ // Persisted with the preferences.
+ s.prefs.edit(|_| ());
+ }
+ let c = &s.color.settings;
+ let desc = |m: ColorMode| s.color.working(m).description.clone();
+ Ok(json!({
+ "settings": c,
+ "working": {"rgb": desc(ColorMode::Rgb), "cmyk": desc(ColorMode::Cmyk), "gray": desc(ColorMode::Grayscale)},
+ }))
+}
+
+/// Resolve an embedded-profile mismatch reported when opening (the "Embedded Profile
+/// Mismatch" dialog): keep the embedded profile, convert to the working space, or discard it.
+fn profile_mismatch(s: &mut Session, p: &Value) -> Result<Value> {
+ let action = p.get("action").and_then(Value::as_str).unwrap_or("preserve");
+ let mode = s.active().ok_or(EngineError::NoDocument)?.doc.mode;
+ match action {
+ "preserve" | "useEmbedded" => Ok(json!({"action": "kept"})),
+ "convert" | "convertToWorking" => {
+ let dst = s.color.working(mode);
+ let (intent, bpc) = (s.color.settings.intent(), s.color.settings.bpc);
+ s.edit("Convert to Working RGB", |doc, _| convert_document(doc, &dst, intent, bpc))?;
+ Ok(json!({"action": "converted", "profile": dst.description}))
+ }
+ "discard" | "off" => {
+ s.edit("Discard Profile", |doc, _| {
+ doc.icc_profile = None;
+ Ok(())
+ })?;
+ Ok(json!({"action": "discarded"}))
+ }
+ "assignWorking" => {
+ let w = s.color.working(mode);
+ s.edit("Assign Profile", |doc, _| {
+ doc.icc_profile = Some(w.to_bytes());
+ Ok(())
+ })?;
+ Ok(json!({"action": "assigned", "profile": w.description}))
+ }
+ other => Err(EngineError::BadParams { cmd: "color.profileMismatch".into(), msg: format!("unknown action `{other}` (preserve|convert|discard|assignWorking)") }),
+ }
+}
+
+impl Session {
+ /// Add a document read from a file, applying the Color Settings policy first (preserve,
+ /// convert to the working space, or discard the embedded profile). Returns the document
+ /// index and a report (`action`, `mismatch`, `ask`) the UI can turn into a prompt.
+ pub fn open_document(&mut self, mut doc: Document, path: Option<String>) -> (usize, Value) {
+ let report = self.color.open_policy(&mut doc);
+ (self.add_document(doc, path), report)
+ }
+}
+
+macro_rules! spec {
+ ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr, $journal:expr) => {
+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: $journal }
+ };
+ ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr, $journal:expr, $sc:expr) => {
+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: Some($sc), params: $params, enabled: $en, run: $run, journal: $journal }
+ };
+}
+
+/// Colour management command specs.
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!("edit.assignProfile", "Assign Profile…", ["Edit"], r##"{"profile":"working|srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020|gray-gamma-2.2|sgray|lab-d50|coated-cmyk|none" (or a path to an .icc file)}"##, has_doc, assign_profile, true),
+ spec!("edit.convertToProfile", "Convert to Profile…", ["Edit"], r##"{"profile":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020|gray-gamma-2.2|sgray|lab-d50|coated-cmyk|working" (or a path to an .icc file),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, has_doc, convert_to_profile, true),
+ spec!(
+ "edit.colorSettings",
+ "Color Settings…",
+ ["Edit"],
+ r##"{"workingRgb":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020","workingCmyk":"coated-cmyk","workingGray":"sgray|gray-gamma-2.2","policyRgb":"preserve|convert|off","policyCmyk":"preserve|convert|off","policyGray":"preserve|convert|off","askOnMismatch":bool=true,"askOnPaste":bool=true,"askOnMissing":bool=false,"intent":"relative|perceptual|saturation|absolute","bpc":bool=true,"dither":bool=true,"reset":bool=false} (working spaces also accept .icc paths)"##,
+ always,
+ color_settings,
+ true,
+ "Cmd+Shift+K"
+ ),
+ spec!("color.profileMismatch", "Embedded Profile Mismatch", [], r##"{"action":"preserve|convert|discard|assignWorking"}"##, has_doc, profile_mismatch, true),
+ spec!("edit.profileInfo", "Profile Info", [], r##"{"profile":"<builtin id>|document|/path/to/profile.icc"=document}"##, always, profile_info, false),
+ spec!("view.proofSetup", "Proof Setup…", [], r##"{"profile":"working-cmyk|srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020|gray-gamma-2.2|sgray|lab-d50|coated-cmyk" (or a path to an .icc file)="working-cmyk","intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"simulatePaper":bool=false}"##, has_doc, proof_setup, false),
+ spec!("view.proofColors", "Proof Colors", ["View"], r##"{"on":bool=toggle}"##, has_doc, proof_colors, false, "Cmd+Y"),
+ spec!("view.gamutWarning", "Gamut Warning", ["View"], r##"{"on":bool=toggle,"threshold":deltaE=4,"profile":"<proof profile override>"}"##, has_doc, gamut_warning, false, "Cmd+Shift+Y"),
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_geom::Rect;
+
+ fn session(mode: &str, depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 32, "mode": mode, "depth": depth})).unwrap();
+ s
+ }
+
+ fn paint_rgb(s: &mut Session) {
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("paint", |doc, active| {
+ let l = doc.layer_mut(active.unwrap()).unwrap();
+ let surf = l.surface_mut().unwrap();
+ surf.fill_rect(Rect::new(0, 0, 16, 16), &[1.0, 0.0, 0.0, 1.0]);
+ surf.fill_rect(Rect::new(16, 0, 32, 16), &[0.0, 0.0, 1.0, 1.0]);
+ surf.fill_rect(Rect::new(32, 0, 48, 16), &[0.5, 0.5, 0.5, 0.5]);
+ l.mask = Some(photocraft_doc::LayerMask::reveal_all());
+ Ok(())
+ })
+ .unwrap();
+ }
+
+ fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+ }
+
+ #[test]
+ fn mode_conversions_all_depths_with_undo() {
+ for depth in [8, 16, 32] {
+ let mut s = session("rgb", depth);
+ paint_rgb(&mut s);
+ let before = doc(&s).layers[1].surface().unwrap().pixel(40, 8);
+ s.execute("image.mode.cmyk", json!({})).unwrap();
+ let d = doc(&s);
+ assert_eq!(d.mode, ColorMode::Cmyk);
+ assert_eq!(d.icc_profile.as_deref(), Some(&*Builtin::CoatedCmyk.profile().to_bytes()), "tagged with the destination");
+ let l = &d.layers[1];
+ assert_eq!(l.surface().unwrap().format().mode, ColorMode::Cmyk);
+ assert_eq!(l.mask.as_ref().unwrap().surface.format().mode, ColorMode::Grayscale, "masks untouched");
+ let gray = l.surface().unwrap().pixel(40, 8);
+ assert!((gray[4] - 0.5).abs() < 1e-2, "alpha kept: {gray:?}");
+ assert!(gray[..4].iter().all(|v| (0.0..=1.0).contains(v)));
+ // Red goes to M+Y heavy separation.
+ let red = l.surface().unwrap().pixel(8, 8);
+ assert!(red[1] > 0.7 && red[2] > 0.7 && red[0] < 0.2, "{depth}: {red:?}");
+ // Background white → no ink.
+ let bg = d.layers[0].surface().unwrap().pixel(60, 30);
+ assert!(bg[..4].iter().all(|v| *v < 0.01), "{bg:?}");
+ s.execute("image.mode.lab", json!({})).unwrap();
+ let lab = doc(&s).layers[1].surface().unwrap().pixel(40, 8);
+ assert!((lab[1] - 128.0 / 255.0).abs() < 0.03 && (lab[2] - 128.0 / 255.0).abs() < 0.03, "{lab:?}");
+ s.execute("image.mode.grayscale", json!({"intent": "perceptual"})).unwrap();
+ s.execute("image.mode.rgb", json!({})).unwrap();
+ let after = doc(&s).layers[1].surface().unwrap().pixel(40, 8);
+ assert!((after[0] - before[0]).abs() < 0.04 && (after[0] - after[2]).abs() < 0.01, "{depth}: {before:?} -> {after:?}");
+ for _ in 0..4 {
+ s.execute("edit.undo", json!({})).unwrap();
+ }
+ assert_eq!(doc(&s).mode, ColorMode::Rgb);
+ assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(40, 8), before);
+ }
+ }
+
+ #[test]
+ fn rgb_lab_rgb_roundtrip_16bit() {
+ let mut s = session("rgb", 16);
+ paint_rgb(&mut s);
+ let before = doc(&s).layers[1].surface().unwrap().pixel(8, 8);
+ s.execute("image.mode.lab", json!({})).unwrap();
+ s.execute("image.mode.rgb", json!({})).unwrap();
+ let after = doc(&s).layers[1].surface().unwrap().pixel(8, 8);
+ for k in 0..3 {
+ assert!((before[k] - after[k]).abs() < 1.0 / 255.0, "{before:?} -> {after:?}");
+ }
+ }
+
+ #[test]
+ fn assign_and_convert_profile() {
+ let mut s = session("rgb", 8);
+ paint_rgb(&mut s);
+ s.execute("edit.assignProfile", json!({"profile": "display-p3"})).unwrap();
+ assert_eq!(document_profile(doc(&s)).description, "Display P3");
+ let px = doc(&s).layers[1].surface().unwrap().pixel(8, 8);
+ assert_eq!(px, vec![1.0, 0.0, 0.0, 1.0], "assign does not change pixels");
+ assert!(s.execute("edit.assignProfile", json!({"profile": "coated-cmyk"})).is_err(), "wrong colour space");
+ s.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "relative"})).unwrap();
+ let px = doc(&s).layers[1].surface().unwrap().pixel(8, 8);
+ assert!(px[0] > 0.99 && px[1] < 0.01, "P3 red clips to sRGB red: {px:?}");
+ s.execute("edit.convertToProfile", json!({"profile": "coated-cmyk", "intent": "perceptual"})).unwrap();
+ assert_eq!(doc(&s).mode, ColorMode::Cmyk);
+ s.execute("edit.assignProfile", json!({"profile": "none"})).unwrap();
+ assert!(doc(&s).icc_profile.is_none());
+ let info = s.execute("edit.profileInfo", json!({})).unwrap();
+ assert_eq!(info["profile"]["colorSpace"], "Cmyk");
+ assert!(info["builtins"].as_array().unwrap().len() >= 10);
+ assert!(s.execute("edit.convertToProfile", json!({"profile": "nope"})).is_err());
+ }
+
+ #[test]
+ fn fill_and_effect_colours_follow_the_mode() {
+ let mut s = session("rgb", 8);
+ s.edit("fill layer", |doc, _| {
+ let mut l = Layer::new("Fill", LayerContent::Fill(Fill::Solid(Color::rgb(0.0, 0.0, 1.0))));
+ l.effects.items.push(Effect::default_drop_shadow());
+ doc.layers.push(l);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("image.mode.cmyk", json!({})).unwrap();
+ let l = &doc(&s).layers[1];
+ let LayerContent::Fill(Fill::Solid(c)) = &l.content else { panic!() };
+ assert_eq!(c.mode, ColorMode::Cmyk);
+ assert!(c.c[0] > 0.6, "{c:?}");
+ let Effect::DropShadow(sh) = &l.effects.items[0] else { panic!() };
+ assert_eq!(sh.color.mode, ColorMode::Cmyk);
+ }
+
+ #[test]
+ fn proofing_state_and_gamut_warning() {
+ let mut s = session("rgb", 8);
+ paint_rgb(&mut s);
+ let id = doc(&s).id;
+ assert!(!s.color.proof(id).enabled);
+ s.execute("view.proofSetup", json!({"profile": "coated-cmyk", "intent": "perceptual", "simulatePaper": true})).unwrap();
+ let pv = s.color.proof(id);
+ assert_eq!((pv.setup.intent, pv.setup.simulate_paper), (Intent::Perceptual, true));
+ s.execute("view.proofColors", json!({})).unwrap();
+ assert!(s.color.proof(id).enabled);
+ let d = doc(&s).clone();
+ let t = s.color.display_transform(&d).unwrap();
+ let mut o = [0.0f32; 3];
+ t.eval(&[1.0, 1.0, 1.0], &mut o);
+ assert!(o[0] < 0.97, "paper simulation: {o:?}");
+ let lut = s.color.display_lut(&d, 17).unwrap();
+ assert_eq!(lut.data.len(), 17 * 17 * 17);
+ s.execute("view.proofColors", json!({"on": false})).unwrap();
+ let t2 = s.color.display_transform(&d).unwrap();
+ t2.eval(&[1.0, 1.0, 1.0], &mut o);
+ assert!(o.iter().all(|v| (v - 1.0).abs() < 1e-3), "no proof: identity-ish {o:?}");
+ // Saturated sRGB blue is outside coated CMYK; mid gray and white are inside.
+ let r = s.execute("view.gamutWarning", json!({"on": true})).unwrap();
+ assert!(r["on"].as_bool().unwrap());
+ let (mask, count) = gamut_mask(&d, &s.color.proof(id).setup, 4.0).unwrap();
+ assert_eq!(r["outOfGamut"].as_u64().unwrap() as usize, count);
+ let w = d.size.width as usize;
+ assert_eq!(mask[8 * w + 20], 255, "blue out of gamut");
+ assert_eq!(mask[8 * w + 40], 0, "gray in gamut");
+ assert_eq!(mask[30 * w + 60], 0, "white in gamut");
+ }
+
+ #[test]
+ fn gray_and_cmyk_composite_profiles() {
+ let s = session("gray", 8);
+ let p = composite_profile(doc(&s));
+ assert_eq!(p.color_space, ColorSpace::Rgb);
+ let t = s.color.display_transform(doc(&s)).unwrap();
+ let mut o = [0.0f32; 3];
+ t.eval(&[0.5, 0.5, 0.5], &mut o);
+ assert!(o.iter().all(|v| (v - 0.5).abs() < 2e-3), "sGray displays as sRGB gray: {o:?}");
+ let s = session("cmyk", 8);
+ assert_eq!(composite_profile(doc(&s)).description, "sRGB IEC61966-2.1");
+ }
+
+ /// `cargo test -p photocraft-engine --release -- --ignored bench_cmyk --nocapture`
+ #[test]
+ #[ignore]
+ fn bench_cmyk_conversion_6016() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 6016, "height": 6016, "mode": "rgb", "depth": 8})).unwrap();
+ s.edit("noise", |doc, _| {
+ let r = doc.bounds();
+ let surf = doc.layers[0].surface_mut().unwrap();
+ let mut bytes = vec![0u8; r.width() as usize * r.height() as usize * 4];
+ let mut x = 1u32;
+ for px in bytes.chunks_exact_mut(4) {
+ x ^= x << 13;
+ x ^= x >> 17;
+ x ^= x << 5;
+ px.copy_from_slice(&[x as u8, (x >> 8) as u8, (x >> 16) as u8, 255]);
+ }
+ surf.write_interleaved(r, &bytes);
+ Ok(())
+ })
+ .unwrap();
+ let mut d = (*s.active().unwrap().doc).clone();
+ let t = std::time::Instant::now();
+ convert_document(&mut d, Builtin::CoatedCmyk.profile(), Intent::RelativeColorimetric, true).unwrap();
+ eprintln!("convert_document alone: {} ms", t.elapsed().as_millis());
+ let t = std::time::Instant::now();
+ s.execute("image.mode.cmyk", json!({})).unwrap();
+ eprintln!("6016×6016 RGB8 → CMYK: {} ms", t.elapsed().as_millis());
+ }
+}
+
+#[cfg(test)]
+mod settings_tests {
+ use super::*;
+
+ fn tagged(spec: &str) -> Document {
+ let mut d = Document::with_background("t", photocraft_doc::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::rgba(0.2, 0.6, 0.9, 1.0));
+ d.icc_profile = Some(Builtin::from_id(spec).unwrap().profile().to_bytes());
+ d
+ }
+
+ fn desc(d: &Document) -> Option<String> {
+ d.icc_profile.as_ref().map(|b| profile_from_bytes(b).unwrap().description.clone())
+ }
+
+ #[test]
+ fn color_settings_validate_and_report() {
+ let mut s = Session::new();
+ let r = s.execute("edit.colorSettings", json!({})).unwrap();
+ assert_eq!(r["settings"]["workingRgb"], "srgb");
+ assert!(s.execute("edit.colorSettings", json!({"workingRgb": "coated-cmyk"})).is_err());
+ assert!(s.execute("edit.colorSettings", json!({"policyRgb": "sometimes"})).is_err());
+ assert!(s.execute("edit.colorSettings", json!({"intent": "vivid"})).is_err());
+ let r = s.execute("edit.colorSettings", json!({"workingRgb": "adobe-rgb-compat", "intent": "perceptual", "bpc": false})).unwrap();
+ assert!(r["working"]["rgb"].as_str().unwrap().starts_with("Adobe RGB"));
+ assert_eq!(s.color.settings.intent(), Intent::Perceptual);
+ // Settings travel with the preferences file.
+ let mut t = Session::new();
+ t.load_prefs_json(&s.prefs_to_json()).unwrap();
+ assert_eq!(t.color.settings, s.color.settings);
+ }
+
+ #[test]
+ fn open_policies() {
+ let mut s = Session::new();
+ // Preserve (default): an Adobe RGB file keeps its profile and asks.
+ let (_, r) = s.open_document(tagged("adobe-rgb-compat"), None);
+ assert_eq!((r["action"].as_str(), r["mismatch"].as_bool(), r["ask"].as_bool()), (Some("kept"), Some(true), Some(true)));
+ assert!(desc(&s.active().unwrap().doc).unwrap().starts_with("Adobe RGB"));
+ // Matching profiles never ask.
+ let (_, r) = s.open_document(tagged("srgb"), None);
+ assert_eq!(r["mismatch"], false);
+ // Convert to working: pixels converted and the document tagged with sRGB.
+ s.execute("edit.colorSettings", json!({"policyRgb": "convert"})).unwrap();
+ let (_, r) = s.open_document(tagged("adobe-rgb-compat"), None);
+ assert_eq!(r["action"], "converted");
+ let d = &s.active().unwrap().doc;
+ assert!(desc(d).unwrap().starts_with("sRGB"));
+ assert!((d.layers[0].surface().unwrap().pixel(1, 1)[0] - 0.2).abs() > 0.01, "values changed by the conversion");
+ // Off: the embedded profile is discarded.
+ s.execute("edit.colorSettings", json!({"policyRgb": "off"})).unwrap();
+ let (_, r) = s.open_document(tagged("display-p3"), None);
+ assert_eq!(r["action"], "discarded");
+ assert!(s.active().unwrap().doc.icc_profile.is_none());
+ // Untagged files are assumed to be in a non-default working space and tagged with it.
+ s.execute("edit.colorSettings", json!({"policyRgb": "preserve", "workingRgb": "display-p3"})).unwrap();
+ let mut d = tagged("srgb");
+ d.icc_profile = None;
+ let (_, r) = s.open_document(d, None);
+ assert_eq!(r["action"], "assigned");
+ assert_eq!(desc(&s.active().unwrap().doc).as_deref(), Some("Display P3"));
+ }
+
+ #[test]
+ fn mode_conversion_uses_working_spaces() {
+ let mut s = Session::new();
+ s.execute("edit.colorSettings", json!({"workingRgb": "rec2020"})).unwrap();
+ for depth in [8, 16, 32] {
+ s.execute("file.new", json!({"width": 8, "height": 8, "mode": "gray", "depth": depth})).unwrap();
+ s.execute("image.mode.rgb", json!({})).unwrap();
+ let d = &s.active().unwrap().doc;
+ assert_eq!(d.mode, ColorMode::Rgb);
+ assert!(desc(d).unwrap().contains("2020"), "depth {depth}: {:?}", desc(d));
+ }
+ // "working" specs follow the settings too.
+ let p = s.color.resolve("working-rgb", None, None).unwrap();
+ assert!(p.description.contains("2020"));
+ }
+
+ #[test]
+ fn mismatch_resolution_command() {
+ let mut s = Session::new();
+ s.open_document(tagged("adobe-rgb-compat"), None);
+ s.execute("color.profileMismatch", json!({"action": "convert"})).unwrap();
+ assert!(desc(&s.active().unwrap().doc).unwrap().starts_with("sRGB"));
+ s.undo();
+ s.execute("color.profileMismatch", json!({"action": "discard"})).unwrap();
+ assert!(s.active().unwrap().doc.icc_profile.is_none());
+ assert!(s.execute("color.profileMismatch", json!({"action": "explode"})).is_err());
+ }
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 413be4c73..74f4a97a6 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -4,7 +4,6 @@ use photocraft_color::{BlendMode, Color, ColorMode, SampleType};
use photocraft_doc::adjust::CurvePoint;
use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, LayerId, LayerMask, Size};
use photocraft_geom::Rect;
-use photocraft_paint::{BrushSettings, Stroke, StrokePoint};
use photocraft_raster::Surface;
use serde_json::{Value, json};
@@ -45,8 +44,18 @@ 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 pixel layer, or a targeted alpha channel / Quick Mask (adjustments and fills apply to it).
+fn has_pixel_or_channel(s: &Session) -> std::result::Result<(), String> {
+ if crate::channel_cmds::edits_channel(s) {
+ return Ok(());
+ }
+ has_pixel_layer(s)
+}
/// 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> {
+ if crate::channel_cmds::edits_channel(s) {
+ return Ok(());
+ }
has_layer(s)?;
let d = s.active().unwrap();
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
@@ -107,7 +116,7 @@ pub(crate) fn int(p: &Value, key: &str) -> Option<i64> {
fn f32_or(p: &Value, key: &str, default: f32) -> f32 {
p.get(key).and_then(Value::as_f64).map(|v| v as f32).unwrap_or(default)
}
-fn color_param(p: &Value, key: &str, default: [f32; 4]) -> [f32; 4] {
+pub(crate) fn color_param(p: &Value, key: &str, default: [f32; 4]) -> [f32; 4] {
match p.get(key) {
Some(Value::Array(a)) if a.len() >= 3 => {
let v: Vec<f32> = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();
@@ -126,7 +135,7 @@ fn parse_hex(s: &str) -> Option<[f32; 4]> {
_ => None,
}
}
-fn layer_param(s: &Session, p: &Value) -> Result<LayerId> {
+pub(crate) fn layer_param(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())),
@@ -150,7 +159,18 @@ fn new_adjustment(s: &mut Session, adj: Adjustment) -> Result<Value> {
Ok(json!({ "layer": id.0 }))
}
-fn destructive_adjust(s: &mut Session, label: &str, adj: Adjustment) -> Result<Value> {
+fn destructive_adjust(s: &mut Session, label: &str, adj: Adjustment, p: &Value) -> Result<Value> {
+ if crate::channel_cmds::is_channel_target(p) {
+ // Alpha channel / Quick Mask target: the adjustment runs on the grayscale channel.
+ return s.edit(label, |doc, _| {
+ let sel = doc.selection.clone();
+ if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, p)? {
+ pixels::adjust_surface(surf, &adj, sel.as_ref());
+ surf.prune();
+ }
+ Ok(Value::Null)
+ });
+ }
let id = layer_param(s, &Value::Null)?;
s.edit(label, |doc, _| {
let sel = doc.selection.clone();
@@ -219,6 +239,9 @@ pub fn adjustment_from_params(kind: &str, p: &Value) -> Adjustment {
"channelMixer" => Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false },
"colorBalance" => Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [0.0; 3], highlights: [0.0; 3], preserve_luminosity: true },
"gradientMap" => Adjustment::GradientMap { stops: vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])], reverse: false },
+ "selectiveColor" => crate::adjust_cmds::selective_from_params(p, None),
+ // Best effort here (a bad LUT file gives an empty lookup); commands use the checked path.
+ "colorLookup" => crate::adjust_cmds::lookup_from_params(p, None).unwrap_or(Adjustment::ColorLookup { name: String::new(), lut: None, size: 0, tetrahedral: false, dither: false }),
_ => Adjustment::Invert,
}
}
@@ -267,15 +290,16 @@ fn build() -> Vec<CommandSpec> {
// Edit
cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))),
cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))),
- cmd!("edit.fill", "Fill…", ["Edit"], Some("Shift+F5"), r##"{"color":"#rrggbb|[r,g,b,a]"=foreground}"##, has_pixel_layer, |s, p| {
+ cmd!("edit.fill", "Fill…", ["Edit"], Some("Shift+F5"), r##"{"contents":"color|pattern"="color","color":"#rrggbb|[r,g,b,a]"=foreground,"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"opacity":%=100,"target":"pixels"|{"channel":i}|"quickMask"?}"##, has_pixel_or_channel, |s, p| {
+ if p.get("contents").and_then(Value::as_str) == Some("pattern") {
+ return crate::pattern_cmds::fill_with_pattern(s, p);
+ }
let color = color_param(p, "color", s.tools.foreground);
- let id = layer_param(s, p)?;
+ let id = if crate::channel_cmds::is_channel_target(p) { None } else { Some(layer_param(s, p)?) };
s.edit("Fill", |doc, _| {
let sel = doc.selection.clone();
let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds());
- 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 (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
pixels::fill_surface(surf, area, color, sel.as_ref(), lock);
Ok(())
})?;
@@ -376,19 +400,11 @@ fn build() -> Vec<CommandSpec> {
})?;
Ok(json!({ "layer": id.0 }))
}),
- cmd!("layer.groupLayers", "Group Layers", ["Layer"], Some("Cmd+G"), r##"{"layer":id?}"##, has_layer, |s, p| {
- let id = layer_param(s, p)?;
- let gid = s.edit("Group Layers", |doc, active| {
- let l = doc.remove(id).ok_or(EngineError::NoLayer(id))?;
- let path_hint = *active;
- let g = Layer::group(doc.next_layer_name("Group"), vec![l]);
- let gid = doc.insert_above(path_hint.filter(|a| *a != id), g);
- *active = Some(gid);
- Ok(gid)
- })?;
- Ok(json!({ "layer": gid.0 }))
- }),
- cmd!("layer.duplicate", "Duplicate Layer…", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| {
+ cmd!("layer.groupLayers", "Group Layers", ["Layer"], Some("Cmd+G"), r##"{"layer":id?,"name":str?} (no layer: every selected layer)"##, has_layer, crate::layer_multi_cmds::group_layers),
+ cmd!("layer.duplicate", "Duplicate Layer…", ["Layer"], None, r##"{"layer":id?} (no layer: every selected layer)"##, has_layer, |s, p| {
+ if crate::layer_multi_cmds::multi(s, p) {
+ return crate::layer_multi_cmds::duplicate_selected(s);
+ }
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();
@@ -399,7 +415,10 @@ fn build() -> Vec<CommandSpec> {
})?;
Ok(json!({ "layer": nid.0 }))
}),
- cmd!("layer.delete", "Delete Layer", ["Layer", "Delete"], None, r##"{"layer":id?}"##, has_layer, |s, p| {
+ cmd!("layer.delete", "Delete Layer", ["Layer", "Delete"], None, r##"{"layer":id?} (no layer: every selected layer)"##, has_layer, |s, p| {
+ if crate::layer_multi_cmds::multi(s, p) {
+ return crate::layer_multi_cmds::delete_selected(s);
+ }
let id = layer_param(s, p)?;
s.edit("Delete Layer", |doc, active| {
doc.remove(id).ok_or(EngineError::NoLayer(id))?;
@@ -410,11 +429,7 @@ fn build() -> Vec<CommandSpec> {
})?;
Ok(Value::Null)
}),
- cmd!("layer.select", "Select Layer", [], None, r##"{"layer":id}"##, has_doc, |s, p| {
- let id = p.get("layer").and_then(Value::as_u64).ok_or_else(|| bad("layer.select", "missing `layer`"))?;
- s.select_layer(LayerId(id))?;
- Ok(Value::Null)
- }),
+ cmd!("layer.select", "Select Layer", [], None, r##"{"layer":id,"mode":"replace|toggle|range|add"="replace"} (toggle = ⌘-click, range = ⇧-click)"##, has_doc, crate::layer_multi_cmds::select),
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" };
@@ -486,7 +501,7 @@ fn build() -> Vec<CommandSpec> {
set_mask(s, p, "Add Layer Mask", Some(mask))
}),
cmd!("layer.layerMask.delete", "Delete", ["Layer", "Layer Mask"], None, r##"{"layer":id?}"##, has_layer, |s, p| set_mask(s, p, "Delete Layer Mask", None)),
- cmd!("layer.mergeDown", "Merge Down", ["Layer"], Some("Cmd+E"), r##"{"layer":id?}"##, has_layer, |s, p| {
+ cmd!("layer.mergeDown", "Merge Down", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| {
let id = layer_param(s, p)?;
s.edit("Merge Down", |doc, active| {
let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?;
@@ -550,7 +565,10 @@ fn build() -> Vec<CommandSpec> {
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
let LayerContent::Adjustment(adj) = &mut l.content else { return Err(EngineError::Other("not an adjustment layer".into())) };
let kind = adjustment_kind(adj);
- *adj = adjustment_from_params(kind, p);
+ *adj = match crate::adjust_cmds::update_adjustment(adj, p) {
+ Some(r) => r?,
+ None => adjustment_from_params(kind, p),
+ };
Ok(())
})?;
Ok(Value::Null)
@@ -586,25 +604,7 @@ fn build() -> Vec<CommandSpec> {
})?;
Ok(Value::Null)
}),
- cmd!("layer.translate", "Move Layer", [], None, r##"{"layer":id?,"dx":i32,"dy":i32}"##, has_layer, |s, p| {
- let id = layer_param(s, p)?;
- let dx = int(p, "dx").unwrap_or(0) as i32;
- let dy = int(p, "dy").unwrap_or(0) as i32;
- if dx == 0 && dy == 0 {
- 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(&snapshot, l, dx, dy);
- crate::vector_cmds::translate_vectors(&snapshot, l, dx as f64, dy as f64);
- Ok(())
- })?;
- Ok(Value::Null)
- }),
+ cmd!("layer.translate", "Move Layer", [], None, r##"{"layer":id?,"dx":i32,"dy":i32} (no layer: every selected layer; linked layers follow)"##, has_layer, crate::layer_multi_cmds::translate),
// Image
cmd!("image.imageRotation.flipCanvasHorizontal", "Flip Canvas Horizontal", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| {
s.edit("Flip Canvas Horizontal", |doc, _| {
@@ -649,52 +649,10 @@ fn build() -> Vec<CommandSpec> {
Ok(Value::Null)
}),
cmd!("image.adjustments.desaturate", "Desaturate", ["Image", "Adjustments"], Some("Cmd+Shift+U"), "{}", has_pixel_layer, |s, _| {
- destructive_adjust(s, "Desaturate", Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false })
+ destructive_adjust(s, "Desaturate", Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false }, &Value::Null)
}),
// 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?,"target":"pixels|mask"="pixels"}"##, has_paintable, |s, p| {
- let pts: Vec<StrokePoint> = p
- .get("points")
- .and_then(Value::as_array)
- .ok_or_else(|| bad("paint.stroke", "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("paint.stroke", "`points` is empty"));
- }
- let base = s.tools.brush.clone();
- let brush = BrushSettings {
- size: f32_or(p, "size", base.size),
- hardness: f32_or(p, "hardness", base.hardness),
- opacity: f32_or(p, "opacity", base.opacity),
- flow: f32_or(p, "flow", base.flow),
- spacing: f32_or(p, "spacing", base.spacing),
- color: color_param(p, "color", s.tools.foreground),
- 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)?;
- let label = if stroke.brush.erase { "Eraser" } else { "Brush Tool" };
- 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 && !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() {
- st.last_damage = Some(dmg);
- }
- Ok(json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] }))
- }),
+ cmd!("paint.stroke", "Brush Stroke", [], None, r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"spacing":0..10?,"color":"#rrggbb"?=foreground,"erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##, has_paintable, crate::brush_cmds::paint_stroke),
cmd!("tools.setColors", "Set Colors", [], None, r##"{"foreground":"#rrggbb"?,"background":"#rrggbb"?}"##, always, |s, p| {
s.tools.foreground = color_param(p, "foreground", s.tools.foreground);
s.tools.background = color_param(p, "background", s.tools.background);
@@ -750,6 +708,8 @@ fn build() -> Vec<CommandSpec> {
("posterize", "Posterize…", r##"{"levels":2..255}"##),
("threshold", "Threshold…", r##"{"level":1..255}"##),
("gradientMap", "Gradient Map…", "{}"),
+ ("selectiveColor", "Selective Color…", r##"{"method":"relative|absolute"="relative","colors":"reds|yellows|greens|cyans|blues|magentas|whites|neutrals|blacks"="reds","cyan":-100..100=0,"magenta":-100..100=0,"yellow":-100..100=0,"black":-100..100=0,"reds":json} (per-range [c,m,y,k] arrays: reds yellows greens cyans blues magentas whites neutrals blacks)"##),
+ ("colorLookup", "Color Lookup…", r##"{"lut":"none|warm|cool|tealOrange|bleachBypass|fadedFilm|dayForNight|monoContrast|crossProcess"="none","file":text,"interpolation":"trilinear|tetrahedral"="trilinear","dither":bool=false,"data":json} (file: .cube/.3dl/.look path; data: file text + "fileName")"##),
];
for &(kind, label, params) in ADJ {
let layer_id: &'static str = Box::leak(format!("layer.newAdjustmentLayer.{kind}").into_boxed_str());
@@ -763,7 +723,8 @@ fn build() -> Vec<CommandSpec> {
enabled: has_doc,
run: |s, p| {
let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string();
- new_adjustment(s, adjustment_from_params(&kind, p))
+ let adj = if kind == "colorLookup" { crate::adjust_cmds::lookup_from_params(p, None)? } else { adjustment_from_params(&kind, p) };
+ new_adjustment(s, adj)
},
journal: true,
});
@@ -781,27 +742,44 @@ fn build() -> Vec<CommandSpec> {
_ => None,
},
params,
- enabled: has_pixel_layer,
+ enabled: has_pixel_or_channel,
run: |s, p| {
let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string();
- let adj = adjustment_from_params(&kind, p);
+ let adj = if kind == "colorLookup" { crate::adjust_cmds::lookup_from_params(p, None)? } else { adjustment_from_params(&kind, p) };
let label = adj.label().to_string();
- destructive_adjust(s, &label, adj)
+ destructive_adjust(s, &label, adj, p)
},
journal: true,
});
}
v.extend(crate::layer_style::specs());
v.extend(crate::filters::specs());
+ v.extend(crate::filters_ext::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::color_cmds::specs());
+ v.extend(crate::brush_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.extend(crate::extra_cmds::specs());
+ v.extend(crate::file_cmds::specs());
+ v.extend(crate::type_extra_cmds::specs());
+ v.extend(crate::smart_cmds::specs());
+ v.extend(crate::layer_multi_cmds::specs());
+ v.extend(crate::prefs::specs());
+ v.extend(crate::edit_menu_cmds::specs());
+ v.extend(crate::align_cmds::specs());
+ v.extend(crate::channel_cmds::specs());
+ v.extend(crate::adjust_cmds::specs());
+ v.extend(crate::layer_menu_cmds::specs());
+ v.extend(crate::mode_cmds::specs());
+ v.extend(crate::pattern_cmds::specs());
+ v.extend(crate::warp_cmds::specs());
v
}
@@ -833,6 +811,8 @@ pub fn adjustment_kind(a: &Adjustment) -> &'static str {
Adjustment::Posterize { .. } => "posterize",
Adjustment::Threshold { .. } => "threshold",
Adjustment::GradientMap { .. } => "gradientMap",
+ Adjustment::SelectiveColor { .. } => "selectiveColor",
+ Adjustment::ColorLookup { .. } => "colorLookup",
_ => "invert",
}
}
@@ -879,7 +859,7 @@ fn combine(a: &Surface, b: &Surface, area: Rect, f: impl Fn(f32, f32) -> f32) ->
/// 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) {
+pub(crate) 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
@@ -897,6 +877,7 @@ fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) {
translate_layer(doc, c, dx, dy);
}
}
+ LayerContent::Smart(sm) => crate::smart_cmds::shift_smart(sm, dx, dy),
_ => {}
}
}
diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs
new file mode 100644
index 000000000..e97e3c280
--- /dev/null
+++ b/crates/engine/src/edit_menu_cmds.rs
@@ -0,0 +1,882 @@
+//! The rest of Photoshop's Edit menu: Fade, Purge, Content-Aware Fill and Scale, Define Brush
+//! Preset / Custom Shape, Find and Replace Text, the Preset Manager and preset export/import.
+//! Auto-Align and Auto-Blend Layers live in [`crate::align_cmds`].
+//!
+//! Check Spelling is not implemented: it needs a word list per language, and no permissively
+//! licensed dictionary small enough to bundle (or a pure-Rust checker with one) was available.
+
+use photocraft_color::{BlendMode, PixelFormat};
+use photocraft_doc::vector::Path;
+use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId};
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, from_rgba_into, to_rgba};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, blend_from_str, int, layer_param};
+use crate::{EngineError, Result, Session};
+
+// ------------------------------------------------------------------ state
+
+/// What Edit › Fade would fade: the result of the last filter, adjustment or paint command.
+#[derive(Clone, Debug, PartialEq)]
+pub struct FadeSource {
+ pub doc: DocId,
+ /// Document revision right after the command; any later change disables Fade.
+ pub revision: u64,
+ pub layer: LayerId,
+ pub mask: bool,
+ pub label: String,
+}
+
+/// A custom shape (Edit › Define Custom Shape), usable by the Custom Shape tool.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct CustomShape {
+ pub name: String,
+ pub path: Path,
+}
+
+/// Edit-menu state kept by the session.
+#[derive(Clone, Debug, Default)]
+pub struct EditState {
+ pub fade: Option<FadeSource>,
+ /// Custom shape library (the vector tools read it).
+ pub custom_shapes: Vec<CustomShape>,
+ /// Find and Replace Text position: (layer, byte offset after the current match).
+ pub find_cursor: Option<(LayerId, usize, usize)>,
+}
+
+/// Commands whose result Edit › Fade can blend back against the previous state.
+fn fadeable(id: &str) -> bool {
+ id.starts_with("filter.") || id.starts_with("image.adjustments.") || id.starts_with("paint.") || matches!(id, "edit.fill" | "edit.stroke" | "edit.contentAwareFill" | "image.autoTone" | "image.autoContrast" | "image.autoColor")
+}
+
+/// Called after every successful command: remember a fadeable result.
+pub(crate) fn after_command(s: &mut Session, id: &str) {
+ if !fadeable(id) {
+ return;
+ }
+ let Some(st) = s.active() else { return };
+ let Some(layer) = st.active_layer else { return };
+ let label = st.history.undo_label().unwrap_or(id).to_string();
+ let mask = st.doc.layer(layer).is_some_and(|l| l.mask.is_some()) && st.history.state(st.history.past_len().wrapping_sub(1)).is_some_and(|prev| {
+ // The mask changed and the pixels didn't: the command painted the mask.
+ let now = st.doc.layer(layer);
+ let was = prev.layer(layer);
+ let surf_eq = |a: Option<&Surface>, b: Option<&Surface>| match (a, b) {
+ (Some(a), Some(b)) => crate_fingerprint(a) == crate_fingerprint(b),
+ (None, None) => true,
+ _ => false,
+ };
+ surf_eq(now.and_then(|l| l.surface()), was.and_then(|l| l.surface())) && !surf_eq(now.and_then(|l| l.mask.as_ref().map(|m| &m.surface)), was.and_then(|l| l.mask.as_ref().map(|m| &m.surface)))
+ });
+ s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, layer, mask, label });
+}
+
+/// Tile identity of a surface (pointer equality of its COW tiles).
+fn crate_fingerprint(s: &Surface) -> u64 {
+ s.tiles().fold(s.tile_count() as u64, |h, (c, t)| (h ^ std::sync::Arc::as_ptr(t) as usize as u64 ^ ((c.tx as u64) << 32 | c.ty as u32 as u64)).wrapping_mul(0x100_0000_01b3))
+}
+
+// ------------------------------------------------------------------ helpers
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn f32_or(p: &Value, k: &str, d: f32) -> f32 {
+ p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32)
+}
+
+fn str_or<'a>(p: &'a Value, k: &str, d: &'a str) -> &'a str {
+ p.get(k).and_then(Value::as_str).unwrap_or(d)
+}
+
+fn bool_or(p: &Value, k: &str, d: bool) -> bool {
+ p.get(k).and_then(Value::as_bool).unwrap_or(d)
+}
+
+fn always(_: &Session) -> std::result::Result<(), String> {
+ Ok(())
+}
+
+fn pixel_layer(s: &Session) -> std::result::Result<LayerId, String> {
+ let d = s.active().ok_or("no document open")?;
+ let id = d.active_layer.ok_or("no active layer")?;
+ let l = d.doc.layer(id).ok_or("no active layer")?;
+ if !matches!(l.content, LayerContent::Raster(_)) {
+ return Err(format!("active layer is a {} layer, not a pixel layer", l.content.kind_name()));
+ }
+ if l.locks.all || l.locks.pixels {
+ return Err(format!("the layer \"{}\" is locked", l.name));
+ }
+ Ok(id)
+}
+
+fn writable_surface(doc: &mut Document, id: LayerId) -> Result<&mut Surface> {
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ if l.locks.all || l.locks.pixels {
+ return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name)));
+ }
+ l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))
+}
+
+// ------------------------------------------------------------------ Fade
+
+fn can_fade(s: &Session) -> std::result::Result<(), String> {
+ let st = s.active().ok_or("no document open")?;
+ let f = s.edit_state.fade.as_ref().ok_or("nothing to fade")?;
+ if f.doc != st.doc.id || f.revision != st.revision || !st.history.can_undo() {
+ return Err("Fade is only available right after a filter, adjustment or painting step".into());
+ }
+ if st.doc.layer(f.layer).is_none() {
+ return Err("the faded layer no longer exists".into());
+ }
+ Ok(())
+}
+
+fn surface_of(doc: &Document, id: LayerId, mask: bool) -> Option<&Surface> {
+ let l = doc.layer(id)?;
+ if mask { l.mask.as_ref().map(|m| &m.surface) } else { l.surface() }
+}
+
+/// Blend `after` back towards `before` over `area`: `before + opacity × (B(before, after) − before)`
+/// with blend mode `mode` (premultiplied, so alpha changes fade too).
+pub fn fade_surface(before: &Surface, after: &mut Surface, area: Rect, mode: BlendMode, opacity: f32) {
+ let fmt = after.format();
+ let n = fmt.channels();
+ if area.is_empty() || n == 0 {
+ return;
+ }
+ let b = before.read_region(area);
+ let mut a = after.read_region(area);
+ let k = opacity.clamp(0.0, 1.0);
+ let lerp_premul = |pb: &[f32], pa: &[f32], out: &mut [f32], alpha: bool| {
+ let m = out.len();
+ if !alpha {
+ for c in 0..m {
+ out[c] = pb[c] + (pa[c] - pb[c]) * k;
+ }
+ return;
+ }
+ let (ab, aa) = (pb[m - 1], pa[m - 1]);
+ let ao = ab + (aa - ab) * k;
+ for c in 0..m - 1 {
+ let pm = pb[c] * ab + (pa[c] * aa - pb[c] * ab) * k;
+ out[c] = if ao > 1e-9 { pm / ao } else { 0.0 };
+ }
+ out[m - 1] = ao;
+ };
+ let mut tmp = vec![0.0f32; n];
+ for (pa, pb) in a.chunks_exact_mut(n).zip(b.chunks_exact(n)) {
+ if mode == BlendMode::Normal || n == 1 {
+ lerp_premul(pb, pa, &mut tmp, fmt.alpha);
+ pa.copy_from_slice(&tmp);
+ } else {
+ let rb = to_rgba(&fmt, pb);
+ let ra = to_rgba(&fmt, pa);
+ let blended = photocraft_color::blend::composite(mode, rb, ra, 1.0);
+ let mut o = [0.0f32; 4];
+ lerp_premul(&rb, &blended, &mut o, true);
+ let mut enc = [0.0f32; 8];
+ from_rgba_into(&fmt, o, &mut enc);
+ pa.copy_from_slice(&enc[..n]);
+ }
+ }
+ after.write_region(area, &a);
+}
+
+fn fade(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.fade";
+ let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?;
+ let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0;
+ let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?;
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let prev = st.history.state(st.history.past_len() - 1).ok_or_else(|| bad(cmd, "no previous state"))?;
+ let before = surface_of(&prev, src.layer, src.mask).cloned().ok_or_else(|| EngineError::Other("the layer did not exist before this step".into()))?;
+ let now = surface_of(&st.doc, src.layer, src.mask).ok_or(EngineError::NoLayer(src.layer))?;
+ if now.format() != before.format() {
+ return Err(EngineError::Other("can't fade a step that changed the layer's pixel format".into()));
+ }
+ let area = before.content_bounds().union(&now.content_bounds());
+ let label = format!("Fade {}", src.label);
+ s.edit(&label, |doc, _| {
+ let l = doc.layer_mut(src.layer).ok_or(EngineError::NoLayer(src.layer))?;
+ let surf = if src.mask { l.mask.as_mut().map(|m| &mut m.surface) } else { l.surface_mut() }.ok_or(EngineError::NoLayer(src.layer))?;
+ fade_surface(&before, surf, area, mode, opacity);
+ surf.prune();
+ Ok(())
+ })?;
+ Ok(json!({"faded": src.label, "opacity": opacity * 100.0, "mode": mode.label()}))
+}
+
+// ------------------------------------------------------------------ Purge
+
+fn history_bytes(s: &Session, all: bool) -> usize {
+ let docs: Vec<&crate::DocState> = if all { s.documents().iter().collect() } else { s.active().into_iter().collect() };
+ docs.iter().map(|d| d.history.unique_bytes(&d.doc)).sum()
+}
+
+fn clip_bytes(s: &Session) -> usize {
+ s.clipboard.as_ref().map_or(0, |c| c.surface.tiles().map(|(_, t)| t.bytes().len()).sum())
+}
+
+fn purge(s: &mut Session, what: &str) -> Result<Value> {
+ let mut freed = 0usize;
+ let mut items: Vec<&str> = Vec::new();
+ if matches!(what, "undo" | "all") && s.active().is_some_and(|d| d.history.can_undo()) {
+ let before = history_bytes(s, false);
+ if let Some(st) = s.active_mut() {
+ st.history.purge_last();
+ }
+ freed += before.saturating_sub(history_bytes(s, false));
+ items.push("undo");
+ }
+ if matches!(what, "clipboard" | "all") && (s.clipboard.is_some() || s.style_clipboard.is_some()) {
+ freed += clip_bytes(s);
+ s.clipboard = None;
+ s.style_clipboard = None;
+ items.push("clipboard");
+ }
+ if matches!(what, "histories" | "all") {
+ let b = history_bytes(s, true);
+ if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) {
+ for st in &mut s.docs {
+ st.history.clear();
+ st.coalesce = None;
+ }
+ freed += b;
+ items.push("histories");
+ }
+ }
+ if what == "all" {
+ let fx = photocraft_compose::purge_effect_cache();
+ if fx > 0 {
+ freed += fx;
+ items.push("effect cache");
+ }
+ }
+ s.edit_state.fade = None;
+ let msg = if items.is_empty() { "nothing to purge".to_string() } else { format!("purged {}", items.join(", ")) };
+ Ok(json!({"purged": items, "bytes": freed, "message": msg}))
+}
+
+fn can_purge_undo(s: &Session) -> std::result::Result<(), String> {
+ s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to purge".into())
+}
+fn can_purge_clipboard(s: &Session) -> std::result::Result<(), String> {
+ if s.clipboard.is_some() || s.style_clipboard.is_some() { Ok(()) } else { Err("the clipboard is empty".into()) }
+}
+fn can_purge_histories(s: &Session) -> std::result::Result<(), String> {
+ if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { Ok(()) } else { Err("no history to purge".into()) }
+}
+fn can_purge_all(s: &Session) -> std::result::Result<(), String> {
+ can_purge_histories(s).or_else(|_| can_purge_clipboard(s)).or_else(|_| if photocraft_compose::effect_cache_bytes() > 0 { Ok(()) } else { Err("nothing to purge".into()) })
+}
+
+// ------------------------------------------------------------------ Content-Aware Fill
+
+fn can_caf(s: &Session) -> std::result::Result<(), String> {
+ pixel_layer(s)?;
+ let d = s.active().ok_or("no document open")?;
+ if d.doc.selection.as_ref().is_none_or(|m| m.content_bounds().is_empty()) {
+ return Err("make a selection around what to remove".into());
+ }
+ Ok(())
+}
+
+/// Mask surface (gray) of an alpha channel by index or name.
+fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> {
+ match v {
+ Value::Number(n) => doc.channels.get(n.as_u64()? as usize).map(|c| &c.surface),
+ Value::String(name) => doc.channels.iter().find(|c| c.name == *name).map(|c| &c.surface),
+ _ => None,
+ }
+}
+
+fn rect_param(p: &Value, key: &str) -> Option<Rect> {
+ let a = p.get(key)?.as_array()?;
+ let n = |i: usize| a.get(i).and_then(Value::as_f64).map(|v| v.round() as i32);
+ Some(Rect::new(n(0)?, n(1)?, n(0)? + n(2)?.max(0), n(1)? + n(3)?.max(0)))
+}
+
+fn content_aware_fill(s: &mut Session, p: &Value) -> Result<Value> {
+ use photocraft_algo::content_aware::{FillOptions, color_level, fill, rotation_level};
+ let cmd = "edit.contentAwareFill";
+ let id = pixel_layer(s).map_err(EngineError::Other)?;
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = st.doc.clone();
+ let sel = doc.selection.clone().ok_or_else(|| bad(cmd, "no selection"))?;
+ let hb = sel.content_bounds().intersect(&doc.bounds());
+ if hb.is_empty() {
+ return Err(bad(cmd, "the selection is outside the canvas"));
+ }
+ let ext = hb.width().max(hb.height()) as i32;
+ let sampling = str_or(p, "sampling", "auto");
+ let custom_mask = p.get("channel").and_then(|v| channel_mask(&doc, v));
+ let custom_rect = rect_param(p, "area");
+ let window = match sampling {
+ "auto" => hb.inflate((ext * 3 / 4).max(32)),
+ "rectangular" => hb.inflate(int(p, "margin").map_or(ext.max(16), |m| m.clamp(0, 100_000) as i32)),
+ "custom" => {
+ let r = match (custom_rect, custom_mask) {
+ (Some(r), _) => r,
+ (None, Some(m)) => m.content_bounds(),
+ (None, None) => return Err(bad(cmd, "custom sampling needs `area` [x,y,w,h] or `channel` (alpha channel index or name)")),
+ };
+ r.union(&hb).inflate(4)
+ }
+ other => return Err(bad(cmd, format!("unknown sampling `{other}` (auto|rectangular|custom)"))),
+ }
+ .intersect(&doc.bounds());
+ let opts = FillOptions {
+ color_adaptation: color_level(str_or(p, "colorAdaptation", "default")),
+ rotations: rotation_level(str_or(p, "rotationAdaptation", "none")),
+ scale: bool_or(p, "scale", false),
+ mirror: bool_or(p, "mirror", false),
+ seed: p.get("seed").and_then(Value::as_u64).unwrap_or(1),
+ };
+ let output = str_or(p, "output", "current").to_string();
+ if !matches!(output.as_str(), "current" | "new" | "duplicate") {
+ return Err(bad(cmd, "`output` must be current|new|duplicate"));
+ }
+ let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?;
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let (w, h) = (window.width() as usize, window.height() as usize);
+ let img = surf.read_region(window);
+ let mut cover = vec![0.0f32; w * h];
+ let mut hole = vec![false; w * h];
+ let mut source = vec![true; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ let (dx, dy) = (window.x0 + x as i32, window.y0 + y as i32);
+ let i = y * w + x;
+ cover[i] = sel.sample_channel(dx, dy, 0);
+ hole[i] = cover[i] > 0.0;
+ if sampling == "custom" {
+ source[i] = match (custom_rect, custom_mask) {
+ (Some(r), _) => r.contains(dx, dy),
+ (None, Some(m)) => m.sample_channel(dx, dy, 0) > 0.5,
+ _ => true,
+ };
+ }
+ }
+ }
+ let filled = fill(w, h, n, &img, &hole, &source, &opts);
+ let n_hole = hole.iter().filter(|h| **h).count();
+ let label = "Content-Aware Fill";
+ let layer = s.edit(label, |doc, active| {
+ let target = match output.as_str() {
+ "new" => {
+ let mut l = Layer::raster(doc.next_layer_name("Content-Aware Fill"), PixelFormat { alpha: true, ..fmt });
+ let mut px = vec![0.0f32; w * h * n.max(1)];
+ let lf = l.surface().map(|s| s.format()).unwrap_or(fmt);
+ let ln = lf.channels();
+ px.resize(w * h * ln, 0.0);
+ for i in 0..w * h {
+ if hole[i] {
+ let rgba = to_rgba(&fmt, &filled[i * n..(i + 1) * n]);
+ let mut enc = [0.0f32; 8];
+ from_rgba_into(&lf, [rgba[0], rgba[1], rgba[2], rgba[3] * cover[i]], &mut enc);
+ px[i * ln..(i + 1) * ln].copy_from_slice(&enc[..ln]);
+ }
+ }
+ if let Some(s) = l.surface_mut() {
+ s.write_region(window, &px);
+ s.prune();
+ }
+ let nid = doc.insert_above(Some(id), l);
+ *active = Some(nid);
+ return Ok(nid);
+ }
+ "duplicate" => {
+ let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate();
+ dup.name = format!("{} copy", dup.name);
+ let nid = doc.insert_above(Some(id), dup);
+ *active = Some(nid);
+ nid
+ }
+ _ => id,
+ };
+ let surf = writable_surface(doc, target)?;
+ let mut out = img.clone();
+ for (i, &k) in cover.iter().enumerate() {
+ if k > 0.0 {
+ for c in 0..n {
+ let j = i * n + c;
+ out[j] = img[j] + (filled[j] - img[j]) * k;
+ }
+ }
+ }
+ surf.write_region(window, &out);
+ Ok(target)
+ })?;
+ Ok(json!({"layer": layer.0, "filled": n_hole, "window": [window.x0, window.y0, window.width(), window.height()]}))
+}
+
+// ------------------------------------------------------------------ Content-Aware Scale
+
+fn content_aware_scale(s: &mut Session, p: &Value) -> Result<Value> {
+ use photocraft_algo::seam::{carve, resize_bilinear, skin_mask};
+ let cmd = "edit.contentAwareScale";
+ let id = pixel_layer(s).map_err(EngineError::Other)?;
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = st.doc.clone();
+ let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?;
+ let region = match &doc.selection {
+ Some(sel) => sel.content_bounds().intersect(&doc.bounds()),
+ None => surf.content_bounds(),
+ };
+ if region.is_empty() {
+ return Err(EngineError::Other("nothing to scale: the layer is empty".into()));
+ }
+ let (w, h) = (region.width() as usize, region.height() as usize);
+ let dim = |k: &str, pct: &str, cur: usize| -> Result<usize> {
+ let v = match (p.get(k).and_then(Value::as_f64), p.get(pct).and_then(Value::as_f64)) {
+ (Some(px), _) => px,
+ (None, Some(pc)) => cur as f64 * pc / 100.0,
+ (None, None) => cur as f64,
+ };
+ if !(1.0..=60_000.0).contains(&v) {
+ return Err(bad(cmd, format!("`{k}` must be 1..60000 px")));
+ }
+ Ok(v.round() as usize)
+ };
+ let (nw, nh) = (dim("width", "scaleX", w)?, dim("height", "scaleY", h)?);
+ let amount = f32_or(p, "amount", 100.0).clamp(0.0, 100.0) / 100.0;
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let img = surf.read_region(region);
+ // Protection: an alpha channel and/or skin tones.
+ let mut protect: Option<Vec<f32>> = None;
+ if let Some(m) = p.get("protect").filter(|v| !v.is_null() && v.as_str() != Some("none")).and_then(|v| channel_mask(&doc, v)) {
+ protect = Some((0..w * h).map(|i| m.sample_channel(region.x0 + (i % w) as i32, region.y0 + (i / w) as i32, 0)).collect());
+ } else if p.get("protect").is_some_and(|v| !v.is_null() && v.as_str() != Some("none")) {
+ return Err(bad(cmd, "`protect` must name an alpha channel (index or name) or \"none\""));
+ }
+ if bool_or(p, "protectSkinTones", false) {
+ let rgba: Vec<f32> = img.chunks_exact(n).flat_map(|px| to_rgba(&fmt, px)).collect();
+ let skin = skin_mask(w, h, 4, &rgba);
+ protect = Some(match protect {
+ Some(pm) => pm.iter().zip(&skin).map(|(a, b)| a.max(*b)).collect(),
+ None => skin,
+ });
+ }
+ let carved = if amount > 0.0 { carve(w, h, n, &img, protect.as_deref(), nw, nh) } else { Vec::new() };
+ let plain = if amount < 1.0 { resize_bilinear(w, h, n, &img, nw, nh) } else { Vec::new() };
+ let out: Vec<f32> = match (carved.is_empty(), plain.is_empty()) {
+ (false, true) => carved,
+ (true, false) => plain,
+ _ => carved.iter().zip(&plain).map(|(c, l)| l + (c - l) * amount).collect(),
+ };
+ let dst = Rect::from_xywh(region.x0, region.y0, nw as u32, nh as u32);
+ s.edit("Content-Aware Scale", |doc, _| {
+ let surf = writable_surface(doc, id)?;
+ crate::pixels::clear_surface(surf, region, None);
+ surf.write_region(dst, &out);
+ surf.prune();
+ Ok(())
+ })?;
+ Ok(json!({"from": [w, h], "to": [nw, nh], "bounds": [dst.x0, dst.y0, nw, nh]}))
+}
+
+// ------------------------------------------------------------------ Define Brush / Custom Shape
+
+fn define_brush_preset(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = match p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) {
+ Some(n) => n.to_string(),
+ None => {
+ let n = s.tools.presets.iter().filter(|b| b.name.starts_with("Sampled Brush")).count() + 1;
+ format!("Sampled Brush {n}")
+ }
+ };
+ s.execute("brush.defineFromSelection", json!({"name": name}))
+}
+
+/// The path Define Custom Shape uses: `"work"`, a saved path name, else the work path, the
+/// active shape layer, the active layer's vector mask, or the last saved path.
+fn current_path(doc: &Document, active: Option<LayerId>, spec: Option<&str>) -> Option<Path> {
+ let ok = |p: &Path| !p.subpaths.is_empty();
+ match spec {
+ Some("work") => return doc.work_path.clone().filter(ok),
+ Some(name) => return doc.paths.iter().find(|n| n.name == name).map(|n| n.path.clone()).filter(ok),
+ None => {}
+ }
+ if let Some(p) = doc.work_path.clone().filter(ok) {
+ return Some(p);
+ }
+ if let Some(l) = active.and_then(|id| doc.layer(id)) {
+ if let LayerContent::Shape(sh) = &l.content
+ && ok(&sh.path)
+ {
+ return Some(sh.path.clone());
+ }
+ if let Some(vm) = l.vector_mask.as_ref().filter(|v| ok(&v.path)) {
+ return Some(vm.path.clone());
+ }
+ }
+ doc.paths.last().map(|n| n.path.clone()).filter(ok)
+}
+
+fn can_define_shape(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ current_path(&d.doc, d.active_layer, None).map(|_| ()).ok_or_else(|| "select a path or shape layer first".into())
+}
+
+fn define_custom_shape(s: &mut Session, p: &Value) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let path = current_path(&st.doc, st.active_layer, p.get("path").and_then(Value::as_str)).ok_or_else(|| bad("edit.defineCustomShape", "no such path"))?;
+ let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| format!("Shape {}", s.edit_state.custom_shapes.len() + 1));
+ let shapes = &mut s.edit_state.custom_shapes;
+ match shapes.iter_mut().find(|c| c.name == name) {
+ Some(c) => c.path = path,
+ None => shapes.push(CustomShape { name: name.clone(), path }),
+ }
+ Ok(json!({"name": name, "count": shapes.len()}))
+}
+
+// ------------------------------------------------------------------ Find and Replace Text
+
+/// Byte ranges of `find` in `text` (case-insensitive unless `case`; whole words only with `whole`).
+pub fn find_matches(text: &str, find: &str, case: bool, whole: bool) -> Vec<(usize, usize)> {
+ if find.is_empty() {
+ return Vec::new();
+ }
+ let norm = |c: char| -> String { if case { c.to_string() } else { c.to_lowercase().collect() } };
+ let needle: String = find.chars().map(norm).collect();
+ let mut out = Vec::new();
+ let mut at = 0;
+ while at < text.len() {
+ // Compare char by char so case folding that changes byte lengths stays aligned.
+ let mut hay = String::new();
+ let mut end = at;
+ for (i, c) in text[at..].char_indices() {
+ if hay.len() >= needle.len() {
+ break;
+ }
+ hay.push_str(&norm(c));
+ end = at + i + c.len_utf8();
+ }
+ if hay == needle {
+ let word = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '_');
+ let before = text[..at].chars().next_back();
+ let after = text[end..].chars().next();
+ if !whole || (!word(before) && !word(after)) {
+ out.push((at, end));
+ at = end;
+ continue;
+ }
+ }
+ at += text[at..].chars().next().map_or(1, char::len_utf8);
+ }
+ out
+}
+
+fn type_layers(doc: &Document, forward: bool) -> Vec<LayerId> {
+ // Layers panel order: top first.
+ let mut ids: Vec<LayerId> = doc.walk().into_iter().rev().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_)) && !l.locks.all).map(|(_, _, l)| l.id).collect();
+ if !forward {
+ ids.reverse();
+ }
+ ids
+}
+
+fn has_type_layer(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if type_layers(&d.doc, true).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) }
+}
+
+fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.findAndReplaceText";
+ let find = p.get("find").and_then(Value::as_str).filter(|f| !f.is_empty()).ok_or_else(|| bad(cmd, "missing `find`"))?.to_string();
+ let replace = str_or(p, "replace", "").to_string();
+ let (case, whole, forward, all_layers) = (bool_or(p, "caseSensitive", false), bool_or(p, "wholeWord", false), bool_or(p, "forward", true), bool_or(p, "allLayers", true));
+ let action = str_or(p, "action", "changeAll").to_string();
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let mut layers = type_layers(&st.doc, forward);
+ if !all_layers {
+ let active = layer_param(s, p).ok();
+ layers.retain(|id| Some(*id) == active);
+ }
+ let text_of = |doc: &Document, id: LayerId| -> Option<String> {
+ match &doc.layer(id)?.content {
+ LayerContent::Text(t) => Some(t.text.clone()),
+ _ => None,
+ }
+ };
+ match action.as_str() {
+ "changeAll" => {
+ let doc = st.doc.clone();
+ let plan: Vec<(LayerId, Vec<(usize, usize)>)> = layers.iter().filter_map(|id| Some((*id, find_matches(&text_of(&doc, *id)?, &find, case, whole)))).filter(|(_, m)| !m.is_empty()).collect();
+ let count: usize = plan.iter().map(|(_, m)| m.len()).sum();
+ if count == 0 {
+ return Ok(json!({"count": 0, "layers": 0}));
+ }
+ s.edit("Replace All Text", |doc, _| {
+ let snapshot = doc.clone();
+ for (id, matches) in &plan {
+ if let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) {
+ for (a, b) in matches.iter().rev() {
+ crate::type_cmds::replace_text(t, *a, *b, &replace);
+ }
+ crate::type_cmds::refresh(&snapshot, t);
+ }
+ }
+ Ok(())
+ })?;
+ s.edit_state.find_cursor = None;
+ Ok(json!({"count": count, "layers": plan.len()}))
+ }
+ "find" | "change" | "changeFind" => {
+ let doc = st.doc.clone();
+ let cursor = s.edit_state.find_cursor;
+ let mut changed = None;
+ if action != "find"
+ && let Some((id, a, b)) = cursor
+ && text_of(&doc, id).is_some_and(|t| find_matches(&t, &find, case, whole).contains(&(a, b)))
+ {
+ s.edit("Replace Text", |doc, _| {
+ let snapshot = doc.clone();
+ if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) {
+ crate::type_cmds::replace_text(t, a, b, &replace);
+ crate::type_cmds::refresh(&snapshot, t);
+ }
+ Ok(())
+ })?;
+ let end = a + replace.len();
+ s.edit_state.find_cursor = Some((id, end, end));
+ changed = Some((id, a, end));
+ if action == "change" {
+ return Ok(json!({"changed": {"layer": id.0, "start": a, "end": end}}));
+ }
+ }
+ // Find the next match after the cursor (wrapping through the layers).
+ let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ let cursor = s.edit_state.find_cursor;
+ let start = cursor.and_then(|(id, _, _)| layers.iter().position(|l| *l == id)).unwrap_or(0);
+ for k in 0..=layers.len() {
+ let id = layers[(start + k) % layers.len().max(1)];
+ let Some(text) = text_of(&doc, id) else { continue };
+ let ms = find_matches(&text, &find, case, whole);
+ let hit = match (k, cursor) {
+ (0, Some((cid, a, b))) if cid == id => {
+ if forward {
+ ms.into_iter().find(|m| m.0 >= b)
+ } else {
+ ms.into_iter().rev().find(|m| m.1 <= a)
+ }
+ }
+ _ => {
+ if forward {
+ ms.into_iter().next()
+ } else {
+ ms.into_iter().next_back()
+ }
+ }
+ };
+ if let Some((a, b)) = hit {
+ s.edit_state.find_cursor = Some((id, a, b));
+ let _ = s.select_layer(id);
+ return Ok(json!({"found": {"layer": id.0, "start": a, "end": b, "text": &text[a..b]}, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}));
+ }
+ }
+ s.edit_state.find_cursor = None;
+ Ok(json!({"found": null, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}))
+ }
+ other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))),
+ }
+}
+
+// ------------------------------------------------------------------ presets
+
+/// Libraries the Preset Manager edits (patterns export as `.pat` with `pattern.export`).
+const PRESET_KINDS: [&str; 3] = ["brushes", "customShapes", "patterns"];
+
+fn preset_names(s: &Session, kind: &str) -> Option<Vec<String>> {
+ Some(match kind {
+ "brushes" => s.tools.presets.iter().map(|b| b.name.clone()).collect(),
+ "customShapes" => s.edit_state.custom_shapes.iter().map(|c| c.name.clone()).collect(),
+ "patterns" => s.patterns.items.iter().map(|p| p.name.clone()).collect(),
+ _ => return None,
+ })
+}
+
+/// Move item `i` of `v` to position `to`.
+fn move_item<T>(v: &mut Vec<T>, i: usize, to: usize) {
+ let x = v.remove(i);
+ let to = to.min(v.len());
+ v.insert(to, x);
+}
+
+fn preset_index(s: &Session, kind: &str, p: &Value) -> Result<usize> {
+ let names = preset_names(s, kind).ok_or_else(|| bad("edit.presets.presetManager", format!("unknown preset kind `{kind}` ({})", PRESET_KINDS.join("|"))))?;
+ if let Some(i) = p.get("index").and_then(Value::as_u64) {
+ return if (i as usize) < names.len() { Ok(i as usize) } else { Err(bad("edit.presets.presetManager", format!("no preset {i}"))) };
+ }
+ let name = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("edit.presets.presetManager", "give `index` or `name`"))?;
+ names.iter().position(|n| n == name).ok_or_else(|| bad("edit.presets.presetManager", format!("no preset named `{name}`")))
+}
+
+fn preset_manager(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.presets.presetManager";
+ let action = str_or(p, "action", "list");
+ if action == "list" {
+ let kinds: Vec<&str> = match p.get("kind").and_then(Value::as_str) {
+ Some(k) => vec![k],
+ None => PRESET_KINDS.to_vec(),
+ };
+ let mut out = serde_json::Map::new();
+ for k in kinds {
+ out.insert(k.to_string(), json!(preset_names(s, k).ok_or_else(|| bad(cmd, format!("unknown preset kind `{k}`")))?));
+ }
+ return Ok(Value::Object(out));
+ }
+ let kind = p.get("kind").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing `kind`"))?.to_string();
+ let i = preset_index(s, &kind, p)?;
+ match action {
+ "rename" => {
+ let new = p.get("newName").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `newName`"))?.to_string();
+ match kind.as_str() {
+ "brushes" => s.tools.presets[i].name = new,
+ "patterns" => s.patterns.items[i].name = new,
+ _ => s.edit_state.custom_shapes[i].name = new,
+ }
+ }
+ "delete" => match kind.as_str() {
+ "brushes" => drop(s.tools.presets.remove(i)),
+ "patterns" => drop(s.patterns.items.remove(i)),
+ _ => drop(s.edit_state.custom_shapes.remove(i)),
+ },
+ "move" => {
+ let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize;
+ match kind.as_str() {
+ "brushes" => move_item(&mut s.tools.presets, i, to),
+ "patterns" => move_item(&mut s.patterns.items, i, to),
+ _ => move_item(&mut s.edit_state.custom_shapes, i, to),
+ }
+ }
+ other => return Err(bad(cmd, format!("unknown action `{other}` (list|rename|delete|move)"))),
+ }
+ Ok(json!({kind.clone(): preset_names(s, &kind)}))
+}
+
+/// Exported preset file (`.pcpresets`, JSON).
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct PresetFile {
+ pub format: String,
+ pub version: u32,
+ pub brushes: Vec<photocraft_paint::BrushPreset>,
+ pub custom_shapes: Vec<CustomShape>,
+}
+
+pub const PRESET_FORMAT: &str = "photocraft-presets";
+
+fn export_import(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.presets.exportImportPresets";
+ let kinds: Vec<String> = p.get("kinds").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_else(|| ["brushes", "customShapes"].iter().map(|k| k.to_string()).collect());
+ let want = |k: &str| kinds.iter().any(|x| x == k);
+ match str_or(p, "action", "export") {
+ "export" => {
+ let file = PresetFile {
+ format: PRESET_FORMAT.into(),
+ version: 1,
+ brushes: if want("brushes") { s.tools.presets.iter().filter(|b| !b.builtin || bool_or(p, "includeBuiltins", false)).cloned().collect() } else { Vec::new() },
+ custom_shapes: if want("customShapes") { s.edit_state.custom_shapes.clone() } else { Vec::new() },
+ };
+ Ok(json!({"data": file, "brushes": file.brushes.len(), "customShapes": file.custom_shapes.len()}))
+ }
+ "import" => {
+ let data = p.get("data").cloned().ok_or_else(|| bad(cmd, "missing `data` (an exported preset file)"))?;
+ let data = match data {
+ Value::String(text) => serde_json::from_str(&text).map_err(|e| bad(cmd, format!("not a preset file: {e}")))?,
+ v => v,
+ };
+ let file: PresetFile = serde_json::from_value(data).map_err(|e| bad(cmd, format!("not a preset file: {e}")))?;
+ if file.format != PRESET_FORMAT {
+ return Err(bad(cmd, format!("not a preset file (format `{}`)", file.format)));
+ }
+ let (mut nb, mut ns) = (0, 0);
+ if want("brushes") {
+ for b in file.brushes {
+ match s.tools.presets.iter_mut().find(|x| x.name == b.name) {
+ Some(x) => *x = b,
+ None => s.tools.presets.push(b),
+ }
+ nb += 1;
+ }
+ }
+ if want("customShapes") {
+ for c in file.custom_shapes {
+ match s.edit_state.custom_shapes.iter_mut().find(|x| x.name == c.name) {
+ Some(x) => *x = c,
+ None => s.edit_state.custom_shapes.push(c),
+ }
+ ns += 1;
+ }
+ }
+ Ok(json!({"brushes": nb, "customShapes": ns}))
+ }
+ other => Err(bad(cmd, format!("unknown action `{other}` (export|import)"))),
+ }
+}
+
+// ------------------------------------------------------------------ specs
+
+macro_rules! spec {
+ ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true }
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!("edit.fade", "Fade…", ["Edit"], Some("Cmd+Shift+F"), r##"{"opacity":0..100=100,"mode":"normal|multiply|screen|overlay|softLight|hardLight|darken|lighten|difference|color|luminosity"}"##, can_fade, fade),
+ spec!("edit.purge.undo", "Undo", ["Edit", "Purge"], None, "{}", can_purge_undo, |s, _| purge(s, "undo")),
+ spec!("edit.purge.clipboard", "Clipboard", ["Edit", "Purge"], None, "{}", can_purge_clipboard, |s, _| purge(s, "clipboard")),
+ spec!("edit.purge.histories", "Histories", ["Edit", "Purge"], None, "{}", can_purge_histories, |s, _| purge(s, "histories")),
+ spec!("edit.purge.videoCache", "Video Cache", ["Edit", "Purge"], None, "{}", always, |_, _| Ok(json!({"purged": [], "bytes": 0, "message": "nothing to purge (no video layers)"}))),
+ spec!("edit.purge.all", "All", ["Edit", "Purge"], None, "{}", can_purge_all, |s, _| purge(s, "all")),
+ spec!(
+ "edit.contentAwareFill",
+ "Content-Aware Fill…",
+ ["Edit"],
+ None,
+ r##"{"sampling":"auto|rectangular|custom","margin":px?,"area":[x,y,w,h]?,"channel":index|name?,"colorAdaptation":"default|none|high|veryHigh","rotationAdaptation":"none|low|medium|high|full","scale":bool=false,"mirror":bool=false,"output":"current|new|duplicate","seed":u64=1}"##,
+ can_caf,
+ content_aware_fill
+ ),
+ spec!(
+ "edit.contentAwareScale",
+ "Content-Aware Scale",
+ ["Edit"],
+ Some("Cmd+Alt+Shift+C"),
+ r##"{"width":px?,"height":px?,"scaleX":1..400=100,"scaleY":1..400=100,"amount":0..100=100,"protect":"none"|channel index|name,"protectSkinTones":bool=false}"##,
+ |s| pixel_layer(s).map(|_| ()),
+ content_aware_scale
+ ),
+ spec!("edit.defineBrushPreset", "Define Brush Preset…", ["Edit"], None, r##"{"name":text}"##, |s| if s.is_enabled("brush.defineFromSelection") { Ok(()) } else { Err("select pixels to define a brush from".into()) }, define_brush_preset),
+ spec!("edit.defineCustomShape", "Define Custom Shape…", ["Edit"], None, r##"{"name":text,"path":"work|<saved path name>"?}"##, can_define_shape, define_custom_shape),
+ spec!(
+ "edit.findAndReplaceText",
+ "Find and Replace Text…",
+ ["Edit"],
+ None,
+ r##"{"find":text,"replace":text,"action":"changeAll|find|change|changeFind","caseSensitive":bool=false,"wholeWord":bool=false,"forward":bool=true,"allLayers":bool=true}"##,
+ has_type_layer,
+ find_replace
+ ),
+ spec!("edit.presets.presetManager", "Preset Manager…", ["Edit", "Presets"], None, r##"{"action":"list|rename|delete|move","kind":"brushes|customShapes|patterns","index":n?,"name":str?,"newName":str?,"to":n?}"##, always, preset_manager),
+ spec!("edit.presets.exportImportPresets", "Export/Import Presets…", ["Edit", "Presets"], None, r##"{"action":"export|import","kinds":["brushes","customShapes"]?,"data":json (import),"includeBuiltins":bool=false}"##, always, export_import),
+ ]
+}
+
+/// The custom shape library (for the Custom Shape tool).
+pub fn custom_shapes(s: &Session) -> &[CustomShape] {
+ &s.edit_state.custom_shapes
+}
+
+#[cfg(test)]
+#[path = "edit_menu_cmds/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/edit_menu_cmds/tests.rs b/crates/engine/src/edit_menu_cmds/tests.rs
new file mode 100644
index 000000000..3b402dee9
--- /dev/null
+++ b/crates/engine/src/edit_menu_cmds/tests.rs
@@ -0,0 +1,273 @@
+use super::*;
+use photocraft_doc::vector::Subpath;
+
+fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth, "background": "white"})).unwrap();
+ s
+}
+
+fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
+ let st = s.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)
+}
+
+fn active(s: &Session) -> &Layer {
+ let st = s.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap()
+}
+
+#[test]
+fn fade_blends_last_step_at_all_depths() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ assert!(!s.is_enabled("edit.fade"), "nothing to fade yet");
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ assert!(s.is_enabled("edit.fade"));
+ let undo_steps = s.active().unwrap().history.past_len();
+ s.execute("edit.fade", json!({"opacity": 25})).unwrap();
+ let v = px(&s, 5, 5);
+ assert!((v[0] - 0.75).abs() < 0.01, "depth {depth}: {v:?}");
+ // One history step, labelled after the faded command, and Fade can't repeat.
+ assert_eq!(s.active().unwrap().history.past_len(), undo_steps + 1);
+ assert_eq!(s.active().unwrap().history.undo_label(), Some("Fade Fill"));
+ assert!(!s.is_enabled("edit.fade"));
+ s.undo();
+ assert_eq!(px(&s, 5, 5)[0], 0.0);
+ }
+}
+
+#[test]
+fn fade_with_blend_mode_and_invalidation() {
+ let mut s = session(8);
+ s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
+ s.execute("image.adjustments.invert", json!({})).unwrap();
+ // Difference of grey and inverted grey at 100%: |0.502 − 0.498| ≈ 0.
+ s.execute("edit.fade", json!({"opacity": 100, "mode": "difference"})).unwrap();
+ assert!(px(&s, 1, 1)[0] < 0.02);
+ // Any other edit in between disables Fade.
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ assert!(!s.is_enabled("edit.fade"));
+ assert!(s.execute("edit.fade", json!({})).is_err());
+ // Queries don't.
+ s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();
+ s.execute("document.inspect", json!({})).unwrap();
+ assert!(s.is_enabled("edit.fade"));
+ assert!(s.execute("edit.fade", json!({"mode": "nonsense"})).is_err());
+}
+
+#[test]
+fn purge_commands() {
+ let mut s = session(8);
+ assert!(!s.is_enabled("edit.purge.undo"));
+ assert!(s.is_enabled("edit.purge.videoCache"));
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ let r = s.execute("edit.purge.undo", json!({})).unwrap();
+ assert_eq!(r["purged"][0], "undo");
+ assert!(r["bytes"].as_u64().unwrap() > 0);
+ // One step left to undo (the black fill is gone from history).
+ assert!(s.undo());
+ assert!(!s.undo());
+ s.execute("select.all", json!({})).unwrap();
+ s.execute("edit.copy", json!({})).unwrap();
+ assert!(s.is_enabled("edit.purge.clipboard"));
+ s.execute("edit.purge.clipboard", json!({})).unwrap();
+ assert!(s.clipboard.is_none());
+ assert!(!s.is_enabled("edit.purge.clipboard"));
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ s.execute("edit.purge.histories", json!({})).unwrap();
+ assert!(s.documents().iter().all(|d| !d.history.can_undo()));
+ assert!(!s.is_enabled("edit.purge.histories"));
+ assert_eq!(s.execute("edit.purge.videoCache", json!({})).unwrap()["bytes"], 0);
+ let _ = s.execute("edit.purge.all", json!({}));
+}
+
+/// White canvas with vertical black stripes, a red blob to remove, and a selection around it.
+fn blob_session(depth: u32) -> Session {
+ let mut s = session(depth);
+ s.edit("stripes", |doc, active| {
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ for x in (0..64).step_by(8) {
+ surf.fill_rect(Rect::new(x, 0, x + 3, 48), &[0.0, 0.0, 0.0, 1.0]);
+ }
+ surf.fill_rect(Rect::new(28, 18, 36, 28), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("select.rect", json!({"x": 26, "y": 16, "width": 12, "height": 14})).unwrap();
+ s
+}
+
+#[test]
+fn content_aware_fill_removes_object_at_all_depths() {
+ for depth in [8, 16, 32] {
+ let mut s = blob_session(depth);
+ assert!(s.is_enabled("edit.contentAwareFill"));
+ let r = s.execute("edit.contentAwareFill", json!({"colorAdaptation": "none"})).unwrap();
+ assert!(r["filled"].as_u64().unwrap() > 100);
+ for (x, y) in [(30, 20), (33, 25)] {
+ let v = px(&s, x, y);
+ assert!(!(v[0] > 0.9 && v[1] < 0.1), "depth {depth}: red left at ({x},{y}): {v:?}");
+ }
+ // Outside the selection untouched.
+ assert_eq!(px(&s, 1, 1)[0], 0.0);
+ assert_eq!(px(&s, 4, 1)[0], 1.0);
+ s.undo();
+ assert_eq!(px(&s, 30, 20)[1], 0.0, "undo restores the blob");
+ }
+}
+
+#[test]
+fn content_aware_fill_outputs_and_sampling() {
+ let mut s = blob_session(8);
+ let base = s.active().unwrap().active_layer.unwrap();
+ let r = s.execute("edit.contentAwareFill", json!({"output": "new", "sampling": "rectangular", "margin": 12})).unwrap();
+ let nid = LayerId(r["layer"].as_u64().unwrap());
+ assert_ne!(nid, base);
+ // The new layer holds only the fill.
+ let l = s.active().unwrap().doc.layer(nid).unwrap();
+ let b = l.surface().unwrap().content_bounds();
+ assert!(Rect::new(26, 16, 38, 30).contains_rect(&b), "{b:?}");
+ s.undo();
+ let r = s.execute("edit.contentAwareFill", json!({"output": "duplicate", "sampling": "custom", "area": [0, 0, 20, 48], "mirror": true})).unwrap();
+ assert_eq!(s.active().unwrap().doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap().name, "Background copy");
+ assert!(s.execute("edit.contentAwareFill", json!({"sampling": "custom"})).is_err());
+ assert!(s.execute("edit.contentAwareFill", json!({"output": "elsewhere"})).is_err());
+ s.execute("select.deselect", json!({})).unwrap();
+ assert!(!s.is_enabled("edit.contentAwareFill"));
+}
+
+#[test]
+fn content_aware_scale_keeps_subject() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("paint", |doc, active| {
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ surf.fill_rect(Rect::new(0, 0, 64, 48), &[0.5, 0.5, 0.5, 1.0]);
+ for x in 20..26 {
+ let c = if x % 2 == 0 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] };
+ surf.fill_rect(Rect::new(x, 0, x + 1, 48), &c);
+ }
+ Ok(())
+ })
+ .unwrap();
+ let r = s.execute("edit.contentAwareScale", json!({"width": 40})).unwrap();
+ assert_eq!(r["to"], json!([40, 48]));
+ let surf = active(&s).surface().unwrap();
+ assert_eq!(surf.content_bounds(), Rect::new(0, 0, 40, 48), "depth {depth}");
+ let striped = (0..40).filter(|x| {
+ let p = surf.pixel(*x, 10);
+ p[1] < 0.05 && (p[0] > 0.95 || p[2] > 0.95)
+ });
+ assert_eq!(striped.count(), 6, "depth {depth}: the striped subject survives");
+ s.undo();
+ assert_eq!(active(&s).surface().unwrap().content_bounds().width(), 64);
+ }
+}
+
+#[test]
+fn content_aware_scale_params() {
+ let mut s = session(8);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("paint", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 32, 32), &[0.8, 0.6, 0.5, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let r = s.execute("edit.contentAwareScale", json!({"scaleX": 150, "scaleY": 50, "amount": 50, "protectSkinTones": true})).unwrap();
+ assert_eq!(r["to"], json!([48, 16]));
+ assert!(s.execute("edit.contentAwareScale", json!({"width": 0})).is_err());
+ assert!(s.execute("edit.contentAwareScale", json!({"protect": "no such channel"})).is_err());
+}
+
+fn square_path(x: f64, y: f64, w: f64) -> Path {
+ Path::new(vec![Subpath::polygon(&[(x, y), (x + w, y), (x + w, y + w), (x, y + w)])])
+}
+
+#[test]
+fn define_custom_shape_and_preset_manager() {
+ let mut s = session(8);
+ assert!(!s.is_enabled("edit.defineCustomShape"));
+ s.edit("path", |doc, _| {
+ doc.work_path = Some(square_path(4.0, 4.0, 10.0));
+ Ok(())
+ })
+ .unwrap();
+ s.execute("edit.defineCustomShape", json!({"name": "Box"})).unwrap();
+ s.execute("edit.defineCustomShape", json!({})).unwrap();
+ assert_eq!(custom_shapes(&s).len(), 2);
+ assert_eq!(custom_shapes(&s)[1].name, "Shape 2");
+ let list = s.execute("edit.presets.presetManager", json!({})).unwrap();
+ assert_eq!(list["customShapes"], json!(["Box", "Shape 2"]));
+ assert!(list["brushes"].as_array().unwrap().len() > 3);
+ s.execute("edit.presets.presetManager", json!({"action": "rename", "kind": "customShapes", "name": "Shape 2", "newName": "Star"})).unwrap();
+ s.execute("edit.presets.presetManager", json!({"action": "move", "kind": "customShapes", "index": 1, "to": 0})).unwrap();
+ assert_eq!(custom_shapes(&s)[0].name, "Star");
+ s.execute("edit.presets.presetManager", json!({"action": "delete", "kind": "customShapes", "name": "Box"})).unwrap();
+ assert_eq!(custom_shapes(&s).len(), 1);
+ assert!(s.execute("edit.presets.presetManager", json!({"action": "delete", "kind": "gradients", "index": 0})).is_err());
+ // The pattern library (Edit › Define Pattern) is managed here too.
+ let n = list["patterns"].as_array().unwrap().len();
+ assert!(n > 0);
+ s.execute("edit.presets.presetManager", json!({"action": "rename", "kind": "patterns", "index": 0, "newName": "First"})).unwrap();
+ s.execute("edit.presets.presetManager", json!({"action": "delete", "kind": "patterns", "name": "First"})).unwrap();
+ assert_eq!(s.patterns.items.len(), n - 1);
+ // Export → import into a fresh session.
+ s.execute("brush.presets.save", json!({"name": "Mine"})).unwrap();
+ let out = s.execute("edit.presets.exportImportPresets", json!({"action": "export"})).unwrap();
+ assert_eq!(out["brushes"], 1, "built-ins are not exported by default");
+ let mut t = Session::new();
+ let r = t.execute("edit.presets.exportImportPresets", json!({"action": "import", "data": out["data"].to_string()})).unwrap();
+ assert_eq!((r["brushes"].as_u64(), r["customShapes"].as_u64()), (Some(1), Some(1)));
+ assert!(t.tools.presets.iter().any(|b| b.name == "Mine"));
+ assert_eq!(custom_shapes(&t)[0].path, custom_shapes(&s)[0].path);
+ assert!(t.execute("edit.presets.exportImportPresets", json!({"action": "import", "data": {"format": "other"}})).is_err());
+}
+
+#[test]
+fn define_brush_preset_wraps_define_from_selection() {
+ let mut s = session(8);
+ assert!(!s.is_enabled("edit.defineBrushPreset"));
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
+ s.execute("edit.defineBrushPreset", json!({})).unwrap();
+ assert!(s.tools.presets.iter().any(|b| b.name == "Sampled Brush 1"));
+}
+
+#[test]
+fn find_matches_cases() {
+ assert_eq!(find_matches("Cat cat CAT", "cat", false, false), vec![(0, 3), (4, 7), (8, 11)]);
+ assert_eq!(find_matches("Cat cat CAT", "cat", true, false), vec![(4, 7)]);
+ assert_eq!(find_matches("cat catalog bobcat", "cat", false, true), vec![(0, 3)]);
+ assert_eq!(find_matches("Straße STRASSE", "straße", false, false), vec![(0, 7)]);
+ assert!(find_matches("abc", "", false, false).is_empty());
+}
+
+#[test]
+fn find_and_replace_across_type_layers() {
+ let mut s = session(8);
+ assert!(!s.is_enabled("edit.findAndReplaceText"));
+ s.execute("type.create", json!({"text": "Hello world", "x": 4, "y": 20, "size": 12})).unwrap();
+ s.execute("type.create", json!({"text": "world peace, World", "x": 4, "y": 40, "size": 12})).unwrap();
+ let r = s.execute("edit.findAndReplaceText", json!({"find": "world", "replace": "planet"})).unwrap();
+ assert_eq!((r["count"].as_u64(), r["layers"].as_u64()), (Some(3), Some(2)));
+ let texts: Vec<String> = s.active().unwrap().doc.walk().into_iter().filter_map(|(_, _, l)| match &l.content {
+ LayerContent::Text(t) => Some(t.text.clone()),
+ _ => None,
+ }).collect();
+ assert!(texts.contains(&"Hello planet".to_string()), "{texts:?}");
+ assert!(texts.contains(&"planet peace, planet".to_string()), "{texts:?}");
+ s.undo();
+ // Step through matches: case-sensitive finds only lower-case "world".
+ let f1 = s.execute("edit.findAndReplaceText", json!({"find": "world", "action": "find", "caseSensitive": true})).unwrap();
+ assert_eq!(f1["found"]["text"], "world");
+ let f2 = s.execute("edit.findAndReplaceText", json!({"find": "world", "action": "changeFind", "replace": "Earth", "caseSensitive": true})).unwrap();
+ assert!(f2["changed"].is_object());
+ assert_eq!(f2["found"]["text"], "world");
+ assert_ne!(f2["found"]["layer"], f2["changed"]["layer"]);
+ assert!(s.execute("edit.findAndReplaceText", json!({"find": ""})).is_err());
+}
diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs
new file mode 100644
index 000000000..d744bb310
--- /dev/null
+++ b/crates/engine/src/extra_cmds.rs
@@ -0,0 +1,825 @@
+//! Everyday Photoshop commands that build on the core ones: Edit › Stroke, the fixed Transform
+//! presets (Rotate 180°/90°, Flip), Paste Into, Reselect, Equalize, Reveal All, Layer from
+//! Background, Copy/Paste Layer Style, Hide All Effects, layer-mask toggles, Rasterize variants,
+//! Delete Hidden / Empty Layers, Ungroup, Hide/Show Layers, Average and Clouds.
+
+use photocraft_algo::selection as sel;
+use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerMask};
+use photocraft_geom::Rect;
+use photocraft_raster::{from_rgba_into, to_rgba};
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, color_param, layer_param};
+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 active_layer(s: &Session) -> std::result::Result<&Layer, String> {
+ let d = s.active().ok_or("no document open")?;
+ d.active_layer.and_then(|id| d.doc.layer(id)).ok_or_else(|| "no active layer".into())
+}
+
+fn has_layer(s: &Session) -> std::result::Result<(), String> {
+ active_layer(s).map(|_| ())
+}
+
+fn has_pixels(s: &Session) -> std::result::Result<(), String> {
+ match active_layer(s)?.content {
+ LayerContent::Raster(_) => Ok(()),
+ ref c => Err(format!("active layer is a {} layer, not a pixel layer", c.kind_name())),
+ }
+}
+
+fn has_mask(s: &Session) -> std::result::Result<(), String> {
+ active_layer(s)?.mask.as_ref().map(|_| ()).ok_or_else(|| "the active layer has no layer mask".into())
+}
+
+fn has_clip_and_selection(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ s.clipboard.as_ref().ok_or("the clipboard is empty")?;
+ d.doc.selection.as_ref().map(|_| ()).ok_or_else(|| "Paste Into needs a selection".into())
+}
+
+fn is_background(l: &Layer) -> bool {
+ l.name == "Background" && l.locks.transparency && l.locks.position && matches!(l.content, LayerContent::Raster(_))
+}
+
+fn has_background(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ d.doc.layers.first().filter(|l| is_background(l)).map(|_| ()).ok_or_else(|| "the document has no Background layer".into())
+}
+
+/// A key that makes the sub-commands of one command share a single history step.
+fn step_key(s: &Session, what: &str) -> String {
+ format!("{what}#{}", s.active().map_or(0, |d| d.revision))
+}
+
+// ---------- pixel helpers ----------
+
+/// Rewrite the active pixel layer's RGBA over the selection bounds (or the canvas). `f` gets the
+/// area, the pixels, and the selection coverage per pixel; results are blended back by coverage,
+/// and transparency stays locked when the layer locks it.
+fn map_pixels(s: &mut Session, label: &str, f: impl FnOnce(Rect, &mut [[f32; 4]], &[f32])) -> Result<Value> {
+ let id = layer_param(s, &Value::Null)?;
+ s.edit(label, |doc, _| {
+ let canvas = doc.bounds();
+ let selection = doc.selection.clone();
+ let area = selection.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas));
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ if l.locks.pixels || l.locks.all {
+ return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name)));
+ }
+ let lock_alpha = l.locks.transparency;
+ let surf = l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?;
+ if area.is_empty() {
+ return Ok(());
+ }
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let mut raw = surf.read_region(area);
+ let orig: Vec<[f32; 4]> = raw.chunks_exact(n).map(|p| to_rgba(&fmt, p)).collect();
+ let w = area.width() as usize;
+ let cover: Vec<f32> = match &selection {
+ Some(m) => (0..orig.len()).map(|i| m.sample_channel(area.x0 + (i % w) as i32, area.y0 + (i / w) as i32, 0)).collect(),
+ None => vec![1.0; orig.len()],
+ };
+ let mut px = orig.clone();
+ f(area, &mut px, &cover);
+ let mut enc = [0.0f32; 8];
+ for (i, out) in raw.chunks_exact_mut(n).enumerate() {
+ let k = cover[i];
+ if k <= 0.0 {
+ continue;
+ }
+ let (o, p) = (orig[i], px[i]);
+ let mut v = [0.0; 4];
+ for c in 0..4 {
+ v[c] = o[c] + (p[c] - o[c]) * k;
+ }
+ if lock_alpha {
+ v[3] = o[3];
+ }
+ from_rgba_into(&fmt, v, &mut enc);
+ out.copy_from_slice(&enc[..n]);
+ }
+ surf.write_region(area, &raw);
+ surf.prune();
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+/// Edit › Stroke: a band along the selection edge (or the layer's opaque edge without a selection).
+fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
+ let width = p.get("width").and_then(Value::as_f64).unwrap_or(1.0).clamp(1.0, 250.0) as f32;
+ let mut color = color_param(p, "color", s.tools.foreground);
+ color[3] *= (p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0) as f32 / 100.0).clamp(0.0, 1.0);
+ let location = p.get("location").and_then(Value::as_str).unwrap_or("center").to_string();
+ let id = layer_param(s, p)?;
+ s.edit("Stroke", |doc, _| {
+ let canvas = doc.bounds();
+ let (w, h) = (canvas.width() as usize, canvas.height() as usize);
+ let edge = match &doc.selection {
+ Some(m) => sel::mask_from_surface(Some(m), canvas),
+ None => {
+ let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let surf = l.surface().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?;
+ let mut px = vec![[0.0f32; 4]; w * h];
+ surf.read_rgba_into(canvas, &mut px);
+ px.iter().map(|p| p[3]).collect()
+ }
+ };
+ let (outer, inner) = match location.as_str() {
+ "inside" => (edge.clone(), sel::contract(&edge, w, h, width)),
+ "outside" => (sel::expand(&edge, w, h, width), edge.clone()),
+ _ => (sel::expand(&edge, w, h, width / 2.0), sel::contract(&edge, w, h, width / 2.0)),
+ };
+ let band: Vec<f32> = outer.iter().zip(&inner).map(|(o, i)| (o - i).clamp(0.0, 1.0)).collect();
+ let band = sel::mask_to_surface(&band, canvas);
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let lock = l.locks.transparency;
+ let surf = crate::commands::paint_surface(l, &Value::Null)?;
+ let area = band.content_bounds().intersect(&canvas);
+ if !area.is_empty() {
+ crate::pixels::fill_surface(surf, area, color, Some(&band), lock);
+ surf.prune();
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+/// Histogram equalization, like Photoshop's: one CDF over the R, G and B values of
+/// the selected pixels, applied to every channel.
+fn equalize(s: &mut Session) -> Result<Value> {
+ map_pixels(s, "Equalize", |_, px, cover| {
+ let mut hist = [0f64; 256];
+ for (p, &k) in px.iter().zip(cover) {
+ if k > 0.0 && p[3] > 0.0 {
+ for &v in &p[..3] {
+ hist[(v.clamp(0.0, 1.0) * 255.0).round() as usize] += 1.0;
+ }
+ }
+ }
+ let total: f64 = hist.iter().sum();
+ if total == 0.0 {
+ return;
+ }
+ let first = hist.iter().copied().find(|v| *v > 0.0).unwrap_or(0.0);
+ let mut lut = [0f32; 256];
+ let mut acc = 0.0;
+ for (i, h) in hist.iter().enumerate() {
+ acc += h;
+ lut[i] = if total > first { ((acc - first) / (total - first)).clamp(0.0, 1.0) as f32 } else { i as f32 / 255.0 };
+ }
+ // Same 256 bins as the histogram, at every depth (like Photoshop).
+ let map = |v: f32| lut[(v.clamp(0.0, 1.0) * 255.0).round() as usize];
+ for p in px.iter_mut() {
+ for v in &mut p[..3] {
+ *v = map(*v);
+ }
+ }
+ })
+}
+
+/// Filter › Blur › Average: the selection (or layer) filled with its mean colour.
+fn average(s: &mut Session) -> Result<Value> {
+ map_pixels(s, "Average", |_, px, cover| {
+ let (mut sum, mut wsum, mut asum, mut n) = ([0f64; 3], 0f64, 0f64, 0f64);
+ for (p, &k) in px.iter().zip(cover) {
+ let w = (p[3] * k) as f64;
+ for c in 0..3 {
+ sum[c] += p[c] as f64 * w;
+ }
+ wsum += w;
+ asum += (p[3] * k) as f64;
+ n += k as f64;
+ }
+ if wsum <= 0.0 {
+ return;
+ }
+ let avg = [(sum[0] / wsum) as f32, (sum[1] / wsum) as f32, (sum[2] / wsum) as f32, (asum / n.max(1e-9)) as f32];
+ px.fill(avg);
+ })
+}
+
+fn hash(x: i32, y: i32, seed: u32) -> f32 {
+ let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f);
+ h ^= h >> 13;
+ h = h.wrapping_mul(0x5bd1_e995);
+ h ^= h >> 15;
+ (h & 0x00ff_ffff) as f32 / 0x00ff_ffff as f32
+}
+
+/// Smooth value noise, summed over octaves (fBm), in 0..1.
+pub(crate) fn clouds_value(x: f32, y: f32, base: f32, seed: u32) -> f32 {
+ let (mut sum, mut amp, mut freq, mut norm) = (0.0, 1.0, 1.0 / base, 0.0);
+ for o in 0..8u32 {
+ let (fx, fy) = (x * freq, y * freq);
+ let (ix, iy) = (fx.floor() as i32, fy.floor() as i32);
+ let (tx, ty) = (fx - ix as f32, fy - iy as f32);
+ let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty));
+ let s = seed.wrapping_add(o * 7919);
+ let top = hash(ix, iy, s) + (hash(ix + 1, iy, s) - hash(ix, iy, s)) * sx;
+ let bot = hash(ix, iy + 1, s) + (hash(ix + 1, iy + 1, s) - hash(ix, iy + 1, s)) * sx;
+ sum += (top + (bot - top) * sy) * amp;
+ norm += amp;
+ amp *= 0.5;
+ freq *= 2.0;
+ }
+ // Stretch the bell-shaped sum so the clouds use the full foreground→background range.
+ ((sum / norm - 0.5) * 2.2 + 0.5).clamp(0.0, 1.0)
+}
+
+/// Filter › Render › Clouds / Difference Clouds, between the foreground and background colours.
+fn clouds(s: &mut Session, p: &Value, difference: bool) -> Result<Value> {
+ let (fg, bg) = (s.tools.foreground, s.tools.background);
+ let seed = p.get("seed").and_then(Value::as_u64).unwrap_or(0) as u32;
+ let size = s.active().map_or(256.0, |d| d.doc.size.width.max(d.doc.size.height) as f32);
+ let base = (size / 4.0).clamp(16.0, 512.0);
+ map_pixels(s, if difference { "Difference Clouds" } else { "Clouds" }, |area, px, _| {
+ let w = area.width() as usize;
+ for (i, p) in px.iter_mut().enumerate() {
+ let (x, y) = ((area.x0 + (i % w) as i32) as f32, (area.y0 + (i / w) as i32) as f32);
+ let t = clouds_value(x, y, base, seed);
+ let c: [f32; 3] = std::array::from_fn(|k| fg[k] + (bg[k] - fg[k]) * t);
+ if difference {
+ for k in 0..3 {
+ p[k] = (p[k] - c[k]).abs();
+ }
+ } else {
+ *p = [c[0], c[1], c[2], 1.0];
+ }
+ }
+ })
+}
+
+// ---------- transform presets ----------
+
+fn transform_preset(s: &mut Session, kind: &str) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?;
+ let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let b = crate::transform_cmds::transform_bounds(&d.doc, l);
+ if b.is_empty() {
+ return Err(EngineError::Other("nothing to transform".into()));
+ }
+ // Integer offsets keep these exact pixel permutations on the grid (nearest sampling).
+ let (sx, sy) = ((b.x0 + b.x1) as f64, (b.y0 + b.y1) as f64);
+ let (cx, cy) = (sx / 2.0, sy / 2.0);
+ let m: [f64; 6] = match kind {
+ "rotate180" => [-1.0, 0.0, 0.0, -1.0, sx, sy],
+ "rotate90Cw" => [0.0, 1.0, -1.0, 0.0, (cx + cy).round(), (cy - cx).round()],
+ "rotate90Ccw" => [0.0, -1.0, 1.0, 0.0, (cx - cy).round(), (cx + cy).round()],
+ "flipHorizontal" => [-1.0, 0.0, 0.0, 1.0, sx, 0.0],
+ _ => [1.0, 0.0, 0.0, -1.0, 0.0, sy],
+ };
+ s.execute("edit.transform", json!({"layer": id.0, "matrix": m, "interpolation": "nearest"}))
+}
+
+// ---------- selection / clipboard ----------
+
+fn reselect_target(s: &Session) -> Option<photocraft_raster::Surface> {
+ let d = s.active()?;
+ if d.doc.selection.is_some() {
+ return None;
+ }
+ (0..d.history.past_len()).rev().find_map(|i| d.history.state(i).and_then(|doc| doc.selection.clone()))
+}
+
+fn can_reselect(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ reselect_target(s).map(|_| ()).ok_or_else(|| "there is no selection to restore".into())
+}
+
+fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let selection = d.doc.selection.clone().ok_or(EngineError::Other("Paste Into needs a selection".into()))?;
+ let b = selection.content_bounds();
+ let key = step_key(s, "pasteInto");
+ let mut params = json!({"center": [(b.x0 + b.x1) as f64 / 2.0, (b.y0 + b.y1) as f64 / 2.0], "coalesce": key});
+ if let Some(c) = p.get("center") {
+ params["center"] = c.clone();
+ }
+ let r = s.execute("edit.paste", params)?;
+ let id = layer_param(s, &Value::Null)?;
+ s.execute("layer.layerMask.revealAll", json!({"layer": id.0, "coalesce": key}))?;
+ s.coalesce_request = Some(key);
+ let r2 = s.edit(if outside { "Paste Outside" } else { "Paste Into" }, |doc, _| {
+ let canvas = doc.bounds();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let surface = if outside {
+ // Everything but the selection: default reveal, the selection's area inverted.
+ let area = b.intersect(&canvas);
+ let inv: Vec<f32> = sel::mask_from_surface(Some(&selection), area).iter().map(|v| 1.0 - v).collect();
+ let mut m = photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[1.0]);
+ m.write_region(area, &inv);
+ m
+ } else {
+ selection
+ };
+ l.mask = Some(LayerMask { surface, linked: false, ..LayerMask::reveal_all() });
+ Ok(())
+ });
+ s.coalesce_request = None;
+ r2?;
+ Ok(r)
+}
+
+// ---------- layers ----------
+
+fn layer_from_background(s: &mut Session) -> Result<Value> {
+ let id = s.edit("Layer From Background", |doc, active| {
+ let l = doc.layers.first_mut().filter(|l| is_background(l)).ok_or(EngineError::Other("the document has no Background layer".into()))?;
+ l.name = "Layer 0".into();
+ l.locks.transparency = false;
+ l.locks.position = false;
+ *active = Some(l.id);
+ Ok(l.id)
+ })?;
+ Ok(json!({"layer": id.0}))
+}
+
+fn toggle_mask(s: &mut Session, p: &Value, key: &str) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ let label = if key == "enabled" { "Enable/Disable Layer Mask" } else { "Link/Unlink Layer Mask" };
+ let v = s.edit(label, |doc, _| {
+ let m = doc.layer_mut(id).and_then(|l| l.mask.as_mut()).ok_or(EngineError::Other("the layer has no layer mask".into()))?;
+ let slot = if key == "enabled" { &mut m.enabled } else { &mut m.linked };
+ *slot = p.get(key).and_then(Value::as_bool).unwrap_or(!*slot);
+ Ok(*slot)
+ })?;
+ Ok(json!({ key: v }))
+}
+
+fn set_all_effects(s: &mut Session, enabled: bool) -> Result<Value> {
+ s.edit(if enabled { "Show All Effects" } else { "Hide All Effects" }, |doc, _| {
+ fn rec(ls: &mut [Layer], on: bool) {
+ for l in ls {
+ if !l.effects.items.is_empty() {
+ l.effects.enabled = on;
+ }
+ if let Some(ch) = l.children_mut() {
+ rec(ch, on);
+ }
+ }
+ }
+ rec(&mut doc.layers, enabled);
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+/// Remove every layer matching `pred` (whole subtrees), keeping at least one layer.
+fn delete_where(s: &mut Session, label: &str, pred: fn(&Layer) -> bool) -> Result<Value> {
+ let n = s.edit(label, |doc, active| {
+ fn rec(ls: &mut Vec<Layer>, pred: fn(&Layer) -> bool) -> usize {
+ let before = ls.len();
+ ls.retain(|l| !pred(l));
+ let mut n = before - ls.len();
+ for l in ls.iter_mut() {
+ if let Some(ch) = l.children_mut() {
+ n += rec(ch, pred);
+ }
+ }
+ n
+ }
+ let backup = doc.layers.clone();
+ let n = rec(&mut doc.layers, pred);
+ if doc.layers.is_empty() {
+ doc.layers = backup;
+ return Err(EngineError::Other("a document must keep at least one layer".into()));
+ }
+ if active.is_none_or(|id| doc.layer(id).is_none()) {
+ *active = doc.top_layer();
+ }
+ Ok(n)
+ })?;
+ Ok(json!({"deleted": n}))
+}
+
+fn is_empty_layer(l: &Layer) -> bool {
+ match &l.content {
+ LayerContent::Raster(s) => s.content_bounds().is_empty() && l.mask.is_none() && l.effects.items.is_empty(),
+ LayerContent::Group(g) => g.children.iter().all(is_empty_layer),
+ _ => false,
+ }
+}
+
+fn ungroup(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ s.edit("Ungroup Layers", |doc, active| {
+ let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?;
+ let g = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let LayerContent::Group(group) = &g.content else {
+ return Err(EngineError::Other("the active layer is not a group".into()));
+ };
+ let children = group.children.clone();
+ let (&idx, parent) = path.split_last().unwrap();
+ let sib = if parent.is_empty() { &mut doc.layers } else { doc.layer_at_mut(parent).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(id))? };
+ sib.remove(idx);
+ let top = children.last().map(|l| l.id);
+ for (k, l) in children.into_iter().enumerate() {
+ sib.insert(idx + k, l);
+ }
+ *active = top.or_else(|| doc.top_layer());
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn set_visible(s: &mut Session, p: &Value, visible: bool) -> Result<Value> {
+ if crate::layer_multi_cmds::multi(s, p) {
+ return crate::layer_multi_cmds::set_visible_selected(s, visible);
+ }
+ let id = layer_param(s, p)?;
+ s.edit(if visible { "Show Layer" } else { "Hide Layer" }, |doc, _| {
+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.visible = visible;
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+/// Pixels of a fill or smart-object layer's content alone (no mask, effects or opacity).
+fn content_pixels(doc: &Document, l: &Layer) -> photocraft_raster::Surface {
+ let mut tmp = l.clone();
+ tmp.mask = None;
+ tmp.vector_mask = None;
+ tmp.effects.items.clear();
+ tmp.opacity = 1.0;
+ tmp.fill_opacity = 1.0;
+ tmp.blend = photocraft_color::BlendMode::Normal;
+ tmp.clipped = false;
+ tmp.visible = true;
+ let canvas = doc.bounds();
+ let buf = photocraft_compose::render_layer(&tmp, canvas);
+ let fmt = doc.pixel_format();
+ let n = fmt.channels();
+ let mut data = vec![0.0f32; buf.px.len() * n];
+ for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) {
+ from_rgba_into(&fmt, *p, out);
+ }
+ let mut s = photocraft_raster::Surface::new(fmt);
+ s.write_region(canvas, &data);
+ s.prune();
+ s
+}
+
+fn kind_of(s: &Session, id: LayerId) -> Option<&'static str> {
+ let d = s.active()?;
+ Some(match &d.doc.layer(id)?.content {
+ LayerContent::Text(_) => "type",
+ LayerContent::Shape(_) => "shape",
+ LayerContent::Fill(_) => "fill",
+ LayerContent::Smart(_) => "smart",
+ _ => return None,
+ })
+}
+
+/// Rasterize one layer; `only` restricts it to one kind. Returns false when there was nothing to do.
+fn rasterize_one(s: &mut Session, id: LayerId, only: Option<&str>, key: &str) -> Result<bool> {
+ let Some(kind) = kind_of(s, id).filter(|k| only.is_none_or(|o| o == *k)) else { return Ok(false) };
+ match kind {
+ "type" => {
+ s.execute("type.rasterize", json!({"layer": id.0, "coalesce": key}))?;
+ }
+ "shape" => {
+ s.execute("layer.rasterize.shape", json!({"layer": id.0, "coalesce": key}))?;
+ }
+ _ => {
+ let label = if kind == "fill" { "Rasterize Fill Content" } else { "Rasterize Smart Object" };
+ s.coalesce_request = Some(key.to_string());
+ let r = s.edit(label, |doc, _| {
+ let snap = doc.layer(id).cloned().ok_or(EngineError::NoLayer(id))?;
+ let px = content_pixels(doc, &snap);
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ l.content = LayerContent::Raster(px);
+ l.fill_cache = None;
+ Ok(())
+ });
+ s.coalesce_request = None;
+ r?;
+ }
+ }
+ Ok(true)
+}
+
+fn rasterize(s: &mut Session, p: &Value, only: Option<&'static str>) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ let key = step_key(s, "rasterize");
+ if !rasterize_one(s, id, only, &key)? {
+ return Err(EngineError::Other(match only {
+ Some(k) => format!("the layer is not a {k} layer"),
+ None => "the layer has nothing to rasterize".into(),
+ }));
+ }
+ Ok(json!({"layer": id.0}))
+}
+
+fn rasterize_all(s: &mut Session) -> Result<Value> {
+ let ids: Vec<LayerId> = s.active().map(|d| d.doc.walk().into_iter().map(|(_, _, l)| l.id).collect()).unwrap_or_default();
+ let key = step_key(s, "rasterizeAll");
+ let mut n = 0;
+ for id in ids {
+ // Every sub-step shares one history entry via the coalescing key.
+ if rasterize_one(s, id, None, &key)? {
+ n += 1;
+ }
+ }
+ Ok(json!({"rasterized": n}))
+}
+
+// ---------- registry ----------
+
+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.stroke", "Stroke…", &["Edit"], None, r##"{"width":1..250=1,"color":"#rrggbb|[r,g,b,a]"=foreground,"location":"inside|center|outside"="center","opacity":0..100=100}"##, has_pixels, stroke),
+ spec!("edit.transform.rotate180", "Rotate 180°", &["Edit", "Transform"], None, "{}", has_layer, |s, _| transform_preset(s, "rotate180")),
+ spec!("edit.transform.rotate90Cw", "Rotate 90° Clockwise", &["Edit", "Transform"], None, "{}", has_layer, |s, _| transform_preset(s, "rotate90Cw")),
+ spec!("edit.transform.rotate90Ccw", "Rotate 90° Counter Clockwise", &["Edit", "Transform"], None, "{}", has_layer, |s, _| transform_preset(s, "rotate90Ccw")),
+ spec!("edit.transform.flipHorizontal", "Flip Horizontal", &["Edit", "Transform"], None, "{}", has_layer, |s, _| transform_preset(s, "flipHorizontal")),
+ spec!("edit.transform.flipVertical", "Flip Vertical", &["Edit", "Transform"], None, "{}", has_layer, |s, _| transform_preset(s, "flipVertical")),
+ spec!("edit.pasteSpecial.pasteInto", "Paste Into", &["Edit", "Paste Special"], Some("Cmd+Alt+Shift+V"), r##"{"center":[x,y]?}"##, has_clip_and_selection, |s, p| paste_into(s, p, false)),
+ spec!("edit.pasteSpecial.pasteOutside", "Paste Outside", &["Edit", "Paste Special"], None, r##"{"center":[x,y]?}"##, has_clip_and_selection, |s, p| paste_into(s, p, true)),
+ spec!("select.reselect", "Reselect", &["Select"], Some("Cmd+Shift+D"), "{}", can_reselect, |s, _| {
+ let m = reselect_target(s).ok_or(EngineError::Other("there is no selection to restore".into()))?;
+ s.edit("Reselect", |doc, _| {
+ doc.selection = Some(m);
+ Ok(())
+ })?;
+ Ok(json!({"selected": true}))
+ }),
+ spec!("image.adjustments.equalize", "Equalize", &["Image", "Adjustments"], None, "{}", has_pixels, |s, _| equalize(s)),
+ spec!("image.revealAll", "Reveal All", &["Image"], None, "{}", has_doc, |s, _| {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let canvas = d.doc.bounds();
+ let all = d.doc.walk().into_iter().filter_map(|(_, _, l)| l.surface().map(|s| s.content_bounds())).fold(canvas, |a, b| a.union(&b));
+ if all == canvas {
+ return Ok(json!({"changed": false}));
+ }
+ s.execute("image.crop", json!({"x": all.x0, "y": all.y0, "width": all.width(), "height": all.height(), "deleteCroppedPixels": false}))?;
+ Ok(json!({"changed": true}))
+ }),
+ spec!("layer.new.layerFromBackground", "Layer From Background…", &["Layer", "New"], None, "{}", has_background, |s, _| layer_from_background(s)),
+ spec!("layer.layerStyle.copyLayerStyle", "Copy Layer Style", &["Layer", "Layer Style"], None, r##"{"layer":id?}"##, has_layer, |s, p| {
+ let id = layer_param(s, p)?;
+ let l = s.active().and_then(|d| d.doc.layer(id)).ok_or(EngineError::NoLayer(id))?;
+ let style = (l.effects.clone(), l.blend, l.fill_opacity);
+ s.style_clipboard = Some(style);
+ Ok(Value::Null)
+ }),
+ spec!("layer.layerStyle.pasteLayerStyle", "Paste Layer Style", &["Layer", "Layer Style"], None, r##"{"layer":id?}"##, |s| {
+ has_layer(s)?;
+ s.style_clipboard.as_ref().map(|_| ()).ok_or_else(|| "no layer style has been copied".into())
+ }, |s, p| {
+ let id = layer_param(s, p)?;
+ let (fx, blend, fill) = s.style_clipboard.clone().ok_or(EngineError::Other("no layer style has been copied".into()))?;
+ s.edit("Paste Layer Style", |doc, _| {
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ l.effects = fx;
+ l.blend = blend;
+ l.fill_opacity = fill;
+ Ok(())
+ })?;
+ Ok(Value::Null)
+ }),
+ spec!("layer.layerStyle.hideAllEffects", "Hide All Effects", &["Layer", "Layer Style"], None, "{}", has_doc, |s, _| set_all_effects(s, false)),
+ spec!("layer.layerStyle.showAllEffects", "Show All Effects", &[], None, "{}", has_doc, |s, _| set_all_effects(s, true)),
+ spec!("layer.layerMask.enabled", "Disable Layer Mask", &["Layer", "Layer Mask"], None, r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, has_mask, |s, p| toggle_mask(s, p, "enabled")),
+ spec!("layer.layerMask.linked", "Unlink Layer Mask", &["Layer", "Layer Mask"], None, r##"{"layer":id?,"linked":bool? (default: toggle)}"##, has_mask, |s, p| toggle_mask(s, p, "linked")),
+ spec!("layer.rasterize.layer", "Layer", &["Layer", "Rasterize"], None, r##"{"layer":id?}"##, has_layer, |s, p| rasterize(s, p, None)),
+ spec!("layer.rasterize.allLayers", "All Layers", &["Layer", "Rasterize"], None, "{}", has_doc, |s, _| rasterize_all(s)),
+ spec!("layer.rasterize.type", "Type", &["Layer", "Rasterize"], None, r##"{"layer":id?}"##, has_layer, |s, p| rasterize(s, p, Some("type"))),
+ spec!("layer.rasterize.fillContent", "Fill Content", &["Layer", "Rasterize"], None, r##"{"layer":id?}"##, has_layer, |s, p| rasterize(s, p, Some("fill"))),
+ spec!("layer.rasterize.smartObject", "Smart Object", &["Layer", "Rasterize"], None, r##"{"layer":id?}"##, has_layer, |s, p| rasterize(s, p, Some("smart"))),
+ spec!("layer.delete.hiddenLayers", "Hidden Layers", &["Layer", "Delete"], None, "{}", has_doc, |s, _| delete_where(s, "Delete Hidden Layers", |l| !l.visible)),
+ spec!("file.scripts.deleteAllEmptyLayers", "Delete All Empty Layers", &["File", "Scripts"], None, "{}", has_doc, |s, _| delete_where(s, "Delete All Empty Layers", is_empty_layer)),
+ spec!("layer.ungroupLayers", "Ungroup Layers", &["Layer"], Some("Cmd+Shift+G"), r##"{"layer":id?}"##, |s| match active_layer(s)?.is_group() {
+ true => Ok(()),
+ false => Err("the active layer is not a group".into()),
+ }, ungroup),
+ spec!("layer.hideLayers", "Hide Layers", &["Layer"], Some("Cmd+,"), r##"{"layer":id?}"##, has_layer, |s, p| set_visible(s, p, false)),
+ spec!("layer.showLayers", "Show Layers", &[], None, r##"{"layer":id?}"##, has_layer, |s, p| set_visible(s, p, true)),
+ spec!("filter.blur.average", "Average", &["Filter", "Blur"], None, "{}", has_pixels, |s, _| average(s)),
+ spec!("filter.render.clouds", "Clouds", &["Filter", "Render"], None, r##"{"seed":u32=0}"##, has_pixels, |s, p| clouds(s, p, false)),
+ spec!("filter.render.differenceClouds", "Difference Clouds", &["Filter", "Render"], None, r##"{"seed":u32=0}"##, has_pixels, |s, p| clouds(s, p, true)),
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s
+ }
+
+ fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+ }
+
+ fn active(s: &Session) -> &Layer {
+ let d = s.active().unwrap();
+ d.doc.layer(d.active_layer.unwrap()).unwrap()
+ }
+
+ fn pixel(s: &Session, x: i32, y: i32) -> Vec<f32> {
+ active(s).surface().unwrap().pixel(x, y)
+ }
+
+ fn paint_square(s: &mut Session, r: Rect, c: [f32; 4]) {
+ s.edit("paint", |doc, a| {
+ doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(r, &c);
+ Ok(())
+ })
+ .unwrap();
+ }
+
+ #[test]
+ fn stroke_locations_at_several_depths() {
+ for depth in [8, 16, 32] {
+ for (loc, inside, outside) in [("inside", 1.0, 0.0), ("outside", 0.0, 1.0), ("center", 1.0, 1.0)] {
+ let mut s = session(depth);
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();
+ s.execute("edit.stroke", json!({"width": 2, "color": "#ff0000", "location": loc})).unwrap();
+ assert!((pixel(&s, 10, 15)[3] - inside).abs() < 0.02, "{depth} {loc} inside {:?}", pixel(&s, 10, 15));
+ assert!((pixel(&s, 9, 15)[3] - outside).abs() < 0.02, "{depth} {loc} outside {:?}", pixel(&s, 9, 15));
+ assert_eq!(pixel(&s, 15, 15)[3], 0.0, "centre untouched");
+ }
+ }
+ // Without a selection the layer's opaque edge is stroked.
+ let mut s = session(8);
+ paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.0, 0.0, 1.0, 1.0]);
+ s.execute("edit.stroke", json!({"width": 3, "color": "#00ff00", "location": "outside"})).unwrap();
+ assert_eq!(pixel(&s, 8, 15), vec![0.0, 1.0, 0.0, 1.0]);
+ assert_eq!(pixel(&s, 15, 15), vec![0.0, 0.0, 1.0, 1.0]);
+ }
+
+ #[test]
+ fn transform_presets_are_exact() {
+ let mut s = session(8);
+ paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]);
+ paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]);
+ s.execute("edit.transform.flipHorizontal", json!({})).unwrap();
+ assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14));
+ assert_eq!(pixel(&s, 19, 10), vec![0.0, 1.0, 0.0, 1.0]);
+ s.execute("edit.transform.flipVertical", json!({})).unwrap();
+ assert_eq!(pixel(&s, 19, 13), vec![0.0, 1.0, 0.0, 1.0]);
+ s.execute("edit.transform.rotate180", json!({})).unwrap();
+ assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]);
+ s.execute("edit.transform.rotate90Cw", json!({})).unwrap();
+ let b = active(&s).surface().unwrap().content_bounds();
+ assert_eq!((b.width(), b.height()), (4, 10));
+ // Top-left corner goes to the top-right after a clockwise turn.
+ assert_eq!(pixel(&s, b.x1 - 1, b.y0), vec![0.0, 1.0, 0.0, 1.0]);
+ s.execute("edit.transform.rotate90Ccw", json!({})).unwrap();
+ assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14));
+ assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]);
+ }
+
+ #[test]
+ fn reselect_restores_the_last_selection() {
+ let mut s = session(8);
+ assert!(!s.is_enabled("select.reselect"));
+ s.execute("select.rect", json!({"x": 2, "y": 3, "width": 5, "height": 6})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ assert!(doc(&s).selection.is_none());
+ s.execute("select.reselect", json!({})).unwrap();
+ assert_eq!(doc(&s).selection.as_ref().unwrap().content_bounds(), Rect::new(2, 3, 7, 9));
+ assert!(!s.is_enabled("select.reselect"), "nothing to reselect while a selection exists");
+ }
+
+ #[test]
+ fn equalize_spreads_values() {
+ for depth in [8, 16] {
+ let mut s = session(depth);
+ paint_square(&mut s, Rect::new(0, 0, 40, 15), [0.4, 0.4, 0.4, 1.0]);
+ paint_square(&mut s, Rect::new(0, 15, 40, 30), [0.5, 0.5, 0.5, 1.0]);
+ s.execute("image.adjustments.equalize", json!({})).unwrap();
+ let (dark, light) = (pixel(&s, 1, 1)[0], pixel(&s, 1, 20)[0]);
+ assert!(dark < 0.05 && light > 0.95, "{depth}: {dark} {light}");
+ }
+ }
+
+ #[test]
+ fn average_and_clouds() {
+ let mut s = session(8);
+ paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]);
+ paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 1.0]);
+ s.execute("filter.blur.average", json!({})).unwrap();
+ let p = pixel(&s, 5, 5);
+ assert!((p[0] - 0.5).abs() < 0.01 && (p[2] - 0.5).abs() < 0.01, "{p:?}");
+ s.execute("filter.render.clouds", json!({"seed": 3})).unwrap();
+ let vals: Vec<f32> = (0..40).map(|x| pixel(&s, x, 12)[0]).collect();
+ let (lo, hi) = vals.iter().fold((1.0f32, 0.0f32), |(a, b), v| (a.min(*v), b.max(*v)));
+ assert!(hi - lo > 0.05, "clouds vary: {lo}..{hi}");
+ assert!(vals.windows(2).all(|w| (w[0] - w[1]).abs() < 0.2), "clouds are smooth");
+ // Difference Clouds over itself with the same seed cancels to black.
+ s.execute("filter.render.differenceClouds", json!({"seed": 3})).unwrap();
+ assert!(pixel(&s, 7, 7)[..3].iter().all(|v| *v < 0.01), "{:?}", pixel(&s, 7, 7));
+ }
+
+ #[test]
+ fn paste_into_masks_to_the_selection() {
+ let mut s = session(8);
+ paint_square(&mut s, Rect::new(0, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]);
+ s.execute("select.all", json!({})).unwrap();
+ s.execute("edit.copy", json!({})).unwrap();
+ let steps = s.active().unwrap().history.past_len();
+ s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap();
+ s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap();
+ let l = active(&s);
+ let m = l.mask.as_ref().unwrap();
+ assert!(!m.linked);
+ assert_eq!(m.surface.content_bounds(), Rect::new(20, 10, 28, 18));
+ assert_eq!(m.value(0, 0), 0.0);
+ assert!(doc(&s).selection.is_none());
+ assert_eq!(s.active().unwrap().history.past_len(), steps + 2, "select + one Paste Into step");
+ // Paste Outside reveals everything but the selection.
+ s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap();
+ s.execute("edit.pasteSpecial.pasteOutside", json!({})).unwrap();
+ let m = active(&s).mask.as_ref().unwrap();
+ assert_eq!((m.value(0, 0), m.value(22, 12)), (1.0, 0.0));
+ }
+
+ #[test]
+ fn layer_utilities() {
+ let mut s = session(8);
+ // Layer from Background.
+ assert!(s.is_enabled("layer.new.layerFromBackground"));
+ s.execute("layer.new.layerFromBackground", json!({})).unwrap();
+ assert_eq!(doc(&s).layers[0].name, "Layer 0");
+ assert!(!doc(&s).layers[0].locks.transparency);
+ assert!(!s.is_enabled("layer.new.layerFromBackground"));
+ // Copy / paste style and hide all effects.
+ s.execute("layer.layerStyle.dropShadow", json!({})).unwrap();
+ s.execute("layer.layerStyle.copyLayerStyle", json!({})).unwrap();
+ let top = doc(&s).layers[1].id;
+ s.execute("layer.layerStyle.pasteLayerStyle", json!({"layer": top.0})).unwrap();
+ assert_eq!(doc(&s).layers[1].effects.items.len(), 1);
+ s.execute("layer.layerStyle.hideAllEffects", json!({})).unwrap();
+ assert!(doc(&s).walk().iter().all(|(_, _, l)| l.effects.items.is_empty() || !l.effects.enabled));
+ // Mask toggles.
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ s.execute("layer.layerMask.enabled", json!({})).unwrap();
+ assert!(!active(&s).mask.as_ref().unwrap().enabled);
+ s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap();
+ assert!(!active(&s).mask.as_ref().unwrap().linked);
+ // Hide, delete hidden, delete empty.
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("layer.hideLayers", json!({})).unwrap();
+ assert!(!active(&s).visible);
+ assert_eq!(s.execute("layer.delete.hiddenLayers", json!({})).unwrap()["deleted"], 1);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let n = doc(&s).layer_count();
+ assert_eq!(s.execute("file.scripts.deleteAllEmptyLayers", json!({})).unwrap()["deleted"], 1);
+ assert_eq!(doc(&s).layer_count(), n - 1);
+ }
+
+ #[test]
+ fn ungroup_restores_children_in_order() {
+ let mut s = session(8);
+ let a = active(&s).id;
+ s.execute("layer.groupLayers", json!({})).unwrap();
+ assert!(active(&s).is_group());
+ s.execute("layer.ungroupLayers", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().active_layer, Some(a));
+ assert!(doc(&s).layers.iter().all(|l| !l.is_group()));
+ assert_eq!(doc(&s).layers.len(), 2);
+ }
+
+ #[test]
+ fn reveal_all_grows_the_canvas() {
+ let mut s = session(8);
+ s.execute("layer.translate", json!({"dx": 0, "dy": 0})).ok();
+ paint_square(&mut s, Rect::new(-5, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]);
+ s.execute("image.revealAll", json!({})).unwrap();
+ assert_eq!((doc(&s).size.width, doc(&s).size.height), (45, 30));
+ assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false);
+ }
+
+ #[test]
+ fn rasterize_fill_and_all_in_one_step() {
+ let mut s = session(8);
+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap();
+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap();
+ s.execute("layer.rasterize.fillContent", json!({})).unwrap();
+ assert!(matches!(active(&s).content, LayerContent::Raster(_)));
+ assert_eq!(pixel(&s, 3, 3), vec![0.0, 0.0, 1.0, 1.0]);
+ assert!(s.execute("layer.rasterize.type", json!({})).is_err());
+ let steps = s.active().unwrap().history.past_len();
+ assert_eq!(s.execute("layer.rasterize.allLayers", json!({})).unwrap()["rasterized"], 1);
+ assert_eq!(s.active().unwrap().history.past_len(), steps + 1);
+ assert!(doc(&s).walk().iter().all(|(_, _, l)| !matches!(l.content, LayerContent::Fill(_))));
+ }
+}
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
new file mode 100644
index 000000000..21d679519
--- /dev/null
+++ b/crates/engine/src/file_cmds.rs
@@ -0,0 +1,990 @@
+//! File-menu commands beyond New/Close: Close All / Others, Revert, Save a Copy, Open As, Place
+//! Embedded / Linked, File Info, the Automate and Scripts items (Fit Image, Conditional Mode
+//! Change, Batch, Image Processor, Load Files into Stack, Flatten All Layer Effects / Masks),
+//! Export › Layers to Files and Color Lookup Tables, plus the document-level guide layouts of the
+//! View menu (New Guide Layout, New Guides From Shape, Clear Canvas Guides).
+//!
+//! Commands that touch the file system take explicit paths (the UI asks for them with its own
+//! pickers) and are unavailable on the web, where there is no file system; their byte-level
+//! cores ([`place_bytes`], [`open_bytes_as`]) work everywhere.
+
+use std::sync::Arc;
+
+use photocraft_algo::resample::{Resample, resize_surface, translate_surface};
+use photocraft_color::{ColorMode, PixelFormat};
+use photocraft_doc::{Affine, Document, Layer, LayerContent, LayerId, SmartObject, SmartSource};
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, from_rgba_into};
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, layer_param};
+use crate::{EngineError, Result, Session};
+
+// ---------- predicates ----------
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+/// The file system is reachable (not on the web).
+fn native(_: &Session) -> std::result::Result<(), String> {
+ if cfg!(target_arch = "wasm32") { Err("not available on the web (no file system)".into()) } else { Ok(()) }
+}
+
+fn native_doc(s: &Session) -> std::result::Result<(), String> {
+ native(s)?;
+ has_doc(s)
+}
+
+fn can_revert(s: &Session) -> std::result::Result<(), String> {
+ native(s)?;
+ let d = s.active().ok_or("no document open")?;
+ let path = d.path.as_deref().ok_or("the document has never been saved")?;
+ if !is_file(path) {
+ return Err(format!("{path} is not a file on disk"));
+ }
+ Ok(())
+}
+
+fn has_adjustments(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if d.doc.layers.iter().any(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))) {
+ Ok(())
+ } else {
+ Err("the document has no visible adjustment layers to export".into())
+ }
+}
+
+fn has_shape(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) {
+ Some(LayerContent::Shape(_)) => Ok(()),
+ _ => Err("the active layer is not a shape layer".into()),
+ }
+}
+
+// ---------- file system (native only) ----------
+
+#[cfg(not(target_arch = "wasm32"))]
+fn is_file(path: &str) -> bool {
+ std::path::Path::new(path).is_file()
+}
+#[cfg(target_arch = "wasm32")]
+fn is_file(_path: &str) -> bool {
+ false
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn read_file(path: &str) -> Result<Vec<u8>> {
+ std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
+}
+#[cfg(target_arch = "wasm32")]
+fn read_file(path: &str) -> Result<Vec<u8>> {
+ Err(EngineError::Other(format!("cannot read {path}: no file system on the web")))
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
+ if let Some(dir) = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()) {
+ std::fs::create_dir_all(dir).map_err(|e| EngineError::Other(format!("{}: {e}", dir.display())))?;
+ }
+ std::fs::write(path, bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))
+}
+#[cfg(target_arch = "wasm32")]
+fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
+ Err(EngineError::Other(format!("cannot write {path}: no file system on the web")))
+}
+
+/// Files of a folder that look like images we can open, sorted by name.
+#[cfg(not(target_arch = "wasm32"))]
+fn list_images(dir: &str) -> Result<Vec<String>> {
+ let rd = std::fs::read_dir(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?;
+ let mut out: Vec<String> = rd
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter(|p| p.is_file() && p.extension().and_then(|x| x.to_str()).is_some_and(|x| OPENABLE.contains(&x.to_ascii_lowercase().as_str())))
+ .map(|p| p.to_string_lossy().into_owned())
+ .collect();
+ out.sort();
+ Ok(out)
+}
+#[cfg(target_arch = "wasm32")]
+fn list_images(dir: &str) -> Result<Vec<String>> {
+ Err(EngineError::Other(format!("cannot list {dir}: no file system on the web")))
+}
+
+/// Extensions the batch commands pick up from a folder.
+const OPENABLE: &[&str] = &["psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", "pnm", "ppm", "pgm"];
+
+fn file_name(path: &str) -> String {
+ path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
+}
+
+fn stem(path: &str) -> String {
+ let n = file_name(path);
+ match n.rfind('.') {
+ Some(i) if i > 0 => n[..i].to_string(),
+ _ => n,
+ }
+}
+
+fn join(dir: &str, name: &str) -> String {
+ if dir.is_empty() {
+ name.to_string()
+ } else if dir.ends_with('/') || dir.ends_with('\\') {
+ format!("{dir}{name}")
+ } else {
+ format!("{dir}/{name}")
+ }
+}
+
+/// A file-name-safe version of a layer name.
+fn sanitize(name: &str) -> String {
+ let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ' | '.') { c } else { '_' }).collect();
+ let s = s.trim().trim_matches('.').to_string();
+ if s.is_empty() { "layer".into() } else { s }
+}
+
+fn import(name: &str, bytes: &[u8]) -> Result<Document> {
+ photocraft_io::import(name, bytes).map(|r| r.document).map_err(|e| EngineError::Other(format!("{name}: {e}")))
+}
+
+/// Encodes `doc` for `path`'s extension. `quality` is Photoshop's 0–12 JPEG scale.
+fn encode(doc: &Document, path: &str, quality: Option<f64>) -> Result<(Vec<u8>, Vec<String>)> {
+ let mut opts = photocraft_io::ExportOptions::default();
+ if let Some(q) = quality {
+ opts.encode.jpeg_quality = (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8;
+ }
+ photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
+}
+
+fn save_doc(doc: &Document, path: &str, quality: Option<f64>) -> Result<Vec<String>> {
+ let (bytes, warnings) = encode(doc, path, quality)?;
+ write_file(path, &bytes)?;
+ Ok(warnings)
+}
+
+fn str_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> {
+ p.get(key).and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing \"{key}\"") })
+}
+
+fn f64_param(p: &Value, key: &str) -> Option<f64> {
+ p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite())
+}
+
+/// A size parameter; zero or negative means "not set" (dialogs send 0 for empty fields).
+fn size_param(p: &Value, key: &str) -> Option<f64> {
+ f64_param(p, key).filter(|v| *v > 0.0)
+}
+
+// ---------- pixels ----------
+
+/// A composite buffer as a surface in `fmt` (straight RGBA → the format's model and depth).
+fn buffer_surface(buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Surface {
+ let n = fmt.channels();
+ let mut data = vec![0.0f32; buf.px.len() * n];
+ for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) {
+ from_rgba_into(&fmt, *p, out);
+ }
+ let mut s = Surface::new(fmt);
+ if !buf.rect.is_empty() {
+ s.write_region(buf.rect, &data);
+ }
+ s.prune();
+ s
+}
+
+/// The flattened image of `doc` as a surface in `fmt`, placed at the origin.
+fn flattened(doc: &Document, fmt: PixelFormat) -> Surface {
+ buffer_surface(&photocraft_compose::flatten(doc), fmt)
+}
+
+// ---------- close / revert / save a copy / open as ----------
+
+fn close_all(s: &mut Session) -> Result<Value> {
+ let n = s.documents().len();
+ while !s.documents().is_empty() {
+ s.close(s.documents().len() - 1);
+ }
+ Ok(json!({"closed": n}))
+}
+
+fn close_others(s: &mut Session, p: &Value) -> Result<Value> {
+ let keep = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?;
+ if keep >= s.documents().len() {
+ return Err(EngineError::BadParams { cmd: "file.closeOthers".into(), msg: format!("no document {keep}") });
+ }
+ let n = s.documents().len() - 1;
+ for i in (0..s.documents().len()).rev() {
+ if i != keep {
+ s.close(i);
+ }
+ }
+ s.set_active(0);
+ Ok(json!({"closed": n}))
+}
+
+/// File › Revert: reload the saved file as one history step (undoable, like Photoshop's
+/// "Revert" history state); the document is clean afterwards.
+fn revert(s: &mut Session) -> Result<Value> {
+ let path = s.active().and_then(|d| d.path.clone()).ok_or(EngineError::Other("the document has never been saved".into()))?;
+ let bytes = read_file(&path)?;
+ let fresh = import(&file_name(&path), &bytes)?;
+ s.edit("Revert", |doc, active| {
+ let (id, name) = (doc.id, doc.name.clone());
+ *doc = fresh;
+ // Keep the identity (colour state, views and caches are keyed by it) and the tab name.
+ doc.id = id;
+ doc.name = name;
+ *active = doc.top_layer();
+ Ok(())
+ })?;
+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;
+ st.saved_revision = st.revision;
+ Ok(json!({"path": path, "layers": st.doc.layers.len()}))
+}
+
+fn save_a_copy(s: &mut Session, p: &Value) -> Result<Value> {
+ let path = str_param(p, "path", "file.saveACopy")?.to_string();
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let mut doc = (*d.doc).clone();
+ if p.get("layers").and_then(Value::as_bool) == Some(false) {
+ // "Layers" unchecked in Save a Copy: write the flattened image.
+ let fmt = doc.pixel_format();
+ let px = flattened(&doc, fmt);
+ doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))];
+ }
+ let warnings = save_doc(&doc, &path, f64_param(p, "quality"))?;
+ Ok(json!({"path": path, "warnings": warnings}))
+}
+
+/// Open a file's bytes, decoding them as the format `as_ext` (Open As) when given.
+pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&str>, path: Option<String>) -> Result<Value> {
+ let decode_name = match as_ext {
+ Some(ext) => format!("{}.{}", stem(name), ext.trim_start_matches('.')),
+ None => name.to_string(),
+ };
+ let mut doc = import(&decode_name, bytes)?;
+ doc.name = file_name(name);
+ // Color Settings policies (preserve / convert / discard the embedded profile).
+ let (i, color) = s.open_document(doc, path);
+ Ok(json!({"document": i, "color": color}))
+}
+
+fn open_as(s: &mut Session, p: &Value) -> Result<Value> {
+ let path = str_param(p, "path", "file.openAs")?.to_string();
+ let bytes = read_file(&path)?;
+ let as_ext = p.get("as").or_else(|| p.get("format")).and_then(Value::as_str);
+ open_bytes_as(s, &path, &bytes, as_ext, Some(path.clone()))
+}
+
+// ---------- place ----------
+
+/// Place a file's bytes as a smart object layer, centred and (when larger than the canvas)
+/// scaled down to fit, like Photoshop's Place with "Resize Image During Place". `linked` makes it
+/// a linked smart object that refers to that path instead of embedding the bytes.
+pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec<u8>, linked: Option<String>, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let (cw, ch) = (d.doc.size.width as f64, d.doc.size.height as f64);
+ let fmt = d.doc.pixel_format();
+ let src = import(name, &bytes)?;
+ let (w, h) = (src.size.width as f64, src.size.height as f64);
+ let scale = match f64_param(p, "scale") {
+ Some(k) => (k / 100.0).max(1e-4),
+ None if p.get("fit").and_then(Value::as_bool) != Some(false) && (w > cw || h > ch) => (cw / w).min(ch / h),
+ None => 1.0,
+ };
+ let center = match p.get("center").and_then(Value::as_array) {
+ Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)),
+ _ => (cw / 2.0, ch / 2.0),
+ };
+ let (dx, dy) = ((center.0 - w * scale / 2.0).round(), (center.1 - h * scale / 2.0).round());
+ let mut px = flattened(&src, fmt);
+ if (scale - 1.0).abs() > 1e-9 {
+ px = resize_surface(&px, scale, scale, Resample::Bicubic);
+ }
+ let px = translate_surface(&px, dx as i32, dy as i32);
+ let source = match linked {
+ Some(path) => SmartSource::Linked { path },
+ None => SmartSource::Embedded { file_name: file_name(name), bytes: Arc::new(bytes) },
+ };
+ let so = SmartObject::new(source, Affine { m: [scale, 0.0, 0.0, scale, dx, dy] }, Some(px));
+ let layer_name = stem(name);
+ let label = if matches!(so.source, SmartSource::Linked { .. }) { "Place Linked" } else { "Place Embedded" };
+ let id = s.edit(label, |doc, active| {
+ let id = doc.insert_above(*active, Layer::new(layer_name, LayerContent::Smart(so)));
+ *active = Some(id);
+ Ok(id)
+ })?;
+ Ok(json!({"layer": id.0, "scale": scale * 100.0, "bounds": [dx, dy, dx + w * scale, dy + h * scale]}))
+}
+
+fn place(s: &mut Session, p: &Value, linked: bool) -> Result<Value> {
+ let cmd = if linked { "file.placeLinked" } else { "file.placeEmbedded" };
+ let path = str_param(p, "path", cmd)?.to_string();
+ let bytes = read_file(&path)?;
+ place_bytes(s, &path, bytes, linked.then(|| path.clone()), p)
+}
+
+// ---------- File Info (XMP) ----------
+
+/// The File Info fields we edit, as (JSON key, XMP property, container kind).
+const INFO_FIELDS: [(&str, &str, &str); 6] = [
+ ("title", "dc:title", "Alt"),
+ ("author", "dc:creator", "Seq"),
+ ("description", "dc:description", "Alt"),
+ ("keywords", "dc:subject", "Bag"),
+ ("copyright", "dc:rights", "Alt"),
+ ("authorTitle", "photoshop:AuthorsPosition", ""),
+];
+
+fn xml_escape(s: &str) -> String {
+ s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
+}
+
+fn xml_unescape(s: &str) -> String {
+ s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;", "'").replace("&amp;", "&")
+}
+
+/// The element `<tag …>…</tag>` (first occurrence) as (start, end, inner).
+fn find_element<'a>(xmp: &'a str, tag: &str) -> Option<(usize, usize, &'a str)> {
+ let open = format!("<{tag}");
+ let mut from = 0;
+ while let Some(i) = xmp[from..].find(&open).map(|i| i + from) {
+ let after = xmp[i + open.len()..].chars().next();
+ if matches!(after, Some('>' | ' ' | '/' | '\n' | '\r' | '\t')) {
+ let gt = xmp[i..].find('>')? + i;
+ if xmp[..gt].ends_with('/') {
+ return Some((i, gt + 1, ""));
+ }
+ let close = format!("</{tag}>");
+ let c = xmp[gt..].find(&close)? + gt;
+ return Some((i, c + close.len(), &xmp[gt + 1..c]));
+ }
+ from = i + open.len();
+ }
+ None
+}
+
+/// `rdf:li` values of a container (or the element text for simple properties).
+fn li_values(inner: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ let mut rest = inner;
+ while let Some((a, b, v)) = find_element(rest, "rdf:li") {
+ out.push(xml_unescape(v.trim()));
+ rest = &rest[b..];
+ let _ = a;
+ }
+ if out.is_empty() && !inner.contains('<') && !inner.trim().is_empty() {
+ out.push(xml_unescape(inner.trim()));
+ }
+ out
+}
+
+/// Attribute form `prop="value"` on an `rdf:Description`.
+fn find_attr<'a>(xmp: &'a str, prop: &str) -> Option<(usize, usize, &'a str)> {
+ let key = format!(" {prop}=\"");
+ let i = xmp.find(&key)?;
+ let v0 = i + key.len();
+ let v1 = xmp[v0..].find('"')? + v0;
+ Some((i, v1 + 1, &xmp[v0..v1]))
+}
+
+/// File Info fields read from an XMP packet.
+pub fn read_file_info(xmp: Option<&str>) -> Value {
+ let mut m = serde_json::Map::new();
+ let x = xmp.unwrap_or("");
+ for (key, prop, kind) in INFO_FIELDS {
+ let vals = match find_element(x, prop) {
+ Some((_, _, inner)) => li_values(inner),
+ None => find_attr(x, prop).map(|(_, _, v)| vec![xml_unescape(v)]).unwrap_or_default(),
+ };
+ let v = if kind == "Bag" { json!(vals) } else if kind == "Seq" { json!(vals.join("; ")) } else { json!(vals.into_iter().next().unwrap_or_default()) };
+ m.insert(key.into(), v);
+ }
+ let marked = find_element(x, "xmpRights:Marked").map(|(_, _, v)| v.trim().to_string()).or_else(|| find_attr(x, "xmpRights:Marked").map(|(_, _, v)| v.to_string()));
+ m.insert(
+ "copyrightStatus".into(),
+ json!(match marked.as_deref() {
+ Some("True") => "copyrighted",
+ Some("False") => "publicDomain",
+ _ => "unknown",
+ }),
+ );
+ let url = find_element(x, "xmpRights:WebStatement").map(|(_, _, v)| xml_unescape(v.trim())).or_else(|| find_attr(x, "xmpRights:WebStatement").map(|(_, _, v)| xml_unescape(v)));
+ m.insert("copyrightUrl".into(), json!(url.unwrap_or_default()));
+ Value::Object(m)
+}
+
+/// Rewrites the File Info fields of an XMP packet (creating one when there is none), keeping
+/// every other property. Edited properties move into their own `rdf:Description` (several
+/// descriptions per packet are valid XMP).
+pub fn write_file_info(xmp: Option<&str>, info: &Value) -> String {
+ let mut cur = read_file_info(xmp);
+ if let (Some(c), Some(n)) = (cur.as_object_mut(), info.as_object()) {
+ for (k, v) in n {
+ if c.contains_key(k) {
+ c.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ let mut x = xmp.filter(|s| s.contains("</rdf:RDF>")).map(str::to_string).unwrap_or_else(|| {
+ "<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>".to_string()
+ });
+ let props: Vec<&str> = INFO_FIELDS.iter().map(|f| f.1).chain(["xmpRights:Marked", "xmpRights:WebStatement"]).collect();
+ for prop in &props {
+ while let Some((a, b, _)) = find_element(&x, prop) {
+ x.replace_range(a..b, "");
+ }
+ while let Some((a, b, _)) = find_attr(&x, prop) {
+ x.replace_range(a..b, "");
+ }
+ }
+ let get = |k: &str| cur.get(k).cloned().unwrap_or(Value::Null);
+ let mut body = String::new();
+ for (key, prop, kind) in INFO_FIELDS {
+ let vals: Vec<String> = match get(key) {
+ Value::Array(a) => a.iter().filter_map(|v| v.as_str()).map(str::to_string).filter(|v| !v.is_empty()).collect(),
+ Value::String(s) if kind == "Bag" || kind == "Seq" => s.split([';', ',']).map(|v| v.trim().to_string()).filter(|v| !v.is_empty()).collect(),
+ Value::String(s) if !s.is_empty() => vec![s],
+ _ => Vec::new(),
+ };
+ if vals.is_empty() {
+ continue;
+ }
+ let items: String = vals
+ .iter()
+ .map(|v| if kind == "Alt" { format!("<rdf:li xml:lang=\"x-default\">{}</rdf:li>", xml_escape(v)) } else { format!("<rdf:li>{}</rdf:li>", xml_escape(v)) })
+ .collect();
+ if kind.is_empty() {
+ body.push_str(&format!(" <{prop}>{}</{prop}>\n", xml_escape(&vals[0])));
+ } else {
+ body.push_str(&format!(" <{prop}><rdf:{kind}>{items}</rdf:{kind}></{prop}>\n"));
+ }
+ }
+ match get("copyrightStatus").as_str() {
+ Some("copyrighted") => body.push_str(" <xmpRights:Marked>True</xmpRights:Marked>\n"),
+ Some("publicDomain") => body.push_str(" <xmpRights:Marked>False</xmpRights:Marked>\n"),
+ _ => {}
+ }
+ if let Some(u) = get("copyrightUrl").as_str().filter(|u| !u.is_empty()) {
+ body.push_str(&format!(" <xmpRights:WebStatement>{}</xmpRights:WebStatement>\n", xml_escape(u)));
+ }
+ if !body.is_empty() {
+ let desc = format!(
+ " <rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:photoshop=\"http://ns.adobe.com/photoshop/1.0/\" xmlns:xmpRights=\"http://ns.adobe.com/xap/1.0/rights/\">\n{body} </rdf:Description>\n "
+ );
+ let at = x.rfind("</rdf:RDF>").unwrap_or(x.len());
+ x.insert_str(at, &desc);
+ }
+ x
+}
+
+fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
+ let keys = ["title", "author", "authorTitle", "description", "keywords", "copyright", "copyrightStatus", "copyrightUrl"];
+ let edits = p.as_object().is_some_and(|m| m.keys().any(|k| keys.contains(&k.as_str())));
+ if edits {
+ let xmp = s.active().ok_or(EngineError::NoDocument)?.doc.metadata.xmp.clone();
+ let new = write_file_info(xmp.as_deref(), p);
+ s.edit("File Info", |doc, _| {
+ doc.metadata.xmp = Some(new);
+ Ok(())
+ })?;
+ }
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ Ok(read_file_info(d.doc.metadata.xmp.as_deref()))
+}
+
+// ---------- Automate ----------
+
+fn fit_image(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let (w, h) = (d.doc.size.width as f64, d.doc.size.height as f64);
+ let bw = f64_param(p, "width").unwrap_or(w).max(1.0);
+ let bh = f64_param(p, "height").unwrap_or(h).max(1.0);
+ let k = (bw / w).min(bh / h);
+ if (k > 1.0 && p.get("dontEnlarge").and_then(Value::as_bool).unwrap_or(false)) || ((w * k).round() == w && (h * k).round() == h) {
+ return Ok(json!({"width": w, "height": h, "changed": false}));
+ }
+ let (nw, nh) = ((w * k).round().max(1.0), (h * k).round().max(1.0));
+ let resample = p.get("resample").and_then(Value::as_str).unwrap_or("bicubic");
+ s.execute("image.imageSize", json!({"width": nw, "height": nh, "resample": resample}))?;
+ Ok(json!({"width": nw, "height": nh, "changed": true}))
+}
+
+fn mode_name(m: ColorMode) -> &'static str {
+ match m {
+ ColorMode::Bitmap => "bitmap",
+ ColorMode::Grayscale => "grayscale",
+ ColorMode::Duotone => "duotone",
+ ColorMode::Indexed => "indexed",
+ ColorMode::Rgb => "rgb",
+ ColorMode::Cmyk => "cmyk",
+ ColorMode::Lab => "lab",
+ ColorMode::Multichannel => "multichannel",
+ }
+}
+
+fn conditional_mode_change(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.automate.conditionalModeChange";
+ let to = str_param(p, "to", cmd)?.to_ascii_lowercase();
+ let to = match to.as_str() {
+ "gray" | "grayscale" => "grayscale",
+ "rgb" => "rgb",
+ "cmyk" => "cmyk",
+ "lab" => "lab",
+ other => return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unsupported target mode \"{other}\" (rgb, grayscale, cmyk, lab)") }),
+ };
+ let cur = mode_name(s.active().ok_or(EngineError::NoDocument)?.doc.mode);
+ let from: Vec<String> = match p.get("from") {
+ Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(|v| v.to_ascii_lowercase().replace("gray", "grayscale").replace("grayscalescale", "grayscale")).collect(),
+ Some(Value::String(v)) if v != "any" => vec![v.to_ascii_lowercase()],
+ _ => vec!["any".into()],
+ };
+ if cur == to || !(from.iter().any(|f| f == "any" || f == cur)) {
+ return Ok(json!({"changed": false, "mode": cur}));
+ }
+ s.execute(&format!("image.mode.{to}"), json!({}))?;
+ Ok(json!({"changed": true, "mode": to}))
+}
+
+/// One `[id, params]` / `{command, params}` / `{id, params}` step of an action.
+fn parse_steps(v: &Value) -> Result<Vec<(String, Value)>> {
+ let bad = |m: &str| EngineError::BadParams { cmd: "file.automate.batch".into(), msg: m.into() };
+ let arr = v.as_array().ok_or_else(|| bad("\"steps\" must be an array"))?;
+ arr.iter()
+ .map(|st| match st {
+ Value::Array(a) if !a.is_empty() => Ok((a[0].as_str().ok_or_else(|| bad("step id must be a string"))?.to_string(), a.get(1).cloned().unwrap_or(json!({})))),
+ Value::Object(o) => {
+ let id = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).ok_or_else(|| bad("step needs \"command\""))?;
+ Ok((id.to_string(), o.get("params").cloned().unwrap_or(json!({}))))
+ }
+ Value::String(id) => Ok((id.clone(), json!({}))),
+ _ => Err(bad("each step is [id, params] or {\"command\", \"params\"}")),
+ })
+ .collect()
+}
+
+/// Inputs of a batch command: `"input"` is a folder or an array of files.
+fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<String>> {
+ match p.get("input").or_else(|| p.get("files")) {
+ Some(Value::Array(a)) => Ok(a.iter().filter_map(Value::as_str).map(str::to_string).collect()),
+ Some(Value::String(dir)) => list_images(dir),
+ _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"input\" (folder or array of files)".into() }),
+ }
+}
+
+/// Opens each input in a scratch session, runs `f` on it and saves it to `output` as `format`
+/// (`"same"` keeps the input's extension). Errors per file are collected, not fatal.
+fn process_files(inputs: &[String], output: &str, format: &str, quality: Option<f64>, suffix: &str, f: &dyn Fn(&mut Session) -> Result<()>) -> Value {
+ let mut files = Vec::new();
+ let mut errors = Vec::new();
+ for path in inputs {
+ let r = (|| -> Result<String> {
+ let bytes = read_file(path)?;
+ let mut scratch = Session::new();
+ let doc = import(&file_name(path), &bytes)?;
+ scratch.add_document(doc, Some(path.clone()));
+ f(&mut scratch)?;
+ let ext = if format == "same" { path.rsplit('.').next().unwrap_or("png").to_ascii_lowercase() } else { format.trim_start_matches('.').to_ascii_lowercase() };
+ let out = join(output, &format!("{}{suffix}.{ext}", stem(path)));
+ let d = scratch.active().ok_or(EngineError::NoDocument)?;
+ save_doc(&d.doc, &out, quality)?;
+ Ok(out)
+ })();
+ match r {
+ Ok(out) => files.push(out),
+ Err(e) => errors.push(json!({"file": path, "error": e.to_string()})),
+ }
+ }
+ json!({"files": files, "errors": errors})
+}
+
+fn batch(_s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.automate.batch";
+ let steps = parse_steps(p.get("steps").or_else(|| p.get("action")).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: "missing \"steps\"".into() })?)?;
+ if let Some((id, _)) = steps.iter().find(|(id, _)| crate::commands::find(id).is_none()) {
+ return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unknown command `{id}` in the action") });
+ }
+ let inputs = batch_inputs(p, cmd)?;
+ let output = str_param(p, "output", cmd)?.to_string();
+ let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string();
+ let r = process_files(&inputs, &output, &format, f64_param(p, "quality"), "", &|scratch| {
+ for (id, params) in &steps {
+ scratch.execute(id, params.clone())?;
+ }
+ Ok(())
+ });
+ Ok(r)
+}
+
+fn image_processor(_s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.scripts.imageProcessor";
+ let inputs = batch_inputs(p, cmd)?;
+ let output = str_param(p, "output", cmd)?.to_string();
+ let format = p.get("format").and_then(Value::as_str).unwrap_or("jpg").to_string();
+ let fit = match (size_param(p, "width"), size_param(p, "height")) {
+ (None, None) => None,
+ (w, h) => Some(json!({"width": w.unwrap_or(1e9), "height": h.unwrap_or(1e9), "dontEnlarge": true})),
+ };
+ let to_srgb = p.get("convertToSrgb").and_then(Value::as_bool).unwrap_or(false);
+ let r = process_files(&inputs, &output, &format, f64_param(p, "quality").or(Some(8.0)), "", &|scratch| {
+ if to_srgb && scratch.active().is_some_and(|d| d.doc.mode != ColorMode::Rgb) {
+ scratch.execute("image.mode.rgb", json!({}))?;
+ }
+ if let Some(fp) = &fit {
+ fit_image(scratch, fp)?;
+ }
+ Ok(())
+ });
+ Ok(r)
+}
+
+fn load_files_into_stack(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.scripts.loadFilesIntoStack";
+ let paths: Vec<String> = match p.get("paths").or_else(|| p.get("input")) {
+ Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
+ Some(Value::String(dir)) => list_images(dir)?,
+ _ => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"paths\"".into() }),
+ };
+ if paths.is_empty() {
+ return Err(EngineError::BadParams { cmd: cmd.into(), msg: "no files to load".into() });
+ }
+ let mut docs = Vec::new();
+ for path in &paths {
+ let bytes = read_file(path)?;
+ docs.push((file_name(path), import(&file_name(path), &bytes)?));
+ }
+ let first = &docs[0].1;
+ let w = docs.iter().map(|(_, d)| d.size.width).max().unwrap_or(1);
+ let h = docs.iter().map(|(_, d)| d.size.height).max().unwrap_or(1);
+ let mut stack = Document::new(stem(&paths[0]), photocraft_doc::Size::new(w, h), first.mode, first.depth);
+ stack.resolution_dpi = first.resolution_dpi;
+ stack.icc_profile = first.icc_profile.clone();
+ let fmt = stack.pixel_format();
+ // First file at the bottom, like Photoshop's script.
+ for (name, d) in &docs {
+ stack.layers.push(Layer::new(name.clone(), LayerContent::Raster(flattened(d, fmt))));
+ }
+ let n = stack.layers.len();
+ if p.get("createSmartObject").and_then(Value::as_bool).unwrap_or(false) {
+ // "Create Smart Object after Loading Layers": the layers go inside one smart object, ready
+ // for Layer › Smart Objects › Stack Mode.
+ let children = std::mem::take(&mut stack.layers);
+ let group = Layer::new(stem(&paths[0]), LayerContent::Group(photocraft_doc::Group { children, expanded: true, artboard: None }));
+ let smart = crate::smart_cmds::layer_to_smart(&stack, &group)?;
+ stack.layers = vec![smart];
+ }
+ let i = s.add_document(stack, None);
+ Ok(json!({"document": i, "layers": n}))
+}
+
+// ---------- Scripts: flatten effects / masks ----------
+
+fn has_live_effects(l: &Layer) -> bool {
+ l.effects.enabled && l.effects.items.iter().any(|e| e.enabled())
+}
+
+/// The layer rendered alone (keeping what `keep` says), as a surface in `fmt`.
+fn bake(l: &Layer, canvas: Rect, fmt: PixelFormat, keep_effects: bool) -> Surface {
+ let mut tmp = l.clone();
+ tmp.opacity = 1.0;
+ tmp.blend = photocraft_color::BlendMode::Normal;
+ tmp.visible = true;
+ tmp.clipped = false;
+ if !keep_effects {
+ tmp.effects.items.clear();
+ tmp.fill_opacity = 1.0;
+ }
+ // Render over the union of the canvas and the content so off-canvas pixels survive.
+ let area = l.surface().map_or(canvas, |s| s.content_bounds().union(&canvas));
+ let area = if keep_effects { area.inflate(256) } else { area };
+ buffer_surface(&photocraft_compose::render_layer(&tmp, area), fmt)
+}
+
+fn walk_ids(doc: &Document) -> Vec<LayerId> {
+ doc.walk().into_iter().map(|(_, _, l)| l.id).collect()
+}
+
+fn flatten_all_effects(s: &mut Session) -> Result<Value> {
+ let mut n = 0;
+ s.edit("Flatten All Layer Effects", |doc, _| {
+ let canvas = doc.bounds();
+ let fmt = doc.pixel_format();
+ for id in walk_ids(doc) {
+ let Some(l) = doc.layer(id) else { continue };
+ if !has_live_effects(l) || matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) {
+ continue;
+ }
+ let px = bake(l, canvas, fmt, true);
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ l.content = LayerContent::Raster(px);
+ l.effects = Default::default();
+ l.mask = None;
+ l.vector_mask = None;
+ l.fill_opacity = 1.0;
+ l.fill_cache = None;
+ l.psd_blocks.retain(|(k, _)| !matches!(k, b"TySh" | b"SoLd" | b"PlLd" | b"SoLE" | b"vmsk" | b"vsms" | b"vogk" | b"vscg" | b"vstk"));
+ n += 1;
+ }
+ Ok(())
+ })?;
+ Ok(json!({"flattened": n}))
+}
+
+fn flatten_all_masks(s: &mut Session) -> Result<Value> {
+ let (mut n, mut skipped) = (0, 0);
+ s.edit("Flatten All Masks", |doc, _| {
+ let canvas = doc.bounds();
+ let fmt = doc.pixel_format();
+ for id in walk_ids(doc) {
+ let Some(l) = doc.layer(id) else { continue };
+ let masked = l.mask.as_ref().is_some_and(|m| m.enabled) || l.vector_mask.is_some();
+ if !masked {
+ continue;
+ }
+ if !matches!(l.content, LayerContent::Raster(_)) {
+ // Masks on groups, adjustment, type, shape and smart layers have no pixels to
+ // fold into; Photoshop's script leaves them too.
+ skipped += 1;
+ continue;
+ }
+ let px = bake(l, canvas, fmt, false);
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ l.content = LayerContent::Raster(px);
+ l.mask = None;
+ l.vector_mask = None;
+ l.psd_blocks.retain(|(k, _)| !matches!(k, b"vmsk" | b"vsms"));
+ n += 1;
+ }
+ Ok(())
+ })?;
+ Ok(json!({"flattened": n, "skipped": skipped}))
+}
+
+// ---------- Export ----------
+
+fn layers_to_files(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export.layersToFiles";
+ let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string();
+ let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
+ let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true);
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));
+ let doc = d.doc.clone();
+ let mut files = Vec::new();
+ // Top-level layers (groups export merged), top to bottom like Photoshop's numbering.
+ let layers: Vec<&Layer> = doc.layers.iter().rev().filter(|l| l.visible || !visible_only).collect();
+ for (i, l) in layers.iter().enumerate() {
+ if matches!(l.content, LayerContent::Adjustment(_)) {
+ continue;
+ }
+ let mut one = (*doc).clone();
+ let mut only = (*l).clone();
+ only.visible = true;
+ only.clipped = false;
+ one.layers = vec![only];
+ let path = join(&dir, &format!("{}_{:04}_{}.{format}", sanitize(&prefix), i, sanitize(&l.name)));
+ save_doc(&one, &path, f64_param(p, "quality"))?;
+ files.push(path);
+ }
+ Ok(json!({"files": files}))
+}
+
+/// The document's visible top-level adjustment layers applied to an identity lattice, as a
+/// `.cube` 3D LUT (red fastest, values 0–1).
+pub fn bake_cube(doc: &Document, size: usize, title: &str) -> String {
+ let n = size.clamp(2, 256);
+ let (w, h) = ((n * n) as u32, n as u32);
+ let mut lattice = Document::new("lut", photocraft_doc::Size::new(w, h), ColorMode::Rgb, photocraft_color::SampleType::F32);
+ let fmt = lattice.pixel_format();
+ let step = 1.0 / (n - 1) as f32;
+ let mut data = Vec::with_capacity((w * h) as usize * fmt.channels());
+ for g in 0..n {
+ for b in 0..n {
+ for r in 0..n {
+ let mut px = [0.0f32; 8];
+ let k = from_rgba_into(&fmt, [r as f32 * step, g as f32 * step, b as f32 * step, 1.0], &mut px);
+ data.extend_from_slice(&px[..k]);
+ }
+ }
+ }
+ let mut surf = Surface::new(fmt);
+ surf.write_region(Rect::new(0, 0, w as i32, h as i32), &data);
+ lattice.layers.push(Layer::new("Lattice", LayerContent::Raster(surf)));
+ for l in doc.layers.iter().filter(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))) {
+ let mut a = l.clone();
+ // Masks and clipping are spatial; a LUT is the adjustment stack's colour mapping.
+ a.mask = None;
+ a.vector_mask = None;
+ a.clipped = false;
+ lattice.layers.push(a);
+ }
+ let out = photocraft_compose::flatten(&lattice);
+ let mut s = format!("TITLE \"{}\"\n# Created by Photocraft\nLUT_3D_SIZE {n}\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n", title.replace('"', "'"));
+ // .cube order: red changes fastest, then green, then blue.
+ for b in 0..n {
+ for g in 0..n {
+ for r in 0..n {
+ let (x, y) = (b * n + r, g);
+ let px = out.px[y * w as usize + x];
+ s.push_str(&format!("{:.6} {:.6} {:.6}\n", px[0].clamp(0.0, 1.0), px[1].clamp(0.0, 1.0), px[2].clamp(0.0, 1.0)));
+ }
+ }
+ }
+ s
+}
+
+fn color_lookup_tables(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let size = p.get("size").and_then(Value::as_u64).unwrap_or(33) as usize;
+ let title = p.get("title").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));
+ let cube = bake_cube(&d.doc, size, &title);
+ match p.get("path").and_then(Value::as_str) {
+ Some(path) => {
+ write_file(path, cube.as_bytes())?;
+ Ok(json!({"path": path, "size": size.clamp(2, 256)}))
+ }
+ None => Ok(json!({"cube": cube, "size": size.clamp(2, 256)})),
+ }
+}
+
+// ---------- guides ----------
+
+fn push_unique(v: &mut Vec<f32>, x: f64) {
+ let x = x as f32;
+ if !v.iter().any(|g| (g - x).abs() < 0.01) {
+ v.push(x);
+ }
+}
+
+/// Guide positions for `count` columns (or rows) across `[start, end]`, Photoshop-style: both
+/// edges of every column; a fixed `width` packs columns from `start` (or centres them).
+fn layout_lines(start: f64, end: f64, count: u32, width: Option<f64>, gutter: f64, center: bool, out: &mut Vec<f32>) {
+ let avail = (end - start).max(0.0);
+ if count == 0 {
+ return;
+ }
+ let n = count as f64;
+ let w = width.unwrap_or(((avail - (n - 1.0) * gutter) / n).max(0.0));
+ let total = n * w + (n - 1.0) * gutter;
+ let x0 = if center && width.is_some() { start + (avail - total) / 2.0 } else { start };
+ for i in 0..count {
+ let a = x0 + i as f64 * (w + gutter);
+ push_unique(out, a);
+ push_unique(out, a + w);
+ }
+}
+
+fn new_guide_layout(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let (cw, ch) = (d.doc.size.width as f64, d.doc.size.height as f64);
+ let m = match p.get("margin") {
+ Some(Value::Array(a)) if a.len() == 4 => [0, 1, 2, 3].map(|i| a[i].as_f64().unwrap_or(0.0)),
+ Some(v) if v.is_number() => [v.as_f64().unwrap_or(0.0); 4],
+ _ => [0.0; 4],
+ };
+ let [top, left, bottom, right] = m;
+ let cols = p.get("columns").and_then(Value::as_u64).unwrap_or(0) as u32;
+ let rows = p.get("rows").and_then(Value::as_u64).unwrap_or(0) as u32;
+ let mut v: Vec<f32> = Vec::new();
+ let mut h: Vec<f32> = Vec::new();
+ let has_margin = m.iter().any(|x| *x != 0.0);
+ if has_margin {
+ push_unique(&mut v, left);
+ push_unique(&mut v, cw - right);
+ push_unique(&mut h, top);
+ push_unique(&mut h, ch - bottom);
+ }
+ let center = p.get("centerColumns").and_then(Value::as_bool).unwrap_or(false);
+ layout_lines(left, cw - right, cols, size_param(p, "width"), f64_param(p, "gutter").unwrap_or(0.0), center, &mut v);
+ layout_lines(top, ch - bottom, rows, size_param(p, "height"), f64_param(p, "rowGutter").or_else(|| f64_param(p, "gutter")).unwrap_or(0.0), center, &mut h);
+ if v.is_empty() && h.is_empty() {
+ return Err(EngineError::BadParams { cmd: "view.newGuideLayout".into(), msg: "give \"columns\", \"rows\" or a \"margin\"".into() });
+ }
+ let clear = p.get("clearExisting").and_then(Value::as_bool).unwrap_or(false);
+ let (nv, nh) = (v.len(), h.len());
+ s.edit("New Guide Layout", |doc, _| {
+ if clear {
+ doc.guides.vertical.clear();
+ doc.guides.horizontal.clear();
+ }
+ for x in v {
+ push_unique(&mut doc.guides.vertical, x as f64);
+ }
+ for y in h {
+ push_unique(&mut doc.guides.horizontal, y as f64);
+ }
+ Ok(())
+ })?;
+ Ok(json!({"vertical": nv, "horizontal": nh}))
+}
+
+fn guides_from_shape(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ 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("the layer is not a shape layer".into())) };
+ let (x0, y0, x1, y1) = sh.path.control_bounds().ok_or(EngineError::Other("the shape has no path".into()))?;
+ s.edit("New Guides From Shape", |doc, _| {
+ for x in [x0, (x0 + x1) / 2.0, x1] {
+ push_unique(&mut doc.guides.vertical, x);
+ }
+ for y in [y0, (y0 + y1) / 2.0, y1] {
+ push_unique(&mut doc.guides.horizontal, y);
+ }
+ Ok(())
+ })?;
+ Ok(json!({"bounds": [x0, y0, x1, y1]}))
+}
+
+fn clear_canvas_guides(s: &mut Session) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ if d.doc.guides.vertical.is_empty() && d.doc.guides.horizontal.is_empty() {
+ return Ok(json!({"cleared": 0}));
+ }
+ let n = d.doc.guides.vertical.len() + d.doc.guides.horizontal.len();
+ // Without artboards every guide is a canvas guide.
+ s.edit("Clear Canvas Guides", |doc, _| {
+ doc.guides.vertical.clear();
+ doc.guides.horizontal.clear();
+ Ok(())
+ })?;
+ Ok(json!({"cleared": n}))
+}
+
+// ---------- registry ----------
+
+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!("file.closeAll", "Close All", &["File"], Some("Cmd+Alt+W"), "{}", has_doc, |s, _| close_all(s)),
+ spec!("file.closeOthers", "Close Others", &["File"], Some("Cmd+Alt+P"), r##"{"document":index? (the one to keep; default active)}"##, has_doc, close_others),
+ spec!("file.revert", "Revert", &["File"], Some("F12"), "{} (reloads the saved file as one undoable step)", can_revert, |s, _| revert(s)),
+ spec!("file.saveACopy", "Save a Copy…", &["File"], Some("Cmd+Alt+S"), r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true}"##, native_doc, save_a_copy),
+ spec!("file.openAs", "Open As…", &["File"], Some("Cmd+Alt+Shift+O"), r##"{"path":str,"as":"psd|png|jpg|tiff|…"? (decode as this format)}"##, native, open_as),
+ spec!("file.placeEmbedded", "Place Embedded…", &["File"], None, r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool=true,"center":[x,y]?}"##, native_doc, |s, p| place(s, p, false)),
+ spec!("file.placeLinked", "Place Linked…", &["File"], None, r##"{"path":str,"scale":%?,"fit":bool=true,"center":[x,y]?}"##, native_doc, |s, p| place(s, p, true)),
+ spec!("file.fileInfo", "File Info…", &["File"], Some("Cmd+Alt+Shift+I"), r##"{"title":str?,"author":str?,"authorTitle":str?,"description":str?,"keywords":[str]|"a; b"?,"copyright":str?,"copyrightStatus":"unknown|copyrighted|publicDomain"?,"copyrightUrl":str?} (no keys: read)"##, has_doc, file_info),
+ spec!("file.automate.fitImage", "Fit Image…", &["File", "Automate"], None, r##"{"width":px,"height":px,"dontEnlarge":bool=false,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"}"##, has_doc, fit_image),
+ spec!("file.automate.conditionalModeChange", "Conditional Mode Change…", &["File", "Automate"], None, r##"{"from":["rgb","grayscale","cmyk","lab","indexed","bitmap",…]|"any"="any","to":"rgb|grayscale|cmyk|lab"}"##, has_doc, conditional_mode_change),
+ spec!("file.automate.batch", "Batch…", &["File", "Automate"], None, r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?} → {files, errors}"##, native, batch),
+ spec!("file.scripts.imageProcessor", "Image Processor…", &["File", "Scripts"], None, r##"{"input":folder|[paths],"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors}"##, native, image_processor),
+ spec!("file.scripts.loadFilesIntoStack", "Load Files into Stack…", &["File", "Scripts"], None, r##"{"paths":[str]|folder,"createSmartObject":bool=false} → new document with one layer per file (inside one smart object with createSmartObject)"##, native, load_files_into_stack),
+ spec!("file.scripts.flattenAllLayerEffects", "Flatten All Layer Effects", &["File", "Scripts"], None, "{}", has_doc, |s, _| flatten_all_effects(s)),
+ spec!("file.scripts.flattenAllMasks", "Flatten All Masks", &["File", "Scripts"], None, "{} (pixel layers; masks on other layer kinds are left)", has_doc, |s, _| flatten_all_masks(s)),
+ spec!("file.export.layersToFiles", "Layers to Files…", &["File", "Export"], None, r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?} → {files}"##, native_doc, layers_to_files),
+ spec!("file.export.colorLookupTables", "Color Lookup Tables…", &["File", "Export"], None, r##"{"path":str? (.cube; omit to return the text),"size":2..256=33,"title":str?}"##, has_adjustments, color_lookup_tables),
+ spec!("view.newGuideLayout", "New Guide Layout…", &["View"], None, r##"{"columns":n=0,"width":px?,"gutter":px=0,"rows":n=0,"height":px?,"rowGutter":px=gutter,"margin":px|[top,left,bottom,right]=0,"centerColumns":bool=false,"clearExisting":bool=false}"##, has_doc, new_guide_layout),
+ spec!("view.newGuidesFromShape", "New Guides From Shape", &["View"], None, r##"{"layer":id?}"##, has_shape, guides_from_shape),
+ spec!("view.clearCanvasGuides", "Clear Canvas Guides", &["View"], None, "{}", has_doc, |s, _| clear_canvas_guides(s)),
+ ]
+}
+
+#[cfg(test)]
+#[path = "file_cmds/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs
new file mode 100644
index 000000000..c28cb2b6f
--- /dev/null
+++ b/crates/engine/src/file_cmds/tests.rs
@@ -0,0 +1,327 @@
+use super::*;
+
+fn tmp(name: &str) -> String {
+ let d = std::env::temp_dir().join(format!("photocraft-file-cmds-{}-{name}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d.to_string_lossy().into_owned()
+}
+
+fn session(w: u32, h: u32, depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap();
+ s
+}
+
+fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+}
+
+/// Writes a solid-colour PNG of `w × h` and returns its path.
+fn png(dir: &str, name: &str, w: u32, h: u32, color: &str) -> String {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": w, "height": h, "background": color})).unwrap();
+ let path = join(dir, name);
+ save_doc(doc(&s), &path, None).unwrap();
+ path
+}
+
+fn composite(s: &Session, x: i32, y: i32) -> [f32; 4] {
+ let b = photocraft_compose::render(doc(s), Rect::new(x, y, x + 1, y + 1));
+ b.px[0]
+}
+
+#[test]
+fn close_all_and_close_others() {
+ let mut s = session(8, 8, 8);
+ s.execute("file.new", json!({"width": 9, "height": 9})).unwrap();
+ s.execute("file.new", json!({"width": 10, "height": 10})).unwrap();
+ s.set_active(1);
+ assert_eq!(s.execute("file.closeOthers", json!({})).unwrap()["closed"], 2);
+ assert_eq!(s.documents().len(), 1);
+ assert_eq!(doc(&s).size.width, 9);
+ assert_eq!(s.active_index(), Some(0));
+ assert!(s.execute("file.closeOthers", json!({"document": 5})).is_err());
+ s.execute("file.new", json!({})).unwrap();
+ assert_eq!(s.execute("file.closeAll", json!({})).unwrap()["closed"], 2);
+ assert!(s.documents().is_empty());
+ assert!(!s.is_enabled("file.closeAll"));
+}
+
+#[test]
+fn revert_reloads_as_one_undoable_step() {
+ let dir = tmp("revert");
+ let path = png(&dir, "a.png", 16, 12, "#ff0000");
+ let mut s = Session::new();
+ assert!(!s.is_enabled("file.revert"));
+ let bytes = std::fs::read(&path).unwrap();
+ open_bytes_as(&mut s, &path, &bytes, None, Some(path.clone())).unwrap();
+ let id = doc(&s).id;
+ assert!(s.is_enabled("file.revert"));
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ assert!(s.active().unwrap().is_dirty());
+ s.execute("file.revert", json!({})).unwrap();
+ assert_eq!(doc(&s).layers.len(), 1);
+ assert_eq!(doc(&s).id, id, "identity kept");
+ assert!(!s.active().unwrap().is_dirty());
+ assert!(composite(&s, 3, 3)[0] > 0.99);
+ // Revert is a history state: undo brings the edits back.
+ assert!(s.undo());
+ assert_eq!(doc(&s).layers.len(), 2);
+ // An unsaved document cannot revert.
+ s.execute("file.new", json!({})).unwrap();
+ assert!(s.execute("file.revert", json!({})).is_err());
+}
+
+#[test]
+fn save_a_copy_keeps_path_and_dirty_state() {
+ let dir = tmp("copy");
+ let mut s = session(20, 10, 16);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let rev = s.active().unwrap().revision;
+ let out = join(&dir, "copy.psd");
+ s.execute("file.saveACopy", json!({"path": out})).unwrap();
+ assert!(std::fs::metadata(&out).unwrap().len() > 0);
+ assert_eq!(s.active().unwrap().path, None);
+ assert_eq!(s.active().unwrap().revision, rev);
+ assert!(s.active().unwrap().is_dirty());
+ let back = photocraft_io::import("copy.psd", &std::fs::read(&out).unwrap()).unwrap().document;
+ assert_eq!(back.layers.len(), 2);
+ assert_eq!(back.depth, photocraft_color::SampleType::U16);
+ // Flattened copy.
+ let flat = join(&dir, "flat.psd");
+ s.execute("file.saveACopy", json!({"path": flat, "layers": false})).unwrap();
+ assert_eq!(photocraft_io::import("flat.psd", &std::fs::read(&flat).unwrap()).unwrap().document.layers.len(), 1);
+ assert!(s.execute("file.saveACopy", json!({})).is_err());
+}
+
+#[test]
+fn open_as_forces_the_decoder() {
+ let dir = tmp("openas");
+ let path = png(&dir, "a.png", 6, 5, "#00ff00");
+ let renamed = join(&dir, "mystery.bin");
+ std::fs::copy(&path, &renamed).unwrap();
+ let mut s = Session::new();
+ s.execute("file.openAs", json!({"path": renamed, "as": "png"})).unwrap();
+ assert_eq!(doc(&s).size.width, 6);
+ assert_eq!(doc(&s).name, "mystery.bin");
+ assert_eq!(s.active().unwrap().path.as_deref(), Some(renamed.as_str()));
+ assert!(s.execute("file.openAs", json!({"path": join(&dir, "missing.png")})).is_err());
+}
+
+#[test]
+fn place_embedded_centres_fits_and_embeds() {
+ let dir = tmp("place");
+ let big = png(&dir, "big.png", 200, 100, "#ff0000");
+ let small = png(&dir, "small.png", 10, 10, "#0000ff");
+ for depth in [8, 16, 32] {
+ let mut s = session(100, 100, depth);
+ let r = s.execute("file.placeEmbedded", json!({"path": big})).unwrap();
+ assert!((r["scale"].as_f64().unwrap() - 50.0).abs() < 1e-9);
+ let d = s.active().unwrap();
+ let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
+ assert_eq!(l.name, "big");
+ let LayerContent::Smart(so) = &l.content else { panic!("smart object expected") };
+ assert!(matches!(&so.source, SmartSource::Embedded { file_name, bytes } if file_name == "big.png" && !bytes.is_empty()));
+ assert_eq!(so.transform.m[0], 0.5);
+ // Fitted to the canvas width, centred vertically: rows 25..75 red.
+ assert!(composite(&s, 50, 50)[0] > 0.99 && composite(&s, 50, 50)[2] < 0.01);
+ assert!(composite(&s, 50, 10)[1] > 0.99, "white background above");
+ // Small images keep their size, centred.
+ s.execute("file.placeLinked", json!({"path": small})).unwrap();
+ assert!(composite(&s, 50, 50)[2] > 0.99);
+ assert!(composite(&s, 40, 40)[2] < 0.01);
+ let d = s.active().unwrap();
+ let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
+ assert!(matches!(&l.content, LayerContent::Smart(so) if matches!(&so.source, SmartSource::Linked { path } if path == &small)));
+ // One step each.
+ assert!(s.undo() && s.undo());
+ assert_eq!(doc(&s).layers.len(), 1);
+ }
+}
+
+#[test]
+fn file_info_round_trips_through_xmp_and_psd() {
+ let mut s = session(8, 8, 8);
+ let empty = s.execute("file.fileInfo", json!({})).unwrap();
+ assert_eq!(empty["title"], "");
+ assert!(!s.undo(), "reading is not a history step");
+ s.execute("file.fileInfo", json!({"title": "Starry <Night>", "author": "V. van Gogh", "keywords": ["stars", "night"], "copyright": "Public domain", "copyrightStatus": "publicDomain", "description": "Oil & canvas"})).unwrap();
+ let info = s.execute("file.fileInfo", json!({})).unwrap();
+ assert_eq!(info["title"], "Starry <Night>");
+ assert_eq!(info["author"], "V. van Gogh");
+ assert_eq!(info["keywords"], json!(["stars", "night"]));
+ assert_eq!(info["description"], "Oil & canvas");
+ assert_eq!(info["copyrightStatus"], "publicDomain");
+ // Editing one field keeps the others and replaces, not duplicates.
+ s.execute("file.fileInfo", json!({"title": "The Starry Night"})).unwrap();
+ let xmp = doc(&s).metadata.xmp.clone().unwrap();
+ assert_eq!(xmp.matches("<dc:title>").count(), 1);
+ assert_eq!(read_file_info(Some(&xmp))["author"], "V. van Gogh");
+ // PSD round trip.
+ let (bytes, _) = encode(doc(&s), "x.psd", None).unwrap();
+ let back = photocraft_io::import("x.psd", &bytes).unwrap().document;
+ let info = read_file_info(back.metadata.xmp.as_deref());
+ assert_eq!(info["title"], "The Starry Night");
+ assert_eq!(info["keywords"], json!(["stars", "night"]));
+ // Foreign XMP (attribute form, other namespaces) keeps its other properties.
+ let foreign = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:CreatorTool="Other App" photoshop:AuthorsPosition="Painter"/></rdf:RDF></x:xmpmeta>"#;
+ assert_eq!(read_file_info(Some(foreign))["authorTitle"], "Painter");
+ let out = write_file_info(Some(foreign), &json!({"authorTitle": "Artist"}));
+ assert!(out.contains("xmp:CreatorTool=\"Other App\""));
+ assert_eq!(read_file_info(Some(&out))["authorTitle"], "Artist");
+}
+
+#[test]
+fn fit_image_and_conditional_mode_change() {
+ let mut s = session(400, 200, 8);
+ s.execute("file.automate.fitImage", json!({"width": 100, "height": 100})).unwrap();
+ assert_eq!((doc(&s).size.width, doc(&s).size.height), (100, 50));
+ let r = s.execute("file.automate.fitImage", json!({"width": 1000, "height": 1000, "dontEnlarge": true})).unwrap();
+ assert_eq!(r["changed"], false);
+ s.execute("file.automate.fitImage", json!({"width": 1000, "height": 1000})).unwrap();
+ assert_eq!(doc(&s).size.width, 1000);
+ let r = s.execute("file.automate.conditionalModeChange", json!({"from": ["cmyk"], "to": "grayscale"})).unwrap();
+ assert_eq!(r["changed"], false);
+ s.execute("file.automate.conditionalModeChange", json!({"from": ["rgb", "lab"], "to": "grayscale"})).unwrap();
+ assert_eq!(doc(&s).mode, ColorMode::Grayscale);
+ s.execute("file.automate.conditionalModeChange", json!({"to": "rgb"})).unwrap();
+ assert_eq!(doc(&s).mode, ColorMode::Rgb);
+ assert!(s.execute("file.automate.conditionalModeChange", json!({"to": "duotone"})).is_err());
+}
+
+#[test]
+fn flatten_all_layer_effects_and_masks() {
+ for depth in [8, 16, 32] {
+ let mut s = session(40, 40, depth);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ let id = s.active().unwrap().active_layer.unwrap();
+ s.edit("fx", |doc, _| {
+ let l = doc.layer_mut(id).unwrap();
+ l.effects.enabled = true;
+ l.effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::effects::FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), color: photocraft_color::Color::rgb(0.0, 1.0, 0.0) });
+ Ok(())
+ })
+ .unwrap();
+ let before = composite(&s, 15, 15);
+ assert!(before[1] > 0.99, "overlay renders green");
+ assert_eq!(s.execute("file.scripts.flattenAllLayerEffects", json!({})).unwrap()["flattened"], 1);
+ let l = doc(&s).layer(id).unwrap();
+ assert!(l.effects.items.is_empty() && matches!(l.content, LayerContent::Raster(_)));
+ let after = composite(&s, 15, 15);
+ assert!((after[1] - before[1]).abs() < 0.01 && after[0] < 0.01, "{after:?}");
+ // Masks: hide the left half, flatten, mask gone, pixels gone.
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 40})).unwrap();
+ s.execute("select.inverse", json!({})).unwrap();
+ s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ assert!(composite(&s, 15, 15)[1] > 0.99 && composite(&s, 15, 15)[0] > 0.99, "white shows through the mask");
+ let r = s.execute("file.scripts.flattenAllMasks", json!({})).unwrap();
+ assert_eq!(r["flattened"], 1);
+ let l = doc(&s).layer(id).unwrap();
+ assert!(l.mask.is_none());
+ assert!(l.surface().unwrap().content_bounds().x0 >= 20);
+ assert!(composite(&s, 25, 15)[1] > 0.99 && composite(&s, 25, 15)[0] < 0.01);
+ // Each script is a single history step.
+ assert!(s.undo());
+ assert!(doc(&s).layer(id).unwrap().mask.is_some());
+ }
+}
+
+#[test]
+fn layers_to_files_writes_each_visible_layer() {
+ let dir = tmp("layers");
+ let mut s = session(12, 12, 8);
+ s.execute("layer.new.layer", json!({"name": "Ink/1"})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "Hidden"})).unwrap();
+ s.execute("layer.setProps", json!({"visible": false})).unwrap();
+ let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "png"})).unwrap();
+ let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
+ assert_eq!(files.len(), 2, "{files:?}");
+ assert!(files[0].ends_with("doc_0000_Ink_1.png"), "{files:?}");
+ assert!(files.iter().all(|f| std::path::Path::new(f).is_file()));
+ let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "visibleOnly": false, "format": "psd"})).unwrap();
+ assert_eq!(r["files"].as_array().unwrap().len(), 3);
+}
+
+#[test]
+fn load_files_into_stack_and_image_processor_and_batch() {
+ let dir = tmp("batch");
+ let input = join(&dir, "in");
+ std::fs::create_dir_all(&input).unwrap();
+ let a = png(&input, "a.png", 40, 20, "#ff0000");
+ let b = png(&input, "b.png", 30, 30, "#0000ff");
+ std::fs::write(join(&input, "notes.txt"), "not an image").unwrap();
+ let mut s = Session::new();
+ let r = s.execute("file.scripts.loadFilesIntoStack", json!({"paths": [a, b]})).unwrap();
+ assert_eq!(r["layers"], 2);
+ assert_eq!((doc(&s).size.width, doc(&s).size.height), (40, 30));
+ assert_eq!(doc(&s).layers[0].name, "a.png");
+ // Image Processor: fit into 20×20 JPEGs.
+ let out = join(&dir, "jpg");
+ let r = s.execute("file.scripts.imageProcessor", json!({"input": input, "output": out, "format": "jpg", "width": 20, "height": 20})).unwrap();
+ let files = r["files"].as_array().unwrap();
+ assert_eq!(files.len(), 2, "{r}");
+ let back = photocraft_io::import("a.jpg", &std::fs::read(files[0].as_str().unwrap()).unwrap()).unwrap().document;
+ assert_eq!((back.size.width, back.size.height), (20, 10));
+ // Batch: run an action (invert) over the folder, save PNGs.
+ let out = join(&dir, "png");
+ let r = s.execute("file.automate.batch", json!({"steps": [["image.adjustments.invert", {}]], "input": input, "output": out, "format": "png"})).unwrap();
+ assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}");
+ assert!(r["errors"].as_array().unwrap().is_empty());
+ let inv = photocraft_io::import("a.png", &std::fs::read(join(&out, "a.png")).unwrap()).unwrap().document;
+ let px = photocraft_compose::render(&inv, Rect::new(1, 1, 2, 2)).px[0];
+ assert!(px[0] < 0.01 && px[1] > 0.99 && px[2] > 0.99, "red inverted to cyan: {px:?}");
+ assert!(s.execute("file.automate.batch", json!({"steps": [["no.such.command", {}]], "input": input, "output": out})).is_err());
+}
+
+#[test]
+fn color_lookup_table_bakes_the_adjustment_stack() {
+ let mut s = session(8, 8, 8);
+ assert!(!s.is_enabled("file.export.colorLookupTables"));
+ s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();
+ let r = s.execute("file.export.colorLookupTables", json!({"size": 3})).unwrap();
+ let cube = r["cube"].as_str().unwrap();
+ assert!(cube.contains("LUT_3D_SIZE 3"));
+ let rows: Vec<Vec<f32>> = cube.lines().filter(|l| l.chars().next().is_some_and(|c| c.is_ascii_digit())).map(|l| l.split(' ').map(|v| v.parse().unwrap()).collect()).collect();
+ assert_eq!(rows.len(), 27);
+ // First entry (0,0,0) → white; second (r = 0.5) → 0.5; last (1,1,1) → black.
+ assert!(rows[0].iter().all(|v| (v - 1.0).abs() < 1e-3), "{:?}", rows[0]);
+ assert!((rows[1][0] - 0.5).abs() < 0.01 && (rows[1][1] - 1.0).abs() < 1e-3);
+ assert!(rows[2][0].abs() < 1e-3 && (rows[2][2] - 1.0).abs() < 1e-3, "red fastest");
+ assert!(rows[26].iter().all(|v| v.abs() < 1e-3));
+ let dir = tmp("lut");
+ let path = join(&dir, "invert.cube");
+ s.execute("file.export.colorLookupTables", json!({"path": path, "size": 17})).unwrap();
+ assert!(std::fs::read_to_string(&path).unwrap().contains("LUT_3D_SIZE 17"));
+}
+
+#[test]
+fn guide_layouts() {
+ let mut s = session(100, 50, 8);
+ let r = s.execute("view.newGuideLayout", json!({"columns": 2, "gutter": 10, "margin": [5, 10, 5, 10]})).unwrap();
+ assert_eq!(r["vertical"], 4);
+ let g = &doc(&s).guides;
+ assert_eq!(g.vertical, vec![10.0, 90.0, 45.0, 55.0]);
+ assert_eq!(g.horizontal, vec![5.0, 45.0]);
+ s.execute("view.newGuideLayout", json!({"rows": 2, "clearExisting": true})).unwrap();
+ let g = &doc(&s).guides;
+ assert!(g.vertical.is_empty());
+ assert_eq!(g.horizontal, vec![0.0, 25.0, 50.0]);
+ // Fixed-width centred columns.
+ s.execute("view.newGuideLayout", json!({"columns": 2, "width": 20, "gutter": 10, "centerColumns": true, "clearExisting": true})).unwrap();
+ assert_eq!(doc(&s).guides.vertical, vec![25.0, 45.0, 55.0, 75.0]);
+ assert!(s.execute("view.newGuideLayout", json!({})).is_err());
+ assert_eq!(s.execute("view.clearCanvasGuides", json!({})).unwrap()["cleared"], 4);
+ assert!(doc(&s).guides.vertical.is_empty());
+ assert!(!s.is_enabled("view.newGuidesFromShape"));
+ s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20]})).unwrap();
+ s.execute("view.newGuidesFromShape", json!({})).unwrap();
+ let g = &doc(&s).guides;
+ assert_eq!(g.vertical, vec![10.0, 30.0, 50.0]);
+ assert_eq!(g.horizontal, vec![10.0, 20.0, 30.0]);
+}
diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs
index 87e094eaf..878a2f370 100644
--- a/crates/engine/src/filters.rs
+++ b/crates/engine/src/filters.rs
@@ -36,6 +36,13 @@ fn undefined(p: &Value) -> UndefinedAreas {
pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {
Some(match id {
"filter.blur.gaussianBlur" => FilterParams::GaussianBlur { radius: f(p, "radius", 1.0).clamp(0.1, 1000.0) },
+ // One-step presets (no dialog), tuned to match Photoshop's fixed-strength filters.
+ "filter.blur.blur" => FilterParams::GaussianBlur { radius: 0.6 },
+ "filter.blur.blurMore" => FilterParams::GaussianBlur { radius: 1.4 },
+ "filter.sharpen.sharpen" => FilterParams::UnsharpMask { amount: 60.0, radius: 0.5, threshold: 0.0 },
+ "filter.sharpen.sharpenMore" => FilterParams::UnsharpMask { amount: 150.0, radius: 0.6, threshold: 0.0 },
+ "filter.sharpen.sharpenEdges" => FilterParams::UnsharpMask { amount: 100.0, radius: 0.8, threshold: 6.0 },
+ "filter.noise.despeckle" => FilterParams::SurfaceBlur { radius: 2.0, threshold: 12.0 },
"filter.blur.boxBlur" => FilterParams::BoxBlur { radius: f(p, "radius", 1.0).clamp(1.0, 2000.0) },
"filter.blur.motionBlur" => FilterParams::MotionBlur { angle: f(p, "angle", 0.0), distance: f(p, "distance", 10.0).clamp(1.0, 2000.0) },
"filter.blur.radialBlur" => FilterParams::RadialBlur {
@@ -106,11 +113,35 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {
"filter.distort.polarCoordinates" => FilterParams::PolarCoordinates {
mode: if s(p, "mode", "rectangularToPolar") == "polarToRectangular" { PolarMode::PolarToRectangular } else { PolarMode::RectangularToPolar },
},
- _ => return None,
+ _ => return crate::filters_ext::params_for(id, p),
})
}
-fn has_filterable_layer(s: &Session) -> std::result::Result<(), String> {
+/// Runs filter command `id` with JSON `params` on `surf` (the pixel function behind every
+/// `filter.*` command; smart filters re-run it on re-render). `bounds` frames distortions;
+/// `selection` limits the result. Like layer filters, neighbourhood filters repeat the edge pixels
+/// of `canvas` ∪ the surface's content instead of fading in transparency, and the output is
+/// clipped to it. `None` for ids that aren't pixel filters.
+pub fn apply_filter_to_surface(
+ id: &str,
+ params: &Value,
+ surf: &photocraft_raster::Surface,
+ bounds: photocraft_geom::Rect,
+ selection: Option<&photocraft_raster::Surface>,
+ canvas: photocraft_geom::Rect,
+) -> Option<photocraft_raster::Surface> {
+ let fp = params_for(id, params)?;
+ let sel_bounds = selection.map(photocraft_raster::Surface::content_bounds);
+ let content = surf.content_bounds();
+ let area = algo::output_area(&fp, content, bounds, sel_bounds);
+ Some(algo::apply_in(surf, &fp, area, bounds, selection, canvas.union(&content)))
+}
+
+pub(crate) fn has_filterable_layer(s: &Session) -> std::result::Result<(), String> {
+ // A targeted alpha channel or Quick Mask is filtered instead of the layer (channel_cmds).
+ if crate::channel_cmds::edits_channel(s) {
+ return Ok(());
+ }
let d = s.active().ok_or("no document open")?;
let id = d.active_layer.ok_or("no active layer")?;
let l = d.doc.layer(id).ok_or("no active layer")?;
@@ -121,8 +152,12 @@ fn has_filterable_layer(s: &Session) -> std::result::Result<(), String> {
}
}
-fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
- let fp = params_for(id, p).ok_or_else(|| EngineError::Other(format!("unknown filter {id}")))?;
+pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
+ // Session state some filters read (colours) becomes explicit params; external inputs resolve here.
+ let prepared = crate::filters_ext::prepare(s, id, p);
+ let p = &prepared;
+ let mut fp = params_for(id, p).ok_or_else(|| EngineError::Other(format!("unknown filter {id}")))?;
+ crate::filters_ext::resolve(s, &mut fp, p)?;
let layer = match p.get("layer").and_then(Value::as_u64) {
Some(l) => photocraft_doc::LayerId(l),
None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))?,
@@ -136,18 +171,30 @@ fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
let selection = doc.selection.clone();
let sel_bounds = selection.as_ref().map(photocraft_raster::Surface::content_bounds);
// Distortions centre on the selection when there is one, else the canvas.
- let bounds = sel_bounds.filter(|b| !b.is_empty()).unwrap_or_else(|| doc.bounds());
+ let doc_bounds = doc.bounds();
+ let bounds = sel_bounds.filter(|b| !b.is_empty()).unwrap_or(doc_bounds);
+ // Neighbourhood filters repeat edge pixels at the canvas edge (or past it, where the
+ // layer has off-canvas pixels) instead of fading in transparency, as Photoshop does.
+ if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, p)? {
+ let content = surf.content_bounds();
+ let area = algo::output_area(&fp, content, bounds, sel_bounds);
+ *surf = algo::apply_in(surf, &fp, area, bounds, selection.as_ref(), doc_bounds.union(&content));
+ return Ok(());
+ }
let l = doc.layer_mut(layer).ok_or(EngineError::NoLayer(layer))?;
+ crate::filters_ext::resolve_in_layer(&mut fp, l, bounds);
let surf = match &mut l.content {
LayerContent::Raster(surf) => surf,
- LayerContent::Smart(sm) => {
- sm.smart_filters.push(SmartFilter { command: id.to_string(), params: params.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true });
- sm.cache.as_mut().ok_or_else(|| EngineError::Other("smart object has no pixels".into()))?
+ LayerContent::Smart(_) => {
+ // Non-destructive: record the filter and re-render the smart object from its source.
+ let sf = SmartFilter { command: id.to_string(), params: params.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true };
+ return crate::smart_cmds::add_smart_filter(doc, layer, sf, selection.as_ref());
}
_ => return Err(EngineError::Other("not a pixel layer".into())),
};
- let area = algo::output_area(&fp, surf.content_bounds(), bounds, sel_bounds);
- *surf = algo::apply(surf, &fp, area, bounds, selection.as_ref());
+ let content = surf.content_bounds();
+ let area = algo::output_area(&fp, content, bounds, sel_bounds);
+ *surf = algo::apply_in(surf, &fp, area, bounds, selection.as_ref(), doc_bounds.union(&content));
Ok(())
})?;
Ok(json!({ "layer": layer.0, "filter": serde_json::to_value(&fp).unwrap_or(Value::Null) }))
@@ -172,6 +219,12 @@ macro_rules! filter_cmd {
pub fn specs() -> Vec<CommandSpec> {
vec![
filter_cmd!("filter.blur.gaussianBlur", "Gaussian Blur…", ["Filter", "Blur"], r##"{"radius":0.1..1000=1}"##),
+ filter_cmd!("filter.blur.blur", "Blur", ["Filter", "Blur"], "{}"),
+ filter_cmd!("filter.blur.blurMore", "Blur More", ["Filter", "Blur"], "{}"),
+ filter_cmd!("filter.sharpen.sharpen", "Sharpen", ["Filter", "Sharpen"], "{}"),
+ filter_cmd!("filter.sharpen.sharpenMore", "Sharpen More", ["Filter", "Sharpen"], "{}"),
+ filter_cmd!("filter.sharpen.sharpenEdges", "Sharpen Edges", ["Filter", "Sharpen"], "{}"),
+ filter_cmd!("filter.noise.despeckle", "Despeckle", ["Filter", "Noise"], "{}"),
filter_cmd!("filter.blur.boxBlur", "Box Blur…", ["Filter", "Blur"], r##"{"radius":1..2000=1}"##),
filter_cmd!("filter.blur.motionBlur", "Motion Blur…", ["Filter", "Blur"], r##"{"angle":-360..360=0,"distance":1..2000=10}"##),
filter_cmd!("filter.blur.radialBlur", "Radial Blur…", ["Filter", "Blur"], r##"{"amount":1..100=10,"method":"spin|zoom","centerX":0..1=0.5,"centerY":0..1=0.5}"##),
@@ -380,6 +433,10 @@ mod tests {
smart_filters: vec![],
cache: Some(cache),
psd_raw: None,
+ filters_enabled: true,
+ filter_mask: None,
+ warp: None,
+ stack_mode: None,
}),
);
*active = Some(doc.insert_above(*active, l));
diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rs
new file mode 100644
index 000000000..244a9b5a9
--- /dev/null
+++ b/crates/engine/src/filters_ext.rs
@@ -0,0 +1,503 @@
+//! The second batch of `filter.*` commands: Pixelate, Stylize, Distort (Displace, Shear,
+//! ZigZag), Render (Fibers, Lens Flare, Lighting Effects), Reduce Noise, Smart/Lens/Shape Blur,
+//! Blur Gallery, Other (Custom, HSB/HSL) and Video.
+//!
+//! They run through [`crate::filters::run_filter`] (selection, smart objects, history and
+//! `filter.lastFilter` work the same as for every other filter). This module adds what some of
+//! them need from the session: the foreground/background colours, a displacement map from
+//! another document or a file, and a layer mask as Lens Blur depth.
+
+use std::sync::Arc;
+
+use photocraft_algo::{
+ self as algo, BlurPath, BlurQuality, BlurShape, DepthSource, DiffuseMode, Distribution, ExtrudeType, FieldPin, FilterParams, HsbModel, IrisPin, LensType, Light, LightKind, MezzotintType, SmartBlurMode, SpinPin,
+ TextureChannel, TileFill, UndefinedAreas, WindMethod, ZigZagStyle,
+};
+use photocraft_doc::{Document, Layer};
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+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 i(p: &Value, k: &str, d: i64) -> i64 {
+ p.get(k).and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f.round() as i64))).unwrap_or(d)
+}
+fn b(p: &Value, k: &str, d: bool) -> bool {
+ p.get(k).and_then(Value::as_bool).unwrap_or(d)
+}
+fn s<'a>(p: &'a Value, k: &str, d: &'a str) -> &'a str {
+ p.get(k).and_then(Value::as_str).unwrap_or(d)
+}
+fn seed(p: &Value) -> u32 {
+ i(p, "seed", 0) as u32
+}
+/// Straight RGBA colour from `[r, g, b(, a)]` (0–1) or `#rrggbb`.
+fn colour(p: &Value, k: &str, d: [f32; 4]) -> [f32; 4] {
+ match p.get(k) {
+ Some(Value::Array(a)) if a.len() >= 3 => {
+ let c = |j: usize, dv: f32| a.get(j).and_then(Value::as_f64).map_or(dv, |v| v as f32);
+ [c(0, 0.0), c(1, 0.0), c(2, 0.0), c(3, 1.0)]
+ }
+ Some(Value::String(h)) if h.len() == 7 && h.starts_with('#') => {
+ let ch = |j: usize| u8::from_str_radix(&h[j..j + 2], 16).map_or(0.0, |v| v as f32 / 255.0);
+ [ch(1), ch(3), ch(5), 1.0]
+ }
+ _ => d,
+ }
+}
+fn undefined(p: &Value, d: &str) -> UndefinedAreas {
+ match s(p, "undefinedAreas", d) {
+ "repeat" => UndefinedAreas::Repeat,
+ "transparent" => UndefinedAreas::Transparent,
+ _ => UndefinedAreas::Wrap,
+ }
+}
+/// A JSON array param deserialized into `T`s (invalid entries are skipped).
+fn list<T: serde::de::DeserializeOwned>(p: &Value, k: &str) -> Option<Vec<T>> {
+ let a = p.get(k)?.as_array()?;
+ let v: Vec<T> = a.iter().filter_map(|e| serde_json::from_value(e.clone()).ok()).collect();
+ (!v.is_empty()).then_some(v)
+}
+
+const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
+const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
+
+/// Algorithm parameters for the ids this module owns (Photoshop dialog units).
+pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {
+ let blur = |d: f32| f(p, "blur", d).clamp(0.0, 500.0);
+ Some(match id {
+ // ---- Pixelate ----
+ "filter.pixelate.colorHalftone" => FilterParams::ColorHalftone {
+ max_radius: f(p, "maxRadius", 8.0).clamp(4.0, 127.0),
+ angles: [f(p, "channel1", 108.0), f(p, "channel2", 162.0), f(p, "channel3", 90.0), f(p, "channel4", 45.0)],
+ },
+ "filter.pixelate.crystallize" => FilterParams::Crystallize { cell_size: f(p, "cellSize", 10.0).clamp(3.0, 300.0), seed: seed(p) },
+ "filter.pixelate.facet" => FilterParams::Facet,
+ "filter.pixelate.fragment" => FilterParams::Fragment,
+ "filter.pixelate.mezzotint" => FilterParams::Mezzotint {
+ kind: match s(p, "type", "fineDots") {
+ "mediumDots" => MezzotintType::MediumDots,
+ "grainyDots" => MezzotintType::GrainyDots,
+ "coarseDots" => MezzotintType::CoarseDots,
+ "shortLines" => MezzotintType::ShortLines,
+ "mediumLines" => MezzotintType::MediumLines,
+ "longLines" => MezzotintType::LongLines,
+ "shortStrokes" => MezzotintType::ShortStrokes,
+ "mediumStrokes" => MezzotintType::MediumStrokes,
+ "longStrokes" => MezzotintType::LongStrokes,
+ _ => MezzotintType::FineDots,
+ },
+ seed: seed(p),
+ },
+ "filter.pixelate.pointillize" => FilterParams::Pointillize { cell_size: f(p, "cellSize", 5.0).clamp(3.0, 300.0), seed: seed(p), background: colour(p, "background", WHITE) },
+ // ---- Stylize ----
+ "filter.stylize.diffuse" => FilterParams::Diffuse {
+ mode: match s(p, "mode", "normal") {
+ "darkenOnly" => DiffuseMode::DarkenOnly,
+ "lightenOnly" => DiffuseMode::LightenOnly,
+ "anisotropic" => DiffuseMode::Anisotropic,
+ _ => DiffuseMode::Normal,
+ },
+ seed: seed(p),
+ },
+ "filter.stylize.extrude" => FilterParams::Extrude {
+ kind: if s(p, "type", "blocks") == "pyramids" { ExtrudeType::Pyramids } else { ExtrudeType::Blocks },
+ size: f(p, "size", 30.0).clamp(2.0, 255.0),
+ depth: f(p, "depth", 30.0).clamp(1.0, 255.0),
+ level_based: s(p, "depthMode", "random") == "levelBased",
+ solid_front: b(p, "solidFrontFaces", false),
+ mask_incomplete: b(p, "maskIncompleteBlocks", false),
+ seed: seed(p),
+ },
+ "filter.stylize.oilPaint" => FilterParams::OilPaint {
+ stylization: f(p, "stylization", 4.0).clamp(0.1, 10.0),
+ cleanliness: f(p, "cleanliness", 5.0).clamp(0.0, 10.0),
+ scale: f(p, "scale", 1.0).clamp(0.1, 10.0),
+ bristle_detail: f(p, "bristleDetail", 5.0).clamp(0.0, 10.0),
+ lighting: b(p, "lighting", true),
+ angle: f(p, "angle", -60.0),
+ shine: f(p, "shine", 1.0).clamp(0.0, 10.0),
+ },
+ "filter.stylize.tiles" => FilterParams::Tiles {
+ count: i(p, "count", 10).clamp(1, 99) as u32,
+ max_offset: f(p, "maxOffset", 10.0).clamp(1.0, 99.0),
+ fill: match s(p, "fill", "background") {
+ "foreground" => TileFill::Foreground,
+ "inverse" => TileFill::Inverse,
+ "unaltered" => TileFill::Unaltered,
+ _ => TileFill::Background,
+ },
+ foreground: colour(p, "foreground", BLACK),
+ background: colour(p, "background", WHITE),
+ seed: seed(p),
+ },
+ "filter.stylize.traceContour" => FilterParams::TraceContour { level: f(p, "level", 128.0).clamp(0.0, 255.0), upper: s(p, "edge", "lower") == "upper" },
+ "filter.stylize.wind" => FilterParams::Wind {
+ method: match s(p, "method", "wind") {
+ "blast" => WindMethod::Blast,
+ "stagger" => WindMethod::Stagger,
+ _ => WindMethod::Wind,
+ },
+ from_right: s(p, "direction", "fromRight") != "fromLeft",
+ seed: seed(p),
+ },
+ // ---- Distort ----
+ "filter.distort.displace" => FilterParams::Displace {
+ horizontal: f(p, "horizontal", 10.0).clamp(-999.0, 999.0),
+ vertical: f(p, "vertical", 10.0).clamp(-999.0, 999.0),
+ stretch: s(p, "fit", "stretch") != "tile",
+ undefined: undefined(p, "repeat"),
+ map: None,
+ },
+ "filter.distort.shear" => FilterParams::Shear {
+ points: list::<[f32; 2]>(p, "points").unwrap_or_else(|| {
+ let a = f(p, "amount", 0.0).clamp(-100.0, 100.0) / 100.0;
+ vec![[0.0, 0.0], [0.5, a], [1.0, 0.0]]
+ }),
+ undefined: undefined(p, "wrap"),
+ },
+ "filter.distort.zigZag" => FilterParams::ZigZag {
+ amount: f(p, "amount", 10.0).clamp(-100.0, 100.0),
+ ridges: f(p, "ridges", 5.0).clamp(0.0, 20.0),
+ style: match s(p, "style", "pondRipples") {
+ "outFromCenter" => ZigZagStyle::OutFromCenter,
+ "aroundCenter" => ZigZagStyle::AroundCenter,
+ _ => ZigZagStyle::PondRipples,
+ },
+ },
+ // ---- Render ----
+ "filter.render.fibers" => FilterParams::Fibers {
+ variance: f(p, "variance", 16.0).clamp(1.0, 64.0),
+ strength: f(p, "strength", 4.0).clamp(1.0, 64.0),
+ seed: seed(p),
+ foreground: colour(p, "foreground", BLACK),
+ background: colour(p, "background", WHITE),
+ },
+ "filter.render.lensFlare" => FilterParams::LensFlare {
+ brightness: f(p, "brightness", 100.0).clamp(10.0, 300.0),
+ center_x: f(p, "centerX", 0.5).clamp(-0.5, 1.5),
+ center_y: f(p, "centerY", 0.5).clamp(-0.5, 1.5),
+ lens: match s(p, "lens", "zoom") {
+ "prime35" => LensType::Prime35,
+ "prime105" => LensType::Prime105,
+ "moviePrime" => LensType::MoviePrime,
+ _ => LensType::Zoom,
+ },
+ },
+ "filter.render.lightingEffects" => FilterParams::LightingEffects {
+ lights: list::<Light>(p, "lights").unwrap_or_else(|| {
+ vec![Light {
+ kind: match s(p, "lightType", "spot") {
+ "point" => LightKind::Point,
+ "infinite" => LightKind::Infinite,
+ _ => LightKind::Spot,
+ },
+ x: f(p, "lightX", 0.25),
+ y: f(p, "lightY", 0.2),
+ z: f(p, "lightZ", 0.6).clamp(0.0, 10.0),
+ target_x: f(p, "targetX", 0.5),
+ target_y: f(p, "targetY", 0.55),
+ angle: f(p, "angle", 135.0),
+ elevation: f(p, "elevation", 45.0).clamp(0.0, 90.0),
+ color: { let c = colour(p, "color", WHITE); [c[0], c[1], c[2]] },
+ intensity: f(p, "intensity", 75.0).clamp(-100.0, 100.0),
+ cone: f(p, "cone", 45.0).clamp(1.0, 89.0),
+ hotspot: f(p, "hotspot", 50.0).clamp(0.0, 100.0),
+ radius: f(p, "radius", 0.8).clamp(0.01, 10.0),
+ }]
+ }),
+ gloss: f(p, "gloss", 0.0).clamp(-100.0, 100.0),
+ metallic: f(p, "metallic", 0.0).clamp(-100.0, 100.0),
+ exposure: f(p, "exposure", 0.0).clamp(-100.0, 100.0),
+ ambience: f(p, "ambience", 8.0).clamp(-100.0, 100.0),
+ texture: match s(p, "texture", "none") {
+ "red" => TextureChannel::Red,
+ "green" => TextureChannel::Green,
+ "blue" => TextureChannel::Blue,
+ "alpha" => TextureChannel::Alpha,
+ "luminance" => TextureChannel::Luminance,
+ _ => TextureChannel::None,
+ },
+ height: f(p, "height", 50.0).clamp(0.0, 100.0),
+ white_is_high: b(p, "whiteIsHigh", true),
+ },
+ // ---- Noise ----
+ "filter.noise.reduceNoise" => FilterParams::ReduceNoise {
+ strength: f(p, "strength", 6.0).clamp(0.0, 10.0),
+ preserve_details: f(p, "preserveDetails", 60.0).clamp(0.0, 100.0),
+ reduce_color_noise: f(p, "reduceColorNoise", 45.0).clamp(0.0, 100.0),
+ sharpen_details: f(p, "sharpenDetails", 25.0).clamp(0.0, 100.0),
+ remove_jpeg_artifact: b(p, "removeJpegArtifact", false),
+ },
+ // ---- Blur ----
+ "filter.blur.smartBlur" => FilterParams::SmartBlur {
+ radius: f(p, "radius", 3.0).clamp(0.1, 100.0),
+ threshold: f(p, "threshold", 25.0).clamp(0.1, 100.0),
+ quality: match s(p, "quality", "high") {
+ "low" => BlurQuality::Low,
+ "medium" => BlurQuality::Medium,
+ _ => BlurQuality::High,
+ },
+ mode: match s(p, "mode", "normal") {
+ "edgeOnly" => SmartBlurMode::EdgeOnly,
+ "overlayEdge" => SmartBlurMode::OverlayEdge,
+ _ => SmartBlurMode::Normal,
+ },
+ },
+ "filter.blur.lensBlur" => FilterParams::LensBlur {
+ radius: f(p, "radius", 15.0).clamp(0.0, 100.0),
+ blades: match s(p, "shape", "hexagon") {
+ "triangle" => 3,
+ "square" => 4,
+ "pentagon" => 5,
+ "heptagon" => 7,
+ "octagon" => 8,
+ _ => 6,
+ },
+ curvature: f(p, "bladeCurvature", 0.0).clamp(0.0, 100.0),
+ rotation: f(p, "rotation", 0.0),
+ depth: match s(p, "depthMap", "none") {
+ "transparency" => DepthSource::Transparency,
+ "layerMask" => DepthSource::LayerMask,
+ _ => DepthSource::None,
+ },
+ focal_distance: f(p, "focalDistance", 0.0).clamp(0.0, 255.0),
+ invert_depth: b(p, "invert", false),
+ brightness: f(p, "brightness", 0.0).clamp(0.0, 100.0),
+ threshold: f(p, "threshold", 255.0).clamp(0.0, 255.0),
+ noise: f(p, "noise", 0.0).clamp(0.0, 100.0),
+ distribution: if s(p, "distribution", "uniform") == "gaussian" { Distribution::Gaussian } else { Distribution::Uniform },
+ monochromatic: b(p, "monochromatic", false),
+ seed: seed(p),
+ depth_map: None,
+ },
+ "filter.blur.shapeBlur" => FilterParams::ShapeBlur {
+ radius: f(p, "radius", 10.0).clamp(5.0, 1000.0),
+ shape: match s(p, "shape", "circle") {
+ "ring" => BlurShape::Ring,
+ "square" => BlurShape::Square,
+ "diamond" => BlurShape::Diamond,
+ "triangle" => BlurShape::Triangle,
+ "hexagon" => BlurShape::Hexagon,
+ "star" => BlurShape::Star,
+ "heart" => BlurShape::Heart,
+ "cross" => BlurShape::Cross,
+ _ => BlurShape::Circle,
+ },
+ },
+ // ---- Blur Gallery ----
+ "filter.blurGallery.tiltShift" => FilterParams::TiltShift {
+ blur: blur(15.0),
+ center_x: f(p, "centerX", 0.5),
+ center_y: f(p, "centerY", 0.5),
+ angle: f(p, "angle", 0.0),
+ focus: f(p, "focus", 0.1).clamp(0.0, 2.0),
+ transition: f(p, "transition", 0.15).clamp(0.001, 2.0),
+ },
+ "filter.blurGallery.irisBlur" => FilterParams::IrisBlur {
+ pins: list::<IrisPin>(p, "pins").unwrap_or_else(|| {
+ vec![IrisPin {
+ x: f(p, "centerX", 0.5),
+ y: f(p, "centerY", 0.5),
+ radius_x: f(p, "radiusX", 0.35).max(0.001),
+ radius_y: f(p, "radiusY", 0.25).max(0.001),
+ angle: f(p, "angle", 0.0),
+ roundness: f(p, "roundness", 0.0).clamp(0.0, 100.0),
+ feather: f(p, "feather", 0.5).clamp(0.0, 0.99),
+ blur: blur(15.0),
+ }]
+ }),
+ },
+ "filter.blurGallery.fieldBlur" => FilterParams::FieldBlur {
+ pins: list::<FieldPin>(p, "pins").unwrap_or_else(|| vec![FieldPin { x: f(p, "centerX", 0.5), y: f(p, "centerY", 0.5), blur: blur(15.0) }]),
+ },
+ "filter.blurGallery.spinBlur" => FilterParams::SpinBlur {
+ pins: list::<SpinPin>(p, "pins").unwrap_or_else(|| {
+ vec![SpinPin {
+ x: f(p, "centerX", 0.5),
+ y: f(p, "centerY", 0.5),
+ radius_x: f(p, "radiusX", 0.3).max(0.001),
+ radius_y: f(p, "radiusY", 0.3).max(0.001),
+ angle: f(p, "angle", 0.0),
+ blur_angle: f(p, "blurAngle", 15.0).clamp(0.0, 360.0),
+ }]
+ }),
+ },
+ "filter.blurGallery.pathBlur" => FilterParams::PathBlur {
+ paths: list::<BlurPath>(p, "paths").unwrap_or_else(|| {
+ vec![BlurPath {
+ points: vec![[f(p, "startX", 0.2), f(p, "startY", 0.5)], [f(p, "endX", 0.8), f(p, "endY", 0.5)]],
+ speed: f(p, "speed", 50.0).clamp(0.0, 500.0),
+ taper: f(p, "taper", 0.0).clamp(0.0, 100.0),
+ }]
+ }),
+ },
+ // ---- Other ----
+ "filter.other.custom" => FilterParams::Custom {
+ kernel: p
+ .get("kernel")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().take(25).map(|v| v.as_f64().unwrap_or(0.0).clamp(-999.0, 999.0) as f32).collect())
+ .unwrap_or_else(|| (0..25).map(|k| if k == 12 { 1.0 } else { 0.0 }).collect()),
+ scale: f(p, "scale", 1.0).clamp(1.0, 9999.0),
+ offset: f(p, "offset", 0.0).clamp(-9999.0, 9999.0),
+ },
+ "filter.other.hsbHsl" => {
+ let m = |k: &str, d: &str| match s(p, k, d) {
+ "hsb" => HsbModel::Hsb,
+ "hsl" => HsbModel::Hsl,
+ _ => HsbModel::Rgb,
+ };
+ FilterParams::HsbHsl { input: m("inputMode", "rgb"), output: m("rowOrder", "hsb") }
+ }
+ // ---- Video ----
+ "filter.video.deInterlace" => FilterParams::DeInterlace { eliminate_even: s(p, "eliminate", "oddFields") == "evenFields", interpolate: s(p, "createBy", "interpolation") != "duplication" },
+ "filter.video.ntscColors" => FilterParams::NtscColors,
+ _ => return None,
+ })
+}
+
+/// Ids whose rendering uses the foreground/background colours.
+fn uses_colours(id: &str) -> bool {
+ matches!(id, "filter.render.fibers" | "filter.stylize.tiles" | "filter.pixelate.pointillize")
+}
+
+/// Fills in session state a filter reads (the current colours) as explicit params, so the
+/// recorded params (journal, smart filters) reproduce the result.
+pub(crate) fn prepare(s: &Session, id: &str, p: &Value) -> Value {
+ let mut out = if p.is_object() { p.clone() } else { json!({}) };
+ if uses_colours(id)
+ && let Value::Object(m) = &mut out
+ {
+ m.entry("foreground").or_insert_with(|| json!(s.tools.foreground));
+ m.entry("background").or_insert_with(|| json!(s.tools.background));
+ }
+ out
+}
+
+/// A flattened document (or one of its layers) as an RGBA map image.
+fn map_from_document(doc: &Document, layer: Option<u64>) -> Option<algo::Image> {
+ let buf = match layer.and_then(|l| doc.layer(photocraft_doc::LayerId(l))) {
+ Some(l) => photocraft_compose::render_layer(l, l.surface().map(|s| s.content_bounds()).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds())),
+ None => photocraft_compose::flatten(doc),
+ };
+ if buf.rect.is_empty() {
+ return None;
+ }
+ Some(algo::Image { rect: buf.rect, ch: 4, data: buf.px.iter().flatten().copied().collect() })
+}
+
+/// Resolves inputs that live outside the target layer: Displace's map (`mapPath`, or
+/// `mapDocument` index with optional `mapLayer` id).
+pub(crate) fn resolve(s: &Session, fp: &mut FilterParams, p: &Value) -> Result<()> {
+ let FilterParams::Displace { map, .. } = fp else { return Ok(()) };
+ if map.is_some() {
+ return Ok(());
+ }
+ let layer = p.get("mapLayer").and_then(Value::as_u64);
+ let img = if let Some(path) = p.get("mapPath").and_then(Value::as_str).filter(|p| !p.is_empty()) {
+ let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("cannot read displacement map `{path}`: {e}")))?;
+ let imported = photocraft_io::import(path, &bytes).map_err(|e| EngineError::Other(format!("cannot open displacement map `{path}`: {e}")))?;
+ map_from_document(&imported.document, layer)
+ } else if let Some(d) = p.get("mapDocument") {
+ let docs = s.documents();
+ let found = match d {
+ Value::String(name) => docs.iter().find(|ds| ds.doc.name == *name || ds.path.as_deref() == Some(name.as_str())),
+ other => other.as_u64().and_then(|k| docs.get(k as usize)),
+ };
+ let ds = found.ok_or_else(|| EngineError::Other("displacement map document not found".into()))?;
+ map_from_document(&ds.doc, layer)
+ } else {
+ return Err(EngineError::Other("Displace needs a displacement map: pass `mapPath` or `mapDocument`".into()));
+ };
+ *map = Some(Arc::new(img.ok_or_else(|| EngineError::Other("the displacement map is empty".into()))?));
+ Ok(())
+}
+
+/// Resolves inputs read from the target layer itself: the layer mask as Lens Blur depth.
+pub(crate) fn resolve_in_layer(fp: &mut FilterParams, layer: &Layer, bounds: Rect) {
+ if let FilterParams::LensBlur { depth: DepthSource::LayerMask, depth_map, .. } = fp
+ && depth_map.is_none()
+ && let Some(m) = &layer.mask
+ {
+ *depth_map = Some(Arc::new(algo::Image::read(&m.surface, bounds)));
+ }
+}
+
+macro_rules! cmd {
+ ($id:literal, $label:literal, [$($m:literal),*], $params:literal) => {
+ CommandSpec {
+ id: $id,
+ label: $label,
+ menu: &[$($m),*],
+ shortcut: None,
+ params: $params,
+ enabled: crate::filters::has_filterable_layer,
+ run: |s, p| crate::filters::run_filter(s, $id, p),
+ journal: true,
+ }
+ };
+}
+
+/// The command specs of this batch.
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ // Pixelate
+ cmd!("filter.pixelate.colorHalftone", "Color Halftone…", ["Filter", "Pixelate"], r##"{"maxRadius":4..127=8,"channel1":-360..360=108,"channel2":-360..360=162,"channel3":-360..360=90,"channel4":-360..360=45}"##),
+ cmd!("filter.pixelate.crystallize", "Crystallize…", ["Filter", "Pixelate"], r##"{"cellSize":3..300=10,"seed":u32=0}"##),
+ cmd!("filter.pixelate.facet", "Facet", ["Filter", "Pixelate"], "{}"),
+ cmd!("filter.pixelate.fragment", "Fragment", ["Filter", "Pixelate"], "{}"),
+ cmd!("filter.pixelate.mezzotint", "Mezzotint…", ["Filter", "Pixelate"], r##"{"type":"fineDots|mediumDots|grainyDots|coarseDots|shortLines|mediumLines|longLines|shortStrokes|mediumStrokes|longStrokes","seed":u32=0}"##),
+ cmd!("filter.pixelate.pointillize", "Pointillize…", ["Filter", "Pixelate"], r##"{"cellSize":3..300=5,"seed":u32=0,"background":json}"##),
+ // Stylize
+ cmd!("filter.stylize.diffuse", "Diffuse…", ["Filter", "Stylize"], r##"{"mode":"normal|darkenOnly|lightenOnly|anisotropic","seed":u32=0}"##),
+ cmd!("filter.stylize.extrude", "Extrude…", ["Filter", "Stylize"], r##"{"type":"blocks|pyramids","size":2..255=30,"depth":1..255=30,"depthMode":"random|levelBased","solidFrontFaces":bool,"maskIncompleteBlocks":bool,"seed":u32=0}"##),
+ cmd!("filter.stylize.oilPaint", "Oil Paint…", ["Filter", "Stylize"], r##"{"stylization":0.1..10=4,"cleanliness":0..10=5,"scale":0.1..10=1,"bristleDetail":0..10=5,"lighting":bool=true,"angle":-180..180=-60,"shine":0..10=1}"##),
+ cmd!("filter.stylize.tiles", "Tiles…", ["Filter", "Stylize"], r##"{"count":1..99=10,"maxOffset":1..99=10,"fill":"background|foreground|inverse|unaltered","seed":u32=0,"foreground":json,"background":json}"##),
+ cmd!("filter.stylize.traceContour", "Trace Contour…", ["Filter", "Stylize"], r##"{"level":0..255=128,"edge":"lower|upper"}"##),
+ cmd!("filter.stylize.wind", "Wind…", ["Filter", "Stylize"], r##"{"method":"wind|blast|stagger","direction":"fromRight|fromLeft","seed":u32=0}"##),
+ // Distort
+ cmd!("filter.distort.displace", "Displace…", ["Filter", "Distort"], r##"{"horizontal":-999..999=10,"vertical":-999..999=10,"fit":"stretch|tile","undefinedAreas":"repeat|wrap","mapDocument":doc,"mapPath":text,"mapLayer":json}"##),
+ cmd!("filter.distort.shear", "Shear…", ["Filter", "Distort"], r##"{"amount":-100..100=0,"undefinedAreas":"wrap|repeat","points":json}"##),
+ cmd!("filter.distort.zigZag", "ZigZag…", ["Filter", "Distort"], r##"{"amount":-100..100=10,"ridges":0..20=5,"style":"pondRipples|outFromCenter|aroundCenter"}"##),
+ // Render
+ cmd!("filter.render.fibers", "Fibers…", ["Filter", "Render"], r##"{"variance":1..64=16,"strength":1..64=4,"seed":u32=0,"foreground":json,"background":json}"##),
+ cmd!("filter.render.lensFlare", "Lens Flare…", ["Filter", "Render"], r##"{"brightness":10..300=100,"centerX":0..1=0.5,"centerY":0..1=0.5,"lens":"zoom|prime35|prime105|moviePrime"}"##),
+ cmd!(
+ "filter.render.lightingEffects",
+ "Lighting Effects…",
+ ["Filter", "Render"],
+ r##"{"lightType":"spot|point|infinite","intensity":-100..100=75,"lightX":0..1=0.25,"lightY":0..1=0.2,"lightZ":0..2=0.6,"targetX":0..1=0.5,"targetY":0..1=0.55,"cone":1..89=45,"hotspot":0..100=50,"angle":-180..180=135,"elevation":0..90=45,"gloss":-100..100=0,"metallic":-100..100=0,"exposure":-100..100=0,"ambience":-100..100=8,"texture":"none|red|green|blue|alpha|luminance","height":0..100=50,"whiteIsHigh":bool=true,"lights":json}"##
+ ),
+ // Noise
+ cmd!("filter.noise.reduceNoise", "Reduce Noise…", ["Filter", "Noise"], r##"{"strength":0..10=6,"preserveDetails":0..100=60,"reduceColorNoise":0..100=45,"sharpenDetails":0..100=25,"removeJpegArtifact":bool}"##),
+ // Blur
+ cmd!("filter.blur.smartBlur", "Smart Blur…", ["Filter", "Blur"], r##"{"radius":0.1..100=3,"threshold":0.1..100=25,"quality":"high|medium|low","mode":"normal|edgeOnly|overlayEdge"}"##),
+ cmd!(
+ "filter.blur.lensBlur",
+ "Lens Blur…",
+ ["Filter", "Blur"],
+ r##"{"radius":0..100=15,"shape":"hexagon|triangle|square|pentagon|heptagon|octagon","bladeCurvature":0..100=0,"rotation":0..360=0,"depthMap":"none|transparency|layerMask","focalDistance":0..255=0,"invert":bool,"brightness":0..100=0,"threshold":0..255=255,"noise":0..100=0,"distribution":"uniform|gaussian","monochromatic":bool,"seed":u32=0}"##
+ ),
+ cmd!("filter.blur.shapeBlur", "Shape Blur…", ["Filter", "Blur"], r##"{"radius":5..1000=10,"shape":"circle|ring|square|diamond|triangle|hexagon|star|heart|cross"}"##),
+ // Blur Gallery
+ cmd!("filter.blurGallery.tiltShift", "Tilt-Shift…", ["Filter", "Blur Gallery"], r##"{"blur":0..500=15,"centerX":0..1=0.5,"centerY":0..1=0.5,"angle":-90..90=0,"focus":0..1=0.1,"transition":0.01..1=0.15}"##),
+ cmd!("filter.blurGallery.irisBlur", "Iris Blur…", ["Filter", "Blur Gallery"], r##"{"blur":0..500=15,"centerX":0..1=0.5,"centerY":0..1=0.5,"radiusX":0.01..1=0.35,"radiusY":0.01..1=0.25,"angle":-180..180=0,"roundness":0..100=0,"feather":0..0.99=0.5,"pins":json}"##),
+ cmd!("filter.blurGallery.fieldBlur", "Field Blur…", ["Filter", "Blur Gallery"], r##"{"blur":0..500=15,"centerX":0..1=0.5,"centerY":0..1=0.5,"pins":json}"##),
+ cmd!("filter.blurGallery.spinBlur", "Spin Blur…", ["Filter", "Blur Gallery"], r##"{"blurAngle":0..360=15,"centerX":0..1=0.5,"centerY":0..1=0.5,"radiusX":0.01..1=0.3,"radiusY":0.01..1=0.3,"angle":-180..180=0,"pins":json}"##),
+ cmd!("filter.blurGallery.pathBlur", "Path Blur…", ["Filter", "Blur Gallery"], r##"{"speed":0..500=50,"taper":0..100=0,"startX":0..1=0.2,"startY":0..1=0.5,"endX":0..1=0.8,"endY":0..1=0.5,"paths":json}"##),
+ // Other
+ cmd!("filter.other.custom", "Custom…", ["Filter", "Other"], r##"{"kernel":int[25],"scale":1..9999=1,"offset":-9999..9999=0}"##),
+ cmd!("filter.other.hsbHsl", "HSB/HSL", ["Filter", "Other"], r##"{"inputMode":"rgb|hsb|hsl","rowOrder":"hsb|hsl|rgb"}"##),
+ // Video
+ cmd!("filter.video.deInterlace", "De-Interlace…", ["Filter", "Video"], r##"{"eliminate":"oddFields|evenFields","createBy":"interpolation|duplication"}"##),
+ cmd!("filter.video.ntscColors", "NTSC Colors", ["Filter", "Video"], "{}"),
+ ]
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/filters_ext/tests.rs b/crates/engine/src/filters_ext/tests.rs
new file mode 100644
index 000000000..19c0839fd
--- /dev/null
+++ b/crates/engine/src/filters_ext/tests.rs
@@ -0,0 +1,212 @@
+use super::*;
+use photocraft_geom::Rect;
+
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 48, "height": 32})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("pattern", |doc, active| {
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ for y in 0..32 {
+ for x in 0..48 {
+ let v = ((x * 5 + y * 3) % 17) as f32 / 16.0;
+ surf.write_pixel(x, y, &[v, 1.0 - v, (x % 3) as f32 / 2.0, 1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ s
+}
+
+fn pixels(s: &Session) -> Vec<f32> {
+ let d = s.active().unwrap();
+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 48, 32))
+}
+
+const IDS: [&str; 33] = [
+ "filter.pixelate.colorHalftone",
+ "filter.pixelate.crystallize",
+ "filter.pixelate.facet",
+ "filter.pixelate.fragment",
+ "filter.pixelate.mezzotint",
+ "filter.pixelate.pointillize",
+ "filter.stylize.diffuse",
+ "filter.stylize.extrude",
+ "filter.stylize.oilPaint",
+ "filter.stylize.tiles",
+ "filter.stylize.traceContour",
+ "filter.stylize.wind",
+ "filter.distort.shear",
+ "filter.distort.zigZag",
+ "filter.render.fibers",
+ "filter.render.lensFlare",
+ "filter.render.lightingEffects",
+ "filter.noise.reduceNoise",
+ "filter.blur.smartBlur",
+ "filter.blur.lensBlur",
+ "filter.blur.shapeBlur",
+ "filter.blurGallery.tiltShift",
+ "filter.blurGallery.irisBlur",
+ "filter.blurGallery.fieldBlur",
+ "filter.blurGallery.spinBlur",
+ "filter.blurGallery.pathBlur",
+ "filter.other.custom",
+ "filter.other.hsbHsl",
+ "filter.video.deInterlace",
+ "filter.video.ntscColors",
+ "filter.stylize.wind",
+ "filter.distort.zigZag",
+ "filter.blur.smartBlur",
+];
+
+fn test_params(id: &str) -> Value {
+ match id {
+ "filter.distort.shear" => json!({"amount": 40}),
+ "filter.extrude" => json!({}),
+ "filter.stylize.extrude" => json!({"size": 6, "depth": 40}),
+ "filter.stylize.tiles" => json!({"count": 4, "maxOffset": 30}),
+ "filter.blur.shapeBlur" => json!({"radius": 5, "shape": "star"}),
+ "filter.blur.lensBlur" => json!({"radius": 4}),
+ "filter.blurGallery.tiltShift" => json!({"blur": 6}),
+ "filter.blurGallery.irisBlur" => json!({"blur": 6}),
+ "filter.blurGallery.fieldBlur" => json!({"blur": 4}),
+ "filter.blurGallery.pathBlur" => json!({"speed": 8}),
+ "filter.other.custom" => json!({"kernel": [0,0,0,0,0, 0,0,-1,0,0, 0,-1,5,-1,0, 0,0,-1,0,0, 0,0,0,0,0]}),
+ "filter.blur.smartBlur" => json!({"threshold": 60}),
+ _ => json!({}),
+ }
+}
+
+#[test]
+fn ids_match_the_menu_catalog_and_are_unique() {
+ let all = crate::command_specs();
+ for id in IDS {
+ assert!(crate::commands::find(id).is_some(), "{id} not registered");
+ assert_eq!(all.iter().filter(|c| c.id == id).count(), 1, "{id} registered twice");
+ assert!(params_for(id, &Value::Null).is_some(), "{id} has no params mapping");
+ }
+ assert!(crate::commands::find("filter.distort.displace").is_some());
+}
+
+#[test]
+fn every_new_filter_runs_changes_pixels_and_undoes_in_one_step() {
+ for id in IDS {
+ let mut s = session();
+ let before = pixels(&s);
+ let depth = s.active().unwrap().history.past_len();
+ let r = s.execute(id, test_params(id)).unwrap_or_else(|e| panic!("{id}: {e}"));
+ assert!(r.get("filter").is_some(), "{id}");
+ assert_ne!(pixels(&s), before, "{id} changed nothing");
+ assert_eq!(s.active().unwrap().history.past_len(), depth + 1, "{id} is one history step");
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(pixels(&s), before, "{id} undo");
+ }
+}
+
+#[test]
+fn new_filters_work_at_16_and_32_bit() {
+ for (depth, mode) in [(16, "rgb"), (32, "rgb"), (8, "cmyk"), (16, "lab"), (8, "gray")] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 24, "height": 16, "depth": depth, "mode": mode})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("edit.fill", json!({"color": "#3366cc"})).ok();
+ for id in IDS {
+ s.execute(id, test_params(id)).unwrap_or_else(|e| panic!("{id} at {depth}-bit {mode}: {e}"));
+ }
+ }
+}
+
+#[test]
+fn disabled_without_pixel_layer() {
+ let mut s = Session::new();
+ for id in IDS {
+ assert!(!s.is_enabled(id), "{id}");
+ }
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();
+ assert!(!s.is_enabled("filter.stylize.oilPaint"));
+}
+
+#[test]
+fn selection_limits_new_filters() {
+ let mut s = session();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 12, "height": 12})).unwrap();
+ let before = pixels(&s);
+ s.execute("filter.pixelate.crystallize", json!({"cellSize": 4})).unwrap();
+ let after = pixels(&s);
+ let far = (28 * 48 + 40) * 4;
+ assert_eq!(after[far..far + 4], before[far..far + 4]);
+ assert_ne!(after[..12 * 4], before[..12 * 4]);
+}
+
+#[test]
+fn last_filter_repeats_new_filters() {
+ let mut s = session();
+ s.execute("filter.stylize.diffuse", json!({"seed": 3})).unwrap();
+ let once = pixels(&s);
+ assert!(s.is_enabled("filter.lastFilter"));
+ s.execute("filter.lastFilter", json!({})).unwrap();
+ assert_ne!(pixels(&s), once);
+}
+
+#[test]
+fn colour_filters_use_and_record_tool_colours() {
+ let mut s = session();
+ s.tools.foreground = [1.0, 0.0, 0.0, 1.0];
+ s.tools.background = [0.0, 0.0, 1.0, 1.0];
+ let r = s.execute("filter.render.fibers", json!({"seed": 1})).unwrap();
+ assert_eq!(r["filter"]["foreground"], json!([1.0, 0.0, 0.0, 1.0]));
+ let px = pixels(&s);
+ for p in px.chunks_exact(4) {
+ assert!(p[1] < 1e-2 && (p[0] + p[2] - 1.0).abs() < 2e-2, "{p:?}");
+ }
+}
+
+#[test]
+fn displace_reads_another_document() {
+ let mut s = session();
+ // Map document: a flat colour that shifts 3 px right at 25 % (see the algo test).
+ s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32})).unwrap();
+ let v = 0.5 + 3.0 / 64.0;
+ s.edit("map", |doc, _| {
+ let bg = doc.layers[0].id;
+ doc.layer_mut(bg).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[v, 0.5, 0.5, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s.set_active(0);
+ let before = pixels(&s);
+ assert!(s.execute("filter.distort.displace", json!({})).is_err(), "needs a map");
+ s.execute("filter.distort.displace", json!({"mapDocument": 1, "horizontal": 25, "vertical": 0, "fit": "tile", "undefinedAreas": "wrap"})).unwrap();
+ let after = pixels(&s);
+ let at = |v: &[f32], x: usize, y: usize| v[(y * 48 + x) * 4];
+ for x in 5..40 {
+ assert!((at(&after, x, 10) - at(&before, x + 3, 10)).abs() < 1e-2, "x={x}");
+ }
+}
+
+#[test]
+fn lens_blur_uses_the_layer_mask_as_depth() {
+ let mut s = session();
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ let before = pixels(&s);
+ // Reveal-all mask = depth 1 everywhere; focal distance 255 puts it all in focus.
+ s.execute("filter.blur.lensBlur", json!({"radius": 6, "depthMap": "layerMask", "focalDistance": 255})).unwrap();
+ assert_eq!(pixels(&s), before);
+ s.execute("filter.blur.lensBlur", json!({"radius": 6, "depthMap": "layerMask", "focalDistance": 0})).unwrap();
+ assert_ne!(pixels(&s), before);
+}
+
+#[test]
+fn params_map_to_algorithm_units() {
+ assert_eq!(params_for("filter.pixelate.crystallize", &json!({"cellSize": 1})), Some(FilterParams::Crystallize { cell_size: 3.0, seed: 0 }));
+ assert_eq!(params_for("filter.stylize.traceContour", &json!({"level": 300, "edge": "upper"})), Some(FilterParams::TraceContour { level: 255.0, upper: true }));
+ let Some(FilterParams::IrisBlur { pins }) = params_for("filter.blurGallery.irisBlur", &json!({"pins": [{"x": 0.2, "blur": 30}, {"x": 0.8}]})) else { panic!() };
+ assert_eq!(pins.len(), 2);
+ assert_eq!(pins[0].blur, 30.0);
+ assert_eq!(pins[1].blur, IrisPin::default().blur);
+ let Some(FilterParams::Shear { points, .. }) = params_for("filter.distort.shear", &json!({"points": [[0, 0.1], [1, -0.1]]})) else { panic!() };
+ assert_eq!(points, vec![[0.0, 0.1], [1.0, -0.1]]);
+ assert!(params_for("filter.nope", &json!({})).is_none());
+}
diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs
index 4b067ef25..d0aa2bf40 100644
--- a/crates/engine/src/image_cmds.rs
+++ b/crates/engine/src/image_cmds.rs
@@ -2,7 +2,7 @@
//! bit depth) conversions, Duplicate.
use photocraft_algo::resample::{Resample, crop_surface, resize_surface, translate_surface};
-use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Document, Effect, Effects, FxPaint, Layer, LayerContent, Size};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
@@ -57,7 +57,7 @@ fn for_each_layer(layers: &mut [Layer], f: &mut dyn FnMut(&mut Layer)) {
}
}
-fn scale_effects(fx: &mut Effects, k: f32) {
+pub(crate) fn scale_effects(fx: &mut Effects, k: f32) {
for e in &mut fx.items {
match e {
Effect::DropShadow(s) | Effect::InnerShadow(s) => {
@@ -130,7 +130,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
});
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 {
+ for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
ch.surface = resize_surface(&ch.surface, sx, sy, Resample::Bilinear);
}
if let Some(sel) = &doc.selection {
@@ -154,7 +154,7 @@ fn translate_doc(doc: &mut Document, dx: i32, dy: i32) {
return;
}
for_each_surface(&mut doc.layers, true, &mut |surf, _| *surf = translate_surface(surf, dx, dy));
- for ch in &mut doc.channels {
+ for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
ch.surface = translate_surface(&ch.surface, dx, dy);
}
if let Some(sel) = &doc.selection {
@@ -297,22 +297,9 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
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 → colour model, through the CMS (see [`crate::color_cmds::convert_mode`]).
+fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value> {
+ crate::color_cmds::convert_mode(s, mode, p)
}
/// Image → Mode → 8/16/32 Bits/Channel.
@@ -325,7 +312,7 @@ fn convert_depth(s: &mut Session, depth: SampleType) -> Result<Value> {
let f = surf.format().with_sample(depth);
*surf = surf.convert(f);
});
- for ch in &mut doc.channels {
+ for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
let f = ch.surface.format().with_sample(depth);
ch.surface = ch.surface.convert(f);
}
@@ -369,10 +356,10 @@ pub fn specs() -> Vec<CommandSpec> {
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.rgb", "RGB Color", ["Image", "Mode"], r##"{"profile":"<builtin id>|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, has_doc, |s, p| convert_mode(s, ColorMode::Rgb, p)),
+ spec!("image.mode.grayscale", "Grayscale", ["Image", "Mode"], r##"{"profile":"<builtin id>|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, has_doc, |s, p| convert_mode(s, ColorMode::Grayscale, p)),
+ spec!("image.mode.cmyk", "CMYK Color", ["Image", "Mode"], r##"{"profile":"<builtin id>|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, has_doc, |s, p| convert_mode(s, ColorMode::Cmyk, p)),
+ spec!("image.mode.lab", "Lab Color", ["Image", "Mode"], r##"{"profile":"<builtin id>|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, has_doc, |s, p| convert_mode(s, ColorMode::Lab, p)),
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)),
diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs
index 0ac1096c3..ef21720cc 100644
--- a/crates/engine/src/inspect.rs
+++ b/crates/engine/src/inspect.rs
@@ -24,6 +24,7 @@ pub fn session(s: &Session) -> Value {
pub fn document(d: &DocState) -> Value {
let doc = &d.doc;
+ let selected = d.selected_layers();
json!({
"name": doc.name,
"width": doc.size.width,
@@ -32,18 +33,26 @@ pub fn document(d: &DocState) -> Value {
"depth": doc.depth.bits(),
"resolution": doc.resolution_dpi,
"activeLayer": d.active_layer.map(|l| l.0),
+ "selectedLayers": selected.iter().map(|l| l.0).collect::<Vec<_>>(),
"hasSelection": doc.selection.is_some(),
"selectionBounds": doc.selection.as_ref().map(|s| { let r = s.content_bounds(); [r.x0, r.y0, r.width() as i32, r.height() as i32] }),
- "layers": doc.layers.iter().rev().map(layer).collect::<Vec<_>>(),
+ "layers": doc.layers.iter().rev().map(|l| layer_sel(l, &selected)).collect::<Vec<_>>(),
"history": d.history.entries(),
"canUndo": d.history.can_undo(),
"canRedo": d.history.can_redo(),
"revision": d.revision,
+ "channels": crate::channel_cmds::channels_json(d),
+ "quickMask": doc.quick_mask.is_some(),
})
}
/// Layer tree top-to-bottom (display order).
pub fn layer(l: &Layer) -> Value {
+ layer_sel(l, &[])
+}
+
+/// [`layer`] with a `selected` flag on every node (Layers panel multi-selection).
+fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId]) -> Value {
let bounds = l.surface().map(|s| {
let r = s.content_bounds();
[r.x0, r.y0, r.width() as i32, r.height() as i32]
@@ -59,15 +68,31 @@ pub fn layer(l: &Layer) -> Value {
"clipped": l.clipped,
"hasMask": l.mask.is_some(),
"bounds": bounds,
+ "selected": selected.contains(&l.id),
+ "linkGroup": l.link_group,
});
match &l.content {
LayerContent::Group(g) => {
- v["children"] = Value::Array(g.children.iter().rev().map(layer).collect());
+ v["children"] = Value::Array(g.children.iter().rev().map(|c| layer_sel(c, selected)).collect());
}
LayerContent::Adjustment(a) => {
v["adjustment"] = serde_json::to_value(a).unwrap_or(Value::Null);
}
+ LayerContent::Smart(sm) => {
+ v["smartFilters"] = Value::Array(sm.smart_filters.iter().map(|f| json!({"command": f.command, "params": f.params, "visible": f.visible, "opacity": f.opacity, "blend": f.blend.label()})).collect());
+ v["smartFiltersEnabled"] = json!(sm.filters_enabled);
+ }
+ LayerContent::Text(t) => {
+ v["text"] = json!({"text": t.text, "font": t.font_family, "sizePt": t.size_pt});
+ }
_ => {}
}
+ // Layer styles, so agents can verify what they applied (full settings via the style commands).
+ if !l.effects.items.is_empty() {
+ v["effects"] = json!({
+ "enabled": l.effects.enabled,
+ "items": l.effects.items.iter().map(|e| json!({"kind": e.label(), "enabled": e.enabled()})).collect::<Vec<_>>(),
+ });
+ }
v
}
diff --git a/crates/engine/src/layer_menu_cmds.rs b/crates/engine/src/layer_menu_cmds.rs
new file mode 100644
index 000000000..1c29fe8ea
--- /dev/null
+++ b/crates/engine/src/layer_menu_cmds.rs
@@ -0,0 +1,954 @@
+//! Layer menu remnants: Layer Mask › Apply / From Transparency / Hide Selection, Mask All
+//! Objects, Matting, Smart Objects › Stack Mode and Reveal in Finder, Layer Style › Blending
+//! Options / Global Light / Create Layer / Scale Effects, Layer Content Options, and exporting
+//! just the active layer (Quick Export as PNG, Export As).
+
+use photocraft_algo::selection::Region;
+use photocraft_color::BlendMode;
+use photocraft_doc::{
+ Document, Effect, Layer, LayerContent, LayerId, LayerMask, SmartSource, StackMode,
+};
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, from_rgba_into, to_rgba};
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, layer_param};
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams {
+ cmd: cmd.into(),
+ msg: msg.into(),
+ }
+}
+
+fn other(msg: impl Into<String>) -> EngineError {
+ EngineError::Other(msg.into())
+}
+
+fn num(p: &Value, key: &str, default: f32) -> f32 {
+ p.get(key)
+ .and_then(Value::as_f64)
+ .map_or(default, |v| v as f32)
+}
+
+type Enabled = std::result::Result<(), String>;
+
+fn active_layer(s: &Session) -> std::result::Result<&Layer, String> {
+ let d = s.active().ok_or("no document open")?;
+ d.active_layer
+ .and_then(|id| d.doc.layer(id))
+ .ok_or_else(|| "no active layer".into())
+}
+
+fn has_layer(s: &Session) -> Enabled {
+ active_layer(s).map(|_| ())
+}
+
+fn has_raster(s: &Session) -> Enabled {
+ let l = active_layer(s)?;
+ if matches!(l.content, LayerContent::Raster(_)) {
+ Ok(())
+ } else {
+ Err(format!(
+ "active layer is a {} layer, not a pixel layer",
+ l.content.kind_name()
+ ))
+ }
+}
+
+fn has_raster_with_mask(s: &Session) -> Enabled {
+ has_raster(s)?;
+ if active_layer(s)?.mask.is_some() {
+ Ok(())
+ } else {
+ Err("the layer has no layer mask".into())
+ }
+}
+
+fn has_selection_layer(s: &Session) -> Enabled {
+ has_layer(s)?;
+ if s.active().is_some_and(|d| d.doc.selection.is_some()) {
+ Ok(())
+ } else {
+ Err("no selection".into())
+ }
+}
+
+fn has_doc(s: &Session) -> Enabled {
+ s.active()
+ .map(|_| ())
+ .ok_or_else(|| "no document open".into())
+}
+
+fn has_smart(s: &Session) -> Enabled {
+ if matches!(active_layer(s)?.content, LayerContent::Smart(_)) {
+ Ok(())
+ } else {
+ Err("the active layer is not a smart object".into())
+ }
+}
+
+fn has_linked_smart(s: &Session) -> Enabled {
+ match &active_layer(s)?.content {
+ LayerContent::Smart(sm) if matches!(sm.source, SmartSource::Linked { .. }) => Ok(()),
+ _ => Err("the active layer is not a linked smart object".into()),
+ }
+}
+
+fn has_effects(s: &Session) -> Enabled {
+ let l = active_layer(s)?;
+ if l.effects.items.iter().any(Effect::enabled) {
+ Ok(())
+ } else {
+ Err("the layer has no layer effects".into())
+ }
+}
+
+fn has_content_options(s: &Session) -> Enabled {
+ let l = active_layer(s)?;
+ match l.content {
+ LayerContent::Adjustment(_)
+ | LayerContent::Fill(_)
+ | LayerContent::Text(_)
+ | LayerContent::Smart(_)
+ | LayerContent::Shape(_) => Ok(()),
+ _ => Err(format!(
+ "{} layers have no content options",
+ l.content.kind_name()
+ )),
+ }
+}
+
+// ---------- RGBA helpers ----------
+
+/// Straight RGBA of `surf` over `r` (row-major).
+fn read_rgba(surf: &Surface, r: Rect) -> Vec<[f32; 4]> {
+ let fmt = surf.format();
+ let n = fmt.channels();
+ surf.read_region(r)
+ .chunks_exact(n)
+ .map(|q| to_rgba(&fmt, q))
+ .collect()
+}
+
+fn write_rgba(surf: &mut Surface, r: Rect, px: &[[f32; 4]]) {
+ let fmt = surf.format();
+ let mut out = Vec::with_capacity(px.len() * fmt.channels());
+ let mut enc = [0.0f32; 8];
+ for q in px {
+ let m = from_rgba_into(&fmt, *q, &mut enc);
+ out.extend_from_slice(&enc[..m]);
+ }
+ surf.write_region(r, &out);
+}
+
+/// One history step editing the active raster layer's RGBA (content bounds grown by `grow`).
+fn edit_rgba(
+ s: &mut Session,
+ label: &str,
+ grow: i32,
+ f: impl FnOnce(&mut Vec<[f32; 4]>, Rect),
+) -> Result<Value> {
+ let id = layer_param(s, &Value::Null)?;
+ s.edit(label, |doc, _| {
+ let bounds = doc.bounds();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let surf = crate::commands::paint_surface(l, &Value::Null)?;
+ let r = surf
+ .content_bounds()
+ .inflate(grow)
+ .intersect(&bounds.inflate(grow));
+ if r.is_empty() {
+ return Ok(Value::Null);
+ }
+ let mut px = read_rgba(surf, r);
+ f(&mut px, r);
+ write_rgba(surf, r, &px);
+ surf.prune();
+ Ok(Value::Null)
+ })
+}
+
+// ---------- layer masks ----------
+
+/// Layer › Layer Mask › Apply: multiply the pixels' alpha by the mask, then delete the mask.
+fn apply_mask(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ s.edit("Apply Layer Mask", |doc, _| {
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let mask = l
+ .mask
+ .take()
+ .ok_or_else(|| other("the layer has no layer mask"))?;
+ let surf = crate::commands::paint_surface(l, &Value::Null)?;
+ let r = surf.content_bounds();
+ if !r.is_empty() {
+ let mut px = read_rgba(surf, r);
+ let mut m = Vec::new();
+ mask.values_into(r, &mut m);
+ for (q, k) in px.iter_mut().zip(&m) {
+ q[3] *= k;
+ }
+ write_rgba(surf, r, &px);
+ surf.prune();
+ }
+ Ok(Value::Null)
+ })
+}
+
+/// Layer › Layer Mask › From Transparency: the alpha becomes a layer mask and the pixels opaque.
+fn mask_from_transparency(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ s.edit("From Transparency", |doc, _| {
+ let bounds = doc.bounds();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let surf = crate::commands::paint_surface(l, &Value::Null)?;
+ let r = surf.content_bounds().intersect(&bounds);
+ let mut mask = LayerMask::hide_all();
+ if !r.is_empty() {
+ let mut px = read_rgba(surf, r);
+ let alpha: Vec<f32> = px.iter().map(|q| q[3]).collect();
+ mask.surface.write_region(r, &alpha);
+ mask.surface.prune();
+ for q in &mut px {
+ q[3] = 1.0;
+ }
+ write_rgba(surf, r, &px);
+ }
+ l.mask = Some(mask);
+ Ok(Value::Null)
+ })
+}
+
+/// Layer › Layer Mask › Hide Selection: a mask that hides the selected area.
+fn hide_selection(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ s.edit("Add Layer Mask", |doc, _| {
+ let sel = doc.selection.clone().ok_or_else(|| other("no selection"))?;
+ let bounds = doc.bounds();
+ let mut v = sel.read_region(bounds);
+ for x in &mut v {
+ *x = 1.0 - *x;
+ }
+ let mut mask = LayerMask::reveal_all();
+ mask.surface.write_region(bounds, &v);
+ mask.surface.prune();
+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(mask);
+ doc.selection = None;
+ Ok(Value::Null)
+ })
+}
+
+/// Layer › Mask All Objects: detects the main objects (the Select › Subject segmentation over the
+/// layer, or the composite for non-pixel layers) and masks the layer to them. Photoshop makes one
+/// group per object; here the objects share one mask.
+fn mask_all_objects(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = d.doc.clone();
+ let layer = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let region: Option<Region> = match layer.surface() {
+ Some(surf) if matches!(layer.content, LayerContent::Raster(_)) => {
+ photocraft_algo::segment::subject::select_subject(
+ &photocraft_algo::segment::SurfaceSampler(surf),
+ doc.bounds(),
+ )
+ }
+ _ => {
+ struct Composite<'a>(&'a Document);
+ impl photocraft_algo::segment::Sampler for Composite<'_> {
+ fn rgba(&self, r: Rect) -> Vec<[f32; 4]> {
+ photocraft_compose::render(self.0, r).px
+ }
+ }
+ photocraft_algo::segment::subject::select_subject(&Composite(&doc), doc.bounds())
+ }
+ };
+ let region = region.ok_or_else(|| other("no objects were found"))?;
+ let bbox = region.bbox;
+ s.edit("Mask All Objects", |doc, _| {
+ let mut mask = LayerMask::hide_all();
+ let v: Vec<f32> = region.mask.iter().map(|m| f32::from(*m) / 255.0).collect();
+ mask.surface.write_region(bbox, &v);
+ mask.surface.prune();
+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(mask);
+ Ok(())
+ })?;
+ Ok(json!({"bounds": [bbox.x0, bbox.y0, bbox.width(), bbox.height()]}))
+}
+
+// ---------- matting ----------
+
+/// Layer › Matting › Defringe: edge pixels (within `width` of transparency) take the colour of
+/// the nearest pixels further inside, grown outward one pixel at a time. Alpha is unchanged.
+pub fn defringe(px: &mut [[f32; 4]], w: usize, h: usize, width: usize) {
+ let outside: Vec<bool> = px.iter().map(|q| q[3] <= 0.01).collect();
+ if !outside.iter().any(|o| *o) {
+ return;
+ }
+ let dist = photocraft_algo::selection::edt(&outside, w, h);
+ let mut known: Vec<bool> = (0..px.len())
+ .map(|i| !outside[i] && dist[i] > width as f32)
+ .collect();
+ let mut todo: Vec<usize> = (0..px.len())
+ .filter(|&i| !outside[i] && !known[i])
+ .collect();
+ while !todo.is_empty() {
+ let mut next = Vec::new();
+ let mut updates = Vec::new();
+ for &i in &todo {
+ let (x, y) = ((i % w) as i32, (i / w) as i32);
+ let mut acc = [0.0f32; 3];
+ let mut n = 0.0;
+ for (dx, dy) in [
+ (-1, 0),
+ (1, 0),
+ (0, -1),
+ (0, 1),
+ (-1, -1),
+ (1, -1),
+ (-1, 1),
+ (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 known[j] {
+ for c in 0..3 {
+ acc[c] += px[j][c];
+ }
+ n += 1.0;
+ }
+ }
+ if n > 0.0 {
+ updates.push((i, acc.map(|v| v / n)));
+ } else {
+ next.push(i);
+ }
+ }
+ if updates.is_empty() {
+ break; // isolated fringe with no core colour nearby
+ }
+ for (i, c) in updates {
+ px[i][..3].copy_from_slice(&c);
+ known[i] = true;
+ }
+ todo = next;
+ }
+}
+
+fn matting_defringe(s: &mut Session, p: &Value) -> Result<Value> {
+ let width = num(p, "width", 1.0).clamp(1.0, 200.0).round() as usize;
+ edit_rgba(s, "Defringe", 1, |px, r| {
+ defringe(px, r.width() as usize, r.height() as usize, width)
+ })
+}
+
+/// Remove Black / White Matte: un-premultiply colours that were composited over black or white.
+fn remove_matte(s: &mut Session, white: bool) -> Result<Value> {
+ edit_rgba(
+ s,
+ if white {
+ "Remove White Matte"
+ } else {
+ "Remove Black Matte"
+ },
+ 0,
+ |px, _| {
+ for q in px.iter_mut().filter(|q| q[3] > 0.0 && q[3] < 1.0) {
+ let a = q[3];
+ for v in &mut q[..3] {
+ *v = if white { (*v - (1.0 - a)) / a } else { *v / a }.clamp(0.0, 1.0);
+ }
+ }
+ },
+ )
+}
+
+/// Layer › Matting › Color Decontaminate: fringe colours move toward nearby opaque colours
+/// (the Select and Mask decontamination, driven by the layer's own alpha).
+fn color_decontaminate(s: &mut Session, p: &Value) -> Result<Value> {
+ let amount = num(p, "amount", 100.0).clamp(0.0, 100.0);
+ let radius = num(p, "radius", 4.0).clamp(1.0, 100.0);
+ let id = layer_param(s, &Value::Null)?;
+ s.edit("Color Decontaminate", |doc, _| {
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let surf = crate::commands::paint_surface(l, &Value::Null)?;
+ let r = surf.content_bounds();
+ if r.is_empty() || !surf.format().alpha {
+ return Ok(());
+ }
+ let alpha: Vec<u8> = read_rgba(surf, r)
+ .iter()
+ .map(|q| (q[3].clamp(0.0, 1.0) * 255.0).round() as u8)
+ .collect();
+ let region = Region {
+ bbox: r,
+ mask: alpha,
+ };
+ *surf = photocraft_algo::matting::decontaminate(surf, &region, radius, amount);
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+// ---------- smart object stack modes ----------
+
+fn stack_mode(s: &mut Session, p: &Value, mode: Option<StackMode>) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ let label = mode.map_or("None", StackMode::label);
+ s.edit(&format!("Stack Mode: {label}"), |doc, _| {
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let LayerContent::Smart(sm) = &mut l.content else {
+ return Err(other("the active layer is not a smart object"));
+ };
+ sm.stack_mode = mode;
+ crate::smart_cmds::refresh(doc, id)?;
+ Ok(())
+ })?;
+ Ok(json!({"stackMode": mode.map(StackMode::id)}))
+}
+
+macro_rules! stack_spec {
+ ($id:literal, $label:literal, $mode:expr) => {
+ CommandSpec {
+ id: concat!("layer.smartObjects.stackMode.", $id),
+ label: $label,
+ menu: &["Layer", "Smart Objects", "Stack Mode"],
+ shortcut: None,
+ params: r##"{"layer":id?}"##,
+ enabled: has_smart,
+ run: |s, p| stack_mode(s, p, $mode),
+ journal: true,
+ }
+ };
+}
+
+/// Native-only: show a linked smart object's file in the platform file manager.
+fn reveal_in_finder(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let l = d
+ .active_layer
+ .and_then(|id| d.doc.layer(id))
+ .ok_or_else(|| other("no active layer"))?;
+ let LayerContent::Smart(sm) = &l.content else {
+ return Err(other("the active layer is not a smart object"));
+ };
+ let SmartSource::Linked { path } = &sm.source else {
+ return Err(other("embedded smart objects have no file to reveal"));
+ };
+ let (program, args) = reveal_command(path);
+ if p.get("dryRun").and_then(Value::as_bool).unwrap_or(false) {
+ return Ok(json!({"program": program, "args": args}));
+ }
+ spawn(program, &args)?;
+ Ok(json!({"path": path}))
+}
+
+/// The file-manager invocation that selects `path` on this platform.
+pub fn reveal_command(path: &str) -> (&'static str, Vec<String>) {
+ if cfg!(target_os = "macos") {
+ ("open", vec!["-R".into(), path.into()])
+ } else if cfg!(target_os = "windows") {
+ ("explorer", vec![format!("/select,{path}")])
+ } else {
+ let parent = std::path::Path::new(path)
+ .parent()
+ .map_or_else(|| ".".to_string(), |p| p.to_string_lossy().into_owned());
+ ("xdg-open", vec![parent])
+ }
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn spawn(program: &str, args: &[String]) -> Result<()> {
+ std::process::Command::new(program)
+ .args(args)
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| other(format!("{program}: {e}")))
+}
+
+#[cfg(target_arch = "wasm32")]
+fn spawn(_: &str, _: &[String]) -> Result<()> {
+ Err(other("Reveal in Finder needs the desktop app"))
+}
+
+fn native(_: &Session) -> Enabled {
+ if cfg!(target_arch = "wasm32") {
+ Err("not available in the browser".into())
+ } else {
+ Ok(())
+ }
+}
+
+// ---------- layer style ----------
+
+fn blending_options(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "layer.layerStyle.blendingOptions";
+ let id = layer_param(s, p)?;
+ let blend = match p.get("blend").and_then(Value::as_str) {
+ Some(b) => Some(
+ crate::commands::blend_from_str(b)
+ .ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?,
+ ),
+ None => None,
+ };
+ let opacity = p
+ .get("opacity")
+ .and_then(Value::as_f64)
+ .map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
+ let fill = p
+ .get("fillOpacity")
+ .and_then(Value::as_f64)
+ .map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
+ s.edit("Blending Options", |doc, _| {
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ if let Some(b) = blend {
+ if b == BlendMode::PassThrough && !l.is_group() {
+ return Err(bad(CMD, "Pass Through is for groups"));
+ }
+ l.blend = b;
+ }
+ if let Some(o) = opacity {
+ l.opacity = o;
+ }
+ if let Some(f) = fill {
+ l.fill_opacity = f;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn global_light(s: &mut Session, p: &Value) -> Result<Value> {
+ let cur = s.active().ok_or(EngineError::NoDocument)?.doc.global_light;
+ let angle = num(p, "angle", cur.angle);
+ let altitude = num(p, "altitude", cur.altitude).clamp(0.0, 90.0);
+ let angle = (angle + 180.0).rem_euclid(360.0) - 180.0;
+ s.edit("Global Light", |doc, _| {
+ doc.global_light.angle = angle;
+ doc.global_light.altitude = altitude;
+ Ok(())
+ })?;
+ Ok(json!({"angle": angle, "altitude": altitude}))
+}
+
+fn scale_effects(s: &mut Session, p: &Value) -> Result<Value> {
+ let k = num(p, "scale", 100.0).clamp(1.0, 1000.0) / 100.0;
+ let id = layer_param(s, p)?;
+ s.edit("Scale Effects", |doc, _| {
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ crate::image_cmds::scale_effects(&mut l.effects, k);
+ l.effects.psd_raw = None;
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+/// Effects drawn beneath the layer (they become separate layers below it, unclipped).
+fn is_below(e: &Effect) -> bool {
+ match e {
+ Effect::DropShadow(_) | Effect::OuterGlow(_) => true,
+ Effect::Stroke(st) => st.position == photocraft_doc::StrokePosition::Outside,
+ Effect::BevelEmboss(b) => matches!(
+ b.style,
+ photocraft_doc::BevelStyle::OuterBevel
+ | photocraft_doc::BevelStyle::Emboss
+ | photocraft_doc::BevelStyle::PillowEmboss
+ ),
+ _ => false,
+ }
+}
+
+fn effect_common_mut(e: &mut Effect) -> Option<&mut photocraft_doc::FxCommon> {
+ match e {
+ Effect::DropShadow(s) | Effect::InnerShadow(s) => Some(&mut s.common),
+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => Some(&mut g.common),
+ Effect::Stroke(s) => Some(&mut s.common),
+ Effect::ColorOverlay { common, .. }
+ | Effect::GradientOverlay { common, .. }
+ | Effect::PatternOverlay { common, .. } => Some(common),
+ Effect::Satin(s) => Some(&mut s.common),
+ Effect::BevelEmboss(_) => None,
+ }
+}
+
+/// Layer › Layer Style › Create Layer: each enabled effect is rendered on its own (normal blend,
+/// full opacity) into a pixel layer named like Photoshop's ("<layer>'s Drop Shadow"), carrying the
+/// effect's blend mode and opacity. Shadows/glows/outer strokes go below the layer; inner effects
+/// and overlays go above it, clipped to it. The layer keeps its pixels and loses its effects.
+fn create_layer(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ let made = s.edit("Create Layers", |doc, active| {
+ let canvas = doc.bounds();
+ let fmt = doc.pixel_format();
+ let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone();
+ let effects: Vec<Effect> = l
+ .effects
+ .items
+ .iter()
+ .filter(|e| e.enabled())
+ .cloned()
+ .collect();
+ if effects.is_empty() || !l.effects.enabled {
+ return Err(other("the layer has no layer effects"));
+ }
+ let area = l
+ .surface()
+ .map_or(canvas, |s| s.content_bounds().union(&canvas))
+ .inflate(256);
+ let light = doc.global_light;
+ let mut below = Vec::new();
+ let mut above = Vec::new();
+ for e in effects {
+ let mut alone = l.clone();
+ alone.visible = true;
+ alone.opacity = 1.0;
+ alone.blend = BlendMode::Normal;
+ alone.clipped = false;
+ alone.mask = None;
+ // Fill opacity 0 hides the layer's own pixels; effects still draw.
+ alone.fill_opacity = 0.0;
+ let mut e1 = e.clone();
+ let (blend, opacity) = match effect_common_mut(&mut e1) {
+ Some(c) => {
+ let r = (c.blend, c.opacity);
+ c.blend = BlendMode::Normal;
+ c.opacity = 1.0;
+ r
+ }
+ None => (BlendMode::Normal, 1.0),
+ };
+ alone.effects.items = vec![e1];
+ alone.effects.psd_raw = None;
+ let mut tmp = Document::new("fx", doc.size, doc.mode, doc.depth);
+ tmp.global_light = light;
+ tmp.patterns = doc.patterns.clone();
+ tmp.layers = vec![alone];
+ let buf = photocraft_compose::render(&tmp, area);
+ let mut surf = Surface::new(fmt);
+ let data: Vec<f32> = buf
+ .px
+ .iter()
+ .flat_map(|q| photocraft_raster::from_rgba(&fmt, *q))
+ .collect();
+ surf.write_region(area, &data);
+ surf.prune();
+ let mut nl = Layer::new(
+ format!("{}'s {}", l.name, e.label()),
+ LayerContent::Raster(surf),
+ );
+ nl.blend = blend;
+ nl.opacity = opacity;
+ if is_below(&e) {
+ below.push(nl);
+ } else {
+ nl.clipped = true;
+ above.push(nl);
+ }
+ }
+ let n = below.len() + above.len();
+ // Insert in order: below layers under the source, clipped layers above it.
+ let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?;
+ let (&at, parent) = path.split_last().expect("non-empty path");
+ let sib = if parent.is_empty() {
+ &mut doc.layers
+ } else {
+ doc.layer_at_mut(parent)
+ .and_then(|t| t.children_mut())
+ .ok_or_else(|| other("bad layer path"))?
+ };
+ let src = &mut sib[at];
+ src.effects.items.clear();
+ src.effects.psd_raw = None;
+ for (k, nl) in above.into_iter().enumerate() {
+ sib.insert(at + 1 + k, nl);
+ }
+ for nl in below.into_iter().rev() {
+ sib.insert(at, nl);
+ }
+ *active = Some(id);
+ Ok(n)
+ })?;
+ Ok(json!({"layers": made}))
+}
+
+/// Layer › Layer Content Options…: which editor the active layer opens (UIs show it).
+fn content_options(s: &mut Session, _: &Value) -> Result<Value> {
+ let l = active_layer(s).map_err(other)?;
+ let editor = match &l.content {
+ LayerContent::Adjustment(a) => {
+ format!("adjustment:{}", crate::commands::adjustment_kind(a))
+ }
+ LayerContent::Fill(_) => "fill".into(),
+ LayerContent::Text(_) => "text".into(),
+ LayerContent::Smart(_) => "smartObject".into(),
+ LayerContent::Shape(_) => "shape".into(),
+ other => {
+ return Err(EngineError::Other(format!(
+ "{} layers have no content options",
+ other.kind_name()
+ )));
+ }
+ };
+ Ok(json!({"layer": l.id.0, "editor": editor}))
+}
+
+// ---------- export just the active layer ----------
+
+/// The layer rendered alone (visible, its blend mode ignored) and trimmed to its pixels, as a
+/// one-layer document — what Export As does for a layer.
+pub fn layer_document(doc: &Document, id: LayerId) -> Result<Document> {
+ let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let mut alone = l.clone();
+ alone.visible = true;
+ alone.blend = if alone.is_group() {
+ BlendMode::PassThrough
+ } else {
+ BlendMode::Normal
+ };
+ alone.clipped = false;
+ let mut tmp = doc.clone();
+ tmp.layers = vec![alone];
+ tmp.selection = None;
+ let area = doc.bounds();
+ let buf = photocraft_compose::render(&tmp, area);
+ let w = area.width() as usize;
+ let mut b = Rect::EMPTY;
+ for (i, q) in buf.px.iter().enumerate() {
+ if q[3] > 0.0 {
+ let (x, y) = (area.x0 + (i % w) as i32, area.y0 + (i / w) as i32);
+ b = b.union(&Rect::new(x, y, x + 1, y + 1));
+ }
+ }
+ if b.is_empty() {
+ return Err(other("the layer is empty"));
+ }
+ let fmt = doc.pixel_format();
+ let mut out = Document::new(
+ l.name.clone(),
+ photocraft_doc::Size::new(b.width(), b.height()),
+ doc.mode,
+ doc.depth,
+ );
+ out.resolution_dpi = doc.resolution_dpi;
+ out.icc_profile = doc.icc_profile.clone();
+ let mut surf = Surface::new(fmt);
+ let rows: Vec<f32> = (b.y0..b.y1)
+ .flat_map(|y| {
+ let row = (y - area.y0) as usize * w;
+ let px = &buf.px;
+ (b.x0..b.x1).flat_map(move |x| {
+ photocraft_raster::from_rgba(&fmt, px[row + (x - area.x0) as usize])
+ })
+ })
+ .collect();
+ surf.write_region(Rect::from_xywh(0, 0, b.width(), b.height()), &rows);
+ out.layers
+ .push(Layer::new(l.name.clone(), LayerContent::Raster(surf)));
+ Ok(out)
+}
+
+fn export_layer(s: &mut Session, p: &Value, cmd: &str, png_only: bool) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let mut ldoc = layer_document(&d.doc, id)?;
+ let path = p
+ .get("path")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ .ok_or_else(|| bad(cmd, "missing `path` (UIs ask for one)"))?;
+ let lower = path.to_ascii_lowercase();
+ if png_only && !lower.ends_with(".png") {
+ return Err(bad(cmd, "Quick Export as PNG writes .png files"));
+ }
+ let scale = num(p, "scale", 100.0).clamp(1.0, 1000.0);
+ if (scale - 100.0).abs() > 1e-3 {
+ let mut tmp = Session::new();
+ tmp.add_document(ldoc, None);
+ let w = (tmp.active().map_or(1, |d| d.doc.size.width) as f32 * scale / 100.0)
+ .round()
+ .max(1.0);
+ tmp.execute("image.imageSize", json!({"width": w}))?;
+ ldoc = (*tmp.active().ok_or(EngineError::NoDocument)?.doc).clone();
+ }
+ let out = photocraft_io::export(&ldoc, path, &Default::default())
+ .map_err(|e| other(e.to_string()))?;
+ write_file(path, &out.bytes)?;
+ Ok(
+ json!({"path": path, "bytes": out.bytes.len(), "width": ldoc.size.width, "height": ldoc.size.height, "warnings": out.warnings}),
+ )
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
+ std::fs::write(path, bytes).map_err(|e| other(format!("{path}: {e}")))
+}
+
+#[cfg(target_arch = "wasm32")]
+fn write_file(_: &str, _: &[u8]) -> Result<()> {
+ Err(other("writing files needs the desktop app"))
+}
+
+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 }
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!(
+ "layer.layerMask.apply",
+ "Apply",
+ ["Layer", "Layer Mask"],
+ r##"{"layer":id?}"##,
+ has_raster_with_mask,
+ apply_mask
+ ),
+ spec!(
+ "layer.layerMask.fromTransparency",
+ "From Transparency",
+ ["Layer", "Layer Mask"],
+ r##"{"layer":id?}"##,
+ has_raster,
+ mask_from_transparency
+ ),
+ spec!(
+ "layer.layerMask.hideSelection",
+ "Hide Selection",
+ ["Layer", "Layer Mask"],
+ r##"{"layer":id?}"##,
+ has_selection_layer,
+ hide_selection
+ ),
+ spec!(
+ "layer.maskAllObjects",
+ "Mask All Objects",
+ ["Layer"],
+ r##"{"layer":id?}"##,
+ has_layer,
+ mask_all_objects
+ ),
+ spec!(
+ "layer.matting.defringe",
+ "Defringe…",
+ ["Layer", "Matting"],
+ r##"{"width":1..200=1}"##,
+ has_raster,
+ matting_defringe
+ ),
+ spec!(
+ "layer.matting.removeBlackMatte",
+ "Remove Black Matte",
+ ["Layer", "Matting"],
+ "{}",
+ has_raster,
+ |s, _| remove_matte(s, false)
+ ),
+ spec!(
+ "layer.matting.removeWhiteMatte",
+ "Remove White Matte",
+ ["Layer", "Matting"],
+ "{}",
+ has_raster,
+ |s, _| remove_matte(s, true)
+ ),
+ spec!(
+ "layer.matting.colorDecontaminate",
+ "Color Decontaminate…",
+ ["Layer", "Matting"],
+ r##"{"amount":0..100=100,"radius":1..100=4}"##,
+ has_raster,
+ color_decontaminate
+ ),
+ stack_spec!("entropy", "Entropy", Some(StackMode::Entropy)),
+ stack_spec!("kurtosis", "Kurtosis", Some(StackMode::Kurtosis)),
+ stack_spec!("maximum", "Maximum", Some(StackMode::Maximum)),
+ stack_spec!("mean", "Mean", Some(StackMode::Mean)),
+ stack_spec!("median", "Median", Some(StackMode::Median)),
+ stack_spec!("minimum", "Minimum", Some(StackMode::Minimum)),
+ stack_spec!("range", "Range", Some(StackMode::Range)),
+ stack_spec!("skewness", "Skewness", Some(StackMode::Skewness)),
+ stack_spec!(
+ "standardDeviation",
+ "Standard Deviation",
+ Some(StackMode::StandardDeviation)
+ ),
+ stack_spec!("summation", "Summation", Some(StackMode::Summation)),
+ stack_spec!("variance", "Variance", Some(StackMode::Variance)),
+ stack_spec!("none", "None", None),
+ spec!(
+ "layer.smartObjects.revealInFinder",
+ "Reveal in Finder",
+ ["Layer", "Smart Objects"],
+ r##"{"dryRun":bool=false}"##,
+ |s| native(s).and_then(|_| has_linked_smart(s)),
+ reveal_in_finder
+ ),
+ spec!(
+ "layer.layerStyle.blendingOptions",
+ "Blending Options…",
+ ["Layer", "Layer Style"],
+ r##"{"layer":id?,"blend":"normal|multiply|…"?,"opacity":0..100?,"fillOpacity":0..100?}"##,
+ has_layer,
+ blending_options
+ ),
+ spec!(
+ "layer.layerStyle.globalLight",
+ "Global Light…",
+ ["Layer", "Layer Style"],
+ r##"{"angle":-180..180=120,"altitude":0..90=30}"##,
+ has_doc,
+ global_light
+ ),
+ spec!(
+ "layer.layerStyle.createLayer",
+ "Create Layer",
+ ["Layer", "Layer Style"],
+ r##"{"layer":id?}"##,
+ has_effects,
+ create_layer
+ ),
+ spec!(
+ "layer.layerStyle.scaleEffects",
+ "Scale Effects…",
+ ["Layer", "Layer Style"],
+ r##"{"scale":1..1000=100}"##,
+ has_effects,
+ scale_effects
+ ),
+ CommandSpec {
+ id: "layer.layerContentOptions",
+ label: "Layer Content Options…",
+ menu: &["Layer"],
+ shortcut: None,
+ params: "{}",
+ enabled: has_content_options,
+ run: content_options,
+ journal: false,
+ },
+ spec!(
+ "layer.quickExportAsPng",
+ "Quick Export as PNG",
+ ["Layer"],
+ r##"{"layer":id?,"path":text}"##,
+ has_layer,
+ |s, p| export_layer(s, p, "layer.quickExportAsPng", true)
+ ),
+ spec!(
+ "layer.exportAs",
+ "Export As…",
+ ["Layer"],
+ r##"{"layer":id?,"path":text,"scale":1..1000=100} (format from the path's extension)"##,
+ has_layer,
+ |s, p| export_layer(s, p, "layer.exportAs", false)
+ ),
+ ]
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/layer_menu_cmds/tests.rs b/crates/engine/src/layer_menu_cmds/tests.rs
new file mode 100644
index 000000000..bd828eb36
--- /dev/null
+++ b/crates/engine/src/layer_menu_cmds/tests.rs
@@ -0,0 +1,511 @@
+use super::*;
+
+const DEPTHS: [u64; 3] = [8, 16, 32];
+
+fn session(depth: u64, mode: &str) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "mode": mode, "background": "transparent"})).unwrap();
+ s
+}
+
+fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+}
+
+fn active(s: &Session) -> &Layer {
+ let d = s.active().unwrap();
+ d.doc.layer(d.active_layer.unwrap()).unwrap()
+}
+
+fn paint(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);
+ surf.prune();
+ Ok(())
+ })
+ .unwrap();
+}
+
+/// A red disc with a soft, dark-contaminated edge on transparency.
+fn disc(x: i32, y: i32) -> [f32; 4] {
+ let d = (((x - 20) * (x - 20) + (y - 15) * (y - 15)) as f32).sqrt();
+ let a = (10.0 - d).clamp(0.0, 1.0);
+ // Edge pixels were matted on black: colour scaled by alpha.
+ [
+ 0.9 * if a < 1.0 { a } else { 1.0 },
+ 0.1 * a.min(1.0),
+ 0.1 * a.min(1.0),
+ a,
+ ]
+}
+
+fn select_left_half(s: &mut Session) {
+ s.edit("sel", |doc, _| {
+ let mut sel = Surface::new(photocraft_color::PixelFormat::GRAY8);
+ sel.write_region(Rect::new(0, 0, 20, 30), &vec![1.0; 600]);
+ doc.selection = Some(sel);
+ Ok(())
+ })
+ .unwrap();
+}
+
+#[test]
+fn mask_apply_from_transparency_hide_selection() {
+ for depth in DEPTHS {
+ let mut s = session(depth, "rgb");
+ paint(&mut s, |_, _| [0.2, 0.4, 0.6, 1.0]);
+ assert!(!s.is_enabled("layer.layerMask.apply"));
+ select_left_half(&mut s);
+ s.execute("layer.layerMask.hideSelection", json!({}))
+ .unwrap();
+ assert!(doc(&s).selection.is_none());
+ let m = active(&s).mask.as_ref().unwrap();
+ assert_eq!((m.value(5, 5), m.value(30, 5)), (0.0, 1.0));
+ s.execute("layer.layerMask.apply", json!({})).unwrap();
+ assert!(active(&s).mask.is_none());
+ let surf = active(&s).surface().unwrap();
+ assert_eq!(surf.rgba(5, 5)[3], 0.0);
+ assert_eq!(surf.rgba(30, 5)[3], 1.0);
+ // From Transparency: alpha moves into the mask, pixels become opaque.
+ s.execute("layer.layerMask.fromTransparency", json!({}))
+ .unwrap();
+ let l = active(&s);
+ assert_eq!(l.mask.as_ref().unwrap().value(5, 5), 0.0);
+ assert_eq!(l.mask.as_ref().unwrap().value(30, 5), 1.0);
+ assert_eq!(l.surface().unwrap().rgba(30, 5)[3], 1.0);
+ // The composite looks the same.
+ let px = photocraft_compose::render(doc(&s), Rect::from_xywh(5, 5, 1, 1)).px[0];
+ assert_eq!(px[3], 0.0);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(active(&s).mask.is_none());
+ }
+}
+
+#[test]
+fn matting_commands_fix_dark_fringes() {
+ for depth in DEPTHS {
+ let mut s = session(depth, "rgb");
+ paint(&mut s, disc);
+ let edge = (0..40).find(|&x| {
+ let a = active(&s).surface().unwrap().rgba(x, 17)[3];
+ a > 0.05 && a < 0.95
+ });
+ let ex = edge.expect("an antialiased edge pixel");
+ let before = active(&s).surface().unwrap().rgba(ex, 17);
+ s.execute("layer.matting.removeBlackMatte", json!({}))
+ .unwrap();
+ let after = active(&s).surface().unwrap().rgba(ex, 17);
+ assert!(
+ after[0] > before[0] + 0.05,
+ "{depth}: {before:?} → {after:?}"
+ );
+ assert!((after[3] - before[3]).abs() < 1e-2, "alpha kept");
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("layer.matting.defringe", json!({"width": 2}))
+ .unwrap();
+ let d = active(&s).surface().unwrap().rgba(ex, 17);
+ assert!(
+ d[0] > 0.8,
+ "{depth}: defringed edge takes the core red: {d:?}"
+ );
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("layer.matting.colorDecontaminate", json!({"amount": 100}))
+ .unwrap();
+ let c = active(&s).surface().unwrap().rgba(ex, 17);
+ assert!(c[0] > before[0], "{depth}: {before:?} → {c:?}");
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("layer.matting.removeWhiteMatte", json!({}))
+ .unwrap();
+ }
+}
+
+#[test]
+fn defringe_pure_function() {
+ // 5×1: transparent, fringe (blue), core red ×3.
+ let mut px = vec![
+ [0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 1.0, 0.5],
+ [1.0, 0.0, 0.0, 1.0],
+ [1.0, 0.0, 0.0, 1.0],
+ [1.0, 0.0, 0.0, 1.0],
+ ];
+ defringe(&mut px, 5, 1, 1);
+ assert_eq!(px[1], [1.0, 0.0, 0.0, 0.5]);
+ assert_eq!(px[0][3], 0.0);
+}
+
+#[test]
+fn global_light_blending_options_scale_effects() {
+ let mut s = session(8, "rgb");
+ paint(&mut s, disc);
+ s.execute(
+ "layer.layerStyle.globalLight",
+ json!({"angle": 200, "altitude": 45}),
+ )
+ .unwrap();
+ assert_eq!(
+ (doc(&s).global_light.angle, doc(&s).global_light.altitude),
+ (-160.0, 45.0)
+ );
+ s.execute(
+ "layer.layerStyle.blendingOptions",
+ json!({"blend": "Multiply", "opacity": 50, "fillOpacity": 25}),
+ )
+ .unwrap();
+ let l = active(&s);
+ assert_eq!(
+ (l.blend, l.opacity, l.fill_opacity),
+ (BlendMode::Multiply, 0.5, 0.25)
+ );
+ assert!(
+ s.execute("layer.layerStyle.blendingOptions", json!({"blend": "nope"}))
+ .is_err()
+ );
+ assert!(
+ s.execute(
+ "layer.layerStyle.blendingOptions",
+ json!({"blend": "Pass Through"})
+ )
+ .is_err()
+ );
+ assert!(!s.is_enabled("layer.layerStyle.scaleEffects"));
+ s.execute(
+ "layer.layerStyle.dropShadow",
+ json!({"distance": 10, "size": 4}),
+ )
+ .unwrap();
+ s.execute("layer.layerStyle.scaleEffects", json!({"scale": 200}))
+ .unwrap();
+ match &active(&s).effects.items[0] {
+ Effect::DropShadow(sh) => assert_eq!((sh.distance, sh.size), (20.0, 8.0)),
+ e => panic!("{e:?}"),
+ }
+}
+
+#[test]
+fn create_layer_splits_effects_and_keeps_the_look() {
+ let mut s = session(8, "rgb");
+ s.execute("layer.new.layer", json!({})).unwrap();
+ paint(&mut s, |x, y| {
+ if (10..30).contains(&x) && (8..22).contains(&y) {
+ [0.2, 0.5, 0.9, 1.0]
+ } else {
+ [0.0; 4]
+ }
+ });
+ s.execute(
+ "layer.layerStyle.dropShadow",
+ json!({"blend": "normal", "distance": 4, "size": 2, "opacity": 60}),
+ )
+ .unwrap();
+ s.execute(
+ "layer.layerStyle.colorOverlay",
+ json!({"color": "#ff8000", "opacity": 50, "add": true}),
+ )
+ .unwrap();
+ let id = active(&s).id;
+ let before = photocraft_compose::flatten(doc(&s));
+ let n0 = doc(&s).layers.len();
+ let r = s
+ .execute("layer.layerStyle.createLayer", json!({}))
+ .unwrap();
+ assert_eq!(r["layers"], json!(2));
+ let d = doc(&s);
+ assert_eq!(d.layers.len(), n0 + 2);
+ let i = d.layers.iter().position(|l| l.id == id).unwrap();
+ assert!(d.layers[i - 1].name.ends_with("Drop Shadow") && !d.layers[i - 1].clipped);
+ assert!(d.layers[i + 1].name.ends_with("Color Overlay") && d.layers[i + 1].clipped);
+ assert!(d.layers[i].effects.items.is_empty());
+ let after = photocraft_compose::flatten(d);
+ let worst = before
+ .px
+ .iter()
+ .zip(&after.px)
+ .map(|(a, b)| (0..4).map(|c| (a[c] - b[c]).abs()).fold(0.0, f32::max))
+ .fold(0.0, f32::max);
+ assert!(
+ worst < 3.0 / 255.0,
+ "composite changed by {}",
+ worst * 255.0
+ );
+ assert!(!s.is_enabled("layer.layerStyle.createLayer"));
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(doc(&s).layers.len(), n0);
+}
+
+#[test]
+fn content_options_reports_the_editor() {
+ let mut s = session(8, "rgb");
+ assert!(!s.is_enabled("layer.layerContentOptions"));
+ s.execute("layer.newAdjustmentLayer.levels", json!({}))
+ .unwrap();
+ assert_eq!(
+ s.execute("layer.layerContentOptions", json!({})).unwrap()["editor"],
+ json!("adjustment:levels")
+ );
+ s.execute("layer.newFillLayer.solidColor", json!({}))
+ .unwrap();
+ assert_eq!(
+ s.execute("layer.layerContentOptions", json!({})).unwrap()["editor"],
+ json!("fill")
+ );
+}
+
+#[test]
+fn export_layer_trims_to_its_pixels() {
+ let mut s = session(16, "rgb");
+ paint(&mut s, |x, y| {
+ if (5..15).contains(&x) && (4..10).contains(&y) {
+ [1.0, 0.0, 0.0, 1.0]
+ } else {
+ [0.0; 4]
+ }
+ });
+ let d = layer_document(doc(&s), active(&s).id).unwrap();
+ assert_eq!((d.size.width, d.size.height), (10, 6));
+ assert_eq!(
+ d.layers[0].surface().unwrap().rgba(0, 0),
+ [1.0, 0.0, 0.0, 1.0]
+ );
+ let dir = std::env::temp_dir().join(format!("pc-layer-export-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("layer.png");
+ let r = s
+ .execute(
+ "layer.quickExportAsPng",
+ json!({"path": path.to_string_lossy()}),
+ )
+ .unwrap();
+ assert_eq!(
+ (r["width"].as_u64(), r["height"].as_u64()),
+ (Some(10), Some(6))
+ );
+ assert!(
+ std::fs::read(&path)
+ .unwrap()
+ .starts_with(&[0x89, b'P', b'N', b'G'])
+ );
+ let jpg = dir.join("layer.jpg");
+ let r = s
+ .execute(
+ "layer.exportAs",
+ json!({"path": jpg.to_string_lossy(), "scale": 200}),
+ )
+ .unwrap();
+ assert_eq!(r["width"].as_u64(), Some(20));
+ assert!(
+ s.execute(
+ "layer.quickExportAsPng",
+ json!({"path": jpg.to_string_lossy()})
+ )
+ .is_err()
+ );
+ assert!(s.execute("layer.exportAs", json!({})).is_err());
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn stack_modes_render_from_the_nested_layers() {
+ let mut s = session(8, "rgb");
+ // Three frames: the same gray, one with a bright outlier pixel.
+ s.edit("frames", |doc, active| {
+ let fmt = doc.pixel_format();
+ let mut kids = Vec::new();
+ for k in 0..3 {
+ let mut l = Layer::raster(format!("f{k}"), fmt);
+ let v = if k == 2 { 1.0 } else { 0.4 };
+ let surf = l.surface_mut().unwrap();
+ surf.write_region(
+ Rect::new(0, 0, 40, 30),
+ &photocraft_raster::from_rgba(&fmt, [0.4, 0.4, 0.4, 1.0]).repeat(1200),
+ );
+ surf.write_region(
+ Rect::new(3, 3, 4, 4),
+ &photocraft_raster::from_rgba(&fmt, [v, v, v, 1.0]),
+ );
+ kids.push(l);
+ }
+ let g = Layer::new(
+ "stack",
+ LayerContent::Group(photocraft_doc::Group {
+ children: kids,
+ expanded: true,
+ artboard: None,
+ }),
+ );
+ let smart = crate::smart_cmds::layer_to_smart(doc, &g)?;
+ let id = smart.id;
+ doc.layers = vec![smart];
+ *active = Some(id);
+ Ok(())
+ })
+ .unwrap();
+ let px = |s: &Session| active(s).content.clone();
+ let at = |s: &Session, x: i32, y: i32| match px(s) {
+ LayerContent::Smart(sm) => sm.cache.unwrap().rgba(x, y),
+ _ => panic!(),
+ };
+ assert!(
+ at(&s, 3, 3)[0] > 0.9,
+ "normal composite shows the top frame"
+ );
+ s.execute("layer.smartObjects.stackMode.median", json!({}))
+ .unwrap();
+ assert!(
+ (at(&s, 3, 3)[0] - 0.4).abs() < 2.0 / 255.0,
+ "median removes the outlier"
+ );
+ s.execute("layer.smartObjects.stackMode.maximum", json!({}))
+ .unwrap();
+ assert!(at(&s, 3, 3)[0] > 0.99);
+ s.execute("layer.smartObjects.stackMode.range", json!({}))
+ .unwrap();
+ assert!(at(&s, 10, 10)[0] < 1.0 / 255.0);
+ for m in StackMode::ALL {
+ s.execute(
+ &format!("layer.smartObjects.stackMode.{}", m.id()),
+ json!({}),
+ )
+ .unwrap();
+ match &active(&s).content {
+ LayerContent::Smart(sm) => assert_eq!(sm.stack_mode, Some(m)),
+ _ => panic!(),
+ }
+ }
+ s.execute("layer.smartObjects.stackMode.none", json!({}))
+ .unwrap();
+ assert!(at(&s, 3, 3)[0] > 0.9);
+ // The stack mode survives .pcraft.
+ s.execute("layer.smartObjects.stackMode.mean", json!({}))
+ .unwrap();
+ let bytes = photocraft_format::save_to_bytes(doc(&s), &Default::default()).unwrap();
+ let back = photocraft_format::load_from_bytes(&bytes).unwrap();
+ match &back.layers[0].content {
+ LayerContent::Smart(sm) => assert_eq!(sm.stack_mode, Some(StackMode::Mean)),
+ _ => panic!(),
+ }
+ assert!(!session(8, "rgb").is_enabled("layer.smartObjects.stackMode.mean"));
+}
+
+#[test]
+fn reveal_in_finder_dry_run_and_enabled() {
+ let mut s = session(8, "rgb");
+ assert!(!s.is_enabled("layer.smartObjects.revealInFinder"));
+ s.edit("linked", |doc, active| {
+ let mut l = Layer::new(
+ "linked",
+ LayerContent::Smart(photocraft_doc::SmartObject::new(
+ SmartSource::Linked {
+ path: "/tmp/pics/a.png".into(),
+ },
+ photocraft_geom::Affine::IDENTITY,
+ None,
+ )),
+ );
+ l.visible = true;
+ *active = Some(doc.insert_above(*active, l));
+ Ok(())
+ })
+ .unwrap();
+ assert!(s.is_enabled("layer.smartObjects.revealInFinder"));
+ let r = s
+ .execute("layer.smartObjects.revealInFinder", json!({"dryRun": true}))
+ .unwrap();
+ let (prog, args) = reveal_command("/tmp/pics/a.png");
+ assert_eq!(r["program"], json!(prog));
+ assert_eq!(r["args"], json!(args));
+}
+
+#[test]
+fn mask_all_objects_masks_the_subject() {
+ let mut s = session(8, "rgb");
+ paint(&mut s, |x, y| {
+ let inside = (((x - 20) * (x - 20) + (y - 15) * (y - 15)) as f32).sqrt() < 8.0;
+ if inside {
+ [0.9, 0.2, 0.1, 1.0]
+ } else {
+ [0.95, 0.95, 0.95, 1.0]
+ }
+ });
+ match s.execute("layer.maskAllObjects", json!({})) {
+ Ok(_) => {
+ let m = active(&s).mask.as_ref().unwrap();
+ assert!(
+ m.value(20, 15) > m.value(1, 1),
+ "subject revealed, background hidden"
+ );
+ }
+ // The segmentation may decline tiny images; then nothing changes.
+ Err(_) => assert!(active(&s).mask.is_none()),
+ }
+}
+
+#[test]
+fn layer_masks_in_gray_cmyk_lab() {
+ for mode in ["gray", "cmyk", "lab"] {
+ let mut s = session(16, mode);
+ paint(&mut s, disc);
+ s.execute("layer.layerMask.fromTransparency", json!({}))
+ .unwrap();
+ s.execute("layer.layerMask.apply", json!({})).unwrap();
+ s.execute("layer.matting.defringe", json!({"width": 1}))
+ .unwrap();
+ s.execute("layer.matting.removeBlackMatte", json!({}))
+ .unwrap();
+ assert!(
+ active(&s).surface().unwrap().rgba(20, 15)[3] > 0.99,
+ "{mode}"
+ );
+ }
+}
+
+#[test]
+fn load_files_into_stack_as_smart_object_then_median() {
+ let dir = std::env::temp_dir().join(format!("pc-stack-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut paths = Vec::new();
+ for (k, v) in [0.2f32, 0.2, 0.9].iter().enumerate() {
+ let d = Document::with_background(
+ "f",
+ photocraft_doc::Size::new(6, 4),
+ photocraft_color::ColorMode::Rgb,
+ photocraft_color::SampleType::U8,
+ photocraft_doc::Color::rgba(*v, *v, *v, 1.0),
+ );
+ let p = dir.join(format!("f{k}.png"));
+ std::fs::write(
+ &p,
+ photocraft_io::export(&d, "f.png", &Default::default())
+ .unwrap()
+ .bytes,
+ )
+ .unwrap();
+ paths.push(p.to_string_lossy().into_owned());
+ }
+ let mut s = Session::new();
+ s.execute(
+ "file.scripts.loadFilesIntoStack",
+ json!({"paths": paths, "createSmartObject": true}),
+ )
+ .unwrap();
+ assert_eq!(doc(&s).layers.len(), 1);
+ assert!(matches!(doc(&s).layers[0].content, LayerContent::Smart(_)));
+ s.execute("layer.smartObjects.stackMode.median", json!({}))
+ .unwrap();
+ let px = photocraft_compose::render(doc(&s), Rect::from_xywh(2, 2, 1, 1)).px[0];
+ assert!((px[0] - 0.2).abs() < 2.0 / 255.0, "{px:?}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
new file mode 100644
index 000000000..57262f3d5
--- /dev/null
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -0,0 +1,1030 @@
+//! Multi-layer selection and the commands that act on it: ⌘/⇧-click selection, Select › All /
+//! Deselect / Find Layers, Layer › Align and Distribute, Link Layers, Merge Layers, Group from
+//! Layers, Arrange › Reverse, Lock Layers and Rename Layer.
+//!
+//! The selection itself lives in [`DocState::selected_layers`] (UI state, like the active layer):
+//! changing it never adds a history step. Every structural change below is one history step.
+
+use photocraft_color::PixelFormat;
+use photocraft_doc::{Document, Layer, LayerContent, LayerId};
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, int};
+use crate::{DocState, EngineError, Result, Session};
+
+// ---------- selection state ----------
+
+fn doc_state(s: &Session) -> std::result::Result<&DocState, String> {
+ s.active().ok_or_else(|| "no document open".into())
+}
+
+/// Selected layers of the active document, bottom-to-top.
+pub fn selected(s: &Session) -> Vec<LayerId> {
+ s.active().map(DocState::selected_layers).unwrap_or_default()
+}
+
+/// Ids in `ids` that have no ancestor also in `ids` (a selected group already carries its
+/// selected children), bottom-to-top.
+fn top_level(doc: &Document, ids: &[LayerId]) -> Vec<LayerId> {
+ let walk = doc.walk();
+ let paths: Vec<_> = walk.iter().filter(|(_, _, l)| ids.contains(&l.id)).map(|(p, _, l)| (p.clone(), l.id)).collect();
+ paths.iter().filter(|(p, _)| !paths.iter().any(|(q, _)| q.len() < p.len() && p.starts_with(q))).map(|(_, id)| *id).collect()
+}
+
+/// Replace the layer selection without a history step (like [`Session::select_layer`]).
+pub fn set_selection(s: &mut Session, ids: Vec<LayerId>, active: Option<LayerId>, anchor: Option<LayerId>) -> Result<()> {
+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;
+ if let Some(bad) = ids.iter().chain(active.iter()).find(|id| st.doc.layer(**id).is_none()) {
+ return Err(EngineError::NoLayer(*bad));
+ }
+ let active = active.or_else(|| ids.last().copied());
+ st.selected_layers = ids;
+ if let Some(a) = active
+ && !st.selected_layers.contains(&a)
+ {
+ st.selected_layers.push(a);
+ }
+ st.active_layer = active;
+ st.layer_anchor = anchor.or(active);
+ crate::fix_selection(st);
+ // Selecting layers 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(Rect::EMPTY);
+ Ok(())
+}
+
+/// After a structural edit, make `ids` the selection (dropping any that no longer exist).
+fn reselect(s: &mut Session, ids: Vec<LayerId>, active: Option<LayerId>) {
+ if let Some(st) = s.active_mut() {
+ st.selected_layers = ids;
+ if let Some(a) = active {
+ st.active_layer = Some(a);
+ st.layer_anchor = Some(a);
+ }
+ crate::fix_selection(st);
+ }
+}
+
+/// `layer.select`: `{"layer": id, "mode": "replace|toggle|range|add"}`.
+pub fn select(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = LayerId(p.get("layer").and_then(Value::as_u64).ok_or_else(|| bad("layer.select", "missing `layer`"))?);
+ let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace");
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ if st.doc.layer(id).is_none() {
+ return Err(EngineError::NoLayer(id));
+ }
+ let mut sel = st.selected_layers();
+ match mode {
+ "replace" => s.select_layer(id)?,
+ "add" => {
+ if !sel.contains(&id) {
+ sel.push(id);
+ }
+ set_selection(s, sel, Some(id), Some(id))?;
+ }
+ "toggle" => {
+ if sel.contains(&id) {
+ if sel.len() == 1 {
+ // Photoshop keeps at least the clicked layer targeted.
+ return Ok(json!({"selected": [id.0]}));
+ }
+ sel.retain(|x| *x != id);
+ let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer };
+ set_selection(s, sel, active, active)?;
+ } else {
+ sel.push(id);
+ set_selection(s, sel, Some(id), Some(id))?;
+ }
+ }
+ "range" => {
+ let anchor = st.layer_anchor.filter(|a| st.doc.layer(*a).is_some()).or(st.active_layer).unwrap_or(id);
+ let order: Vec<LayerId> = st.doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ let (a, b) = (order.iter().position(|x| *x == anchor).unwrap_or(0), order.iter().position(|x| *x == id).unwrap_or(0));
+ let range = order[a.min(b)..=a.max(b)].to_vec();
+ set_selection(s, range, Some(id), Some(anchor))?;
+ }
+ other => return Err(bad("layer.select", format!("unknown mode `{other}`"))),
+ }
+ Ok(json!({"selected": selected(s).iter().map(|l| l.0).collect::<Vec<_>>()}))
+}
+
+fn is_locked_background(l: &Layer) -> bool {
+ l.name == "Background" && l.locks.transparency && matches!(l.content, LayerContent::Raster(_))
+}
+
+fn select_all_layers(s: &mut Session) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let ids: Vec<LayerId> = d.doc.walk().into_iter().filter(|(_, _, l)| !is_locked_background(l)).map(|(_, _, l)| l.id).collect();
+ if ids.is_empty() {
+ return Err(EngineError::Other("there are no layers to select".into()));
+ }
+ let active = d.active_layer.filter(|a| ids.contains(a)).or(ids.last().copied());
+ let n = ids.len();
+ set_selection(s, ids, active, None)?;
+ Ok(json!({"selected": n}))
+}
+
+fn find_layers(s: &mut Session, p: &Value) -> Result<Value> {
+ let needle = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("select.findLayers", "missing `name`"))?.to_lowercase();
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let ids: Vec<LayerId> = d.doc.walk().into_iter().filter(|(_, _, l)| l.name.to_lowercase().contains(&needle)).map(|(_, _, l)| l.id).collect();
+ if ids.is_empty() {
+ return Err(EngineError::Other(format!("no layer name contains \"{needle}\"")));
+ }
+ let out = ids.iter().map(|l| l.0).collect::<Vec<_>>();
+ set_selection(s, ids, None, None)?;
+ Ok(json!({"selected": out}))
+}
+
+fn select_linked(s: &mut Session) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let groups = link_groups(&d.doc, &d.selected_layers());
+ let ids: Vec<LayerId> = d.doc.walk().into_iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| groups.contains(&g))).map(|(_, _, l)| l.id).collect();
+ let active = d.active_layer;
+ let n = ids.len();
+ set_selection(s, ids, active, active)?;
+ Ok(json!({"selected": n}))
+}
+
+// ---------- enabled predicates ----------
+
+fn has_layer(s: &Session) -> std::result::Result<(), String> {
+ if selected(s).is_empty() { Err("no layer selected".into()) } else { Ok(()) }
+}
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ doc_state(s).map(|_| ())
+}
+fn two_plus(s: &Session) -> std::result::Result<(), String> {
+ if selected(s).len() >= 2 { Ok(()) } else { Err("select two or more layers".into()) }
+}
+fn can_align(s: &Session) -> std::result::Result<(), String> {
+ let d = doc_state(s)?;
+ match d.selected_layers().len() {
+ 0 => Err("no layer selected".into()),
+ 1 if d.doc.selection.is_none() => Err("select two or more layers, or make a selection to align to".into()),
+ _ => Ok(()),
+ }
+}
+fn can_distribute(s: &Session) -> std::result::Result<(), String> {
+ if selected(s).len() >= 3 { Ok(()) } else { Err("select three or more layers to distribute".into()) }
+}
+fn can_link(s: &Session) -> std::result::Result<(), String> {
+ let d = doc_state(s)?;
+ let sel = d.selected_layers();
+ match sel.len() {
+ 0 => Err("no layer selected".into()),
+ 1 if d.doc.layer(sel[0]).is_none_or(|l| l.link_group.is_none()) => Err("select two or more layers to link".into()),
+ _ => Ok(()),
+ }
+}
+fn has_linked(s: &Session) -> std::result::Result<(), String> {
+ let d = doc_state(s)?;
+ if link_groups(&d.doc, &d.selected_layers()).is_empty() { Err("the selected layers are not linked".into()) } else { Ok(()) }
+}
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+// ---------- moving layers ----------
+
+fn link_groups(doc: &Document, ids: &[LayerId]) -> Vec<u64> {
+ let mut g: Vec<u64> = ids.iter().filter_map(|id| doc.layer(*id)?.link_group).collect();
+ g.sort_unstable();
+ g.dedup();
+ g
+}
+
+/// `ids` plus every layer linked to one of them.
+pub(crate) fn with_links(doc: &Document, ids: &[LayerId]) -> Vec<LayerId> {
+ let groups = link_groups(doc, ids);
+ let mut out = ids.to_vec();
+ if !groups.is_empty() {
+ for (_, _, l) in doc.walk() {
+ if l.link_group.is_some_and(|g| groups.contains(&g)) && !out.contains(&l.id) {
+ out.push(l.id);
+ }
+ }
+ }
+ out
+}
+
+/// Move layers by whole pixels the way the Move tool does: pixels, linked masks, type and
+/// vector content (shapes, linked vector masks) all move together.
+pub(crate) fn move_layers(doc: &mut Document, moves: &[(LayerId, i32, i32)]) -> Result<()> {
+ let snapshot = doc.clone();
+ for &(id, dx, dy) in moves {
+ if dx == 0 && dy == 0 {
+ continue;
+ }
+ 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)));
+ }
+ crate::commands::translate_layer(&snapshot, l, dx, dy);
+ crate::vector_cmds::translate_vectors(&snapshot, l, dx as f64, dy as f64);
+ }
+ Ok(())
+}
+
+/// `layer.translate`: the explicit layer, or every selected layer, plus their linked layers.
+pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
+ let dx = int(p, "dx").unwrap_or(0) as i32;
+ let dy = int(p, "dy").unwrap_or(0) as i32;
+ if dx == 0 && dy == 0 {
+ return Ok(Value::Null);
+ }
+ let roots = match p.get("layer").and_then(Value::as_u64) {
+ Some(id) => vec![LayerId(id)],
+ None => selected(s),
+ };
+ if roots.is_empty() {
+ return Err(EngineError::Other("no active layer".into()));
+ }
+ s.edit("Move", |doc, _| {
+ let ids = top_level(doc, &with_links(doc, &roots));
+ if ids.is_empty() {
+ return Err(EngineError::NoLayer(roots[0]));
+ }
+ let moves: Vec<_> = ids.into_iter().map(|id| (id, dx, dy)).collect();
+ move_layers(doc, &moves)
+ })?;
+ Ok(Value::Null)
+}
+
+/// Content bounds used by Align/Distribute: the layer's pixels (type and shape layers use their
+/// rendered pixels), or the union of a group's children. Fill and adjustment layers have none.
+pub fn layer_bounds(l: &Layer) -> Option<Rect> {
+ let r = match &l.content {
+ LayerContent::Group(g) => g.children.iter().filter_map(layer_bounds).fold(Rect::EMPTY, |a, b| a.union(&b)),
+ _ => l.surface().map(|s| s.content_bounds()).unwrap_or(Rect::EMPTY),
+ };
+ (!r.is_empty()).then_some(r)
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum Edge {
+ Top,
+ VCenter,
+ Bottom,
+ Left,
+ HCenter,
+ Right,
+}
+
+impl Edge {
+ fn parse(k: &str) -> Option<Edge> {
+ Some(match k {
+ "topEdges" => Edge::Top,
+ "verticalCenters" => Edge::VCenter,
+ "bottomEdges" => Edge::Bottom,
+ "leftEdges" => Edge::Left,
+ "horizontalCenters" => Edge::HCenter,
+ "rightEdges" => Edge::Right,
+ _ => return None,
+ })
+ }
+ fn vertical(self) -> bool {
+ matches!(self, Edge::Top | Edge::VCenter | Edge::Bottom)
+ }
+ /// The edge's coordinate, doubled so centres stay integral.
+ fn value2(self, r: &Rect) -> i64 {
+ let (a, b) = if self.vertical() { (r.y0, r.y1) } else { (r.x0, r.x1) };
+ match self {
+ Edge::Top | Edge::Left => 2 * a as i64,
+ Edge::Bottom | Edge::Right => 2 * b as i64,
+ Edge::VCenter | Edge::HCenter => a as i64 + b as i64,
+ }
+ }
+ fn delta(self, d: i32) -> (i32, i32) {
+ if self.vertical() { (0, d) } else { (d, 0) }
+ }
+}
+
+/// Selected top-level layers that have content bounds, bottom-to-top.
+fn bounded_selection(doc: &Document, sel: &[LayerId]) -> Vec<(LayerId, Rect)> {
+ top_level(doc, sel).into_iter().filter_map(|id| Some((id, layer_bounds(doc.layer(id)?)?))).collect()
+}
+
+fn align(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
+ let cmd = format!("layer.align.{kind}");
+ let edge = Edge::parse(kind).ok_or_else(|| bad(&cmd, "unknown edge"))?;
+ let sel = selected(s);
+ let to = p.get("to").and_then(Value::as_str).unwrap_or("auto").to_string();
+ let moved = s.edit("Align", |doc, _| {
+ let items = bounded_selection(doc, &sel);
+ if items.is_empty() {
+ return Err(EngineError::Other("the selected layers have no content to align".into()));
+ }
+ let target = match to.as_str() {
+ "canvas" => doc.bounds(),
+ "selection" => doc.selection.as_ref().map(|m| m.content_bounds()).ok_or_else(|| EngineError::Other("there is no selection to align to".into()))?,
+ "auto" | "layers" => match (&doc.selection, sel.len()) {
+ // Photoshop: one layer plus an active selection aligns to the selection bounds.
+ (Some(m), 1) if to == "auto" => m.content_bounds(),
+ _ => items.iter().fold(Rect::EMPTY, |a, (_, b)| a.union(b)),
+ },
+ other => return Err(bad(&cmd, format!("`to` must be auto|layers|selection|canvas, not `{other}`"))),
+ };
+ if target.is_empty() {
+ return Err(EngineError::Other("nothing to align to".into()));
+ }
+ let t2 = edge.value2(&target);
+ let moves: Vec<(LayerId, i32, i32)> = items
+ .iter()
+ .flat_map(|(id, r)| {
+ let d = (t2 - edge.value2(r)).div_euclid(2) as i32;
+ let (dx, dy) = edge.delta(d);
+ // Linked layers travel with the layer they are linked to.
+ with_links(doc, &[*id]).into_iter().map(move |l| (l, dx, dy))
+ })
+ .collect();
+ let moves = dedup_moves(doc, moves);
+ move_layers(doc, &moves)?;
+ Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count())
+ })?;
+ Ok(json!({"moved": moved}))
+}
+
+/// One move per layer (first wins), skipping layers nested in another moved layer.
+fn dedup_moves(doc: &Document, moves: Vec<(LayerId, i32, i32)>) -> Vec<(LayerId, i32, i32)> {
+ let mut out: Vec<(LayerId, i32, i32)> = Vec::new();
+ for m in moves {
+ if !out.iter().any(|o| o.0 == m.0) {
+ out.push(m);
+ }
+ }
+ let ids: Vec<LayerId> = out.iter().map(|m| m.0).collect();
+ let keep = top_level(doc, &ids);
+ out.retain(|m| keep.contains(&m.0));
+ out
+}
+
+fn distribute(s: &mut Session, kind: &str) -> Result<Value> {
+ let sel = selected(s);
+ let kind = kind.to_string();
+ let moved = s.edit("Distribute", |doc, _| {
+ let mut items = bounded_selection(doc, &sel);
+ if items.len() < 3 {
+ return Err(EngineError::Other("distributing needs three or more layers with content".into()));
+ }
+ let n = items.len();
+ let mut moves = Vec::new();
+ match kind.as_str() {
+ "horizontally" | "vertically" => {
+ // Equal gaps between neighbours; the outermost layers stay put.
+ let v = kind == "vertically";
+ let lo = |r: &Rect| if v { r.y0 } else { r.x0 } as i64;
+ let hi = |r: &Rect| if v { r.y1 } else { r.x1 } as i64;
+ items.sort_by_key(|(_, r)| (lo(r) + hi(r), lo(r)));
+ let span = hi(&items[n - 1].1) - lo(&items[0].1);
+ let total: i64 = items.iter().map(|(_, r)| hi(r) - lo(r)).sum();
+ let gap = (span - total) as f64 / (n - 1) as f64;
+ let mut cursor = lo(&items[0].1) as f64;
+ for (id, r) in &items {
+ let want = cursor.round() as i64;
+ let d = (want - lo(r)) as i32;
+ moves.push(if v { (*id, 0, d) } else { (*id, d, 0) });
+ cursor += (hi(r) - lo(r)) as f64 + gap;
+ }
+ }
+ k => {
+ let edge = Edge::parse(k).ok_or_else(|| bad("layer.distribute", format!("unknown kind `{k}`")))?;
+ items.sort_by_key(|(_, r)| edge.value2(r));
+ let (first, last) = (edge.value2(&items[0].1) as f64, edge.value2(&items[n - 1].1) as f64);
+ for (i, (id, r)) in items.iter().enumerate() {
+ let want2 = first + (last - first) * i as f64 / (n - 1) as f64;
+ let d = ((want2 - edge.value2(r) as f64) / 2.0).round() as i32;
+ let (dx, dy) = edge.delta(d);
+ moves.push((*id, dx, dy));
+ }
+ }
+ }
+ let moves: Vec<_> = moves.into_iter().flat_map(|(id, dx, dy)| with_links(doc, &[id]).into_iter().map(move |l| (l, dx, dy))).collect();
+ let moves = dedup_moves(doc, moves);
+ move_layers(doc, &moves)?;
+ Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count())
+ })?;
+ Ok(json!({"moved": moved}))
+}
+
+// ---------- structural commands ----------
+
+fn link_layers(s: &mut Session) -> Result<Value> {
+ let sel = selected(s);
+ let linked = s.edit("Link Layers", |doc, _| {
+ let groups: Vec<Option<u64>> = sel.iter().map(|id| doc.layer(*id).and_then(|l| l.link_group)).collect();
+ // Already one link group (or a single linked layer): unlink, like Photoshop's toggle.
+ let unlink = groups[0].is_some() && groups.iter().all(|g| *g == groups[0]);
+ let next = doc.walk().iter().filter_map(|(_, _, l)| l.link_group).max().unwrap_or(0) + 1;
+ for id in &sel {
+ let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
+ l.link_group = if unlink { None } else { Some(next) };
+ }
+ // A group left with a single member is no longer a link.
+ let mut counts = std::collections::HashMap::<u64, usize>::new();
+ for (_, _, l) in doc.walk() {
+ if let Some(g) = l.link_group {
+ *counts.entry(g).or_default() += 1;
+ }
+ }
+ let lonely: Vec<LayerId> = doc.walk().iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| counts[&g] < 2)).map(|(_, _, l)| l.id).collect();
+ for id in lonely {
+ if let Some(l) = doc.layer_mut(id) {
+ l.link_group = None;
+ }
+ }
+ Ok(!unlink)
+ })?;
+ Ok(json!({"linked": linked}))
+}
+
+fn lock_layers(s: &mut Session, p: &Value) -> Result<Value> {
+ let sel = selected(s);
+ let keys = ["transparency", "pixels", "position", "artboard", "all"];
+ let given: Vec<(&str, bool)> = keys.iter().filter_map(|k| Some((*k, p.get(*k)?.as_bool()?))).collect();
+ s.edit("Lock Layers", |doc, _| {
+ // No explicit locks: toggle "lock all" (on unless every selected layer is already locked).
+ let all_locked = sel.iter().all(|id| doc.layer(*id).is_some_and(|l| l.locks.all));
+ let given: Vec<(&str, bool)> = if given.is_empty() { vec![("all", !all_locked)] } else { given.clone() };
+ for id in &sel {
+ let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
+ for (k, v) in &given {
+ match *k {
+ "transparency" => l.locks.transparency = *v,
+ "pixels" => l.locks.pixels = *v,
+ "position" => l.locks.position = *v,
+ "artboard" => l.locks.artboard = *v,
+ _ => l.locks.all = *v,
+ }
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({"layers": sel.len()}))
+}
+
+fn rename_layer(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("layer.renameLayer", "missing `name`"))?.to_string();
+ let id = crate::commands::layer_param(s, p)?;
+ s.edit("Rename Layer", |doc, _| {
+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.name = name;
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn reverse(s: &mut Session) -> Result<Value> {
+ let sel = selected(s);
+ s.edit("Reverse", |doc, _| {
+ let ids = top_level(doc, &sel);
+ if ids.len() < 2 {
+ return Err(EngineError::Other("select two or more layers to reverse".into()));
+ }
+ let paths: Vec<Vec<usize>> = ids.iter().map(|id| doc.path_of(*id).ok_or(EngineError::NoLayer(*id))).collect::<Result<_>>()?;
+ let layers: Vec<Layer> = ids.iter().map(|id| doc.layer(*id).cloned().ok_or(EngineError::NoLayer(*id))).collect::<Result<_>>()?;
+ // Slots are disjoint (no layer is nested in another), so writing whole layers back to the
+ // same paths never shifts another slot.
+ for (path, l) in paths.iter().zip(layers.into_iter().rev()) {
+ *doc.layer_at_mut(path).ok_or_else(|| EngineError::Other("layer tree changed".into()))? = l;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+/// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves
+/// into a new group placed where the top-most of them was. Bottom-to-top order is preserved.
+pub fn group_layers(s: &mut Session, p: &Value) -> Result<Value> {
+ let ids = match p.get("layer").and_then(Value::as_u64) {
+ Some(id) => vec![LayerId(id)],
+ None => selected(s),
+ };
+ if ids.is_empty() {
+ return Err(EngineError::Other("no layer selected".into()));
+ }
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);
+ let gid = s.edit("Group Layers", |doc, active| {
+ let ids = top_level(doc, &ids);
+ let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?;
+ let name = name.unwrap_or_else(|| doc.next_layer_name("Group"));
+ let gid = doc.insert_above(Some(top), Layer::group(name, vec![]));
+ let mut children = Vec::with_capacity(ids.len());
+ for id in &ids {
+ children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?);
+ }
+ *doc.layer_mut(gid).and_then(Layer::children_mut).expect("new group") = children;
+ *active = Some(gid);
+ Ok(gid)
+ })?;
+ reselect(s, vec![gid], Some(gid));
+ Ok(json!({ "layer": gid.0 }))
+}
+
+fn merge_layers(s: &mut Session) -> Result<Value> {
+ let sel = selected(s);
+ if sel.len() < 2 {
+ return s.execute("layer.mergeDown", json!({}));
+ }
+ let mid = s.edit("Merge Layers", |doc, active| {
+ let ids = top_level(doc, &sel);
+ let top_id = *ids.last().expect("two or more");
+ let top = doc.layer(top_id).ok_or(EngineError::NoLayer(top_id))?.clone();
+ let mut solo = doc.clone();
+ solo.layers = ids.iter().filter_map(|id| doc.layer(*id)).filter(|l| l.visible).cloned().collect();
+ if solo.layers.is_empty() {
+ return Err(EngineError::Other("the selected layers are all hidden".into()));
+ }
+ let buf = photocraft_compose::flatten(&solo);
+ 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 merged = Layer::raster(top.name.clone(), fmt);
+ merged.locks = top.locks;
+ let surf = merged.surface_mut().expect("raster");
+ surf.write_region(doc.bounds(), &data);
+ surf.prune();
+ let mid = merged.id;
+ // Hidden selected layers are discarded, as in Photoshop.
+ for id in &ids[..ids.len() - 1] {
+ doc.remove(*id);
+ }
+ *doc.layer_mut(top_id).ok_or(EngineError::NoLayer(top_id))? = merged;
+ *active = Some(mid);
+ Ok(mid)
+ })?;
+ reselect(s, vec![mid], Some(mid));
+ Ok(json!({ "layer": mid.0 }))
+}
+
+/// Delete Layer with several layers selected.
+pub fn delete_selected(s: &mut Session) -> Result<Value> {
+ let sel = selected(s);
+ s.edit("Delete Layers", |doc, active| {
+ let ids = top_level(doc, &sel);
+ let below = ids.first().and_then(|id| {
+ let order: Vec<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ let i = order.iter().position(|x| x == id)?;
+ order[..i].iter().rev().find(|x| !sel.contains(x)).copied()
+ });
+ for id in &ids {
+ doc.remove(*id).ok_or(EngineError::NoLayer(*id))?;
+ }
+ if doc.layers.is_empty() {
+ return Err(EngineError::Other("a document must keep at least one layer".into()));
+ }
+ *active = below.filter(|b| doc.layer(*b).is_some()).or_else(|| doc.top_layer());
+ Ok(())
+ })?;
+ Ok(json!({"deleted": sel.len()}))
+}
+
+/// Duplicate Layer with several layers selected: each copy goes above its original and the
+/// copies become the selection.
+pub fn duplicate_selected(s: &mut Session) -> Result<Value> {
+ let sel = selected(s);
+ let old_active = s.active().and_then(|d| d.active_layer);
+ let (copies, active) = s.edit("Duplicate Layers", |doc, active| {
+ let mut copies = Vec::new();
+ let mut new_active = None;
+ for id in top_level(doc, &sel) {
+ let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate();
+ dup.name = format!("{} copy", dup.name);
+ let nid = doc.insert_above(Some(id), dup);
+ if Some(id) == old_active {
+ new_active = Some(nid);
+ }
+ copies.push(nid);
+ }
+ let a = new_active.or(copies.last().copied());
+ *active = a;
+ Ok((copies, a))
+ })?;
+ let out = copies.iter().map(|l| l.0).collect::<Vec<_>>();
+ reselect(s, copies, active);
+ Ok(json!({"layers": out}))
+}
+
+/// Show/hide every selected layer in one step.
+pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result<Value> {
+ let sel = selected(s);
+ s.edit(if visible { "Show Layers" } else { "Hide Layers" }, |doc, _| {
+ for id in &sel {
+ doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.visible = visible;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+/// Is more than one layer selected (so single-layer commands should act on the whole set)?
+pub fn multi(s: &Session, p: &Value) -> bool {
+ p.get("layer").is_none() && selected(s).len() > 1
+}
+
+// ---------- registry ----------
+
+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 }
+ };
+ }
+ const ALIGN: &str = r##"{"to":"auto|layers|selection|canvas"="auto"} (auto: the selection bounds with one layer and an active selection, else the selected layers' bounds)"##;
+ vec![
+ spec!("select.allLayers", "All Layers", &["Select"], Some("Cmd+Alt+A"), "{}", has_doc, |s, _| select_all_layers(s)),
+ spec!("select.deselectLayers", "Deselect Layers", &["Select"], None, "{}", has_layer, |s, _| {
+ set_selection(s, Vec::new(), None, None)?;
+ if let Some(st) = s.active_mut() {
+ st.active_layer = None;
+ st.selected_layers.clear();
+ }
+ Ok(Value::Null)
+ }),
+ spec!("select.findLayers", "Find Layers", &["Select"], Some("Cmd+Alt+Shift+F"), r##"{"name":str (case-insensitive substring)}"##, has_doc, find_layers),
+ spec!("layer.selectLinkedLayers", "Select Linked Layers", &["Layer"], None, "{}", has_linked, |s, _| select_linked(s)),
+ spec!("layer.align.topEdges", "Top Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "topEdges")),
+ spec!("layer.align.verticalCenters", "Vertical Centers", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "verticalCenters")),
+ spec!("layer.align.bottomEdges", "Bottom Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "bottomEdges")),
+ spec!("layer.align.leftEdges", "Left Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "leftEdges")),
+ spec!("layer.align.horizontalCenters", "Horizontal Centers", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "horizontalCenters")),
+ spec!("layer.align.rightEdges", "Right Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "rightEdges")),
+ spec!("layer.distribute.topEdges", "Top Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "topEdges")),
+ spec!("layer.distribute.verticalCenters", "Vertical Centers", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "verticalCenters")),
+ spec!("layer.distribute.bottomEdges", "Bottom Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "bottomEdges")),
+ spec!("layer.distribute.leftEdges", "Left Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "leftEdges")),
+ spec!("layer.distribute.horizontalCenters", "Horizontal Centers", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "horizontalCenters")),
+ spec!("layer.distribute.rightEdges", "Right Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "rightEdges")),
+ spec!("layer.distribute.horizontally", "Horizontally", &["Layer", "Distribute"], None, "{} (equal horizontal gaps)", can_distribute, |s, _| distribute(s, "horizontally")),
+ spec!("layer.distribute.vertically", "Vertically", &["Layer", "Distribute"], None, "{} (equal vertical gaps)", can_distribute, |s, _| distribute(s, "vertically")),
+ spec!("layer.linkLayers", "Link Layers", &["Layer"], None, "{} (toggles: unlinks when the selection is already one link group)", can_link, |s, _| link_layers(s)),
+ spec!("layer.mergeLayers", "Merge Layers", &["Layer"], Some("Cmd+E"), "{} (one layer selected: Merge Down)", has_layer, |s, _| merge_layers(s)),
+ spec!("layer.new.groupFromLayers", "Group from Layers…", &["Layer", "New"], None, r##"{"name":str?}"##, has_layer, group_layers),
+ spec!("layer.arrange.reverse", "Reverse", &["Layer", "Arrange"], None, "{}", two_plus, |s, _| reverse(s)),
+ spec!("layer.lockLayers", "Lock Layers…", &["Layer"], None, r##"{"transparency":bool?,"pixels":bool?,"position":bool?,"artboard":bool?,"all":bool?} (none given: toggle lock all)"##, has_layer, lock_layers),
+ spec!("layer.renameLayer", "Rename Layer", &["Layer"], None, r##"{"layer":id?,"name":str}"##, has_layer, rename_layer),
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth})).unwrap();
+ s
+ }
+
+ fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+ }
+
+ /// New pixel layer with an opaque red rectangle.
+ fn rect_layer(s: &mut Session, r: Rect) -> LayerId {
+ let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap());
+ s.edit("paint", |doc, _| {
+ doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ id
+ }
+
+ fn bounds(s: &Session, id: LayerId) -> Rect {
+ layer_bounds(doc(s).layer(id).unwrap()).unwrap()
+ }
+
+ fn sel(s: &Session) -> Vec<LayerId> {
+ selected(s)
+ }
+
+ fn select_all(s: &mut Session, ids: &[LayerId]) {
+ s.execute("layer.select", json!({"layer": ids[0].0})).unwrap();
+ for id in &ids[1..] {
+ s.execute("layer.select", json!({"layer": id.0, "mode": "toggle"})).unwrap();
+ }
+ }
+
+ #[test]
+ fn toggle_and_range_selection() {
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ assert_eq!(sel(&s), vec![d]);
+ s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap();
+ assert_eq!(sel(&s), vec![b, d]);
+ assert_eq!(s.active().unwrap().active_layer, Some(b));
+ // Toggling the active layer off hands "active" to a remaining member.
+ s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap();
+ assert_eq!(sel(&s), vec![d]);
+ assert_eq!(s.active().unwrap().active_layer, Some(d));
+ // The last selected layer can't be toggled off.
+ s.execute("layer.select", json!({"layer": d.0, "mode": "toggle"})).unwrap();
+ assert_eq!(sel(&s), vec![d]);
+ // Range from the anchor (a) to c.
+ s.execute("layer.select", json!({"layer": a.0})).unwrap();
+ s.execute("layer.select", json!({"layer": c.0, "mode": "range"})).unwrap();
+ assert_eq!(sel(&s), vec![a, b, c]);
+ // A second ⇧-click re-ranges from the same anchor.
+ s.execute("layer.select", json!({"layer": b.0, "mode": "range"})).unwrap();
+ assert_eq!(sel(&s), vec![a, b]);
+ assert!(s.execute("layer.select", json!({"layer": b.0, "mode": "bogus"})).is_err());
+ // Selection changes are not edits.
+ let history = s.active().unwrap().history.entries().len();
+ s.execute("select.allLayers", json!({})).unwrap();
+ assert_eq!(sel(&s), vec![a, b, c, d], "Select All Layers skips the locked Background");
+ s.execute("select.deselectLayers", json!({})).unwrap();
+ assert!(sel(&s).is_empty());
+ assert_eq!(s.active().unwrap().history.entries().len(), history);
+ assert!(!s.is_enabled("layer.align.topEdges"));
+ }
+
+ #[test]
+ fn find_layers_by_name() {
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ s.execute("layer.renameLayer", json!({"layer": a.0, "name": "Sky photo"})).unwrap();
+ s.execute("layer.renameLayer", json!({"layer": b.0, "name": "Photo of sea"})).unwrap();
+ assert_eq!(doc(&s).layer(a).unwrap().name, "Sky photo");
+ let r = s.execute("select.findLayers", json!({"name": "PHOTO"})).unwrap();
+ assert_eq!(r["selected"], json!([a.0, b.0]));
+ assert!(s.execute("select.findLayers", json!({"name": "nothing"})).is_err());
+ assert!(s.execute("layer.renameLayer", json!({})).is_err());
+ }
+
+ #[test]
+ fn align_each_edge() {
+ for depth in [8, 16, 32] {
+ let cases: [(&str, [Rect; 2]); 6] = [
+ ("topEdges", [Rect::new(10, 5, 20, 15), Rect::new(40, 5, 50, 25)]),
+ ("bottomEdges", [Rect::new(10, 20, 20, 30), Rect::new(40, 10, 50, 30)]),
+ // Union 5..30: centre 17.5; half-pixel offsets round towards the top.
+ ("verticalCenters", [Rect::new(10, 12, 20, 22), Rect::new(40, 7, 50, 27)]),
+ ("leftEdges", [Rect::new(10, 5, 20, 15), Rect::new(10, 10, 50, 30)]),
+ ("rightEdges", [Rect::new(40, 5, 50, 15), Rect::new(10, 10, 50, 30)]),
+ ("horizontalCenters", [Rect::new(25, 5, 35, 15), Rect::new(10, 10, 50, 30)]),
+ ];
+ for (kind, want) in cases {
+ let mut s = session(depth);
+ let a = rect_layer(&mut s, Rect::new(10, 5, 20, 15));
+ let b = rect_layer(&mut s, Rect::new(40, 10, 50, 30));
+ // For the horizontal cases make b wide so it defines the target bounds.
+ if !matches!(kind, "topEdges" | "bottomEdges" | "verticalCenters") {
+ s.edit("wide", |doc, _| {
+ doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[0.0, 1.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ }
+ select_all(&mut s, &[a, b]);
+ s.execute(&format!("layer.align.{kind}"), json!({})).unwrap();
+ assert_eq!([bounds(&s, a), bounds(&s, b)], want, "{kind} at {depth}-bit");
+ // Pixels moved, not just bounds.
+ let r = want[0];
+ assert_eq!(doc(&s).layer(a).unwrap().surface().unwrap().pixel(r.x0, r.y0)[..4], [1.0, 0.0, 0.0, 1.0]);
+ // One undo restores the original positions.
+ s.undo();
+ assert_eq!(bounds(&s, a), Rect::new(10, 5, 20, 15));
+ }
+ }
+ }
+
+ #[test]
+ fn align_single_layer_to_selection() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20));
+ assert!(!s.is_enabled("layer.align.leftEdges"), "one layer without a selection");
+ s.execute("select.rect", json!({"x": 50, "y": 40, "width": 30, "height": 30})).unwrap();
+ assert!(s.is_enabled("layer.align.leftEdges"));
+ s.execute("layer.align.rightEdges", json!({})).unwrap();
+ assert_eq!(bounds(&s, a), Rect::new(70, 10, 80, 20));
+ s.execute("layer.align.verticalCenters", json!({})).unwrap();
+ assert_eq!(bounds(&s, a), Rect::new(70, 50, 80, 60));
+ s.execute("layer.align.topEdges", json!({"to": "canvas"})).unwrap();
+ assert_eq!(bounds(&s, a), Rect::new(70, 0, 80, 10));
+ }
+ }
+
+ #[test]
+ fn distribute_uneven_layers() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10));
+ let b = rect_layer(&mut s, Rect::new(12, 0, 32, 10)); // 20 wide
+ let c = rect_layer(&mut s, Rect::new(70, 0, 100, 10)); // 30 wide
+ select_all(&mut s, &[a, b, c]);
+ assert!(s.is_enabled("layer.distribute.leftEdges"));
+ s.execute("layer.distribute.leftEdges", json!({})).unwrap();
+ assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10), "left edges 0, 35, 70");
+ s.undo();
+ s.execute("layer.distribute.horizontalCenters", json!({})).unwrap();
+ // centres 5 and 85 → middle centre 45
+ assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10));
+ s.undo();
+ s.execute("layer.distribute.rightEdges", json!({})).unwrap();
+ // right edges 10 and 100 → 55
+ assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10));
+ s.undo();
+ s.execute("layer.distribute.horizontally", json!({})).unwrap();
+ // span 100, widths 60 → gaps of 20: b at 30..50
+ assert_eq!(bounds(&s, b), Rect::new(30, 0, 50, 10));
+ assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10));
+ assert_eq!(bounds(&s, c), Rect::new(70, 0, 100, 10));
+ s.undo();
+ assert_eq!(bounds(&s, b), Rect::new(12, 0, 32, 10));
+ }
+ // Vertical: tall layers with uneven heights.
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10));
+ let b = rect_layer(&mut s, Rect::new(0, 50, 10, 54));
+ let c = rect_layer(&mut s, Rect::new(0, 60, 10, 80));
+ select_all(&mut s, &[a, b, c]);
+ s.execute("layer.distribute.vertically", json!({})).unwrap();
+ // span 80, heights 34 → gaps 23: b at 33..37
+ assert_eq!(bounds(&s, b), Rect::new(0, 33, 10, 37));
+ s.undo();
+ s.execute("layer.distribute.topEdges", json!({})).unwrap();
+ assert_eq!(bounds(&s, b), Rect::new(0, 30, 10, 34));
+ s.undo();
+ s.execute("layer.distribute.bottomEdges", json!({})).unwrap();
+ assert_eq!(bounds(&s, b), Rect::new(0, 41, 10, 45));
+ s.undo();
+ s.execute("layer.distribute.verticalCenters", json!({})).unwrap();
+ // centres 5 and 70 → 37.5, b is 4 tall → top 35.5 → rounds to 36 (35 for ties down)
+ let y0 = bounds(&s, b).y0;
+ assert!((35..=36).contains(&y0), "{y0}");
+ // Two layers can't be distributed.
+ select_all(&mut s, &[a, b]);
+ assert!(!s.is_enabled("layer.distribute.leftEdges"));
+ }
+
+ #[test]
+ fn merge_selected_into_top_most() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10));
+ let b = rect_layer(&mut s, Rect::new(20, 0, 30, 10));
+ let c = rect_layer(&mut s, Rect::new(40, 0, 50, 10));
+ s.execute("layer.renameLayer", json!({"layer": c.0, "name": "Top"})).unwrap();
+ select_all(&mut s, &[a, c]);
+ let before = doc(&s).layer_count();
+ let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
+ let d = doc(&s);
+ assert_eq!(d.layer_count(), before - 1);
+ let ml = d.layer(m).unwrap();
+ assert_eq!(ml.name, "Top");
+ assert_eq!(layer_bounds(ml).unwrap(), Rect::new(0, 0, 50, 10));
+ assert_eq!(ml.surface().unwrap().pixel(5, 5)[..4], [1.0, 0.0, 0.0, 1.0]);
+ assert_eq!(ml.surface().unwrap().pixel(25, 5)[3], 0.0, "b was not merged");
+ assert!(d.layer(b).is_some() && d.layer(a).is_none());
+ assert_eq!(d.layers.last().unwrap().id, m, "merged layer sits where the top-most was");
+ assert_eq!(sel(&s), vec![m]);
+ s.undo();
+ assert_eq!(doc(&s).layer_count(), before);
+ assert_eq!(sel(&s), vec![c], "undo leaves a valid selection");
+ // One layer selected: Merge Down.
+ s.execute("layer.mergeLayers", json!({})).unwrap();
+ assert_eq!(doc(&s).layer_count(), before - 1);
+ }
+ }
+
+ #[test]
+ fn group_from_layers_preserves_order() {
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ select_all(&mut s, &[c, a]);
+ let g = LayerId(s.execute("layer.new.groupFromLayers", json!({"name": "Pair"})).unwrap()["layer"].as_u64().unwrap());
+ let docu = doc(&s);
+ let gl = docu.layer(g).unwrap();
+ assert_eq!(gl.name, "Pair");
+ assert_eq!(gl.children().unwrap().iter().map(|l| l.id).collect::<Vec<_>>(), vec![a, c]);
+ // Root (bottom-to-top): Background, b, Pair (where c was), d.
+ assert_eq!(docu.layers.iter().map(|l| l.id).skip(1).collect::<Vec<_>>(), vec![b, g, d]);
+ assert_eq!(sel(&s), vec![g]);
+ s.undo();
+ assert_eq!(doc(&s).layers.len(), 5);
+ // ⌘G with several selected groups them too.
+ select_all(&mut s, &[b, d]);
+ s.execute("layer.groupLayers", json!({})).unwrap();
+ assert_eq!(doc(&s).layers.len(), 4);
+ }
+
+ #[test]
+ fn linked_layers_move_together_and_undo() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10));
+ let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30));
+ let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60));
+ assert!(!s.is_enabled("layer.linkLayers"));
+ select_all(&mut s, &[a, b]);
+ assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true);
+ let g = doc(&s).layer(a).unwrap().link_group;
+ assert!(g.is_some() && doc(&s).layer(b).unwrap().link_group == g);
+ // Move only a: b follows, c stays.
+ s.execute("layer.select", json!({"layer": a.0})).unwrap();
+ s.execute("layer.translate", json!({"dx": 5, "dy": 3})).unwrap();
+ assert_eq!(bounds(&s, a), Rect::new(5, 3, 15, 13));
+ assert_eq!(bounds(&s, b), Rect::new(25, 23, 35, 33));
+ assert_eq!(bounds(&s, c), Rect::new(50, 50, 60, 60));
+ s.undo();
+ assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10));
+ assert_eq!(bounds(&s, b), Rect::new(20, 20, 30, 30));
+ // Select Linked Layers from just a.
+ s.execute("layer.selectLinkedLayers", json!({})).unwrap();
+ assert_eq!(sel(&s), vec![a, b]);
+ // Multi-selection translate moves all selected (c added, unlinked).
+ s.execute("layer.select", json!({"layer": c.0, "mode": "toggle"})).unwrap();
+ s.execute("layer.translate", json!({"dx": -1, "dy": 0})).unwrap();
+ assert_eq!(bounds(&s, c), Rect::new(49, 50, 59, 60));
+ assert_eq!(bounds(&s, a), Rect::new(-1, 0, 9, 10));
+ // Toggle: linking the same group again unlinks.
+ select_all(&mut s, &[a, b]);
+ assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false);
+ assert!(doc(&s).layer(a).unwrap().link_group.is_none());
+ }
+ }
+
+ #[test]
+ fn selection_pruned_after_delete_and_undo() {
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ select_all(&mut s, &[a, c]);
+ // Deleting one layer explicitly prunes it from the set.
+ s.execute("layer.delete", json!({"layer": a.0})).unwrap();
+ assert_eq!(sel(&s), vec![c]);
+ s.undo();
+ assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some()));
+ // Deleting with several selected removes them all, then selects the layer below.
+ select_all(&mut s, &[a, c]);
+ s.execute("layer.delete", json!({})).unwrap();
+ assert!(doc(&s).layer(a).is_none() && doc(&s).layer(c).is_none());
+ assert_eq!(doc(&s).layer_count(), 2);
+ assert_eq!(sel(&s).len(), 1);
+ assert!(s.active().unwrap().selected_layers.iter().all(|id| doc(&s).layer(*id).is_some()));
+ s.undo();
+ assert_eq!(doc(&s).layer_count(), 4);
+ let _ = b;
+ // Redo then undo again keeps the set valid.
+ s.redo();
+ assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some()));
+ }
+
+ #[test]
+ fn duplicate_hide_lock_and_reverse_selected() {
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ select_all(&mut s, &[a, c]);
+ let r = s.execute("layer.duplicate", json!({})).unwrap();
+ assert_eq!(r["layers"].as_array().unwrap().len(), 2);
+ assert_eq!(doc(&s).layer_count(), 6);
+ assert_eq!(sel(&s).len(), 2);
+ assert!(sel(&s).iter().all(|id| *id != a && *id != c));
+ s.undo();
+ select_all(&mut s, &[a, b]);
+ s.execute("layer.hideLayers", json!({})).unwrap();
+ assert!(!doc(&s).layer(a).unwrap().visible && !doc(&s).layer(b).unwrap().visible && doc(&s).layer(c).unwrap().visible);
+ s.execute("layer.showLayers", json!({})).unwrap();
+ assert!(doc(&s).layer(a).unwrap().visible);
+ s.execute("layer.lockLayers", json!({})).unwrap();
+ assert!(doc(&s).layer(a).unwrap().locks.all && doc(&s).layer(b).unwrap().locks.all);
+ assert!(s.execute("layer.translate", json!({"dx": 1})).is_err(), "locked layers don't move");
+ s.execute("layer.lockLayers", json!({})).unwrap();
+ assert!(!doc(&s).layer(a).unwrap().locks.all);
+ s.execute("layer.lockLayers", json!({"position": true})).unwrap();
+ assert!(doc(&s).layer(b).unwrap().locks.position && !doc(&s).layer(c).unwrap().locks.position);
+ // Reverse a, b, c.
+ select_all(&mut s, &[a, b, c]);
+ s.execute("layer.arrange.reverse", json!({})).unwrap();
+ assert_eq!(doc(&s).layers.iter().skip(1).map(|l| l.id).collect::<Vec<_>>(), vec![c, b, a]);
+ assert_eq!(s.active().unwrap().history.entries().last().map(|e| e.as_str()), Some("Reverse"));
+ }
+
+ #[test]
+ fn inspect_reports_selection() {
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ select_all(&mut s, &[a, b]);
+ let v = s.execute("document.inspect", json!({})).unwrap();
+ assert_eq!(v["selectedLayers"], json!([a.0, b.0]));
+ assert_eq!(v["layers"][0]["selected"], true);
+ }
+}
diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs
index 73f86086b..bd9bdfc78 100644
--- a/crates/engine/src/layer_style.rs
+++ b/crates/engine/src/layer_style.rs
@@ -103,6 +103,16 @@ pub fn effect_from_params(kind: &str, p: &Value) -> Option<Effect> {
}),
"colorOverlay" => Effect::ColorOverlay { common: common(p, BlendMode::Normal, 1.0), color: color(p, "color", [1.0, 0.0, 0.0]) },
"gradientOverlay" => Effect::GradientOverlay { common: common(p, BlendMode::Normal, 1.0), gradient: gradient(p), dither: false },
+ // `name` carries the requested pattern key; `set_effect` resolves it (pattern_cmds).
+ "patternOverlay" => Effect::PatternOverlay {
+ common: common(p, BlendMode::Normal, 1.0),
+ name: p.get("pattern").and_then(Value::as_str).unwrap_or("").to_string(),
+ id: String::new(),
+ scale: (f(p, "scale", 100.0) / 100.0).clamp(0.01, 10.0),
+ angle: f(p, "angle", 0.0),
+ link: b(p, "link", true),
+ phase: (f(p, "phaseX", 0.0), f(p, "phaseY", 0.0)),
+ },
"satin" => Effect::Satin(Satin {
common: common(p, BlendMode::Multiply, 0.5),
color: color(p, "color", [0.0; 3]),
@@ -145,6 +155,7 @@ fn same_kind(a: &Effect, b: &Effect) -> bool {
fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
let fx = effect_from_params(kind, p).ok_or_else(|| EngineError::Other(format!("unknown effect {kind}")))?;
+ let (fx, pattern) = crate::pattern_cmds::resolve_effect(s, fx)?;
let label = format!("Layer Style: {}", fx.label());
let add = b(p, "add", false);
let id = match p.get("layer").and_then(Value::as_u64) {
@@ -152,6 +163,9 @@ fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))?,
};
s.edit(&label, |doc, _| {
+ if let Some(pat) = &pattern {
+ crate::pattern_cmds::ensure_in_doc(doc, pat);
+ }
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
l.effects.enabled = true;
match l.effects.items.iter_mut().find(|e| same_kind(e, &fx)) {
@@ -193,6 +207,7 @@ pub fn specs() -> Vec<CommandSpec> {
style_cmd!("stroke", "Stroke…", r##"{"size":px=3,"position":"outside|inside|center","color":"#rrggbb","from":"#rrggbb","to":"#rrggbb","style":str,"angle":deg,"opacity":0..100,"blend":str,"add":bool}"##),
style_cmd!("colorOverlay", "Color Overlay…", r##"{"color":"#rrggbb","opacity":0..100=100,"blend":str,"add":bool}"##),
style_cmd!("gradientOverlay", "Gradient Overlay…", r##"{"from":"#rrggbb","to":"#rrggbb","style":"linear|radial|angle|reflected|diamond","angle":deg=90,"scale":10..150=100,"reverse":bool,"opacity":0..100,"blend":str,"add":bool}"##),
+ style_cmd!("patternOverlay", "Pattern Overlay…", r##"{"pattern":id|name?=first library pattern,"opacity":0..100=100,"blend":str,"scale":1..1000=100,"angle":deg=0,"link":bool=true,"phaseX":px,"phaseY":px,"add":bool}"##),
style_cmd!("bevelEmboss", "Bevel & Emboss…", r##"{"style":"inner|outer|emboss|pillow","depth":1..1000=100,"direction":"up|down","size":px=5,"soften":px,"angle":deg,"altitude":deg,"add":bool}"##),
style_cmd!("satin", "Satin…", r##"{"color":"#rrggbb","opacity":0..100=50,"blend":str,"angle":deg,"distance":px,"size":px,"invert":bool,"add":bool}"##),
CommandSpec {
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index f41003301..d8f22160f 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -6,10 +6,15 @@
//! server. This is what makes the UI swappable and the app fully scriptable.
#![forbid(unsafe_code)]
+pub mod adjust_cmds;
+pub mod layer_menu_cmds;
+pub mod mode_cmds;
+pub mod channel_cmds;
pub mod commands;
pub mod inspect;
pub mod layer_style;
pub mod filters;
+pub mod filters_ext;
pub mod type_cmds;
pub mod transform_cmds;
pub mod vector_cmds;
@@ -18,8 +23,21 @@ pub mod edit_cmds;
pub mod retouch_cmds;
pub mod image_cmds;
pub mod paint_cmds;
+pub mod pattern_cmds;
+pub mod warp_cmds;
pub mod selection_cmds;
+pub mod brush_cmds;
+pub mod extra_cmds;
+pub mod color_cmds;
+pub mod layer_multi_cmds;
+pub mod smart_cmds;
+pub mod file_cmds;
+pub mod type_extra_cmds;
mod pixels;
+pub mod prefs;
+pub mod snap;
+pub mod edit_menu_cmds;
+pub mod align_cmds;
use std::sync::Arc;
@@ -30,6 +48,7 @@ use serde_json::Value;
pub use commands::{CommandSpec, command_specs};
pub use photocraft_doc as doc;
pub use photocraft_paint::BrushSettings;
+pub use photocraft_paint as paint;
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
@@ -54,7 +73,14 @@ pub type Result<T> = std::result::Result<T, EngineError>;
pub struct DocState {
pub doc: Arc<Document>,
pub history: History,
+ /// The primary ("key") layer: what single-layer commands act on. Always a member of
+ /// `selected_layers` when set.
pub active_layer: Option<LayerId>,
+ /// Every selected layer in the Layers panel (⌘/⇧-click), in selection order. Like
+ /// `active_layer` this is UI state, not history; see [`DocState::selected_layers`].
+ pub selected_layers: Vec<LayerId>,
+ /// Anchor of ⇧-click range selection (the last plainly or ⌘-clicked layer).
+ pub layer_anchor: Option<LayerId>,
pub path: Option<String>,
/// Increments on every change; UIs re-render when it moves.
pub revision: u64,
@@ -63,12 +89,37 @@ pub struct DocState {
pub last_damage: Option<photocraft_geom::Rect>,
/// Coalescing key of the latest history step (see [`Session::execute`]'s `coalesce` param).
pub coalesce: Option<String>,
+ /// Channels panel: targeted channel and eye toggles (view state, not history).
+ pub channel_view: channel_cmds::ChannelView,
}
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, coalesce: None }
+ Self {
+ doc: Arc::new(doc),
+ history: History::default(),
+ active_layer,
+ selected_layers: active_layer.into_iter().collect(),
+ layer_anchor: active_layer,
+ path,
+ revision: 1,
+ saved_revision: 1,
+ last_damage: None,
+ coalesce: None,
+ channel_view: Default::default(),
+ }
+ }
+ /// The selected layers in bottom-to-top document order, always including the active layer.
+ /// Robust against stale state: ids no longer in the document are skipped, and if the active
+ /// layer was changed without updating the set, the selection is just the active layer.
+ pub fn selected_layers(&self) -> Vec<LayerId> {
+ let Some(active) = self.active_layer else { return Vec::new() };
+ let set: &[LayerId] = if self.selected_layers.contains(&active) { &self.selected_layers } else { std::slice::from_ref(&active) };
+ self.doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect()
+ }
+ pub fn is_layer_selected(&self, id: LayerId) -> bool {
+ self.active_layer == Some(id) || (self.active_layer.is_some_and(|a| self.selected_layers.contains(&a)) && self.selected_layers.contains(&id))
}
pub fn is_dirty(&self) -> bool {
self.revision != self.saved_revision
@@ -81,11 +132,21 @@ pub struct ToolState {
pub foreground: [f32; 4],
pub background: [f32; 4],
pub brush: photocraft_paint::BrushSettings,
+ /// Brush presets (built-ins plus user presets; see `brush.presets.*`).
+ pub presets: Vec<photocraft_paint::BrushPreset>,
+ /// Mixer Brush paint carried between strokes.
+ pub mixer: photocraft_paint::mixer::MixerState,
}
impl Default for ToolState {
fn default() -> Self {
- Self { foreground: [0.0, 0.0, 0.0, 1.0], background: [1.0, 1.0, 1.0, 1.0], brush: Default::default() }
+ Self {
+ foreground: [0.0, 0.0, 0.0, 1.0],
+ background: [1.0, 1.0, 1.0, 1.0],
+ brush: Default::default(),
+ presets: photocraft_paint::presets::builtin(),
+ mixer: Default::default(),
+ }
}
}
@@ -100,6 +161,24 @@ pub struct Session {
coalesce_request: Option<String>,
/// Pixels copied with Edit › Copy / Cut (shared by all documents, like Photoshop).
pub clipboard: Option<edit_cmds::Clip>,
+ /// Layer › Layer Style › Copy Layer Style: effects, blend mode and fill opacity.
+ pub style_clipboard: Option<(photocraft_doc::Effects, photocraft_color::BlendMode, f32)>,
+ /// Colour management: proofing state, monitor profile, display transforms.
+ pub color: color_cmds::ColorState,
+ /// Open Edit Contents documents and the smart objects they update.
+ pub smart_links: Vec<smart_cmds::SmartLink>,
+ /// Type › Save Default Type Styles: character and paragraph style new type layers start from.
+ pub type_defaults: Option<(photocraft_doc::text::CharStyle, photocraft_doc::text::ParagraphStyle)>,
+ /// Quick Mask Options (colour, opacity, colour indicates) used when entering Quick Mask.
+ pub quick_mask_options: channel_cmds::QuickMaskOptions,
+ /// Colour channel the running command may change (a single colour channel is targeted).
+ color_restrict: Option<usize>,
+ /// Edit › Preferences, keyboard shortcuts, menu and toolbar customisation (see `prefs`).
+ pub prefs: prefs::PrefsStore,
+ /// Edit menu state: Fade source, custom shape library (see `edit_menu_cmds`).
+ pub edit_state: edit_menu_cmds::EditState,
+ /// The pattern library (Window › Patterns; see `pattern.*`).
+ pub patterns: pattern_cmds::PatternLibrary,
}
impl Session {
@@ -130,7 +209,9 @@ impl Session {
/// Add a document (from File → New, an import, etc.) and make it active.
pub fn add_document(&mut self, doc: Document, path: Option<String>) -> usize {
- self.docs.push(DocState::new(doc, path));
+ let mut st = DocState::new(doc, path);
+ st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize;
+ self.docs.push(st);
let i = self.docs.len() - 1;
self.active = Some(i);
i
@@ -140,6 +221,7 @@ impl Session {
if index >= self.docs.len() {
return None;
}
+ smart_cmds::on_close(self, index);
let d = self.docs.remove(index);
self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) };
Some(d)
@@ -156,9 +238,14 @@ impl Session {
return Err(EngineError::Disabled(id.to_string(), why));
}
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()));
+ // Pixel commands follow the Channels panel target unless the caller names one.
+ let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone()));
+ self.color_restrict = channel_cmds::color_restriction(self, id, &run_params);
+ let r = (spec.run)(self, &run_params);
self.coalesce_request = None;
+ self.color_restrict = None;
let r = r?;
+ edit_menu_cmds::after_command(self, id);
if spec.journal {
self.journal.push((id.to_string(), params));
}
@@ -172,13 +259,19 @@ impl Session {
/// Apply an undoable edit to the active document.
pub fn edit<R>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option<LayerId>) -> Result<R>) -> Result<R> {
+ let restrict = self.color_restrict;
let st = self.active_mut().ok_or(EngineError::NoDocument)?;
let before = st.doc.clone();
let mut doc = (*before).clone();
let mut active = st.active_layer;
let r = f(&mut doc, &mut active)?;
+ if let (Some(k), Some(id)) = (restrict, active) {
+ channel_cmds::restrict_to_color(&before, &mut doc, id, k);
+ }
st.doc = Arc::new(doc);
st.active_layer = active;
+ fix_selection(st);
+ channel_cmds::fix_view(st);
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() {
@@ -197,6 +290,8 @@ impl Session {
return Err(EngineError::NoLayer(id));
}
st.active_layer = Some(id);
+ st.selected_layers = vec![id];
+ st.layer_anchor = Some(id);
// Selecting a layer is not an edit: keep a clean document clean.
let clean = st.saved_revision == st.revision;
st.revision += 1;
@@ -242,6 +337,28 @@ fn fix_active(st: &mut DocState) {
if st.active_layer.is_none_or(|id| st.doc.layer(id).is_none()) {
st.active_layer = st.doc.top_layer();
}
+ fix_selection(st);
+ channel_cmds::fix_view(st);
+}
+
+/// Keep the layer selection valid after the document or the active layer changed: drop deleted
+/// layers, and collapse to the active layer when a command made a non-member active.
+pub(crate) fn fix_selection(st: &mut DocState) {
+ let Some(active) = st.active_layer else {
+ st.selected_layers.clear();
+ return;
+ };
+ if !st.selected_layers.contains(&active) {
+ st.selected_layers = vec![active];
+ } else {
+ let live: std::collections::HashSet<LayerId> = st.doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ st.selected_layers.retain(|id| live.contains(id));
+ let mut seen = std::collections::HashSet::new();
+ st.selected_layers.retain(|id| seen.insert(*id));
+ }
+ if st.layer_anchor.is_some_and(|a| !st.selected_layers.contains(&a)) {
+ st.layer_anchor = Some(active);
+ }
}
#[cfg(test)]
diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/mode_cmds.rs
new file mode 100644
index 000000000..2f5e6ddc9
--- /dev/null
+++ b/crates/engine/src/mode_cmds.rs
@@ -0,0 +1,681 @@
+//! Image menu remnants: Image Rotation › Arbitrary, and the palette / ink modes — Mode › Indexed
+//! Color, Color Table, Bitmap and Duotone.
+//!
+//! Indexed, Bitmap and Duotone documents keep expanded pixels (RGB 8-bit / Gray 8-bit / Gray, see
+//! `Document::pixel_format`): Indexed and Bitmap quantise the flattened image in place and record
+//! the palette (`Document::color_table`) or the 1-bit look; Duotone keeps the gray pixels and the
+//! inks (`Document::duotone`), which display and flat export render through. Like Photoshop the
+//! conversions flatten (Indexed, Bitmap) and require a grayscale source (Bitmap, Duotone).
+
+use photocraft_algo::quantize::{self, BitmapMethod, Dither, Forced, HalftoneShape, PaletteKind};
+use photocraft_algo::transform::{Homography, Interp};
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_doc::adjust::CurvePoint;
+use photocraft_doc::{
+ ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size,
+};
+use photocraft_geom::Affine;
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams {
+ cmd: cmd.into(),
+ msg: msg.into(),
+ }
+}
+
+fn num(p: &Value, key: &str, default: f32) -> f32 {
+ p.get(key)
+ .and_then(Value::as_f64)
+ .map_or(default, |v| v as f32)
+}
+
+fn str_or<'a>(p: &'a Value, key: &str, default: &'a str) -> &'a str {
+ p.get(key).and_then(Value::as_str).unwrap_or(default)
+}
+
+type Enabled = std::result::Result<(), String>;
+
+fn has_doc(s: &Session) -> Enabled {
+ s.active()
+ .map(|_| ())
+ .ok_or_else(|| "no document open".into())
+}
+
+fn mode_is(s: &Session, modes: &[ColorMode], what: &str) -> Enabled {
+ let d = s.active().ok_or("no document open")?;
+ if modes.contains(&d.doc.mode) {
+ Ok(())
+ } else {
+ Err(format!("{what} (the document is {:?})", d.doc.mode))
+ }
+}
+
+// ---------- Image Rotation › Arbitrary ----------
+
+/// Canvas size after rotating `size` by `deg` (the canvas grows to fit, as in Photoshop).
+pub fn rotated_size(size: Size, deg: f64) -> Size {
+ let (s, c) = deg.to_radians().sin_cos();
+ let (w, h) = (f64::from(size.width), f64::from(size.height));
+ let nw = (w * c.abs() + h * s.abs() - 1e-6).ceil().max(1.0);
+ let nh = (w * s.abs() + h * c.abs() - 1e-6).ceil().max(1.0);
+ Size::new(nw as u32, nh as u32)
+}
+
+fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.rotation.arbitrary";
+ let angle = f64::from(num(p, "angle", 0.0));
+ if !angle.is_finite() || angle.abs() > 3600.0 {
+ return Err(bad(CMD, "angle out of range"));
+ }
+ let deg = match str_or(p, "direction", "cw") {
+ "cw" => angle,
+ "ccw" => -angle,
+ d => return Err(bad(CMD, format!("direction `{d}` (cw|ccw)"))),
+ };
+ if deg.rem_euclid(360.0).abs() < 1e-9 {
+ return Ok(
+ json!({"width": s.active().map(|d| d.doc.size.width), "height": s.active().map(|d| d.doc.size.height)}),
+ );
+ }
+ let bg = s.tools.background;
+ let size = s.edit("Rotate Canvas", |doc, _| {
+ let old = doc.size;
+ let new = rotated_size(old, deg);
+ let (sn, cs) = deg.to_radians().sin_cos();
+ let (cx, cy) = (f64::from(old.width) / 2.0, f64::from(old.height) / 2.0);
+ let (nx, ny) = (f64::from(new.width) / 2.0, f64::from(new.height) / 2.0);
+ // Clockwise on screen (y down): x' = c·x − s·y, y' = s·x + c·y about the centres.
+ let a = Affine {
+ m: [
+ cs,
+ sn,
+ -sn,
+ cs,
+ nx - (cs * cx - sn * cy),
+ ny - (sn * cx + cs * cy),
+ ],
+ };
+ let h = Homography([
+ a.m[0], a.m[2], a.m[4], a.m[1], a.m[3], a.m[5], 0.0, 0.0, 1.0,
+ ]);
+ let interp = Interp::parse(str_or(p, "interpolation", "bicubic"));
+ doc.size = new;
+ let canvas = doc.bounds();
+ let fmt = doc.pixel_format();
+ for l in doc.layers.iter_mut() {
+ let background = l.name == "Background"
+ && l.locks.position
+ && matches!(l.content, LayerContent::Raster(_));
+ if background {
+ // The Background stays a Background: rotated pixels over the background colour.
+ let surf = l.surface_mut().expect("raster");
+ let src = surf.content_bounds();
+ let rotated = photocraft_algo::transform::warp_surface(surf, src, &h, interp);
+ let mut base = Surface::new(fmt);
+ let fill = photocraft_raster::from_rgba(&fmt, bg);
+ base.write_region(
+ canvas,
+ &fill.repeat(canvas.width() as usize * canvas.height() as usize),
+ );
+ crate::transform_cmds::composite_over(&mut base, &rotated);
+ base.prune();
+ *surf = base;
+ if let Some(m) = l.mask.as_mut() {
+ m.surface = crate::transform_cmds::warp_gray(&m.surface, &h, interp);
+ }
+ } else {
+ // Rotating the whole image moves locked layers too.
+ let locks = l.locks;
+ l.locks.position = false;
+ l.locks.all = false;
+ crate::transform_cmds::transform_layer(None, l, &h, Some(a), interp)?;
+ l.locks = locks;
+ }
+ }
+ for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
+ ch.surface = crate::transform_cmds::warp_gray(&ch.surface, &h, interp);
+ }
+ if let Some(sel) = &doc.selection {
+ doc.selection = Some(crate::transform_cmds::warp_gray(sel, &h, Interp::Bilinear))
+ .filter(|s| !s.content_bounds().is_empty());
+ }
+ // Type and smart objects re-render from their new transforms.
+ let ids: Vec<LayerId> = doc
+ .walk()
+ .iter()
+ .filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_) | LayerContent::Smart(_)))
+ .map(|(_, _, l)| l.id)
+ .collect();
+ for id in ids {
+ let snapshot = doc.clone();
+ if let Some(l) = doc.layer_mut(id) {
+ crate::transform_cmds::refresh_text(&snapshot, l);
+ }
+ }
+ doc.guides = Default::default();
+ Ok(new)
+ })?;
+ Ok(json!({"width": size.width, "height": size.height}))
+}
+
+// ---------- flatten helpers ----------
+
+/// The flattened image as straight RGBA (over white when `opaque`).
+fn composite(doc: &Document, opaque: bool) -> Vec<[f32; 4]> {
+ let buf = photocraft_compose::flatten(doc);
+ if opaque {
+ buf.over_background([1.0, 1.0, 1.0]).px
+ } else {
+ buf.px
+ }
+}
+
+/// Replace the document's layers by one 8-bit layer holding `px` in `mode`'s storage format.
+fn single_layer(
+ doc: &mut Document,
+ active: &mut Option<LayerId>,
+ mode: ColorMode,
+ px: &[[f32; 4]],
+ name: &str,
+ background: bool,
+) {
+ doc.mode = mode;
+ doc.depth = SampleType::U8;
+ let fmt = doc.pixel_format();
+ let data: Vec<f32> = px
+ .iter()
+ .flat_map(|q| photocraft_raster::from_rgba(&fmt, *q))
+ .collect();
+ let mut l = Layer::raster(name, fmt);
+ if background {
+ l.locks.transparency = true;
+ l.locks.position = true;
+ }
+ l.surface_mut()
+ .expect("raster")
+ .write_region(doc.bounds(), &data);
+ *active = Some(l.id);
+ doc.layers = vec![l];
+ for ch in doc.channels.iter_mut() {
+ let f = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false);
+ ch.surface = ch.surface.convert(PixelFormat {
+ alpha: ch.surface.format().alpha,
+ ..f
+ });
+ }
+ doc.quick_mask = None;
+ doc.color_table = None;
+ doc.duotone = None;
+}
+
+// ---------- Indexed Color / Color Table ----------
+
+fn parse_forced(s: &str) -> Option<Forced> {
+ Some(match s {
+ "none" => Forced::None,
+ "blackWhite" | "blackAndWhite" => Forced::BlackWhite,
+ "primaries" => Forced::Primaries,
+ "web" => Forced::Web,
+ _ => return None,
+ })
+}
+
+fn parse_dither(s: &str) -> Option<Dither> {
+ Some(match s {
+ "none" => Dither::None,
+ "diffusion" => Dither::Diffusion,
+ "pattern" => Dither::Pattern,
+ "noise" => Dither::Noise,
+ _ => return None,
+ })
+}
+
+fn indexed_color(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.mode.indexedColor";
+ let kind = PaletteKind::from_id(str_or(p, "palette", "selective")).ok_or_else(|| {
+ bad(
+ CMD,
+ "palette: exact|systemMac|systemWindows|web|uniform|perceptual|selective|adaptive",
+ )
+ })?;
+ let forced = parse_forced(str_or(p, "forced", "blackWhite"))
+ .ok_or_else(|| bad(CMD, "forced: none|blackWhite|primaries|web"))?;
+ let dither = parse_dither(str_or(p, "dither", "diffusion"))
+ .ok_or_else(|| bad(CMD, "dither: none|diffusion|pattern|noise"))?;
+ let colors = num(p, "colors", 256.0).clamp(2.0, 256.0) as usize;
+ let amount = num(p, "amount", 75.0).clamp(0.0, 100.0) / 100.0;
+ let transparency = p
+ .get("transparency")
+ .and_then(Value::as_bool)
+ .unwrap_or(true);
+ let (pal_len, transparent) = s.edit("Indexed Color", |doc, active| {
+ let mut px = composite(doc, !transparency);
+ let has_clear = transparency && px.iter().any(|q| q[3] < 0.5);
+ let mut pal = quantize::build_palette(
+ &px,
+ kind,
+ if has_clear {
+ colors.saturating_sub(1).max(2)
+ } else {
+ colors
+ },
+ forced,
+ )
+ .map_err(|e| bad(CMD, e))?;
+ let transparent = if has_clear && pal.len() < 256 {
+ pal.push([255, 255, 255]);
+ Some(pal.len() - 1)
+ } else {
+ None
+ };
+ let w = doc.size.width as usize;
+ quantize::quantize(&mut px, w, &pal, dither, amount, transparent);
+ single_layer(
+ doc,
+ active,
+ ColorMode::Indexed,
+ &px,
+ if transparent.is_some() {
+ "Index"
+ } else {
+ "Background"
+ },
+ transparent.is_none(),
+ );
+ doc.color_table = Some(ColorTable {
+ colors: pal.clone(),
+ transparent: transparent.map(|t| t as u8),
+ });
+ Ok((pal.len(), transparent))
+ })?;
+ Ok(json!({"colors": pal_len, "transparentIndex": transparent}))
+}
+
+fn hex(c: [u8; 3]) -> String {
+ format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])
+}
+
+fn parse_color(v: &Value) -> Option<[u8; 3]> {
+ match v {
+ Value::String(s) => {
+ let s = s.trim_start_matches('#');
+ let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok();
+ Some([b(0)?, b(2)?, b(4)?])
+ }
+ Value::Array(a) if a.len() >= 3 => {
+ let c = |i: usize| a[i].as_f64().map(|x| x.round().clamp(0.0, 255.0) as u8);
+ Some([c(0)?, c(1)?, c(2)?])
+ }
+ _ => None,
+ }
+}
+
+/// Built-in Color Table presets.
+pub fn preset_table(name: &str) -> Option<Vec<[u8; 3]>> {
+ let ramp = |f: &dyn Fn(f32) -> [f32; 3]| {
+ (0..256)
+ .map(|i| f(i as f32 / 255.0).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8))
+ .collect()
+ };
+ Some(match name {
+ "grayscale" => ramp(&|t| [t; 3]),
+ // Black → red → yellow → white, the incandescence scale.
+ "blackBody" => ramp(&|t| {
+ [
+ (t * 3.0).min(1.0),
+ (t * 3.0 - 1.0).clamp(0.0, 1.0),
+ (t * 3.0 - 2.0).clamp(0.0, 1.0),
+ ]
+ }),
+ "spectrum" => ramp(&|t| {
+ let h = t * 300.0 / 60.0;
+ let x = 1.0 - (h % 2.0 - 1.0).abs();
+ match h as i32 {
+ 0 => [1.0, x, 0.0],
+ 1 => [x, 1.0, 0.0],
+ 2 => [0.0, 1.0, x],
+ 3 => [0.0, x, 1.0],
+ _ => [x, 0.0, 1.0],
+ }
+ }),
+ "systemMac" | "system" => quantize::mac_palette(),
+ "systemWindows" => quantize::windows_palette(),
+ "web" => quantize::web_palette(),
+ _ => return None,
+ })
+}
+
+/// Image › Mode › Color Table: replace entries (pixels keep their index, so their colour follows
+/// the table, as in Photoshop) and set the transparent entry. No changes: report the table.
+fn color_table(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.mode.colorTable";
+ let cur = s
+ .active()
+ .ok_or(EngineError::NoDocument)?
+ .doc
+ .color_table
+ .clone()
+ .ok_or_else(|| EngineError::Other("the document has no color table".into()))?;
+ let mut table = cur.clone();
+ match str_or(p, "table", "custom") {
+ "custom" => {}
+ name => {
+ table.colors =
+ preset_table(name).ok_or_else(|| bad(CMD, format!("unknown table `{name}`")))?
+ }
+ }
+ if let Some(a) = p.get("colors").and_then(Value::as_array) {
+ let c: Option<Vec<[u8; 3]>> = a.iter().map(parse_color).collect();
+ let c = c.ok_or_else(|| bad(CMD, "colors: [\"#rrggbb\" | [r, g, b], …]"))?;
+ if c.is_empty() || c.len() > 256 {
+ return Err(bad(CMD, "a color table has 1 to 256 entries"));
+ }
+ table.colors = c;
+ }
+ if let Some(e) = p.get("entries").and_then(Value::as_object) {
+ for (k, v) in e {
+ let i: usize = k
+ .parse()
+ .map_err(|_| bad(CMD, format!("entry index `{k}`")))?;
+ let c = parse_color(v).ok_or_else(|| bad(CMD, format!("entry {i}: bad colour")))?;
+ if i >= table.colors.len() {
+ return Err(bad(
+ CMD,
+ format!(
+ "entry {i} is past the table ({} entries)",
+ table.colors.len()
+ ),
+ ));
+ }
+ table.colors[i] = c;
+ }
+ }
+ match p.get("transparent") {
+ Some(Value::Null) => table.transparent = None,
+ Some(v) => {
+ table.transparent = v
+ .as_u64()
+ .filter(|&i| (i as usize) < table.colors.len())
+ .map(|i| i as u8)
+ .or(table.transparent)
+ }
+ None => {}
+ }
+ let report = |t: &ColorTable| json!({"colors": t.colors.iter().map(|c| hex(*c)).collect::<Vec<_>>(), "transparent": t.transparent});
+ if table == cur {
+ return Ok(report(&cur));
+ }
+ let out = report(&table);
+ s.edit("Color Table", |doc, _| {
+ let old = cur.clone();
+ for surf in doc.layers.iter_mut().filter_map(Layer::surface_mut) {
+ let r = surf.content_bounds();
+ if r.is_empty() {
+ continue;
+ }
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let mut data = surf.read_region(r);
+ for q in data.chunks_exact_mut(n) {
+ let c = photocraft_raster::to_rgba(&fmt, q);
+ if c[3] <= 0.0 {
+ continue;
+ }
+ let i = old.nearest([c[0], c[1], c[2]]);
+ let alpha = if table.transparent == Some(i as u8) {
+ 0.0
+ } else {
+ c[3]
+ };
+ let nc = if i < table.colors.len() {
+ table.rgb(i)
+ } else {
+ table.rgb(table.nearest([c[0], c[1], c[2]]))
+ };
+ let mut enc = [0.0f32; 8];
+ let m =
+ photocraft_raster::from_rgba_into(&fmt, [nc[0], nc[1], nc[2], alpha], &mut enc);
+ q.copy_from_slice(&enc[..m]);
+ }
+ surf.write_region(r, &data);
+ surf.prune();
+ }
+ doc.color_table = Some(table.clone());
+ Ok(())
+ })?;
+ Ok(out)
+}
+
+// ---------- Bitmap ----------
+
+fn bitmap(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.mode.bitmap";
+ let dpi = s
+ .active()
+ .ok_or(EngineError::NoDocument)?
+ .doc
+ .resolution_dpi
+ .max(1.0);
+ let method = match str_or(p, "method", "diffusion") {
+ "threshold" | "threshold50" => BitmapMethod::Threshold,
+ "pattern" => BitmapMethod::Pattern,
+ "diffusion" => BitmapMethod::Diffusion,
+ "halftone" => {
+ let freq = num(p, "frequency", 53.0).clamp(1.0, 999.0);
+ BitmapMethod::Halftone {
+ cell: (dpi / freq).max(2.0),
+ angle: num(p, "angle", 45.0),
+ shape: HalftoneShape::from_id(str_or(p, "shape", "round")),
+ }
+ }
+ m => {
+ return Err(bad(
+ CMD,
+ format!("method `{m}` (threshold|pattern|diffusion|halftone)"),
+ ));
+ }
+ };
+ s.edit("Bitmap", |doc, active| {
+ let px = composite(doc, true);
+ let mut gray: Vec<f32> = px
+ .iter()
+ .map(|q| photocraft_color::convert::rgb_to_gray([q[0], q[1], q[2]]))
+ .collect();
+ quantize::to_bitmap(&mut gray, doc.size.width as usize, method);
+ let out: Vec<[f32; 4]> = gray.iter().map(|g| [*g, *g, *g, 1.0]).collect();
+ single_layer(doc, active, ColorMode::Bitmap, &out, "Background", true);
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+// ---------- Duotone ----------
+
+/// Default inks per type: black first, then warm brown, gold and slate blue (generic names;
+/// Photoshop ships Pantone presets, which we don't reproduce).
+fn default_inks(n: usize) -> Vec<DuotoneInk> {
+ let all = [
+ ("Black", [0.0, 0.0, 0.0]),
+ ("Warm Brown", [0.62, 0.38, 0.18]),
+ ("Gold", [0.86, 0.68, 0.18]),
+ ("Slate Blue", [0.27, 0.38, 0.58]),
+ ];
+ all.iter()
+ .take(n)
+ .map(|(name, c)| DuotoneInk::new(*name, *c))
+ .collect()
+}
+
+fn parse_inks(cmd: &str, v: &Value, n: usize) -> Result<Vec<DuotoneInk>> {
+ let a = v.as_array().ok_or_else(|| {
+ bad(
+ cmd,
+ "inks: [{\"name\",\"color\":\"#rrggbb\",\"curve\":[[in,out],…] (0..100)}, …]",
+ )
+ })?;
+ let defaults = default_inks(n.max(a.len()).min(4));
+ let mut out = Vec::new();
+ for (i, ink) in a.iter().take(4).enumerate() {
+ let mut d = defaults
+ .get(i)
+ .cloned()
+ .unwrap_or_else(|| DuotoneInk::new(format!("Ink {}", i + 1), [0.0; 3]));
+ if let Some(name) = ink.get("name").and_then(Value::as_str) {
+ d.name = name.to_string();
+ }
+ if let Some(c) = ink.get("color").and_then(parse_color) {
+ d.color = c.map(|v| f32::from(v) / 255.0);
+ }
+ if let Some(pts) = ink.get("curve").and_then(Value::as_array) {
+ let mut curve: Vec<CurvePoint> = pts
+ .iter()
+ .filter_map(|p| {
+ Some(CurvePoint {
+ input: p.get(0)?.as_f64()? as f32 / 100.0,
+ output: p.get(1)?.as_f64()? as f32 / 100.0,
+ })
+ })
+ .collect();
+ curve.sort_by(|a, b| a.input.total_cmp(&b.input));
+ if curve.len() >= 2 {
+ d.curve = curve;
+ }
+ }
+ out.push(d);
+ }
+ Ok(out)
+}
+
+fn duotone(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.mode.duotone";
+ let n = match str_or(p, "type", "duotone") {
+ "monotone" => 1,
+ "duotone" => 2,
+ "tritone" => 3,
+ "quadtone" => 4,
+ t => {
+ return Err(bad(
+ CMD,
+ format!("type `{t}` (monotone|duotone|tritone|quadtone)"),
+ ));
+ }
+ };
+ let mut inks = match p.get("inks") {
+ Some(v) => parse_inks(CMD, v, n)?,
+ None => default_inks(n),
+ };
+ if inks.len() < n {
+ inks.extend(default_inks(n).into_iter().skip(inks.len()));
+ }
+ inks.truncate(n);
+ let names: Vec<String> = inks.iter().map(|i| i.name.clone()).collect();
+ s.edit("Duotone", |doc, _| {
+ doc.mode = ColorMode::Duotone;
+ doc.duotone = Some(Duotone {
+ inks,
+ psd_raw: None,
+ });
+ doc.color_table = None;
+ Ok(())
+ })?;
+ Ok(json!({"inks": names}))
+}
+
+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 }
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!(
+ "image.rotation.arbitrary",
+ "Arbitrary…",
+ ["Image", "Image Rotation"],
+ r##"{"angle":-359.99..359.99=0,"direction":"cw|ccw"="cw","interpolation":"bicubic|bilinear|nearest"="bicubic"}"##,
+ has_doc,
+ rotate_arbitrary
+ ),
+ spec!(
+ "image.mode.indexedColor",
+ "Indexed Color…",
+ ["Image", "Mode"],
+ r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens)"##,
+ |s| mode_is(
+ s,
+ &[
+ ColorMode::Rgb,
+ ColorMode::Grayscale,
+ ColorMode::Indexed,
+ ColorMode::Duotone,
+ ColorMode::Cmyk,
+ ColorMode::Lab
+ ],
+ "Indexed Color needs an RGB or Grayscale image"
+ ),
+ indexed_color
+ ),
+ spec!(
+ "image.mode.colorTable",
+ "Color Table…",
+ ["Image", "Mode"],
+ r##"{"table":"custom|blackBody|grayscale|spectrum|systemMac|systemWindows|web"="custom","colors":json,"entries":json,"transparent":json} (colors: ["#rrggbb", …]; entries: {"index": "#rrggbb"}; transparent: index|null)"##,
+ |s| mode_is(
+ s,
+ &[ColorMode::Indexed],
+ "Color Table needs an Indexed Color image"
+ ),
+ color_table
+ ),
+ spec!(
+ "image.mode.bitmap",
+ "Bitmap…",
+ ["Image", "Mode"],
+ r##"{"method":"diffusion|threshold|pattern|halftone"="diffusion","frequency":1..999=53,"angle":-180..180=45,"shape":"round|ellipse|line|square|diamond|cross"="round"} (halftone frequency in lines/inch; flattens)"##,
+ |s| mode_is(
+ s,
+ &[ColorMode::Grayscale],
+ "Bitmap needs a Grayscale image (Image › Mode › Grayscale first)"
+ ),
+ bitmap
+ ),
+ spec!(
+ "image.mode.duotone",
+ "Duotone…",
+ ["Image", "Mode"],
+ r##"{"type":"duotone|monotone|tritone|quadtone"="duotone","inks":json} (inks: [{"name","color":"#rrggbb","curve":[[in,out],…] in 0..100}, …])"##,
+ |s| mode_is(
+ s,
+ &[ColorMode::Grayscale, ColorMode::Duotone],
+ "Duotone needs a Grayscale image (Image › Mode › Grayscale first)"
+ ),
+ duotone
+ ),
+ ]
+}
+
+/// The gradient-map layer that renders Duotone inks over the gray composite.
+pub fn duotone_display_layer(d: &Duotone) -> Layer {
+ Layer::new("Duotone", LayerContent::Adjustment(d.display_adjustment()))
+}
+
+/// A copy of `doc` that displays like the printed result (Duotone inks), or None when the
+/// document displays as stored.
+pub fn display_document(doc: &Document) -> Option<Document> {
+ let d = doc
+ .duotone
+ .as_ref()
+ .filter(|_| doc.mode == ColorMode::Duotone)?;
+ let mut out = doc.clone();
+ out.layers.push(duotone_display_layer(d));
+ Some(out)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/mode_cmds/tests.rs b/crates/engine/src/mode_cmds/tests.rs
new file mode 100644
index 000000000..5d4a44ed1
--- /dev/null
+++ b/crates/engine/src/mode_cmds/tests.rs
@@ -0,0 +1,349 @@
+use super::*;
+use photocraft_geom::Rect;
+
+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();
+ paint(&mut s, |x, y| {
+ [x as f32 / w as f32, y as f32 / h as f32, 0.5, 1.0]
+ });
+ s
+}
+
+fn paint(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 doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+}
+
+fn colours(d: &Document) -> std::collections::HashSet<[u8; 3]> {
+ let surf = d.layers[0].surface().unwrap();
+ let mut set = std::collections::HashSet::new();
+ for y in 0..d.size.height as i32 {
+ for x in 0..d.size.width as i32 {
+ let c = surf.rgba(x, y);
+ if c[3] > 0.0 {
+ set.insert([c[0], c[1], c[2]].map(|v| (v * 255.0).round() as u8));
+ }
+ }
+ }
+ set
+}
+
+#[test]
+fn rotate_arbitrary_grows_canvas_and_keeps_background() {
+ for depth in [8, 16, 32] {
+ let mut s = session(40, 20, depth, "rgb");
+ s.execute("layer.new.layer", json!({})).unwrap();
+ paint(&mut s, |x, y| {
+ if (15..25).contains(&x) && (5..15).contains(&y) {
+ [1.0, 0.0, 0.0, 1.0]
+ } else {
+ [0.0; 4]
+ }
+ });
+ s.execute("tools.setColors", json!({"background": "#00ff00"}))
+ .unwrap();
+ let r = s
+ .execute(
+ "image.rotation.arbitrary",
+ json!({"angle": 90, "direction": "cw"}),
+ )
+ .unwrap();
+ assert_eq!(
+ (r["width"].as_u64(), r["height"].as_u64()),
+ (Some(20), Some(40))
+ );
+ let d = doc(&s);
+ assert_eq!(d.layers[0].name, "Background");
+ // The red square stays centred.
+ assert!(
+ d.layers[1].surface().unwrap().rgba(10, 20)[0] > 0.9,
+ "{depth}"
+ );
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute(
+ "image.rotation.arbitrary",
+ json!({"angle": 30, "direction": "ccw"}),
+ )
+ .unwrap();
+ let d = doc(&s);
+ assert_eq!(d.size, rotated_size(Size::new(40, 20), 30.0));
+ assert!(d.size.width > 40 && d.size.height > 20);
+ // Exposed corners take the background colour on the Background layer.
+ let corner = d.layers[0].surface().unwrap().rgba(0, 0);
+ assert!(corner[1] > 0.9 && corner[0] < 0.1, "{corner:?}");
+ }
+ let mut s = session(10, 10, 8, "rgb");
+ assert!(
+ s.execute(
+ "image.rotation.arbitrary",
+ json!({"angle": 10, "direction": "up"})
+ )
+ .is_err()
+ );
+ let n = s.active().unwrap().history.past_len();
+ s.execute("image.rotation.arbitrary", json!({"angle": 360}))
+ .unwrap();
+ assert_eq!(
+ s.active().unwrap().history.past_len(),
+ n,
+ "a full turn changes nothing"
+ );
+}
+
+#[test]
+fn rotate_arbitrary_other_modes() {
+ for mode in ["gray", "cmyk", "lab"] {
+ let mut s = session(16, 12, 16, mode);
+ s.execute("image.rotation.arbitrary", json!({"angle": 45}))
+ .unwrap();
+ assert_eq!(
+ doc(&s).size,
+ rotated_size(Size::new(16, 12), 45.0),
+ "{mode}"
+ );
+ }
+}
+
+#[test]
+fn indexed_color_palettes_and_dithers() {
+ for palette in [
+ "selective",
+ "perceptual",
+ "adaptive",
+ "web",
+ "uniform",
+ "systemMac",
+ "systemWindows",
+ ] {
+ for dither in ["none", "diffusion", "pattern", "noise"] {
+ let mut s = session(24, 16, 16, "rgb");
+ let r = s
+ .execute(
+ "image.mode.indexedColor",
+ json!({"palette": palette, "colors": 16, "dither": dither, "forced": "none"}),
+ )
+ .unwrap();
+ let d = doc(&s);
+ assert_eq!(
+ (d.mode, d.depth),
+ (ColorMode::Indexed, SampleType::U8),
+ "{palette} {dither}"
+ );
+ let table = d.color_table.as_ref().unwrap();
+ assert_eq!(table.colors.len() as u64, r["colors"].as_u64().unwrap());
+ let used = colours(d);
+ assert!(
+ used.iter().all(|c| table.colors.contains(c)),
+ "{palette} {dither}: pixels off the table"
+ );
+ if !matches!(palette, "web" | "systemMac" | "systemWindows") {
+ assert!(
+ table.colors.len() <= 16,
+ "{palette}: {}",
+ table.colors.len()
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn indexed_exact_transparency_and_sources() {
+ // Two colours + transparency: exact palette with a transparent entry.
+ let mut s = Session::new();
+ s.execute(
+ "file.new",
+ json!({"width": 8, "height": 8, "background": "transparent"}),
+ )
+ .unwrap();
+ paint(&mut s, |x, _| {
+ if x < 3 {
+ [1.0, 0.0, 0.0, 1.0]
+ } else if x < 6 {
+ [0.0, 0.0, 1.0, 1.0]
+ } else {
+ [0.0; 4]
+ }
+ });
+ s.execute(
+ "image.mode.indexedColor",
+ json!({"palette": "exact", "forced": "none"}),
+ )
+ .unwrap();
+ let d = doc(&s);
+ let t = d.color_table.as_ref().unwrap();
+ assert_eq!(t.colors.len(), 3);
+ assert_eq!(t.transparent, Some(2));
+ assert_eq!(d.layers[0].name, "Index");
+ assert_eq!(d.layers[0].surface().unwrap().rgba(7, 0)[3], 0.0);
+ // Exact fails on a gradient.
+ let mut s = session(64, 64, 8, "rgb");
+ assert!(
+ s.execute("image.mode.indexedColor", json!({"palette": "exact"}))
+ .is_err()
+ );
+ // Gray, CMYK and Lab sources flatten through the composite.
+ for mode in ["gray", "cmyk", "lab"] {
+ let mut s = session(12, 12, 16, mode);
+ s.execute("image.mode.indexedColor", json!({"colors": 8}))
+ .unwrap();
+ assert_eq!(doc(&s).mode, ColorMode::Indexed, "{mode}");
+ }
+ // Back to RGB drops the table.
+ s.execute("image.mode.indexedColor", json!({"colors": 8}))
+ .unwrap();
+ s.execute("image.mode.rgb", json!({})).unwrap();
+ assert!(doc(&s).color_table.is_none());
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(doc(&s).color_table.is_some());
+}
+
+#[test]
+fn color_table_presets_and_entries() {
+ let mut s = session(16, 16, 8, "rgb");
+ assert!(!s.is_enabled("image.mode.colorTable"));
+ s.execute(
+ "image.mode.indexedColor",
+ json!({"palette": "uniform", "colors": 8, "dither": "none", "forced": "none"}),
+ )
+ .unwrap();
+ let before = doc(&s).color_table.clone().unwrap();
+ // No changes: a report, no history step.
+ let n = s.active().unwrap().history.past_len();
+ let r = s.execute("image.mode.colorTable", json!({})).unwrap();
+ assert_eq!(r["colors"].as_array().unwrap().len(), before.colors.len());
+ assert_eq!(s.active().unwrap().history.past_len(), n);
+ // Replace entry 0: pixels of index 0 change colour.
+ let px0 = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
+ let i0 = before.nearest([px0[0], px0[1], px0[2]]);
+ s.execute(
+ "image.mode.colorTable",
+ json!({"entries": {i0.to_string(): "#ff00ff"}}),
+ )
+ .unwrap();
+ assert_eq!(
+ doc(&s).layers[0].surface().unwrap().rgba(0, 0),
+ [1.0, 0.0, 1.0, 1.0]
+ );
+ s.execute("image.mode.colorTable", json!({"table": "blackBody"}))
+ .unwrap();
+ assert_eq!(doc(&s).color_table.as_ref().unwrap().colors.len(), 256);
+ s.execute("image.mode.colorTable", json!({"transparent": 0}))
+ .unwrap();
+ assert!(
+ s.execute("image.mode.colorTable", json!({"table": "nope"}))
+ .is_err()
+ );
+ assert!(
+ s.execute(
+ "image.mode.colorTable",
+ json!({"entries": {"999": "#000000"}})
+ )
+ .is_err()
+ );
+}
+
+#[test]
+fn bitmap_methods_need_grayscale() {
+ let mut s = session(32, 32, 16, "rgb");
+ assert!(!s.is_enabled("image.mode.bitmap"));
+ s.execute("image.mode.grayscale", json!({})).unwrap();
+ for method in ["threshold", "pattern", "diffusion", "halftone"] {
+ s.execute(
+ "image.mode.bitmap",
+ json!({"method": method, "frequency": 12, "shape": "diamond"}),
+ )
+ .unwrap();
+ let d = doc(&s);
+ assert_eq!(
+ (d.mode, d.depth),
+ (ColorMode::Bitmap, SampleType::U8),
+ "{method}"
+ );
+ let surf = d.layers[0].surface().unwrap();
+ for y in 0..32 {
+ for x in 0..32 {
+ let v = surf.pixel(x, y)[0];
+ assert!(v == 0.0 || v == 1.0, "{method}: {v}");
+ }
+ }
+ s.execute("edit.undo", json!({})).unwrap();
+ }
+ assert!(
+ s.execute("image.mode.bitmap", json!({"method": "nope"}))
+ .is_err()
+ );
+}
+
+#[test]
+fn duotone_inks_and_display() {
+ let mut s = session(16, 8, 8, "gray");
+ paint(&mut s, |x, _| [x as f32 / 15.0; 4].map(|v| v.min(1.0)));
+ assert!(
+ s.execute("image.mode.duotone", json!({"type": "quintone"}))
+ .is_err()
+ );
+ let r = s.execute("image.mode.duotone", json!({"type": "duotone", "inks": [{"name": "Black"}, {"name": "Orange", "color": "#ff8000", "curve": [[0, 0], [100, 80]]}]})).unwrap();
+ assert_eq!(r["inks"], json!(["Black", "Orange"]));
+ let d = doc(&s);
+ assert_eq!(d.mode, ColorMode::Duotone);
+ let inks = &d.duotone.as_ref().unwrap().inks;
+ assert_eq!(inks[1].curve.last().unwrap().output, 0.8);
+ // Display: warm midtones (red > blue) where the gray image is neutral.
+ let shown = display_document(d).unwrap();
+ let px = photocraft_compose::render(&shown, Rect::from_xywh(8, 4, 1, 1)).px[0];
+ assert!(px[0] > px[2] + 0.05, "{px:?}");
+ assert!(
+ display_document(&Document::new(
+ "x",
+ Size::new(1, 1),
+ ColorMode::Grayscale,
+ SampleType::U8
+ ))
+ .is_none()
+ );
+ // Tritone defaults and leaving the mode.
+ s.execute("image.mode.duotone", json!({"type": "tritone"}))
+ .unwrap();
+ assert_eq!(doc(&s).duotone.as_ref().unwrap().inks.len(), 3);
+ s.execute("image.mode.grayscale", json!({})).unwrap();
+ assert!(doc(&s).duotone.is_none());
+ assert_eq!(doc(&s).mode, ColorMode::Grayscale);
+ assert!(!session(4, 4, 8, "rgb").is_enabled("image.mode.duotone"));
+}
+
+#[test]
+fn modes_round_trip_through_pcraft() {
+ let mut s = session(12, 12, 8, "rgb");
+ s.execute("image.mode.indexedColor", json!({"colors": 6}))
+ .unwrap();
+ let bytes = photocraft_format::save_to_bytes(doc(&s), &Default::default()).unwrap();
+ let back = photocraft_format::load_from_bytes(&bytes).unwrap();
+ assert_eq!(back.color_table, doc(&s).color_table);
+ assert_eq!(back.mode, ColorMode::Indexed);
+}
diff --git a/crates/engine/src/paint_cmds.rs b/crates/engine/src/paint_cmds.rs
index 1757036ca..adaadd564 100644
--- a/crates/engine/src/paint_cmds.rs
+++ b/crates/engine/src/paint_cmds.rs
@@ -42,8 +42,7 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
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 (surf, _) = crate::channel_cmds::target_surface(doc, *active, p)?;
let ok = bucket_fill(surf, area, (x, y), tol, contiguous, aa, c, opacity, sel.as_ref());
surf.prune();
Ok(ok)
@@ -74,8 +73,7 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
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)?;
+ let (surf, _) = crate::channel_cmds::target_surface(doc, *active, p)?;
paint_gradient(surf, area, from, to, shape, &stops, reverse, opacity, blend, sel.as_ref());
Ok(())
})?;
@@ -90,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
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}"##,
+ params: r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"color":"#rrggbb"=foreground,"opacity":1..100=100,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,
enabled: crate::commands::has_paintable,
run: bucket,
journal: true,
@@ -100,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
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"}"##,
+ 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","target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,
enabled: crate::commands::has_paintable,
run: gradient,
journal: true,
diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/pattern_cmds.rs
new file mode 100644
index 000000000..ccd72891b
--- /dev/null
+++ b/crates/engine/src/pattern_cmds.rs
@@ -0,0 +1,545 @@
+//! Patterns: Edit › Define Pattern, the pattern library (`pattern.*`), Layer › New Fill Layer ›
+//! Pattern, Edit › Fill with a pattern and brush textures from library patterns.
+//!
+//! Two places hold patterns, as in Photoshop:
+//! - the **library** ([`PatternLibrary`], on the [`Session`]): built-in procedural patterns plus
+//! defined and imported ones. Library edits are app state, not document history.
+//! - the **document** ([`photocraft_doc::Document::patterns`]): the patterns its layers use
+//! (saved in PSD `Patt` blocks and `.pcraft`). Commands that apply a pattern copy it into the
+//! document in the same history step, so a document always renders on its own.
+//!
+//! Patterns are referenced by `"pattern": id | name` (document first, then library).
+
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_doc::{Color, Document, Fill, Layer, LayerContent, Pattern, Rect};
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, layer_param};
+use crate::{EngineError, Result, Session};
+
+/// The app-level pattern library (Window › Patterns).
+#[derive(Clone, Debug)]
+pub struct PatternLibrary {
+ pub items: Vec<Pattern>,
+}
+
+impl Default for PatternLibrary {
+ fn default() -> Self {
+ PatternLibrary { items: builtin() }
+ }
+}
+
+fn hash01(x: u32, y: u32, seed: u32) -> f32 {
+ let mut h = x.wrapping_mul(0x8da6_b343) ^ y.wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f);
+ h ^= h >> 13;
+ h = h.wrapping_mul(0x5bd1_e995);
+ h ^= h >> 15;
+ (h & 0xffff) as f32 / 65535.0
+}
+
+fn procedural(name: &str, w: u32, h: u32, f: impl Fn(u32, u32) -> [f32; 3]) -> Pattern {
+ let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, false);
+ let mut s = Surface::new(fmt);
+ let mut px = Vec::with_capacity((w * h * 3) as usize);
+ for y in 0..h {
+ for x in 0..w {
+ px.extend_from_slice(&f(x, y));
+ }
+ }
+ // Quantise through the 8-bit surface so ids are stable.
+ s.write_region(Rect::new(0, 0, w as i32, h as i32), &px);
+ Pattern::new(name, s, w, h)
+}
+
+/// Built-in patterns: generated procedurally here (our own, CC0), so the library is never empty.
+pub fn builtin() -> Vec<Pattern> {
+ let g = |v: f32| [v, v, v];
+ vec![
+ procedural("Checkerboard", 16, 16, |x, y| g(if (x / 8 + y / 8) % 2 == 0 { 0.8 } else { 1.0 })),
+ procedural("Diagonal Lines", 8, 8, |x, y| g(if (x + y) % 8 < 2 { 0.2 } else { 1.0 })),
+ procedural("Dots", 12, 12, |x, y| {
+ let (dx, dy) = (x as f32 + 0.5 - 6.0, y as f32 + 0.5 - 6.0);
+ g(((dx * dx + dy * dy).sqrt() - 3.0).clamp(0.0, 1.0))
+ }),
+ procedural("Grid", 16, 16, |x, y| g(if x == 0 || y == 0 { 0.55 } else { 1.0 })),
+ procedural("Bricks", 32, 16, |x, y| {
+ let row = y / 8;
+ let xo = (x + if row % 2 == 1 { 8 } else { 0 }) % 16;
+ let mortar = y % 8 == 7 || xo == 15;
+ let n = hash01(x, y, 7) * 0.08;
+ if mortar { [0.78 + n, 0.76 + n, 0.72 + n] } else { [0.62 + n, 0.27 + n * 0.5, 0.2] }
+ }),
+ procedural("Weave", 16, 16, |x, y| {
+ let over = ((x / 4) + (y / 4)) % 2 == 0;
+ let t = if over { (y % 4) as f32 / 3.0 } else { (x % 4) as f32 / 3.0 };
+ let v = 0.55 + 0.35 * (1.0 - (2.0 * t - 1.0).abs());
+ [v, v * 0.92, v * 0.8]
+ }),
+ procedural("Paper Noise", 64, 64, |x, y| {
+ // Two octaves of smoothed value noise (wraps at 64 px).
+ let oct = |cell: u32, seed: u32| {
+ let (cx, cy) = (x / cell, y / cell);
+ let (fx, fy) = ((x % cell) as f32 / cell as f32, (y % cell) as f32 / cell as f32);
+ let n = 64 / cell;
+ let v = |i: u32, j: u32| hash01(i % n, j % n, seed);
+ let s = |t: f32| t * t * (3.0 - 2.0 * t);
+ let (sx, sy) = (s(fx), s(fy));
+ let a = v(cx, cy) + (v(cx + 1, cy) - v(cx, cy)) * sx;
+ let b = v(cx, cy + 1) + (v(cx + 1, cy + 1) - v(cx, cy + 1)) * sx;
+ a + (b - a) * sy
+ };
+ g(0.78 + 0.14 * oct(8, 1) + 0.08 * oct(2, 2))
+ }),
+ ]
+}
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn always(_: &Session) -> std::result::Result<(), String> {
+ Ok(())
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn has_pattern(s: &Session) -> std::result::Result<(), String> {
+ if s.patterns.items.is_empty() && s.active().is_none_or(|d| d.doc.patterns.is_empty()) { Err("no patterns".into()) } else { Ok(()) }
+}
+
+/// Finds a pattern by id or name: the active document's first, then the library. An empty key
+/// picks the first library pattern (Photoshop's default).
+pub fn resolve(s: &Session, key: &str) -> Option<Pattern> {
+ if key.is_empty() {
+ return s.patterns.items.first().cloned();
+ }
+ if let Some(d) = s.active()
+ && let Some(p) = photocraft_doc::pattern::find(&d.doc.patterns, key, key)
+ {
+ return Some(p.clone());
+ }
+ photocraft_doc::pattern::find(&s.patterns.items, key, key).cloned()
+}
+
+fn resolve_param(s: &Session, cmd: &str, p: &Value) -> Result<Pattern> {
+ let key = p.get("pattern").and_then(Value::as_str).unwrap_or("");
+ resolve(s, key).ok_or_else(|| bad(cmd, format!("no pattern \"{key}\" (see pattern.list)")))
+}
+
+/// Copies `pat` into the document's patterns unless it is already there (by id).
+pub fn ensure_in_doc(doc: &mut Document, pat: &Pattern) {
+ if !doc.patterns.iter().any(|p| p.id == pat.id) {
+ doc.patterns.push(pat.clone());
+ }
+}
+
+/// Resolves the pattern of a Pattern Overlay / pattern stroke built from params (its `name`
+/// holds the requested key) into a real pattern: returns the effect with name and id filled in,
+/// plus the pattern to copy into the document.
+pub fn resolve_effect(s: &Session, fx: photocraft_doc::Effect) -> Result<(photocraft_doc::Effect, Option<Pattern>)> {
+ use photocraft_doc::Effect;
+ match fx {
+ Effect::PatternOverlay { common, name, id, scale, angle, link, phase } => {
+ let key = if id.is_empty() { name } else { id };
+ let pat = resolve(s, &key).ok_or_else(|| bad("layer.layerStyle.patternOverlay", format!("no pattern \"{key}\" (see pattern.list)")))?;
+ Ok((Effect::PatternOverlay { common, name: pat.name.clone(), id: pat.id.clone(), scale, angle, link, phase }, Some(pat)))
+ }
+ other => Ok((other, None)),
+ }
+}
+
+fn info(p: &Pattern, in_doc: bool, in_library: bool) -> Value {
+ let f = p.surface.format();
+ json!({
+ "id": p.id, "name": p.display_name(), "storedName": p.name, "width": p.width, "height": p.height,
+ "mode": format!("{:?}", f.mode), "depth": format!("{:?}", f.sample), "alpha": f.alpha,
+ "inDocument": in_doc, "inLibrary": in_library,
+ })
+}
+
+fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ let doc_pats: Vec<Pattern> = s.active().map(|d| d.doc.patterns.clone()).unwrap_or_default();
+ let mut out: Vec<Value> = s.patterns.items.iter().map(|p| info(p, doc_pats.iter().any(|d| d.id == p.id), true)).collect();
+ out.extend(doc_pats.iter().filter(|d| !s.patterns.items.iter().any(|p| p.id == d.id)).map(|p| info(p, true, false)));
+ Ok(Value::Array(out))
+}
+
+/// The visible composite over `r` as a surface in the document's pixel format (with alpha).
+fn composite_surface(doc: &Document, r: Rect) -> Surface {
+ let buf = photocraft_compose::render(doc, r);
+ let df = doc.pixel_format();
+ let fmt = PixelFormat::new(df.mode, df.sample, true);
+ let n = fmt.channels();
+ let mut px = vec![0.0f32; buf.px.len() * n];
+ for (o, p) in px.chunks_exact_mut(n).zip(&buf.px) {
+ photocraft_raster::from_rgba_into(&fmt, *p, o);
+ }
+ let mut s = Surface::new(fmt);
+ s.write_region(Rect::new(0, 0, r.width() as i32, r.height() as i32), &px);
+ s
+}
+
+fn define(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.definePattern";
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = &st.doc;
+ let r = match p.get("rect").and_then(Value::as_array) {
+ Some(a) if a.len() == 4 => {
+ let v: Vec<i32> = a.iter().map(|x| x.as_f64().unwrap_or(0.0).round() as i32).collect();
+ Rect::new(v[0], v[1], v[2], v[3])
+ }
+ _ => doc.selection.as_ref().map_or(doc.bounds(), |m| m.content_bounds()),
+ }
+ .intersect(&doc.bounds());
+ if r.is_empty() {
+ return Err(bad(cmd, "the area is empty"));
+ }
+ if r.width() > 4000 || r.height() > 4000 {
+ return Err(bad(cmd, "patterns are limited to 4000 × 4000 px"));
+ }
+ let mut surf = composite_surface(doc, r);
+ // Opaque patterns drop their alpha channel (as Photoshop does).
+ let fmt = surf.format();
+ let px = surf.read_region(Rect::new(0, 0, r.width() as i32, r.height() as i32));
+ if px.chunks_exact(fmt.channels()).all(|q| q[fmt.channels() - 1] >= 1.0) {
+ surf = surf.convert(PixelFormat::new(fmt.mode, fmt.sample, false));
+ }
+ let name = match p.get("name").and_then(Value::as_str) {
+ Some(n) if !n.trim().is_empty() => n.to_string(),
+ _ => {
+ let base = std::path::Path::new(&doc.name).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "Pattern".into());
+ let mut i = 1;
+ loop {
+ let n = if i == 1 { base.clone() } else { format!("{base} {i}") };
+ if !s.patterns.items.iter().any(|q| q.name == n) {
+ break n;
+ }
+ i += 1;
+ }
+ }
+ };
+ let pat = Pattern::new(name, surf, r.width(), r.height());
+ let id = pat.id.clone();
+ let out = info(&pat, false, true);
+ if !s.patterns.items.iter().any(|q| q.id == id) {
+ s.patterns.items.push(pat);
+ }
+ Ok(json!({"pattern": id, "info": out}))
+}
+
+fn library_index(s: &Session, cmd: &str, p: &Value) -> Result<usize> {
+ let key = p.get("pattern").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing `pattern` (id or name)"))?;
+ let found = photocraft_doc::pattern::find(&s.patterns.items, key, key).map(|f| f.id.clone()).ok_or_else(|| bad(cmd, format!("no library pattern \"{key}\"")))?;
+ Ok(s.patterns.items.iter().position(|q| q.id == found).unwrap_or(0))
+}
+
+fn rename(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "pattern.rename";
+ let name = p.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).ok_or_else(|| bad(cmd, "missing `name`"))?.to_string();
+ let i = library_index(s, cmd, p)?;
+ let id = s.patterns.items[i].id.clone();
+ s.patterns.items[i].name = name.clone();
+ // A copy stored in the document is renamed too (a document edit, so undoable).
+ if s.active().is_some_and(|d| d.doc.patterns.iter().any(|q| q.id == id)) {
+ s.edit("Rename Pattern", |doc, _| {
+ for q in doc.patterns.iter_mut().filter(|q| q.id == id) {
+ q.name = name.clone();
+ }
+ Ok(())
+ })?;
+ }
+ Ok(json!({"pattern": id, "name": name}))
+}
+
+fn delete(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = library_index(s, "pattern.delete", p)?;
+ let pat = s.patterns.items.remove(i);
+ Ok(json!({"deleted": pat.id}))
+}
+
+fn import(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "pattern.import";
+ let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing `path` (.pat file)"))?;
+ let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ let pats = photocraft_io::pattern_map::read_pat(&bytes).map_err(EngineError::Other)?;
+ let mut ids = Vec::new();
+ for pat in pats {
+ ids.push(pat.id.clone());
+ match s.patterns.items.iter_mut().find(|q| q.id == pat.id) {
+ Some(q) => *q = pat,
+ None => s.patterns.items.push(pat),
+ }
+ }
+ Ok(json!({"imported": ids}))
+}
+
+fn export(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "pattern.export";
+ let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing `path`"))?;
+ let pats: Vec<Pattern> = match p.get("patterns").and_then(Value::as_array) {
+ Some(keys) => keys.iter().filter_map(Value::as_str).map(|k| resolve(s, k).ok_or_else(|| bad(cmd, format!("no pattern \"{k}\"")))).collect::<Result<_>>()?,
+ None => s.patterns.items.clone(),
+ };
+ let bytes = photocraft_io::pattern_map::write_pat(&pats).map_err(EngineError::Other)?;
+ std::fs::write(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ Ok(json!({"path": path, "count": pats.len(), "bytes": bytes.len()}))
+}
+
+fn placement(p: &Value) -> (f32, f32, bool, (f32, f32)) {
+ let num = |k: &str, d: f64| p.get(k).and_then(Value::as_f64).unwrap_or(d) as f32;
+ let phase = p.get("phase").and_then(Value::as_array).map_or((0.0, 0.0), |a| {
+ (a.first().and_then(Value::as_f64).unwrap_or(0.0) as f32, a.get(1).and_then(Value::as_f64).unwrap_or(0.0) as f32)
+ });
+ ((num("scale", 100.0) / 100.0).clamp(0.01, 10.0), num("angle", 0.0), p.get("link").and_then(Value::as_bool).unwrap_or(true), phase)
+}
+
+fn new_fill_layer(s: &mut Session, p: &Value) -> Result<Value> {
+ let pat = resolve_param(s, "layer.newFillLayer.pattern", p)?;
+ let (scale, angle, link, phase) = placement(p);
+ let id = s.edit("New Pattern Fill Layer", |doc, active| {
+ ensure_in_doc(doc, &pat);
+ let fill = Fill::Pattern { name: pat.name.clone(), scale, id: pat.id.clone(), angle, link, phase };
+ let l = Layer::new(doc.next_layer_name("Pattern Fill"), LayerContent::Fill(fill));
+ let id = doc.insert_above(*active, l);
+ *active = Some(id);
+ Ok(id)
+ })?;
+ Ok(json!({"layer": id.0, "pattern": pat.id}))
+}
+
+/// Edit › Fill with `"contents": "pattern"`: tiles the pattern over the selection (or the whole
+/// target), composited at `opacity` (Normal), respecting transparency locks.
+pub fn fill_with_pattern(s: &mut Session, p: &Value) -> Result<Value> {
+ let pat = resolve_param(s, "edit.fill", p)?;
+ let (scale, angle, _, phase) = placement(p);
+ let opacity = (p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0) as f32 / 100.0).clamp(0.0, 1.0);
+ let id = if crate::channel_cmds::is_channel_target(p) { None } else { Some(layer_param(s, p)?) };
+ let tile = photocraft_compose::pattern::Tile::new(&pat).ok_or_else(|| bad("edit.fill", "the pattern is empty"))?;
+ s.edit("Fill", |doc, _| {
+ let sel = doc.selection.clone();
+ let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds());
+ // Photoshop's Fill uses the canvas origin.
+ let place = photocraft_compose::pattern::Placement::new(Rect::EMPTY, false, phase, scale, angle);
+ let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let mut region = surf.read_region(area);
+ let src = photocraft_compose::pattern::render(&tile, &place, area);
+ let w = area.width() as usize;
+ for (i, (px, c)) in region.chunks_exact_mut(n).zip(&src).enumerate() {
+ let k = sel.as_ref().map_or(1.0, |m| m.sample_channel(area.x0 + (i % w) as i32, area.y0 + (i / w) as i32, 0)) * opacity;
+ if k <= 0.0 {
+ continue;
+ }
+ let d = photocraft_raster::to_rgba(&fmt, px);
+ let sa = c[3] * k;
+ let oa = sa + d[3] * (1.0 - sa);
+ let mut o = [0.0f32; 4];
+ if oa > 0.0 {
+ for ch in 0..3 {
+ o[ch] = (c[ch] * sa + d[ch] * d[3] * (1.0 - sa)) / oa;
+ }
+ }
+ o[3] = if lock || !fmt.alpha { d[3] } else { oa };
+ let mut enc = [0.0f32; 8];
+ photocraft_raster::from_rgba_into(&fmt, o, &mut enc);
+ px.copy_from_slice(&enc[..n]);
+ }
+ surf.write_region(area, &region);
+ Ok(())
+ })?;
+ Ok(json!({"pattern": pat.id}))
+}
+
+fn brush_texture(s: &mut Session, p: &Value) -> Result<Value> {
+ let pat = resolve_param(s, "brush.texturePattern", p)?;
+ // Brush textures are grey: luminance of the composite over white.
+ let mut px = vec![[0.0f32; 4]; (pat.width * pat.height) as usize];
+ pat.surface.read_rgba_into(pat.rect(), &mut px);
+ let lum: Vec<f32> = px.iter().map(|q| {
+ let l = 0.299 * q[0] + 0.587 * q[1] + 0.114 * q[2];
+ l * q[3] + (1.0 - q[3])
+ }).collect();
+ let tile = photocraft_paint::GrayTile::from_f32(pat.width, pat.height, &lum);
+ let t = &mut s.tools.brush.texture;
+ t.pattern = photocraft_paint::Pattern::Tile(tile);
+ t.enabled = p.get("enabled").and_then(Value::as_bool).unwrap_or(true);
+ if let Some(sc) = p.get("scale").and_then(Value::as_f64) {
+ t.scale = (sc as f32 / 100.0).clamp(0.01, 10.0);
+ }
+ Ok(json!({"pattern": pat.id}))
+}
+
+/// A swatch colour for UIs (average of the tile), straight RGB.
+pub fn average_color(p: &Pattern) -> Color {
+ let mut px = vec![[0.0f32; 4]; (p.width * p.height) as usize];
+ p.surface.read_rgba_into(p.rect(), &mut px);
+ let n = px.len().max(1) as f32;
+ let s = px.iter().fold([0.0f32; 3], |a, q| [a[0] + q[0], a[1] + q[1], a[2] + q[2]]);
+ Color::rgb(s[0] / n, s[1] / n, s[2] / n)
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec {
+ id: "edit.definePattern",
+ label: "Define Pattern…",
+ menu: &["Edit"],
+ shortcut: None,
+ params: r##"{"name":str?,"rect":[x0,y0,x1,y1]? (default: selection bounds, else the canvas)} → {"pattern":id} (added to the library; samples the visible composite)"##,
+ enabled: has_doc,
+ journal: true,
+ run: define,
+ },
+ CommandSpec { id: "pattern.list", label: "Patterns", menu: &[], shortcut: None, params: "{} → [{id,name,width,height,mode,depth,inDocument,inLibrary}]", enabled: always, journal: false, run: list },
+ CommandSpec { id: "pattern.rename", label: "Rename Pattern", menu: &[], shortcut: None, params: r##"{"pattern":id|name,"name":str}"##, enabled: has_pattern, journal: true, run: rename },
+ CommandSpec { id: "pattern.delete", label: "Delete Pattern", menu: &[], shortcut: None, params: r##"{"pattern":id|name} (library only; documents keep their copy)"##, enabled: has_pattern, journal: true, run: delete },
+ CommandSpec { id: "pattern.import", label: "Import Patterns…", menu: &[], shortcut: None, params: r##"{"path":".pat file"}"##, enabled: always, journal: true, run: import },
+ CommandSpec { id: "pattern.export", label: "Export Patterns…", menu: &[], shortcut: None, params: r##"{"path":".pat file","patterns":[id|name]? (default: the whole library)}"##, enabled: has_pattern, journal: true, run: export },
+ CommandSpec {
+ id: "layer.newFillLayer.pattern",
+ label: "Pattern…",
+ menu: &["Layer", "New Fill Layer"],
+ shortcut: None,
+ params: r##"{"pattern":id|name?=first library pattern,"scale":1..1000=100,"angle":deg=0,"link":bool=true,"phase":[x,y]?}"##,
+ enabled: has_doc,
+ journal: true,
+ run: new_fill_layer,
+ },
+ CommandSpec {
+ id: "brush.texturePattern",
+ label: "Brush Texture Pattern",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"pattern":id|name,"scale":1..1000?,"enabled":bool=true} (sets the session brush's Texture to that pattern)"##,
+ enabled: has_pattern,
+ journal: true,
+ run: brush_texture,
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::LayerId;
+
+ fn session(depth: u64) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap();
+ s
+ }
+
+ fn pixel(s: &Session, x: i32, y: i32) -> [f32; 4] {
+ let b = photocraft_compose::render(&s.active().unwrap().doc, Rect::new(x, y, x + 1, y + 1));
+ b.px[0]
+ }
+
+ #[test]
+ fn library_has_builtins_and_lists() {
+ let mut s = Session::new();
+ let v = s.execute("pattern.list", json!({})).unwrap();
+ assert!(v.as_array().unwrap().len() >= 6);
+ assert!(v[0]["id"].as_str().unwrap().len() == 36);
+ // Built-in ids are stable across sessions.
+ assert_eq!(builtin()[0].id, Session::new().patterns.items[0].id);
+ }
+
+ #[test]
+ fn define_rename_delete_and_pat_round_trip() {
+ let mut s = session(8);
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ s.execute("select.rect", json!({"x": 2, "y": 3, "width": 5, "height": 4})).unwrap();
+ let r = s.execute("edit.definePattern", json!({"name": "Red"})).unwrap();
+ let id = r["pattern"].as_str().unwrap().to_string();
+ let pat = resolve(&s, &id).unwrap();
+ assert_eq!((pat.width, pat.height), (5, 4));
+ assert!(!pat.surface.format().alpha, "opaque pattern drops alpha");
+ // Same content → same id (replayable); not duplicated.
+ let n = s.patterns.items.len();
+ s.execute("edit.definePattern", json!({"name": "Red"})).unwrap();
+ assert_eq!(s.patterns.items.len(), n);
+ s.execute("pattern.rename", json!({"pattern": id, "name": "Crimson"})).unwrap();
+ assert_eq!(resolve(&s, "Crimson").unwrap().id, id);
+ let dir = std::env::temp_dir().join(format!("pc-pat-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("lib.pat");
+ let path = path.to_str().unwrap();
+ s.execute("pattern.export", json!({"path": path})).unwrap();
+ s.execute("pattern.delete", json!({"pattern": "Crimson"})).unwrap();
+ assert!(resolve(&s, "Crimson").is_none());
+ assert!(s.execute("pattern.delete", json!({"pattern": "Crimson"})).is_err());
+ let v = s.execute("pattern.import", json!({"path": path})).unwrap();
+ assert!(v["imported"].as_array().unwrap().iter().any(|x| x == id.as_str()));
+ assert_eq!(resolve(&s, &id).unwrap().surface.read_region(Rect::new(0, 0, 5, 4)), pat.surface.read_region(Rect::new(0, 0, 5, 4)));
+ std::fs::remove_dir_all(dir).ok();
+ assert!(s.execute("pattern.import", json!({"path": "/nonexistent.pat"})).is_err());
+ }
+
+ #[test]
+ fn pattern_fill_layer_renders_at_every_depth_and_undoes() {
+ for depth in [8u64, 16, 32] {
+ let mut s = session(depth);
+ let r = s.execute("layer.newFillLayer.pattern", json!({"pattern": "Checkerboard"})).unwrap();
+ let id = LayerId(r["layer"].as_u64().unwrap());
+ let st = s.active().unwrap();
+ assert_eq!(st.doc.patterns.len(), 1, "copied into the document");
+ assert!(matches!(&st.doc.layer(id).unwrap().content, LayerContent::Fill(Fill::Pattern { .. })));
+ // Checkerboard: 8 px squares of 0.8 and 1.0 grey from the canvas origin.
+ let (a, b) = (pixel(&s, 1, 1), pixel(&s, 9, 1));
+ assert!((a[0] - 0.8).abs() < 0.01 && (b[0] - 1.0).abs() < 0.01, "{depth}: {a:?} {b:?}");
+ s.undo();
+ assert!(s.active().unwrap().doc.patterns.is_empty());
+ assert!(s.execute("layer.newFillLayer.pattern", json!({"pattern": "nope"})).is_err());
+ }
+ }
+
+ #[test]
+ fn fill_with_pattern_respects_selection() {
+ for depth in [8u64, 16, 32] {
+ let mut s = session(depth);
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
+ s.execute("edit.fill", json!({"contents": "pattern", "pattern": "Diagonal Lines"})).unwrap();
+ let st = s.active().unwrap();
+ let surf = st.doc.layers[0].surface().unwrap();
+ assert!(surf.pixel(0, 0)[0] < 0.3, "{depth}: line pixel");
+ assert!(surf.pixel(4, 0)[0] > 0.9);
+ assert!(surf.pixel(20, 20)[0] > 0.99, "outside the selection untouched");
+ }
+ }
+
+ #[test]
+ fn pattern_overlay_composes_with_an_outside_stroke() {
+ let mut s = session(8);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();
+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("layer.layerStyle.patternOverlay", json!({"pattern": "Diagonal Lines"})).unwrap();
+ s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#00ff00", "add": true})).unwrap();
+ let out = pixel(&s, 8, 15);
+ assert!(out[1] > 0.9 && out[0] < 0.1, "stroke outside: {out:?}");
+ }
+
+ #[test]
+ fn pattern_overlay_renders_and_brush_texture_uses_library() {
+ let mut s = session(16);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ s.execute("layer.layerStyle.patternOverlay", json!({"pattern": "Checkerboard", "opacity": 100})).unwrap();
+ let st = s.active().unwrap();
+ assert_eq!(st.doc.patterns.len(), 1);
+ let p = pixel(&s, 1, 1);
+ assert!((p[0] - 0.8).abs() < 0.01 && (p[2] - 0.8).abs() < 0.01, "{p:?}");
+ assert!(s.execute("layer.layerStyle.patternOverlay", json!({"pattern": "missing"})).is_err());
+ s.execute("layer.layerStyle.stroke", json!({"size": 4, "color": "#ffffff", "add": true})).unwrap();
+ let st = s.active().unwrap();
+ assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().effects.items.len(), 2);
+ s.execute("brush.texturePattern", json!({"pattern": "Dots", "scale": 50})).unwrap();
+ assert!(s.tools.brush.texture.enabled);
+ assert!(matches!(s.tools.brush.texture.pattern, photocraft_paint::Pattern::Tile(_)));
+ }
+}
diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs
index e216e9cf4..11331b56d 100644
--- a/crates/engine/src/pixels.rs
+++ b/crates/engine/src/pixels.rs
@@ -110,6 +110,9 @@ pub fn remap_document(doc: &mut Document, map: &dyn Fn(i32, i32) -> (i32, i32))
}
}
rec(&mut doc.layers, map);
+ for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
+ ch.surface = remap_surface(&ch.surface, map);
+ }
if let Some(sel) = &doc.selection {
doc.selection = Some(remap_surface(sel, map));
}
diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs
new file mode 100644
index 000000000..4d749d009
--- /dev/null
+++ b/crates/engine/src/prefs.rs
@@ -0,0 +1,1293 @@
+//! Persistent preferences (Edit › Preferences), keyboard-shortcut, menu and toolbar
+//! customisation, grouped like Photoshop's Preferences dialog sections.
+//!
+//! The whole set is plain serde data owned by the [`Session`] ([`Session::prefs`]), so every
+//! frontend reads the same values and agents change them with `prefs.get` / `prefs.set` /
+//! `prefs.reset`. Sections that only the GUI shell honours (cursors, checkerboard, guide colours,
+//! interface theme…) live here too: keeping one document means the headless MCP server sees and
+//! edits exactly what the desktop app persists, and the shell has no second store to keep in sync.
+//!
+//! The engine never touches the filesystem for preferences (it must build for wasm). Frontends
+//! persist [`Session::prefs_to_json`] wherever the platform keeps settings (the desktop app: the
+//! OS config directory; the web shell: browser storage) and restore it with
+//! [`Session::load_prefs_json`].
+//!
+//! Engine-side values are applied by [`Session::apply_prefs`]: the history state limit (every
+//! open document), the effect-cache memory budget, and units for commands that report lengths.
+//! Colour settings (`colorSettings`) are stored with the colour state
+//! ([`crate::color_cmds::ColorSettings`]) and persisted in the same document.
+
+use std::collections::BTreeMap;
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+/// A string-valued choice enum with its JSON names (used to validate `prefs.set` and to fill
+/// dropdowns in the Preferences dialog).
+macro_rules! choice {
+ ($(#[$m:meta])* $name:ident { $($var:ident = $s:literal),+ $(,)? } default $def:ident) => {
+ $(#[$m])*
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+ pub enum $name { $(#[serde(rename = $s)] $var),+ }
+ impl Default for $name {
+ fn default() -> Self { Self::$def }
+ }
+ impl $name {
+ pub const NAMES: &'static [&'static str] = &[$($s),+];
+ pub fn name(self) -> &'static str {
+ match self { $(Self::$var => $s),+ }
+ }
+ pub fn parse(s: &str) -> Option<Self> {
+ match s { $($s => Some(Self::$var),)+ _ => None }
+ }
+ }
+ };
+}
+
+choice!(
+ /// Length units for rulers, the Info panel and size dialogs.
+ Unit { Pixels = "pixels", Inches = "inches", Centimeters = "cm", Millimeters = "mm", Points = "points", Picas = "picas", Percent = "percent" } default Pixels
+);
+choice!(TypeUnit { Points = "points", Pixels = "pixels", Millimeters = "mm" } default Points);
+choice!(PointSize { PostScript = "postScript", Traditional = "traditional" } default PostScript);
+choice!(Interpolation { BicubicAutomatic = "bicubicAutomatic", Nearest = "nearestNeighbor", Bilinear = "bilinear", Bicubic = "bicubic", BicubicSmoother = "bicubicSmoother", BicubicSharper = "bicubicSharper", PreserveDetails = "preserveDetails" } default BicubicAutomatic);
+choice!(ColorPicker { Adobe = "adobe", System = "system" } default Adobe);
+choice!(Theme { Pro = "pro", Studio = "studio", StudioLight = "studioLight", Classic = "classic" } default Pro);
+choice!(CanvasColor { Default = "default", Black = "black", DarkGray = "darkGray", MediumGray = "mediumGray", LightGray = "lightGray", Custom = "custom" } default Default);
+choice!(CanvasBorder { DropShadow = "dropShadow", Line = "line", None = "none" } default DropShadow);
+choice!(UiScale { Auto = "auto", P100 = "100", P200 = "200" } default Auto);
+choice!(UiFontSize { Tiny = "tiny", Small = "small", Medium = "medium", Large = "large" } default Small);
+choice!(LogDestination { Metadata = "metadata", TextFile = "textFile", Both = "both" } default Metadata);
+choice!(LogDetail { SessionsOnly = "sessionsOnly", Concise = "concise", Detailed = "detailed" } default Concise);
+choice!(Ask { Always = "always", Never = "never", Ask = "ask" } default Always);
+choice!(QuickExportFormat { Png = "png", Jpg = "jpg", Gif = "gif", Webp = "webp" } default Png);
+choice!(ExportLocation { Ask = "ask", SameFolder = "sameFolder" } default Ask);
+choice!(ExportMetadata { None = "none", Copyright = "copyright", All = "all" } default Copyright);
+choice!(
+ /// Painting cursors: Standard (tool icon), Precise (crosshair), Normal Brush Tip (the 50%
+ /// opacity contour), Full Size Brush Tip (the whole diameter).
+ PaintingCursor { Standard = "standard", Precise = "precise", NormalTip = "normalTip", FullSizeTip = "fullSizeTip" } default NormalTip
+);
+choice!(OtherCursor { Standard = "standard", Precise = "precise" } default Standard);
+choice!(CheckerSize { None = "none", Small = "small", Medium = "medium", Large = "large" } default Medium);
+choice!(CheckerColors { Light = "light", Medium = "medium", Dark = "dark", Red = "red", Orange = "orange", Green = "green", Blue = "blue", Purple = "purple", Custom = "custom" } default Light);
+choice!(LineStyle { Lines = "lines", Dashed = "dashedLines", Dots = "dots" } default Lines);
+choice!(TextEngine { Modern = "modern", EastAsian = "eastAsian", WorldReady = "worldReady" } default WorldReady);
+choice!(FontPreview { Off = "off", Small = "small", Medium = "medium", Large = "large", ExtraLarge = "extraLarge", Huge = "huge" } default Medium);
+choice!(RawColorSpace { Srgb = "srgb", AdobeRgb = "adobeRgb", ProPhoto = "proPhoto", DisplayP3 = "displayP3" } default AdobeRgb);
+choice!(RawDepth { Eight = "8", Sixteen = "16" } default Sixteen);
+choice!(RawSharpen { None = "none", Screen = "screen", Glossy = "glossy", Matte = "matte" } default None);
+
+impl Unit {
+ /// Document pixels → this unit. `dpi` is the document resolution, `extent` the 100% length
+ /// (for percent), `ppi` points per inch (72 PostScript, 72.27 traditional).
+ pub fn from_px(self, px: f64, dpi: f64, extent: f64, ppi: f64) -> f64 {
+ let dpi = dpi.max(1e-6);
+ match self {
+ Unit::Pixels => px,
+ Unit::Inches => px / dpi,
+ Unit::Centimeters => px / dpi * 2.54,
+ Unit::Millimeters => px / dpi * 25.4,
+ Unit::Points => px / dpi * ppi,
+ Unit::Picas => px / dpi * ppi / 12.0,
+ Unit::Percent => px / extent.max(1e-6) * 100.0,
+ }
+ }
+ /// This unit → document pixels (inverse of [`Unit::from_px`]).
+ pub fn to_px(self, v: f64, dpi: f64, extent: f64, ppi: f64) -> f64 {
+ let dpi = dpi.max(1e-6);
+ match self {
+ Unit::Pixels => v,
+ Unit::Inches => v * dpi,
+ Unit::Centimeters => v / 2.54 * dpi,
+ Unit::Millimeters => v / 25.4 * dpi,
+ Unit::Points => v / ppi.max(1e-6) * dpi,
+ Unit::Picas => v * 12.0 / ppi.max(1e-6) * dpi,
+ Unit::Percent => v * extent / 100.0,
+ }
+ }
+ /// Short suffix for readouts ("px", "in", "cm", …).
+ pub fn suffix(self) -> &'static str {
+ match self {
+ Unit::Pixels => "px",
+ Unit::Inches => "in",
+ Unit::Centimeters => "cm",
+ Unit::Millimeters => "mm",
+ Unit::Points => "pt",
+ Unit::Picas => "pica",
+ Unit::Percent => "%",
+ }
+ }
+ /// Decimal places a readout in this unit needs.
+ pub fn decimals(self) -> usize {
+ match self {
+ Unit::Pixels => 0,
+ Unit::Points | Unit::Percent | Unit::Millimeters => 1,
+ _ => 2,
+ }
+ }
+}
+
+impl PointSize {
+ /// Points per inch.
+ pub fn per_inch(self) -> f64 {
+ match self {
+ PointSize::PostScript => 72.0,
+ PointSize::Traditional => 72.27,
+ }
+ }
+}
+
+// ------------------------------------------------------------------ sections
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct General {
+ pub color_picker: ColorPicker,
+ /// Default resampling for Image Size and transforms.
+ pub image_interpolation: Interpolation,
+ pub beep_when_done: bool,
+ pub export_clipboard: bool,
+ pub resize_image_during_place: bool,
+ pub always_create_smart_objects_when_placing: bool,
+ /// Scroll wheel zooms instead of panning.
+ pub zoom_with_scroll_wheel: bool,
+ pub animated_zoom: bool,
+ pub zoom_resizes_windows: bool,
+ pub use_legacy_free_transform: bool,
+ pub auto_show_home_screen: bool,
+}
+
+impl Default for General {
+ fn default() -> Self {
+ Self {
+ color_picker: ColorPicker::Adobe,
+ image_interpolation: Interpolation::BicubicAutomatic,
+ beep_when_done: false,
+ export_clipboard: true,
+ resize_image_during_place: true,
+ always_create_smart_objects_when_placing: true,
+ zoom_with_scroll_wheel: false,
+ animated_zoom: true,
+ zoom_resizes_windows: false,
+ use_legacy_free_transform: false,
+ auto_show_home_screen: true,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Interface {
+ pub theme: Theme,
+ /// Pasteboard colour in standard screen mode (`canvasCustomColor` when "custom").
+ pub canvas_color: CanvasColor,
+ pub canvas_custom_color: String,
+ /// Document border in standard screen mode.
+ pub canvas_border: CanvasBorder,
+ pub ui_scale: UiScale,
+ pub ui_font_size: UiFontSize,
+ pub show_channels_in_color: bool,
+ pub dynamic_color_sliders: bool,
+ /// Draw menu item colours set with Edit › Menus.
+ pub show_menu_colors: bool,
+ pub show_tooltips: bool,
+}
+
+impl Default for Interface {
+ fn default() -> Self {
+ Self {
+ theme: Theme::Pro,
+ canvas_color: CanvasColor::Default,
+ canvas_custom_color: "#282828".into(),
+ canvas_border: CanvasBorder::DropShadow,
+ ui_scale: UiScale::Auto,
+ ui_font_size: UiFontSize::Small,
+ show_channels_in_color: false,
+ dynamic_color_sliders: true,
+ show_menu_colors: true,
+ show_tooltips: true,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Workspace {
+ pub auto_collapse_icon_panels: bool,
+ pub auto_show_hidden_panels: bool,
+ pub open_documents_as_tabs: bool,
+ pub enable_floating_document_window_docking: bool,
+ pub large_tabs: bool,
+ pub enable_narrow_options_bar: bool,
+ pub remember_workspace_changes: bool,
+}
+
+impl Default for Workspace {
+ fn default() -> Self {
+ Self { auto_collapse_icon_panels: false, auto_show_hidden_panels: true, open_documents_as_tabs: true, enable_floating_document_window_docking: true, large_tabs: false, enable_narrow_options_bar: false, remember_workspace_changes: true }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Tools {
+ pub show_tooltips: bool,
+ /// Tool keys cycle a tool group only with ⇧ held (Photoshop's "Use Shift Key for Tool Switch").
+ pub use_shift_key_for_tool_switch: bool,
+ pub zoom_clicked_point_to_center: bool,
+ pub enable_flick_panning: bool,
+ pub vary_round_brush_hardness_on_hud: bool,
+ /// Round snapped vector and transform coordinates to whole pixels.
+ pub snap_vector_tools_and_transforms_to_pixel_grid: bool,
+ pub show_transformation_values: bool,
+ pub overscroll: bool,
+ pub double_click_layer_mask_launches_select_and_mask: bool,
+}
+
+impl Default for Tools {
+ fn default() -> Self {
+ Self {
+ show_tooltips: true,
+ use_shift_key_for_tool_switch: false,
+ zoom_clicked_point_to_center: false,
+ enable_flick_panning: true,
+ vary_round_brush_hardness_on_hud: true,
+ snap_vector_tools_and_transforms_to_pixel_grid: true,
+ show_transformation_values: true,
+ overscroll: true,
+ double_click_layer_mask_launches_select_and_mask: true,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct HistoryLog {
+ pub enabled: bool,
+ pub destination: LogDestination,
+ /// Text file the log is appended to (destination textFile/both).
+ pub file_path: String,
+ pub detail: LogDetail,
+}
+
+impl Default for HistoryLog {
+ fn default() -> Self {
+ Self { enabled: false, destination: LogDestination::Metadata, file_path: String::new(), detail: LogDetail::Concise }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct FileHandling {
+ pub image_previews: Ask,
+ pub lowercase_extension: bool,
+ pub save_in_background: bool,
+ /// Save recovery information (crash recovery autosave).
+ pub autosave: bool,
+ /// Minutes between autosaves of documents with unsaved changes.
+ pub autosave_minutes: u32,
+ /// Offer to reopen recovered documents at launch.
+ pub recover_on_launch: bool,
+ pub ignore_exif_profile_tag: bool,
+ pub ask_before_saving_layered_tiff: bool,
+ pub maximize_psd_compatibility: Ask,
+ pub recent_file_count: u32,
+ /// Most recently opened files, newest first (File › Open Recent).
+ pub recent_files: Vec<String>,
+}
+
+impl Default for FileHandling {
+ fn default() -> Self {
+ Self {
+ image_previews: Ask::Always,
+ lowercase_extension: true,
+ save_in_background: true,
+ autosave: true,
+ autosave_minutes: 10,
+ recover_on_launch: true,
+ ignore_exif_profile_tag: false,
+ ask_before_saving_layered_tiff: true,
+ maximize_psd_compatibility: Ask::Always,
+ recent_file_count: 20,
+ recent_files: Vec::new(),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Export {
+ pub quick_export_format: QuickExportFormat,
+ pub quick_export_location: ExportLocation,
+ pub jpeg_quality: u32,
+ pub metadata: ExportMetadata,
+ pub convert_to_srgb: bool,
+}
+
+impl Default for Export {
+ fn default() -> Self {
+ Self { quick_export_format: QuickExportFormat::Png, quick_export_location: ExportLocation::Ask, jpeg_quality: 85, metadata: ExportMetadata::Copyright, convert_to_srgb: true }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Performance {
+ /// Memory Photocraft may use, in MB (informational budget; drives the caches below).
+ pub memory_usage_mb: u32,
+ /// Undo steps kept per document (History panel states).
+ pub history_states: u32,
+ /// Display cache levels (mip levels kept for zoomed-out views).
+ pub cache_levels: u32,
+ /// Side of the GPU canvas texture tiles, in pixels (applies at next launch).
+ pub cache_tile_size: u32,
+ /// Draw the canvas with the GPU (applies at next launch).
+ pub use_gpu: bool,
+ /// Memory budget of the layer-effect cache, in MB.
+ pub effect_cache_mb: u32,
+ pub legacy_compositing: bool,
+}
+
+impl Default for Performance {
+ fn default() -> Self {
+ Self { memory_usage_mb: 8192, history_states: 50, cache_levels: 4, cache_tile_size: 8192, use_gpu: true, effect_cache_mb: 768, legacy_compositing: false }
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct ScratchDisk {
+ pub path: String,
+ pub enabled: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct ScratchDisks {
+ /// Disks for spilling tiles once the memory budget is reached (in priority order).
+ pub disks: Vec<ScratchDisk>,
+}
+
+impl Default for ScratchDisks {
+ fn default() -> Self {
+ Self { disks: vec![ScratchDisk { path: "(system temp)".into(), enabled: true }] }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Cursors {
+ pub painting: PaintingCursor,
+ pub show_crosshair_in_brush_tip: bool,
+ pub show_only_crosshair_while_painting: bool,
+ pub other: OtherCursor,
+ /// Brush preview (HUD) colour.
+ pub brush_preview_color: String,
+}
+
+impl Default for Cursors {
+ fn default() -> Self {
+ Self { painting: PaintingCursor::NormalTip, show_crosshair_in_brush_tip: false, show_only_crosshair_while_painting: false, other: OtherCursor::Standard, brush_preview_color: "#ff0000".into() }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct TransparencyAndGamut {
+ pub grid_size: CheckerSize,
+ pub grid_colors: CheckerColors,
+ /// Checkerboard colours used when `gridColors` is "custom".
+ pub custom_light: String,
+ pub custom_dark: String,
+ pub gamut_warning_color: String,
+ /// Gamut warning opacity, percent.
+ pub gamut_warning_opacity: u32,
+}
+
+impl Default for TransparencyAndGamut {
+ fn default() -> Self {
+ Self { grid_size: CheckerSize::Medium, grid_colors: CheckerColors::Light, custom_light: "#ffffff".into(), custom_dark: "#cccccc".into(), gamut_warning_color: "#808080".into(), gamut_warning_opacity: 100 }
+ }
+}
+
+impl TransparencyAndGamut {
+ /// Checker square side in screen points (`None`: no checkerboard, transparency shows white).
+ pub fn square(&self) -> Option<f32> {
+ match self.grid_size {
+ CheckerSize::None => None,
+ CheckerSize::Small => Some(4.0),
+ CheckerSize::Medium => Some(8.0),
+ CheckerSize::Large => Some(16.0),
+ }
+ }
+ /// The two checkerboard colours (light, dark) as sRGB bytes.
+ pub fn colors(&self) -> [[u8; 3]; 2] {
+ match self.grid_colors {
+ CheckerColors::Light => [[255, 255, 255], [204, 204, 204]],
+ CheckerColors::Medium => [[153, 153, 153], [102, 102, 102]],
+ CheckerColors::Dark => [[102, 102, 102], [51, 51, 51]],
+ CheckerColors::Red => [[255, 255, 255], [255, 204, 204]],
+ CheckerColors::Orange => [[255, 255, 255], [255, 229, 204]],
+ CheckerColors::Green => [[255, 255, 255], [204, 255, 204]],
+ CheckerColors::Blue => [[255, 255, 255], [204, 229, 255]],
+ CheckerColors::Purple => [[255, 255, 255], [229, 204, 255]],
+ CheckerColors::Custom => [parse_hex(&self.custom_light).unwrap_or([255; 3]), parse_hex(&self.custom_dark).unwrap_or([204; 3])],
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct UnitsAndRulers {
+ pub rulers: Unit,
+ pub type_units: TypeUnit,
+ pub column_width: f64,
+ pub gutter: f64,
+ pub print_resolution: f64,
+ pub screen_resolution: f64,
+ pub point_size: PointSize,
+}
+
+impl Default for UnitsAndRulers {
+ fn default() -> Self {
+ Self { rulers: Unit::Pixels, type_units: TypeUnit::Points, column_width: 180.0, gutter: 12.0, print_resolution: 300.0, screen_resolution: 72.0, point_size: PointSize::PostScript }
+ }
+}
+
+impl UnitsAndRulers {
+ /// Format a length in document pixels in the ruler unit, e.g. `"2.50 in"`.
+ pub fn format(&self, px: f64, dpi: f64, extent: f64) -> String {
+ let v = self.rulers.from_px(px, dpi, extent, self.point_size.per_inch());
+ format!("{:.*}", self.rulers.decimals(), v)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct GuidesGridAndSlices {
+ pub guide_color: String,
+ pub guide_style: LineStyle,
+ pub smart_guide_color: String,
+ pub grid_color: String,
+ pub grid_style: LineStyle,
+ /// Major gridline spacing in `gridUnit`.
+ pub gridline_every: f64,
+ pub grid_unit: Unit,
+ pub subdivisions: u32,
+ pub slice_color: String,
+ pub show_slice_numbers: bool,
+}
+
+impl Default for GuidesGridAndSlices {
+ fn default() -> Self {
+ Self {
+ guide_color: "#4affff".into(),
+ guide_style: LineStyle::Lines,
+ smart_guide_color: "#ff00ff".into(),
+ grid_color: "#8c8c8c".into(),
+ grid_style: LineStyle::Lines,
+ gridline_every: 1.0,
+ grid_unit: Unit::Inches,
+ subdivisions: 4,
+ slice_color: "#38b5ff".into(),
+ show_slice_numbers: true,
+ }
+ }
+}
+
+impl GuidesGridAndSlices {
+ /// Major gridline spacing in document pixels.
+ pub fn major_px(&self, dpi: f64, extent: f64, ppi: f64) -> f64 {
+ self.grid_unit.to_px(self.gridline_every.max(1e-3), dpi, extent, ppi).max(1e-3)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct PlugIns {
+ pub additional_plugins_folder: String,
+ pub show_extension_panels: bool,
+ pub allow_scripts_to_connect: bool,
+ pub generator_enabled: bool,
+}
+
+impl Default for PlugIns {
+ fn default() -> Self {
+ Self { additional_plugins_folder: String::new(), show_extension_panels: true, allow_scripts_to_connect: false, generator_enabled: false }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct TypePrefs {
+ pub smart_quotes: bool,
+ pub missing_glyph_protection: bool,
+ pub show_font_names_in_english: bool,
+ pub use_esc_to_commit: bool,
+ pub text_engine: TextEngine,
+ pub font_preview: FontPreview,
+ pub fill_new_type_layers_with_placeholder: bool,
+ pub recent_fonts: u32,
+}
+
+impl Default for TypePrefs {
+ fn default() -> Self {
+ Self { smart_quotes: true, missing_glyph_protection: true, show_font_names_in_english: true, use_esc_to_commit: true, text_engine: TextEngine::WorldReady, font_preview: FontPreview::Medium, fill_new_type_layers_with_placeholder: true, recent_fonts: 10 }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct EnhancedControls {
+ pub scrubby_slider_acceleration: bool,
+ pub touch_gestures: bool,
+ pub zoom_with_trackpad_pinch: bool,
+ pub rotate_view_with_trackpad: bool,
+}
+
+impl Default for EnhancedControls {
+ fn default() -> Self {
+ Self { scrubby_slider_acceleration: true, touch_gestures: true, zoom_with_trackpad_pinch: true, rotate_view_with_trackpad: false }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct RawDefaults {
+ pub color_space: RawColorSpace,
+ pub bit_depth: RawDepth,
+ pub resolution: f64,
+ pub sharpen_for: RawSharpen,
+ pub open_as_smart_object: bool,
+ pub apply_auto_tone: bool,
+}
+
+impl Default for RawDefaults {
+ fn default() -> Self {
+ Self { color_space: RawColorSpace::AdobeRgb, bit_depth: RawDepth::Sixteen, resolution: 300.0, sharpen_for: RawSharpen::None, open_as_smart_object: false, apply_auto_tone: false }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Integrations {
+ /// Allow agents to drive the app over the loopback control channel / MCP bridge.
+ pub allow_agent_control: bool,
+ /// Default control port (0 = only when `--control` is given).
+ pub control_port: u32,
+}
+
+impl Default for Integrations {
+ fn default() -> Self {
+ Self { allow_agent_control: true, control_port: 0 }
+ }
+}
+
+/// Edit › Menus: hidden items and item colours, by command id.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct MenuCustomization {
+ pub hidden: Vec<String>,
+ /// Command id → colour name (red, orange, yellow, green, blue, violet, gray).
+ pub colors: BTreeMap<String, String>,
+}
+
+/// Edit › Toolbar: hidden tools and a custom order (tool names as in `ui.set {tool}`).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct ToolbarCustomization {
+ pub hidden: Vec<String>,
+ pub order: Vec<String>,
+}
+
+/// All preferences. JSON keys are the `edit.preferences.<section>` ids.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Preferences {
+ pub general: General,
+ pub interface: Interface,
+ pub workspace: Workspace,
+ pub tools: Tools,
+ pub history_log: HistoryLog,
+ pub file_handling: FileHandling,
+ pub export: Export,
+ pub performance: Performance,
+ pub scratch_disks: ScratchDisks,
+ pub cursors: Cursors,
+ pub transparency_and_gamut: TransparencyAndGamut,
+ pub units_and_rulers: UnitsAndRulers,
+ pub guides_grid_and_slices: GuidesGridAndSlices,
+ pub plug_ins: PlugIns,
+ #[serde(rename = "type")]
+ pub type_: TypePrefs,
+ pub enhanced_controls: EnhancedControls,
+ pub raw_defaults: RawDefaults,
+ pub integrations: Integrations,
+ /// Edit › Keyboard Shortcuts: command id → shortcut (`Cmd+Shift+N` notation); an empty
+ /// string removes the default shortcut.
+ pub shortcuts: BTreeMap<String, String>,
+ pub menus: MenuCustomization,
+ pub toolbar: ToolbarCustomization,
+}
+
+/// Preferences dialog sections in Photoshop's order: (id, title).
+pub const SECTIONS: [(&str, &str); 18] = [
+ ("general", "General"),
+ ("interface", "Interface"),
+ ("workspace", "Workspace"),
+ ("tools", "Tools"),
+ ("historyLog", "History Log"),
+ ("fileHandling", "File Handling"),
+ ("export", "Export"),
+ ("performance", "Performance"),
+ ("scratchDisks", "Scratch Disks"),
+ ("cursors", "Cursors"),
+ ("transparencyAndGamut", "Transparency & Gamut"),
+ ("unitsAndRulers", "Units & Rulers"),
+ ("guidesGridAndSlices", "Guides, Grid & Slices"),
+ ("plugIns", "Plug-ins"),
+ ("type", "Type"),
+ ("enhancedControls", "Enhanced Controls"),
+ ("rawDefaults", "Camera Raw Defaults"),
+ ("integrations", "Integrations"),
+];
+
+/// Choices of an enumerated preference (dotted path, e.g. `"cursors.painting"`).
+pub fn choices(path: &str) -> Option<&'static [&'static str]> {
+ Some(match path {
+ "general.colorPicker" => ColorPicker::NAMES,
+ "general.imageInterpolation" => Interpolation::NAMES,
+ "interface.theme" => Theme::NAMES,
+ "interface.canvasColor" => CanvasColor::NAMES,
+ "interface.canvasBorder" => CanvasBorder::NAMES,
+ "interface.uiScale" => UiScale::NAMES,
+ "interface.uiFontSize" => UiFontSize::NAMES,
+ "historyLog.destination" => LogDestination::NAMES,
+ "historyLog.detail" => LogDetail::NAMES,
+ "fileHandling.imagePreviews" | "fileHandling.maximizePsdCompatibility" => Ask::NAMES,
+ "export.quickExportFormat" => QuickExportFormat::NAMES,
+ "export.quickExportLocation" => ExportLocation::NAMES,
+ "export.metadata" => ExportMetadata::NAMES,
+ "cursors.painting" => PaintingCursor::NAMES,
+ "cursors.other" => OtherCursor::NAMES,
+ "transparencyAndGamut.gridSize" => CheckerSize::NAMES,
+ "transparencyAndGamut.gridColors" => CheckerColors::NAMES,
+ "unitsAndRulers.rulers" | "guidesGridAndSlices.gridUnit" => Unit::NAMES,
+ "unitsAndRulers.typeUnits" => TypeUnit::NAMES,
+ "unitsAndRulers.pointSize" => PointSize::NAMES,
+ "guidesGridAndSlices.guideStyle" | "guidesGridAndSlices.gridStyle" => LineStyle::NAMES,
+ "type.textEngine" => TextEngine::NAMES,
+ "type.fontPreview" => FontPreview::NAMES,
+ "rawDefaults.colorSpace" => RawColorSpace::NAMES,
+ "rawDefaults.bitDepth" => RawDepth::NAMES,
+ "rawDefaults.sharpenFor" => RawSharpen::NAMES,
+ _ => return None,
+ })
+}
+
+/// Valid range of a numeric preference.
+pub fn range(path: &str) -> Option<(f64, f64)> {
+ Some(match path {
+ "fileHandling.autosaveMinutes" => (1.0, 240.0),
+ "fileHandling.recentFileCount" => (0.0, 100.0),
+ "export.jpegQuality" => (1.0, 100.0),
+ "performance.memoryUsageMb" => (256.0, 1_048_576.0),
+ "performance.historyStates" => (1.0, 1000.0),
+ "performance.cacheLevels" => (1.0, 8.0),
+ "performance.cacheTileSize" => (256.0, 16384.0),
+ "performance.effectCacheMb" => (16.0, 65536.0),
+ "transparencyAndGamut.gamutWarningOpacity" => (1.0, 100.0),
+ "unitsAndRulers.columnWidth" | "unitsAndRulers.gutter" => (0.0, 10_000.0),
+ "unitsAndRulers.printResolution" | "unitsAndRulers.screenResolution" | "rawDefaults.resolution" => (1.0, 10_000.0),
+ "guidesGridAndSlices.gridlineEvery" => (0.001, 10_000.0),
+ "guidesGridAndSlices.subdivisions" => (1.0, 100.0),
+ "type.recentFonts" => (0.0, 50.0),
+ "integrations.controlPort" => (0.0, 65535.0),
+ _ => return None,
+ })
+}
+
+/// Is this preference a `#rrggbb` colour?
+pub fn is_color(path: &str) -> bool {
+ if choices(path).is_some() || path.starts_with("shortcuts.") || path.starts_with("menus.") {
+ return false;
+ }
+ let leaf = path.rsplit('.').next().unwrap_or(path);
+ matches!(leaf, "guideColor" | "smartGuideColor" | "gridColor" | "sliceColor" | "canvasCustomColor" | "brushPreviewColor" | "gamutWarningColor" | "customLight" | "customDark")
+}
+
+pub fn parse_hex(s: &str) -> Option<[u8; 3]> {
+ let s = s.trim().trim_start_matches('#');
+ if s.len() != 6 {
+ return None;
+ }
+ let b = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).ok();
+ Some([b(0)?, b(2)?, b(4)?])
+}
+
+// ------------------------------------------------------------------ JSON paths
+
+/// Map keys that are command ids (which contain dots): `shortcuts.<id>`, `menus.colors.<id>`.
+fn keyed(path: &str) -> Option<(&str, &str)> {
+ for prefix in ["shortcuts.", "menus.colors."] {
+ if let Some(id) = path.strip_prefix(prefix) {
+ return Some((&prefix[..prefix.len() - 1], id));
+ }
+ }
+ None
+}
+
+fn get_path<'a>(root: &'a Value, path: &str) -> Option<&'a Value> {
+ if path.is_empty() {
+ return Some(root);
+ }
+ if let Some((map, id)) = keyed(path) {
+ return get_path(root, map)?.get(id);
+ }
+ path.split('.').try_fold(root, |v, k| v.get(k))
+}
+
+/// Set `value` at `path` (creating keys only inside free-form maps such as `shortcuts`).
+fn set_path(root: &mut Value, path: &str, value: Value) -> std::result::Result<(), String> {
+ if let Some((map, id)) = keyed(path) {
+ let mut cur = &mut *root;
+ for k in map.split('.') {
+ cur = cur.get_mut(k).ok_or_else(|| format!("unknown preference `{path}`"))?;
+ }
+ cur.as_object_mut().ok_or_else(|| format!("`{map}` is not a map"))?.insert(id.to_string(), value);
+ return Ok(());
+ }
+ let keys: Vec<&str> = path.split('.').filter(|k| !k.is_empty()).collect();
+ let Some((last, parents)) = keys.split_last() else { return Err("empty path".into()) };
+ let mut cur = root;
+ for k in parents {
+ cur = cur.get_mut(*k).ok_or_else(|| format!("unknown preference `{path}`"))?;
+ }
+ let free_map = matches!(parents.first(), Some(&"shortcuts")) || (parents.len() == 2 && parents[0] == "menus" && parents[1] == "colors");
+ let obj = cur.as_object_mut().ok_or_else(|| format!("`{path}` is not inside a section"))?;
+ if !obj.contains_key(*last) && !free_map {
+ return Err(format!("unknown preference `{path}`"));
+ }
+ obj.insert(last.to_string(), value);
+ Ok(())
+}
+
+/// Validate one value for `path` before it is stored (choices, ranges, colours).
+fn check_value(path: &str, v: &Value) -> std::result::Result<(), String> {
+ if let Some(c) = choices(path) {
+ let s = v.as_str().ok_or_else(|| format!("`{path}` must be one of {}", c.join("|")))?;
+ if !c.contains(&s) {
+ return Err(format!("`{path}` must be one of {} (got `{s}`)", c.join("|")));
+ }
+ }
+ if let Some((lo, hi)) = range(path) {
+ let x = v.as_f64().ok_or_else(|| format!("`{path}` must be a number"))?;
+ if !(lo..=hi).contains(&x) {
+ return Err(format!("`{path}` must be within {lo}..{hi} (got {x})"));
+ }
+ }
+ if is_color(path) && v.as_str().and_then(parse_hex).is_none() {
+ return Err(format!("`{path}` must be a #rrggbb colour"));
+ }
+ if let Some(sc) = path.strip_prefix("shortcuts.") {
+ let s = v.as_str().ok_or_else(|| format!("shortcut for `{sc}` must be a string"))?;
+ if !s.is_empty() && normalize_shortcut(s).is_none() {
+ return Err(format!("`{s}` is not a valid shortcut (e.g. Cmd+Shift+N, F7)"));
+ }
+ }
+ Ok(())
+}
+
+impl Preferences {
+ /// The preferences as JSON (camelCase keys).
+ pub fn to_json(&self) -> Value {
+ serde_json::to_value(self).unwrap_or(Value::Null)
+ }
+
+ /// Read a value by dotted path (`""` = everything).
+ pub fn get(&self, path: &str) -> Option<Value> {
+ get_path(&self.to_json(), path).cloned()
+ }
+
+ /// Set a value by dotted path, validating it. Unknown paths and wrong types are errors.
+ pub fn set(&mut self, path: &str, value: Value) -> std::result::Result<(), String> {
+ let value = match (path.strip_prefix("shortcuts."), &value) {
+ // Normalise shortcut spelling so conflicts compare equal.
+ (Some(_), Value::String(s)) if !s.is_empty() => Value::String(normalize_shortcut(s).ok_or_else(|| format!("`{s}` is not a valid shortcut"))?),
+ (Some(_), Value::Null) => {
+ // null = back to the default.
+ let id = &path["shortcuts.".len()..];
+ self.shortcuts.remove(id);
+ return Ok(());
+ }
+ _ => value,
+ };
+ check_value(path, &value)?;
+ let mut root = self.to_json();
+ set_path(&mut root, path, value)?;
+ *self = serde_json::from_value(root).map_err(|e| format!("invalid value for `{path}`: {e}"))?;
+ Ok(())
+ }
+
+ /// Reset one section (or one dotted path), or everything with `None`.
+ pub fn reset(&mut self, path: Option<&str>) -> std::result::Result<(), String> {
+ let Some(path) = path.filter(|p| !p.is_empty()) else {
+ *self = Preferences::default();
+ return Ok(());
+ };
+ let def = Preferences::default().get(path).ok_or_else(|| format!("unknown preference `{path}`"))?;
+ if path == "shortcuts" {
+ self.shortcuts.clear();
+ return Ok(());
+ }
+ let mut root = self.to_json();
+ set_path(&mut root, path, def)?;
+ *self = serde_json::from_value(root).map_err(|e| e.to_string())?;
+ Ok(())
+ }
+
+ /// The shortcut in effect for a command: the user's override, else its default.
+ pub fn shortcut<'a>(&'a self, id: &str, default: Option<&'a str>) -> Option<&'a str> {
+ match self.shortcuts.get(id) {
+ Some(s) if s.is_empty() => None,
+ Some(s) => Some(s.as_str()),
+ None => default,
+ }
+ }
+}
+
+// ------------------------------------------------------------------ shortcuts
+
+/// Canonical spelling of a shortcut: modifiers in `Cmd+Ctrl+Alt+Shift` order, key last
+/// (single characters upper-cased). `None` if it has no key or an unknown modifier.
+pub fn normalize_shortcut(s: &str) -> Option<String> {
+ let s = s.trim();
+ if s.is_empty() {
+ return None;
+ }
+ let (mut cmd, mut ctrl, mut alt, mut shift) = (false, false, false, false);
+ let mut key: Option<String> = None;
+ // A trailing "+" key is spelled "Cmd++".
+ let (body, plus_key) = if s.ends_with("++") || s == "+" { (s.trim_end_matches('+'), true) } else { (s, false) };
+ for part in body.split('+').filter(|p| !p.is_empty()) {
+ match part.to_ascii_lowercase().as_str() {
+ "cmd" | "command" | "⌘" | "meta" | "super" => cmd = true,
+ "ctrl" | "control" | "⌃" => ctrl = true,
+ "alt" | "option" | "opt" | "⌥" => alt = true,
+ "shift" | "⇧" => shift = true,
+ _ => {
+ if key.is_some() {
+ return None;
+ }
+ let k = if part.chars().count() == 1 { part.to_uppercase() } else { capitalize(part) };
+ key = Some(k);
+ }
+ }
+ }
+ if plus_key {
+ if key.is_some() {
+ return None;
+ }
+ key = Some("+".into());
+ }
+ let key = key?;
+ let mut out = Vec::new();
+ if cmd {
+ out.push("Cmd");
+ }
+ if ctrl {
+ out.push("Ctrl");
+ }
+ if alt {
+ out.push("Alt");
+ }
+ if shift {
+ out.push("Shift");
+ }
+ let mut s = out.join("+");
+ if !s.is_empty() {
+ s.push('+');
+ }
+ s.push_str(&key);
+ Some(s)
+}
+
+fn capitalize(s: &str) -> String {
+ let mut c = s.chars();
+ match c.next() {
+ Some(f) if f.is_ascii_alphabetic() => {
+ let rest: String = c.collect();
+ // Function keys stay upper-case (F1…F24); named keys are Title case.
+ if f.eq_ignore_ascii_case(&'f') && rest.chars().all(|c| c.is_ascii_digit()) && !rest.is_empty() { format!("F{rest}") } else { format!("{}{}", f.to_ascii_uppercase(), rest.to_ascii_lowercase()) }
+ }
+ _ => s.to_string(),
+ }
+}
+
+/// Shortcuts bound to more than one command: (shortcut, ids). `bindings` are (id, shortcut).
+pub fn conflicts<'a>(bindings: impl IntoIterator<Item = (&'a str, &'a str)>) -> Vec<(String, Vec<String>)> {
+ let mut by: BTreeMap<String, Vec<String>> = BTreeMap::new();
+ for (id, sc) in bindings {
+ if let Some(n) = normalize_shortcut(sc) {
+ by.entry(n).or_default().push(id.to_string());
+ }
+ }
+ by.into_iter().filter(|(_, ids)| ids.len() > 1).collect()
+}
+
+// ------------------------------------------------------------------ store
+
+/// The session's preferences plus a revision counter that moves on every change (frontends
+/// persist when it moves).
+#[derive(Clone, Debug, Default)]
+pub struct PrefsStore {
+ values: Preferences,
+ rev: u64,
+}
+
+impl PrefsStore {
+ pub fn get(&self) -> &Preferences {
+ &self.values
+ }
+ /// Change preferences; bumps the revision.
+ pub fn edit<R>(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R {
+ self.rev += 1;
+ f(&mut self.values)
+ }
+ pub fn rev(&self) -> u64 {
+ self.rev
+ }
+}
+
+impl Session {
+ /// The current preferences.
+ pub fn prefs(&self) -> &Preferences {
+ self.prefs.get()
+ }
+
+ /// Change preferences and apply the engine-side ones.
+ pub fn edit_prefs<R>(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R {
+ let r = self.prefs.edit(f);
+ self.apply_prefs();
+ r
+ }
+
+ /// Push engine-relevant preferences into live state: every document's history limit and
+ /// the layer-effect cache budget.
+ pub fn apply_prefs(&mut self) {
+ let n = self.prefs().performance.history_states.max(1) as usize;
+ let budget = self.prefs().performance.effect_cache_mb as usize;
+ for st in &mut self.docs {
+ st.history.max_states = n;
+ }
+ photocraft_compose::set_effect_cache_budget(budget << 20);
+ }
+
+ /// Everything persisted as one JSON document: the preferences plus `colorSettings`.
+ pub fn prefs_to_json(&self) -> String {
+ let mut v = self.prefs().to_json();
+ if let Value::Object(m) = &mut v {
+ m.insert("colorSettings".into(), serde_json::to_value(&self.color.settings).unwrap_or(Value::Null));
+ m.insert("version".into(), json!(1));
+ }
+ serde_json::to_string_pretty(&v).unwrap_or_default()
+ }
+
+ /// Restore preferences saved by [`Session::prefs_to_json`]. Missing keys keep their
+ /// defaults and unknown keys are ignored, so files from older and newer versions load.
+ pub fn load_prefs_json(&mut self, s: &str) -> std::result::Result<(), String> {
+ let mut v: Value = serde_json::from_str(s).map_err(|e| format!("preferences: {e}"))?;
+ let color = v.as_object_mut().and_then(|m| m.remove("colorSettings"));
+ let prefs: Preferences = serde_json::from_value(v).map_err(|e| format!("preferences: {e}"))?;
+ if let Some(c) = color {
+ self.color.settings = serde_json::from_value(c).unwrap_or_default();
+ }
+ self.prefs.edit(|p| *p = prefs);
+ self.apply_prefs();
+ Ok(())
+ }
+
+ /// Full JSON view used by `prefs.get`: preferences plus `colorSettings`.
+ fn prefs_view(&self) -> Value {
+ let mut v = self.prefs().to_json();
+ if let Value::Object(m) = &mut v {
+ m.insert("colorSettings".into(), serde_json::to_value(&self.color.settings).unwrap_or(Value::Null));
+ }
+ v
+ }
+
+ /// Set one dotted path, routing `colorSettings.*` to the colour state.
+ fn set_pref(&mut self, path: &str, value: Value) -> std::result::Result<(), String> {
+ if let Some(rest) = path.strip_prefix("colorSettings") {
+ let mut cur = serde_json::to_value(&self.color.settings).map_err(|e| e.to_string())?;
+ let rest = rest.trim_start_matches('.');
+ if rest.is_empty() {
+ cur = value;
+ } else {
+ set_path(&mut cur, rest, value)?;
+ }
+ self.color.settings = serde_json::from_value(cur).map_err(|e| format!("invalid value for `{path}`: {e}"))?;
+ crate::color_cmds::validate_settings(&self.color.settings)?;
+ self.prefs.edit(|_| ());
+ return Ok(());
+ }
+ let mut next = self.prefs().clone();
+ if path.is_empty() || SECTIONS.iter().any(|(id, _)| *id == path) || matches!(path, "shortcuts" | "menus" | "toolbar") {
+ // Whole section (or everything): merge the object key by key so each value is checked.
+ let obj = value.as_object().ok_or_else(|| format!("`{path}` needs an object"))?;
+ for (k, v) in obj {
+ let p = if path.is_empty() { k.clone() } else { format!("{path}.{k}") };
+ if path.is_empty() && k == "colorSettings" {
+ self.set_pref("colorSettings", v.clone())?;
+ continue;
+ }
+ if v.is_object() && !p.starts_with("shortcuts") && !p.ends_with(".colors") && next.get(&p).is_some_and(|c| c.is_object()) {
+ for (k2, v2) in v.as_object().into_iter().flatten() {
+ next.set(&format!("{p}.{k2}"), v2.clone())?;
+ }
+ } else {
+ next.set(&p, v.clone())?;
+ }
+ }
+ } else {
+ next.set(path, value)?;
+ }
+ self.prefs.edit(|p| *p = next);
+ Ok(())
+ }
+}
+
+// ------------------------------------------------------------------ commands
+
+fn always(_: &Session) -> std::result::Result<(), String> {
+ Ok(())
+}
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn prefs_get(s: &mut Session, p: &Value) -> Result<Value> {
+ let path = p.get("path").and_then(Value::as_str).unwrap_or("");
+ let v = s.prefs_view();
+ get_path(&v, path).cloned().ok_or_else(|| bad("prefs.get", format!("unknown preference `{path}`")))
+}
+
+fn prefs_set(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "prefs.set";
+ let mut changes: Vec<(String, Value)> = Vec::new();
+ if let Some(path) = p.get("path").and_then(Value::as_str) {
+ changes.push((path.to_string(), p.get("value").cloned().ok_or_else(|| bad(cmd, "missing `value`"))?));
+ }
+ if let Some(m) = p.get("values").and_then(Value::as_object) {
+ changes.extend(m.iter().map(|(k, v)| (k.clone(), v.clone())));
+ }
+ if changes.is_empty() {
+ return Err(bad(cmd, "give `path` and `value`, or `values: {path: value, …}`"));
+ }
+ // All or nothing: validate against a scratch copy first.
+ let (saved_prefs, saved_color) = (s.prefs().clone(), s.color.settings.clone());
+ for (path, v) in &changes {
+ if let Err(e) = s.set_pref(path, v.clone()) {
+ s.prefs.edit(|p| *p = saved_prefs);
+ s.color.settings = saved_color;
+ return Err(bad(cmd, e));
+ }
+ }
+ s.apply_prefs();
+ let view = s.prefs_view();
+ let out: Map<String, Value> = changes.iter().map(|(k, _)| (k.clone(), get_path(&view, k).cloned().unwrap_or(Value::Null))).collect();
+ Ok(Value::Object(out))
+}
+
+fn prefs_reset(s: &mut Session, p: &Value) -> Result<Value> {
+ let path = p.get("path").or_else(|| p.get("section")).and_then(Value::as_str);
+ match path {
+ Some("colorSettings") => s.color.settings = Default::default(),
+ None => {
+ s.color.settings = Default::default();
+ s.edit_prefs(|p| p.reset(None)).map_err(|e| bad("prefs.reset", e))?;
+ }
+ Some(path) => {
+ let mut next = s.prefs().clone();
+ next.reset(Some(path)).map_err(|e| bad("prefs.reset", e))?;
+ s.edit_prefs(|p| *p = next);
+ }
+ }
+ s.prefs.edit(|_| ());
+ s.apply_prefs();
+ prefs_get(s, &json!({"path": path.unwrap_or("")}))
+}
+
+/// `edit.preferences.<section>`: the section's values (the GUI opens the dialog on it instead).
+fn preferences_section(s: &mut Session, p: &Value) -> Result<Value> {
+ let section = p.get("__section").and_then(Value::as_str).unwrap_or("general").to_string();
+ let title = SECTIONS.iter().find(|(id, _)| *id == section).map_or("General", |(_, t)| *t);
+ let values = s.prefs().get(&section).unwrap_or(Value::Null);
+ Ok(json!({"section": section, "title": title, "values": values}))
+}
+
+/// Edit › Keyboard Shortcuts (engine part): list, change and reset application shortcuts.
+fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.keyboardShortcuts";
+ if let Some(r) = p.get("reset") {
+ match r {
+ Value::Bool(true) => s.edit_prefs(|p| p.shortcuts.clear()),
+ Value::Array(ids) => s.edit_prefs(|p| {
+ for id in ids.iter().filter_map(Value::as_str) {
+ p.shortcuts.remove(id);
+ }
+ }),
+ _ => {}
+ }
+ }
+ if let Some(m) = p.get("set").and_then(Value::as_object) {
+ let mut next = s.prefs().clone();
+ for (id, v) in m {
+ if crate::commands::find(id).is_none() && !p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false) {
+ return Err(bad(cmd, format!("unknown command `{id}`")));
+ }
+ next.set(&format!("shortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?;
+ }
+ // Like Photoshop, a shortcut moved to a new command is taken away from the old one.
+ if p.get("removeConflicts").and_then(Value::as_bool).unwrap_or(true) {
+ for (id, v) in m {
+ let Some(sc) = v.as_str().and_then(normalize_shortcut) else { continue };
+ for c in crate::command_specs() {
+ if c.id != id && next.shortcut(c.id, c.shortcut).and_then(normalize_shortcut).as_deref() == Some(sc.as_str()) {
+ next.shortcuts.insert(c.id.to_string(), String::new());
+ }
+ }
+ }
+ }
+ s.edit_prefs(|p| *p = next);
+ }
+ let prefs = s.prefs();
+ let filter = p.get("filter").and_then(Value::as_str).map(str::to_ascii_lowercase);
+ let list: Vec<Value> = crate::command_specs()
+ .iter()
+ .filter(|c| filter.as_ref().is_none_or(|f| c.id.to_ascii_lowercase().contains(f) || c.label.to_ascii_lowercase().contains(f)))
+ .filter(|c| p.get("list").and_then(Value::as_bool).unwrap_or(false) || filter.is_some() || prefs.shortcuts.contains_key(c.id))
+ .map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "default": c.shortcut, "shortcut": prefs.shortcut(c.id, c.shortcut)}))
+ .collect();
+ let bindings: Vec<(&str, &str)> = crate::command_specs().iter().filter_map(|c| Some((c.id, prefs.shortcut(c.id, c.shortcut)?))).collect();
+ let conflicts: Vec<Value> = conflicts(bindings).into_iter().map(|(sc, ids)| json!({"shortcut": sc, "commands": ids})).collect();
+ Ok(json!({"overrides": prefs.shortcuts, "commands": list, "conflicts": conflicts}))
+}
+
+/// Edit › Menus: hide/show items and give them colours.
+fn menus(s: &mut Session, p: &Value) -> Result<Value> {
+ let ids = |k: &str| -> Vec<String> { p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default() };
+ const COLORS: [&str; 8] = ["none", "red", "orange", "yellow", "green", "blue", "violet", "gray"];
+ if let Some(m) = p.get("color").and_then(Value::as_object) {
+ for v in m.values() {
+ if let Some(c) = v.as_str().filter(|c| !COLORS.contains(c)) {
+ return Err(bad("edit.menus", format!("unknown colour `{c}` ({})", COLORS.join("|"))));
+ }
+ }
+ }
+ let (hide, show) = (ids("hide"), ids("show"));
+ s.edit_prefs(|pr| {
+ if p.get("reset").and_then(Value::as_bool) == Some(true) {
+ pr.menus = MenuCustomization::default();
+ }
+ for id in hide {
+ if !pr.menus.hidden.contains(&id) {
+ pr.menus.hidden.push(id);
+ }
+ }
+ pr.menus.hidden.retain(|h| !show.contains(h));
+ if let Some(m) = p.get("color").and_then(Value::as_object) {
+ for (id, v) in m {
+ match v.as_str() {
+ Some(c) if c != "none" => {
+ pr.menus.colors.insert(id.clone(), c.to_string());
+ }
+ _ => {
+ pr.menus.colors.remove(id);
+ }
+ }
+ }
+ }
+ });
+ Ok(serde_json::to_value(&s.prefs().menus).unwrap_or_default())
+}
+
+/// Edit › Toolbar: hide tools and reorder the toolbar.
+fn toolbar(s: &mut Session, p: &Value) -> Result<Value> {
+ let ids = |k: &str| -> Option<Vec<String>> { p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) };
+ s.edit_prefs(|pr| {
+ if p.get("reset").and_then(Value::as_bool) == Some(true) {
+ pr.toolbar = ToolbarCustomization::default();
+ }
+ if let Some(h) = ids("hidden") {
+ pr.toolbar.hidden = h;
+ }
+ if let Some(o) = ids("order") {
+ pr.toolbar.order = o;
+ }
+ });
+ Ok(serde_json::to_value(&s.prefs().toolbar).unwrap_or_default())
+}
+
+macro_rules! spec {
+ ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $run:expr, $journal:expr) => {
+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: always, run: $run, journal: $journal }
+ };
+}
+
+macro_rules! section {
+ ($id:literal, $label:literal) => {
+ CommandSpec { id: $id, label: $label, menu: &["Edit", "Preferences"], shortcut: None, params: r##"{}"##, enabled: always, run: |s, _| preferences_section(s, &json!({"__section": section_of($id)})), journal: false }
+ };
+}
+
+fn section_of(id: &str) -> &str {
+ id.rsplit('.').next().unwrap_or("general")
+}
+
+/// Preference command specs.
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!("prefs.get", "Get Preferences", [], None, r##"{"path":"section.key"?=everything (e.g. "performance.historyStates", "colorSettings.workingRgb")}"##, prefs_get, false),
+ spec!("prefs.set", "Set Preferences", [], None, r##"{"path":"section.key","value":json} or {"values":{"section.key":json,…}} (validated; all or nothing)"##, prefs_set, false),
+ spec!("prefs.reset", "Reset Preferences", [], None, r##"{"path":"section|section.key"?=everything}"##, prefs_reset, false),
+ section!("edit.preferences.general", "General…"),
+ section!("edit.preferences.interface", "Interface…"),
+ section!("edit.preferences.workspace", "Workspace…"),
+ section!("edit.preferences.tools", "Tools…"),
+ section!("edit.preferences.historyLog", "History Log…"),
+ section!("edit.preferences.fileHandling", "File Handling…"),
+ section!("edit.preferences.export", "Export…"),
+ section!("edit.preferences.performance", "Performance…"),
+ section!("edit.preferences.scratchDisks", "Scratch Disks…"),
+ section!("edit.preferences.cursors", "Cursors…"),
+ section!("edit.preferences.transparencyAndGamut", "Transparency & Gamut…"),
+ section!("edit.preferences.unitsAndRulers", "Units & Rulers…"),
+ section!("edit.preferences.guidesGridAndSlices", "Guides, Grid & Slices…"),
+ section!("edit.preferences.plugIns", "Plug-ins…"),
+ section!("edit.preferences.type", "Type…"),
+ section!("edit.preferences.enhancedControls", "Enhanced Controls…"),
+ section!("edit.preferences.rawDefaults", "Camera Raw…"),
+ section!("edit.preferences.integrations", "Integrations…"),
+ spec!(
+ "edit.keyboardShortcuts",
+ "Keyboard Shortcuts…",
+ ["Edit"],
+ Some("Cmd+Alt+Shift+K"),
+ r##"{"set":{"<command id>":"Cmd+Shift+X"|""(remove)|null(default)}?,"reset":true|["<id>",…]?,"removeConflicts":bool=true,"filter":str?,"list":bool=false}"##,
+ keyboard_shortcuts,
+ true
+ ),
+ spec!("edit.menus", "Menus…", ["Edit"], Some("Cmd+Alt+Shift+M"), r##"{"hide":["<id>",…]?,"show":["<id>",…]?,"color":{"<id>":"red|orange|yellow|green|blue|violet|gray|none"}?,"reset":bool=false}"##, menus, true),
+ spec!("edit.toolbar", "Toolbar…", ["Edit"], None, r##"{"hidden":["<tool>",…]?,"order":["<tool>",…]?,"reset":bool=false}"##, toolbar, true),
+ ]
+}
+
+#[cfg(test)]
+#[path = "prefs/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs
new file mode 100644
index 000000000..342c977a1
--- /dev/null
+++ b/crates/engine/src/prefs/tests.rs
@@ -0,0 +1,188 @@
+use super::*;
+
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
+ s
+}
+
+#[test]
+fn defaults_match_photoshop() {
+ let p = Preferences::default();
+ assert_eq!(p.performance.history_states, 50);
+ assert_eq!(p.guides_grid_and_slices.subdivisions, 4);
+ assert_eq!(p.guides_grid_and_slices.guide_color, "#4affff");
+ assert_eq!(p.transparency_and_gamut.colors(), [[255, 255, 255], [204, 204, 204]]);
+ assert_eq!(p.transparency_and_gamut.square(), Some(8.0));
+ assert_eq!(p.cursors.painting, PaintingCursor::NormalTip);
+ // Every dialog section is a key of the JSON form.
+ let v = p.to_json();
+ for (id, _) in SECTIONS {
+ assert!(v.get(id).is_some_and(Value::is_object), "{id}");
+ }
+}
+
+#[test]
+fn get_set_reset_by_path() {
+ let mut s = session();
+ assert_eq!(s.execute("prefs.get", json!({"path": "performance.historyStates"})).unwrap(), json!(50));
+ s.execute("prefs.set", json!({"path": "performance.historyStates", "value": 3})).unwrap();
+ assert_eq!(s.prefs().performance.history_states, 3);
+ // Applied to open documents: only three undo steps remain.
+ for i in 0..6 {
+ s.execute("layer.new.layer", json!({"name": format!("L{i}")})).unwrap();
+ }
+ let mut n = 0;
+ while s.undo() {
+ n += 1;
+ }
+ assert_eq!(n, 3);
+ // New documents too.
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ assert_eq!(s.active().unwrap().history.max_states, 3);
+ s.execute("prefs.reset", json!({"path": "performance"})).unwrap();
+ assert_eq!(s.prefs().performance.history_states, 50);
+ assert_eq!(s.active().unwrap().history.max_states, 50);
+}
+
+#[test]
+fn set_validates_and_is_all_or_nothing() {
+ let mut s = session();
+ for (path, value) in [
+ ("cursors.painting", json!("huge")),
+ ("performance.historyStates", json!(0)),
+ ("performance.historyStates", json!("ten")),
+ ("guidesGridAndSlices.guideColor", json!("cyan")),
+ ("nope.nothing", json!(1)),
+ ("general.notAField", json!(true)),
+ ("shortcuts.edit.undo", json!("Cmd+Banana+Q")),
+ ] {
+ assert!(s.execute("prefs.set", json!({"path": path, "value": value})).is_err(), "{path}");
+ }
+ let r = s.execute("prefs.set", json!({"values": {"cursors.painting": "precise", "performance.historyStates": -4}}));
+ assert!(r.is_err());
+ assert_eq!(s.prefs().cursors.painting, PaintingCursor::NormalTip, "nothing applied");
+ let r = s.execute("prefs.set", json!({"values": {"cursors.painting": "precise", "unitsAndRulers.rulers": "cm"}})).unwrap();
+ assert_eq!(r["cursors.painting"], "precise");
+ assert_eq!(s.prefs().units_and_rulers.rulers, Unit::Centimeters);
+}
+
+#[test]
+fn whole_section_set_merges_keys() {
+ let mut s = session();
+ s.execute("prefs.set", json!({"path": "transparencyAndGamut", "value": {"gridSize": "large", "gridColors": "custom", "customDark": "#336699"}})).unwrap();
+ let t = &s.prefs().transparency_and_gamut;
+ assert_eq!(t.square(), Some(16.0));
+ assert_eq!(t.colors()[1], [0x33, 0x66, 0x99]);
+ assert_eq!(t.gamut_warning_color, "#808080", "untouched keys keep their values");
+}
+
+#[test]
+fn json_round_trip_tolerates_unknown_and_missing_keys() {
+ let mut s = session();
+ s.execute("prefs.set", json!({"values": {"interface.theme": "studioLight", "fileHandling.autosaveMinutes": 5, "shortcuts.edit.fill": "Cmd+Shift+F"}})).unwrap();
+ s.execute("edit.colorSettings", json!({"workingRgb": "display-p3", "policyRgb": "convert"})).unwrap();
+ let text = s.prefs_to_json();
+ let mut t = Session::new();
+ t.load_prefs_json(&text).unwrap();
+ assert_eq!(t.prefs(), s.prefs());
+ assert_eq!(t.color.settings.working_rgb, "display-p3");
+ assert_eq!(t.color.settings.policy_rgb, crate::color_cmds::Policy::Convert);
+ // Older/newer files: unknown keys ignored, missing ones default.
+ let mut u = Session::new();
+ u.load_prefs_json(r#"{"general": {"beepWhenDone": true, "futureThing": 1}, "someNewSection": {}}"#).unwrap();
+ assert!(u.prefs().general.beep_when_done);
+ assert_eq!(u.prefs().performance.history_states, 50);
+ assert!(u.load_prefs_json("not json").is_err());
+}
+
+#[test]
+fn units_convert_both_ways() {
+ for u in [Unit::Pixels, Unit::Inches, Unit::Centimeters, Unit::Millimeters, Unit::Points, Unit::Picas, Unit::Percent] {
+ let v = u.from_px(450.0, 300.0, 900.0, 72.0);
+ assert!((u.to_px(v, 300.0, 900.0, 72.0) - 450.0).abs() < 1e-9, "{u:?}");
+ }
+ assert_eq!(Unit::Inches.from_px(600.0, 300.0, 0.0, 72.0), 2.0);
+ assert_eq!(Unit::Points.from_px(300.0, 300.0, 0.0, 72.0), 72.0);
+ assert_eq!(Unit::Percent.from_px(450.0, 300.0, 900.0, 72.0), 50.0);
+ let r = UnitsAndRulers { rulers: Unit::Centimeters, ..Default::default() };
+ assert_eq!(r.format(300.0, 300.0, 0.0), "2.54");
+}
+
+#[test]
+fn shortcuts_normalise_and_detect_conflicts() {
+ assert_eq!(normalize_shortcut("shift+cmd+n").as_deref(), Some("Cmd+Shift+N"));
+ assert_eq!(normalize_shortcut("Alt+Cmd+f7").as_deref(), Some("Cmd+Alt+F7"));
+ assert_eq!(normalize_shortcut("Cmd++").as_deref(), Some("Cmd++"));
+ assert_eq!(normalize_shortcut("Cmd+Shift"), None);
+ assert_eq!(normalize_shortcut("Cmd+A+B"), None);
+ let c = conflicts([("a", "Cmd+J"), ("b", "cmd+j"), ("c", "Cmd+K")]);
+ assert_eq!(c, vec![("Cmd+J".to_string(), vec!["a".to_string(), "b".to_string()])]);
+}
+
+#[test]
+fn keyboard_shortcuts_reassign_and_reset() {
+ let mut s = session();
+ let undo = crate::commands::find("edit.undo").unwrap().shortcut;
+ assert_eq!(s.prefs().shortcut("edit.undo", undo), Some("Cmd+Z"));
+ // Give ⌘Z to Fill: Undo loses it (Photoshop moves a shortcut rather than duplicating it).
+ let r = s.execute("edit.keyboardShortcuts", json!({"set": {"edit.fill": "Cmd+Z"}})).unwrap();
+ assert_eq!(s.prefs().shortcut("edit.fill", None), Some("Cmd+Z"));
+ assert_eq!(s.prefs().shortcut("edit.undo", undo), None);
+ assert!(r["conflicts"].as_array().unwrap().is_empty());
+ // Keeping the duplicate reports a conflict.
+ let r = s.execute("edit.keyboardShortcuts", json!({"set": {"edit.undo": "Cmd+Z"}, "removeConflicts": false})).unwrap();
+ assert_eq!(r["conflicts"][0]["shortcut"], "Cmd+Z");
+ assert!(s.execute("edit.keyboardShortcuts", json!({"set": {"no.such.command": "F9"}})).is_err());
+ s.execute("edit.keyboardShortcuts", json!({"reset": true})).unwrap();
+ assert!(s.prefs().shortcuts.is_empty());
+ assert_eq!(s.prefs().shortcut("edit.undo", undo), Some("Cmd+Z"));
+ // Listing with a filter.
+ let r = s.execute("edit.keyboardShortcuts", json!({"filter": "gaussian"})).unwrap();
+ assert!(r["commands"].as_array().unwrap().iter().any(|c| c["id"] == "filter.blur.gaussianBlur"));
+}
+
+#[test]
+fn menus_and_toolbar_customisation_persist() {
+ let mut s = session();
+ s.execute("edit.menus", json!({"hide": ["edit.fade"], "color": {"edit.fill": "red"}})).unwrap();
+ assert_eq!(s.prefs().menus.hidden, vec!["edit.fade".to_string()]);
+ assert_eq!(s.prefs().menus.colors["edit.fill"], "red");
+ assert!(s.execute("edit.menus", json!({"color": {"edit.fill": "plaid"}})).is_err());
+ s.execute("edit.menus", json!({"show": ["edit.fade"], "color": {"edit.fill": "none"}})).unwrap();
+ assert!(s.prefs().menus.hidden.is_empty() && s.prefs().menus.colors.is_empty());
+ s.execute("edit.toolbar", json!({"hidden": ["Sponge"]})).unwrap();
+ let back: Preferences = serde_json::from_str(&s.prefs_to_json()).unwrap();
+ assert_eq!(back.toolbar.hidden, vec!["Sponge".to_string()]);
+}
+
+#[test]
+fn preference_sections_are_commands() {
+ let mut s = Session::new();
+ for (id, title) in SECTIONS {
+ let r = s.execute(&format!("edit.preferences.{id}"), json!({})).unwrap();
+ assert_eq!(r["section"], id);
+ assert_eq!(r["title"], title);
+ assert!(r["values"].is_object(), "{id}");
+ }
+}
+
+#[test]
+fn choice_and_range_tables_cover_enum_fields() {
+ let p = Preferences::default().to_json();
+ for (id, _) in SECTIONS {
+ for (k, v) in p[id].as_object().unwrap() {
+ let path = format!("{id}.{k}");
+ if let Some(c) = choices(&path) {
+ assert!(c.contains(&v.as_str().unwrap()), "{path}");
+ }
+ if let Some((lo, hi)) = range(&path) {
+ let x = v.as_f64().unwrap();
+ assert!(x >= lo && x <= hi, "{path} default {x} outside {lo}..{hi}");
+ }
+ if is_color(&path) {
+ assert!(parse_hex(v.as_str().unwrap()).is_some(), "{path}");
+ }
+ }
+ }
+}
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs
index a782a09e0..0ad96122f 100644
--- a/crates/engine/src/retouch_cmds.rs
+++ b/crates/engine/src/retouch_cmds.rs
@@ -54,7 +54,7 @@ fn parse_brush(s: &Session, p: &Value, cmd: &str) -> Result<(Stroke, LayerId)> {
.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 })
+ Some(StrokePoint::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2).and_then(Value::as_f64).unwrap_or(1.0) as f32))
})
.collect();
if pts.is_empty() {
diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs
index cd12a55af..4fb46978a 100644
--- a/crates/engine/src/retouch_cmds/tests.rs
+++ b/crates/engine/src/retouch_cmds/tests.rs
@@ -107,8 +107,11 @@ fn clone_stamp_respects_selection_and_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");
+ // CMYK pixels display through the CMYK profile, so sRGB blue/yellow come back as their
+ // (less saturated) in-gamut CMYK equivalents.
+ let (inside, outside) = (rgba(&s, 44, 16), rgba(&s, 52, 16));
+ assert!(inside[2] > inside[0] + 0.2, "inside the selection: cloned blue {inside:?}");
+ assert!(outside[2] < 0.3 && outside[0] > 0.8, "outside the selection: untouched yellow {outside:?}");
}
#[test]
diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs
new file mode 100644
index 000000000..1760aeb7b
--- /dev/null
+++ b/crates/engine/src/smart_cmds.rs
@@ -0,0 +1,889 @@
+//! Smart Objects and Smart Filters: Layer › Smart Objects, Layer › Smart Filter and
+//! Filter › Convert for Smart Filters.
+//!
+//! A smart object keeps its **source** (embedded file bytes, or a linked path) plus a
+//! `transform` and a stack of smart filters; its `cache` is the rendered appearance the
+//! compositors draw. The engine owns re-rendering (compose stays a pure function of the
+//! document):
+//!
+//! ```text
+//! source bytes ──decode + composite (cached by content hash)──► source image (source pixels)
+//! ──transform (exact shift, or bicubic warp)──────► placed (document pixels)
+//! ──each visible smart filter, blended (blend/opacity)──► filtered
+//! ──filter mask mix (unfiltered ↔ filtered)───────► cache
+//! ```
+//!
+//! Converting a layer embeds it as an in-memory `.pcraft` bundle of a nested document (exactly
+//! lossless, layered, any depth/model). PSD placed layers keep their source in the preserved
+//! global `lnk2` block (found by uuid), and keep Photoshop's rendering until something changes,
+//! so an unedited PSD still round-trips byte for byte.
+
+use std::sync::{Arc, Mutex};
+
+use photocraft_algo::resample::translate_surface;
+use photocraft_algo::transform::{Homography, Interp, warp_surface};
+use photocraft_color::{BlendMode, PixelFormat};
+use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, LayerMask, Metadata, SmartObject, SmartSource};
+use photocraft_geom::{Affine, Rect, Size};
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, blend_from_str, layer_param};
+use crate::{EngineError, Result, Session};
+
+/// An open Edit Contents document and the smart object it updates when saved or closed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SmartLink {
+ pub child: DocId,
+ pub parent: DocId,
+ pub layer: LayerId,
+}
+
+/// PSD placed-layer keys that describe the smart object's source; stale once we change it.
+const PLACED_KEYS: [&[u8; 4]; 3] = [b"SoLd", b"PlLd", b"SoLE"];
+
+fn other(msg: impl Into<String>) -> EngineError {
+ EngineError::Other(msg.into())
+}
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+// ---------- source encoding / decoding ----------
+
+/// Encodes a document as embedded smart-object contents: an in-memory `.pcraft` bundle.
+pub fn encode_source(doc: &Document) -> Result<Vec<u8>> {
+ photocraft_format::save_to_bytes(doc, &Default::default()).map_err(|e| other(format!("can't encode smart object contents: {e}")))
+}
+
+/// Decodes smart-object contents (a `.pcraft` bundle, PSD/PSB, or any flat image format).
+pub fn decode_source(file_name: &str, bytes: &[u8]) -> Result<Document> {
+ photocraft_io::import(file_name, bytes).map(|r| r.document).map_err(|e| other(format!("can't read smart object contents \"{file_name}\": {e}")))
+}
+
+fn base_name(path: &str) -> String {
+ path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
+}
+
+fn read_file(path: &str) -> Option<Vec<u8>> {
+ if path.is_empty() { None } else { std::fs::read(path).ok() }
+}
+
+/// The source file of a smart object: embedded bytes, the PSD's embedded linked-layer data (PSD
+/// import keeps the placed layer's uuid as the path), or a linked file on disk.
+pub fn source_bytes(meta: &Metadata, src: &SmartSource) -> Option<(String, Arc<Vec<u8>>)> {
+ match src {
+ SmartSource::Embedded { file_name, bytes } => Some((file_name.clone(), bytes.clone())),
+ SmartSource::Linked { path } => {
+ if let Some(f) = photocraft_io::linked::find_linked_file(meta, path) {
+ return Some((f.file_name, Arc::new(f.bytes)));
+ }
+ read_file(path).map(|b| (base_name(path), Arc::new(b)))
+ }
+ }
+}
+
+/// A decoded, composited source in its own pixel space (`bounds` starts at the origin).
+#[derive(Clone, Debug)]
+pub struct SourceImage {
+ pub surface: Arc<Surface>,
+ pub bounds: Rect,
+}
+
+type CacheKey = ([u8; 32], PixelFormat);
+
+struct CacheEntry {
+ key: CacheKey,
+ image: SourceImage,
+ decodes: u32,
+}
+
+/// Decoded source composites by content hash, most recent last. Re-filtering or re-transforming
+/// a smart object never decodes its contents again.
+static SOURCE_CACHE: Mutex<Vec<CacheEntry>> = Mutex::new(Vec::new());
+const CACHE_ENTRIES: usize = 32;
+const CACHE_BYTES: usize = 1 << 30;
+
+fn cache_key(bytes: &[u8], fmt: PixelFormat) -> CacheKey {
+ (*blake3::hash(bytes).as_bytes(), fmt)
+}
+
+fn cache_get(key: &CacheKey) -> Option<SourceImage> {
+ let mut c = SOURCE_CACHE.lock().ok()?;
+ let i = c.iter().position(|e| e.key == *key)?;
+ let e = c.remove(i);
+ let img = e.image.clone();
+ c.push(e);
+ Some(img)
+}
+
+fn cache_put(key: CacheKey, image: SourceImage) {
+ let Ok(mut c) = SOURCE_CACHE.lock() else { return };
+ let decodes = match c.iter().position(|e| e.key == key) {
+ Some(i) => c.remove(i).decodes + 1,
+ None => 1,
+ };
+ c.push(CacheEntry { key, image, decodes });
+ let size = |e: &CacheEntry| e.image.bounds.width() as usize * e.image.bounds.height() as usize * e.key.1.channels() * 4;
+ while c.len() > CACHE_ENTRIES || (c.len() > 1 && c.iter().map(size).sum::<usize>() > CACHE_BYTES) {
+ c.remove(0);
+ }
+}
+
+/// How many times these contents were decoded at this pixel format (0 = never / evicted).
+pub fn source_decode_count(bytes: &[u8], fmt: PixelFormat) -> u32 {
+ let key = cache_key(bytes, fmt);
+ SOURCE_CACHE.lock().ok().and_then(|c| c.iter().find(|e| e.key == key).map(|e| e.decodes)).unwrap_or(0)
+}
+
+fn buffer_to_surface(buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Surface {
+ let n = fmt.channels();
+ let mut data = vec![0.0f32; buf.px.len() * n];
+ for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) {
+ photocraft_raster::from_rgba_into(&fmt, *p, out);
+ }
+ let mut s = Surface::new(fmt);
+ if !buf.rect.is_empty() {
+ s.write_region(buf.rect, &data);
+ }
+ s.prune();
+ s
+}
+
+/// The composited source image of `bytes` in pixel format `fmt` (decoded once, then cached).
+pub fn source_image(file_name: &str, bytes: &[u8], fmt: PixelFormat) -> Result<SourceImage> {
+ let key = cache_key(bytes, fmt);
+ if let Some(img) = cache_get(&key) {
+ return Ok(img);
+ }
+ let doc = decode_source(file_name, bytes)?;
+ let buf = photocraft_compose::flatten(&doc);
+ let img = SourceImage { surface: Arc::new(buffer_to_surface(&buf, fmt)), bounds: doc.bounds() };
+ cache_put(key, img.clone());
+ Ok(img)
+}
+
+/// Layer › Smart Objects › Stack Mode: the source's layers (or, when it holds a single group, the
+/// group's layers) combined per pixel with `mode`. Cached like [`source_image`], keyed by mode.
+pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> Result<SourceImage> {
+ use photocraft_algo::stack::Stat;
+ let mut key = cache_key(bytes, fmt);
+ key.0 = *blake3::hash(&[&key.0[..], b"stack:", mode.id().as_bytes()].concat()).as_bytes();
+ if let Some(img) = cache_get(&key) {
+ return Ok(img);
+ }
+ let doc = decode_source(file_name, bytes)?;
+ let layers: &[Layer] = match doc.layers.as_slice() {
+ [only] if only.is_group() => only.children().unwrap_or_default(),
+ all => all,
+ };
+ let bounds = doc.bounds();
+ let frames: Vec<Vec<[f32; 4]>> = layers.iter().filter(|l| l.visible).map(|l| {
+ let mut one = l.clone();
+ one.blend = BlendMode::Normal;
+ one.clipped = false;
+ photocraft_compose::render_layer(&one, bounds).px
+ }).collect();
+ let stat = match mode {
+ photocraft_doc::StackMode::Entropy => Stat::Entropy,
+ photocraft_doc::StackMode::Kurtosis => Stat::Kurtosis,
+ photocraft_doc::StackMode::Maximum => Stat::Maximum,
+ photocraft_doc::StackMode::Mean => Stat::Mean,
+ photocraft_doc::StackMode::Median => Stat::Median,
+ photocraft_doc::StackMode::Minimum => Stat::Minimum,
+ photocraft_doc::StackMode::Range => Stat::Range,
+ photocraft_doc::StackMode::Skewness => Stat::Skewness,
+ photocraft_doc::StackMode::StandardDeviation => Stat::StandardDeviation,
+ photocraft_doc::StackMode::Summation => Stat::Summation,
+ photocraft_doc::StackMode::Variance => Stat::Variance,
+ };
+ let buf = photocraft_compose::Buffer { rect: bounds, px: photocraft_algo::stack::combine(&frames, stat) };
+ let img = SourceImage { surface: Arc::new(buffer_to_surface(&buf, fmt)), bounds };
+ cache_put(key, img.clone());
+ Ok(img)
+}
+
+// ---------- rendering ----------
+
+/// Places the source image in the document: an exact shift for whole-pixel translations
+/// (conversion and re-render are then lossless), a bicubic warp otherwise.
+fn place(img: &SourceImage, t: &Affine) -> Surface {
+ let [a, b, c, d, e, f] = t.m;
+ let near = |x: f64, y: f64| (x - y).abs() < 1e-9;
+ if near(a, 1.0) && near(b, 0.0) && near(c, 0.0) && near(d, 1.0) && near(e, e.round()) && near(f, f.round()) {
+ return translate_surface(&img.surface, e.round() as i32, f.round() as i32);
+ }
+ warp_surface(&img.surface, img.bounds, &Homography([a, c, e, b, d, f, 0.0, 0.0, 1.0]), Interp::Bicubic)
+}
+
+/// Places the source image through its warp (source space) and then its transform, in one
+/// resampling pass (Edit › Transform › Warp on a smart object stays lossless).
+fn place_warped(img: &SourceImage, w: &photocraft_geom::warp::Warp, t: &Affine) -> Surface {
+ let [a, b, c, d, e, f] = t.m;
+ let map = |x: f64, y: f64| {
+ let (u, v) = w.map(x, y);
+ (a * u + c * v + e, b * u + d * v + f)
+ };
+ photocraft_algo::warp::warp_mesh_surface(&img.surface, img.bounds, &map, Interp::Bicubic)
+}
+
+/// `top` blended over `base` with `mode` at `opacity` (a smart filter's blending options).
+fn blend_surfaces(base: &Surface, top: &Surface, mode: BlendMode, opacity: f32) -> Surface {
+ let fmt = base.format();
+ let area = base.content_bounds().union(&top.content_bounds());
+ let mut out = base.clone();
+ if area.is_empty() {
+ return out;
+ }
+ let n = fmt.channels();
+ let (b, t) = (base.read_region(area), top.read_region(area));
+ let mut o = vec![0.0f32; b.len()];
+ for ((bp, tp), op) in b.chunks_exact(n).zip(t.chunks_exact(n)).zip(o.chunks_exact_mut(n)) {
+ let rgba = photocraft_color::blend::composite(mode, photocraft_raster::to_rgba(&fmt, bp), photocraft_raster::to_rgba(&fmt, tp), opacity);
+ photocraft_raster::from_rgba_into(&fmt, rgba, op);
+ }
+ out.write_region(area, &o);
+ out.prune();
+ out
+}
+
+/// Mixes `filtered` over `base` through the filter mask (premultiplied, any channel layout).
+fn mask_mix(base: &Surface, filtered: &Surface, mask: &LayerMask) -> Surface {
+ let fmt = base.format();
+ let area = base.content_bounds().union(&filtered.content_bounds());
+ let mut out = filtered.clone();
+ if area.is_empty() {
+ return out;
+ }
+ let n = fmt.channels();
+ let (b, f) = (base.read_region(area), filtered.read_region(area));
+ let mut k = Vec::new();
+ mask.values_into(area, &mut k);
+ let mut o = vec![0.0f32; b.len()];
+ for (i, ((bp, fp), op)) in b.chunks_exact(n).zip(f.chunks_exact(n)).zip(o.chunks_exact_mut(n)).enumerate() {
+ let m = k.get(i).copied().unwrap_or(1.0).clamp(0.0, 1.0);
+ if !fmt.alpha {
+ for c in 0..n {
+ op[c] = bp[c] + (fp[c] - bp[c]) * m;
+ }
+ continue;
+ }
+ let a = n - 1;
+ let oa = bp[a] + (fp[a] - bp[a]) * m;
+ op[a] = oa;
+ for c in 0..a {
+ let pm = bp[c] * bp[a] + (fp[c] * fp[a] - bp[c] * bp[a]) * m;
+ op[c] = if oa > 0.0 { (pm / oa).clamp(0.0, 1.0) } else { 0.0 };
+ }
+ }
+ out.write_region(area, &o);
+ out.prune();
+ out
+}
+
+/// Runs the smart filter stack on the placed (unfiltered) content.
+pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) -> Surface {
+ if !sm.filters_enabled || !sm.smart_filters.iter().any(|f| f.visible) {
+ return placed.clone();
+ }
+ let mut cur = placed.clone();
+ // Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters.
+ let extent = canvas.union(&placed.content_bounds());
+ for f in sm.smart_filters.iter().filter(|f| f.visible) {
+ // Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone.
+ let Some(out) = crate::filters::apply_filter_to_surface(&f.command, &f.params, &cur, canvas, None, extent) else { continue };
+ cur = if f.blend == BlendMode::Normal && f.opacity >= 1.0 { out } else { blend_surfaces(&cur, &out, f.blend, f.opacity.clamp(0.0, 1.0)) };
+ }
+ match sm.filter_mask.as_ref().filter(|m| m.enabled) {
+ Some(m) => mask_mix(placed, &cur, m),
+ None => cur,
+ }
+}
+
+/// Renders a smart object from its source. `Ok(None)` when the source is unavailable (a missing
+/// linked file, or a PSD placed layer without embedded data): callers keep the existing cache.
+pub fn render(doc: &Document, sm: &SmartObject) -> Result<Option<Surface>> {
+ let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok(None) };
+ let img = match sm.stack_mode {
+ Some(mode) => stack_image(&name, &bytes, doc.pixel_format(), mode)?,
+ None => source_image(&name, &bytes, doc.pixel_format())?,
+ };
+ let placed = match sm.warp.as_ref().filter(|w| !w.is_identity()) {
+ Some(w) => place_warped(&img, w, &sm.transform),
+ None => place(&img, &sm.transform),
+ };
+ Ok(Some(apply_smart_filters(&placed, sm, doc.bounds())))
+}
+
+/// Re-renders smart layer `l` (which lives in `doc`) in place. Returns false if its source is
+/// unavailable (the cache is then left alone).
+pub fn refresh_layer(doc: &Document, l: &mut Layer) -> Result<bool> {
+ let LayerContent::Smart(sm) = &mut l.content else { return Ok(false) };
+ match render(doc, sm)? {
+ Some(px) => {
+ sm.cache = Some(px);
+ Ok(true)
+ }
+ None => Ok(false),
+ }
+}
+
+/// Re-renders the smart object `id` of `doc`.
+pub fn refresh(doc: &mut Document, id: LayerId) -> Result<bool> {
+ let mut l = doc.layer(id).cloned().ok_or(EngineError::NoLayer(id))?;
+ if !matches!(l.content, LayerContent::Smart(_)) {
+ return Err(other("the layer is not a smart object"));
+ }
+ let ok = refresh_layer(doc, &mut l)?;
+ if ok && let Some(dst) = doc.layer_mut(id) {
+ dst.content = l.content;
+ }
+ Ok(ok)
+}
+
+fn refresh_or_fail(doc: &mut Document, id: LayerId) -> Result<()> {
+ if refresh(doc, id)? { Ok(()) } else { Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered")) }
+}
+
+fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> {
+ match &doc.layer(id).ok_or(EngineError::NoLayer(id))?.content {
+ LayerContent::Smart(sm) => Ok(sm),
+ _ => Err(other("the layer is not a smart object")),
+ }
+}
+
+fn smart_mut(doc: &mut Document, id: LayerId) -> Result<&mut SmartObject> {
+ match &mut doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.content {
+ LayerContent::Smart(sm) => Ok(sm),
+ _ => Err(other("the layer is not a smart object")),
+ }
+}
+
+fn mask_from_selection(sel: &Surface) -> LayerMask {
+ LayerMask { surface: sel.clone(), enabled: true, linked: true, density: 1.0, feather: 0.0 }
+}
+
+/// Appends a smart filter (from a `filter.*` command) and re-renders. A selection becomes the
+/// filter mask, as in Photoshop. Without a renderable source the filter is applied to the cached
+/// pixels (and still recorded).
+pub(crate) fn add_smart_filter(doc: &mut Document, id: LayerId, sf: photocraft_doc::SmartFilter, selection: Option<&Surface>) -> Result<()> {
+ let canvas = doc.bounds();
+ let renderable = source_bytes(&doc.metadata, &smart(doc, id)?.source).is_some();
+ let sm = smart_mut(doc, id)?;
+ if renderable {
+ if let Some(sel) = selection
+ && sm.filter_mask.is_none()
+ {
+ sm.filter_mask = Some(mask_from_selection(sel));
+ }
+ sm.smart_filters.push(sf);
+ return refresh_or_fail(doc, id);
+ }
+ let bounds = selection.map(Surface::content_bounds).filter(|b| !b.is_empty()).unwrap_or(canvas);
+ let cache = sm.cache.as_ref().ok_or_else(|| other("smart object has no pixels"))?;
+ let out = crate::filters::apply_filter_to_surface(&sf.command, &sf.params, cache, bounds, selection, canvas).ok_or_else(|| other(format!("unknown filter {}", sf.command)))?;
+ sm.cache = Some(out);
+ sm.smart_filters.push(sf);
+ Ok(())
+}
+
+/// Rounds float noise off a composed transform (scale 0.1 then 10 should be exactly 1), so
+/// repeated transforms land back on exact, lossless placements.
+pub(crate) fn snap_affine(a: Affine) -> Affine {
+ Affine { m: a.m.map(|v| if (v - v.round()).abs() < 1e-9 { v.round() } else { v }) }
+}
+
+/// Moves a smart object by whole pixels without re-rendering.
+pub(crate) fn shift_smart(sm: &mut SmartObject, dx: i32, dy: i32) {
+ sm.transform = Affine::translate(dx as f64, dy as f64).mul(&sm.transform);
+ if let Some(c) = &mut sm.cache {
+ *c = translate_surface(c, dx, dy);
+ }
+ if let Some(m) = &mut sm.filter_mask {
+ m.surface = translate_surface(&m.surface, dx, dy);
+ }
+}
+
+/// Forget PSD placed-layer data that no longer describes the smart object (PSD export then
+/// writes the rendered pixels).
+fn detach_psd(l: &mut Layer) {
+ if let LayerContent::Smart(sm) = &mut l.content {
+ sm.psd_raw = None;
+ }
+ l.psd_blocks.retain(|(k, _)| !PLACED_KEYS.contains(&k));
+}
+
+// ---------- conversion ----------
+
+/// Moves a layer (any kind) by whole pixels without re-rendering anything.
+fn shift_layer(l: &mut Layer, dx: i32, dy: i32) {
+ if dx == 0 && dy == 0 {
+ return;
+ }
+ let a = Affine::translate(dx as f64, dy as f64);
+ let mv = |s: &Surface| translate_surface(s, dx, dy);
+ if let Some(m) = &mut l.mask {
+ m.surface = mv(&m.surface);
+ }
+ if let Some(vm) = &mut l.vector_mask {
+ vm.path = vm.path.transform(&a);
+ }
+ if let Some(fc) = &mut l.fill_cache {
+ fc.surface = mv(&fc.surface);
+ }
+ match &mut l.content {
+ LayerContent::Raster(s) => *s = mv(s),
+ LayerContent::Text(t) => {
+ t.transform = a.mul(&t.transform);
+ if let Some(c) = &mut t.cache {
+ *c = mv(c);
+ }
+ }
+ LayerContent::Shape(sh) => {
+ crate::vector_cmds::transform_shape(sh, &a);
+ if let Some(c) = &mut sh.cache {
+ *c = mv(c);
+ }
+ }
+ LayerContent::Smart(sm) => shift_smart(sm, dx, dy),
+ LayerContent::Group(g) => g.children.iter_mut().for_each(|c| shift_layer(c, dx, dy)),
+ LayerContent::Adjustment(_) | LayerContent::Fill(_) => {}
+ }
+}
+
+fn subtree_bounds(l: &Layer, canvas: Rect) -> Rect {
+ match &l.content {
+ LayerContent::Group(g) => g.children.iter().map(|c| subtree_bounds(c, canvas)).fold(Rect::EMPTY, |a, b| a.union(&b)),
+ LayerContent::Adjustment(_) | LayerContent::Fill(_) => canvas,
+ _ => l.surface().map_or(Rect::EMPTY, Surface::content_bounds),
+ }
+}
+
+fn any_layer(l: &Layer, f: &dyn Fn(&Layer) -> bool) -> bool {
+ f(l) || l.children().is_some_and(|c| c.iter().any(|c| any_layer(c, f)))
+}
+
+/// Builds the smart-object layer replacing `l` in `doc`: the layer (with its mask, effects and
+/// fill opacity) becomes a nested document cropped to its rendered bounds; visibility, opacity,
+/// blend mode, clipping and label stay on the smart layer. The cache is the exact composite, so
+/// the document looks the same before and after.
+pub fn layer_to_smart(doc: &Document, l: &Layer) -> Result<Layer> {
+ let canvas = doc.bounds();
+ let background = l.name == "Background" && l.locks.position;
+ let mut inner = l.clone();
+ inner.visible = true;
+ inner.opacity = 1.0;
+ inner.clipped = false;
+ inner.locks = Default::default();
+ if !(inner.is_group() && inner.blend == BlendMode::PassThrough) {
+ inner.blend = BlendMode::Normal;
+ }
+ if background {
+ inner.name = "Layer 0".into();
+ }
+ let mut sub = Document::new(format!("{}.pcraft", l.name), doc.size, doc.mode, doc.depth);
+ sub.resolution_dpi = doc.resolution_dpi;
+ sub.icc_profile = doc.icc_profile.clone();
+ sub.global_light = doc.global_light;
+ if any_layer(l, &|x| matches!(x.content, LayerContent::Smart(_))) {
+ // Nested PSD placed layers find their embedded files here.
+ sub.metadata.psd_global_blocks = doc.metadata.psd_global_blocks.clone();
+ }
+ sub.layers = vec![inner];
+
+ let has_fx = any_layer(l, &|x| x.effects.enabled && !x.effects.items.is_empty());
+ let region = subtree_bounds(l, canvas).union(&canvas).inflate(if has_fx { 256 } else { 0 });
+ let buf = photocraft_compose::render(&sub, region);
+ let w = region.width() as usize;
+ let mut b = Rect::EMPTY;
+ for (i, p) in buf.px.iter().enumerate() {
+ if p[3] > 0.0 {
+ let (x, y) = (region.x0 + (i % w) as i32, region.y0 + (i / w) as i32);
+ b = b.union(&Rect::new(x, y, x + 1, y + 1));
+ }
+ }
+ if b.is_empty() {
+ return Err(other("the layer is empty, so there is nothing to convert"));
+ }
+ let fmt = doc.pixel_format();
+ let mut cache = buffer_to_surface(&buf, fmt);
+ cache = photocraft_algo::resample::crop_surface(&cache, b);
+ cache.prune();
+
+ shift_layer(&mut sub.layers[0], -b.x0, -b.y0);
+ sub.size = Size::new(b.width(), b.height());
+ let bytes = encode_source(&sub)?;
+ // Seed the decode cache with the composite we already have.
+ cache_put(cache_key(&bytes, fmt), SourceImage { surface: Arc::new(translate_surface(&cache, -b.x0, -b.y0)), bounds: sub.bounds() });
+
+ let source = SmartSource::Embedded { file_name: sub.name.clone(), bytes: Arc::new(bytes) };
+ let mut out = Layer::new(if background { "Layer 0".to_string() } else { l.name.clone() }, LayerContent::Smart(SmartObject::new(source, Affine::translate(b.x0 as f64, b.y0 as f64), Some(cache))));
+ out.visible = l.visible;
+ out.opacity = l.opacity;
+ out.blend = if l.blend == BlendMode::PassThrough { BlendMode::Normal } else { l.blend };
+ out.clipped = l.clipped;
+ out.label = l.label;
+ if !background {
+ out.locks = l.locks;
+ }
+ Ok(out)
+}
+
+fn convert(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ s.edit("Convert to Smart Object", |doc, active| {
+ let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let so = layer_to_smart(doc, l)?;
+ let new_id = so.id;
+ let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?;
+ *doc.layer_at_mut(&path).ok_or(EngineError::NoLayer(id))? = so;
+ *active = Some(new_id);
+ Ok(json!({"layer": new_id.0}))
+ })
+}
+
+// ---------- contents ----------
+
+fn via_copy(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ s.edit("New Smart Object via Copy", |doc, active| {
+ let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let mut copy = src.duplicate();
+ copy.name = format!("{} copy", src.name);
+ if let LayerContent::Smart(sm) = &mut copy.content {
+ // Independent contents: resolve to embedded bytes and drop the shared PSD uuid.
+ if let Some((file_name, bytes)) = source_bytes(&doc.metadata, &sm.source) {
+ sm.source = SmartSource::Embedded { file_name, bytes };
+ }
+ } else {
+ return Err(other("the layer is not a smart object"));
+ }
+ detach_psd(&mut copy);
+ let new_id = doc.insert_above(Some(id), copy);
+ *active = Some(new_id);
+ Ok(json!({"layer": new_id.0}))
+ })
+}
+
+fn path_param<'a>(cmd: &str, p: &'a Value) -> Result<&'a str> {
+ p.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "pass `path`"))
+}
+
+/// Swaps a smart object's source, keeping its transform and filters, and re-renders.
+fn set_source(s: &mut Session, p: &Value, label: &str, keep_psd: bool, make: impl FnOnce(&Metadata, &SmartSource) -> Result<SmartSource>) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ s.edit(label, |doc, _| {
+ let new = make(&doc.metadata, &smart(doc, id)?.source)?;
+ smart_mut(doc, id)?.source = new;
+ if !keep_psd {
+ detach_psd(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?);
+ }
+ refresh_or_fail(doc, id)?;
+ Ok(json!({"layer": id.0}))
+ })
+}
+
+fn replace_contents(s: &mut Session, p: &Value) -> Result<Value> {
+ let path = path_param("layer.smartObjects.replaceContents", p)?.to_string();
+ let bytes = std::fs::read(&path).map_err(|e| other(format!("can't read {path}: {e}")))?;
+ let name = base_name(&path);
+ decode_source(&name, &bytes)?; // fail before touching the document
+ set_source(s, p, "Replace Contents", false, |_, _| Ok(SmartSource::Embedded { file_name: name, bytes: Arc::new(bytes) }))
+}
+
+fn export_contents(s: &mut Session, p: &Value) -> Result<Value> {
+ let path = path_param("layer.smartObjects.exportContents", p)?;
+ let id = layer_param(s, p)?;
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let (name, bytes) = source_bytes(&st.doc.metadata, &smart(&st.doc, id)?.source).ok_or_else(|| other("the smart object's contents are unavailable"))?;
+ std::fs::write(path, &*bytes).map_err(|e| other(format!("can't write {path}: {e}")))?;
+ Ok(json!({"path": path, "fileName": name, "bytes": bytes.len()}))
+}
+
+fn edit_contents(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let parent = st.doc.id;
+ let (name, bytes) = source_bytes(&st.doc.metadata, &smart(&st.doc, id)?.source).ok_or_else(|| other("the smart object's contents are unavailable"))?;
+ let mut child = decode_source(&name, &bytes)?;
+ // Bundles keep their document id; each open copy needs its own.
+ child.id = DocId::fresh();
+ child.name = name;
+ let child_id = child.id;
+ let index = s.add_document(child, None);
+ s.smart_links.retain(|l| l.child != child_id);
+ s.smart_links.push(SmartLink { child: child_id, parent, layer: id });
+ Ok(json!({"document": index, "parentLayer": id.0}))
+}
+
+/// Writes an Edit Contents document back into its parent smart object (one undoable step in the
+/// parent) and marks it saved. Returns false if `index` isn't an Edit Contents document.
+pub fn commit_child(s: &mut Session, index: usize) -> Result<bool> {
+ let Some(st) = s.docs.get(index) else { return Ok(false) };
+ let child = st.doc.clone();
+ let Some(link) = s.smart_links.iter().find(|l| l.child == child.id).copied() else { return Ok(false) };
+ let parent = s.docs.iter().position(|d| d.doc.id == link.parent).ok_or_else(|| other("the smart object's document was closed"))?;
+ let bytes = Arc::new(encode_source(&child)?);
+ let prev = s.active;
+ s.active = Some(parent);
+ let r = s.edit("Edit Contents", |doc, _| {
+ let sm = smart_mut(doc, link.layer)?;
+ let stem = match &sm.source {
+ SmartSource::Embedded { file_name, .. } => file_name.rsplit_once('.').map_or(file_name.as_str(), |(a, _)| a).to_string(),
+ SmartSource::Linked { .. } => child.name.rsplit_once('.').map_or(child.name.as_str(), |(a, _)| a).to_string(),
+ };
+ sm.source = SmartSource::Embedded { file_name: format!("{stem}.pcraft"), bytes: bytes.clone() };
+ detach_psd(doc.layer_mut(link.layer).ok_or(EngineError::NoLayer(link.layer))?);
+ refresh_or_fail(doc, link.layer)
+ });
+ s.active = prev;
+ r?;
+ if let Some(st) = s.docs.get_mut(index) {
+ st.saved_revision = st.revision;
+ }
+ Ok(true)
+}
+
+/// Called before a document closes: an edited Edit Contents document updates its parent.
+pub(crate) fn on_close(s: &mut Session, index: usize) {
+ let Some(st) = s.docs.get(index) else { return };
+ let id = st.doc.id;
+ if st.is_dirty() && s.smart_links.iter().any(|l| l.child == id) {
+ let _ = commit_child(s, index);
+ }
+ s.smart_links.retain(|l| l.child != id && l.parent != id);
+}
+
+fn is_smart_child(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if s.smart_links.iter().any(|l| l.child == d.doc.id) { Ok(()) } else { Err("this document isn't smart object contents".into()) }
+}
+
+fn update_all(s: &mut Session) -> Result<Value> {
+ let ids: Vec<LayerId> = s
+ .active()
+ .ok_or(EngineError::NoDocument)?
+ .doc
+ .walk()
+ .into_iter()
+ .filter(|(_, _, l)| matches!(&l.content, LayerContent::Smart(sm) if matches!(sm.source, SmartSource::Linked { .. })))
+ .map(|(_, _, l)| l.id)
+ .collect();
+ let mut updated = Vec::new();
+ s.edit("Update All Modified Content", |doc, _| {
+ for id in &ids {
+ if refresh(doc, *id)? {
+ updated.push(id.0);
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({"updated": updated}))
+}
+
+// ---------- smart filter editing ----------
+
+fn edit_filters(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut SmartObject) -> Result<()>) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ s.edit(label, |doc, _| {
+ f(smart_mut(doc, id)?)?;
+ refresh_or_fail(doc, id)?;
+ Ok(json!({"layer": id.0}))
+ })
+}
+
+fn filter_index(cmd: &str, p: &Value, sm: &SmartObject) -> Result<usize> {
+ let n = sm.smart_filters.len();
+ if n == 0 {
+ return Err(other("the smart object has no smart filters"));
+ }
+ match p.get("index") {
+ None => Ok(n - 1),
+ Some(v) => v.as_u64().map(|i| i as usize).filter(|i| *i < n).ok_or_else(|| bad(cmd, format!("`index` must be 0..{n} (0 = bottom filter)"))),
+ }
+}
+
+fn set_filter_visible(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "layer.smartFilter.setVisible";
+ edit_filters(s, p, "Smart Filter Visibility", |sm| {
+ let i = filter_index(CMD, p, sm)?;
+ let f = &mut sm.smart_filters[i];
+ f.visible = p.get("visible").and_then(Value::as_bool).unwrap_or(!f.visible);
+ Ok(())
+ })
+}
+
+fn set_filter_params(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "layer.smartFilter.setParams";
+ let new = p.get("params").cloned().ok_or_else(|| bad(CMD, "pass `params` (merged into the filter's parameters)"))?;
+ edit_filters(s, p, "Edit Smart Filter", |sm| {
+ let i = filter_index(CMD, p, sm)?;
+ let f = &mut sm.smart_filters[i];
+ match (&mut f.params, new) {
+ (Value::Object(old), Value::Object(n)) => old.extend(n),
+ (slot, n) => *slot = n,
+ }
+ Ok(())
+ })
+}
+
+fn blending_options(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "layer.smartFilter.blendingOptions";
+ let blend = match p.get("blend").and_then(Value::as_str) {
+ Some(b) => Some(blend_from_str(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?),
+ None => None,
+ };
+ let opacity = p.get("opacity").and_then(Value::as_f64).map(|o| if o > 1.0 { o / 100.0 } else { o } as f32);
+ edit_filters(s, p, "Smart Filter Blending Options", |sm| {
+ let i = filter_index(CMD, p, sm)?;
+ let f = &mut sm.smart_filters[i];
+ if let Some(b) = blend {
+ f.blend = b;
+ }
+ if let Some(o) = opacity {
+ f.opacity = o.clamp(0.0, 1.0);
+ }
+ Ok(())
+ })
+}
+
+fn delete_filter(s: &mut Session, p: &Value) -> Result<Value> {
+ edit_filters(s, p, "Delete Smart Filter", |sm| {
+ let i = filter_index("layer.smartFilter.delete", p, sm)?;
+ sm.smart_filters.remove(i);
+ Ok(())
+ })
+}
+
+fn move_filter(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "layer.smartFilter.move";
+ edit_filters(s, p, "Move Smart Filter", |sm| {
+ let i = filter_index(CMD, p, sm)?;
+ let n = sm.smart_filters.len();
+ let to = p.get("to").and_then(Value::as_u64).map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(CMD, format!("`to` must be 0..{n}")))?;
+ let f = sm.smart_filters.remove(i);
+ sm.smart_filters.insert(to, f);
+ Ok(())
+ })
+}
+
+// ---------- enablement ----------
+
+fn active_smart(s: &Session) -> std::result::Result<&SmartObject, String> {
+ let d = s.active().ok_or("no document open")?;
+ let id = d.active_layer.ok_or("no active layer")?;
+ match &d.doc.layer(id).ok_or("no active layer")?.content {
+ LayerContent::Smart(sm) => Ok(sm),
+ other => Err(format!("the active layer is a {} layer, not a smart object", other.kind_name())),
+ }
+}
+fn has_smart(s: &Session) -> std::result::Result<(), String> {
+ active_smart(s).map(|_| ())
+}
+fn has_linked(s: &Session) -> std::result::Result<(), String> {
+ match active_smart(s)?.source {
+ SmartSource::Linked { .. } => Ok(()),
+ _ => Err("the smart object is embedded".into()),
+ }
+}
+fn has_smart_filters(s: &Session) -> std::result::Result<(), String> {
+ if active_smart(s)?.smart_filters.is_empty() { Err("the smart object has no smart filters".into()) } else { Ok(()) }
+}
+fn has_filter_mask(s: &Session) -> std::result::Result<(), String> {
+ active_smart(s)?.filter_mask.as_ref().map(|_| ()).ok_or_else(|| "the smart object has no filter mask".into())
+}
+fn convertible(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ let id = d.active_layer.ok_or("no active layer")?;
+ d.doc.layer(id).map(|_| ()).ok_or_else(|| "no active layer".into())
+}
+fn not_smart(s: &Session) -> std::result::Result<(), String> {
+ convertible(s)?;
+ if active_smart(s).is_ok() { Err("the layer is already a smart object".into()) } else { Ok(()) }
+}
+
+macro_rules! spec {
+ ($id:literal, $label:literal, $menu:expr, $params:literal, $en:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: $menu, shortcut: None, params: $params, enabled: $en, run: $run, journal: true }
+ };
+}
+
+const SO: &[&str] = &["Layer", "Smart Objects"];
+const SF: &[&str] = &["Layer", "Smart Filter"];
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!("layer.smartObjects.convertToSmartObject", "Convert to Smart Object", SO, r##"{"layer":id?}"##, convertible, convert),
+ spec!("filter.convertForSmartFilters", "Convert for Smart Filters", &["Filter"], r##"{"layer":id?}"##, not_smart, convert),
+ spec!("layer.smartObjects.newSmartObjectViaCopy", "New Smart Object via Copy", SO, r##"{"layer":id?}"##, has_smart, via_copy),
+ spec!("layer.smartObjects.rasterize", "Rasterize", SO, r##"{"layer":id?}"##, has_smart, |s, p| s.execute("layer.rasterize.smartObject", p.clone())),
+ spec!("layer.smartObjects.editContents", "Edit Contents", SO, r##"{"layer":id?} → opens the contents as a new document; saving (layer.smartObjects.saveContents) or closing it updates the smart object"##, has_smart, edit_contents),
+ spec!("layer.smartObjects.saveContents", "Save Contents", &[], "{} (in an Edit Contents document)", is_smart_child, |s, _| {
+ let i = s.active_index().ok_or(EngineError::NoDocument)?;
+ Ok(json!({"updated": commit_child(s, i)?}))
+ }),
+ spec!("layer.smartObjects.replaceContents", "Replace Contents…", SO, r##"{"layer":id?,"path":str}"##, has_smart, replace_contents),
+ spec!("layer.smartObjects.exportContents", "Export Contents…", SO, r##"{"layer":id?,"path":str}"##, has_smart, export_contents),
+ spec!("layer.smartObjects.relinkToFile", "Relink to File…", SO, r##"{"layer":id?,"path":str}"##, has_smart, |s, p| {
+ let path = path_param("layer.smartObjects.relinkToFile", p)?.to_string();
+ set_source(s, p, "Relink to File", false, |_, _| Ok(SmartSource::Linked { path }))
+ }),
+ spec!("layer.smartObjects.updateModifiedContent", "Update Modified Content", SO, r##"{"layer":id?}"##, has_linked, |s, p| {
+ let id = layer_param(s, p)?;
+ s.edit("Update Modified Content", |doc, _| refresh_or_fail(doc, id))?;
+ Ok(json!({"layer": id.0}))
+ }),
+ spec!("layer.smartObjects.updateAllModifiedContent", "Update All Modified Content", SO, "{}", |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), |s, _| update_all(s)),
+ spec!("layer.smartObjects.convertToEmbedded", "Convert to Embedded", SO, r##"{"layer":id?}"##, has_linked, |s, p| {
+ set_source(s, p, "Convert to Embedded", true, |meta, src| {
+ let (file_name, bytes) = source_bytes(meta, src).ok_or_else(|| other("the linked file can't be read"))?;
+ Ok(SmartSource::Embedded { file_name, bytes })
+ })
+ }),
+ spec!("layer.smartObjects.convertToLinked", "Convert to Linked…", SO, r##"{"layer":id?,"path":str} (writes the contents there)"##, has_smart, |s, p| {
+ let path = path_param("layer.smartObjects.convertToLinked", p)?.to_string();
+ set_source(s, p, "Convert to Linked", false, |meta, src| {
+ let (_, bytes) = source_bytes(meta, src).ok_or_else(|| other("the smart object's contents are unavailable"))?;
+ std::fs::write(&path, &*bytes).map_err(|e| other(format!("can't write {path}: {e}")))?;
+ Ok(SmartSource::Linked { path })
+ })
+ }),
+ // Smart filters
+ spec!("layer.smartFilter.disableSmartFilters", "Disable Smart Filters", SF, r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, has_smart_filters, |s, p| {
+ edit_filters(s, p, "Disable Smart Filters", |sm| {
+ sm.filters_enabled = p.get("enabled").and_then(Value::as_bool).unwrap_or(!sm.filters_enabled);
+ Ok(())
+ })
+ }),
+ spec!("layer.smartFilter.deleteFilterMask", "Delete Filter Mask", SF, r##"{"layer":id?}"##, has_filter_mask, |s, p| {
+ edit_filters(s, p, "Delete Filter Mask", |sm| {
+ sm.filter_mask = None;
+ Ok(())
+ })
+ }),
+ spec!("layer.smartFilter.disableFilterMask", "Disable Filter Mask", SF, r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, has_filter_mask, |s, p| {
+ edit_filters(s, p, "Disable Filter Mask", |sm| {
+ if let Some(m) = &mut sm.filter_mask {
+ m.enabled = p.get("enabled").and_then(Value::as_bool).unwrap_or(!m.enabled);
+ }
+ Ok(())
+ })
+ }),
+ spec!("layer.smartFilter.blendingOptions", "Blending Options…", SF, r##"{"layer":id?,"index":u32? (0 = bottom; default top),"blend":str?,"opacity":0..1?}"##, has_smart_filters, blending_options),
+ spec!("layer.smartFilter.clearSmartFilters", "Clear Smart Filters", SF, r##"{"layer":id?}"##, has_smart_filters, |s, p| {
+ edit_filters(s, p, "Clear Smart Filters", |sm| {
+ sm.smart_filters.clear();
+ sm.filter_mask = None;
+ Ok(())
+ })
+ }),
+ spec!("layer.smartFilter.setVisible", "Show/Hide Smart Filter", &[], r##"{"layer":id?,"index":u32?,"visible":bool? (default: toggle)}"##, has_smart_filters, set_filter_visible),
+ spec!("layer.smartFilter.setParams", "Edit Smart Filter", &[], r##"{"layer":id?,"index":u32?,"params":{…} (merged)}"##, has_smart_filters, set_filter_params),
+ spec!("layer.smartFilter.delete", "Delete Smart Filter", &[], r##"{"layer":id?,"index":u32?}"##, has_smart_filters, delete_filter),
+ spec!("layer.smartFilter.move", "Move Smart Filter", &[], r##"{"layer":id?,"index":u32?,"to":u32}"##, has_smart_filters, move_filter),
+ ]
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rs
new file mode 100644
index 000000000..b5f83d03f
--- /dev/null
+++ b/crates/engine/src/smart_cmds/tests.rs
@@ -0,0 +1,488 @@
+use super::*;
+
+const DEPTHS: [u64; 3] = [8, 16, 32];
+const W: i32 = 64;
+const H: i32 = 48;
+
+fn session(depth: u64) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": W, "height": H, "depth": depth})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s
+}
+
+/// Paints a textured block on the active layer, partly outside the canvas (top-left), so
+/// conversion has to keep off-canvas pixels and crop/translate correctly.
+fn paint(s: &mut Session) {
+ s.edit("setup", |doc, active| {
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ let fmt = surf.format();
+ let r = Rect::new(-6, 5, 40, 38);
+ let mut data = Vec::new();
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ let v = ((x * 7 + y * 13) % 23) as f32 / 22.0;
+ let a = if (x + y) % 5 == 0 { 0.5 } else { 1.0 };
+ data.extend(photocraft_raster::from_rgba(&fmt, [v, 1.0 - v, ((x * y) % 7) as f32 / 6.0, a]));
+ }
+ }
+ surf.write_region(r, &data);
+ Ok(())
+ })
+ .unwrap();
+}
+
+fn flat(s: &Session) -> Vec<[f32; 4]> {
+ photocraft_compose::flatten(&s.active().unwrap().doc).px
+}
+
+fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 {
+ a.iter().zip(b).flat_map(|(p, q)| (0..4).map(move |c| (p[c] - q[c]).abs())).fold(0.0, f32::max)
+}
+
+fn mean_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 {
+ let sum: f32 = a.iter().zip(b).map(|(p, q)| (0..4).map(|c| (p[c] - q[c]).abs()).sum::<f32>()).sum();
+ sum / (a.len() * 4) as f32
+}
+
+fn active_smart(s: &Session) -> SmartObject {
+ let d = s.active().unwrap();
+ match &d.doc.layer(d.active_layer.unwrap()).unwrap().content {
+ LayerContent::Smart(sm) => sm.clone(),
+ other => panic!("not smart: {}", other.kind_name()),
+ }
+}
+
+fn convert(s: &mut Session) -> u64 {
+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap()
+}
+
+#[test]
+fn conversion_is_pixel_identical_at_every_depth() {
+ for depth in DEPTHS {
+ let mut s = session(depth);
+ paint(&mut s);
+ let id = s.active().unwrap().active_layer.unwrap();
+ s.edit("opacity", |doc, _| {
+ doc.layer_mut(id).unwrap().opacity = 0.6;
+ Ok(())
+ })
+ .unwrap();
+ let before = flat(&s);
+ convert(&mut s);
+ assert_eq!(max_diff(&flat(&s), &before), 0.0, "depth {depth}");
+ let d = s.active().unwrap();
+ let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
+ assert!((l.opacity - 0.6).abs() < 1e-6, "opacity stays on the smart layer");
+ let sm = active_smart(&s);
+ let SmartSource::Embedded { file_name, bytes } = &sm.source else { panic!() };
+ assert!(file_name.ends_with(".pcraft"));
+ // The nested document is cropped to the content, including the off-canvas part.
+ let inner = decode_source(file_name, bytes).unwrap();
+ assert_eq!((inner.size.width, inner.size.height), (46, 33));
+ assert_eq!(inner.depth, d.doc.depth);
+ assert_eq!(sm.transform, Affine::translate(-6.0, 5.0));
+ // Re-rendering from the source reproduces the conversion cache exactly.
+ let rendered = render(&d.doc, &sm).unwrap().unwrap();
+ let b = Rect::new(-6, 5, 40, 38);
+ assert_eq!(rendered.read_region(b), sm.cache.as_ref().unwrap().read_region(b), "depth {depth}");
+ s.undo();
+ assert_eq!(flat(&s), before);
+ }
+}
+
+#[test]
+fn masked_layer_and_group_convert_within_rounding() {
+ let mut s = session(8);
+ paint(&mut s);
+ s.edit("mask", |doc, active| {
+ let l = doc.layer_mut(active.unwrap()).unwrap();
+ let mut m = LayerMask::reveal_all();
+ m.surface.fill_rect(Rect::new(0, 0, 20, 20), &[0.3]);
+ l.mask = Some(m);
+ Ok(())
+ })
+ .unwrap();
+ let before = flat(&s);
+ convert(&mut s);
+ assert!(max_diff(&flat(&s), &before) <= 1.0 / 255.0 + 1e-6);
+ // A group converts too (its children move into the nested document).
+ s.execute("layer.new.layer", json!({})).unwrap();
+ paint(&mut s);
+ s.execute("layer.groupLayers", json!({})).unwrap();
+ let before = flat(&s);
+ convert(&mut s);
+ assert!(max_diff(&flat(&s), &before) <= 1.0 / 255.0 + 1e-6);
+}
+
+#[test]
+fn empty_layer_cannot_be_converted() {
+ let mut s = session(8);
+ assert!(s.execute("layer.smartObjects.convertToSmartObject", json!({})).is_err());
+}
+
+#[test]
+fn smart_filters_are_re_editable() {
+ for depth in [8, 16] {
+ let mut s = session(depth);
+ paint(&mut s);
+ let original = flat(&s);
+ s.execute("filter.convertForSmartFilters", json!({})).unwrap();
+ assert!(!s.is_enabled("filter.convertForSmartFilters"), "already smart");
+ s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap();
+ let r2 = flat(&s);
+ assert!(max_diff(&r2, &original) > 0.05);
+ let sm = active_smart(&s);
+ assert_eq!(sm.smart_filters.len(), 1);
+ let SmartSource::Embedded { bytes, .. } = &sm.source else { panic!() };
+ // Change the radius: the result comes from the source, not from the blurred pixels.
+ s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": {"radius": 6}})).unwrap();
+ let r6 = flat(&s);
+ assert!(max_diff(&r6, &r2) > 0.01);
+ s.execute("layer.smartFilter.setParams", json!({"params": {"radius": 2}})).unwrap();
+ assert!(max_diff(&flat(&s), &r2) < 1e-6, "same params, same pixels");
+ // Hiding the filter shows the original exactly.
+ s.execute("layer.smartFilter.setVisible", json!({"index": 0})).unwrap();
+ assert_eq!(flat(&s), original);
+ assert!(!active_smart(&s).smart_filters[0].visible);
+ s.undo();
+ assert!(max_diff(&flat(&s), &r2) < 1e-6);
+ s.redo();
+ assert_eq!(flat(&s), original);
+ // All of that decoded the contents at most once (the conversion seeded the cache).
+ assert!(source_decode_count(bytes, s.active().unwrap().doc.pixel_format()) <= 1);
+ }
+}
+
+#[test]
+fn filter_stack_order_blend_disable_and_clear() {
+ let mut s = session(8);
+ paint(&mut s);
+ let original = flat(&s);
+ convert(&mut s);
+ s.execute("filter.other.offset", json!({"horizontal": 5, "undefinedAreas": "transparent"})).unwrap();
+ s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap();
+ let ab = flat(&s);
+ s.execute("layer.smartFilter.move", json!({"index": 1, "to": 0})).unwrap();
+ assert_eq!(active_smart(&s).smart_filters[0].command, "filter.blur.gaussianBlur");
+ assert!(max_diff(&flat(&s), &ab) > 1e-3, "order matters");
+ s.undo();
+ assert_eq!(flat(&s), ab);
+ // 0 % opacity on both filters = original.
+ s.execute("layer.smartFilter.blendingOptions", json!({"index": 0, "opacity": 0})).unwrap();
+ s.execute("layer.smartFilter.blendingOptions", json!({"index": 1, "opacity": 0, "blend": "multiply"})).unwrap();
+ assert!(max_diff(&flat(&s), &original) < 1e-6);
+ assert_eq!(active_smart(&s).smart_filters[1].blend, BlendMode::Multiply);
+ assert!(s.execute("layer.smartFilter.blendingOptions", json!({"blend": "nope"})).is_err());
+ s.undo();
+ s.undo();
+ s.execute("layer.smartFilter.disableSmartFilters", json!({})).unwrap();
+ assert_eq!(flat(&s), original);
+ assert!(!active_smart(&s).filters_enabled);
+ s.execute("layer.smartFilter.disableSmartFilters", json!({})).unwrap();
+ assert_eq!(flat(&s), ab);
+ s.execute("layer.smartFilter.delete", json!({"index": 0})).unwrap();
+ assert_eq!(active_smart(&s).smart_filters.len(), 1);
+ assert!(s.execute("layer.smartFilter.delete", json!({"index": 5})).is_err());
+ s.execute("layer.smartFilter.clearSmartFilters", json!({})).unwrap();
+ assert_eq!(flat(&s), original);
+ assert!(!s.is_enabled("layer.smartFilter.clearSmartFilters"));
+}
+
+#[test]
+fn selection_becomes_the_filter_mask() {
+ let mut s = session(8);
+ paint(&mut s);
+ let original = flat(&s);
+ convert(&mut s);
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 48})).unwrap();
+ s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap();
+ assert!(active_smart(&s).filter_mask.is_some());
+ let px = flat(&s);
+ let at = |v: &Vec<[f32; 4]>, x: i32, y: i32| v[(y * W + x) as usize];
+ assert_eq!(at(&px, 30, 20), at(&original, 30, 20), "outside the mask: unfiltered");
+ assert_ne!(at(&px, 6, 20), at(&original, 6, 20), "inside the mask: filtered");
+ s.execute("layer.smartFilter.disableFilterMask", json!({})).unwrap();
+ assert_ne!(at(&flat(&s), 30, 20), at(&original, 30, 20));
+ s.execute("layer.smartFilter.deleteFilterMask", json!({})).unwrap();
+ assert!(active_smart(&s).filter_mask.is_none());
+ assert!(!s.is_enabled("layer.smartFilter.deleteFilterMask"));
+}
+
+/// Scales `id` to 10 % around the origin and back, returning the composite.
+fn shrink_and_grow(s: &mut Session, id: u64) -> Vec<[f32; 4]> {
+ s.execute("edit.transform", json!({"layer": id, "matrix": [0.1, 0, 0, 0.1, 0, 0]})).unwrap();
+ s.execute("edit.transform", json!({"layer": id, "matrix": [10, 0, 0, 10, 0, 0]})).unwrap();
+ flat(s)
+}
+
+#[test]
+fn transforms_re_render_from_source_losslessly() {
+ let mut raster = session(8);
+ paint(&mut raster);
+ let original = flat(&raster);
+ let rid = raster.active().unwrap().active_layer.unwrap().0;
+ let raster_result = shrink_and_grow(&mut raster, rid);
+
+ let mut smart = session(8);
+ paint(&mut smart);
+ let sid = convert(&mut smart);
+ // Scaled down, the smart object really is small...
+ smart.execute("edit.transform", json!({"layer": sid, "matrix": [0.1, 0, 0, 0.1, 0, 0]})).unwrap();
+ let small = active_smart(&smart).cache.unwrap().content_bounds();
+ assert!(small.width() <= 7, "{small:?}");
+ // ...and scaled back up it is the original again.
+ smart.execute("edit.transform", json!({"layer": sid, "matrix": [10, 0, 0, 10, 0, 0]})).unwrap();
+ let smart_result = flat(&smart);
+ let (es, er) = (mean_diff(&smart_result, &original), mean_diff(&raster_result, &original));
+ assert!(es < 1e-6, "smart error {es}");
+ assert!(er > 0.02, "raster error {er}");
+ // A non-integer move re-renders with bicubic; moving back is exact again.
+ smart.execute("edit.transform", json!({"layer": sid, "matrix": [1, 0, 0, 1, 0.5, 0.25]})).unwrap();
+ assert!(max_diff(&flat(&smart), &original) > 0.01);
+ smart.execute("edit.transform", json!({"layer": sid, "matrix": [1, 0, 0, 1, -0.5, -0.25]})).unwrap();
+ assert!(max_diff(&flat(&smart), &original) < 1e-6);
+ // Whole-pixel moves (Move tool) shift without re-rendering.
+ smart.execute("layer.translate", json!({"dx": 3, "dy": -2})).unwrap();
+ assert_eq!(active_smart(&smart).transform, Affine::translate(-3.0, 3.0));
+ // Perspective is refused (for now) rather than silently rasterizing.
+ assert!(smart.execute("edit.transform", json!({"layer": sid, "quad": [[0, 0], [10, 0], [12, 10], [-2, 10]]})).is_err());
+}
+
+#[test]
+fn filters_follow_transforms() {
+ let mut s = session(16);
+ paint(&mut s);
+ let id = convert(&mut s);
+ s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap();
+ let blurred = flat(&s);
+ s.execute("edit.transform", json!({"layer": id, "matrix": [2, 0, 0, 2, 0, 0]})).unwrap();
+ assert_eq!(active_smart(&s).smart_filters.len(), 1);
+ s.execute("edit.transform", json!({"layer": id, "matrix": [0.5, 0, 0, 0.5, 0, 0]})).unwrap();
+ assert!(max_diff(&flat(&s), &blurred) < 1e-6, "filter re-applied to the re-rendered source");
+}
+
+#[test]
+fn edit_contents_updates_the_parent() {
+ let mut s = session(8);
+ paint(&mut s);
+ let id = convert(&mut s);
+ let before = flat(&s);
+ let r = s.execute("layer.smartObjects.editContents", json!({})).unwrap();
+ let child = r["document"].as_u64().unwrap() as usize;
+ assert_eq!(s.active_index(), Some(child));
+ assert!(s.is_enabled("layer.smartObjects.saveContents"));
+ // Paint the nested document's layer solid red.
+ s.edit("paint", |doc, _| {
+ let l = &mut doc.layers[0];
+ let b = Rect::new(0, 0, 46, 33);
+ l.surface_mut().unwrap().fill_rect(b, &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("layer.smartObjects.saveContents", json!({})).unwrap();
+ assert!(!s.active().unwrap().is_dirty());
+ s.set_active(0);
+ let after = flat(&s);
+ assert_eq!(after[(20 * W + 10) as usize], [1.0, 0.0, 0.0, 1.0]);
+ assert_ne!(after, before);
+ s.undo();
+ assert_eq!(flat(&s), before, "the update is one undoable step in the parent");
+ s.redo();
+ // Closing an edited contents document also commits it.
+ s.set_active(child);
+ s.edit("paint2", |doc, _| {
+ doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 46, 33), &[0.0, 0.0, 1.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("file.close", json!({})).unwrap();
+ assert!(s.smart_links.is_empty());
+ s.set_active(0);
+ assert_eq!(flat(&s)[(20 * W + 10) as usize], [0.0, 0.0, 1.0, 1.0]);
+ let d = s.active().unwrap();
+ assert!(matches!(d.doc.layer(LayerId(id)).unwrap().content, LayerContent::Smart(_)));
+}
+
+#[test]
+fn rasterize_and_via_copy() {
+ let mut s = session(8);
+ paint(&mut s);
+ convert(&mut s);
+ s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap();
+ let blurred = flat(&s);
+ // Via copy: an independent smart object above.
+ let copy = s.execute("layer.smartObjects.newSmartObjectViaCopy", json!({})).unwrap()["layer"].as_u64().unwrap();
+ assert_eq!(s.active().unwrap().active_layer, Some(LayerId(copy)));
+ s.execute("layer.smartFilter.setParams", json!({"params": {"radius": 8}})).unwrap();
+ let d = s.active().unwrap();
+ let n_smart = d.doc.walk().iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Smart(_))).count();
+ assert_eq!(n_smart, 2);
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("layer.smartObjects.rasterize", json!({})).unwrap();
+ let d = s.active().unwrap();
+ assert!(matches!(d.doc.layer(d.active_layer.unwrap()).unwrap().content, LayerContent::Raster(_)));
+ assert!(max_diff(&flat(&s), &blurred) <= 1.0 / 255.0 + 1e-6);
+ assert!(!s.is_enabled("layer.smartObjects.rasterize"));
+}
+
+#[test]
+fn pcraft_round_trip_keeps_live_smart_objects() {
+ for depth in [8, 16] {
+ let mut s = session(depth);
+ paint(&mut s);
+ convert(&mut s);
+ s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap();
+ s.execute("filter.noise.addNoise", json!({"amount": 20, "seed": 3})).unwrap();
+ s.execute("layer.smartFilter.blendingOptions", json!({"opacity": 0.5, "blend": "screen"})).unwrap();
+ let doc = s.active().unwrap().doc.clone();
+ let bytes = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap();
+ let back = photocraft_format::load_from_bytes(&bytes).unwrap();
+ let id = s.active().unwrap().active_layer.unwrap();
+ let (a, b) = (smart(&doc, id).unwrap(), smart(&back, id).unwrap());
+ assert_eq!(a, b, "depth {depth}");
+ assert_eq!(b.smart_filters.len(), 2);
+ assert!(b.filter_mask.is_some());
+ // Still live after loading: re-editing works and matches a fresh render.
+ let mut s2 = Session::new();
+ s2.add_document(back, None);
+ s2.select_layer(id).unwrap();
+ s2.execute("layer.smartFilter.setVisible", json!({"index": 1, "visible": false})).unwrap();
+ s.execute("layer.smartFilter.setVisible", json!({"index": 1, "visible": false})).unwrap();
+ assert_eq!(flat(&s2), flat(&s));
+ }
+}
+
+#[test]
+fn psd_placed_layer_renders_from_lnk2_data() {
+ // A PNG embedded the way Photoshop stores placed files: a global lnk2 block keyed by uuid.
+ let mut inner = Document::with_background("in", Size::new(10, 8), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, photocraft_color::Color::rgba(0.0, 1.0, 0.0, 1.0));
+ inner.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 5, 8), &[1.0, 0.0, 0.0, 1.0]);
+ let png = photocraft_io::export(&inner, "png", &Default::default()).unwrap().bytes;
+ let lnk2 = photocraft_io::linked::encode_linked_file(&photocraft_io::linked::LinkedFile { uuid: "uuid-1".into(), file_name: "in.png".into(), bytes: png });
+ let mut s = session(8);
+ s.edit("place", |doc, active| {
+ doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(lnk2)));
+ // Photoshop's rendering (deliberately different, to see the re-render happen).
+ let mut cache = Surface::new(doc.pixel_format());
+ cache.fill_rect(Rect::new(20, 10, 40, 26), &[0.0, 0.0, 1.0, 1.0]);
+ let mut sm = SmartObject::new(SmartSource::Linked { path: "uuid-1".into() }, Affine { m: [2.0, 0.0, 0.0, 2.0, 20.0, 10.0] }, Some(cache));
+ sm.psd_raw = Some(Arc::new(vec![1, 2, 3]));
+ let mut l = Layer::new("placed", LayerContent::Smart(sm));
+ l.psd_blocks.push((*b"SoLd", Arc::new(vec![1, 2, 3])));
+ *active = Some(doc.insert_above(*active, l));
+ Ok(())
+ })
+ .unwrap();
+ // Nothing re-renders until something changes (PSD round trips stay byte-stable).
+ assert_eq!(active_smart(&s).cache.unwrap().rgba(25, 12), [0.0, 0.0, 1.0, 1.0]);
+ s.execute("filter.other.offset", json!({"horizontal": 0})).unwrap();
+ let c = active_smart(&s).cache.unwrap();
+ assert_eq!(c.rgba(23, 15), [1.0, 0.0, 0.0, 1.0], "left half red, from the source");
+ assert_eq!(c.rgba(37, 15), [0.0, 1.0, 0.0, 1.0]);
+ assert!(active_smart(&s).psd_raw.is_some(), "filters alone keep the placed-layer block");
+ // Embedding resolves the lnk2 data.
+ assert!(s.is_enabled("layer.smartObjects.convertToEmbedded"));
+ s.execute("layer.smartObjects.convertToEmbedded", json!({})).unwrap();
+ assert!(matches!(active_smart(&s).source, SmartSource::Embedded { ref file_name, .. } if file_name == "in.png"));
+}
+
+#[test]
+fn export_replace_and_linked_contents() {
+ let dir = std::env::temp_dir().join(format!("pcraft-smart-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut s = session(8);
+ paint(&mut s);
+ convert(&mut s);
+ let out = dir.join("contents.pcraft");
+ s.execute("layer.smartObjects.exportContents", json!({"path": out.to_str().unwrap()})).unwrap();
+ assert!(photocraft_format::is_pcraft(&std::fs::read(&out).unwrap()));
+ // Replace with a flat PNG.
+ let png_doc = Document::with_background("p", Size::new(4, 4), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, photocraft_color::Color::rgba(1.0, 1.0, 0.0, 1.0));
+ let png = dir.join("yellow.png");
+ std::fs::write(&png, photocraft_io::export(&png_doc, "png", &Default::default()).unwrap().bytes).unwrap();
+ s.execute("layer.smartObjects.replaceContents", json!({"path": png.to_str().unwrap()})).unwrap();
+ let sm = active_smart(&s);
+ assert_eq!(sm.cache.as_ref().unwrap().content_bounds(), Rect::new(-6, 5, -2, 9), "transform kept");
+ assert!(s.execute("layer.smartObjects.replaceContents", json!({})).is_err());
+ // Linked: write out, edit the file, update.
+ let linked = dir.join("linked.png");
+ s.execute("layer.smartObjects.convertToLinked", json!({"path": linked.to_str().unwrap()})).unwrap();
+ assert!(matches!(active_smart(&s).source, SmartSource::Linked { .. }));
+ let mut red = png_doc.clone();
+ let rb = red.bounds();
+ red.layers[0].surface_mut().unwrap().fill_rect(rb, &[1.0, 0.0, 0.0, 1.0]);
+ std::fs::write(&linked, photocraft_io::export(&red, "png", &Default::default()).unwrap().bytes).unwrap();
+ s.execute("layer.smartObjects.updateAllModifiedContent", json!({})).unwrap();
+ assert_eq!(active_smart(&s).cache.unwrap().rgba(-5, 6), [1.0, 0.0, 0.0, 1.0]);
+ s.execute("layer.smartObjects.convertToEmbedded", json!({})).unwrap();
+ std::fs::remove_dir_all(&dir).ok();
+ // Missing linked file: re-rendering fails cleanly and changes nothing.
+ s.execute("layer.smartObjects.relinkToFile", json!({"path": dir.join("gone.png").to_str().unwrap()})).unwrap_err();
+ assert!(matches!(active_smart(&s).source, SmartSource::Embedded { .. }));
+}
+
+#[test]
+fn commands_are_registered_with_catalog_ids() {
+ for id in [
+ "layer.smartObjects.convertToSmartObject",
+ "filter.convertForSmartFilters",
+ "layer.smartObjects.newSmartObjectViaCopy",
+ "layer.smartObjects.rasterize",
+ "layer.smartObjects.editContents",
+ "layer.smartObjects.replaceContents",
+ "layer.smartObjects.exportContents",
+ "layer.smartObjects.updateModifiedContent",
+ "layer.smartObjects.updateAllModifiedContent",
+ "layer.smartObjects.convertToEmbedded",
+ "layer.smartObjects.convertToLinked",
+ "layer.smartObjects.relinkToFile",
+ "layer.smartFilter.disableSmartFilters",
+ "layer.smartFilter.clearSmartFilters",
+ "layer.smartFilter.blendingOptions",
+ "layer.smartFilter.deleteFilterMask",
+ "layer.smartFilter.disableFilterMask",
+ ] {
+ let spec = crate::commands::find(id).unwrap_or_else(|| panic!("{id}"));
+ assert!(!spec.menu.is_empty(), "{id}");
+ }
+ let s = Session::new();
+ assert!(!s.is_enabled("layer.smartObjects.convertToSmartObject"));
+ assert!(!s.is_enabled("layer.smartObjects.editContents"));
+}
+
+#[test]
+fn smart_filter_blur_repeats_the_canvas_edge_like_a_layer_filter() {
+ for depth in [8, 32] {
+ let fill_canvas = |s: &mut Session| {
+ s.edit("setup", |doc, active| {
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ let fmt = surf.format();
+ let r = Rect::new(0, 0, W, H);
+ let mut data = Vec::new();
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ let v = if (x / 8 + y / 8) % 2 == 0 { 0.2 } else { 0.9 };
+ data.extend(photocraft_raster::from_rgba(&fmt, [v, 0.5, 1.0 - v, 1.0]));
+ }
+ }
+ surf.write_region(r, &data);
+ Ok(())
+ })
+ .unwrap();
+ };
+ let mut layer = session(depth);
+ fill_canvas(&mut layer);
+ layer.execute("filter.blur.gaussianBlur", json!({"radius": 4})).unwrap();
+ let mut smart = session(depth);
+ fill_canvas(&mut smart);
+ convert(&mut smart);
+ smart.execute("filter.blur.gaussianBlur", json!({"radius": 4})).unwrap();
+ let (a, b) = (flat(&layer), flat(&smart));
+ // The corner stays opaque (no transparency fades in from outside the canvas).
+ assert!((b[0][3] - 1.0).abs() < 1e-3, "corner alpha {}", b[0][3]);
+ assert!(max_diff(&a, &b) < 2.0 / 255.0, "smart re-render matches the layer filter ({depth}-bit)");
+ }
+}
diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs
new file mode 100644
index 000000000..7d2c2e368
--- /dev/null
+++ b/crates/engine/src/snap.rs
@@ -0,0 +1,340 @@
+//! Snapping (View › Snap / Snap To) and smart guides, as pure geometry.
+//!
+//! A [`SnapTargets`] set is built once per gesture from the document (guides, grid, document
+//! bounds and centre, layer edges and centres, selection edges), then every pointer move asks it
+//! to snap a point ([`SnapTargets::snap_point`]: marquee corners, crop handles, guide positions,
+//! pen anchors, transform handles) or a moving rectangle ([`SnapTargets::snap_rect`]: the Move
+//! tool, Free Transform drags). Distances are in document pixels; callers convert their screen
+//! threshold with the zoom (`8 px / zoom`). Results carry [`SnapLine`]s so the UI can draw what
+//! was snapped to (smart guides are the layer-to-layer subset of these, drawn in magenta).
+
+use photocraft_doc::{Document, LayerContent, LayerId};
+use serde::Serialize;
+
+/// What a snap target came from.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum SnapKind {
+ Guide,
+ Grid,
+ DocumentEdge,
+ DocumentCenter,
+ LayerEdge,
+ LayerCenter,
+ Selection,
+}
+
+impl SnapKind {
+ /// Layer-to-layer and document-centre alignments are what Photoshop shows as smart guides.
+ pub fn is_smart(self) -> bool {
+ matches!(self, SnapKind::LayerEdge | SnapKind::LayerCenter | SnapKind::DocumentCenter)
+ }
+}
+
+/// A line to snap to: `pos` on one axis (x for vertical lines), `span` its extent on the other
+/// axis (for drawing alignment lines between objects).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Target {
+ pub pos: f64,
+ pub kind: SnapKind,
+ pub span: (f64, f64),
+}
+
+/// A snapped alignment, for drawing: a vertical line at x = `pos` from y = `from` to `to`
+/// (or horizontal at y = `pos`).
+#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
+pub struct SnapLine {
+ pub vertical: bool,
+ pub pos: f64,
+ pub from: f64,
+ pub to: f64,
+ pub kind: SnapKind,
+}
+
+/// Which target families are active (View › Snap To).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct SnapOptions {
+ pub guides: bool,
+ pub grid: bool,
+ pub layers: bool,
+ pub document: bool,
+ pub selection: bool,
+ /// Grid spacing (document px) used when `grid` is on: the subdivision step.
+ pub grid_step: f64,
+}
+
+impl Default for SnapOptions {
+ fn default() -> Self {
+ Self { guides: true, grid: false, layers: true, document: true, selection: true, grid_step: 18.0 }
+ }
+}
+
+/// Snap targets on both axes.
+#[derive(Clone, Debug, Default)]
+pub struct SnapTargets {
+ /// Vertical lines (x positions).
+ pub x: Vec<Target>,
+ /// Horizontal lines (y positions).
+ pub y: Vec<Target>,
+ /// Regular grid step (document px), when snapping to the grid.
+ pub grid: Option<f64>,
+ /// Extent used for grid lines and guides ([x0, y0, x1, y1]).
+ pub extent: [f64; 4],
+}
+
+/// Bounds of a layer for snapping: what Free Transform would show (`None` for empty layers,
+/// groups and maskless adjustment layers).
+pub fn layer_rect(doc: &Document, id: LayerId) -> Option<[f64; 4]> {
+ let l = doc.layer(id)?;
+ if l.is_group() || (matches!(l.content, LayerContent::Adjustment(_)) && l.mask.is_none()) {
+ return None;
+ }
+ let b = crate::transform_cmds::transform_bounds(doc, l);
+ (!b.is_empty()).then_some([b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64])
+}
+
+impl SnapTargets {
+ /// Targets of `doc` for the enabled families; layers in `exclude` (the ones being moved)
+ /// are skipped.
+ pub fn from_document(doc: &Document, opts: &SnapOptions, exclude: &[LayerId]) -> Self {
+ let (w, h) = (doc.size.width as f64, doc.size.height as f64);
+ let mut t = SnapTargets { extent: [0.0, 0.0, w, h], ..Default::default() };
+ if opts.document {
+ t.add_rect([0.0, 0.0, w, h], SnapKind::DocumentEdge, SnapKind::DocumentCenter);
+ }
+ if opts.guides {
+ for g in &doc.guides.vertical {
+ t.x.push(Target { pos: *g as f64, kind: SnapKind::Guide, span: (0.0, h) });
+ }
+ for g in &doc.guides.horizontal {
+ t.y.push(Target { pos: *g as f64, kind: SnapKind::Guide, span: (0.0, w) });
+ }
+ }
+ if opts.grid && opts.grid_step > 0.0 {
+ t.grid = Some(opts.grid_step);
+ }
+ if opts.layers {
+ for (_, _, l) in doc.walk() {
+ if !l.visible || exclude.contains(&l.id) {
+ continue;
+ }
+ if let Some(r) = layer_rect(doc, l.id) {
+ t.add_rect(r, SnapKind::LayerEdge, SnapKind::LayerCenter);
+ }
+ }
+ }
+ if opts.selection
+ && let Some(sel) = &doc.selection
+ {
+ let b = sel.content_bounds();
+ if !b.is_empty() {
+ let r = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64];
+ t.x.push(Target { pos: r[0], kind: SnapKind::Selection, span: (r[1], r[3]) });
+ t.x.push(Target { pos: r[2], kind: SnapKind::Selection, span: (r[1], r[3]) });
+ t.y.push(Target { pos: r[1], kind: SnapKind::Selection, span: (r[0], r[2]) });
+ t.y.push(Target { pos: r[3], kind: SnapKind::Selection, span: (r[0], r[2]) });
+ }
+ }
+ t
+ }
+
+ /// Add a rectangle's edges and centre lines.
+ pub fn add_rect(&mut self, r: [f64; 4], edge: SnapKind, center: SnapKind) {
+ let (xs, ys) = ((r[1], r[3]), (r[0], r[2]));
+ self.x.push(Target { pos: r[0], kind: edge, span: xs });
+ self.x.push(Target { pos: r[2], kind: edge, span: xs });
+ self.x.push(Target { pos: (r[0] + r[2]) / 2.0, kind: center, span: xs });
+ self.y.push(Target { pos: r[1], kind: edge, span: ys });
+ self.y.push(Target { pos: r[3], kind: edge, span: ys });
+ self.y.push(Target { pos: (r[1] + r[3]) / 2.0, kind: center, span: ys });
+ }
+
+ /// Only the targets for which `keep` holds (e.g. smart guides: layer alignments).
+ pub fn filtered(&self, keep: impl Fn(SnapKind) -> bool) -> SnapTargets {
+ SnapTargets { x: self.x.iter().copied().filter(|t| keep(t.kind)).collect(), y: self.y.iter().copied().filter(|t| keep(t.kind)).collect(), grid: self.grid.filter(|_| keep(SnapKind::Grid)), extent: self.extent }
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.x.is_empty() && self.y.is_empty() && self.grid.is_none()
+ }
+
+ /// The closest target to `v` within `tol` on one axis (`vertical` = x positions). Guides win
+ /// ties over other kinds, as in Photoshop.
+ pub fn nearest(&self, vertical: bool, v: f64, tol: f64) -> Option<Target> {
+ let list = if vertical { &self.x } else { &self.y };
+ let mut best: Option<(f64, Target)> = None;
+ let mut consider = |t: Target| {
+ let d = (t.pos - v).abs();
+ if d > tol {
+ return;
+ }
+ let better = match best {
+ None => true,
+ Some((bd, bt)) => d < bd - 1e-9 || ((d - bd).abs() <= 1e-9 && t.kind == SnapKind::Guide && bt.kind != SnapKind::Guide),
+ };
+ if better {
+ best = Some((d, t));
+ }
+ };
+ list.iter().copied().for_each(&mut consider);
+ if let Some(step) = self.grid {
+ let g = (v / step).round() * step;
+ let span = if vertical { (self.extent[1], self.extent[3]) } else { (self.extent[0], self.extent[2]) };
+ consider(Target { pos: g, kind: SnapKind::Grid, span });
+ }
+ best.map(|(_, t)| t)
+ }
+
+ /// Snap a point: each axis independently to its nearest target within `tol`.
+ pub fn snap_point(&self, p: [f64; 2], tol: f64) -> ([f64; 2], Vec<SnapLine>) {
+ let mut out = p;
+ let mut lines = Vec::new();
+ if let Some(t) = self.nearest(true, p[0], tol) {
+ out[0] = t.pos;
+ lines.push(line(true, t, p[1], p[1]));
+ }
+ if let Some(t) = self.nearest(false, p[1], tol) {
+ out[1] = t.pos;
+ lines.push(line(false, t, out[0], out[0]));
+ }
+ (out, lines)
+ }
+
+ /// Snap a moving rectangle `[x0, y0, x1, y1]`: on each axis the edge or centre closest to a
+ /// target decides the correction. Returns the offset to add and the alignments made (every
+ /// anchor that lines up after the correction, so equal-size neighbours show both edges).
+ pub fn snap_rect(&self, r: [f64; 4], tol: f64) -> ([f64; 2], Vec<SnapLine>) {
+ let mut delta = [0.0, 0.0];
+ let mut lines = Vec::new();
+ for (axis, vertical) in [(0usize, true), (1usize, false)] {
+ let (a, b) = (r[axis], r[axis + 2]);
+ let anchors = [a, (a + b) / 2.0, b];
+ let mut best: Option<(f64, f64)> = None; // (|d|, d)
+ for v in anchors {
+ if let Some(t) = self.nearest(vertical, v, tol) {
+ let d = t.pos - v;
+ if best.is_none_or(|(bd, _)| d.abs() < bd) {
+ best = Some((d.abs(), d));
+ }
+ }
+ }
+ let Some((_, d)) = best else { continue };
+ delta[axis] = d;
+ let other = if vertical { (r[1], r[3]) } else { (r[0], r[2]) };
+ for v in anchors {
+ let moved = v + d;
+ let list = if vertical { &self.x } else { &self.y };
+ let hit = list.iter().copied().filter(|t| (t.pos - moved).abs() < 1e-6).min_by_key(|t| u8::from(t.kind != SnapKind::Guide));
+ let hit = hit.or_else(|| self.grid.filter(|s| ((moved / s).round() * s - moved).abs() < 1e-6).map(|_| Target { pos: moved, kind: SnapKind::Grid, span: other }));
+ if let Some(t) = hit {
+ lines.push(line(vertical, t, other.0, other.1));
+ }
+ }
+ }
+ (delta, lines)
+ }
+}
+
+/// Alignment line through target `t` covering both its span and the snapped object (`a..b`).
+fn line(vertical: bool, t: Target, a: f64, b: f64) -> SnapLine {
+ SnapLine { vertical, pos: t.pos, from: t.span.0.min(a).min(b), to: t.span.1.max(a).max(b), kind: t.kind }
+}
+
+/// Union of rectangles (`None` when empty).
+pub fn union(rects: impl IntoIterator<Item = [f64; 4]>) -> Option<[f64; 4]> {
+ rects.into_iter().reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::{Color, ColorMode, Layer, SampleType, Size};
+
+ fn targets() -> SnapTargets {
+ let mut t = SnapTargets { extent: [0.0, 0.0, 400.0, 300.0], ..Default::default() };
+ t.add_rect([0.0, 0.0, 400.0, 300.0], SnapKind::DocumentEdge, SnapKind::DocumentCenter);
+ t.x.push(Target { pos: 120.0, kind: SnapKind::Guide, span: (0.0, 300.0) });
+ t
+ }
+
+ #[test]
+ fn point_snaps_within_threshold_only() {
+ let t = targets();
+ let (p, lines) = t.snap_point([123.0, 151.0], 4.0);
+ assert_eq!(p, [120.0, 150.0]);
+ assert_eq!(lines.len(), 2);
+ assert_eq!(lines[0].kind, SnapKind::Guide);
+ assert_eq!(lines[1].kind, SnapKind::DocumentCenter);
+ let (p, lines) = t.snap_point([130.0, 160.0], 4.0);
+ assert_eq!(p, [130.0, 160.0]);
+ assert!(lines.is_empty());
+ }
+
+ #[test]
+ fn threshold_scales_with_zoom() {
+ // 8 screen px: at 400% that is 2 document px, at 25% it is 32.
+ let t = targets();
+ assert!(t.nearest(true, 125.0, 8.0 / 4.0).is_none());
+ assert_eq!(t.nearest(true, 145.0, 8.0 / 0.25).map(|t| t.pos), Some(120.0));
+ }
+
+ #[test]
+ fn guides_win_ties() {
+ let mut t = targets();
+ t.x.push(Target { pos: 120.0, kind: SnapKind::LayerEdge, span: (0.0, 10.0) });
+ assert_eq!(t.nearest(true, 121.0, 5.0).unwrap().kind, SnapKind::Guide);
+ }
+
+ #[test]
+ fn grid_snaps_to_nearest_line() {
+ let t = SnapTargets { grid: Some(25.0), extent: [0.0, 0.0, 100.0, 100.0], ..Default::default() };
+ assert_eq!(t.snap_point([48.0, 61.0], 3.0).0, [50.0, 61.0]);
+ assert_eq!(t.nearest(false, 74.0, 3.0).unwrap().kind, SnapKind::Grid);
+ }
+
+ #[test]
+ fn rect_snaps_by_closest_anchor() {
+ let t = targets();
+ // A 50-wide box whose right edge is 2 px left of the guide: moves right by 2.
+ let (d, lines) = t.snap_rect([68.0, 10.0, 118.0, 40.0], 4.0);
+ assert_eq!(d[0], 2.0);
+ assert!(lines.iter().any(|l| l.vertical && l.pos == 120.0));
+ // Centre near the document centre (200, 150): centres both ways.
+ let (d, lines) = t.snap_rect([148.0, 102.0, 248.0, 202.0], 4.0);
+ assert_eq!(d, [2.0, -2.0]);
+ assert!(lines.iter().any(|l| l.kind == SnapKind::DocumentCenter && l.vertical));
+ assert!(lines.iter().any(|l| l.kind == SnapKind::DocumentCenter && !l.vertical));
+ }
+
+ #[test]
+ fn smart_guide_lines_span_both_objects() {
+ let mut t = SnapTargets::default();
+ t.add_rect([300.0, 200.0, 350.0, 260.0], SnapKind::LayerEdge, SnapKind::LayerCenter);
+ // Moving box above-left whose left edge is near x = 300.
+ let (d, lines) = t.snap_rect([302.0, 10.0, 330.0, 40.0], 5.0);
+ assert_eq!(d[0], -2.0);
+ let l = lines.iter().find(|l| l.vertical && l.pos == 300.0).unwrap();
+ assert_eq!((l.from, l.to), (10.0, 260.0));
+ assert!(l.kind.is_smart());
+ }
+
+ #[test]
+ fn targets_from_document() {
+ let mut doc = Document::with_background("s", Size::new(200, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+ doc.guides.vertical.push(40.0);
+ let mut l = Layer::raster("box", doc.pixel_format());
+ l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 20, 30, 60), &[1.0, 0.0, 0.0, 1.0]);
+ let id = doc.insert_above(None, l);
+ let opts = SnapOptions::default();
+ let t = SnapTargets::from_document(&doc, &opts, &[]);
+ assert!(t.x.iter().any(|t| t.kind == SnapKind::Guide && t.pos == 40.0));
+ assert!(t.x.iter().any(|t| t.kind == SnapKind::LayerEdge && t.pos == 30.0));
+ assert!(t.y.iter().any(|t| t.kind == SnapKind::LayerCenter && t.pos == 40.0));
+ assert!(t.x.iter().any(|t| t.kind == SnapKind::DocumentCenter && t.pos == 100.0));
+ // The moving layer is excluded; guides off removes guides.
+ let t = SnapTargets::from_document(&doc, &SnapOptions { guides: false, ..opts }, &[id]);
+ assert!(!t.x.iter().any(|t| t.kind == SnapKind::Guide || (t.kind == SnapKind::LayerEdge && t.pos == 30.0)));
+ assert_eq!(layer_rect(&doc, id), Some([10.0, 20.0, 30.0, 60.0]));
+ assert_eq!(union([[0.0, 0.0, 1.0, 1.0], [2.0, -1.0, 3.0, 0.5]]), Some([0.0, -1.0, 3.0, 1.0]));
+ }
+}
diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs
index 7413ae7ef..e55ed5be0 100644
--- a/crates/engine/src/transform_cmds.rs
+++ b/crates/engine/src/transform_cmds.rs
@@ -33,7 +33,7 @@ pub fn transform_bounds(doc: &Document, layer: &Layer) -> Rect {
/// 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 {
+pub(crate) 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();
@@ -61,7 +61,7 @@ fn warp_gray(s: &Surface, h: &Homography, interp: Interp) -> Surface {
out
}
-fn transform_layer(doc_sel: Option<&Surface>, l: &mut Layer, h: &Homography, affine: Option<Affine>, interp: Interp) -> Result<()> {
+pub(crate) 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;
@@ -89,6 +89,22 @@ fn transform_layer(doc_sel: Option<&Surface>, l: &mut Layer, h: &Homography, aff
};
crate::vector_cmds::transform_shape(sh, &a);
}
+ LayerContent::Smart(sm) => {
+ // Smart objects keep the transform and re-render from their source afterwards
+ // (`refresh_text`), so repeated transforms don't degrade the pixels.
+ let Some(a) = affine else {
+ return Err(EngineError::Other("Distort and Perspective on smart objects aren't supported yet".into()));
+ };
+ sm.transform = crate::smart_cmds::snap_affine(a.mul(&sm.transform));
+ // Fallback appearance for sources that can't be re-rendered.
+ if let Some(c) = &mut sm.cache {
+ let src = c.content_bounds();
+ *c = warp_surface(c, src, h, interp);
+ }
+ if let Some(m) = &mut sm.filter_mask {
+ m.surface = warp_gray(&m.surface, h, interp);
+ }
+ }
_ => {
if let Some(surf) = l.surface_mut() {
let src = surf.content_bounds();
@@ -147,17 +163,21 @@ pub fn split_selected(surf: &Surface, sel: &Surface) -> (Surface, Surface) {
(lifted, rest)
}
-fn refresh_text(doc: &Document, l: &mut Layer) {
+pub(crate) 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::Smart(_) => {
+ // Unavailable sources keep the warped cache.
+ let _ = crate::smart_cmds::refresh_layer(doc, l);
+ }
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) {
+pub(crate) fn composite_over(dst: &mut Surface, top: &Surface) {
let b = top.content_bounds();
if b.is_empty() {
return;
diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs
index e38d1f0b2..bb0db0a98 100644
--- a/crates/engine/src/type_cmds.rs
+++ b/crates/engine/src/type_cmds.rs
@@ -549,11 +549,12 @@ pub fn specs() -> Vec<CommandSpec> {
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() };
+ // Type › Save Default Type Styles sets the starting styles; the colour is always
+ // the foreground colour, as in Photoshop.
+ let (mut style, mut para) = s.type_defaults.clone().unwrap_or_else(|| (CharStyle { font_family: photocraft_text::fonts::DEFAULT_FAMILY.into(), ..Default::default() }, ParagraphStyle::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 => {
diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/type_extra_cmds.rs
new file mode 100644
index 000000000..941c8f166
--- /dev/null
+++ b/crates/engine/src/type_extra_cmds.rs
@@ -0,0 +1,528 @@
+//! The Type menu: anti-aliasing, orientation, point ⇄ paragraph conversion, Create Work Path,
+//! Convert to Shape, Rasterize, Warp Text, the OpenType toggles, Paste Lorem Ipsum, Update All
+//! Text Layers, missing-font replacement and the default type styles.
+//!
+//! Everything edits the typed [`TextLayer`] model and re-renders through `type_cmds::refresh`,
+//! so the PSD `TySh` data (and with it warp, anti-aliasing and the OpenType flags) is regenerated
+//! and the layer saves as editable text.
+
+use photocraft_doc::text::{AntiAlias, FontFeature, Orientation, TextAlign, TextShape, TextWarp};
+use photocraft_doc::vector::{Knot, Path, PathOp, Subpath};
+use photocraft_doc::{Affine, Document, Fill, Layer, LayerContent, LayerId, ShapeLayer, TextLayer};
+use photocraft_geom::Point;
+use photocraft_text::render::PathEl;
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, layer_param};
+use crate::type_cmds::{refresh, replace_text, style_paragraphs, style_range};
+use crate::{EngineError, Result, Session};
+
+/// Photoshop's Paste Lorem Ipsum filler.
+pub const LOREM_IPSUM: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
+
+// ---------- predicates ----------
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn active_text(s: &Session) -> std::result::Result<&TextLayer, String> {
+ let d = s.active().ok_or("no document open")?;
+ match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) {
+ Some(LayerContent::Text(t)) => Ok(t),
+ _ => Err("the active layer is not a type layer".into()),
+ }
+}
+
+fn has_text(s: &Session) -> std::result::Result<(), String> {
+ active_text(s).map(|_| ())
+}
+
+fn has_point_text(s: &Session) -> std::result::Result<(), String> {
+ match active_text(s)?.shape {
+ TextShape::Point => Ok(()),
+ TextShape::Box { .. } => Err("the type layer is already paragraph text".into()),
+ }
+}
+
+fn has_box_text(s: &Session) -> std::result::Result<(), String> {
+ match active_text(s)?.shape {
+ TextShape::Box { .. } => Ok(()),
+ TextShape::Point => Err("the type layer is already point text".into()),
+ }
+}
+
+fn any_text(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if d.doc.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Text(_))) { Ok(()) } else { Err("the document has no type layers".into()) }
+}
+
+fn has_defaults(s: &Session) -> std::result::Result<(), String> {
+ has_text(s)?;
+ s.type_defaults.as_ref().map(|_| ()).ok_or_else(|| "no default type styles have been saved".into())
+}
+
+// ---------- helpers ----------
+
+/// Edits a type layer as one history step and re-renders it.
+fn with_text<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut TextLayer, &Document) -> Result<R>) -> Result<R> {
+ let id = layer_param(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 layout(doc: &Document, t: &TextLayer) -> photocraft_text::TextLayout {
+ photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).layout(t, doc.resolution_dpi)
+}
+
+/// `m ∘ translate(tx, ty)`.
+fn then_translate(m: &Affine, tx: f64, ty: f64) -> Affine {
+ let [a, b, c, d, e, f] = m.m;
+ Affine { m: [a, b, c, d, a * tx + c * ty + e, b * tx + d * ty + f] }
+}
+
+fn first_align(t: &TextLayer) -> TextAlign {
+ t.paragraph_runs().first().map(|p| p.style.align).unwrap_or_default()
+}
+
+fn char_index(text: &str, byte: usize) -> usize {
+ text[..byte.min(text.len())].chars().count()
+}
+
+fn byte_index(text: &str, ci: usize) -> usize {
+ text.char_indices().nth(ci).map_or(text.len(), |(b, _)| b)
+}
+
+// ---------- anti-aliasing / orientation ----------
+
+pub fn aa_name(a: AntiAlias) -> &'static str {
+ match a {
+ AntiAlias::None => "none",
+ AntiAlias::Sharp => "sharp",
+ AntiAlias::Crisp => "crisp",
+ AntiAlias::Strong => "strong",
+ AntiAlias::Smooth => "smooth",
+ AntiAlias::Windows => "windows",
+ AntiAlias::WindowsLcd => "windowsLcd",
+ }
+}
+
+fn set_aa(s: &mut Session, p: &Value, aa: AntiAlias) -> Result<Value> {
+ with_text(s, p, "Anti-Alias", |t, _| {
+ t.antialias = aa;
+ Ok(())
+ })?;
+ Ok(json!({"antialias": aa_name(aa)}))
+}
+
+fn set_orientation(s: &mut Session, p: &Value, o: Orientation) -> Result<Value> {
+ with_text(s, p, "Change Text Orientation", |t, _| {
+ t.orientation = o;
+ Ok(())
+ })?;
+ // Vertical layout is stored and saved (PSD `Ornt`), but rendered horizontally for now.
+ Ok(json!({"orientation": if o == Orientation::Vertical { "vertical" } else { "horizontal" }, "rendered": "horizontal"}))
+}
+
+// ---------- point ⇄ paragraph ----------
+
+fn to_paragraph(s: &mut Session, p: &Value) -> Result<Value> {
+ let r = with_text(s, p, "Convert to Paragraph Text", |t, doc| {
+ let l = layout(doc, t);
+ let [x0, y0, x1, y1] = l.bounds().unwrap_or([0.0, -t.size_pt, t.size_pt, 0.0]);
+ let size_px = t.char_runs().iter().map(|r| r.style.size_pt).fold(t.size_pt, f32::max) * doc.resolution_dpi / 72.0;
+ let ps = t.paragraph_runs().first().map(|p| p.style.clone()).unwrap_or_default();
+ let indents = (ps.start_indent_pt + ps.end_indent_pt).max(0.0) * doc.resolution_dpi / 72.0;
+ // A little slack so no line re-wraps; the box keeps the text where it was.
+ let width = (x1 - x0).max(1.0) + indents + (size_px * 0.5).max(4.0);
+ let height = (y1 - y0).max(1.0) + size_px * 0.5;
+ let x = match ps.align {
+ TextAlign::Center | TextAlign::JustifyCenter => -width / 2.0,
+ TextAlign::Right | TextAlign::JustifyRight => -width,
+ _ => 0.0,
+ };
+ let mut probe = t.clone();
+ probe.shape = TextShape::Box { x, y: y0, width, height };
+ // Box text puts the first baseline at the box top plus the ascender height: measure it and
+ // shift the box so that baseline stays at the point-text anchor (y = 0).
+ let b0 = layout(doc, &probe).lines.first().map_or(0.0, |ln| ln.baseline);
+ let y = y0 - b0;
+ t.shape = TextShape::Box { x: 0.0, y: 0.0, width, height };
+ t.transform = then_translate(&t.transform, f64::from(x), f64::from(y));
+ Ok(json!([x, y, width, height]))
+ })?;
+ Ok(json!({"box": r}))
+}
+
+fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
+ let r = with_text(s, p, "Convert to Point Text", |t, doc| {
+ let TextShape::Box { x, width, .. } = t.shape else { return Err(EngineError::Other("already point text".into())) };
+ let l = layout(doc, t);
+ let baseline = l.lines.first().map_or(0.0, |ln| ln.baseline);
+ // Photoshop inserts a hard return at every soft line break.
+ let mut breaks: Vec<usize> = l.lines.windows(2).filter(|w| w[0].paragraph == w[1].paragraph).map(|w| w[1].range.start).collect();
+ // Lines a box overflows are dropped from the layout; keep their text after a break.
+ breaks.sort_unstable();
+ breaks.dedup();
+ for at in breaks.iter().rev() {
+ replace_text(t, *at, *at, "\n");
+ }
+ let ax = match first_align(t) {
+ TextAlign::Center | TextAlign::JustifyCenter => x + width / 2.0,
+ TextAlign::Right | TextAlign::JustifyRight => x + width,
+ _ => x,
+ };
+ t.shape = TextShape::Point;
+ // `baseline` is in text space (it already includes the box top).
+ t.transform = then_translate(&t.transform, f64::from(ax), f64::from(baseline));
+ Ok(breaks.len())
+ })?;
+ Ok(json!({"inserted": r}))
+}
+
+// ---------- outlines → paths ----------
+
+fn signed_area(knots: &[Knot]) -> f64 {
+ let n = knots.len();
+ (0..n).map(|i| {
+ let (a, b) = (knots[i].anchor, knots[(i + 1) % n].anchor);
+ a.x * b.y - b.x * a.y
+ }).sum::<f64>() / 2.0
+}
+
+/// One glyph's outline elements as closed subpaths.
+fn contours(els: &[PathEl]) -> Vec<Vec<Knot>> {
+ let mut out: Vec<Vec<Knot>> = Vec::new();
+ let mut cur: Vec<Knot> = Vec::new();
+ let p = |v: [f64; 2]| Point::new(v[0], v[1]);
+ let finish = |cur: &mut Vec<Knot>, out: &mut Vec<Vec<Knot>>| {
+ if cur.len() >= 2 {
+ // The closing point duplicates the first anchor: fold its incoming handle in.
+ let (f, l) = (cur[0], cur[cur.len() - 1]);
+ if (f.anchor.x - l.anchor.x).abs() < 1e-9 && (f.anchor.y - l.anchor.y).abs() < 1e-9 {
+ cur[0].in_ctrl = l.in_ctrl;
+ cur.pop();
+ }
+ }
+ if cur.len() >= 2 {
+ out.push(std::mem::take(cur));
+ } else {
+ cur.clear();
+ }
+ };
+ for el in els {
+ match *el {
+ PathEl::MoveTo(a) => {
+ finish(&mut cur, &mut out);
+ cur.push(Knot::corner(a[0], a[1]));
+ }
+ PathEl::LineTo(a) => cur.push(Knot::corner(a[0], a[1])),
+ PathEl::QuadTo(c, a) => {
+ // Exact quadratic → cubic elevation.
+ let Some(last) = cur.last_mut() else { continue };
+ let s = last.anchor;
+ last.out_ctrl = Point::new(s.x + 2.0 / 3.0 * (c[0] - s.x), s.y + 2.0 / 3.0 * (c[1] - s.y));
+ let c2 = Point::new(a[0] + 2.0 / 3.0 * (c[0] - a[0]), a[1] + 2.0 / 3.0 * (c[1] - a[1]));
+ cur.push(Knot { anchor: p(a), in_ctrl: c2, out_ctrl: p(a), smooth: false });
+ }
+ PathEl::CurveTo(c1, c2, a) => {
+ let Some(last) = cur.last_mut() else { continue };
+ last.out_ctrl = p(c1);
+ cur.push(Knot { anchor: p(a), in_ctrl: p(c2), out_ctrl: p(a), smooth: false });
+ }
+ PathEl::Close => finish(&mut cur, &mut out),
+ }
+ }
+ finish(&mut cur, &mut out);
+ out
+}
+
+/// The type layer's glyph outlines as a document-space path. Within each glyph, contours wound
+/// like its largest contour combine and the others (counters such as the hole in "o") subtract,
+/// which reproduces the nonzero fill under Photoshop's per-subpath path operations.
+pub fn text_path(doc: &Document, t: &TextLayer) -> Path {
+ let l = layout(doc, t);
+ let warp = photocraft_text::render::layout_warp(&l, t.warp.as_ref());
+ let mut subpaths = Vec::new();
+ for glyph in photocraft_text::render::outlines(&l, &t.transform, warp.as_ref()) {
+ let cs = contours(&glyph);
+ let Some(outer) = cs.iter().map(|k| signed_area(k)).max_by(|a, b| a.abs().total_cmp(&b.abs())) else { continue };
+ let (fills, holes): (Vec<_>, Vec<_>) = cs.into_iter().partition(|k| signed_area(k).signum() == outer.signum());
+ subpaths.extend(fills.into_iter().map(|knots| Subpath { closed: true, knots, op: PathOp::Combine }));
+ subpaths.extend(holes.into_iter().map(|knots| Subpath { closed: true, knots, op: PathOp::Subtract }));
+ }
+ Path::new(subpaths)
+}
+
+fn create_work_path(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let Some(LayerContent::Text(t)) = d.doc.layer(id).map(|l| &l.content) else { return Err(EngineError::Other("not a type layer".into())) };
+ let path = text_path(&d.doc, t);
+ let n = path.subpaths.len();
+ s.edit("Create Work Path", |doc, _| {
+ doc.work_path = Some(path);
+ Ok(())
+ })?;
+ Ok(json!({"subpaths": n}))
+}
+
+fn convert_to_shape(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = layer_param(s, p)?;
+ let n = s.edit("Convert to Shape", |doc, _| {
+ let snapshot = doc.clone();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let LayerContent::Text(t) = &l.content else { return Err(EngineError::Other("not a type layer".into())) };
+ let color = t.char_runs().first().map_or(t.color, |r| r.style.color);
+ let mut sh = ShapeLayer { path: text_path(&snapshot, t), fill: Some(Fill::Solid(color)), ..Default::default() };
+ crate::vector_cmds::refresh_shape(&snapshot, &mut sh);
+ let n = sh.path.subpaths.len();
+ l.content = LayerContent::Shape(sh);
+ l.psd_blocks.retain(|(k, _)| k != b"TySh");
+ Ok(n)
+ })?;
+ Ok(json!({"layer": id.0, "subpaths": n}))
+}
+
+// ---------- warp ----------
+
+fn warp_text(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "type.warpText";
+ let style = p.get("style").and_then(Value::as_str).unwrap_or("arc");
+ let psd = photocraft_text::warp::psd_style(style).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("unknown warp style \"{style}\"") })?;
+ let f = |k: &str, d: f64| p.get(k).and_then(Value::as_f64).unwrap_or(d).clamp(-100.0, 100.0) as f32;
+ let warp = (psd != "warpNone").then(|| TextWarp {
+ style: psd.into(),
+ value: f("bend", 50.0),
+ horizontal_distortion: f("horizontalDistortion", 0.0),
+ vertical_distortion: f("verticalDistortion", 0.0),
+ horizontal: p.get("orientation").and_then(Value::as_str) != Some("vertical"),
+ });
+ let out = json!({"warp": warp});
+ with_text(s, p, "Warp Text", |t, _| {
+ t.warp = warp;
+ Ok(())
+ })?;
+ Ok(out)
+}
+
+// ---------- OpenType toggles ----------
+
+/// Is the OpenType toggle `tag` on for a character style? (`liga`/`dlig` have dedicated fields.)
+pub fn feature_on(st: &photocraft_doc::text::CharStyle, tag: &str) -> bool {
+ match tag {
+ "liga" => st.ligatures,
+ "dlig" => st.discretionary_ligatures,
+ _ => st.features.iter().any(|f| f.tag == tag && f.value > 0),
+ }
+}
+
+fn set_feature(st: &mut photocraft_doc::text::CharStyle, tag: &str, on: bool) {
+ match tag {
+ "liga" => st.ligatures = on,
+ "dlig" => st.discretionary_ligatures = on,
+ _ => {
+ st.features.retain(|f| f.tag != tag);
+ if on {
+ st.features.push(FontFeature { tag: tag.into(), value: 1 });
+ }
+ }
+ }
+}
+
+fn toggle_opentype(s: &mut Session, p: &Value, tag: &'static str) -> Result<Value> {
+ let cur = active_text(s).ok().and_then(|t| t.char_runs().first().map(|r| feature_on(&r.style, tag))).unwrap_or(false);
+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(!cur);
+ with_text(s, p, "Change OpenType Feature", |t, _| {
+ let (a, b) = match p.get("range").and_then(Value::as_array) {
+ Some(r) if r.len() == 2 => (byte_index(&t.text, r[0].as_u64().unwrap_or(0) as usize), byte_index(&t.text, r[1].as_u64().unwrap_or(0) as usize)),
+ _ => (0, t.text.len()),
+ };
+ style_range(t, a.min(b), a.max(b), &|st| set_feature(st, tag, on));
+ Ok(())
+ })?;
+ Ok(json!({"feature": tag, "on": on}))
+}
+
+// ---------- lorem ipsum / update / fonts / defaults ----------
+
+fn paste_lorem(s: &mut Session, p: &Value) -> Result<Value> {
+ if has_text(s).is_ok() && p.get("new").and_then(Value::as_bool) != Some(true) {
+ let caret = with_text(s, p, "Paste Lorem Ipsum", |t, _| {
+ let at = p.get("at").and_then(Value::as_u64).map_or(t.text.len(), |c| byte_index(&t.text, c as usize));
+ replace_text(t, at, at, LOREM_IPSUM);
+ Ok(char_index(&t.text, at + LOREM_IPSUM.len()))
+ })?;
+ return Ok(json!({"caret": caret}));
+ }
+ // No type layer active: a paragraph text box over most of the canvas.
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let (w, h) = (d.doc.size.width as f64, d.doc.size.height as f64);
+ let size = p.get("size").and_then(Value::as_f64).unwrap_or((h / 20.0 * 72.0 / f64::from(d.doc.resolution_dpi)).clamp(6.0, 72.0));
+ let r = s.execute("type.create", json!({"box": [w * 0.1, h * 0.1, w * 0.8, h * 0.8], "text": LOREM_IPSUM, "size": size, "name": "Lorem ipsum"}))?;
+ Ok(json!({"layer": r["layer"]}))
+}
+
+fn update_all(s: &mut Session) -> Result<Value> {
+ let mut n = 0;
+ s.edit("Update All Text Layers", |doc, _| {
+ let snapshot = doc.clone();
+ let ids: Vec<LayerId> = snapshot.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();
+ for id in ids {
+ if let Some(Layer { content: LayerContent::Text(t), .. }) = doc.layer_mut(id) {
+ refresh(&snapshot, t);
+ n += 1;
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({"updated": n}))
+}
+
+fn installed_families() -> Vec<String> {
+ photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.families().into_iter().map(|f| f.to_lowercase()).collect()
+}
+
+/// Font families used by type layers that the font database cannot supply.
+pub fn missing_fonts(doc: &Document) -> Vec<String> {
+ let have = installed_families();
+ let mut out: Vec<String> = Vec::new();
+ for (_, _, l) in doc.walk() {
+ if let LayerContent::Text(t) = &l.content {
+ for r in t.char_runs() {
+ let f = r.style.font_family;
+ if !f.is_empty() && !have.contains(&f.to_lowercase()) && !out.contains(&f) {
+ out.push(f);
+ }
+ }
+ }
+ }
+ out
+}
+
+/// Replace missing families per `map` (missing → installed; unmapped ones → the default family).
+fn replace_fonts(s: &mut Session, map: &serde_json::Map<String, Value>, all: bool) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let missing = missing_fonts(&d.doc);
+ let pick = |f: &str| -> Option<String> {
+ if !missing.iter().any(|m| m == f) {
+ return None;
+ }
+ map.get(f).and_then(Value::as_str).map(str::to_string).or_else(|| all.then(|| photocraft_text::fonts::DEFAULT_FAMILY.to_string()))
+ };
+ let ids: Vec<LayerId> = d.doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();
+ if missing.is_empty() {
+ return Ok(json!({"missing": [], "replaced": 0}));
+ }
+ let mut n = 0;
+ s.edit("Replace Missing Fonts", |doc, _| {
+ let snapshot = doc.clone();
+ for id in &ids {
+ if let Some(Layer { content: LayerContent::Text(t), .. }) = doc.layer_mut(*id) {
+ let mut changed = false;
+ let runs = t.char_runs();
+ let mut at = 0;
+ for r in runs {
+ if let Some(to) = pick(&r.style.font_family) {
+ style_range(t, at, at + r.len, &|st| {
+ st.font_family = to.clone();
+ st.postscript_name = None;
+ });
+ changed = true;
+ }
+ at += r.len;
+ }
+ if changed {
+ refresh(&snapshot, t);
+ n += 1;
+ }
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({"missing": missing, "replaced": n}))
+}
+
+fn resolve_missing(s: &mut Session, p: &Value) -> Result<Value> {
+ match p.get("map").and_then(Value::as_object) {
+ Some(m) => replace_fonts(s, &m.clone(), false),
+ None => Ok(json!({"missing": missing_fonts(&s.active().ok_or(EngineError::NoDocument)?.doc)})),
+ }
+}
+
+fn save_defaults(s: &mut Session) -> Result<Value> {
+ let t = active_text(s).map_err(EngineError::Other)?;
+ let c = t.char_runs().first().map(|r| r.style.clone()).unwrap_or_default();
+ let pp = t.paragraph_runs().first().map(|r| r.style.clone()).unwrap_or_default();
+ let out = json!({"font": c.font_family, "size": c.size_pt});
+ s.type_defaults = Some((c, pp));
+ Ok(out)
+}
+
+fn load_defaults(s: &mut Session, p: &Value) -> Result<Value> {
+ let (c, pp) = s.type_defaults.clone().ok_or(EngineError::Other("no default type styles have been saved".into()))?;
+ with_text(s, p, "Load Default Type Styles", |t, _| {
+ let n = t.text.len();
+ style_range(t, 0, n, &|st| *st = c.clone());
+ style_paragraphs(t, 0, n, &|st| *st = pp.clone());
+ Ok(())
+ })?;
+ Ok(json!({"font": c.font_family, "size": c.size_pt}))
+}
+
+// ---------- registry ----------
+
+pub fn specs() -> Vec<CommandSpec> {
+ macro_rules! spec {
+ ($id:expr, $label:expr, $menu:expr, $params:expr, $enabled:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: $menu, shortcut: None, params: $params, enabled: $enabled, journal: true, run: $run }
+ };
+ }
+ const LP: &str = r##"{"layer":id?}"##;
+ const OT: &str = r##"{"layer":id?,"on":bool? (default: toggle),"range":[startChar,endChar]? (default all)}"##;
+ vec![
+ spec!("type.antiAlias.none", "None", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::None)),
+ spec!("type.antiAlias.sharp", "Sharp", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Sharp)),
+ spec!("type.antiAlias.crisp", "Crisp", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Crisp)),
+ spec!("type.antiAlias.strong", "Strong", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Strong)),
+ spec!("type.antiAlias.smooth", "Smooth", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Smooth)),
+ spec!("type.antiAlias.windowsLcd", "Windows LCD", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::WindowsLcd)),
+ spec!("type.antiAlias.windows", "Windows", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Windows)),
+ spec!("type.orientation.horizontal", "Horizontal", &["Type", "Orientation"], LP, has_text, |s, p| set_orientation(s, p, Orientation::Horizontal)),
+ spec!("type.orientation.vertical", "Vertical", &["Type", "Orientation"], r##"{"layer":id?} (stored and saved; rendered horizontally for now)"##, has_text, |s, p| set_orientation(s, p, Orientation::Vertical)),
+ spec!("type.openType.standardLigatures", "Standard Ligatures", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "liga")),
+ spec!("type.openType.contextualAlternates", "Contextual Alternates", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "calt")),
+ spec!("type.openType.discretionaryLigatures", "Discretionary Ligatures", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "dlig")),
+ spec!("type.openType.swash", "Swash", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "swsh")),
+ spec!("type.openType.oldstyle", "Oldstyle", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "onum")),
+ spec!("type.openType.stylisticAlternates", "Stylistic Alternates", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "salt")),
+ spec!("type.openType.titlingAlternates", "Titling Alternates", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "titl")),
+ spec!("type.openType.ornaments", "Ornaments", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "ornm")),
+ spec!("type.openType.ordinals", "Ordinals", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "ordn")),
+ spec!("type.openType.fractions", "Fractions", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "frac")),
+ spec!("type.createWorkPath", "Create Work Path", &["Type"], LP, has_text, create_work_path),
+ spec!("type.convertToShape", "Convert to Shape", &["Type"], LP, has_text, convert_to_shape),
+ spec!("type.rasterizeTypeLayer", "Rasterize Type Layer", &["Type"], LP, has_text, |s, p| s.execute("type.rasterize", p.clone())),
+ spec!("type.convertToParagraphText", "Convert to Paragraph Text", &["Type"], LP, has_point_text, to_paragraph),
+ spec!("type.convertToPointText", "Convert to Point Text", &["Type"], LP, has_box_text, to_point),
+ spec!("type.warpText", "Warp Text…", &["Type"], r##"{"layer":id?,"style":"none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist"="arc","bend":-100..100=50,"horizontalDistortion":-100..100=0,"verticalDistortion":-100..100=0,"orientation":"horizontal|vertical"="horizontal"}"##, has_text, warp_text),
+ spec!("type.updateAllTextLayers", "Update All Text Layers", &["Type"], "{}", any_text, |s, _| update_all(s)),
+ spec!("type.replaceAllMissingFonts", "Replace All Missing Fonts", &["Type"], "{} (with the default family)", any_text, |s, _| replace_fonts(s, &serde_json::Map::new(), true)),
+ spec!("type.resolveMissingFonts", "Resolve Missing Fonts…", &["Type"], r##"{"map":{"Missing Family":"Installed Family"}?} (no map: list the missing families)"##, any_text, resolve_missing),
+ spec!("type.pasteLoremIpsum", "Paste Lorem Ipsum", &["Type"], r##"{"layer":id?,"at":char? (default end),"new":bool=false (new paragraph text layer)}"##, has_doc, paste_lorem),
+ spec!("type.saveDefaultTypeStyles", "Save Default Type Styles", &["Type"], "{} (from the active type layer; new type layers start from them)", has_text, |s, _| save_defaults(s)),
+ spec!("type.loadDefaultTypeStyles", "Load Default Type Styles", &["Type"], LP, has_defaults, load_defaults),
+ ]
+}
+
+#[cfg(test)]
+#[path = "type_extra_cmds/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/type_extra_cmds/tests.rs b/crates/engine/src/type_extra_cmds/tests.rs
new file mode 100644
index 000000000..df26a2182
--- /dev/null
+++ b/crates/engine/src/type_extra_cmds/tests.rs
@@ -0,0 +1,203 @@
+use super::*;
+
+fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 300, "height": 120, "depth": depth, "background": "white"})).unwrap();
+ s
+}
+
+fn text_layer(s: &mut Session, text: &str) -> LayerId {
+ let r = s.execute("type.create", json!({"x": 20, "y": 70, "text": text, "size": 36, "color": "#000000"})).unwrap();
+ LayerId(r["layer"].as_u64().unwrap())
+}
+
+fn text(s: &Session, id: LayerId) -> &TextLayer {
+ match &s.active().unwrap().doc.layer(id).unwrap().content {
+ LayerContent::Text(t) => t,
+ c => panic!("not text: {}", c.kind_name()),
+ }
+}
+
+fn ink(s: &Session, id: LayerId) -> photocraft_geom::Rect {
+ s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds()
+}
+
+#[test]
+fn anti_alias_and_orientation_are_one_step_each() {
+ let mut s = session(8);
+ assert!(!s.is_enabled("type.antiAlias.crisp"));
+ let id = text_layer(&mut s, "Aa");
+ for (cmd, aa) in [("type.antiAlias.crisp", AntiAlias::Crisp), ("type.antiAlias.windows", AntiAlias::Windows), ("type.antiAlias.windowsLcd", AntiAlias::WindowsLcd), ("type.antiAlias.none", AntiAlias::None)] {
+ s.execute(cmd, json!({})).unwrap();
+ assert_eq!(text(&s, id).antialias, aa);
+ }
+ // No anti-aliasing: only fully covered or empty pixels.
+ let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone();
+ let r = surf.content_bounds();
+ let n = surf.channels();
+ assert!(surf.read_region(r).chunks_exact(n).all(|p| p[n - 1] == 0.0 || p[n - 1] == 1.0));
+ s.execute("type.orientation.vertical", json!({})).unwrap();
+ assert_eq!(text(&s, id).orientation, Orientation::Vertical);
+ assert!(s.undo());
+ assert_eq!(text(&s, id).orientation, Orientation::Horizontal);
+ assert!(s.undo());
+ assert_eq!(text(&s, id).antialias, AntiAlias::WindowsLcd);
+}
+
+#[test]
+fn point_and_paragraph_conversion_keep_the_text_in_place() {
+ for align in ["left", "center", "right"] {
+ let mut s = session(8);
+ let r = s.execute("type.create", json!({"x": 150, "y": 70, "text": "Hello world", "size": 30, "align": align})).unwrap();
+ let id = LayerId(r["layer"].as_u64().unwrap());
+ let before = ink(&s, id);
+ assert!(!s.is_enabled("type.convertToPointText"));
+ s.execute("type.convertToParagraphText", json!({})).unwrap();
+ assert!(matches!(text(&s, id).shape, TextShape::Box { .. }));
+ let after = ink(&s, id);
+ assert!((after.x0 - before.x0).abs() <= 2 && (after.y0 - before.y0).abs() <= 2, "{align}: {before:?} → {after:?}");
+ let lines = |s: &Session| {
+ let st = s.active().unwrap();
+ layout(&st.doc, text(s, id)).lines.len()
+ };
+ assert_eq!(lines(&s), 1, "{align}: no new wraps");
+ s.execute("type.convertToPointText", json!({})).unwrap();
+ assert!(matches!(text(&s, id).shape, TextShape::Point));
+ let back = ink(&s, id);
+ assert!((back.x0 - before.x0).abs() <= 2 && (back.y0 - before.y0).abs() <= 2, "{align}: {before:?} → {back:?}");
+ }
+}
+
+#[test]
+fn paragraph_to_point_hardens_soft_wraps() {
+ let mut s = session(8);
+ let r = s.execute("type.create", json!({"box": [10, 10, 120, 100], "text": "one two three four five six", "size": 18})).unwrap();
+ let id = LayerId(r["layer"].as_u64().unwrap());
+ let st = s.active().unwrap();
+ let soft = layout(&st.doc, text(&s, id)).lines.len();
+ assert!(soft >= 2);
+ let r = s.execute("type.convertToPointText", json!({})).unwrap();
+ assert_eq!(r["inserted"], soft - 1);
+ let t = text(&s, id);
+ assert_eq!(t.text.matches('\n').count(), soft - 1);
+ assert_eq!(t.text.replace('\n', ""), "one two three four five six");
+ let st = s.active().unwrap();
+ assert_eq!(layout(&st.doc, text(&s, id)).lines.len(), soft);
+}
+
+#[test]
+fn work_path_and_shape_follow_the_glyphs() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ let id = text_layer(&mut s, "oil");
+ let before = ink(&s, id);
+ s.execute("type.createWorkPath", json!({})).unwrap();
+ let wp = s.active().unwrap().doc.work_path.clone().unwrap();
+ // 'o' has an outer contour and a counter (subtracted), plus 'i' (stem + dot) and 'l'.
+ assert!(wp.subpaths.len() >= 5, "{}", wp.subpaths.len());
+ assert!(wp.subpaths.iter().any(|sp| sp.op == PathOp::Subtract));
+ let (x0, y0, x1, y1) = wp.control_bounds().unwrap();
+ assert!((x0 - before.x0 as f64).abs() < 3.0 && (x1 - before.x1 as f64).abs() < 3.0, "{x0},{x1} vs {before:?}");
+ assert!((y0 - before.y0 as f64).abs() < 3.0 && (y1 - before.y1 as f64).abs() < 3.0);
+ // Convert to Shape renders the same pixels (the counter of the 'o' stays open).
+ let comp_before = photocraft_compose::flatten(&s.active().unwrap().doc);
+ s.execute("type.convertToShape", json!({})).unwrap();
+ let l = s.active().unwrap().doc.layer(id).unwrap();
+ assert!(matches!(l.content, LayerContent::Shape(_)));
+ assert!(!l.psd_blocks.iter().any(|(k, _)| k == b"TySh"));
+ let comp_after = photocraft_compose::flatten(&s.active().unwrap().doc);
+ let diff: f32 = comp_before.px.iter().zip(&comp_after.px).map(|(a, b)| (a[0] - b[0]).abs()).sum::<f32>() / comp_before.px.len() as f32;
+ assert!(diff < 0.01, "depth {depth}: mean diff {diff}");
+ // The middle of the 'o' counter is background (white).
+ assert!(s.undo());
+ assert!(matches!(s.active().unwrap().doc.layer(id).unwrap().content, LayerContent::Text(_)));
+ }
+}
+
+#[test]
+fn warp_text_changes_pixels_and_round_trips() {
+ let mut s = session(8);
+ let id = text_layer(&mut s, "WARP ME");
+ let flat = ink(&s, id);
+ s.execute("type.warpText", json!({"style": "arc", "bend": 60})).unwrap();
+ let w = text(&s, id).warp.clone().unwrap();
+ assert_eq!(w.style, "warpArc");
+ assert_eq!(w.value, 60.0);
+ let arced = ink(&s, id);
+ assert!(arced.height() > flat.height() + 8, "{flat:?} → {arced:?}");
+ // The regenerated TySh carries the warp (PSD round trip).
+ let raw = text(&s, id).psd_raw.clone().unwrap();
+ let back = photocraft_text::psd::text_layer_from_tysh(&raw, 72.0).unwrap();
+ assert_eq!(back.warp, Some(w));
+ assert!(s.execute("type.warpText", json!({"style": "spiral"})).is_err());
+ s.execute("type.warpText", json!({"style": "none"})).unwrap();
+ assert!(text(&s, id).warp.is_none());
+ assert_eq!(ink(&s, id), flat);
+ for (_, style) in photocraft_text::warp::STYLES {
+ s.execute("type.warpText", json!({"style": style, "bend": -40, "horizontalDistortion": 10})).unwrap();
+ assert!(!ink(&s, id).is_empty(), "{style}");
+ }
+}
+
+#[test]
+fn opentype_toggles_store_features() {
+ let mut s = session(8);
+ let id = text_layer(&mut s, "office 1/2");
+ let st = |s: &Session| text(s, id).char_runs()[0].style.clone();
+ assert!(st(&s).ligatures);
+ s.execute("type.openType.standardLigatures", json!({})).unwrap();
+ assert!(!st(&s).ligatures);
+ s.execute("type.openType.fractions", json!({})).unwrap();
+ s.execute("type.openType.discretionaryLigatures", json!({"on": true})).unwrap();
+ s.execute("type.openType.swash", json!({"range": [0, 3]})).unwrap();
+ assert!(feature_on(&st(&s), "frac") && feature_on(&st(&s), "dlig") && feature_on(&st(&s), "swsh"));
+ let runs = text(&s, id).char_runs();
+ assert!(!feature_on(&runs.last().unwrap().style, "swsh"), "range respected");
+ s.execute("type.openType.fractions", json!({})).unwrap();
+ assert!(!feature_on(&st(&s), "frac"));
+ // PSD round trip of the toggles.
+ let raw = text(&s, id).psd_raw.clone().unwrap();
+ let back = photocraft_text::psd::text_layer_from_tysh(&raw, 72.0).unwrap();
+ assert!(feature_on(&back.char_runs()[0].style, "swsh") && !back.char_runs()[0].style.ligatures);
+}
+
+#[test]
+fn lorem_update_fonts_and_default_styles() {
+ let mut s = session(16);
+ // No type layer: a new paragraph box.
+ let r = s.execute("type.pasteLoremIpsum", json!({})).unwrap();
+ let box_id = LayerId(r["layer"].as_u64().unwrap());
+ assert!(matches!(text(&s, box_id).shape, TextShape::Box { .. }));
+ let id = text_layer(&mut s, "Hi ");
+ let r = s.execute("type.pasteLoremIpsum", json!({})).unwrap();
+ assert!(text(&s, id).text.starts_with("Hi Lorem ipsum"));
+ assert_eq!(r["caret"], text(&s, id).text.chars().count());
+ assert_eq!(s.execute("type.updateAllTextLayers", json!({})).unwrap()["updated"], 2);
+ // A missing font is reported and replaced.
+ s.execute("type.setStyle", json!({"font": "No Such Font Family"})).unwrap();
+ assert_eq!(s.execute("type.resolveMissingFonts", json!({})).unwrap()["missing"], json!(["No Such Font Family"]));
+ s.execute("type.resolveMissingFonts", json!({"map": {"No Such Font Family": "JetBrains Mono"}})).unwrap();
+ assert_eq!(text(&s, id).char_runs()[0].style.font_family, "JetBrains Mono");
+ s.execute("type.setStyle", json!({"font": "Gone Sans"})).unwrap();
+ assert_eq!(s.execute("type.replaceAllMissingFonts", json!({})).unwrap()["replaced"], 1);
+ assert_eq!(text(&s, id).char_runs()[0].style.font_family, photocraft_text::fonts::DEFAULT_FAMILY);
+ // Default type styles: save from one layer, new layers and Load use them.
+ assert!(!s.is_enabled("type.loadDefaultTypeStyles"));
+ s.execute("type.setStyle", json!({"size": 50, "font": "JetBrains Mono"})).unwrap();
+ s.execute("type.saveDefaultTypeStyles", json!({})).unwrap();
+ s.select_layer(box_id).unwrap();
+ s.execute("type.loadDefaultTypeStyles", json!({})).unwrap();
+ assert_eq!(text(&s, box_id).char_runs()[0].style.size_pt, 50.0);
+ let r = s.execute("type.create", json!({"x": 5, "y": 5, "text": "new"})).unwrap();
+ let st = text(&s, LayerId(r["layer"].as_u64().unwrap())).char_runs()[0].style.clone();
+ assert_eq!((st.font_family.as_str(), st.size_pt), ("JetBrains Mono", 50.0));
+}
+
+#[test]
+fn rasterize_type_layer() {
+ let mut s = session(8);
+ let id = text_layer(&mut s, "R");
+ s.execute("type.rasterizeTypeLayer", json!({})).unwrap();
+ assert!(matches!(s.active().unwrap().doc.layer(id).unwrap().content, LayerContent::Raster(_)));
+ assert!(!s.is_enabled("type.rasterizeTypeLayer"));
+}
diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rs
index e9faee798..9d6f55b89 100644
--- a/crates/engine/src/vector_cmds.rs
+++ b/crates/engine/src/vector_cmds.rs
@@ -188,7 +188,7 @@ fn fill_json(f: &Fill) -> Value {
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 }),
+ Fill::Pattern { name, scale, .. } => json!({ "pattern": name, "scale": scale * 100.0 }),
}
}
@@ -223,7 +223,7 @@ fn parse_fill(v: &Value) -> std::result::Result<Option<Fill>, String> {
}));
}
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 }));
+ return Ok(Some(Fill::Pattern { name: name.into(), scale: f64p(v, "scale").unwrap_or(100.0) as f32 / 100.0, id: String::new(), angle: 0.0, link: true, phase: (0.0, 0.0) }));
}
Err(format!("unrecognised fill {v}"))
}
@@ -827,7 +827,7 @@ fn path_stroke(s: &mut Session, p: &Value) -> Result<Value> {
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();
+ let mut pts: Vec<photocraft_paint::StrokePoint> = pl.pts.iter().map(|&(x, y)| photocraft_paint::StrokePoint::new(x, y, 1.0)).collect();
if pl.closed && let Some(first) = pts.first().copied() {
pts.push(first);
}
diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs
new file mode 100644
index 000000000..360f125aa
--- /dev/null
+++ b/crates/engine/src/warp_cmds.rs
@@ -0,0 +1,446 @@
+//! Edit › Transform › Warp, Layer › Smart Objects › Warp and split warps.
+//!
+//! A warp is a [`Warp`] (preset style + bend/distortions, or a custom bicubic Bezier mesh)
+//! defined over a source box in document space. Pixel layers are resampled once
+//! (`photocraft_algo::warp`); smart objects store the warp in their source space and re-render
+//! from the source, so editing a smart object's warp never degrades it.
+//!
+//! The split commands edit a mesh: either one passed in (`"warp"`, returned edited — what the
+//! Free Transform warp UI uses) or the active smart object's stored warp (a history step).
+
+use photocraft_algo::transform::Interp;
+use photocraft_algo::warp::{warp_mesh_gray, warp_mesh_surface};
+use photocraft_doc::{Document, Layer, LayerContent, LayerId, Rect};
+use photocraft_geom::Affine;
+use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+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 active_smart(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document")?;
+ match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) {
+ Some(LayerContent::Smart(_)) => Ok(()),
+ _ => Err("the active layer is not a smart object".into()),
+ }
+}
+
+fn rect_f(r: Rect) -> [f64; 4] {
+ [f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)]
+}
+
+fn affine_apply(t: &Affine, p: [f64; 2]) -> [f64; 2] {
+ let [a, b, c, d, e, f] = t.m;
+ [a * p[0] + c * p[1] + e, b * p[0] + d * p[1] + f]
+}
+
+/// The box a warp of `layer` starts from (Free Transform's frame).
+/// For a warped smart object that is its (unwarped) source box, so re-warping replaces the warp
+/// over the same frame.
+pub fn warp_bounds(doc: &Document, layer: &Layer) -> Rect {
+ if let LayerContent::Smart(sm) = &layer.content
+ && let Some(w) = &sm.warp
+ {
+ let t = sm.transform;
+ let c = [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| affine_apply(&t, p));
+ let b = c.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);
+ return Rect::new(b[0].round() as i32, b[1].round() as i32, b[2].round() as i32, b[3].round() as i32);
+ }
+ crate::transform_cmds::transform_bounds(doc, layer)
+}
+
+/// A smart object's stored warp expressed in document space (for editing), if it has one.
+pub fn smart_warp_doc_space(layer: &Layer) -> Option<Warp> {
+ let LayerContent::Smart(sm) = &layer.content else { return None };
+ let w = sm.warp.as_ref()?;
+ let t = sm.transform;
+ let mesh = w.to_mesh(1, 1).map_points(|p| affine_apply(&t, p));
+ let corners = [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| affine_apply(&t, p));
+ let b = corners.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);
+ Some(Warp::custom(mesh, b))
+}
+
+/// Parses the warp params: a full `"warp"` object, or `"style"` (+ `"bend"`, `"hDistort"`,
+/// `"vDistort"`, `"vertical"`), `"mesh"` and `"grid"` over `rect`.
+pub fn warp_from_params(cmd: &str, p: &Value, rect: [f64; 4]) -> Result<Warp> {
+ if let Some(w) = p.get("warp") {
+ let w: Warp = serde_json::from_value(w.clone()).map_err(|e| bad(cmd, format!("bad `warp`: {e}")))?;
+ if w.mesh.as_ref().is_some_and(|m| !m.is_valid()) {
+ return Err(bad(cmd, "malformed warp mesh"));
+ }
+ return Ok(w);
+ }
+ let num = |k: &str, d: f64| p.get(k).and_then(Value::as_f64).unwrap_or(d);
+ let style = match p.get("style").and_then(Value::as_str) {
+ Some(st) => WarpStyle::parse(st).ok_or_else(|| bad(cmd, format!("unknown warp style \"{st}\"")))?,
+ None if p.get("mesh").is_some() || p.get("grid").is_some() => WarpStyle::Custom,
+ None => return Err(bad(cmd, "pass `style` (arc, flag, …, custom), `mesh` or `warp`")),
+ };
+ let mut w = Warp::preset(style, num("bend", 50.0), rect);
+ w.h_distort = num("hDistort", 0.0);
+ w.v_distort = num("vDistort", 0.0);
+ w.vertical = p.get("vertical").and_then(Value::as_bool).unwrap_or(false);
+ if style == WarpStyle::Custom {
+ let mesh = match p.get("mesh") {
+ Some(m) => {
+ let m: BezierMesh = serde_json::from_value(m.clone()).map_err(|e| bad(cmd, format!("bad `mesh`: {e}")))?;
+ if !m.is_valid() {
+ return Err(bad(cmd, "malformed mesh (need (3·cols+1)×(3·rows+1) points and knots 0..1)"));
+ }
+ m
+ }
+ None => {
+ let g = p.get("grid").and_then(Value::as_array);
+ let at = |i: usize| g.and_then(|a| a.get(i)).and_then(Value::as_u64).unwrap_or(1) as usize;
+ BezierMesh::identity(rect, at(0), at(1))
+ }
+ };
+ w.mesh = Some(mesh);
+ }
+ Ok(w)
+}
+
+fn warp_layer(doc_sel: Option<&Surface>, l: &mut Layer, w: &Warp, rect: Rect, interp: Interp) -> Result<()> {
+ 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)));
+ }
+ let map = |x: f64, y: f64| w.map(x, y);
+ match &mut l.content {
+ LayerContent::Group(g) => {
+ for c in g.children.iter_mut() {
+ warp_layer(None, c, w, rect, interp)?;
+ }
+ }
+ LayerContent::Text(_) => return Err(EngineError::Other("Warp needs rasterized type (or use Type › Warp Text)".into())),
+ LayerContent::Shape(_) => return Err(EngineError::Other("Warp needs a rasterized shape (Layer › Rasterize › Shape)".into())),
+ LayerContent::Smart(sm) => {
+ // Store in source space: undo the placement transform around the warp.
+ let t = sm.transform;
+ let inv = t.inverse().ok_or_else(|| EngineError::Other("the smart object's transform is degenerate".into()))?;
+ let corners = [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| affine_apply(&inv, p));
+ let sb = corners.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);
+ let src_warp = match w.style {
+ WarpStyle::None => None,
+ WarpStyle::Custom => Some(Warp::custom(w.to_mesh(1, 1).map_points(|p| affine_apply(&inv, p)), sb)),
+ _ => Some(Warp { bounds: sb, mesh: None, ..w.clone() }),
+ };
+ sm.warp = src_warp.filter(|w| !w.is_identity());
+ // Fallback appearance for sources that can't be re-rendered.
+ if let Some(c) = &mut sm.cache {
+ *c = warp_mesh_surface(c, rect, &map, interp);
+ }
+ if let Some(m) = &mut sm.filter_mask {
+ m.surface = warp_mesh_gray(&m.surface, &map, interp);
+ }
+ }
+ _ => {
+ if let Some(surf) = l.surface_mut() {
+ *surf = match doc_sel {
+ Some(sel) => {
+ let (lifted, mut rest) = crate::transform_cmds::split_selected(surf, sel);
+ let moved = warp_mesh_surface(&lifted, rect, &map, interp);
+ crate::transform_cmds::composite_over(&mut rest, &moved);
+ rest.prune();
+ rest
+ }
+ None => {
+ // Content outside the warp box stays where it is.
+ let fmt = surf.format();
+ let warped = warp_mesh_surface(surf, rect, &map, interp);
+ let mut rest = surf.convert(photocraft_color::PixelFormat::new(fmt.mode, fmt.sample, true));
+ crate::pixels::clear_surface(&mut rest, rect, None);
+ crate::transform_cmds::composite_over(&mut rest, &warped);
+ rest.prune();
+ rest
+ }
+ };
+ }
+ }
+ }
+ if let Some(m) = l.mask.as_mut()
+ && m.linked
+ {
+ m.surface = warp_mesh_gray(&m.surface, &map, interp);
+ }
+ Ok(())
+}
+
+fn target(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, Rect)> {
+ 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<i32> = r.iter().map(|x| x.as_f64().unwrap_or(0.0).round() as i32).collect();
+ Rect::new(v[0], v[1], v[2], v[3])
+ }
+ _ => warp_bounds(&st.doc, layer),
+ };
+ if rect.is_empty() {
+ return Err(bad(cmd, "nothing to warp"));
+ }
+ Ok((id, rect))
+}
+
+fn apply(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
+ let (id, rect) = target(s, cmd, p)?;
+ let w = warp_from_params(cmd, p, rect_f(rect))?;
+ let is_smart = matches!(s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content), Some(LayerContent::Smart(_)));
+ if w.is_identity() && !is_smart {
+ return Ok(json!({"layer": id.0, "changed": false}));
+ }
+ let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic"));
+ s.edit("Warp", |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))?;
+ warp_layer(if is_group { None } else { sel.as_ref() }, l, &w, rect, interp)?;
+ let snapshot = doc.clone();
+ if let Some(l) = doc.layer_mut(id) {
+ crate::transform_cmds::refresh_text(&snapshot, l);
+ }
+ if let Some(sel) = &doc.selection {
+ doc.selection = Some(warp_mesh_gray(sel, &|x, y| w.map(x, y), Interp::Bilinear)).filter(|s| !s.content_bounds().is_empty());
+ }
+ Ok(())
+ })?;
+ Ok(json!({"layer": id.0, "changed": true, "rect": [rect.x0, rect.y0, rect.x1, rect.y1]}))
+}
+
+#[derive(Clone, Copy)]
+pub enum Split {
+ Crosswise,
+ Horizontal,
+ Vertical,
+ Remove,
+}
+
+/// Applies a split (or removes the split nearest `at`) on `w`'s mesh (presets become custom).
+pub fn split_warp(w: &Warp, at: Option<[f64; 2]>, how: Split) -> Option<Warp> {
+ let mut mesh = w.to_mesh(1, 1);
+ let (s, t) = match at {
+ Some(p) => mesh.param_at(p),
+ None => (0.5, 0.5),
+ };
+ // Split inside the patch: the middle of the patch containing (s, t) when no point is given.
+ let mid = |k: &[f64], v: f64| {
+ let i = k.windows(2).position(|w| v <= w[1]).unwrap_or(k.len() - 2);
+ (k[i] + k[i + 1]) / 2.0
+ };
+ let (s, t) = if at.is_some() { (s, t) } else { (mid(&mesh.us, s), mid(&mesh.vs, t)) };
+ let ok = match how {
+ Split::Crosswise => {
+ let a = mesh.split_u(s);
+ let b = mesh.split_v(t);
+ a || b
+ }
+ // A horizontal split line divides rows; a vertical one divides columns.
+ Split::Horizontal => mesh.split_v(t),
+ Split::Vertical => mesh.split_u(s),
+ Split::Remove => {
+ let near = |k: &[f64], v: f64| (1..k.len() - 1).min_by(|a, b| (k[*a] - v).abs().total_cmp(&(k[*b] - v).abs()));
+ let (iu, iv) = (near(&mesh.us, s), near(&mesh.vs, t));
+ let du = iu.map_or(f64::MAX, |i| (mesh.us[i] - s).abs());
+ let dv = iv.map_or(f64::MAX, |i| (mesh.vs[i] - t).abs());
+ match (iu, iv) {
+ (Some(i), _) if du <= dv => mesh.remove_split_u(i),
+ (_, Some(i)) => mesh.remove_split_v(i),
+ (Some(i), None) => mesh.remove_split_u(i),
+ _ => false,
+ }
+ }
+ };
+ ok.then(|| Warp::custom(mesh, w.bounds))
+}
+
+fn split(s: &mut Session, p: &Value, cmd: &str, how: Split) -> Result<Value> {
+ let at = p.get("at").and_then(Value::as_array).and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?]));
+ if p.get("warp").is_some() || p.get("mesh").is_some() || p.get("style").is_some() {
+ let rect = p.get("rect").and_then(Value::as_array).map(|r| {
+ let v: Vec<f64> = r.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect();
+ [v[0], v.get(1).copied().unwrap_or(0.0), v.get(2).copied().unwrap_or(1.0), v.get(3).copied().unwrap_or(1.0)]
+ });
+ let rect = rect.unwrap_or([0.0, 0.0, 1.0, 1.0]);
+ let w = warp_from_params(cmd, p, rect)?;
+ let out = split_warp(&w, at, how).ok_or_else(|| bad(cmd, "nothing to split or remove there"))?;
+ return Ok(json!({"warp": out}));
+ }
+ // The active smart object's stored warp.
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let id = st.active_layer.ok_or(EngineError::Other("no active layer".into()))?;
+ let layer = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let LayerContent::Smart(sm) = &layer.content else {
+ return Err(bad(cmd, "pass the warp being edited (`warp`), or select a warped smart object"));
+ };
+ let w = sm.warp.clone().unwrap_or_else(|| {
+ let b = layer.surface().map_or(Rect::EMPTY, Surface::content_bounds);
+ let inv = sm.transform.inverse().unwrap_or(Affine::IDENTITY);
+ let c = [affine_apply(&inv, [f64::from(b.x0), f64::from(b.y0)]), affine_apply(&inv, [f64::from(b.x1), f64::from(b.y1)])];
+ Warp::none([c[0][0].min(c[1][0]), c[0][1].min(c[1][1]), c[0][0].max(c[1][0]), c[0][1].max(c[1][1])])
+ });
+ let t = sm.transform;
+ let at_src = at.and_then(|a| t.inverse().map(|inv| affine_apply(&inv, a)));
+ let out = split_warp(&w, at_src, how).ok_or_else(|| bad(cmd, "nothing to split or remove there"))?;
+ let label = if matches!(how, Split::Remove) { "Remove Warp Split" } else { "Split Warp" };
+ s.edit(label, |doc, _| {
+ if let Some(Layer { content: LayerContent::Smart(sm), .. }) = doc.layer_mut(id) {
+ sm.warp = Some(out.clone());
+ }
+ crate::smart_cmds::refresh(doc, id).map(|_| ())
+ })?;
+ Ok(json!({"layer": id.0, "warp": out}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ const P: &str = r##"{"layer":id?,"rect":[x0,y0,x1,y1]? (warp box; default = layer content ∩ selection),"style":"custom|none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist","bend":%=50,"hDistort":%,"vDistort":%,"vertical":bool,"mesh":{"us":[0,…,1],"vs":[0,…,1],"points":[[x,y]…]} ((3c+1)×(3r+1) control points, row-major, document px),"grid":[cols,rows]?,"warp":{full warp object}?,"interpolation":"bicubic|bilinear|nearest"}"##;
+ const S: &str = r##"{"warp":{…}? (the warp being edited; returned split),"rect":[x0,y0,x1,y1]?,"at":[x,y]? (document point; default = middle of the patch)} — without `warp`, edits the active smart object's warp"##;
+ vec![
+ CommandSpec { id: "edit.transform.warp", label: "Warp", menu: &["Edit", "Transform"], shortcut: None, params: P, enabled: has_layer, journal: true, run: |s, p| apply(s, p, "edit.transform.warp") },
+ CommandSpec { id: "layer.smartObjects.warp", label: "Warp", menu: &["Layer", "Smart Objects"], shortcut: None, params: P, enabled: active_smart, journal: true, run: |s, p| apply(s, p, "layer.smartObjects.warp") },
+ CommandSpec { id: "edit.transform.splitWarpCrosswise", label: "Split Warp Crosswise", menu: &["Edit", "Transform"], shortcut: None, params: S, enabled: has_layer, journal: true, run: |s, p| split(s, p, "edit.transform.splitWarpCrosswise", Split::Crosswise) },
+ CommandSpec { id: "edit.transform.splitWarpHorizontally", label: "Split Warp Horizontally", menu: &["Edit", "Transform"], shortcut: None, params: S, enabled: has_layer, journal: true, run: |s, p| split(s, p, "edit.transform.splitWarpHorizontally", Split::Horizontal) },
+ CommandSpec { id: "edit.transform.splitWarpVertically", label: "Split Warp Vertically", menu: &["Edit", "Transform"], shortcut: None, params: S, enabled: has_layer, journal: true, run: |s, p| split(s, p, "edit.transform.splitWarpVertically", Split::Vertical) },
+ CommandSpec { id: "edit.transform.removeWarpSplit", label: "Remove Warp Split", menu: &["Edit", "Transform"], shortcut: None, params: S, enabled: has_layer, journal: true, run: |s, p| split(s, p, "edit.transform.removeWarpSplit", Split::Remove) },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn session(depth: u64) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("paint", |doc, active| {
+ let l = doc.layer_mut(active.unwrap()).unwrap();
+ let surf = l.surface_mut().unwrap();
+ for y in 10..40 {
+ for x in 10..60 {
+ let v = ((x * 3 + y * 5) % 11) as f32 / 10.0;
+ surf.write_pixel(x, y, &[v, 1.0 - v, 0.5, 1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ s
+ }
+
+ fn active_surface(s: &Session) -> Surface {
+ let st = s.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone()
+ }
+
+ #[test]
+ fn identity_and_bend_zero_are_no_ops_at_every_depth() {
+ for depth in [8u64, 16, 32] {
+ let mut s = session(depth);
+ let before = active_surface(&s);
+ let r = s.execute("edit.transform.warp", json!({"style": "custom"})).unwrap();
+ assert_eq!(r["changed"], false);
+ s.execute("edit.transform.warp", json!({"style": "flag", "bend": 0})).unwrap();
+ // A custom identity mesh passed explicitly (forces a resample) stays within 1/255.
+ let m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 2, 2);
+ let mut w = Warp::custom(m, [10.0, 10.0, 60.0, 40.0]);
+ w.mesh.as_mut().unwrap().points[5][0] += 1e-12; // not exactly identity
+ s.execute("edit.transform.warp", json!({"warp": w})).unwrap();
+ let after = active_surface(&s);
+ let r = Rect::new(10, 10, 60, 40);
+ assert_eq!(after.content_bounds(), r, "{depth}");
+ let worst = before.read_region(r).iter().zip(after.read_region(r)).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
+ assert!(worst <= 1.0 / 255.0, "{depth}: {worst}");
+ }
+ }
+
+ #[test]
+ fn arc_warps_pixels_and_undoes() {
+ let mut s = session(8);
+ let before = active_surface(&s);
+ s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap();
+ let after = active_surface(&s);
+ assert!(after.content_bounds().y1 > 42, "{:?}", after.content_bounds());
+ assert!(after.pixel(11, 11)[3] < 0.5, "top-left corner pulls in");
+ s.undo();
+ assert_eq!(active_surface(&s), before);
+ assert!(s.execute("edit.transform.warp", json!({"style": "spiral"})).is_err());
+ assert!(s.execute("edit.transform.warp", json!({})).is_err());
+ assert!(s.execute("edit.transform.warp", json!({"mesh": {"us": [0, 1], "vs": [0, 1], "points": [[0, 0]]}})).is_err());
+ }
+
+ #[test]
+ fn custom_mesh_moves_a_control_point() {
+ let mut s = session(16);
+ let mut m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 1, 1);
+ m.points[15] = [70.0, 50.0]; // bottom-right corner
+ s.execute("edit.transform.warp", json!({"mesh": m})).unwrap();
+ let b = active_surface(&s).content_bounds();
+ assert!(b.x1 >= 69 && b.y1 >= 49, "{b:?}");
+ }
+
+ #[test]
+ fn split_commands_edit_meshes_exactly() {
+ let mut s = session(8);
+ let w = Warp::preset(WarpStyle::Bulge, 30.0, [10.0, 10.0, 60.0, 40.0]);
+ let r = s.execute("edit.transform.splitWarpCrosswise", json!({"warp": w, "at": [30.0, 20.0]})).unwrap();
+ let split: Warp = serde_json::from_value(r["warp"].clone()).unwrap();
+ let m = split.mesh.as_ref().unwrap();
+ assert_eq!((m.nx(), m.ny()), (7, 7));
+ let r = s.execute("edit.transform.splitWarpVertically", json!({"warp": split})).unwrap();
+ let v: Warp = serde_json::from_value(r["warp"].clone()).unwrap();
+ assert_eq!(v.mesh.as_ref().unwrap().us.len(), 4);
+ let r = s.execute("edit.transform.removeWarpSplit", json!({"warp": v, "at": [30.0, 20.0]})).unwrap();
+ let back: Warp = serde_json::from_value(r["warp"].clone()).unwrap();
+ assert!(back.mesh.as_ref().unwrap().us.len() + back.mesh.as_ref().unwrap().vs.len() < 7);
+ // Splitting never changes the shape.
+ for (x, y) in [(15.0, 15.0), (40.0, 33.0)] {
+ let (a, b) = (w.map(x, y), split.map(x, y));
+ assert!((a.0 - b.0).abs() < 0.6 && (a.1 - b.1).abs() < 0.6, "{a:?} {b:?}");
+ }
+ }
+
+ #[test]
+ fn smart_object_warp_is_lossless() {
+ for depth in [8u64, 16, 32] {
+ let mut s = session(depth);
+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
+ let original = active_surface(&s);
+ s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap();
+ let warped = active_surface(&s);
+ assert_ne!(warped, original);
+ let st = s.active().unwrap();
+ let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() };
+ assert!(sm.warp.is_some());
+ // Removing the warp re-renders the source exactly (no accumulated resampling).
+ s.execute("layer.smartObjects.warp", json!({"style": "none"})).unwrap();
+ assert_eq!(active_surface(&s), original, "{depth}");
+ // Warping twice equals warping once with the second warp.
+ s.execute("layer.smartObjects.warp", json!({"style": "arc", "bend": 20})).unwrap();
+ s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap();
+ assert_eq!(active_surface(&s), warped, "{depth}");
+ // Split on the stored warp keeps the appearance (within resampling of the mesh fit).
+ s.execute("edit.transform.splitWarpCrosswise", json!({})).unwrap();
+ let st = s.active().unwrap();
+ let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() };
+ assert_eq!(sm.warp.as_ref().unwrap().style, WarpStyle::Custom);
+ }
+ }
+}
diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs
index 1992e60d2..cdebeeead 100644
--- a/crates/format/src/convert.rs
+++ b/crates/format/src/convert.rs
@@ -5,8 +5,8 @@ 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,
+ AlphaChannel, CompAppearance, CompLayerState, DocId, Document, Effects, LayerComp, FillCache, Group, Layer, LayerContent, LayerId,
+ LayerMask, Metadata, NamedPath, Pattern, ShapeLayer, SmartObject, SmartSource, TextLayer,
};
use photocraft_geom::{TILE_SIZE, TileCoord};
use photocraft_raster::{Surface, Tile, decode_pixel, encode_pixel};
@@ -112,6 +112,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
LayerContent::Group(g) => ContentM::Group {
children: g.children.iter().map(|c| layer_m(c, sink)).collect(),
expanded: g.expanded,
+ artboard: g.artboard.clone(),
},
LayerContent::Adjustment(a) => ContentM::Adjustment {
adjustment: a.clone(),
@@ -152,6 +153,16 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
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),
+ filters_enabled: s.filters_enabled,
+ filter_mask: s.filter_mask.as_ref().map(|m| MaskM {
+ surface: surface_m(&m.surface, sink),
+ enabled: m.enabled,
+ linked: m.linked,
+ density: m.density,
+ feather: m.feather,
+ }),
+ warp: s.warp.clone(),
+ stack_mode: s.stack_mode,
},
};
LayerM {
@@ -188,6 +199,20 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
fill: fc.fill.clone(),
surface: surface_m(&fc.surface, sink),
}),
+ link_group: l.link_group,
+ }
+}
+
+fn channel_m(c: &AlphaChannel, sink: &mut dyn Sink) -> ChannelM {
+ // Destructured so a new `AlphaChannel` field fails to compile here until it is saved.
+ let AlphaChannel { name, surface, spot, color, opacity, indicates } = c;
+ ChannelM {
+ name: name.clone(),
+ surface: surface_m(surface, sink),
+ spot: *spot,
+ color: *color,
+ opacity: *opacity,
+ indicates: *indicates,
}
}
@@ -201,15 +226,7 @@ pub(crate) fn doc_m(d: &Document, sink: &mut dyn Sink) -> DocM {
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(),
+ channels: d.channels.iter().map(|c| channel_m(c, sink)).collect(),
guides: d.guides.clone(),
selection: d.selection.as_ref().map(|s| surface_m(s, sink)),
metadata: MetadataM {
@@ -240,6 +257,55 @@ pub(crate) fn doc_m(d: &Document, sink: &mut dyn Sink) -> DocM {
.collect(),
work_path: d.work_path.clone(),
clipping_path: d.clipping_path.clone(),
+ quick_mask: d.quick_mask.as_ref().map(|c| channel_m(c, sink)),
+ patterns: d
+ .patterns
+ .iter()
+ .map(|p| PatternM {
+ id: p.id.clone(),
+ name: p.name.clone(),
+ width: p.width,
+ height: p.height,
+ surface: surface_m(&p.surface, sink),
+ })
+ .collect(),
+ color_table: d.color_table.clone(),
+ duotone: d.duotone.clone(),
+ layer_comps: d.layer_comps.iter().map(|c| comp_m(c, sink)).collect(),
+ last_applied_comp: d.last_applied_comp,
+ last_document_state: d.last_document_state.as_ref().map(|c| comp_m(c, sink)),
+ }
+}
+
+fn effects_m(e: &Effects, sink: &mut dyn Sink) -> EffectsM {
+ EffectsM { enabled: e.enabled, items: e.items.clone(), psd_raw: opt_blob(&e.psd_raw, sink) }
+}
+
+fn comp_m(c: &LayerComp, sink: &mut dyn Sink) -> LayerCompM {
+ // Destructured so a new `LayerComp` field fails to compile here until it is saved.
+ let LayerComp { id, name, comment, apply_visibility, apply_position, apply_appearance, states } = c;
+ LayerCompM {
+ id: *id,
+ name: name.clone(),
+ comment: comment.clone(),
+ apply_visibility: *apply_visibility,
+ apply_position: *apply_position,
+ apply_appearance: *apply_appearance,
+ states: states
+ .iter()
+ .map(|s| {
+ let CompLayerState { layer, visible, position, appearance } = s;
+ CompStateM {
+ layer: layer.0,
+ visible: *visible,
+ position: *position,
+ appearance: appearance.as_ref().map(|a| {
+ let CompAppearance { blend, opacity, fill_opacity, effects } = a;
+ CompAppearanceM { blend: *blend, opacity: *opacity, fill_opacity: *fill_opacity, effects: effects_m(effects, sink) }
+ }),
+ }
+ })
+ .collect(),
}
}
@@ -251,6 +317,8 @@ pub(crate) struct Loader<'a> {
pub fetch: &'a mut dyn Fetch,
pub preserve_ids: bool,
pub max_id: u64,
+ /// Stored layer id → loaded id (differs when ids are remapped), for layer comp states.
+ pub id_map: std::collections::HashMap<u64, LayerId>,
}
impl Loader<'_> {
@@ -289,12 +357,42 @@ impl Loader<'_> {
}
fn id(&mut self, raw: u64) -> LayerId {
- if self.preserve_ids {
+ let id = if self.preserve_ids {
self.max_id = self.max_id.max(raw);
LayerId(raw)
} else {
LayerId::fresh()
+ };
+ self.id_map.insert(raw, id);
+ id
+ }
+
+ fn comp(&mut self, m: &LayerCompM) -> Result<LayerComp> {
+ let mut states = Vec::with_capacity(m.states.len());
+ for s in &m.states {
+ let appearance = match &s.appearance {
+ Some(a) => Some(CompAppearance {
+ blend: a.blend,
+ opacity: a.opacity,
+ fill_opacity: a.fill_opacity,
+ effects: Effects { enabled: a.effects.enabled, items: a.effects.items.clone(), psd_raw: self.opt_blob(&a.effects.psd_raw)? },
+ }),
+ None => None,
+ };
+ // States of layers deleted before the save keep their (now dangling) id, which
+ // `layerComp.updateWarnings` reports; it must not collide with a live layer.
+ let layer = self.id_map.get(&s.layer).copied().unwrap_or(LayerId(u64::MAX - s.layer.min(u64::MAX / 2)));
+ states.push(CompLayerState { layer, visible: s.visible, position: s.position, appearance });
}
+ Ok(LayerComp {
+ id: m.id,
+ name: m.name.clone(),
+ comment: m.comment.clone(),
+ apply_visibility: m.apply_visibility,
+ apply_position: m.apply_position,
+ apply_appearance: m.apply_appearance,
+ states,
+ })
}
fn layer(&mut self, m: &LayerM, depth: usize) -> Result<Layer> {
@@ -305,7 +403,8 @@ impl Loader<'_> {
}
let content = match &m.content {
ContentM::Raster { surface } => LayerContent::Raster(self.surface(surface)?),
- ContentM::Group { children, expanded } => LayerContent::Group(Group {
+ ContentM::Group { children, expanded, artboard } => LayerContent::Group(Group {
+ artboard: artboard.clone(),
children: children
.iter()
.map(|c| self.layer(c, depth + 1))
@@ -364,6 +463,10 @@ impl Loader<'_> {
smart_filters,
cache,
psd_raw,
+ filters_enabled,
+ filter_mask,
+ warp,
+ stack_mode,
} => LayerContent::Smart(SmartObject {
source: match source {
SmartSourceM::Embedded { file_name, blob } => SmartSource::Embedded {
@@ -376,6 +479,19 @@ impl Loader<'_> {
smart_filters: smart_filters.clone(),
cache: self.opt_surface(cache)?,
psd_raw: self.opt_blob(psd_raw)?,
+ filters_enabled: *filters_enabled,
+ filter_mask: match filter_mask {
+ Some(mm) => Some(LayerMask {
+ surface: self.surface(&mm.surface)?,
+ enabled: mm.enabled,
+ linked: mm.linked,
+ density: mm.density,
+ feather: mm.feather,
+ }),
+ None => None,
+ },
+ warp: warp.clone().filter(|w| w.mesh.as_ref().is_none_or(|m| m.is_valid())),
+ stack_mode: *stack_mode,
}),
};
let mask = match &m.mask {
@@ -420,6 +536,7 @@ impl Loader<'_> {
psd_blocks,
psd_id: m.psd_id,
fill_cache,
+ link_group: m.link_group,
})
}
@@ -431,12 +548,9 @@ impl Loader<'_> {
.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,
- });
+ channels.push(self.channel(c)?);
}
+ let quick_mask = m.quick_mask.as_ref().map(|c| self.channel(c)).transpose()?;
let mut md = Metadata {
xmp: m.metadata.xmp.clone(),
exif: self.opt_blob(&m.metadata.exif)?,
@@ -458,6 +572,18 @@ impl Loader<'_> {
psd_raw: self.opt_blob(&p.psd_raw)?,
});
}
+ let mut patterns = Vec::with_capacity(m.patterns.len());
+ for p in &m.patterns {
+ patterns.push(Pattern {
+ id: p.id.clone(),
+ name: p.name.clone(),
+ width: p.width,
+ height: p.height,
+ surface: self.surface(&p.surface)?,
+ });
+ }
+ let layer_comps = m.layer_comps.iter().map(|c| self.comp(c)).collect::<Result<Vec<_>>>()?;
+ let last_document_state = m.last_document_state.as_ref().map(|c| self.comp(c)).transpose()?;
let id = if self.preserve_ids {
self.max_id = self.max_id.max(m.id);
DocId(m.id)
@@ -481,6 +607,24 @@ impl Loader<'_> {
paths,
work_path: m.work_path.clone(),
clipping_path: m.clipping_path.clone(),
+ quick_mask,
+ patterns,
+ color_table: m.color_table.clone(),
+ duotone: m.duotone.clone(),
+ layer_comps,
+ last_applied_comp: m.last_applied_comp,
+ last_document_state,
+ })
+ }
+
+ fn channel(&mut self, c: &ChannelM) -> Result<AlphaChannel> {
+ Ok(AlphaChannel {
+ name: c.name.clone(),
+ surface: self.surface(&c.surface)?,
+ spot: c.spot,
+ color: c.color,
+ opacity: c.opacity,
+ indicates: c.indicates,
})
}
}
diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs
index a4a23f454..6568457df 100644
--- a/crates/format/src/manifest.rs
+++ b/crates/format/src/manifest.rs
@@ -57,6 +57,67 @@ pub struct DocM {
pub work_path: Option<Path>,
#[serde(default)]
pub clipping_path: Option<ClippingPath>,
+ /// The temporary Quick Mask channel (saved while Quick Mask mode is on).
+ #[serde(default)]
+ pub quick_mask: Option<ChannelM>,
+ /// Patterns stored with the document.
+ #[serde(default)]
+ pub patterns: Vec<PatternM>,
+ /// Indexed Color palette.
+ #[serde(default)]
+ pub color_table: Option<photocraft_doc::ColorTable>,
+ /// Duotone inks.
+ #[serde(default)]
+ pub duotone: Option<photocraft_doc::Duotone>,
+ /// Window › Layer Comps.
+ #[serde(default)]
+ pub layer_comps: Vec<LayerCompM>,
+ #[serde(default)]
+ pub last_applied_comp: Option<u32>,
+ #[serde(default)]
+ pub last_document_state: Option<LayerCompM>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct LayerCompM {
+ pub id: u32,
+ pub name: String,
+ #[serde(default)]
+ pub comment: String,
+ pub apply_visibility: bool,
+ pub apply_position: bool,
+ pub apply_appearance: bool,
+ #[serde(default)]
+ pub states: Vec<CompStateM>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct CompStateM {
+ /// Layer id (as in `LayerM::id`).
+ pub layer: u64,
+ #[serde(default)]
+ pub visible: Option<bool>,
+ #[serde(default)]
+ pub position: Option<(i32, i32)>,
+ #[serde(default)]
+ pub appearance: Option<CompAppearanceM>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct CompAppearanceM {
+ pub blend: BlendMode,
+ pub opacity: f32,
+ pub fill_opacity: f32,
+ pub effects: EffectsM,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PatternM {
+ pub id: String,
+ pub name: String,
+ pub width: u32,
+ pub height: u32,
+ pub surface: SurfaceM,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -125,6 +186,9 @@ pub struct LayerM {
pub psd_blocks: Vec<(String, Hash)>,
pub psd_id: Option<u32>,
pub fill_cache: Option<FillCacheM>,
+ /// Link Layers group (`None` = not linked).
+ #[serde(default)]
+ pub link_group: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -136,6 +200,9 @@ pub enum ContentM {
Group {
children: Vec<LayerM>,
expanded: bool,
+ /// Artboard (Layer › New › Artboard).
+ #[serde(default)]
+ artboard: Option<photocraft_doc::Artboard>,
},
Adjustment {
adjustment: Adjustment,
@@ -181,9 +248,21 @@ pub enum ContentM {
smart_filters: Vec<SmartFilter>,
cache: Option<SurfaceM>,
psd_raw: Option<Hash>,
+ #[serde(default = "yes")]
+ filters_enabled: bool,
+ #[serde(default)]
+ filter_mask: Option<MaskM>,
+ #[serde(default)]
+ warp: Option<photocraft_geom::warp::Warp>,
+ #[serde(default)]
+ stack_mode: Option<photocraft_doc::StackMode>,
},
}
+fn yes() -> bool {
+ true
+}
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SmartSourceM {
@@ -196,6 +275,21 @@ pub struct ChannelM {
pub name: String,
pub surface: SurfaceM,
pub spot: Option<(Color, f32)>,
+ /// Channel Options overlay colour (older files: Photoshop's red).
+ #[serde(default = "default_channel_color")]
+ pub color: Color,
+ #[serde(default = "default_channel_opacity")]
+ pub opacity: f32,
+ #[serde(default)]
+ pub indicates: photocraft_doc::ColorIndicates,
+}
+
+fn default_channel_color() -> Color {
+ photocraft_doc::AlphaChannel::DEFAULT_COLOR
+}
+
+fn default_channel_opacity() -> f32 {
+ 0.5
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
@@ -207,3 +301,22 @@ pub struct MetadataM {
/// (signature hex, key hex, blob)
pub psd_global_blocks: Vec<(String, String, Hash)>,
}
+
+#[cfg(test)]
+mod channel_tests {
+ use super::*;
+
+ #[test]
+ fn older_channels_load_with_default_options() {
+ let fmt = serde_json::to_value(PixelFormat::GRAY8).unwrap();
+ let old = serde_json::json!({
+ "name": "Alpha 1",
+ "surface": { "format": fmt, "default": "00", "tiles": [] },
+ "spot": null
+ });
+ let c: ChannelM = serde_json::from_value(old).unwrap();
+ assert_eq!(c.color, photocraft_doc::AlphaChannel::DEFAULT_COLOR);
+ assert_eq!(c.opacity, 0.5);
+ assert_eq!(c.indicates, photocraft_doc::ColorIndicates::MaskedAreas);
+ }
+}
diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs
index e6f47eb74..4b08d5309 100644
--- a/crates/format/src/store.rs
+++ b/crates/format/src/store.rs
@@ -202,6 +202,7 @@ pub(crate) fn load(src: &dyn Source, opts: &LoadOptions) -> Result<Document> {
fetch: &mut fetch,
preserve_ids: opts.preserve_ids,
max_id: 0,
+ id_map: HashMap::new(),
};
let doc = loader.document(&m.document)?;
if opts.preserve_ids && !convert::reserve_ids_through(loader.max_id) {
diff --git a/crates/format/tests/common/mod.rs b/crates/format/tests/common/mod.rs
index d1d2aaee0..bbcbb9529 100644
--- a/crates/format/tests/common/mod.rs
+++ b/crates/format/tests/common/mod.rs
@@ -210,6 +210,16 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
}],
cache: Some(cache),
psd_raw: None,
+ filters_enabled: false,
+ filter_mask: Some(LayerMask {
+ surface: Surface::with_default(PixelFormat::GRAY8, &[1.0]),
+ enabled: true,
+ linked: false,
+ density: 0.75,
+ feather: 0.0,
+ }),
+ warp: Some(photocraft_geom::warp::Warp::custom(photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 48.0, 24.0], 2, 1), [0.0, 0.0, 48.0, 24.0])),
+ stack_mode: Some(photocraft_doc::StackMode::Median),
}),
);
let linked = Layer::new(
@@ -222,6 +232,10 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
smart_filters: vec![],
cache: None,
psd_raw: Some(blob(12, 8)),
+ filters_enabled: true,
+ filter_mask: None,
+ warp: None,
+ stack_mode: None,
}),
);
d.layers
@@ -229,16 +243,21 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
let mut ch = Surface::new(PixelFormat::GRAY8.with_sample(depth));
scribble(&mut ch, 13, false);
+ let mut alpha = AlphaChannel::new("Alpha 1", ch.clone());
+ alpha.color = Color::rgb(0.0, 0.5, 1.0);
+ alpha.opacity = 0.35;
+ alpha.indicates = photocraft_doc::ColorIndicates::SelectedAreas;
+ d.channels.push(alpha);
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)),
+ ..AlphaChannel::new("Spot", ch.clone())
});
+ d.quick_mask = Some(AlphaChannel::new("Quick Mask", ch));
+ let mut pat = Surface::new(PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U16, true));
+ scribble(&mut pat, 21, false);
+ d.patterns.push(photocraft_doc::Pattern::new("$$$/Patterns/Test=Scribble", pat, 32, 24));
+ d.color_table = Some(photocraft_doc::ColorTable { colors: vec![[0, 0, 0], [255, 128, 0]], transparent: Some(1) });
+ d.duotone = Some(photocraft_doc::Duotone { inks: vec![photocraft_doc::DuotoneInk::new("Black", [0.0; 3]), photocraft_doc::DuotoneInk::new("PANTONE 151 C", [1.0, 0.5, 0.0])], psd_raw: Some(vec![1, 2, 3]) });
d.guides = Guides {
horizontal: vec![10.0, 20.5],
vertical: vec![100.25],
diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs
index be86c72e9..592f53c1c 100644
--- a/crates/geom/src/lib.rs
+++ b/crates/geom/src/lib.rs
@@ -6,6 +6,8 @@
use serde::{Deserialize, Serialize};
+pub mod warp;
+
/// Edge length of a raster tile in pixels.
pub const TILE_SIZE: i32 = 256;
diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs
new file mode 100644
index 000000000..91e36e8c6
--- /dev/null
+++ b/crates/geom/src/warp.rs
@@ -0,0 +1,747 @@
+//! Warp geometry shared by Edit › Transform › Warp, smart-object warps and Warp Text.
+//!
+//! Two kinds of warp, both forward maps from a source box to document space:
+//! - **Styles** ([`WarpStyle`], Photoshop's fifteen presets plus bend and horizontal/vertical
+//! distortion, the PSD `warp` descriptor's `warpStyle`/`warpValue`/`warpPerspective*`). The
+//! shapes are our own closed-form approximations of each style's look (observed behaviour, not
+//! Adobe's formulas). Every style is the identity at bend 0 and continuous in the bend.
+//! - **Custom meshes** ([`BezierMesh`]): a grid of bicubic Bezier patches. The default is one
+//! patch (a 4×4 control grid); split warps add patch rows/columns by exact de Casteljau
+//! subdivision, so splitting never changes the shape.
+//!
+//! Pure geometry: resampling lives in `photocraft-algo::warp`.
+
+use serde::{Deserialize, Serialize};
+
+/// Warp style: none, a custom mesh, or one of Photoshop's presets (menu order).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum WarpStyle {
+ #[default]
+ None,
+ Custom,
+ Arc,
+ ArcLower,
+ ArcUpper,
+ Arch,
+ Bulge,
+ ShellLower,
+ ShellUpper,
+ Flag,
+ Wave,
+ Fish,
+ Rise,
+ Fisheye,
+ Inflate,
+ Squeeze,
+ Twist,
+}
+
+impl WarpStyle {
+ /// The fifteen presets in Photoshop's menu order.
+ pub const PRESETS: [WarpStyle; 15] = [
+ WarpStyle::Arc,
+ WarpStyle::ArcLower,
+ WarpStyle::ArcUpper,
+ WarpStyle::Arch,
+ WarpStyle::Bulge,
+ WarpStyle::ShellLower,
+ WarpStyle::ShellUpper,
+ WarpStyle::Flag,
+ WarpStyle::Wave,
+ WarpStyle::Fish,
+ WarpStyle::Rise,
+ WarpStyle::Fisheye,
+ WarpStyle::Inflate,
+ WarpStyle::Squeeze,
+ WarpStyle::Twist,
+ ];
+
+ /// Every style (none, custom, presets).
+ pub fn all() -> impl Iterator<Item = WarpStyle> {
+ [WarpStyle::None, WarpStyle::Custom].into_iter().chain(Self::PRESETS)
+ }
+
+ /// PSD `warpStyle` enum value (`warpArc`, `warpCustom`, `warpNone`…).
+ pub fn psd_name(self) -> &'static str {
+ match self {
+ WarpStyle::None => "warpNone",
+ WarpStyle::Custom => "warpCustom",
+ WarpStyle::Arc => "warpArc",
+ WarpStyle::ArcLower => "warpArcLower",
+ WarpStyle::ArcUpper => "warpArcUpper",
+ WarpStyle::Arch => "warpArch",
+ WarpStyle::Bulge => "warpBulge",
+ WarpStyle::ShellLower => "warpShellLower",
+ WarpStyle::ShellUpper => "warpShellUpper",
+ WarpStyle::Flag => "warpFlag",
+ WarpStyle::Wave => "warpWave",
+ WarpStyle::Fish => "warpFish",
+ WarpStyle::Rise => "warpRise",
+ WarpStyle::Fisheye => "warpFisheye",
+ WarpStyle::Inflate => "warpInflate",
+ WarpStyle::Squeeze => "warpSqueeze",
+ WarpStyle::Twist => "warpTwist",
+ }
+ }
+
+ /// Short id used by commands (`arc`, `arcLower`, `custom`, `none`).
+ pub fn id(self) -> &'static str {
+ let p = self.psd_name().trim_start_matches("warp");
+ // Lower-case first letter without allocating: every id is listed.
+ match p {
+ "None" => "none",
+ "Custom" => "custom",
+ "Arc" => "arc",
+ "ArcLower" => "arcLower",
+ "ArcUpper" => "arcUpper",
+ "Arch" => "arch",
+ "Bulge" => "bulge",
+ "ShellLower" => "shellLower",
+ "ShellUpper" => "shellUpper",
+ "Flag" => "flag",
+ "Wave" => "wave",
+ "Fish" => "fish",
+ "Rise" => "rise",
+ "Fisheye" => "fisheye",
+ "Inflate" => "inflate",
+ "Squeeze" => "squeeze",
+ _ => "twist",
+ }
+ }
+
+ /// Menu label (`Arc Lower`).
+ pub fn label(self) -> &'static str {
+ match self {
+ WarpStyle::None => "None",
+ WarpStyle::Custom => "Custom",
+ WarpStyle::Arc => "Arc",
+ WarpStyle::ArcLower => "Arc Lower",
+ WarpStyle::ArcUpper => "Arc Upper",
+ WarpStyle::Arch => "Arch",
+ WarpStyle::Bulge => "Bulge",
+ WarpStyle::ShellLower => "Shell Lower",
+ WarpStyle::ShellUpper => "Shell Upper",
+ WarpStyle::Flag => "Flag",
+ WarpStyle::Wave => "Wave",
+ WarpStyle::Fish => "Fish",
+ WarpStyle::Rise => "Rise",
+ WarpStyle::Fisheye => "Fisheye",
+ WarpStyle::Inflate => "Inflate",
+ WarpStyle::Squeeze => "Squeeze",
+ WarpStyle::Twist => "Twist",
+ }
+ }
+
+ /// Parses a short id, a PSD name or a label (case-insensitive, spaces ignored).
+ pub fn parse(s: &str) -> Option<WarpStyle> {
+ let k: String = s.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
+ Self::all().find(|w| w.id().to_ascii_lowercase() == k || w.psd_name().to_ascii_lowercase() == k)
+ }
+
+ pub fn is_preset(self) -> bool {
+ !matches!(self, WarpStyle::None | WarpStyle::Custom)
+ }
+}
+
+/// A preset style prepared for one box: strengths and the box it bends.
+#[derive(Clone, Copy, Debug)]
+pub struct StyleWarp {
+ style: WarpStyle,
+ /// Bend, -1..1.
+ b: f64,
+ /// Horizontal / vertical distortion, -1..1.
+ hd: f64,
+ vd: f64,
+ /// Warp along the vertical axis (Photoshop's "Vertical" orientation).
+ vertical: bool,
+ c: (f64, f64),
+ h: (f64, f64),
+}
+
+impl StyleWarp {
+ /// Prepares `style` with bend / distortions in percent (-100..100) for `[x0, y0, x1, y1]`.
+ /// `None` for non-presets, an all-zero warp or an empty box.
+ pub fn new(style: WarpStyle, bend: f64, h_distort: f64, v_distort: f64, vertical: bool, bounds: [f64; 4]) -> Option<StyleWarp> {
+ if !style.is_preset() {
+ return None;
+ }
+ let [x0, y0, x1, y1] = bounds;
+ let (hw, hh) = ((x1 - x0) / 2.0, (y1 - y0) / 2.0);
+ if !(hw > 0.0 && hh > 0.0) {
+ return None;
+ }
+ let pct = |v: f64| if v.is_finite() { (v / 100.0).clamp(-1.0, 1.0) } else { 0.0 };
+ let (b, hd, vd) = (pct(bend), pct(h_distort), pct(v_distort));
+ if b == 0.0 && hd == 0.0 && vd == 0.0 {
+ return None;
+ }
+ Some(StyleWarp { style, b, hd, vd, vertical, c: ((x0 + x1) / 2.0, (y0 + y1) / 2.0), h: (hw, hh) })
+ }
+
+ /// Longest segment (px) worth sending through [`StyleWarp::apply`] unsplit.
+ pub fn max_segment(&self) -> f64 {
+ (self.h.0.min(self.h.1) / 16.0).max(0.5)
+ }
+
+ /// Maps a point.
+ pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {
+ // Normalised coordinates: u along the warp axis, v across it, both -1..1 over the box.
+ let (dx, dy) = (x - self.c.0, y - self.c.1);
+ let (u, v, hu, hv) = if self.vertical { (dy / self.h.1, dx / self.h.0, self.h.1, self.h.0) } else { (dx / self.h.0, dy / self.h.1, self.h.0, self.h.1) };
+ let (mut u2, mut v2) = self.bend(u, v, hu / hv);
+ // Distortions: a perspective-like taper along each axis.
+ if self.hd != 0.0 {
+ v2 *= (1.0 + self.hd * u2).max(0.05);
+ }
+ if self.vd != 0.0 {
+ u2 *= (1.0 + self.vd * v2).max(0.05);
+ }
+ let (ox, oy) = if self.vertical { (v2 * self.h.0, u2 * self.h.1) } else { (u2 * self.h.0, v2 * self.h.1) };
+ (self.c.0 + ox, self.c.1 + oy)
+ }
+
+ /// The style's mapping in normalised space; `aspect` = half-length along / across the axis.
+ fn bend(&self, u: f64, v: f64, aspect: f64) -> (f64, f64) {
+ use std::f64::consts::{FRAC_PI_2, PI};
+ let b = self.b;
+ let bell = (1.0 - u * u).max(0.0);
+ match self.style {
+ WarpStyle::Arc => arc(u, v, b, aspect),
+ WarpStyle::ArcLower => lerp2((u, v), arc(u, v, b, aspect), (v + 1.0) / 2.0),
+ WarpStyle::ArcUpper => lerp2((u, v), arc(u, v, b, aspect), (1.0 - v) / 2.0),
+ // Every column moves up (b > 0) by the same parabola; verticals stay vertical.
+ WarpStyle::Arch => (u, v - b * bell),
+ WarpStyle::Bulge => (u, v * (1.0 + b * bell)),
+ // The bottom (top) edge bows out while the opposite edge stays straight.
+ WarpStyle::ShellLower => (u, v + b * bell * (v + 1.0) / 2.0),
+ WarpStyle::ShellUpper => (u, v - b * bell * (1.0 - v) / 2.0),
+ WarpStyle::Flag => (u, v - b * 0.5 * (PI * u).sin()),
+ WarpStyle::Wave => (u, v - b * 0.5 * (PI * u + v * FRAC_PI_2).sin()),
+ // A body swelling towards the head (left) and a narrow tail, curving up.
+ WarpStyle::Fish => (u, v * (1.0 + b * 0.6 * (1.0 - u) * bell.sqrt()) - b * 0.35 * bell),
+ WarpStyle::Rise => (u, v - b * 0.5 * (FRAC_PI_2 * u).sin()),
+ WarpStyle::Fisheye => {
+ let r2 = (u * u + v * v).min(1.0);
+ let k = 1.0 + b * (1.0 - r2);
+ (u * k, v * k)
+ }
+ WarpStyle::Inflate => {
+ let (bu, bv) = ((1.0 - v * v).max(0.0), bell);
+ (u * (1.0 + b * 0.5 * bu), v * (1.0 + b * 0.5 * bv))
+ }
+ WarpStyle::Squeeze => (u * (1.0 + b * 0.5 * (1.0 - v * v).max(0.0)), v * (1.0 - b * 0.5 * bell)),
+ WarpStyle::Twist => {
+ let r = (u * u + v * v).sqrt();
+ if r >= 1.0 {
+ return (u, v);
+ }
+ // Rotate in an isotropic frame so the twist stays circular on wide boxes.
+ let a = b * FRAC_PI_2 * (1.0 - r) * (1.0 - r);
+ let (s, c) = a.sin_cos();
+ let (x, y) = (u * aspect, v);
+ ((x * c - y * s) / aspect, x * s + y * c)
+ }
+ WarpStyle::None | WarpStyle::Custom => (u, v),
+ }
+ }
+}
+
+/// Along a circular arc: the box centre line becomes an arc spanning `b × 180°`.
+fn arc(u: f64, v: f64, b: f64, aspect: f64) -> (f64, f64) {
+ if b.abs() < 1e-6 {
+ return (u, v);
+ }
+ // Work in units of the half-height so the circle is round; arc length of the centre line
+ // equals the box half-length at the ends.
+ let half = aspect;
+ let theta_max = b * std::f64::consts::FRAC_PI_2;
+ let r = half / theta_max;
+ let theta = u * theta_max;
+ let rr = r - v;
+ let x = rr * theta.sin();
+ let y = r - rr * theta.cos();
+ (x / half, y)
+}
+
+fn lerp2(a: (f64, f64), b: (f64, f64), t: f64) -> (f64, f64) {
+ let t = t.clamp(0.0, 1.0);
+ (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)
+}
+
+fn bernstein(t: f64) -> [f64; 4] {
+ let s = 1.0 - t;
+ [s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t]
+}
+
+fn lerp(a: [f64; 2], b: [f64; 2], t: f64) -> [f64; 2] {
+ [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
+}
+
+/// De Casteljau split of a cubic at `t`: 7 points (left 0..=3, right 3..=6).
+fn split_cubic(p: [[f64; 2]; 4], t: f64) -> [[f64; 2]; 7] {
+ let a = lerp(p[0], p[1], t);
+ let b = lerp(p[1], p[2], t);
+ let c = lerp(p[2], p[3], t);
+ let d = lerp(a, b, t);
+ let e = lerp(b, c, t);
+ let f = lerp(d, e, t);
+ [p[0], a, d, f, e, c, p[3]]
+}
+
+/// Inverse of the Bernstein interpolation matrix at t = 0, 1/3, 2/3, 1 (rows: control point,
+/// columns: sample). Exact rational values.
+const BERN_INV: [[f64; 4]; 4] = [
+ [1.0, 0.0, 0.0, 0.0],
+ [-5.0 / 6.0, 3.0, -1.5, 1.0 / 3.0],
+ [1.0 / 3.0, -1.5, 3.0, -5.0 / 6.0],
+ [0.0, 0.0, 0.0, 1.0],
+];
+
+/// A grid of bicubic Bezier patches over the unit square of a source box.
+///
+/// `us`/`vs` are the patch boundaries in the box's normalised coordinates (`0..=1`, increasing,
+/// first 0 and last 1). Control points are a `(3·(us.len()-1)+1) × (3·(vs.len()-1)+1)` grid in
+/// row-major order, in output (document) coordinates; neighbouring patches share their edge row.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct BezierMesh {
+ pub us: Vec<f64>,
+ pub vs: Vec<f64>,
+ pub points: Vec<[f64; 2]>,
+}
+
+impl BezierMesh {
+ /// The identity mesh over `bounds` with `cols × rows` patches (Photoshop's default is 1 × 1,
+ /// a 4 × 4 control grid).
+ pub fn identity(bounds: [f64; 4], cols: usize, rows: usize) -> BezierMesh {
+ let (cols, rows) = (cols.clamp(1, 64), rows.clamp(1, 64));
+ let us: Vec<f64> = (0..=cols).map(|i| i as f64 / cols as f64).collect();
+ let vs: Vec<f64> = (0..=rows).map(|i| i as f64 / rows as f64).collect();
+ Self::fit(&|s, t| [bounds[0] + s * (bounds[2] - bounds[0]), bounds[1] + t * (bounds[3] - bounds[1])], us, vs)
+ }
+
+ /// Fits a mesh with patch boundaries `us`/`vs` to the map `f` (normalised → output) by
+ /// interpolating it at the patch's thirds. Exact for bicubic maps (affine maps included).
+ pub fn fit(f: &dyn Fn(f64, f64) -> [f64; 2], us: Vec<f64>, vs: Vec<f64>) -> BezierMesh {
+ let (pc, pr) = (us.len() - 1, vs.len() - 1);
+ let (nx, ny) = (3 * pc + 1, 3 * pr + 1);
+ let mut points = vec![[0.0; 2]; nx * ny];
+ for pj in 0..pr {
+ for pi in 0..pc {
+ let mut s = [[[0.0; 2]; 4]; 4]; // s[row j][col i]
+ for (j, row) in s.iter_mut().enumerate() {
+ for (i, v) in row.iter_mut().enumerate() {
+ let u = us[pi] + (us[pi + 1] - us[pi]) * i as f64 / 3.0;
+ let t = vs[pj] + (vs[pj + 1] - vs[pj]) * j as f64 / 3.0;
+ *v = f(u, t);
+ }
+ }
+ for j in 0..4 {
+ for i in 0..4 {
+ let mut acc = [0.0; 2];
+ for (a, wa) in BERN_INV[j].iter().enumerate() {
+ for (b, wb) in BERN_INV[i].iter().enumerate() {
+ let k = wa * wb;
+ acc[0] += k * s[a][b][0];
+ acc[1] += k * s[a][b][1];
+ }
+ }
+ points[(3 * pj + j) * nx + 3 * pi + i] = acc;
+ }
+ }
+ }
+ }
+ BezierMesh { us, vs, points }
+ }
+
+ /// Control points per row.
+ pub fn nx(&self) -> usize {
+ 3 * (self.us.len() - 1) + 1
+ }
+ /// Control point rows.
+ pub fn ny(&self) -> usize {
+ 3 * (self.vs.len() - 1) + 1
+ }
+ pub fn point(&self, i: usize, j: usize) -> [f64; 2] {
+ self.points[j * self.nx() + i]
+ }
+
+ /// Checks the invariants (knots and point count); malformed data from files is rejected.
+ pub fn is_valid(&self) -> bool {
+ let knots_ok = |k: &[f64]| k.len() >= 2 && k[0] == 0.0 && k[k.len() - 1] == 1.0 && k.windows(2).all(|w| w[1] > w[0]);
+ knots_ok(&self.us) && knots_ok(&self.vs) && self.points.len() == self.nx() * self.ny() && self.points.iter().all(|p| p[0].is_finite() && p[1].is_finite())
+ }
+
+ fn locate(knots: &[f64], s: f64) -> (usize, f64) {
+ let n = knots.len() - 1;
+ let s = s.clamp(0.0, 1.0);
+ let mut i = 0;
+ while i + 1 < n && s > knots[i + 1] {
+ i += 1;
+ }
+ let w = knots[i + 1] - knots[i];
+ (i, if w > 0.0 { (s - knots[i]) / w } else { 0.0 })
+ }
+
+ /// Evaluates the surface at normalised `(s, t)`.
+ pub fn eval(&self, s: f64, t: f64) -> [f64; 2] {
+ let (pi, a) = Self::locate(&self.us, s);
+ let (pj, b) = Self::locate(&self.vs, t);
+ let (ba, bb) = (bernstein(a), bernstein(b));
+ let nx = self.nx();
+ let mut out = [0.0; 2];
+ for (j, wb) in bb.iter().enumerate() {
+ for (i, wa) in ba.iter().enumerate() {
+ let p = self.points[(3 * pj + j) * nx + 3 * pi + i];
+ let k = wa * wb;
+ out[0] += p[0] * k;
+ out[1] += p[1] * k;
+ }
+ }
+ out
+ }
+
+ /// Splits the patch column containing `s` at `s` (a vertical split line). Exact: the surface
+ /// is unchanged. Returns false when `s` is on or too close to an existing boundary.
+ pub fn split_u(&mut self, s: f64) -> bool {
+ let (pi, a) = Self::locate(&self.us, s);
+ if !(0.01..=0.99).contains(&a) {
+ return false;
+ }
+ let (nx, ny) = (self.nx(), self.ny());
+ let mut pts = Vec::with_capacity((nx + 3) * ny);
+ for j in 0..ny {
+ let row = &self.points[j * nx..(j + 1) * nx];
+ pts.extend_from_slice(&row[..3 * pi]);
+ let seg = [row[3 * pi], row[3 * pi + 1], row[3 * pi + 2], row[3 * pi + 3]];
+ pts.extend_from_slice(&split_cubic(seg, a));
+ pts.extend_from_slice(&row[3 * pi + 4..]);
+ }
+ self.points = pts;
+ self.us.insert(pi + 1, s.clamp(0.0, 1.0));
+ true
+ }
+
+ /// Splits the patch row containing `t` at `t` (a horizontal split line). Exact.
+ pub fn split_v(&mut self, t: f64) -> bool {
+ self.transpose();
+ let ok = self.split_u(t);
+ self.transpose();
+ ok
+ }
+
+ /// Removes interior vertical boundary `k` (1..us.len()-1), merging its two patch columns.
+ /// Exact when the patches came from an unedited split; otherwise the outer control points are
+ /// kept and the inner handles extrapolated.
+ pub fn remove_split_u(&mut self, k: usize) -> bool {
+ if k == 0 || k + 1 >= self.us.len() {
+ return false;
+ }
+ let a = (self.us[k] - self.us[k - 1]) / (self.us[k + 1] - self.us[k - 1]);
+ let (nx, ny) = (self.nx(), self.ny());
+ let mut pts = Vec::with_capacity((nx - 3) * ny);
+ let c0 = 3 * (k - 1);
+ for j in 0..ny {
+ let row = &self.points[j * nx..(j + 1) * nx];
+ let (p0, q1, r2, p3) = (row[c0], row[c0 + 1], row[c0 + 5], row[c0 + 6]);
+ // De Casteljau inverse: q1 = lerp(p0, p1, a), r2 = lerp(p2, p3, a).
+ let p1 = [(q1[0] - (1.0 - a) * p0[0]) / a, (q1[1] - (1.0 - a) * p0[1]) / a];
+ let p2 = [(r2[0] - a * p3[0]) / (1.0 - a), (r2[1] - a * p3[1]) / (1.0 - a)];
+ pts.extend_from_slice(&row[..c0]);
+ pts.extend_from_slice(&[p0, p1, p2, p3]);
+ pts.extend_from_slice(&row[c0 + 7..]);
+ }
+ self.points = pts;
+ self.us.remove(k);
+ true
+ }
+
+ /// Removes interior horizontal boundary `k`.
+ pub fn remove_split_v(&mut self, k: usize) -> bool {
+ self.transpose();
+ let ok = self.remove_split_u(k);
+ self.transpose();
+ ok
+ }
+
+ fn transpose(&mut self) {
+ let (nx, ny) = (self.nx(), self.ny());
+ let mut pts = vec![[0.0; 2]; nx * ny];
+ for j in 0..ny {
+ for i in 0..nx {
+ pts[i * ny + j] = self.points[j * nx + i];
+ }
+ }
+ self.points = pts;
+ std::mem::swap(&mut self.us, &mut self.vs);
+ }
+
+ /// Applies `f` to every control point (exact for affine maps).
+ pub fn map_points(&self, f: impl Fn([f64; 2]) -> [f64; 2]) -> BezierMesh {
+ BezierMesh { us: self.us.clone(), vs: self.vs.clone(), points: self.points.iter().map(|p| f(*p)).collect() }
+ }
+
+ /// Normalised `(s, t)` whose surface point is nearest `p` (coarse search, then Newton
+ /// steps on the patch). Used to place split lines where the user clicks.
+ pub fn param_at(&self, p: [f64; 2]) -> (f64, f64) {
+ let n = 48;
+ let mut best = (0.5, 0.5, f64::MAX);
+ for j in 0..=n {
+ for i in 0..=n {
+ let (s, t) = (i as f64 / n as f64, j as f64 / n as f64);
+ let q = self.eval(s, t);
+ let d = (q[0] - p[0]).powi(2) + (q[1] - p[1]).powi(2);
+ if d < best.2 {
+ best = (s, t, d);
+ }
+ }
+ }
+ let (mut s, mut t) = (best.0, best.1);
+ for _ in 0..12 {
+ let h = 1e-5;
+ let q = self.eval(s, t);
+ let (qs, qt) = (self.eval(s + h, t), self.eval(s, t + h));
+ let (a, b, c, d) = ((qs[0] - q[0]) / h, (qt[0] - q[0]) / h, (qs[1] - q[1]) / h, (qt[1] - q[1]) / h);
+ let det = a * d - b * c;
+ if det.abs() < 1e-12 {
+ break;
+ }
+ let (ex, ey) = (p[0] - q[0], p[1] - q[1]);
+ s = (s + (d * ex - b * ey) / det).clamp(0.0, 1.0);
+ t = (t + (a * ey - c * ex) / det).clamp(0.0, 1.0);
+ }
+ (s, t)
+ }
+
+ /// Bounding box of the control points (the surface lies inside it).
+ pub fn control_bounds(&self) -> [f64; 4] {
+ self.points.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])])
+ }
+}
+
+/// A complete warp: what Photoshop's `warp` descriptor stores, plus the custom mesh.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Warp {
+ pub style: WarpStyle,
+ /// Bend in percent (-100..100), presets only.
+ #[serde(default)]
+ pub bend: f64,
+ #[serde(default)]
+ pub h_distort: f64,
+ #[serde(default)]
+ pub v_distort: f64,
+ /// Warp along the vertical axis.
+ #[serde(default)]
+ pub vertical: bool,
+ /// The source box `[x0, y0, x1, y1]` the warp is defined over.
+ pub bounds: [f64; 4],
+ /// Control mesh for [`WarpStyle::Custom`] (output coordinates).
+ #[serde(default)]
+ pub mesh: Option<BezierMesh>,
+}
+
+impl Warp {
+ /// No warp over `bounds`.
+ pub fn none(bounds: [f64; 4]) -> Warp {
+ Warp { style: WarpStyle::None, bend: 0.0, h_distort: 0.0, v_distort: 0.0, vertical: false, bounds, mesh: None }
+ }
+
+ /// A preset style.
+ pub fn preset(style: WarpStyle, bend: f64, bounds: [f64; 4]) -> Warp {
+ Warp { style, bend, ..Warp::none(bounds) }
+ }
+
+ /// A custom warp from a mesh.
+ pub fn custom(mesh: BezierMesh, bounds: [f64; 4]) -> Warp {
+ Warp { style: WarpStyle::Custom, mesh: Some(mesh), ..Warp::none(bounds) }
+ }
+
+ fn style_warp(&self) -> Option<StyleWarp> {
+ StyleWarp::new(self.style, self.bend, self.h_distort, self.v_distort, self.vertical, self.bounds)
+ }
+
+ /// Whether the warp maps every point of its box onto itself (within `1e-9` px).
+ pub fn is_identity(&self) -> bool {
+ match self.style {
+ WarpStyle::None => true,
+ WarpStyle::Custom => match &self.mesh {
+ None => true,
+ Some(m) => {
+ let id = BezierMesh::fit(&|s, t| self.box_point(s, t), m.us.clone(), m.vs.clone());
+ m.points.iter().zip(&id.points).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9)
+ }
+ },
+ _ => self.style_warp().is_none(),
+ }
+ }
+
+ fn box_point(&self, s: f64, t: f64) -> [f64; 2] {
+ let b = self.bounds;
+ [b[0] + s * (b[2] - b[0]), b[1] + t * (b[3] - b[1])]
+ }
+
+ /// Maps a source point (inside the box) to output space.
+ pub fn map(&self, x: f64, y: f64) -> (f64, f64) {
+ match self.style {
+ WarpStyle::None => (x, y),
+ WarpStyle::Custom => match &self.mesh {
+ Some(m) => {
+ let b = self.bounds;
+ let (w, h) = (b[2] - b[0], b[3] - b[1]);
+ if w <= 0.0 || h <= 0.0 {
+ return (x, y);
+ }
+ let p = m.eval((x - b[0]) / w, (y - b[1]) / h);
+ (p[0], p[1])
+ }
+ None => (x, y),
+ },
+ _ => match self.style_warp() {
+ Some(sw) => sw.apply(x, y),
+ None => (x, y),
+ },
+ }
+ }
+
+ /// The warp as a control mesh (a preset is fitted with `cols × rows` patches; custom warps
+ /// return their own mesh).
+ pub fn to_mesh(&self, cols: usize, rows: usize) -> BezierMesh {
+ if let (WarpStyle::Custom, Some(m)) = (self.style, &self.mesh) {
+ return m.clone();
+ }
+ let (cols, rows) = (cols.clamp(1, 64), rows.clamp(1, 64));
+ let us: Vec<f64> = (0..=cols).map(|i| i as f64 / cols as f64).collect();
+ let vs: Vec<f64> = (0..=rows).map(|i| i as f64 / rows as f64).collect();
+ BezierMesh::fit(
+ &|s, t| {
+ let p = self.box_point(s, t);
+ let (x, y) = self.map(p[0], p[1]);
+ [x, y]
+ },
+ us,
+ vs,
+ )
+ }
+
+ /// The same warp followed by the affine map `[a, b, c, d, e, f]` (`x' = a·x + c·y + e`,
+ /// `y' = b·x + d·y + f`), as a custom mesh (exact for custom warps).
+ pub fn then_affine(&self, m: [f64; 6]) -> Warp {
+ let mesh = self.to_mesh(4, 4).map_points(|p| [m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]]);
+ Warp::custom(mesh, self.bounds)
+ }
+
+ /// Approximate output bounds (sampled; includes the control mesh for custom warps).
+ pub fn output_bounds(&self) -> [f64; 4] {
+ let n = 32;
+ let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];
+ for j in 0..=n {
+ for i in 0..=n {
+ let p = self.box_point(i as f64 / n as f64, j as f64 / n as f64);
+ let (x, y) = self.map(p[0], p[1]);
+ b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)];
+ }
+ }
+ b
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const B: [f64; 4] = [10.0, 20.0, 110.0, 70.0];
+
+ fn close(a: (f64, f64), b: (f64, f64), eps: f64) -> bool {
+ (a.0 - b.0).abs() < eps && (a.1 - b.1).abs() < eps
+ }
+
+ #[test]
+ fn styles_parse_and_round_trip_names() {
+ for s in WarpStyle::all() {
+ assert_eq!(WarpStyle::parse(s.id()), Some(s));
+ assert_eq!(WarpStyle::parse(s.psd_name()), Some(s));
+ assert_eq!(WarpStyle::parse(s.label()), Some(s), "{s:?}");
+ }
+ assert_eq!(WarpStyle::parse("spiral"), None);
+ }
+
+ #[test]
+ fn presets_at_bend_zero_are_identity() {
+ for s in WarpStyle::PRESETS {
+ let w = Warp::preset(s, 0.0, B);
+ assert!(w.is_identity());
+ assert_eq!(w.map(33.0, 44.0), (33.0, 44.0));
+ }
+ }
+
+ #[test]
+ fn identity_mesh_is_exact_and_fit_reproduces_affine() {
+ let m = BezierMesh::identity(B, 1, 1);
+ assert_eq!((m.nx(), m.ny()), (4, 4));
+ let w = Warp::custom(m, B);
+ assert!(w.is_identity());
+ assert!(close(w.map(37.5, 61.25), (37.5, 61.25), 1e-9));
+ // Affine maps fit exactly.
+ let f = |s: f64, t: f64| [3.0 + 2.0 * s - t, 1.0 + 0.5 * s + 4.0 * t];
+ let m = BezierMesh::fit(&f, vec![0.0, 1.0], vec![0.0, 0.4, 1.0]);
+ for (s, t) in [(0.1, 0.9), (0.5, 0.2), (0.77, 0.41)] {
+ let p = m.eval(s, t);
+ let e = f(s, t);
+ assert!((p[0] - e[0]).abs() < 1e-9 && (p[1] - e[1]).abs() < 1e-9);
+ }
+ }
+
+ #[test]
+ fn splits_are_exact_and_removable() {
+ let mut m = BezierMesh::identity(B, 1, 1);
+ // Bend it: move an inner control point.
+ m.points[5] = [50.0, 10.0];
+ let before: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect();
+ let orig = m.clone();
+ assert!(m.split_u(0.3));
+ assert!(m.split_v(0.6));
+ assert!(!m.split_u(0.3), "existing boundary");
+ assert_eq!((m.nx(), m.ny()), (7, 7));
+ assert!(m.is_valid());
+ let after: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect();
+ for (a, b) in before.iter().zip(&after) {
+ assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9);
+ }
+ let (ls, lt) = m.param_at(m.eval(0.42, 0.77));
+ assert!((ls - 0.42).abs() < 1e-6 && (lt - 0.77).abs() < 1e-6, "{ls},{lt}");
+ assert!(m.remove_split_u(1));
+ assert!(m.remove_split_v(1));
+ assert_eq!(m.us, orig.us);
+ for (a, b) in m.points.iter().zip(&orig.points) {
+ assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9);
+ }
+ }
+
+ #[test]
+ fn arc_maps_known_points() {
+ // Arc, bend 50 %: the centre column stays, the ends drop and pull in along a circle.
+ let w = Warp::preset(WarpStyle::Arc, 50.0, [0.0, -40.0, 200.0, 10.0]);
+ let mid = w.map(100.0, -15.0);
+ assert!(close(mid, (100.0, -15.0), 1e-9));
+ // Centre line: radius r = half / θmax with half = 100/25 = 4 (in half-heights), θmax = π/4.
+ let (theta, r) = (std::f64::consts::FRAC_PI_4, 4.0 / std::f64::consts::FRAC_PI_4);
+ let ex = 100.0 - r * theta.sin() * 100.0 / 4.0;
+ let ey = -15.0 + (r - r * theta.cos()) * 25.0;
+ let end = w.map(0.0, -15.0);
+ assert!(close(end, (ex, ey), 1e-6), "{end:?} vs {:?}", (ex, ey));
+ }
+
+ #[test]
+ fn preset_fits_closely_as_mesh_and_affine_composes() {
+ let w = Warp::preset(WarpStyle::Bulge, 40.0, B);
+ let m = Warp::custom(w.to_mesh(4, 4), B);
+ for (x, y) in [(20.0, 30.0), (60.0, 45.0), (100.0, 65.0)] {
+ assert!(close(w.map(x, y), m.map(x, y), 0.5), "{:?} vs {:?}", w.map(x, y), m.map(x, y));
+ }
+ let t = Warp::custom(BezierMesh::identity(B, 1, 1), B).then_affine([1.0, 0.0, 0.0, 1.0, 5.0, -2.0]);
+ assert!(close(t.map(50.0, 50.0), (55.0, 48.0), 1e-9));
+ let ob = Warp::none(B).output_bounds();
+ assert!((ob[0] - 10.0).abs() < 1e-9 && (ob[3] - 70.0).abs() < 1e-9);
+ }
+}
diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl
index 42a58ce6c..43a9c6376 100644
--- a/crates/gpu/src/compose.wgsl
+++ b/crates/gpu/src/compose.wgsl
@@ -278,6 +278,86 @@ fn posterize(v: f32, n: f32) -> f32 {
return floor(bin * 255.0 / (n - 1.0)) / 255.0;
}
+// Document pixel being adjusted (for ordered dither).
+var<private> adj_px: vec2<i32>;
+
+fn lut_at(i: i32) -> f32 {
+ return textureLoad(lut_tex, vec2(i % 4096, i / 4096), 0).r;
+}
+
+fn lut3(n: i32, r: i32, g: i32, b: i32) -> vec3<f32> {
+ let i = ((b * n + g) * n + r) * 3;
+ return vec3(lut_at(i), lut_at(i + 1), lut_at(i + 2));
+}
+
+fn bayer4(p: vec2<i32>) -> f32 {
+ var m = array<f32, 16>(0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0);
+ return (m[(p.y & 3) * 4 + (p.x & 3)] + 0.5) / 16.0 - 0.5;
+}
+
+// compose::adjust::lut3d_sample
+fn color_lookup(c: vec3<f32>, n: i32, tetra: bool) -> vec3<f32> {
+ let m = f32(n - 1);
+ let pos = clamp(c, vec3(0.0), vec3(1.0)) * m;
+ let i0 = min(vec3<i32>(floor(pos)), vec3(n - 2));
+ let f = pos - vec3<f32>(i0);
+ let r = i0.x;
+ let g = i0.y;
+ let b = i0.z;
+ if (tetra) {
+ let c000 = lut3(n, r, g, b);
+ let c111 = lut3(n, r + 1, g + 1, b + 1);
+ if (f.x > f.y) {
+ if (f.y > f.z) {
+ return (1.0 - f.x) * c000 + (f.x - f.y) * lut3(n, r + 1, g, b) + (f.y - f.z) * lut3(n, r + 1, g + 1, b) + f.z * c111;
+ } else if (f.x > f.z) {
+ return (1.0 - f.x) * c000 + (f.x - f.z) * lut3(n, r + 1, g, b) + (f.z - f.y) * lut3(n, r + 1, g, b + 1) + f.y * c111;
+ }
+ return (1.0 - f.z) * c000 + (f.z - f.x) * lut3(n, r, g, b + 1) + (f.x - f.y) * lut3(n, r + 1, g, b + 1) + f.y * c111;
+ }
+ if (f.z > f.y) {
+ return (1.0 - f.z) * c000 + (f.z - f.y) * lut3(n, r, g, b + 1) + (f.y - f.x) * lut3(n, r, g + 1, b + 1) + f.x * c111;
+ } else if (f.z > f.x) {
+ return (1.0 - f.y) * c000 + (f.y - f.z) * lut3(n, r, g + 1, b) + (f.z - f.x) * lut3(n, r, g + 1, b + 1) + f.x * c111;
+ }
+ return (1.0 - f.y) * c000 + (f.y - f.x) * lut3(n, r, g + 1, b) + (f.x - f.z) * lut3(n, r + 1, g + 1, b) + f.z * c111;
+ }
+ let c00 = mix(lut3(n, r, g, b), lut3(n, r + 1, g, b), f.x);
+ let c10 = mix(lut3(n, r, g + 1, b), lut3(n, r + 1, g + 1, b), f.x);
+ let c01 = mix(lut3(n, r, g, b + 1), lut3(n, r + 1, g, b + 1), f.x);
+ let c11 = mix(lut3(n, r, g + 1, b + 1), lut3(n, r + 1, g + 1, b + 1), f.x);
+ return mix(mix(c00, c10, f.y), mix(c01, c11, f.y), f.z);
+}
+
+// compose::adjust::selective_color (ranges × CMYK percentages in LUT row 0)
+fn selective_color(c: vec3<f32>, relative: bool) -> vec3<f32> {
+ let mx = max(max(c.r, c.g), c.b);
+ let mn = min(min(c.r, c.g), c.b);
+ let md = c.r + c.g + c.b - mx - mn;
+ var w: array<f32, 9>;
+ w[0] = select(0.0, mx - md, c.r >= mx);
+ w[1] = select(0.0, md - mn, c.b <= mn);
+ w[2] = select(0.0, mx - md, c.g >= mx);
+ w[3] = select(0.0, md - mn, c.r <= mn);
+ w[4] = select(0.0, mx - md, c.b >= mx);
+ w[5] = select(0.0, md - mn, c.g <= mn);
+ w[6] = max((mn - 0.5) * 2.0, 0.0);
+ w[7] = clamp(1.0 - abs(mx - 0.5) - abs(mn - 0.5), 0.0, 1.0);
+ w[8] = max((0.5 - mx) * 2.0, 0.0);
+ var delta = vec3(0.0);
+ for (var r = 0; r < 9; r++) {
+ if (w[r] <= 0.0) { continue; }
+ let k = lut_at(r * 4 + 3) / 100.0;
+ for (var i = 0; i < 3; i++) {
+ let a = lut_at(r * 4 + i) / 100.0;
+ var d = a + k;
+ if (relative) { d = d * (1.0 - c[i]); }
+ delta[i] += d * w[r];
+ }
+ }
+ return clamp(c - delta, vec3(0.0), vec3(1.0));
+}
+
fn adjust(c: vec3<f32>) -> vec3<f32> {
let p0 = op.p0;
let p1 = op.p1;
@@ -371,6 +451,12 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {
}
return o;
}
+ case 15: { return selective_color(c, p0.x > 0.5); } // Selective color
+ case 16: { // Color lookup (3D LUT)
+ var o = color_lookup(c, i32(p0.x), p0.y > 0.5);
+ if (p0.z > 0.5) { o = clamp(o + bayer4(adj_px) / 255.0, vec3(0.0), vec3(1.0)); }
+ return o;
+ }
default: { return c; }
}
}
@@ -466,8 +552,10 @@ fn fs_atop(in: VOut) -> @location(0) vec4<f32> {
// 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);
+ let p = local(in.pos);
+ let c = textureLoad(tex_a, p, 0);
if (c.a <= 0.0) { return c; }
+ adj_px = doc_px(p);
return vec4(adjust(c.rgb), c.a);
}
diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs
index eab8f0bcd..572afd264 100644
--- a/crates/gpu/src/plan.rs
+++ b/crates/gpu/src/plan.rs
@@ -179,12 +179,20 @@ impl<'a> Planner<'a> {
}
fn check(&self, layer: &Layer) -> Result<(), Unsupported> {
+ if layer.artboard().is_some() {
+ return Err(Unsupported(format!("artboard `{}` (clipped and rendered on the CPU)", layer.name)));
+ }
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)));
}
+ if let LayerContent::Fill(f @ Fill::Pattern { .. }) = &layer.content
+ && layer.fill_cache.as_ref().is_none_or(|c| c.fill != *f)
+ {
+ return Err(Unsupported(format!("pattern fill `{}` (rendered on the CPU)", layer.name)));
+ }
Ok(())
}
@@ -325,7 +333,7 @@ impl<'a> Planner<'a> {
}
p.lut = Some(rows);
}
- // Patterns render once the pattern library lands; transparent until then (as on CPU).
+ // Pattern fills fall back to the CPU compositor (see `check`).
Fill::Pattern { .. } => {}
}
}
@@ -496,8 +504,32 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer) -> Program {
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),
+ Adjustment::SelectiveColor { relative, adjustments } => {
+ // 9 ranges × CMYK don't fit the 16 params: they go in LUT row 0 (read texel-exact).
+ p[0][0] = if *relative { 1.0 } else { 0.0 };
+ let mut row = [0.0f32; 4096];
+ for (i, v) in adjustments.iter().flatten().enumerate() {
+ row[i] = *v;
+ }
+ (15, p, Some(vec![row]))
+ }
+ Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if *size >= 2 && table.len() >= (*size as usize).pow(3) * 3 => {
+ // The flattened table (n³ RGB triplets) spans as many 4096-wide rows as it needs.
+ let n = *size as usize;
+ let len = n * n * n * 3;
+ let rows = table[..len]
+ .chunks(4096)
+ .map(|c| {
+ let mut row = [0.0f32; 4096];
+ row[..c.len()].copy_from_slice(c);
+ row
+ })
+ .collect();
+ p[0] = [n as f32, if *tetrahedral { 1.0 } else { 0.0 }, if *dither { 1.0 } else { 0.0 }, 0.0];
+ (16, p, Some(rows))
+ }
+ // Identity on the CPU too (not evaluated there).
+ Adjustment::ColorLookup { .. } | Adjustment::Unsupported { .. } => (0, p, None),
}
}
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 7cd8a9869..587262e26 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -130,9 +130,32 @@ fn adjustments() -> Vec<Adjustment> {
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 },
+ Adjustment::SelectiveColor { relative: true, adjustments: selective() },
+ Adjustment::SelectiveColor { relative: false, adjustments: selective() },
+ lookup(17, false, false),
+ lookup(5, true, false),
+ lookup(33, false, true),
]
}
+fn selective() -> [[f32; 4]; 9] {
+ std::array::from_fn(|r| std::array::from_fn(|k| ((r * 4 + k) as f32 * 37.0) % 200.0 - 100.0))
+}
+
+/// A warped (non-identity) 3D LUT so interpolation differences show.
+fn lookup(n: usize, tetrahedral: bool, dither: bool) -> Adjustment {
+ let mut t = Vec::with_capacity(n * n * n * 3);
+ for b in 0..n {
+ for g in 0..n {
+ for r in 0..n {
+ let (r, g, b) = (r as f32 / (n - 1) as f32, g as f32 / (n - 1) as f32, b as f32 / (n - 1) as f32);
+ t.extend([(r * r * 0.8 + b * 0.2).min(1.0), g.sqrt(), (1.0 - r) * 0.3 + b * 0.7]);
+ }
+ }
+ }
+ Adjustment::ColorLookup { name: "test".into(), lut: Some(std::sync::Arc::new(t)), size: n as u32, tetrahedral, dither }
+}
+
#[test]
fn adjustment_layers() {
let Some(mut g) = gpu() else { return };
diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml
index 970026270..6b9c10406 100644
--- a/crates/io/Cargo.toml
+++ b/crates/io/Cargo.toml
@@ -12,6 +12,7 @@ workspace = true
[dependencies]
photocraft-geom = { workspace = true }
photocraft-color = { workspace = true }
+photocraft-cms = { workspace = true }
photocraft-raster = { workspace = true }
photocraft-doc = { workspace = true }
photocraft-compose = { workspace = true }
diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs
index 2abea770c..bdccd8ad4 100644
--- a/crates/io/examples/oracle_diff.rs
+++ b/crates/io/examples/oracle_diff.rs
@@ -83,11 +83,22 @@ fn main() {
println!("{}{key}:", " ".repeat(depth));
walk(sub, depth + 1);
}
+ photocraft_psd::descriptor::Value::Text(t) => println!("{}{key} = {:?}", " ".repeat(depth), t.to_string_lossy()),
+ photocraft_psd::descriptor::Value::List(items) if items.iter().all(|i| matches!(i, photocraft_psd::descriptor::Value::Descriptor(_))) => {
+ println!("{}{key} = [{} items]", " ".repeat(depth), items.len());
+ for (i, it) in items.iter().enumerate() {
+ if let photocraft_psd::descriptor::Value::Descriptor(sub) = it {
+ println!("{}[{i}]:", " ".repeat(depth + 1));
+ walk(sub, depth + 2);
+ }
+ }
+ }
_ => println!("{}{key} = {}", " ".repeat(depth), format!("{v:?}").chars().take(600).collect::<String>()),
}
}
}
for rec in file.layers() {
+ println!("-- layer {:?}", String::from_utf8_lossy(&rec.name));
if let Some(b) = rec.block(b"lfx2").or(rec.block(b"lmfx"))
&& let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&b.data[4..])
{
@@ -122,6 +133,23 @@ fn main() {
println!("wrote {out}");
return;
}
+ if std::env::args().nth(3).as_deref() == Some("worst") {
+ // The N worst pixels (premultiplied max channel error), with coordinates.
+ let w = doc.size.width as usize;
+ let n: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(20);
+ let mut v: Vec<(f32, usize)> = ours
+ .iter()
+ .zip(&merged)
+ .enumerate()
+ .map(|(i, (a, b))| ((0..4).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max), i))
+ .collect();
+ v.sort_by(|a, b| b.0.total_cmp(&a.0));
+ for (d, i) in v.into_iter().take(n) {
+ let (a, b) = (ours[i], merged[i]);
+ println!("({:4},{:4}) d={:5.1} ours {:?} ps {:?}", i % w, i / w, d * 255.0, a.map(|v| (v * 255.0).round()), b.map(|v| (v * 255.0).round()));
+ }
+ return;
+ }
if std::env::args().nth(3).as_deref() == Some("row") {
let w = doc.size.width as usize;
let y: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0);
diff --git a/crates/io/examples/pattern_fit.rs b/crates/io/examples/pattern_fit.rs
new file mode 100644
index 000000000..d0ded162c
--- /dev/null
+++ b/crates/io/examples/pattern_fit.rs
@@ -0,0 +1,41 @@
+//! TEMPORARY: fit the pattern tiling origin against Photoshop's merged image.
+//! args: file.psd x0 y0 x1 y1 (region with opaque pattern pixels)
+fn main() {
+ let a: Vec<String> = std::env::args().collect();
+ let bytes = std::fs::read(&a[1]).unwrap();
+ let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap();
+ let imp = photocraft_io::import(&a[1], &bytes).unwrap();
+ let doc = &imp.document;
+ let merged = photocraft_io::merged_composite(&file).unwrap();
+ let w = doc.size.width as usize;
+ for rec in file.layers() {
+ println!("rec {:?} rect t{} l{} b{} r{}", String::from_utf8_lossy(&rec.name), rec.rect.top, rec.rect.left, rec.rect.bottom, rec.rect.right);
+ }
+ let p = &doc.patterns[0];
+ let tile = photocraft_compose::pattern::Tile::new(p).unwrap();
+ let (pw, ph) = (p.width as i64, p.height as i64);
+ let r: Vec<i64> = a[2..6].iter().map(|s| s.parse().unwrap()).collect();
+ let mut best = Vec::new();
+ for oy in 0..ph {
+ for ox in 0..pw {
+ let mut err = 0.0f64;
+ let mut n = 0;
+ for y in (r[1]..r[3]).step_by(1) {
+ for x in (r[0]..r[2]).step_by(1) {
+ let m = merged[y as usize * w + x as usize];
+ if m[3] < 0.999 {
+ continue;
+ }
+ let t = tile.sample((x - ox) as f64 + 0.5, (y - oy) as f64 + 0.5);
+ err += (0..3).map(|c| (t[c] - m[c]).abs() as f64).sum::<f64>();
+ n += 1;
+ }
+ }
+ best.push((err / n.max(1) as f64, ox, oy));
+ }
+ }
+ best.sort_by(|a, b| a.0.total_cmp(&b.0));
+ for b in best.iter().take(5) {
+ println!("origin ({},{}) mean err {:.4}", b.1, b.2, b.0 * 255.0 / 3.0);
+ }
+}
diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs
index 5c71beace..017c14d91 100644
--- a/crates/io/src/adjust_map.rs
+++ b/crates/io/src/adjust_map.rs
@@ -166,11 +166,72 @@ fn parse_any(key: &[u8; 4], data: &[u8], cged: Option<&[u8]>) -> Adjustment {
Some(Adjustment::Levels { master: m, per_channel: [r, g, b] })
})(),
b"curv" => parse_curves(data),
+ b"selc" => parse_selective(data),
+ b"clrL" => parse_lookup(data),
_ => None,
};
parsed.unwrap_or_else(|| unsupported(key, data))
}
+/// `selc`: version, method (0 relative / 1 absolute), then 10 CMYK records of i16 percentages;
+/// record 0 is reserved, records 1..=9 are reds … blacks.
+fn parse_selective(d: &[u8]) -> Option<Adjustment> {
+ if be16(d, 0)? != 1 || d.len() < 84 {
+ return None;
+ }
+ let relative = be16(d, 2)? == 0;
+ let mut adjustments = [[0.0f32; 4]; 9];
+ for (r, rec) in adjustments.iter_mut().enumerate() {
+ for (k, v) in rec.iter_mut().enumerate() {
+ *v = f32::from(bei16(d, 4 + (r + 1) * 8 + k * 2)?);
+ }
+ }
+ Some(Adjustment::SelectiveColor { relative, adjustments })
+}
+
+fn desc_text(d: &Descriptor, key: &str) -> Option<String> {
+ match d.get(key)? {
+ Value::Text(t) => Some(t.to_string_lossy()),
+ _ => None,
+ }
+}
+
+fn desc_enum<'a>(d: &'a Descriptor, key: &str) -> Option<&'a [u8]> {
+ match d.get(key)? {
+ Value::Enumerated { value, .. } => Some(value.as_bytes()),
+ _ => None,
+ }
+}
+
+/// `clrL`: version 1 + a versioned descriptor carrying the LUT file itself (`LUT3DFileData`, in
+/// the format named by `LUTFormat`). Profile-based lookups (abstract / device link) have no
+/// table and stay [`Adjustment::Unsupported`].
+fn parse_lookup(d: &[u8]) -> Option<Adjustment> {
+ if be16(d, 0)? != 1 {
+ return None;
+ }
+ let (v, _) = VersionedDescriptor::parse_prefix(d.get(2..)?).ok()?;
+ let desc = v.descriptor;
+ let bytes = match desc.get("LUT3DFileData")? {
+ Value::RawData(b) if !b.is_empty() => b,
+ _ => return None,
+ };
+ let ext = match desc_enum(&desc, "LUTFormat") {
+ Some(b"LUTFormat3DL") => "x.3dl",
+ Some(b"LUTFormatLOOK") => "x.look",
+ _ => "x.cube",
+ };
+ let lut = photocraft_cms::lutfile::parse(ext, bytes).ok()?;
+ let name = desc_text(&desc, "LUT3DFileName").or_else(|| desc_text(&desc, "NM ")).unwrap_or_default();
+ Some(Adjustment::ColorLookup {
+ name,
+ size: lut.size as u32,
+ lut: Some(std::sync::Arc::new(lut.data)),
+ tetrahedral: false,
+ dither: desc_bool(&desc, "Dthr").unwrap_or(false),
+ })
+}
+
fn put16(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
@@ -278,6 +339,35 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec<u8>)> {
}
return vec![(*b"curv", v)];
}
+ Adjustment::SelectiveColor { relative, adjustments } => {
+ put16(&mut v, 1);
+ put16(&mut v, u16::from(!*relative));
+ v.extend_from_slice(&[0; 8]);
+ for rec in adjustments {
+ for x in rec {
+ v.extend_from_slice(&clamp_i16(x.clamp(-100.0, 100.0)).to_be_bytes());
+ }
+ }
+ return vec![(*b"selc", v)];
+ }
+ Adjustment::ColorLookup { name, lut: Some(table), size, dither, .. } => {
+ let file = photocraft_cms::lutfile::LutFile { title: String::new(), size: *size as usize, data: table.to_vec() };
+ let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) };
+ let text = |t: &str| Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul(t));
+ let d = Descriptor::new("null")
+ .with("lookupType", en("colorLookupType", "3DLUT"))
+ .with("NM ", text(name))
+ .with("Dthr", Value::Boolean(*dither))
+ .with("profile", Value::RawData(Vec::new()))
+ .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE"))
+ .with("dataOrder", en("colorLookupOrder", "rgbOrder"))
+ .with("tableOrder", en("colorLookupOrder", "bgrOrder"))
+ .with("LUT3DFileData", Value::RawData(photocraft_cms::lutfile::write_cube(&file).into_bytes()))
+ .with("LUT3DFileName", text(name));
+ put16(&mut v, 1);
+ v.extend_from_slice(&VersionedDescriptor::new(d).to_bytes());
+ return vec![(*b"clrL", v)];
+ }
Adjustment::Unsupported { psd_key, raw } => {
let k = psd_key.as_bytes();
if k.len() == 4 {
@@ -327,6 +417,58 @@ mod tests {
per_channel: [pts(&[(0, 10), (255, 255)]), pts(&[(0, 0), (255, 245)]), pts(&[(0, 0), (64, 32), (255, 255)])],
});
rt(Adjustment::Unsupported { psd_key: "selc".into(), raw: vec![1, 2, 3] });
+ rt(Adjustment::SelectiveColor { relative: true, adjustments: std::array::from_fn(|r| [r as f32 * 10.0 - 40.0, 5.0, -100.0, 100.0]) });
+ rt(Adjustment::SelectiveColor { relative: false, adjustments: [[0.0; 4]; 9] });
+ let id = photocraft_cms::lutfile::LutFile::identity(5);
+ rt(Adjustment::ColorLookup { name: "Look.cube".into(), lut: Some(std::sync::Arc::new(id.data)), size: 5, tetrahedral: false, dither: true });
+ }
+
+ #[test]
+ fn selective_color_synthetic_block() {
+ // Absolute; reds = (+10, -20, +30, -40), blacks = (0, 0, 0, 25).
+ let mut d = vec![0, 1, 0, 1];
+ d.extend([0u8; 8]);
+ for r in 0..9 {
+ let rec: [i16; 4] = match r {
+ 0 => [10, -20, 30, -40],
+ 8 => [0, 0, 0, 25],
+ _ => [0; 4],
+ };
+ for x in rec {
+ d.extend(x.to_be_bytes());
+ }
+ }
+ let a = parse(b"selc", &d, None, Channels::Rgb);
+ let Adjustment::SelectiveColor { relative, adjustments } = &a else { panic!("{a:?}") };
+ assert!(!relative);
+ assert_eq!(adjustments[0], [10.0, -20.0, 30.0, -40.0]);
+ assert_eq!(adjustments[8], [0.0, 0.0, 0.0, 25.0]);
+ // Written back byte-exact.
+ assert_eq!(write(&a)[0].1, d);
+ }
+
+ #[test]
+ fn color_lookup_synthetic_block() {
+ let cube = b"TITLE \"t\"\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n";
+ let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) };
+ let desc = Descriptor::new("null")
+ .with("lookupType", en("colorLookupType", "3DLUT"))
+ .with("NM ", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("Id")))
+ .with("Dthr", Value::Boolean(true))
+ .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE"))
+ .with("LUT3DFileData", Value::RawData(cube.to_vec()));
+ let mut d = vec![0, 1];
+ d.extend(VersionedDescriptor::new(desc).to_bytes());
+ let a = parse(b"clrL", &d, None, Channels::Rgb);
+ let Adjustment::ColorLookup { name, lut: Some(t), size: 2, dither: true, .. } = &a else { panic!("{a:?}") };
+ assert_eq!(name, "Id");
+ assert_eq!(&t[..6], &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
+ // A profile-based lookup (no table) is preserved raw.
+ let mut p = vec![0, 1];
+ p.extend(VersionedDescriptor::new(Descriptor::new("null").with("lookupType", en("colorLookupType", "abstractProfile"))).to_bytes());
+ assert!(matches!(parse(b"clrL", &p, None, Channels::Rgb), Adjustment::Unsupported { .. }));
+ assert!(matches!(parse(b"clrL", &[0, 1, 9], None, Channels::Rgb), Adjustment::Unsupported { .. }));
+ assert!(matches!(parse(b"selc", &[0, 1, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. }));
}
#[test]
diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs
index 9df79dfdb..9eae02e87 100644
--- a/crates/io/src/blocks.rs
+++ b/crates/io/src/blocks.rs
@@ -239,14 +239,10 @@ pub fn fill_from_desc(key: &[u8; 4], d: &Descriptor) -> Option<Fill> {
Some(Fill::Gradient { stops, angle, scale, style: gradient_style(d), reverse: bool_of(d, "Rvrs") })
}
b"PtFl" => {
- let name = get_desc(d, "Ptrn")
- .and_then(|p| match p.get("Nm ") {
- Some(Value::Text(t)) => Some(t.to_string_lossy()),
- _ => None,
- })
- .unwrap_or_default();
+ let (name, id) = pattern_ref(d);
let scale = num(d.get("Scl ")).map_or(1.0, |v| v as f32 / 100.0);
- Some(Fill::Pattern { name, scale })
+ let (angle, link, phase) = pattern_placement(d);
+ Some(Fill::Pattern { name, scale, id, angle, link, phase })
}
_ => None,
}
@@ -273,18 +269,85 @@ pub fn fill_to_desc(f: &Fill) -> ([u8; 4], Descriptor) {
}
(*b"GdFl", d)
}
- Fill::Pattern { name, scale } => {
- let p = Descriptor::new("Ptrn").with("Nm ", Value::Text(UnicodeString::new_nul(name)));
- (
- *b"PtFl",
- Descriptor::new("null")
- .with("Scl ", Value::UnitFloat { unit: *b"#Prc", value: f64::from(scale * 100.0) })
- .with("Ptrn", Value::Descriptor(p)),
- )
+ Fill::Pattern { name, scale, id, angle, link, phase } => {
+ let d = Descriptor::new("null")
+ .with("Scl ", Value::UnitFloat { unit: *b"#Prc", value: f64::from(scale * 100.0) })
+ .with("Ptrn", Value::Descriptor(pattern_ref_desc(name, id)));
+ (*b"PtFl", with_pattern_placement(d, *angle, *link, *phase))
}
}
}
+/// Pattern name and id (`Ptrn` → `Nm `, `Idnt`) of a pattern fill / overlay descriptor.
+pub(crate) fn pattern_ref(d: &Descriptor) -> (String, String) {
+ let p = get_desc(d, "Ptrn");
+ let text = |k: &str| match p.and_then(|p| p.get(k)) {
+ Some(Value::Text(t)) => t.to_string_lossy(),
+ _ => String::new(),
+ };
+ (text("Nm "), text("Idnt"))
+}
+
+/// The `Ptrn` reference descriptor (the id is omitted when unknown).
+pub(crate) fn pattern_ref_desc(name: &str, id: &str) -> Descriptor {
+ let p = Descriptor::new("Ptrn").with("Nm ", Value::Text(UnicodeString::new_nul(name)));
+ if id.is_empty() { p } else { p.with("Idnt", Value::Text(UnicodeString::new_nul(id))) }
+}
+
+/// Angle (`Angl`, degrees), link with layer (`Algn`, default on) and phase (`phase` point) of a
+/// pattern fill / overlay descriptor.
+pub(crate) fn pattern_placement(d: &Descriptor) -> (f32, bool, (f32, f32)) {
+ let angle = num(d.get("Angl")).unwrap_or(0.0) as f32;
+ let link = !matches!(d.get("Algn"), Some(Value::Boolean(false)));
+ let phase = get_desc(d, "phase").map_or((0.0, 0.0), |p| (num(p.get("Hrzn")).unwrap_or(0.0) as f32, num(p.get("Vrtc")).unwrap_or(0.0) as f32));
+ (angle, link, phase)
+}
+
+/// Adds the keys read by [`pattern_placement`] (angle only when non-zero).
+pub(crate) fn with_pattern_placement(mut d: Descriptor, angle: f32, link: bool, phase: (f32, f32)) -> Descriptor {
+ if angle != 0.0 {
+ d = d.with("Angl", Value::UnitFloat { unit: *b"#Ang", value: f64::from(angle) });
+ }
+ d.with("Algn", Value::Boolean(link))
+ .with("phase", Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(f64::from(phase.0))).with("Vrtc", Value::Double(f64::from(phase.1)))))
+}
+
+/// The warp of a placed layer (`SoLd`/`SoLE` `warp` descriptor): style, bend, distortions,
+/// axis, bounds and, for `warpCustom`, the 4 × 4 `customEnvelopeWarp` mesh. Read-only: the raw
+/// block is what gets written back. `None` when absent or `warpNone` with no mesh.
+pub fn parse_placed_warp(key: &[u8; 4], data: &[u8]) -> Option<photocraft_geom::warp::Warp> {
+ use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};
+ if key != b"SoLd" && key != b"SoLE" {
+ return None;
+ }
+ let d = data.get(8..).and_then(parse_prefix_versioned)?;
+ let w = get_desc(&d, "warp")?;
+ let style = enum_of(w, "warpStyle").and_then(|v| WarpStyle::parse(&String::from_utf8_lossy(v)))?;
+ let b = get_desc(w, "bounds")?;
+ let g = |k: &str| num(b.get(k));
+ let bounds = [g("Left")?, g("Top ")?, g("Rght")?, g("Btom")?];
+ let mut warp = Warp::preset(style, num(w.get("warpValue")).unwrap_or(0.0), bounds);
+ warp.h_distort = num(w.get("warpPerspective")).unwrap_or(0.0);
+ warp.v_distort = num(w.get("warpPerspectiveOther")).unwrap_or(0.0);
+ warp.vertical = enum_of(w, "warpRotate") == Some(b"Vrtc");
+ if style == WarpStyle::Custom {
+ let env = get_desc(w, "customEnvelopeWarp")?;
+ let Some(Value::ObjectArray(arr)) = env.get("meshPoints") else { return None };
+ let vals = |k: &str| match arr.body.get(k) {
+ Some(Value::UnitFloats { values, .. }) => Some(values.clone()),
+ _ => None,
+ };
+ let (xs, ys) = (vals("Hrzn")?, vals("Vrtc")?);
+ if xs.len() != 16 || ys.len() != 16 {
+ return None;
+ }
+ let mesh = BezierMesh { us: vec![0.0, 1.0], vs: vec![0.0, 1.0], points: xs.iter().zip(&ys).map(|(x, y)| [*x, *y]).collect() };
+ warp.mesh = mesh.is_valid().then_some(mesh);
+ warp.mesh.as_ref()?;
+ }
+ (!warp.is_identity()).then_some(warp)
+}
+
/// Text content and transform from a `TySh` block (best effort).
pub fn parse_tysh(data: &[u8]) -> Option<(String, Affine)> {
let f = |at: usize| data.get(at..at + 8).map(|b| f64::from_be_bytes(b.try_into().unwrap_or([0; 8])));
@@ -345,6 +408,51 @@ pub fn effects_enabled(lfx2: &[u8]) -> bool {
mod tests {
use super::*;
+ #[test]
+ fn placed_layer_warp_is_read() {
+ use photocraft_geom::warp::WarpStyle;
+ use photocraft_psd::descriptor::ObjectArray;
+ let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) };
+ let bounds = Descriptor::new("Rctn")
+ .with("Top ", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 })
+ .with("Left", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 })
+ .with("Btom", Value::UnitFloat { unit: *b"#Pxl", value: 30.0 })
+ .with("Rght", Value::UnitFloat { unit: *b"#Pxl", value: 60.0 });
+ let sold = |warp: Descriptor| {
+ let mut v = b"soLD".to_vec();
+ v.extend_from_slice(&4u32.to_be_bytes());
+ v.extend(VersionedDescriptor::new(Descriptor::new("null").with("warp", Value::Descriptor(warp))).to_bytes());
+ v
+ };
+ let arc = Descriptor::new("warp")
+ .with("warpStyle", e("warpStyle", "warpArc"))
+ .with("warpValue", Value::Double(40.0))
+ .with("warpPerspective", Value::Double(0.0))
+ .with("warpPerspectiveOther", Value::Double(0.0))
+ .with("warpRotate", e("Ornt", "Hrzn"))
+ .with("bounds", Value::Descriptor(bounds.clone()));
+ let w = parse_placed_warp(b"SoLd", &sold(arc)).unwrap();
+ assert_eq!((w.style, w.bend, w.bounds), (WarpStyle::Arc, 40.0, [0.0, 0.0, 60.0, 30.0]));
+ let (mut xs, mut ys) = (Vec::new(), Vec::new());
+ for j in 0..4 {
+ for i in 0..4 {
+ xs.push(f64::from(i) * 20.0 + if i == 3 && j == 3 { 7.0 } else { 0.0 });
+ ys.push(f64::from(j) * 10.0);
+ }
+ }
+ let mesh = Descriptor::new("null")
+ .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: xs })
+ .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: ys });
+ let custom = Descriptor::new("warp")
+ .with("warpStyle", e("warpStyle", "warpCustom"))
+ .with("bounds", Value::Descriptor(bounds))
+ .with("customEnvelopeWarp", Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh }))));
+ let w = parse_placed_warp(b"SoLd", &sold(custom)).unwrap();
+ assert_eq!(w.style, WarpStyle::Custom);
+ assert_eq!(w.mesh.as_ref().unwrap().points[15], [67.0, 30.0]);
+ assert!(parse_placed_warp(b"PlLd", &[0; 20]).is_none());
+ }
+
#[test]
fn locks_and_labels() {
for bits in [0u32, 1, 2, 4, 0x10, 0x8000_0000, 0x8000_0017] {
@@ -362,7 +470,7 @@ mod tests {
Fill::Solid(Color { mode: ColorMode::Cmyk, c: [0.1, 0.2, 0.3, 0.4], alpha: 1.0 }),
Fill::Solid(Color::gray(0.25)),
Fill::Gradient { stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], angle: 45.0, scale: 1.0, style: GradientStyle::Reflected, reverse: true },
- Fill::Pattern { name: "Bubbles".into(), scale: 0.5 },
+ Fill::Pattern { name: "Bubbles".into(), scale: 0.5, id: "abc".into(), angle: 30.0, link: false, phase: (3.0, -2.0) },
] {
let (k, d) = write_fill(&f);
let back = parse_fill(&k, &d).unwrap();
diff --git a/crates/io/src/channel_map.rs b/crates/io/src/channel_map.rs
new file mode 100644
index 000000000..dd892ca57
--- /dev/null
+++ b/crates/io/src/channel_map.rs
@@ -0,0 +1,121 @@
+//! Alpha / spot channel options <-> PSD `DisplayInfo` image resources (1077, and the older 1007).
+//!
+//! Layout (Adobe PSD spec, "DisplayInfo"): resource 1077 starts with a 4-byte version (1), then
+//! one 14-byte record per extra channel: colour space (u16), four u16 colour components, opacity
+//! (u16, 0..100), kind (u8: 0 = colour indicates selected areas, 1 = masked ("protected") areas,
+//! 2 = spot channel) and one padding byte. Resource 1007 has the same records without the
+//! version and without the spot kind.
+
+use photocraft_color::{Color, ColorMode};
+use photocraft_doc::{AlphaChannel, ColorIndicates};
+
+pub(crate) const DISPLAY_INFO: u16 = 1077;
+pub(crate) const DISPLAY_INFO_OLD: u16 = 1007;
+/// Quick Mask information: channel id (u16) and an "initially empty" flag (u8).
+pub(crate) const QUICK_MASK_INFO: u16 = 1022;
+
+const SPACE_RGB: u16 = 0;
+const SPACE_CMYK: u16 = 2;
+const SPACE_LAB: u16 = 7;
+const SPACE_GRAY: u16 = 8;
+
+/// Resource 1077 for `channels` (in file order).
+pub(crate) fn display_info(channels: &[&AlphaChannel]) -> Vec<u8> {
+ let mut out = 1u32.to_be_bytes().to_vec();
+ for c in channels {
+ let (color, opacity, kind) = match c.spot {
+ Some((ink, solidity)) => (ink, solidity, 2u8),
+ None => (c.color, c.opacity, if c.indicates == ColorIndicates::SelectedAreas { 0 } else { 1 }),
+ };
+ let rgb = color.to_rgb();
+ out.extend_from_slice(&SPACE_RGB.to_be_bytes());
+ for v in [rgb[0], rgb[1], rgb[2], 0.0] {
+ out.extend_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_be_bytes());
+ }
+ out.extend_from_slice(&((opacity.clamp(0.0, 1.0) * 100.0).round() as u16).to_be_bytes());
+ out.push(kind);
+ out.push(0);
+ }
+ out
+}
+
+/// Applies a DisplayInfo resource (`versioned` = 1077) to the imported channels in order.
+pub(crate) fn apply_display_info(data: &[u8], versioned: bool, channels: &mut [AlphaChannel]) {
+ let body = if versioned { data.get(4..).unwrap_or(&[]) } else { data };
+ for (c, rec) in channels.iter_mut().zip(body.chunks_exact(14)) {
+ let u = |i: usize| u16::from_be_bytes([rec[i], rec[i + 1]]);
+ let comps = [u(2), u(4), u(6), u(8)];
+ let color = decode_color(u(0), comps);
+ let opacity = f32::from(u(10).min(100)) / 100.0;
+ match rec[12] {
+ 2 => c.spot = Some((color, opacity)),
+ k => {
+ c.color = color;
+ c.opacity = opacity;
+ c.indicates = if k == 0 { ColorIndicates::SelectedAreas } else { ColorIndicates::MaskedAreas };
+ }
+ }
+ }
+}
+
+fn decode_color(space: u16, c: [u16; 4]) -> Color {
+ let n = |v: u16| f32::from(v) / 65535.0;
+ match space {
+ // Photoshop colour structures store CMYK inverted (65535 = no ink).
+ SPACE_CMYK => {
+ let cmyk = Color { mode: ColorMode::Cmyk, c: [1.0 - n(c[0]), 1.0 - n(c[1]), 1.0 - n(c[2]), 1.0 - n(c[3])], alpha: 1.0 };
+ let rgb = cmyk.to_rgb();
+ Color::rgb(rgb[0], rgb[1], rgb[2])
+ }
+ SPACE_LAB => {
+ let l = f32::from(c[0].min(10000)) / 10000.0;
+ let a = f32::from(c[1] as i16) / 100.0;
+ let b = f32::from(c[2] as i16) / 100.0;
+ let lab = Color { mode: ColorMode::Lab, c: [l, (a + 128.0) / 255.0, (b + 128.0) / 255.0, 0.0], alpha: 1.0 };
+ let rgb = lab.to_rgb();
+ Color::rgb(rgb[0], rgb[1], rgb[2])
+ }
+ SPACE_GRAY => {
+ let v = 1.0 - f32::from(c[0].min(10000)) / 10000.0;
+ Color::rgb(v, v, v)
+ }
+ _ => Color::rgb(n(c[0]), n(c[1]), n(c[2])),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::PixelFormat;
+ use photocraft_raster::Surface;
+
+ #[test]
+ fn display_info_roundtrip() {
+ let mut a = AlphaChannel::new("A", Surface::new(PixelFormat::GRAY8));
+ a.color = Color::rgb(0.0, 1.0, 0.0);
+ a.opacity = 0.3;
+ a.indicates = ColorIndicates::SelectedAreas;
+ let mut s = AlphaChannel::new("S", Surface::new(PixelFormat::GRAY8));
+ s.spot = Some((Color::rgb(1.0, 0.0, 1.0), 0.8));
+ let bytes = display_info(&[&a, &s]);
+ assert_eq!(bytes.len(), 4 + 28);
+ let mut back = vec![AlphaChannel::new("A", Surface::new(PixelFormat::GRAY8)), AlphaChannel::new("S", Surface::new(PixelFormat::GRAY8))];
+ apply_display_info(&bytes, true, &mut back);
+ assert_eq!(back[0].color, a.color);
+ assert!((back[0].opacity - 0.3).abs() < 1e-6);
+ assert_eq!(back[0].indicates, ColorIndicates::SelectedAreas);
+ assert_eq!(back[1].spot, s.spot);
+ // Truncated data is ignored rather than misread.
+ let mut c = vec![AlphaChannel::new("x", Surface::new(PixelFormat::GRAY8))];
+ apply_display_info(&bytes[..10], true, &mut c);
+ assert_eq!(c[0].opacity, 0.5);
+ }
+
+ #[test]
+ fn decodes_other_spaces() {
+ let g = decode_color(SPACE_GRAY, [10000, 0, 0, 0]);
+ assert_eq!(g.to_rgb(), [0.0; 3]);
+ let lab = decode_color(SPACE_LAB, [10000, 0, 0, 0]).to_rgb();
+ assert!(lab.iter().all(|v| *v > 0.95), "{lab:?}");
+ }
+}
diff --git a/crates/io/src/comps_map.rs b/crates/io/src/comps_map.rs
new file mode 100644
index 000000000..e28181c31
--- /dev/null
+++ b/crates/io/src/comps_map.rs
@@ -0,0 +1,366 @@
+//! Layer comps and artboards ⇄ PSD.
+//!
+//! * Layer comps: image resource 1065 holds a `CompList` descriptor (`list` of `Comp` objects
+//! with `Nm `, `compID`, `capturedInfo` bit flags and an optional `comment`, plus
+//! `lastAppliedComp`). Each layer's state per comp lives in its `shmd` block under the `cmls`
+//! key: `layerSettings`, one object per comp id list with `enab` (visibility) and `Ofst`
+//! (offset from the layer's saved position). Comp id 0 is the Last Document State.
+//! * Artboards: the per-layer `artb` block (older files: `artd`/`abdd`) is an `artboard`
+//! descriptor with `artboardRect`, `guideIndeces`, `artboardPresetName`, `Clr ` and
+//! `artboardBackgroundType` (1 white, 2 black, 3 transparent, 4 other).
+//!
+//! Both are re-emitted verbatim while they still decode to the document's state, and are
+//! regenerated otherwise (comp appearance is not written to PSD; `.pcraft` keeps it).
+
+use photocraft_doc::comps::layer_position;
+use photocraft_doc::{Guides, Artboard, ArtboardBackground, CompLayerState, Document, Layer, LayerComp};
+use photocraft_geom::Rect;
+use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor};
+use photocraft_psd::metadata::{MetadataItem, parse_shmd, write_shmd};
+
+use crate::blocks::{color_from_desc, color_to_desc, num};
+
+/// Image resource id of the layer comp list.
+pub const LAYER_COMPS: u16 = 1065;
+/// Per-layer artboard block keys, preferred first.
+pub const ARTBOARD_KEYS: [&[u8; 4]; 3] = [b"artb", b"artd", b"abdd"];
+
+fn nul_name() -> UnicodeString {
+ UnicodeString(vec![0])
+}
+
+fn obj(class: &str) -> Descriptor {
+ Descriptor { name: nul_name(), ..Descriptor::new(class) }
+}
+
+fn pad_even(mut v: Vec<u8>) -> Vec<u8> {
+ if v.len() % 2 == 1 {
+ v.push(0);
+ }
+ v
+}
+
+fn text(d: &Descriptor, key: &str) -> Option<String> {
+ match d.get(key)? {
+ Value::Text(t) => Some(t.to_string_lossy()),
+ _ => None,
+ }
+}
+
+fn int(d: &Descriptor, key: &str) -> Option<i64> {
+ match d.get(key)? {
+ Value::Integer(i) => Some(i64::from(*i)),
+ Value::LargeInteger(i) => Some(*i),
+ Value::Double(f) => Some(f.round() as i64),
+ Value::UnitFloat { value, .. } => Some(value.round() as i64),
+ _ => None,
+ }
+}
+
+fn desc<'a>(d: &'a Descriptor, key: &str) -> Option<&'a Descriptor> {
+ match d.get(key)? {
+ Value::Descriptor(x) | Value::GlobalObject(x) => Some(x),
+ _ => None,
+ }
+}
+
+// ---------------------------------------------------------------- artboards
+
+/// Decodes an `artb`/`artd`/`abdd` block.
+pub fn parse_artboard(data: &[u8]) -> Option<Artboard> {
+ let (vd, _) = VersionedDescriptor::parse_prefix(data).ok()?;
+ let d = &vd.descriptor;
+ let r = desc(d, "artboardRect")?;
+ let g = |k: &str| num(r.get(k)).map(|v| v.round() as i32);
+ let rect = Rect::new(g("Left")?, g("Top ")?, g("Rght")?, g("Btom")?);
+ let background = match int(d, "artboardBackgroundType").unwrap_or(1) {
+ 2 => ArtboardBackground::Black,
+ 3 => ArtboardBackground::Transparent,
+ 4 => ArtboardBackground::Custom(desc(d, "Clr ").and_then(color_from_desc).unwrap_or(photocraft_doc::Color::WHITE)),
+ _ => ArtboardBackground::White,
+ };
+ let preset = text(d, "artboardPresetName").unwrap_or_default();
+ Some(Artboard { rect, background, preset })
+}
+
+/// Encodes an `artb` block. `guides` are indices into the document's guide list (resource 1032)
+/// that belong to the board.
+pub fn write_artboard(a: &Artboard, guides: &[i32]) -> Vec<u8> {
+ let f = |v: i32| Value::Double(f64::from(v));
+ let rect = Descriptor::new("classFloatRect").with("Top ", f(a.rect.y0)).with("Left", f(a.rect.x0)).with("Btom", f(a.rect.y1)).with("Rght", f(a.rect.x1));
+ let color = match a.background {
+ ArtboardBackground::Custom(c) => c,
+ ArtboardBackground::Black => photocraft_doc::Color::BLACK,
+ _ => photocraft_doc::Color::WHITE,
+ };
+ let d = Descriptor::new("artboard")
+ .with("artboardRect", Value::Descriptor(rect))
+ .with("guideIndeces", Value::List(guides.iter().map(|i| Value::Integer(*i)).collect()))
+ .with("artboardPresetName", Value::Text(UnicodeString::new_nul(&a.preset)))
+ .with("Clr ", Value::Descriptor(color_to_desc(&color)))
+ .with("artboardBackgroundType", Value::Integer(a.background.psd_type()));
+ pad_even(VersionedDescriptor::new(d).to_bytes())
+}
+
+/// Indices of the document guides (horizontal first, then vertical, as in resource 1032) that
+/// lie inside `r`.
+pub fn guides_in(guides: &Guides, r: Rect) -> Vec<i32> {
+ let h = guides.horizontal.iter().map(|y| (*y as f64) > f64::from(r.y0) && (*y as f64) < f64::from(r.y1));
+ let v = guides.vertical.iter().map(|x| (*x as f64) > f64::from(r.x0) && (*x as f64) < f64::from(r.x1));
+ h.chain(v).enumerate().filter(|(_, inside)| *inside).map(|(i, _)| i as i32).collect()
+}
+
+/// Keeps, regenerates or removes the artboard block among a layer's raw blocks.
+pub(crate) fn artboard_block(guides: &Guides, l: &Layer, raw: &mut Vec<([u8; 4], Vec<u8>)>) {
+ let pos = raw.iter().position(|(k, _)| ARTBOARD_KEYS.contains(&k));
+ match (l.artboard(), pos) {
+ (None, Some(_)) => raw.retain(|(k, _)| !ARTBOARD_KEYS.contains(&k)),
+ (None, None) => {}
+ (Some(a), Some(i)) if parse_artboard(&raw[i].1).as_ref() == Some(a) => {}
+ (Some(a), pos) => {
+ let data = write_artboard(a, &guides_in(guides, a.rect));
+ match pos {
+ Some(i) => raw[i] = (*b"artb", data),
+ None => raw.push((*b"artb", data)),
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------- layer comps
+
+/// One `layerSettings` entry of a `cmls` descriptor.
+#[derive(Debug, Clone, PartialEq)]
+struct Setting {
+ comps: Vec<u32>,
+ visible: Option<bool>,
+ offset: Option<(i32, i32)>,
+}
+
+fn parse_cmls(data: &[u8]) -> Option<Vec<Setting>> {
+ let (vd, _) = VersionedDescriptor::parse_prefix(data).ok()?;
+ let Value::List(items) = vd.descriptor.get("layerSettings")? else { return None };
+ let mut out = Vec::new();
+ for it in items {
+ let Value::Descriptor(s) = it else { continue };
+ let comps = match s.get("compList") {
+ Some(Value::List(ids)) => ids.iter().filter_map(|v| if let Value::Integer(i) = v { Some(*i as u32) } else { None }).collect(),
+ _ => Vec::new(),
+ };
+ let visible = match s.get("enab") {
+ Some(Value::Boolean(b)) => Some(*b),
+ _ => None,
+ };
+ let offset = desc(s, "Ofst").and_then(|o| Some((int(o, "Hrzn")? as i32, int(o, "Vrtc")? as i32)));
+ out.push(Setting { comps, visible, offset });
+ }
+ Some(out)
+}
+
+/// The `cmls` item data of a layer's preserved `shmd` block.
+fn layer_cmls(l: &Layer) -> Option<Vec<u8>> {
+ let (_, shmd) = l.psd_blocks.iter().find(|(k, _)| k == b"shmd")?;
+ parse_shmd(shmd).ok()?.into_iter().find(|it| &it.key == b"cmls").map(|it| it.data)
+}
+
+/// Comps, last applied comp and Last Document State described by `resource` (1065 data) and the
+/// layers' `cmls` metadata.
+pub fn comps_from_psd(resource: Option<&[u8]>, doc: &Document) -> (Vec<LayerComp>, Option<u32>, Option<LayerComp>) {
+ let Some(data) = resource else { return (Vec::new(), None, None) };
+ let Ok((vd, _)) = VersionedDescriptor::parse_prefix(data) else { return (Vec::new(), None, None) };
+ let d = &vd.descriptor;
+ let mut comps: Vec<LayerComp> = Vec::new();
+ if let Some(Value::List(items)) = d.get("list") {
+ for it in items {
+ let Value::Descriptor(c) = it else { continue };
+ let Some(id) = int(c, "compID") else { continue };
+ let mut comp = LayerComp {
+ id: id as u32,
+ name: text(c, "Nm ").unwrap_or_default(),
+ comment: text(c, "comment").unwrap_or_default(),
+ apply_visibility: false,
+ apply_position: false,
+ apply_appearance: false,
+ states: Vec::new(),
+ };
+ comp.set_captured_info(int(c, "capturedInfo").unwrap_or(0) as i32);
+ comps.push(comp);
+ }
+ }
+ let last_applied = int(d, "lastAppliedComp").map(|v| v as u32).filter(|id| comps.iter().any(|c| c.id == *id));
+ let mut last = LayerComp { id: 0, name: "Last Document State".into(), comment: String::new(), apply_visibility: true, apply_position: true, apply_appearance: false, states: Vec::new() };
+ for (_, _, l) in doc.walk() {
+ let Some(settings) = layer_cmls(l).and_then(|c| parse_cmls(&c)) else { continue };
+ let here = layer_position(l);
+ for s in settings {
+ if s.visible.is_none() && s.offset.is_none() {
+ continue;
+ }
+ let state = CompLayerState {
+ layer: l.id,
+ visible: s.visible,
+ position: match (here, s.offset) {
+ (Some((x, y)), Some((dx, dy))) => Some((x + dx, y + dy)),
+ _ => None,
+ },
+ appearance: None,
+ };
+ for id in &s.comps {
+ let target = if *id == 0 { Some(&mut last) } else { comps.iter_mut().find(|c| c.id == *id) };
+ if let Some(c) = target {
+ c.states.push(state.clone());
+ }
+ }
+ }
+ }
+ let last = (!last.states.is_empty()).then_some(last);
+ (comps, last_applied, last)
+}
+
+/// The 1065 resource data for `doc`'s comps (None when there are none).
+pub fn write_comps_resource(doc: &Document) -> Option<Vec<u8>> {
+ if doc.layer_comps.is_empty() {
+ return None;
+ }
+ let list = doc
+ .layer_comps
+ .iter()
+ .map(|c| {
+ let mut d = Descriptor::new("Comp").with("Nm ", Value::Text(UnicodeString::new_nul(&c.name)));
+ if !c.comment.is_empty() {
+ d = d.with("comment", Value::Text(UnicodeString::new_nul(&c.comment)));
+ }
+ Value::Descriptor(d.with("compID", Value::Integer(c.id as i32)).with("capturedInfo", Value::Integer(c.captured_info())))
+ })
+ .collect();
+ let mut d = Descriptor::new("CompList").with("list", Value::List(list));
+ if let Some(id) = doc.last_applied_comp {
+ d = d.with("lastAppliedComp", Value::Integer(id as i32));
+ }
+ Some(VersionedDescriptor::new(d).to_bytes())
+}
+
+fn setting_value(ids: &[u32], st: Option<&CompLayerState>, here: Option<(i32, i32)>) -> Value {
+ let mut s = obj("null");
+ if let Some(st) = st {
+ if let Some(v) = st.visible {
+ s = s.with("enab", Value::Boolean(v));
+ }
+ if let (Some((x, y)), Some((hx, hy))) = (st.position, here) {
+ s = s.with("Ofst", Value::Descriptor(obj("null").with("Hrzn", Value::Integer(x - hx)).with("Vrtc", Value::Integer(y - hy))));
+ }
+ }
+ Value::Descriptor(s.with("compList", Value::List(ids.iter().map(|i| Value::Integer(*i as i32)).collect())))
+}
+
+/// The `cmls` item data for one layer (None when the document has no comps).
+pub fn write_cmls(comps: &[LayerComp], last: Option<&LayerComp>, l: &Layer, psd_id: u32) -> Option<Vec<u8>> {
+ if comps.is_empty() {
+ return None;
+ }
+ let here = layer_position(l);
+ let mut settings: Vec<Value> = comps.iter().map(|c| setting_value(&[c.id], c.state(l.id), here)).collect();
+ settings.push(setting_value(&[0], last.and_then(|c| c.state(l.id)), here));
+ let origin = obj("null").with("Hrzn", Value::Double(0.0)).with("Vrtc", Value::Double(0.0));
+ let d = Descriptor::new("null").with("origFXRefPoint", Value::Descriptor(origin)).with("LyrI", Value::Integer(psd_id as i32)).with("layerSettings", Value::List(settings));
+ Some(VersionedDescriptor::new(d).to_bytes())
+}
+
+/// Whether `doc`'s comps still equal what its preserved PSD data (resource 1065 plus the layers'
+/// `cmls`) decodes to, in which case all of it is written back verbatim.
+pub fn comps_unchanged(doc: &Document) -> bool {
+ let raw = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == LAYER_COMPS).map(|(_, _, d)| d.as_slice());
+ let (comps, last_applied, last) = comps_from_psd(raw, doc);
+ comps == doc.layer_comps && last_applied == doc.last_applied_comp && last == doc.last_document_state
+}
+
+/// Replaces (or removes, with `None`) the `cmls` item of a layer's `shmd` block among its raw
+/// blocks, keeping the other metadata items.
+pub(crate) fn set_cmls(raw: &mut Vec<([u8; 4], Vec<u8>)>, cmls: Option<Vec<u8>>) {
+ let pos = raw.iter().position(|(k, _)| k == b"shmd");
+ let mut items = pos.and_then(|i| parse_shmd(&raw[i].1).ok()).unwrap_or_default();
+ match (items.iter().position(|it| &it.key == b"cmls"), cmls) {
+ (Some(i), Some(data)) => items[i] = MetadataItem { data: pad_even(data), ..items[i].clone() },
+ (Some(i), None) => {
+ items.remove(i);
+ }
+ (None, Some(data)) => items.insert(0, MetadataItem::new(*b"cmls", data)),
+ (None, None) => return,
+ }
+ match (pos, items.is_empty()) {
+ (Some(i), true) => {
+ raw.remove(i);
+ }
+ (Some(i), false) => raw[i].1 = write_shmd(&items),
+ (None, false) => raw.push((*b"shmd", write_shmd(&items))),
+ (None, true) => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::{Color, ColorMode, LayerContent, PixelFormat, SampleType, Size};
+
+ #[test]
+ fn artboard_roundtrip() {
+ let a = Artboard { rect: Rect::new(10, 20, 110, 220), background: ArtboardBackground::Custom(Color::rgb(0.2, 0.4, 0.6)), preset: "Web".into() };
+ let b = write_artboard(&a, &[0, 2]);
+ assert_eq!(b.len() % 2, 0);
+ let back = parse_artboard(&b).unwrap();
+ assert_eq!(back.rect, a.rect);
+ assert_eq!(back.preset, "Web");
+ let ArtboardBackground::Custom(c) = back.background else { panic!("{back:?}") };
+ assert!((c.c[1] - 0.4).abs() < 1e-3);
+ for bg in [ArtboardBackground::White, ArtboardBackground::Black, ArtboardBackground::Transparent] {
+ let a = Artboard { background: bg, ..Artboard::new(Rect::new(0, 0, 4, 4)) };
+ assert_eq!(parse_artboard(&write_artboard(&a, &[])), Some(a));
+ }
+ assert_eq!(parse_artboard(&[1, 2, 3]), None);
+ }
+
+ #[test]
+ fn cmls_setting_roundtrip_and_shmd_merge() {
+ let mut d = Document::with_background("t", Size::new(32, 32), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+ let mut l = Layer::raster("A", PixelFormat::RGBA8);
+ l.surface_mut().unwrap().fill_rect(Rect::new(4, 4, 8, 8), &[1.0, 0.0, 0.0, 1.0]);
+ let lid = l.id;
+ d.layers.push(l);
+ d.layer_comps.push(LayerComp {
+ id: 7,
+ name: "One".into(),
+ comment: "c".into(),
+ apply_visibility: true,
+ apply_position: true,
+ apply_appearance: false,
+ states: vec![CompLayerState { layer: lid, visible: Some(false), position: Some((10, 1)), appearance: None }],
+ });
+ d.last_applied_comp = Some(7);
+ let res = write_comps_resource(&d).unwrap();
+ let cm = write_cmls(&d.layer_comps, None, d.layer(lid).unwrap(), 3).unwrap();
+ // Attach as Photoshop would: shmd with cmls plus another item.
+ let mut raw = vec![(*b"shmd", write_shmd(&[MetadataItem::new(*b"cust", vec![1, 2])]))];
+ set_cmls(&mut raw, Some(cm));
+ let items = parse_shmd(&raw[0].1).unwrap();
+ assert_eq!(items.len(), 2);
+ let layer = d.layer_mut(lid).unwrap();
+ layer.psd_blocks = raw.iter().map(|(k, v)| (*k, std::sync::Arc::new(v.clone()))).collect();
+ d.metadata.psd_resources.push((LAYER_COMPS, String::new(), std::sync::Arc::new(res)));
+ let (comps, last_applied, last) = comps_from_psd(d.metadata.psd_resources.last().map(|r| r.2.as_slice()), &d);
+ assert_eq!(comps, d.layer_comps);
+ assert_eq!(last_applied, Some(7));
+ assert_eq!(last, None);
+ assert!(comps_unchanged(&d));
+ // Moving the layer changes the decoded (relative) position: no longer unchanged.
+ if let LayerContent::Raster(s) = &mut d.layer_mut(lid).unwrap().content {
+ s.fill_rect(Rect::new(0, 0, 2, 2), &[0.0, 0.0, 0.0, 1.0]);
+ }
+ assert!(!comps_unchanged(&d));
+ // Removing cmls keeps the other item; removing everything drops the block.
+ set_cmls(&mut raw, None);
+ assert_eq!(parse_shmd(&raw[0].1).unwrap().len(), 1);
+ let mut only = vec![(*b"shmd", write_shmd(&[MetadataItem::new(*b"cmls", vec![0, 0])]))];
+ set_cmls(&mut only, None);
+ assert!(only.is_empty());
+ }
+}
diff --git a/crates/io/src/effects_map.rs b/crates/io/src/effects_map.rs
index 464f142fc..ac984a15c 100644
--- a/crates/io/src/effects_map.rs
+++ b/crates/io/src/effects_map.rs
@@ -11,7 +11,10 @@ use photocraft_doc::{
};
use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor};
-use crate::blocks::{bool_of, color_from_desc, color_to_desc, enum_of, get_desc, gradient_desc, gradient_style, gradient_style_value, num};
+use crate::blocks::{
+ bool_of, color_from_desc, color_to_desc, enum_of, get_desc, gradient_desc, gradient_style, gradient_style_value, num, pattern_placement, pattern_ref,
+ pattern_ref_desc, with_pattern_placement,
+};
const BLEND_NAMES: [(BlendMode, &str); 28] = [
(BlendMode::Normal, "Nrml"),
@@ -220,12 +223,9 @@ fn parse_one(key: &str, d: &Descriptor) -> Option<Effect> {
"SoFi" => Effect::ColorOverlay { common: common(d, BlendMode::Normal, 1.0), color: color(d, "Clr ") },
"GrFl" => Effect::GradientOverlay { common: common(d, BlendMode::Normal, 1.0), gradient: gradient_from(d), dither: bool_of(d, "Dthr") },
"patternFill" => {
- let p = get_desc(d, "Ptrn");
- let text = |k: &str| match p.and_then(|p| p.get(k)) {
- Some(Value::Text(t)) => t.to_string_lossy(),
- _ => String::new(),
- };
- Effect::PatternOverlay { common: common(d, BlendMode::Normal, 1.0), name: text("Nm "), id: text("Idnt"), scale: pct(d, "Scl ", 1.0) }
+ let (name, id) = pattern_ref(d);
+ let (angle, link, phase) = pattern_placement(d);
+ Effect::PatternOverlay { common: common(d, BlendMode::Normal, 1.0), name, id, scale: pct(d, "Scl ", 1.0), angle, link, phase }
}
"ChFX" => Effect::Satin(Satin {
common: common(d, BlendMode::Multiply, 0.5),
@@ -393,16 +393,14 @@ fn write_one(e: &Effect) -> (&'static str, Descriptor) {
Effect::GradientOverlay { common: c, gradient, dither } => {
("GrFl", gradient_keys(with_common(Descriptor::new("GrFl"), c), gradient).with("Dthr", Value::Boolean(*dither)))
}
- Effect::PatternOverlay { common: c, name, id, scale } => (
+ Effect::PatternOverlay { common: c, name, id, scale, angle, link, phase } => (
"patternFill",
- with_common(Descriptor::new("patternFill"), c)
- .with(
- "Ptrn",
- Value::Descriptor(
- Descriptor::new("Ptrn").with("Nm ", Value::Text(UnicodeString::new_nul(name))).with("Idnt", Value::Text(UnicodeString::new_nul(id))),
- ),
- )
- .with("Scl ", unit(b"#Prc", scale * 100.0)),
+ with_pattern_placement(
+ with_common(Descriptor::new("patternFill"), c).with("Ptrn", Value::Descriptor(pattern_ref_desc(name, id))).with("Scl ", unit(b"#Prc", scale * 100.0)),
+ *angle,
+ *link,
+ *phase,
+ ),
),
Effect::Satin(s) => (
"ChFX",
@@ -606,7 +604,7 @@ mod tests {
Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Multiply, 0.5), size: 6.0, position: StrokePosition::Center, paint: FxPaint::Gradient(g.clone()) }),
Effect::ColorOverlay { common: FxCommon::new(BlendMode::Overlay, 0.5), color: Color::rgb(0.0, 0.0, 1.0) },
Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: g, dither: true },
- Effect::PatternOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), name: "Bubbles".into(), id: "abc".into(), scale: 1.0 },
+ Effect::PatternOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), name: "Bubbles".into(), id: "abc".into(), scale: 1.0, angle: 15.0, link: false, phase: (4.0, 2.0) },
Effect::Satin(Satin { common: FxCommon::new(BlendMode::Multiply, 0.5), color: Color::BLACK, angle: 19.0, distance: 11.0, size: 14.0, contour: Contour::Linear, anti_alias: true, invert: true }),
Effect::BevelEmboss(Bevel {
enabled: true,
diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs
index 55ed2b2ab..af781e1ae 100644
--- a/crates/io/src/flat.rs
+++ b/crates/io/src/flat.rs
@@ -95,7 +95,10 @@ pub fn document_to_image(doc: &Document, warnings: &mut Vec<String>) -> Result<I
let canvas = doc.bounds();
let fmt = doc.pixel_format();
let n = (w as usize) * (h as usize);
- let img = if let Some(s) = single_layer(doc) {
+ // Lab has no flat-format layout here: Lab documents always go through the composite.
+ let native = single_layer(doc).filter(|_| fmt.mode != ColorMode::Lab);
+ let mut icc = doc.icc_profile.as_ref().map(|i| i.to_vec());
+ let img = if let Some(s) = native {
// Native path: keep model and depth.
let vals = s.read_region(canvas);
let ch = fmt.channels();
@@ -111,7 +114,10 @@ pub fn document_to_image(doc: &Document, warnings: &mut Vec<String>) -> Result<I
// The compositor works in RGB; write RGB/gray.
let gray = fmt.mode == ColorMode::Grayscale;
if fmt.mode == ColorMode::Cmyk || fmt.mode == ColorMode::Lab {
- warnings.push(format!("{:?} composite written as RGB (naive conversion, no color management)", fmt.mode));
+ // The compositor renders CMYK/Lab documents in sRGB (CMYK through the built-in
+ // profile), so the file is tagged sRGB.
+ warnings.push(format!("{:?} composite written as sRGB RGB (colour-managed conversion)", fmt.mode));
+ icc = Some(photocraft_cms::Builtin::Srgb.profile().to_bytes().to_vec());
}
let layout = layout_for(if gray { ColorMode::Grayscale } else { ColorMode::Rgb }, !opaque);
let mut data = Vec::with_capacity(n * layout.channels());
@@ -133,13 +139,20 @@ pub fn document_to_image(doc: &Document, warnings: &mut Vec<String>) -> Result<I
dpi: Some((doc.resolution_dpi, doc.resolution_dpi)),
text: Vec::new(),
};
- Ok(img.with_icc(doc.icc_profile.as_ref().map(|i| i.to_vec())).with_meta(meta))
+ Ok(img.with_icc(icc).with_meta(meta))
}
/// Flattens and encodes as `format`.
pub fn export_flat(doc: &Document, format: Format, opts: &ExportOptions) -> Result<ExportResult, IoError> {
+ if let Some(r) = export_mode_specific(doc, format, opts)? {
+ return Ok(r);
+ }
let mut warnings = Vec::new();
- let img = document_to_image(doc, &mut warnings)?;
+ let mut img = document_to_image(doc, &mut warnings)?;
+ if img.layout().is_cmyk() && !format.caps().layouts.iter().any(|l| l.is_cmyk()) {
+ img = cmyk_image_to_srgb(&img)?;
+ warnings.push(format!("CMYK converted to sRGB for {format:?} through the document's colour profile"));
+ }
for w in codecs::fidelity_warnings_with(&img, format, &opts.encode) {
if w.is_fatal() {
return Err(IoError::Unsupported(w.to_string()));
@@ -149,3 +162,62 @@ pub fn export_flat(doc: &Document, format: Format, opts: &ExportOptions) -> Resu
let bytes = codecs::encode(&img, format, &opts.encode)?;
Ok(ExportResult { bytes, warnings })
}
+
+/// Colour-managed CMYK → sRGB for formats that cannot store CMYK (the document's embedded
+/// CMYK profile when it parses, else the built-in coated CMYK; relative colorimetric + BPC).
+fn cmyk_image_to_srgb(img: &Image) -> Result<Image, IoError> {
+ use photocraft_cms::{Builtin, ColorSpace, Intent, Profile, Transform};
+ let src = img
+ .icc
+ .as_ref()
+ .and_then(|b| Profile::parse(b).ok())
+ .filter(|p| p.color_space == ColorSpace::Cmyk)
+ .unwrap_or_else(|| Builtin::CoatedCmyk.profile().clone());
+ let dst = Builtin::Srgb.profile();
+ let t = Transform::new(&src, dst, Intent::RelativeColorimetric, true).map_err(|e| IoError::Unsupported(e.to_string()))?;
+ let alpha = img.layout().has_alpha();
+ let (ss, ds) = (if alpha { 5 } else { 4 }, if alpha { 4 } else { 3 });
+ let vals = img.to_normalized();
+ let mut out = vec![0.0f32; img.pixel_count() * ds];
+ t.convert_f32(&vals, ss, &mut out, ds, true);
+ let (w, h) = img.dimensions();
+ let layout = if alpha { ChannelLayout::Rgba } else { ChannelLayout::Rgb };
+ let sample = match img.sample_type() {
+ CSample::F16 => CSample::F32,
+ s => s,
+ };
+ Ok(Image::from_normalized(w, h, layout, sample, &out)?.with_icc(Some(dst.to_bytes().to_vec())).with_meta(img.meta.clone()))
+}
+
+/// Indexed Color → PNG-8 with its colour table; Duotone → the inks rendered as RGB.
+fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> Result<Option<ExportResult>, IoError> {
+ match doc.mode {
+ ColorMode::Indexed if format == Format::Png => {
+ let Some(table) = doc.color_table.as_ref().filter(|t| !t.colors.is_empty() && t.colors.len() <= 256) else { return Ok(None) };
+ let buf = photocraft_compose::flatten(doc);
+ let idx: Vec<u8> = buf
+ .px
+ .iter()
+ .map(|p| match table.transparent {
+ Some(t) if p[3] < 0.5 => t,
+ _ => table.nearest([p[0], p[1], p[2]]) as u8,
+ })
+ .collect();
+ let bytes = codecs::encode_png_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent)?;
+ Ok(Some(ExportResult { bytes, warnings: vec![format!("written as an 8-bit palette PNG ({} colours)", table.colors.len())] }))
+ }
+ ColorMode::Duotone => {
+ let Some(d) = doc.duotone.as_ref() else { return Ok(None) };
+ let mut shown = doc.clone();
+ shown.layers.push(photocraft_doc::Layer::new("Duotone", photocraft_doc::LayerContent::Adjustment(d.display_adjustment())));
+ shown.mode = ColorMode::Rgb;
+ shown.icc_profile = None;
+ shown.duotone = None;
+ let mut r = export_flat(&shown, format, opts)?;
+ r.warnings.retain(|w| !w.contains("flattened"));
+ r.warnings.push(format!("Duotone ({} inks) written as RGB", d.inks.len()));
+ Ok(Some(r))
+ }
+ _ => Ok(None),
+ }
+}
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 94006ec48..6268b0850 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -18,10 +18,14 @@
#![forbid(unsafe_code)]
mod adjust_map;
+mod channel_map;
+pub mod comps_map;
pub mod effects_map;
pub mod blocks;
mod gradient_bake;
mod flat;
+pub mod linked;
+pub mod pattern_map;
mod pixels;
mod psd_export;
mod psd_import;
@@ -134,7 +138,9 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result
pub fn merged_composite(file: &PsdFile) -> Result<Vec<[f32; 4]>, IoError> {
let img = file.composite_rgba8().ok();
let h = &file.header;
- if let (Some(img), false) = (img, matches!(h.color_mode, photocraft_psd::ColorMode::Lab)) {
+ // CMYK goes through the colour-managed model conversion (the PSD crate's RGBA preview is a
+ // naive, profile-free conversion).
+ if let (Some(img), false) = (img, matches!(h.color_mode, photocraft_psd::ColorMode::Lab | photocraft_psd::ColorMode::Cmyk)) {
let unmatte = file.merged_has_alpha();
return Ok(img
.data
@@ -150,7 +156,7 @@ pub fn merged_composite(file: &PsdFile) -> Result<Vec<[f32; 4]>, IoError> {
})
.collect());
}
- // Generic path (Lab and others) via the raster model conversion.
+ // Generic path (Lab, CMYK and others) via the raster model conversion.
let (doc, _) = psd_to_document(&PsdFile { layer_info: None, ..file.clone() });
let l = doc.layers.first().ok_or_else(|| IoError::Unsupported("no merged image".into()))?;
let s = l.surface().ok_or_else(|| IoError::Unsupported("no merged image".into()))?;
diff --git a/crates/io/src/linked.rs b/crates/io/src/linked.rs
new file mode 100644
index 000000000..b07d28ba1
--- /dev/null
+++ b/crates/io/src/linked.rs
@@ -0,0 +1,149 @@
+//! Embedded smart-object files from the PSD global `lnk2`/`lnk3`/`lnkD` blocks.
+//!
+//! PSD import keeps a placed layer's source as `SmartSource::Linked { path: <Idnt uuid> }` and the
+//! file bytes stay inside the preserved global block (so PSD export stays byte-stable). This module
+//! finds the bytes for a uuid when the engine needs to re-render the smart object from its source.
+//!
+//! Layout (Adobe PSD spec, "Linked Layer"): a sequence of items, each `u64 length` + item data,
+//! padded to 4 bytes. Item: type (`liFD` data / `liFE` external / `liFA` alias), version (1–7),
+//! Pascal uuid, Unicode file name, file type, creator, `u64` data length, open-descriptor flag (+
+//! versioned descriptor), then for `liFD` the raw file bytes.
+
+use photocraft_doc::Metadata;
+use photocraft_psd::descriptor::VersionedDescriptor;
+
+/// An embedded file found in a linked-layer block.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct LinkedFile {
+ pub uuid: String,
+ pub file_name: String,
+ pub bytes: Vec<u8>,
+}
+
+struct Rd<'a> {
+ d: &'a [u8],
+ p: usize,
+}
+
+impl<'a> Rd<'a> {
+ fn take(&mut self, n: usize) -> Option<&'a [u8]> {
+ let s = self.d.get(self.p..self.p.checked_add(n)?)?;
+ self.p += n;
+ Some(s)
+ }
+ fn u8(&mut self) -> Option<u8> {
+ self.take(1).map(|b| b[0])
+ }
+ fn u32(&mut self) -> Option<u32> {
+ self.take(4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
+ }
+ fn u64(&mut self) -> Option<u64> {
+ self.take(8).map(|b| u64::from_be_bytes(b.try_into().unwrap_or([0; 8])))
+ }
+ fn unicode(&mut self) -> Option<String> {
+ let n = self.u32()? as usize;
+ let raw = self.take(n.checked_mul(2)?)?;
+ let units: Vec<u16> = raw.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
+ Some(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
+ }
+}
+
+/// Parses one item; `None` for malformed data or non-`liFD` items.
+fn parse_item(item: &[u8]) -> Option<LinkedFile> {
+ let mut r = Rd { d: item, p: 0 };
+ let kind = r.take(4)?;
+ let _version = r.u32()?;
+ let n = r.u8()? as usize;
+ let uuid = String::from_utf8_lossy(r.take(n)?).to_string();
+ let file_name = r.unicode()?;
+ r.take(8)?; // file type + creator
+ let len = usize::try_from(r.u64()?).ok()?;
+ if r.u8()? != 0 {
+ let (_, used) = VersionedDescriptor::parse_prefix(item.get(r.p..)?).ok()?;
+ r.p += used;
+ }
+ if kind != b"liFD" {
+ return None;
+ }
+ let bytes = r.take(len)?.to_vec();
+ Some(LinkedFile { uuid, file_name, bytes })
+}
+
+/// Every embedded (`liFD`) file in one linked-layer block's data.
+pub fn parse_linked_files(data: &[u8]) -> Vec<LinkedFile> {
+ let mut out = Vec::new();
+ let mut r = Rd { d: data, p: 0 };
+ while let Some(len) = r.u64() {
+ let Ok(len) = usize::try_from(len) else { break };
+ let Some(item) = r.take(len) else { break };
+ out.extend(parse_item(item));
+ r.p = r.p.next_multiple_of(4);
+ }
+ out
+}
+
+/// The embedded file for smart-object `uuid` among the document's preserved PSD global blocks.
+pub fn find_linked_file(meta: &Metadata, uuid: &str) -> Option<LinkedFile> {
+ if uuid.is_empty() {
+ return None;
+ }
+ meta.psd_global_blocks
+ .iter()
+ .filter(|(_, k, _)| matches!(k, b"lnk2" | b"lnk3" | b"lnkD"))
+ .flat_map(|(_, _, d)| parse_linked_files(d))
+ .find(|f| f.uuid == uuid)
+}
+
+/// Encodes one `liFD` item (version 2, no open descriptor). Used by tests and writers that
+/// need a minimal linked-layer block.
+pub fn encode_linked_file(f: &LinkedFile) -> Vec<u8> {
+ let mut item = Vec::new();
+ item.extend_from_slice(b"liFD");
+ item.extend_from_slice(&2u32.to_be_bytes());
+ item.push(f.uuid.len().min(255) as u8);
+ item.extend_from_slice(&f.uuid.as_bytes()[..f.uuid.len().min(255)]);
+ let units: Vec<u16> = f.file_name.encode_utf16().collect();
+ item.extend_from_slice(&(units.len() as u32).to_be_bytes());
+ for u in units {
+ item.extend_from_slice(&u.to_be_bytes());
+ }
+ item.extend_from_slice(b" 8BIM");
+ item.extend_from_slice(&(f.bytes.len() as u64).to_be_bytes());
+ item.push(0);
+ item.extend_from_slice(&f.bytes);
+ let mut out = (item.len() as u64).to_be_bytes().to_vec();
+ out.extend_from_slice(&item);
+ while !out.len().is_multiple_of(4) {
+ out.push(0);
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Arc;
+
+ #[test]
+ fn round_trips_and_finds_by_uuid() {
+ let a = LinkedFile { uuid: "abc-1".into(), file_name: "a.png".into(), bytes: vec![1, 2, 3] };
+ let b = LinkedFile { uuid: "def-2".into(), file_name: "b.psd".into(), bytes: vec![9; 10] };
+ let mut data = encode_linked_file(&a);
+ data.extend(encode_linked_file(&b));
+ assert_eq!(parse_linked_files(&data), vec![a.clone(), b.clone()]);
+ let mut meta = Metadata::default();
+ meta.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(data)));
+ assert_eq!(find_linked_file(&meta, "def-2"), Some(b));
+ assert_eq!(find_linked_file(&meta, "zzz"), None);
+ assert_eq!(find_linked_file(&meta, ""), None);
+ }
+
+ #[test]
+ fn malformed_data_is_ignored() {
+ assert!(parse_linked_files(&[0, 0, 0, 0, 0, 0, 0, 200, 1, 2]).is_empty());
+ assert!(parse_linked_files(&[]).is_empty());
+ let mut d = encode_linked_file(&LinkedFile { uuid: "x".into(), file_name: "f".into(), bytes: vec![5; 4] });
+ d.truncate(d.len() - 6);
+ assert!(parse_linked_files(&d).is_empty());
+ }
+}
diff --git a/crates/io/src/pattern_map.rs b/crates/io/src/pattern_map.rs
new file mode 100644
index 000000000..1473b281c
--- /dev/null
+++ b/crates/io/src/pattern_map.rs
@@ -0,0 +1,200 @@
+//! Patterns ⇄ PSD: the global `Patt`/`Pat2`/`Pat3` blocks and `.pat` files.
+//!
+//! Import parses the blocks into [`Document::patterns`] and keeps the raw blocks. Export reuses
+//! the raw blocks verbatim while they still decode to the document's patterns (byte-exact round
+//! trips); otherwise they are replaced by one block written from the document.
+
+use std::sync::Arc;
+
+use photocraft_color::{ColorMode, PixelFormat};
+use photocraft_doc::{Document, Pattern};
+use photocraft_geom::Rect;
+use photocraft_psd::patterns::{PsdPattern, block_key, mode_channels, parse_pattern_block, write_pattern_block};
+use photocraft_raster::Surface;
+
+use crate::pixels::{deinterleave, interleave, max_sample, psd_depth, sample_for_depth, zero_sample};
+
+/// Global block keys holding patterns.
+pub const PATTERN_KEYS: [[u8; 4]; 3] = [*b"Patt", *b"Pat2", *b"Pat3"];
+
+fn psd_mode(m: ColorMode) -> u32 {
+ match m {
+ ColorMode::Grayscale => 1,
+ ColorMode::Cmyk => 4,
+ ColorMode::Lab => 9,
+ _ => 3,
+ }
+}
+
+/// A PSD pattern as a document pattern (indexed patterns become RGB through their palette).
+pub fn from_psd(p: &PsdPattern) -> Option<Pattern> {
+ let (w, h) = (p.width as usize, p.height as usize);
+ if w == 0 || h == 0 {
+ return None;
+ }
+ // 1-bit patterns: expand to 8-bit grey.
+ let (channels, depth): (Vec<Vec<u8>>, u16) = if p.depth == 1 {
+ let row = w.div_ceil(8);
+ let expand = |plane: &Vec<u8>| -> Vec<u8> { (0..w * h).map(|i| if plane.get((i / w) * row + (i % w) / 8).is_some_and(|b| b & (0x80 >> (i % w % 8)) != 0) { 0 } else { 255 }).collect() };
+ (p.channels.iter().map(expand).collect(), 8)
+ } else {
+ (p.channels.clone(), p.depth)
+ };
+ let (mode, channels) = match p.mode {
+ 1 | 8 => (ColorMode::Grayscale, channels),
+ 2 => {
+ let pal = p.palette.as_deref()?;
+ let idx = channels.first()?;
+ let ch: Vec<Vec<u8>> = (0..3).map(|c| idx.iter().map(|i| pal.get(usize::from(*i) * 3 + c).copied().unwrap_or(0)).collect()).collect();
+ (ColorMode::Rgb, ch)
+ }
+ 4 => (ColorMode::Cmyk, channels),
+ 9 => (ColorMode::Lab, channels),
+ 3 => (ColorMode::Rgb, channels),
+ _ => (ColorMode::Grayscale, channels.into_iter().take(1).collect()),
+ };
+ let s = sample_for_depth(depth);
+ let fmt = PixelFormat::new(mode, s, p.alpha.is_some());
+ let cc = mode_channels(psd_mode(mode));
+ if channels.len() < cc {
+ return None;
+ }
+ let mut refs: Vec<Option<&[u8]>> = channels.iter().take(cc).map(|c| Some(c.as_slice())).collect();
+ let mut fill = vec![zero_sample(s); cc];
+ let mut invert = vec![mode == ColorMode::Cmyk; cc];
+ if let Some(a) = &p.alpha {
+ refs.push(Some(a.as_slice()));
+ fill.push(max_sample(s));
+ invert.push(false);
+ }
+ let bytes = interleave(&refs, &fill, w * h, s, &invert);
+ let surface = Surface::from_interleaved(fmt, Rect::new(0, 0, w as i32, h as i32), &bytes);
+ Some(Pattern { id: p.id.clone(), name: p.name.clone(), width: p.width, height: p.height, surface })
+}
+
+/// A document pattern as a PSD pattern (its own depth and colour model; other models as RGB).
+pub fn to_psd(p: &Pattern) -> PsdPattern {
+ let f = p.surface.format();
+ let mode = match f.mode {
+ ColorMode::Grayscale | ColorMode::Rgb | ColorMode::Cmyk | ColorMode::Lab => f.mode,
+ _ => ColorMode::Rgb,
+ };
+ let fmt = PixelFormat::new(mode, f.sample, f.alpha);
+ let surf = if fmt == f { p.surface.clone() } else { p.surface.convert(fmt) };
+ let bytes = surf.to_interleaved(p.rect());
+ let ch = fmt.channels();
+ let mut invert = vec![mode == ColorMode::Cmyk; ch];
+ if fmt.alpha {
+ invert[ch - 1] = false;
+ }
+ let mut planes = deinterleave(&bytes, ch, fmt.sample, &invert);
+ let alpha = fmt.alpha.then(|| planes.pop()).flatten();
+ PsdPattern { mode: psd_mode(mode), width: p.width, height: p.height, name: p.name.clone(), id: p.id.clone(), palette: None, depth: psd_depth(fmt.sample), channels: planes, alpha }
+}
+
+/// Patterns decoded from the document's raw pattern blocks (malformed blocks are skipped).
+pub fn from_global_blocks(doc: &Document) -> Vec<Pattern> {
+ doc.metadata
+ .psd_global_blocks
+ .iter()
+ .filter(|(_, k, _)| PATTERN_KEYS.contains(k))
+ .filter_map(|(_, _, d)| parse_pattern_block(d).ok())
+ .flatten()
+ .filter_map(|p| from_psd(&p))
+ .collect()
+}
+
+/// Global blocks to write: the raw ones while they still match [`Document::patterns`], else the
+/// raw pattern blocks replaced by one written from the document (at the first one's position).
+pub fn export_global_blocks(doc: &Document) -> Vec<photocraft_doc::PsdGlobalBlock> {
+ let raw = &doc.metadata.psd_global_blocks;
+ if from_global_blocks(doc) == doc.patterns {
+ return raw.clone();
+ }
+ let key = block_key(psd_depth(doc.depth));
+ let fresh = write_pattern_block(&doc.patterns.iter().map(to_psd).collect::<Vec<_>>()).unwrap_or_default();
+ let mut out = Vec::with_capacity(raw.len() + 1);
+ let mut placed = false;
+ for b in raw {
+ if PATTERN_KEYS.contains(&b.1) {
+ if !placed {
+ out.push((*b"8BIM", key, Arc::new(fresh.clone())));
+ placed = true;
+ }
+ } else {
+ out.push(b.clone());
+ }
+ }
+ if !placed && !doc.patterns.is_empty() {
+ out.push((*b"8BIM", key, Arc::new(fresh)));
+ }
+ out
+}
+
+/// Reads a `.pat` pattern file.
+pub fn read_pat(bytes: &[u8]) -> Result<Vec<Pattern>, String> {
+ let ps = photocraft_psd::patterns::parse_pat_file(bytes).map_err(|e| format!("not a readable .pat file: {e}"))?;
+ Ok(ps.iter().filter_map(from_psd).collect())
+}
+
+/// Writes patterns as a `.pat` file.
+pub fn write_pat(patterns: &[Pattern]) -> Result<Vec<u8>, String> {
+ photocraft_psd::patterns::write_pat_file(&patterns.iter().map(to_psd).collect::<Vec<_>>()).map_err(|e| e.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::SampleType;
+
+ fn pattern(mode: ColorMode, s: SampleType, alpha: bool) -> Pattern {
+ let fmt = PixelFormat::new(mode, s, alpha);
+ let mut surf = Surface::new(fmt);
+ let n = fmt.channels();
+ for y in 0..3 {
+ for x in 0..5 {
+ let px: Vec<f32> = (0..n).map(|c| ((x * 3 + y * 7 + c as i32 * 5) % 11) as f32 / 10.0).collect();
+ surf.write_pixel(x, y, &px);
+ }
+ }
+ Pattern::new("P", surf, 5, 3)
+ }
+
+ #[test]
+ fn patterns_round_trip_through_psd_at_every_depth_and_model() {
+ for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
+ for s in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for alpha in [false, true] {
+ let p = pattern(mode, s, alpha);
+ let back = from_psd(&to_psd(&p)).unwrap();
+ assert_eq!((&back.id, &back.name, back.width, back.surface.format()), (&p.id, &p.name, p.width, p.surface.format()));
+ // Exact except float CMYK, whose stored inversion (1 − v) rounds.
+ let (a, b) = (back.surface.read_region(p.rect()), p.surface.read_region(p.rect()));
+ assert!(a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-6), "{mode:?} {s:?} {alpha}");
+ if !(mode == ColorMode::Cmyk && s == SampleType::F32) {
+ assert_eq!(back, p, "{mode:?} {s:?} {alpha}");
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn export_reuses_raw_blocks_until_patterns_change() {
+ let mut d = Document::new("x", photocraft_geom::Size { width: 4, height: 4 }, ColorMode::Rgb, SampleType::U8);
+ let p = pattern(ColorMode::Rgb, SampleType::U8, false);
+ let raw = write_pattern_block(&[to_psd(&p)]).unwrap();
+ d.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Txt2", Arc::new(vec![1])), (*b"8BIM", *b"Patt", Arc::new(raw.clone()))];
+ d.patterns = from_global_blocks(&d);
+ assert_eq!(d.patterns.len(), 1);
+ assert_eq!(export_global_blocks(&d), d.metadata.psd_global_blocks);
+ d.patterns.push(pattern(ColorMode::Grayscale, SampleType::U16, true));
+ let out = export_global_blocks(&d);
+ assert_eq!(out.len(), 2);
+ assert_eq!(out[1].1, *b"Patt");
+ let mut d2 = d.clone();
+ d2.metadata.psd_global_blocks = out;
+ assert_eq!(from_global_blocks(&d2), d.patterns);
+ assert_eq!(read_pat(&write_pat(&d.patterns).unwrap()).unwrap(), d.patterns);
+ }
+}
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index 04932f665..a72bf3716 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -38,6 +38,10 @@ struct Ex {
canvas: photocraft_geom::Rect,
records: Vec<LayerRecord>,
warnings: Vec<String>,
+ /// Guides (artboard blocks list the guides inside each board).
+ guides: photocraft_doc::Guides,
+ /// Layer comps to regenerate into each layer's `cmls`; None = preserved data still matches.
+ comps: Option<(Vec<photocraft_doc::LayerComp>, Option<photocraft_doc::LayerComp>)>,
}
fn psd_mode(m: ColorMode) -> PsdMode {
@@ -274,6 +278,12 @@ impl Ex {
if !matches!(l.content, LayerContent::Shape(_)) {
self.vector_mask_block(l, &mut raw);
}
+ crate::comps_map::artboard_block(&self.guides, l, &mut raw);
+ if let Some((comps, last)) = &self.comps {
+ // Ids are assigned to every layer before emitting.
+ let id = self.layer_ids.get(&l.id).copied().unwrap_or(0);
+ crate::comps_map::set_cmls(&mut raw, crate::comps_map::write_cmls(comps, last.as_ref(), l, id));
+ }
regenerated.into_iter().chain(raw).map(|(k, d)| TaggedBlock::new(k, d)).collect()
}
@@ -447,6 +457,8 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile
canvas: doc.bounds(),
records: Vec::new(),
warnings: Vec::new(),
+ guides: doc.guides.clone(),
+ comps: (!crate::comps_map::comps_unchanged(doc)).then(|| (doc.layer_comps.clone(), doc.last_document_state.clone())),
};
if big && !opts.force_psb {
ex.warnings.push("document exceeds 30000 px; written as PSB".into());
@@ -507,7 +519,16 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile
if doc.channels.len() > max_extra {
ex.warnings.push(format!("only {max_extra} alpha channels fit in PSD; the rest were dropped"));
}
- let extra: Vec<_> = doc.channels.iter().take(max_extra).collect();
+ let mut extra: Vec<_> = doc.channels.iter().take(max_extra).collect();
+ // Saved in Quick Mask mode: the mask is written as the last extra channel and flagged by
+ // resource 1022 (quick mask info: channel id, initially-empty flag), as Photoshop does.
+ let quick_mask_id = match &doc.quick_mask {
+ Some(q) if extra.len() < max_extra => {
+ extra.push(q);
+ Some((cc + usize::from(has_alpha) + extra.len() - 1) as u16)
+ }
+ _ => None,
+ };
for a in &extra {
let s = if a.surface.format() != ex.mask_fmt { a.surface.convert(ex.mask_fmt) } else { a.surface.clone() };
let bytes = s.to_interleaved(canvas);
@@ -536,6 +557,12 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile
let names: Vec<&str> = extra.iter().map(|a| a.name.as_str()).collect();
resources.push(ImageResource::new(1006, pascal_names_resource(&names)));
resources.push(ImageResource::new(1045, unicode_names_resource(&names)));
+ resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&extra)));
+ }
+ if let Some(id) = quick_mask_id {
+ let mut data = id.to_be_bytes().to_vec();
+ data.push(0);
+ resources.push(ImageResource::new(crate::channel_map::QUICK_MASK_INFO, data));
}
// Paths: saved paths (2000+), the work path (1025), the clipping path name (2999).
{
@@ -581,12 +608,17 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile
resources.push(ImageResource::new(ids::EXIF, e.to_vec()));
}
let mut global_blocks = Vec::new();
- for (sig, key, data) in &doc.metadata.psd_global_blocks {
+ for (sig, key, data) in &crate::pattern_map::export_global_blocks(doc) {
let mut tb = TaggedBlock::new(*key, data.to_vec());
tb.signature = *sig;
global_blocks.push(tb);
}
+ let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc));
for (id, name, data) in &doc.metadata.psd_resources {
+ // Layer comps: the preserved list while unchanged, else regenerated (or dropped) below.
+ if *id == crate::comps_map::LAYER_COMPS && comps_resource.is_some() {
+ continue;
+ }
// 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));
@@ -599,6 +631,9 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile
r.name = legacy_name(name);
resources.push(r);
}
+ if let Some(Some(data)) = comps_resource {
+ resources.push(ImageResource::new(crate::comps_map::LAYER_COMPS, data));
+ }
resources.push(version_info_resource(true));
let has_layers = !ex.records.is_empty();
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs
index 66d591f45..e2a1a9ab1 100644
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@ -18,7 +18,7 @@ use crate::blocks;
use crate::pixels::{interleave, max_sample, sample_for_depth, zero_sample};
/// Resources that are mapped to document fields or regenerated on export.
-pub(crate) const MAPPED_RESOURCES: [u16; 16] = [
+pub(crate) const MAPPED_RESOURCES: [u16; 19] = [
ids::GLOBAL_ANGLE,
ids::GLOBAL_ALTITUDE,
ids::RESOLUTION_INFO,
@@ -35,6 +35,9 @@ pub(crate) const MAPPED_RESOURCES: [u16; 16] = [
1006, // pascal alpha names
1069, // layer selection ids
1072, // layer group(s) enabled id
+ crate::channel_map::DISPLAY_INFO,
+ crate::channel_map::DISPLAY_INFO_OLD,
+ crate::channel_map::QUICK_MASK_INFO,
];
/// Blocks regenerated from document fields on export; not kept in
@@ -217,6 +220,10 @@ impl Ctx<'_> {
smart_filters: Vec::new(),
cache: Some(self.record_surface(rec, &name)),
psd_raw: principal(k),
+ filters_enabled: true,
+ filter_mask: None,
+ warp: rec.block(k).and_then(|b| blocks::parse_placed_warp(k, &b.data)),
+ stack_mode: None,
})
} 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)));
@@ -287,7 +294,8 @@ impl Ctx<'_> {
let children = self.build(children);
let sd = rec.section_divider();
let expanded = sd.is_none_or(|s| s.kind != photocraft_psd::SectionType::ClosedFolder);
- let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded }));
+ let artboard = crate::comps_map::ARTBOARD_KEYS.iter().find_map(|k| rec.block(k)).and_then(|b| crate::comps_map::parse_artboard(&b.data));
+ let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded, artboard }));
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);
@@ -397,6 +405,7 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {
for b in &file.global_blocks {
doc.metadata.psd_global_blocks.push((b.signature, b.key, Arc::new(b.data.clone())));
}
+ doc.patterns = crate::pattern_map::from_global_blocks(&doc);
let fmt = doc.pixel_format();
let cc = fmt.mode.color_channels();
@@ -465,8 +474,17 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {
} else {
cx.warn(format!("{:?} {}-bit document converted to {:?} 8-bit for editing", h.color_mode, h.depth, fmt.mode));
}
- if !file.color_mode_data.is_empty() {
- cx.warn("color mode data (palette / duotone curves) is not preserved");
+ if h.color_mode == PsdMode::Indexed && file.color_mode_data.len() >= 768 {
+ // Planar palette: 256 reds, 256 greens, 256 blues (the Color Table).
+ let m = &file.color_mode_data;
+ let colors = (0..256).map(|i| [m[i], m[256 + i], m[512 + i]]).collect();
+ doc.color_table = Some(photocraft_doc::ColorTable { colors, transparent: None });
+ } else if h.color_mode == PsdMode::Duotone && !file.color_mode_data.is_empty() {
+ // The duotone ink block is undocumented: keep it raw; the image shows as its gray plate.
+ doc.duotone = Some(photocraft_doc::Duotone { inks: vec![photocraft_doc::DuotoneInk::new("Black", [0.0; 3])], psd_raw: Some(file.color_mode_data.clone()) });
+ cx.warn("duotone inks are not interpreted (shown as grayscale)");
+ } else if !file.color_mode_data.is_empty() {
+ cx.warn("color mode data is not preserved");
}
let rgba = file.composite_rgba8().or_else(|_| {
// Multichannel: show the first channels as RGB.
@@ -511,9 +529,27 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {
s.write_interleaved(canvas, &be_to_ne_plane(p, depth, n));
s.prune();
let name = names.get(k).cloned().unwrap_or_else(|| format!("Alpha {}", k + 1));
- doc.channels.push(AlphaChannel { name, surface: s, spot: None });
+ doc.channels.push(AlphaChannel::new(name, s));
+ }
+ // Channel options (overlay colour, opacity, colour indicates) and spot inks.
+ if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) {
+ crate::channel_map::apply_display_info(&r.data, true, &mut doc.channels);
+ } else if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO_OLD) {
+ crate::channel_map::apply_display_info(&r.data, false, &mut doc.channels);
+ }
+ // Saved in Quick Mask mode: that channel becomes the document's Quick Mask again.
+ if let Some(r) = file.resource(crate::channel_map::QUICK_MASK_INFO)
+ && r.data.len() >= 2
+ && let Some(k) = usize::from(u16::from_be_bytes([r.data[0], r.data[1]])).checked_sub(first)
+ && k < doc.channels.len()
+ {
+ doc.quick_mask = Some(doc.channels.remove(k));
}
}
+ // Layer comps (resource 1065 + per-layer `cmls`); the raw data stays for verbatim export.
+ let raw_comps = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == crate::comps_map::LAYER_COMPS).map(|(_, _, d)| d.clone());
+ (doc.layer_comps, doc.last_applied_comp, doc.last_document_state) = crate::comps_map::comps_from_psd(raw_comps.as_deref().map(Vec::as_slice), &doc);
+
(doc, cx.warnings)
}
diff --git a/crates/io/tests/channels.rs b/crates/io/tests/channels.rs
new file mode 100644
index 000000000..8214f90f8
--- /dev/null
+++ b/crates/io/tests/channels.rs
@@ -0,0 +1,44 @@
+//! Alpha / spot channels, channel options and the Quick Mask through PSD.
+
+use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
+use photocraft_doc::{AlphaChannel, ColorIndicates, Document};
+use photocraft_geom::{Rect, Size};
+use photocraft_io::{document_to_psd, psd_to_document};
+use photocraft_raster::Surface;
+
+fn channel(depth: SampleType, x1: i32) -> Surface {
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false));
+ s.fill_rect(Rect::new(0, 0, x1, 8), &[1.0]);
+ s
+}
+
+#[test]
+fn channel_options_spot_and_quick_mask_roundtrip() {
+ for depth in SampleType::ALL {
+ let mut d = Document::with_background("c", Size::new(16, 8), ColorMode::Rgb, depth, Color::WHITE);
+ let mut a = AlphaChannel::new("Alpha 1", channel(depth, 4));
+ a.color = Color::rgb(0.0, 0.0, 1.0);
+ a.opacity = 0.7;
+ a.indicates = ColorIndicates::SelectedAreas;
+ d.channels.push(a);
+ d.channels.push(AlphaChannel { spot: Some((Color::rgb(1.0, 0.0, 1.0), 0.25)), ..AlphaChannel::new("PANTONE X", channel(depth, 8)) });
+ d.quick_mask = Some(AlphaChannel::new("Quick Mask", channel(depth, 12)));
+ let (back, warnings) = psd_to_document(&document_to_psd(&d));
+ assert!(warnings.is_empty(), "{warnings:?}");
+ assert_eq!(back.channels.len(), 2, "{depth:?}");
+ let (a, s) = (&back.channels[0], &back.channels[1]);
+ assert_eq!((a.name.as_str(), a.color, a.indicates), ("Alpha 1", Color::rgb(0.0, 0.0, 1.0), ColorIndicates::SelectedAreas));
+ assert!((a.opacity - 0.7).abs() < 1e-6);
+ assert_eq!(a.surface.sample_channel(2, 2, 0), 1.0);
+ assert_eq!(a.surface.sample_channel(6, 2, 0), 0.0);
+ assert_eq!(s.name, "PANTONE X");
+ assert_eq!(s.spot, Some((Color::rgb(1.0, 0.0, 1.0), 0.25)));
+ let q = back.quick_mask.as_ref().expect("quick mask restored");
+ assert_eq!(q.surface.sample_channel(10, 2, 0), 1.0);
+ assert_eq!(q.surface.sample_channel(14, 2, 0), 0.0);
+ // Re-exporting doesn't duplicate the display-info resources.
+ let f2 = document_to_psd(&back);
+ assert_eq!(f2.resources.iter().filter(|r| r.id == 1077).count(), 1);
+ assert_eq!(f2.resources.iter().filter(|r| r.id == 1022).count(), 1);
+ }
+}
diff --git a/crates/io/tests/color.rs b/crates/io/tests/color.rs
new file mode 100644
index 000000000..958498cad
--- /dev/null
+++ b/crates/io/tests/color.rs
@@ -0,0 +1,85 @@
+//! ICC profiles through import/export: byte-exact PSD round trips with real profiles, PNG/JPEG
+//! embedding and extraction, colour-managed CMYK → RGB for formats without CMYK.
+
+mod common;
+
+use std::sync::Arc;
+
+use common::*;
+use photocraft_cms::{Builtin, ColorSpace, Profile};
+use photocraft_color::{ColorMode, SampleType};
+use photocraft_io::*;
+
+fn single(mode: ColorMode, depth: SampleType, alpha: bool) -> photocraft_doc::Document {
+ let mut d = photocraft_doc::Document::new("s", photocraft_geom::Size::new(9, 6), mode, depth);
+ let fmt = d.pixel_format();
+ d.layers.push(raster("Background", fmt, d.bounds(), 3, alpha));
+ d
+}
+
+fn real_profiles() -> Vec<Vec<u8>> {
+ let mut v: Vec<Vec<u8>> = Builtin::ALL.iter().map(|b| b.profile().to_bytes().to_vec()).collect();
+ for p in ["/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc", "/System/Library/ColorSync/Profiles/AdobeRGB1998.icc"] {
+ if let Ok(b) = std::fs::read(p) {
+ v.push(b);
+ }
+ }
+ v
+}
+
+#[test]
+fn psd_icc_roundtrip_byte_exact() {
+ for icc in real_profiles() {
+ let p = Profile::parse(&icc).unwrap();
+ let mode = match p.color_space {
+ ColorSpace::Cmyk => ColorMode::Cmyk,
+ ColorSpace::Gray => ColorMode::Grayscale,
+ ColorSpace::Lab => ColorMode::Lab,
+ _ => ColorMode::Rgb,
+ };
+ let mut d = gen_doc(mode, SampleType::U8, Features::PIXELS);
+ d.icc_profile = Some(Arc::new(icc.clone()));
+ let r = export(&d, "x.psd", &ExportOptions::default()).unwrap();
+ let back = import("x.psd", &r.bytes).unwrap().document;
+ assert_eq!(back.icc_profile.as_deref(), Some(&icc), "{}", p.description);
+ }
+}
+
+#[test]
+fn png_and_jpeg_embed_and_extract_icc() {
+ for b in [Builtin::Srgb, Builtin::DisplayP3, Builtin::AdobeRgbCompat, Builtin::ProPhotoCompat] {
+ let icc = b.profile().to_bytes().to_vec();
+ for (name, alpha) in [("x.png", true), ("x.jpg", false)] {
+ let mut d = single(ColorMode::Rgb, SampleType::U8, alpha);
+ d.icc_profile = Some(Arc::new(icc.clone()));
+ let r = export(&d, name, &ExportOptions::default()).unwrap();
+ let back = import(name, &r.bytes).unwrap().document;
+ assert_eq!(back.icc_profile.as_deref(), Some(&icc), "{b:?} {name}");
+ assert_eq!(Profile::parse(back.icc_profile.as_ref().unwrap()).unwrap().description, b.description());
+ }
+ }
+ // Gray PNG with a gray profile.
+ let icc = Builtin::GrayGamma22.profile().to_bytes().to_vec();
+ let mut d = single(ColorMode::Grayscale, SampleType::U16, false);
+ d.icc_profile = Some(Arc::new(icc.clone()));
+ let r = export(&d, "g.png", &ExportOptions::default()).unwrap();
+ assert_eq!(import("g.png", &r.bytes).unwrap().document.icc_profile.as_deref(), Some(&icc));
+}
+
+#[test]
+fn cmyk_to_png_is_colour_managed_and_tagged_srgb() {
+ // Native single-layer CMYK document written to PNG: converted through the CMYK profile.
+ let mut d = single(ColorMode::Cmyk, SampleType::U8, false);
+ d.icc_profile = Some(Builtin::CoatedCmyk.profile().to_bytes());
+ let r = export(&d, "c.png", &ExportOptions::default()).unwrap();
+ assert!(r.warnings.iter().any(|w| w.contains("sRGB")), "{:?}", r.warnings);
+ let back = import("c.png", &r.bytes).unwrap().document;
+ assert_eq!(back.mode, ColorMode::Rgb);
+ let icc = back.icc_profile.expect("tagged");
+ assert_eq!(Profile::parse(&icc).unwrap().description, Builtin::Srgb.profile().description);
+ // Lab documents never write Lab numbers as RGB.
+ let d = single(ColorMode::Lab, SampleType::U8, false);
+ let r = export(&d, "l.png", &ExportOptions::default()).unwrap();
+ let back = import("l.png", &r.bytes).unwrap().document;
+ assert_eq!(Profile::parse(back.icc_profile.as_ref().unwrap()).unwrap().color_space, ColorSpace::Rgb);
+}
diff --git a/crates/io/tests/common/mod.rs b/crates/io/tests/common/mod.rs
index 6885bb73e..2bab8ee02 100644
--- a/crates/io/tests/common/mod.rs
+++ b/crates/io/tests/common/mod.rs
@@ -194,11 +194,7 @@ pub fn gen_doc(mode: ColorMode, depth: SampleType, f: Features) -> Document {
d.metadata.psd_resources.push((4000, String::new(), Arc::new(vec![9, 9, 9])));
d.guides.horizontal.push(5.5);
d.guides.vertical.push(12.0);
- d.channels.push(AlphaChannel {
- name: "Selection".into(),
- surface: mask_surface(depth, d.bounds(), 0.0, 3),
- spot: None,
- });
+ d.channels.push(AlphaChannel::new("Selection", mask_surface(depth, d.bounds(), 0.0, 3)));
}
d
}
diff --git a/crates/io/tests/composite.rs b/crates/io/tests/composite.rs
index 2795fc9f3..d5bb5e41b 100644
--- a/crates/io/tests/composite.rs
+++ b/crates/io/tests/composite.rs
@@ -15,7 +15,15 @@ fn check_export_oracle(d: &photocraft_doc::Document, tol: f32) {
let f = PsdFile::from_bytes(&r.bytes).unwrap();
let merged = merged_composite(&f).unwrap();
let d2 = import("x.psd", &r.bytes).unwrap().document;
- let ours = photocraft_compose::flatten(&d2).px;
+ let mut ours = photocraft_compose::flatten(&d2).px;
+ if d.mode == ColorMode::Cmyk {
+ // The merged CMYK image is the RGB composite separated through the CMYK profile, which
+ // gamut-maps colours that blend modes push outside CMYK: project ours the same way.
+ let fmt = d.pixel_format();
+ for p in &mut ours {
+ *p = photocraft_raster::to_rgba(&fmt, &photocraft_raster::from_rgba(&fmt, *p));
+ }
+ }
let m = max_diff(&ours, &merged);
assert!(m <= tol, "max diff {m} > {tol}");
}
@@ -34,8 +42,8 @@ oracle!(oracle_rgb16, ColorMode::Rgb, SampleType::U16, Features::ALL, TOL);
oracle!(oracle_rgb32, ColorMode::Rgb, SampleType::F32, Features::ALL, TOL);
oracle!(oracle_gray8, ColorMode::Grayscale, SampleType::U8, Features::ALL, TOL);
oracle!(oracle_gray16, ColorMode::Grayscale, SampleType::U16, Features::ALL, TOL);
-// CMYK/Lab merged data is converted naively from the RGB composite, so the
-// stored merged image differs by a quantization round trip through the model.
+// CMYK/Lab merged data is converted from the RGB composite (CMYK through the built-in
+// profile), so the stored merged image differs by a quantization round trip through the model.
oracle!(oracle_cmyk8, ColorMode::Cmyk, SampleType::U8, Features::PIXELS, 3.0 / 255.0);
// Lab: one 8-bit Lab quantization step is amplified up to ~15/255 near the sRGB gamut
// edge (the sRGB toe has slope 12.92), so the tolerance is wider.
diff --git a/crates/io/tests/modes.rs b/crates/io/tests/modes.rs
new file mode 100644
index 000000000..5d5d23e06
--- /dev/null
+++ b/crates/io/tests/modes.rs
@@ -0,0 +1,64 @@
+//! Indexed Color and Duotone documents in flat exports.
+
+use photocraft_color::{Color, ColorMode, SampleType};
+use photocraft_doc::{ColorTable, Document, Duotone, DuotoneInk, Size};
+
+fn doc(mode: ColorMode) -> Document {
+ let mut d = Document::with_background(
+ "m",
+ Size::new(4, 2),
+ ColorMode::Rgb,
+ SampleType::U8,
+ Color::rgba(1.0, 0.0, 0.0, 1.0),
+ );
+ d.mode = mode;
+ d
+}
+
+#[test]
+fn indexed_png_is_palette_png() {
+ let mut d = doc(ColorMode::Indexed);
+ d.color_table = Some(ColorTable {
+ colors: vec![[0, 0, 0], [255, 0, 0]],
+ transparent: None,
+ });
+ let r = photocraft_io::export(&d, "x.png", &Default::default()).unwrap();
+ // IHDR colour type 3 = indexed; a PLTE chunk follows.
+ assert_eq!(r.bytes[25], 3);
+ assert!(r.bytes.windows(4).any(|w| w == b"PLTE"));
+ let back = photocraft_io::import("x.png", &r.bytes).unwrap().document;
+ let px = back.layers[0].surface().unwrap().rgba(1, 1);
+ assert_eq!(&px[..3], &[1.0, 0.0, 0.0]);
+ // Other formats keep the expanded pixels.
+ let j = photocraft_io::export(&d, "x.tif", &Default::default()).unwrap();
+ assert!(!j.bytes.is_empty());
+}
+
+#[test]
+fn duotone_exports_the_inks_as_rgb() {
+ // Mid gray background.
+ let mut d = Document::with_background(
+ "m",
+ Size::new(4, 2),
+ ColorMode::Grayscale,
+ SampleType::U8,
+ Color::rgba(0.5, 0.5, 0.5, 1.0),
+ );
+ d.mode = ColorMode::Duotone;
+ d.duotone = Some(Duotone {
+ inks: vec![
+ DuotoneInk::new("Black", [0.0; 3]),
+ DuotoneInk::new("Orange", [1.0, 0.5, 0.0]),
+ ],
+ psd_raw: None,
+ });
+ let r = photocraft_io::export(&d, "x.png", &Default::default()).unwrap();
+ assert!(
+ r.warnings.iter().any(|w| w.contains("Duotone")),
+ "{:?}",
+ r.warnings
+ );
+ let back = photocraft_io::import("x.png", &r.bytes).unwrap().document;
+ let px = back.layers[0].surface().unwrap().rgba(0, 0);
+ assert!(px[0] > px[2] + 0.05, "warm: {px:?}");
+}
diff --git a/crates/io/tests/psd_structure.rs b/crates/io/tests/psd_structure.rs
index 6d3fc62fe..b72cd8edd 100644
--- a/crates/io/tests/psd_structure.rs
+++ b/crates/io/tests/psd_structure.rs
@@ -353,11 +353,10 @@ fn guides_and_alpha_names_roundtrip() {
d.guides.horizontal = vec![1.0, 2.5];
d.guides.vertical = vec![7.03125];
for name in ["Spot \u{e9}", "Alpha 2"] {
- d.channels.push(photocraft_doc::AlphaChannel {
- name: name.into(),
- surface: photocraft_raster::Surface::new(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Grayscale, photocraft_color::SampleType::U8, false)),
- spot: None,
- });
+ d.channels.push(photocraft_doc::AlphaChannel::new(
+ name,
+ photocraft_raster::Surface::new(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Grayscale, photocraft_color::SampleType::U8, false)),
+ ));
}
let f = document_to_psd(&d);
// RGB + merged transparency (the empty document is transparent) + 2 alpha channels.
diff --git a/crates/io/tests/roundtrip.rs b/crates/io/tests/roundtrip.rs
index 9013c8ecf..63cb8cf87 100644
--- a/crates/io/tests/roundtrip.rs
+++ b/crates/io/tests/roundtrip.rs
@@ -104,6 +104,10 @@ fn text_shape_smart_raw_blocks_survive() {
smart_filters: vec![],
cache: Some(cache.clone()),
psd_raw: Some(placed.clone()),
+ filters_enabled: true,
+ filter_mask: None,
+ warp: None,
+ stack_mode: None,
}),
);
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]))];
@@ -259,7 +263,7 @@ fn gradient_and_pattern_fills_roundtrip() {
reverse: true,
}),
));
- d.layers.push(Layer::new("pat", LayerContent::Fill(Fill::Pattern { name: "Dots".into(), scale: 0.5 })));
+ d.layers.push(Layer::new("pat", LayerContent::Fill(Fill::Pattern { name: "Dots".into(), scale: 0.5, id: String::new(), angle: 0.0, link: true, phase: (0.0, 0.0) })));
let back = roundtrip(&d);
assert_docs_eq(&d, &back);
}
diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs
index 328803175..ba7aacebf 100644
--- a/crates/ops/src/lib.rs
+++ b/crates/ops/src/lib.rs
@@ -95,6 +95,13 @@ impl History {
self.undo.len()
}
+ /// Forget the most recent undo state and every redo state (Edit › Purge › Undo): the
+ /// last step can no longer be undone and its pixels are released.
+ pub fn purge_last(&mut self) -> bool {
+ self.redo.clear();
+ self.undo.pop_back().is_some()
+ }
+
pub fn clear(&mut self) {
self.undo.clear();
self.redo.clear();
diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml
index 3fd02797e..afb9a196d 100644
--- a/crates/paint/Cargo.toml
+++ b/crates/paint/Cargo.toml
@@ -12,3 +12,6 @@ photocraft-geom = { workspace = true }
photocraft-color = { workspace = true }
photocraft-raster = { workspace = true }
serde = { workspace = true }
+
+[dev-dependencies]
+serde_json = { workspace = true }
diff --git a/crates/paint/examples/bench_brush.rs b/crates/paint/examples/bench_brush.rs
new file mode 100644
index 000000000..205af05cc
--- /dev/null
+++ b/crates/paint/examples/bench_brush.rs
@@ -0,0 +1,72 @@
+//! Brush engine benchmark: a 500-point stroke with a 200 px textured, scattered brush on a
+//! 6016×6016 RGBA8 layer, fed in 16-point chunks (as interactive painting would), compositing the
+//! dirty tiles after each chunk.
+//!
+//! `cargo run --release -p photocraft-paint --example bench_brush`
+
+use std::time::Instant;
+
+use photocraft_color::{PixelFormat, SampleType};
+use photocraft_geom::Rect;
+use photocraft_paint::*;
+use photocraft_raster::Surface;
+
+fn run(fmt: PixelFormat, label: &str, brush: &BrushSettings) {
+ let n = 6016;
+ let mut s = Surface::with_default(fmt, &photocraft_raster::from_rgba(&fmt, [1.0; 4]));
+ // Materialise the layer like a real photo layer.
+ s.fill_rect(Rect::new(0, 0, n, n), &photocraft_raster::from_rgba(&fmt, [0.8, 0.7, 0.6, 1.0]));
+ let pts: Vec<StrokePoint> = (0..500)
+ .map(|i| {
+ let t = i as f64 / 499.0;
+ StrokePoint { time: i as f64 * 8.0, ..StrokePoint::new(300.0 + t * 5400.0, 3000.0 + (t * 12.0).sin() * 2000.0, 0.6 + 0.4 * (t * 30.0).sin().abs() as f32) }
+ })
+ .collect();
+ let pre = s.clone();
+ let start = Instant::now();
+ let mut r = StrokeRenderer::new(brush, Some(fmt), 1.0);
+ let mut worst = 0.0f64;
+ let mut chunks = 0;
+ let (mut t_push, mut t_comp) = (0.0f64, 0.0f64);
+ for ch in pts.chunks(16) {
+ let t = Instant::now();
+ r.push(ch);
+ let tp = t.elapsed().as_secs_f64() * 1000.0;
+ r.composite(&pre, &mut s, None, false, false);
+ let tt = t.elapsed().as_secs_f64() * 1000.0;
+ t_push += tp;
+ t_comp += tt - tp;
+ worst = worst.max(tt);
+ chunks += 1;
+ }
+ r.finish();
+ r.composite(&pre, &mut s, None, false, false);
+ let total = start.elapsed().as_secs_f64() * 1000.0;
+ println!(
+ "{label:<34} dabs {:>5} total {total:>7.1} ms (dabs {t_push:>6.1}, composite {t_comp:>6.1}) mean/chunk {:>6.2} ms worst/chunk {worst:>6.2} ms",
+ r.dab_count(),
+ total / chunks as f64
+ );
+}
+
+fn main() {
+ let brush = BrushSettings {
+ size: 200.0,
+ hardness: 0.5,
+ spacing: 0.25,
+ pressure_size: false,
+ seed: 1,
+ shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic::jitter(0.3), angle: Dynamic::jitter(1.0), ..Default::default() },
+ scattering: Scattering { enabled: true, scatter: Dynamic::jitter(1.0), both_axes: true, count: 2, ..Default::default() },
+ texture: Texture { enabled: true, depth: 0.7, ..Default::default() },
+ ..Default::default()
+ };
+ let rgba8 = PixelFormat::RGBA8;
+ run(rgba8, "RGBA8 textured+scattered 200px", &brush);
+ run(rgba8, "RGBA8 per-tip texture", &BrushSettings { texture: Texture { each_tip: true, ..brush.texture.clone() }, ..brush.clone() });
+ let chalk = presets::find(&presets::builtin(), "Chalk").unwrap().brush.clone();
+ run(rgba8, "RGBA8 Chalk (sampled) 200px", &BrushSettings { size: 200.0, ..chalk });
+ run(rgba8.with_sample(SampleType::U16), "RGBA16 textured+scattered", &brush);
+ run(PixelFormat::RGBA32F, "RGBA32F textured+scattered", &brush);
+ run(PixelFormat::CMYKA8, "CMYKA8 textured+scattered", &brush);
+}
diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs
new file mode 100644
index 000000000..c9f3abd49
--- /dev/null
+++ b/crates/paint/src/brush_tests.rs
@@ -0,0 +1,581 @@
+//! Brush-engine tests: tips, spacing, dynamics, masks, smoothing, determinism, formats.
+
+use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};
+use photocraft_geom::{Point, Rect};
+use photocraft_raster::Surface;
+
+use crate::brush::*;
+use crate::dynamics::{Smoother, smooth_points};
+use crate::render::{BrushContext, StrokeRenderer, mask_combine, render_stroke};
+use crate::tile::GrayTile;
+use crate::{Dab, Stroke, StrokePoint, dabs};
+
+fn brush() -> BrushSettings {
+ BrushSettings { pressure_size: false, spacing: 0.25, ..Default::default() }
+}
+
+fn line(x0: f64, x1: f64, y: f64) -> Vec<StrokePoint> {
+ vec![StrokePoint::new(x0, y, 1.0), StrokePoint::new(x1, y, 1.0)]
+}
+
+fn dabs_of(b: &BrushSettings, pts: &[StrokePoint]) -> Vec<Dab> {
+ dabs(&Stroke { brush: b.clone(), points: pts.to_vec() })
+}
+
+fn raster(b: &BrushSettings, d: &Dab) -> (Rect, Vec<f32>) {
+ let ctx = BrushContext::new(b);
+ let r = ctx.dab_rect(d, false);
+ let mut v = Vec::new();
+ ctx.rasterize(d, false, r, &mut v);
+ (r, v)
+}
+
+fn at(r: &(Rect, Vec<f32>), x: i32, y: i32) -> f32 {
+ r.1[((y - r.0.y0) * r.0.width() as i32 + (x - r.0.x0)) as usize]
+}
+
+fn paint(b: &BrushSettings, pts: &[StrokePoint], w: i32, h: i32) -> Surface {
+ let mut s = Surface::new(PixelFormat::RGBA32F);
+ let _ = w + h;
+ render_stroke(&mut s, b, pts, None, false, 1.0);
+ s
+}
+
+fn alpha_sum(s: &Surface, r: Rect) -> f32 {
+ let mut t = 0.0;
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ t += s.rgba(x, y)[3];
+ }
+ }
+ t
+}
+
+// ---------- tips ----------
+
+#[test]
+fn round_tip_roundness_and_angle() {
+ let b = brush();
+ let mut d = Dab::round(Point::new(50.0, 50.0), 20.0, 1.0);
+ d.roundness = 0.25;
+ let r = raster(&b, &d);
+ // Wide along x, thin along y.
+ assert!(at(&r, 50 + 15, 50) > 0.99);
+ assert!(at(&r, 50, 50 + 8) < 0.01);
+ assert!(at(&r, 50, 50 + 3) > 0.99);
+ // Rotated 90° counter-clockwise: now tall.
+ d.angle = std::f32::consts::FRAC_PI_2;
+ let r = raster(&b, &d);
+ assert!(at(&r, 50, 50 - 15) > 0.99);
+ assert!(at(&r, 50 + 8, 50) < 0.01);
+ // 45°: the long axis runs up-right (y-down image space: x+, y−).
+ d.angle = std::f32::consts::FRAC_PI_4;
+ let r = raster(&b, &d);
+ assert!(at(&r, 60, 40) > 0.99, "{}", at(&r, 60, 40));
+ assert!(at(&r, 60, 60) < 0.01);
+}
+
+#[test]
+fn hardness_profile_is_monotonic() {
+ for h in [0.0f32, 0.5, 1.0] {
+ let b = BrushSettings { hardness: h, ..brush() };
+ let r = raster(&b, &Dab::round(Point::new(50.0, 50.0), 20.0, 1.0));
+ let prof: Vec<f32> = (0..22).map(|i| at(&r, 50 + i, 50)).collect();
+ assert!(prof.windows(2).all(|w| w[1] <= w[0] + 1e-6), "h={h} {prof:?}");
+ assert!(prof[0] > 0.99);
+ assert_eq!(prof[21], 0.0);
+ let mid = at(&r, 60, 50);
+ if h == 1.0 {
+ assert!(mid > 0.99);
+ } else if h == 0.0 {
+ assert!(mid > 0.2 && mid < 0.8, "{mid}");
+ }
+ }
+}
+
+#[test]
+fn sampled_tip_is_scaled_and_oriented() {
+ // Tip: left half painted.
+ let tip = GrayTile::from_fn(16, 16, |x, _| if x < 8 { 1.0 } else { 0.0 });
+ let b = BrushSettings { tip: TipShape::Sampled(tip), ..brush() };
+ let d = Dab::round(Point::new(50.0, 50.0), 20.0, 1.0);
+ let r = raster(&b, &d);
+ assert!(at(&r, 40, 50) > 0.99 && at(&r, 60, 50) < 0.01);
+ // Flip X mirrors it.
+ let r = raster(&b, &Dab { flip_x: true, ..d });
+ assert!(at(&r, 40, 50) < 0.01 && at(&r, 60, 50) > 0.99);
+ // Rotated 90° CCW: the painted (left) half moves to the bottom.
+ let r = raster(&b, &Dab { angle: std::f32::consts::FRAC_PI_2, ..d });
+ assert!(at(&r, 50, 60) > 0.99 && at(&r, 50, 40) < 0.01);
+ // Heavily downscaled uses mips: still sensible coverage.
+ let r = raster(&b, &Dab::round(Point::new(50.0, 50.0), 2.0, 1.0));
+ assert!(r.1.iter().sum::<f32>() > 1.0);
+}
+
+#[test]
+fn pencil_is_aliased() {
+ let b = BrushSettings { aliased: true, hardness: 0.0, size: 9.0, ..brush() };
+ let s = paint(&b, &line(10.0, 50.0, 20.5), 64, 40);
+ for y in 10..32 {
+ for x in 0..64 {
+ let a = s.rgba(x, y)[3];
+ assert!(a == 0.0 || a == 1.0, "({x},{y}) = {a}");
+ }
+ }
+ assert_eq!(s.rgba(30, 20)[3], 1.0);
+ // Anti-aliased brush has partial pixels.
+ let s = paint(&BrushSettings { aliased: false, ..b }, &line(10.0, 50.0, 20.3), 64, 40);
+ assert!((10..32).any(|y| (0..64).any(|x| (0.01..0.99).contains(&s.rgba(x, y)[3]))));
+}
+
+// ---------- spacing ----------
+
+#[test]
+fn spacing_sets_dab_count() {
+ for (spacing, len, expect) in [(0.25f32, 100.0, 21usize), (1.0, 100.0, 6), (0.5, 200.0, 21)] {
+ let b = BrushSettings { spacing, size: 20.0, ..brush() };
+ assert_eq!(dabs_of(&b, &line(0.0, len, 0.0)).len(), expect, "spacing {spacing}");
+ }
+ // Spacing carries across segments: a polyline gives the same count as the straight line.
+ let b = BrushSettings { spacing: 0.5, size: 20.0, ..brush() };
+ let pts: Vec<StrokePoint> = (0..=20).map(|i| StrokePoint::new(i as f64 * 10.0, 0.0, 1.0)).collect();
+ assert_eq!(dabs_of(&b, &pts).len(), 21);
+ let d = dabs_of(&b, &pts);
+ assert!(d.windows(2).all(|w| ((w[1].center.x - w[0].center.x) - 10.0).abs() < 1e-6));
+}
+
+// ---------- dynamics ----------
+
+#[test]
+fn pressure_controls_size_with_minimum() {
+ let b = BrushSettings {
+ size: 40.0,
+ shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic { control: Control::PenPressure, minimum: 0.25, ..Default::default() }, ..Default::default() },
+ ..brush()
+ };
+ let pts = vec![StrokePoint::new(0.0, 0.0, 0.0), StrokePoint::new(200.0, 0.0, 1.0)];
+ let d = dabs_of(&b, &pts);
+ assert!((d[0].radius - 5.0).abs() < 1e-3, "min diameter 25 % of 40 → r 5, got {}", d[0].radius);
+ assert!((d.last().unwrap().radius - 20.0).abs() < 0.5);
+ assert!(d.windows(2).all(|w| w[1].radius >= w[0].radius - 1e-4));
+}
+
+#[test]
+fn fade_ramps_over_steps() {
+ let b = BrushSettings {
+ size: 20.0,
+ spacing: 0.5,
+ shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic { control: Control::Fade, fade_steps: 10, minimum: 0.0, ..Default::default() }, ..Default::default() },
+ ..brush()
+ };
+ let d = dabs_of(&b, &line(0.0, 300.0, 0.0));
+ assert!((d[0].radius - 10.0).abs() < 1e-3);
+ assert!(d[5].radius < d[0].radius * 0.6, "{}", d[5].radius);
+ assert!(d.iter().skip(10).all(|x| x.radius <= 0.5 + 1e-6));
+ // Fade on opacity (Transfer).
+ let b = BrushSettings { transfer: Transfer { enabled: true, opacity: Dynamic { control: Control::Fade, fade_steps: 4, ..Default::default() }, ..Default::default() }, ..brush() };
+ let d = dabs_of(&b, &line(0.0, 100.0, 0.0));
+ assert_eq!(d[0].opacity, 1.0);
+ assert_eq!(d[4].opacity, 0.0);
+}
+
+#[test]
+fn tilt_direction_and_rotation_drive_angle() {
+ let mk = |c: Control| BrushSettings { shape_dynamics: ShapeDynamics { enabled: true, angle: Dynamic::controlled(c), ..Default::default() }, ..brush() };
+ let mut p = StrokePoint::new(0.0, 0.0, 1.0);
+ p.tilt_x = 0.0;
+ p.tilt_y = -45.0; // pen leaning "up" the screen
+ let pts = vec![p, StrokePoint { x: 50.0, ..p }];
+ let d = dabs_of(&mk(Control::PenTilt), &pts);
+ assert!((d[0].angle.to_degrees() - 90.0).abs() < 1e-3, "{}", d[0].angle.to_degrees());
+ // Direction: travelling down the screen = -90° (counter-clockwise positive).
+ let pts = vec![StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(0.0, 50.0, 1.0)];
+ let d = dabs_of(&mk(Control::Direction), &pts);
+ assert!(d.iter().all(|x| (x.angle.to_degrees() + 90.0).abs() < 1e-3));
+ // Rotation.
+ let mut q = StrokePoint::new(0.0, 0.0, 1.0);
+ q.rotation = 30.0;
+ let d = dabs_of(&mk(Control::Rotation), &[q, StrokePoint { x: 20.0, ..q }]);
+ assert!((d[0].angle.to_degrees() - 30.0).abs() < 1e-3);
+ // Pen tilt on size: upright pen full size, flat pen minimum.
+ let b = BrushSettings { shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic::controlled(Control::PenTilt), ..Default::default() }, size: 20.0, ..brush() };
+ let mut flat = StrokePoint::new(0.0, 0.0, 1.0);
+ flat.tilt_x = 90.0;
+ let d = dabs_of(&b, &[flat]);
+ assert!(d[0].radius <= 0.5 + 1e-6);
+}
+
+#[test]
+fn jitter_is_deterministic_per_seed() {
+ let b = BrushSettings {
+ size: 30.0,
+ seed: 42,
+ shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic::jitter(1.0), angle: Dynamic::jitter(1.0), roundness: Dynamic { jitter: 1.0, minimum: 0.2, ..Default::default() }, flip_x_jitter: true, flip_y_jitter: true },
+ scattering: Scattering { enabled: true, scatter: Dynamic::jitter(2.0), both_axes: true, count: 3, count_jitter: Dynamic::jitter(1.0) },
+ ..brush()
+ };
+ let pts = line(0.0, 300.0, 50.0);
+ let a = dabs_of(&b, &pts);
+ assert_eq!(a, dabs_of(&b, &pts));
+ let c = dabs_of(&BrushSettings { seed: 43, ..b.clone() }, &pts);
+ assert_ne!(a, c);
+ // Jitter actually varies things, within their ranges.
+ let radii: Vec<f32> = a.iter().map(|d| d.radius).collect();
+ assert!(radii.iter().any(|&r| r < 10.0) && radii.iter().all(|&r| r <= 15.0 + 1e-4));
+ assert!(a.iter().all(|d| d.roundness >= 0.2 - 1e-6 && d.roundness <= 1.0));
+ assert!(a.iter().any(|d| d.flip_x) && a.iter().any(|d| !d.flip_x));
+ // Chunked feeding gives identical dabs.
+ let mut r = StrokeRenderer::new(&b, None, 1.0).record_dabs();
+ let many: Vec<StrokePoint> = (0..=30).map(|i| StrokePoint::new(i as f64 * 10.0, 50.0, 1.0)).collect();
+ for ch in many.chunks(4) {
+ r.push(ch);
+ }
+ r.finish();
+ assert_eq!(r.dabs(), dabs_of(&b, &many).as_slice());
+}
+
+#[test]
+fn scattering_stays_in_bounds() {
+ for both in [false, true] {
+ let b = BrushSettings {
+ size: 20.0,
+ scattering: Scattering { enabled: true, scatter: Dynamic::jitter(2.0), both_axes: both, count: 4, ..Default::default() },
+ ..brush()
+ };
+ let d = dabs_of(&b, &line(0.0, 400.0, 100.0));
+ // count 4 per spacing step (5 px) → 81 steps.
+ assert_eq!(d.len(), 81 * 4);
+ let max_off = 2.0 * 10.0;
+ assert!(d.iter().all(|x| (x.center.y - 100.0).abs() <= max_off + 1e-6));
+ assert!(d.iter().any(|x| (x.center.y - 100.0).abs() > max_off * 0.5), "scatter too small");
+ if !both {
+ // Perpendicular only: x stays on the spacing grid.
+ assert!(d.iter().all(|x| (x.center.x / 5.0 - (x.center.x / 5.0).round()).abs() < 1e-6));
+ } else {
+ assert!(d.iter().any(|x| (x.center.x / 5.0 - (x.center.x / 5.0).round()).abs() > 0.1));
+ }
+ }
+}
+
+#[test]
+fn color_dynamics_ranges() {
+ let base = BrushSettings { color: [1.0, 0.0, 0.0, 1.0], background: [0.0, 0.0, 1.0, 1.0], seed: 5, ..brush() };
+ // FG/BG jitter mixes between the two colours only.
+ let b = BrushSettings { color_dynamics: ColorDynamics { enabled: true, fg_bg: Dynamic::jitter(1.0), ..Default::default() }, ..base.clone() };
+ let d = dabs_of(&b, &line(0.0, 200.0, 0.0));
+ assert!(d.iter().all(|x| x.color[1].abs() < 1e-5 && (x.color[0] + x.color[2] - 1.0).abs() < 1e-3 || x.color[0].max(x.color[2]) >= 0.999));
+ assert!(d.iter().any(|x| x.color[2] > 0.5) && d.iter().any(|x| x.color[0] > 0.5));
+ // Hue jitter keeps saturation/brightness of a pure colour.
+ let b = BrushSettings { color_dynamics: ColorDynamics { enabled: true, hue_jitter: 1.0, ..Default::default() }, ..base.clone() };
+ let d = dabs_of(&b, &line(0.0, 200.0, 0.0));
+ for x in &d {
+ let mx = x.color[0].max(x.color[1]).max(x.color[2]);
+ let mn = x.color[0].min(x.color[1]).min(x.color[2]);
+ assert!((mx - 1.0).abs() < 1e-4 && mn.abs() < 1e-4, "{:?}", x.color);
+ }
+ assert!(d.iter().any(|x| x.color[1] > 0.5 || x.color[2] > 0.5));
+ // Purity -1 desaturates completely.
+ let b = BrushSettings { color_dynamics: ColorDynamics { enabled: true, purity: -1.0, ..Default::default() }, ..base.clone() };
+ let d = dabs_of(&b, &line(0.0, 20.0, 0.0));
+ assert!(d.iter().all(|x| (x.color[0] - x.color[1]).abs() < 1e-5 && (x.color[1] - x.color[2]).abs() < 1e-5));
+ // Per-stroke: one colour for all dabs.
+ let b = BrushSettings { color_dynamics: ColorDynamics { enabled: true, per_tip: false, hue_jitter: 1.0, ..Default::default() }, ..base.clone() };
+ let d = dabs_of(&b, &line(0.0, 200.0, 0.0));
+ assert!(d.windows(2).all(|w| w[0].color == w[1].color));
+ // Per-tip colours land in the pixels.
+ let b = BrushSettings { size: 10.0, spacing: 3.0, color_dynamics: ColorDynamics { enabled: true, fg_bg: Dynamic::jitter(1.0), ..Default::default() }, ..base };
+ let s = paint(&b, &line(10.0, 310.0, 20.0), 330, 40);
+ let colours: Vec<[f32; 4]> = (0..11).map(|i| s.rgba(10 + i * 30, 20)).collect();
+ assert!(colours.iter().any(|c| c[2] > 0.6) && colours.iter().any(|c| c[0] > 0.6), "{colours:?}");
+}
+
+#[test]
+fn transfer_opacity_caps_and_flow_builds() {
+ // Pressure on opacity caps coverage.
+ let b = BrushSettings { transfer: Transfer { enabled: true, opacity: Dynamic::controlled(Control::PenPressure), ..Default::default() }, size: 10.0, ..brush() };
+ let pts = vec![StrokePoint::new(10.0, 10.0, 0.4), StrokePoint::new(90.0, 10.0, 0.4)];
+ let s = paint(&b, &pts, 100, 20);
+ assert!((s.rgba(50, 10)[3] - 0.4).abs() < 0.01, "{}", s.rgba(50, 10)[3]);
+ // Low flow builds up with overlap but never past the opacity.
+ let b = BrushSettings { flow: 0.1, opacity: 0.8, size: 10.0, ..brush() };
+ let one = paint(&b, &[StrokePoint::new(50.0, 10.0, 1.0)], 100, 20).rgba(50, 10)[3];
+ let many = paint(&b, &line(40.0, 60.0, 10.0), 100, 20).rgba(50, 10)[3];
+ assert!((one - 0.08).abs() < 0.01, "{one}");
+ assert!(many > one * 3.0 && many <= 0.8 + 1e-4, "{many}");
+ // Flow jitter varies the dab alpha deterministically.
+ let b = BrushSettings { transfer: Transfer { enabled: true, flow: Dynamic::jitter(1.0), ..Default::default() }, ..brush() };
+ let d = dabs_of(&b, &line(0.0, 100.0, 0.0));
+ assert!(d.iter().any(|x| x.alpha < 0.5) && d.iter().all(|x| x.alpha <= 1.0));
+}
+
+#[test]
+fn build_up_accumulates_over_time() {
+ let b = BrushSettings { build_up: true, build_up_rate: 20.0, flow: 0.05, size: 20.0, hardness: 1.0, ..brush() };
+ let hold = |ms: f64| {
+ let mut a = StrokePoint::new(50.0, 50.0, 1.0);
+ let mut z = a;
+ a.time = 0.0;
+ z.time = ms;
+ let s = paint(&b, &[a, z], 100, 100);
+ (dabs_of(&b, &[a, z]).len(), s.rgba(50, 50)[3])
+ };
+ let (n0, a0) = hold(0.0);
+ let (n1, a1) = hold(500.0);
+ let (n2, a2) = hold(2000.0);
+ assert_eq!((n0, n1, n2), (1, 11, 41));
+ assert!(a0 < a1 && a1 < a2, "{a0} {a1} {a2}");
+ // Without build-up, lingering adds nothing.
+ let nb = BrushSettings { build_up: false, ..b };
+ let mut a = StrokePoint::new(50.0, 50.0, 1.0);
+ let z = StrokePoint { time: 2000.0, ..a };
+ a.time = 0.0;
+ assert_eq!(dabs_of(&nb, &[a, z]).len(), 1);
+}
+
+#[test]
+fn texture_modulates_coverage() {
+ let tile = GrayTile::from_fn(8, 8, |x, _| if x < 4 { 1.0 } else { 0.0 });
+ let tex = |mode: MaskMode, depth: f32, each_tip: bool| BrushSettings {
+ size: 40.0,
+ texture: Texture { enabled: true, pattern: Pattern::Tile(tile.clone()), mode, depth, each_tip, ..Default::default() },
+ ..brush()
+ };
+ for each_tip in [false, true] {
+ let s = paint(&tex(MaskMode::Multiply, 1.0, each_tip), &line(20.0, 80.0, 30.0), 100, 60);
+ assert!(s.rgba(46, 30)[3] < 0.1, "dark texel blocks paint");
+ assert!(s.rgba(41, 30)[3] > 0.9, "light texel passes");
+ let half = paint(&tex(MaskMode::Multiply, 0.5, each_tip), &line(20.0, 80.0, 30.0), 100, 60);
+ let v = half.rgba(46, 30)[3];
+ if each_tip {
+ // Per-tip texturing builds up across overlapping dabs.
+ assert!(v > 0.5 && v < 1.0, "{v}");
+ } else {
+ assert!((v - 0.5).abs() < 0.02, "{v}");
+ }
+ }
+ // Brightness and invert.
+ let mut b = tex(MaskMode::Multiply, 1.0, false);
+ b.texture.invert = true;
+ let s = paint(&b, &line(20.0, 80.0, 30.0), 100, 60);
+ assert!(s.rgba(46, 30)[3] > 0.9 && s.rgba(41, 30)[3] < 0.1);
+ b.texture.invert = false;
+ b.texture.brightness = 1.0;
+ let s = paint(&b, &line(20.0, 80.0, 30.0), 100, 60);
+ assert!(s.rgba(46, 30)[3] > 0.9);
+ // All modes keep zero coverage at zero and stay in range.
+ for m in [MaskMode::Multiply, MaskMode::Subtract, MaskMode::Darken, MaskMode::Overlay, MaskMode::ColorDodge, MaskMode::ColorBurn, MaskMode::LinearBurn, MaskMode::HardMix, MaskMode::LinearHeight, MaskMode::Height] {
+ for t in [0.0, 0.3, 1.0] {
+ assert_eq!(mask_combine(m, 0.0, t, 1.0), 0.0, "{m:?}");
+ let v = mask_combine(m, 0.7, t, 0.8);
+ assert!((0.0..=1.0).contains(&v), "{m:?}");
+ }
+ // Full-white texture never reduces multiply-like masks below the brush.
+ assert!(mask_combine(m, 0.6, 1.0, 1.0) >= 0.6 - 1e-5 || matches!(m, MaskMode::Overlay), "{m:?}");
+ }
+ // Depth jitter per tip is deterministic and within [min depth, depth].
+ let mut b = tex(MaskMode::Multiply, 0.8, true);
+ b.texture.depth_jitter = Dynamic { jitter: 1.0, minimum: 0.25, ..Default::default() };
+ let d = dabs_of(&b, &line(0.0, 200.0, 0.0));
+ assert!(d.iter().all(|x| x.depth <= 0.8 + 1e-6 && x.depth >= 0.8 * 0.25 - 1e-6));
+ assert!(d.iter().any(|x| x.depth < 0.6));
+}
+
+#[test]
+fn dual_brush_intersects() {
+ // Dual tip: small dabs far apart → the stroke survives only where they land.
+ let b = BrushSettings {
+ size: 30.0,
+ dual_brush: DualBrush { enabled: true, size: 6.0, spacing: 5.0, hardness: 1.0, ..Default::default() },
+ ..brush()
+ };
+ let s = paint(&b, &line(20.0, 200.0, 30.0), 220, 60);
+ // Dual dabs every 30 px starting at x = 20.
+ assert!(s.rgba(20, 30)[3] > 0.9 && s.rgba(50, 30)[3] > 0.9);
+ assert!(s.rgba(35, 30)[3] < 0.01, "between dual dabs: {}", s.rgba(35, 30)[3]);
+ // Outside the primary (y beyond its radius) nothing, even if dual covers.
+ assert_eq!(s.rgba(20, 50)[3], 0.0);
+ // Without dual, the stroke is continuous.
+ let s = paint(&BrushSettings { dual_brush: DualBrush::default(), ..b }, &line(20.0, 200.0, 30.0), 220, 60);
+ assert!(s.rgba(35, 30)[3] > 0.9);
+}
+
+#[test]
+fn wet_edges_and_noise() {
+ let b = BrushSettings { size: 40.0, hardness: 0.0, wet_edges: true, ..brush() };
+ let s = paint(&b, &line(20.0, 120.0, 50.0), 140, 100);
+ let centre = s.rgba(70, 50)[3];
+ assert!(centre < 0.6, "wet interior is lighter: {centre}");
+ // Overlap doesn't build up past a single dab.
+ let single = paint(&b, &[StrokePoint::new(70.0, 50.0, 1.0)], 140, 100).rgba(70, 50)[3];
+ assert!((centre - single).abs() < 0.05, "{centre} vs {single}");
+ // Rim is darker than the interior for a hard tip.
+ let hb = BrushSettings { hardness: 1.0, ..b };
+ let d = paint(&hb, &[StrokePoint::new(50.0, 50.0, 1.0)], 100, 100);
+ assert!(d.rgba(50 + 18, 50)[3] > d.rgba(50, 50)[3] + 0.2);
+ // Noise: soft tip coverage becomes grainy (more pixels near 0/1).
+ let soft = BrushSettings { size: 40.0, hardness: 0.0, ..brush() };
+ let a = paint(&soft, &[StrokePoint::new(50.0, 50.0, 1.0)], 100, 100);
+ let n = paint(&BrushSettings { noise: true, ..soft }, &[StrokePoint::new(50.0, 50.0, 1.0)], 100, 100);
+ let extreme = |s: &Surface| (30..70).flat_map(|y| (30..70).map(move |x| (x, y))).filter(|&(x, y)| {
+ let v = s.rgba(x, y)[3];
+ !(0.15..=0.85).contains(&v)
+ }).count();
+ assert!(extreme(&n) > extreme(&a) + 100, "{} vs {}", extreme(&n), extreme(&a));
+}
+
+#[test]
+fn smoothing_modes() {
+ let zig: Vec<StrokePoint> = (0..40).map(|i| StrokePoint::new(i as f64 * 5.0, if i % 2 == 0 { 0.0 } else { 6.0 }, 1.0)).collect();
+ let dev = |pts: &[StrokePoint]| pts.iter().map(|p| (p.y - 3.0).abs()).sum::<f64>() / pts.len() as f64;
+ // Exponential smoothing reduces the zig-zag.
+ let cfg = Smoothing { amount: 0.8, ..Default::default() };
+ let sm = smooth_points(&cfg, 1.0, &zig);
+ assert!(dev(&sm[5..sm.len() - 1]) < dev(&zig) * 0.5);
+ // Catch-up on end finishes at the last input point; without it, the stroke ends short.
+ assert_eq!(sm.last().map(|p| (p.x, p.y)), zig.last().map(|p| (p.x, p.y)));
+ let no = smooth_points(&Smoothing { catch_up_on_end: false, ..cfg.clone() }, 1.0, &zig);
+ assert!(no.last().unwrap().x < zig.last().unwrap().x - 1.0);
+ // Pulled string: jitter smaller than the string moves nothing; the brush trails by the string.
+ let ps = Smoothing { amount: 0.2, pulled_string: true, catch_up_on_end: false, ..Default::default() };
+ let jitter: Vec<StrokePoint> = (0..20).map(|i| StrokePoint::new(if i % 2 == 0 { 0.0 } else { 5.0 }, 0.0, 1.0)).collect();
+ assert_eq!(smooth_points(&ps, 1.0, &jitter).len(), 1, "within the 20 px string: no motion");
+ let far = smooth_points(&ps, 1.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]);
+ assert!((far.last().unwrap().x - 80.0).abs() < 1e-4);
+ // Adjust for zoom: at 200 % zoom the string is half as long in image pixels.
+ let far = smooth_points(&ps, 2.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]);
+ assert!((far.last().unwrap().x - 90.0).abs() < 1e-4);
+ // Stroke catch-up: a pause (timestamps) lets the brush converge on the pointer.
+ let mut a = StrokePoint::new(0.0, 0.0, 1.0);
+ a.time = 0.0;
+ let b = StrokePoint { x: 100.0, time: 16.0, ..a };
+ let c = StrokePoint { time: 500.0, ..b };
+ let mut s = Smoother::new(&Smoothing { amount: 0.8, catch_up: true, catch_up_on_end: false, ..Default::default() }, 1.0);
+ let mut out = Vec::new();
+ for p in [a, b, c] {
+ s.push(p, &mut out);
+ }
+ assert!(out.last().unwrap().x > 99.0, "{}", out.last().unwrap().x);
+ let mut s = Smoother::new(&Smoothing { amount: 0.8, catch_up: false, catch_up_on_end: false, ..Default::default() }, 1.0);
+ let mut out = Vec::new();
+ for p in [a, b, c] {
+ s.push(p, &mut out);
+ }
+ assert!(out.last().unwrap().x < 70.0, "{}", out.last().unwrap().x);
+}
+
+#[test]
+fn pose_overrides_stylus_values() {
+ let b = BrushSettings {
+ size: 40.0,
+ pose: Pose { enabled: true, pressure: 0.5, override_pressure: true, ..Default::default() },
+ shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic::controlled(Control::PenPressure), ..Default::default() },
+ ..brush()
+ };
+ let d = dabs_of(&b, &line(0.0, 50.0, 0.0));
+ assert!(d.iter().all(|x| (x.radius - 10.0).abs() < 1e-4));
+}
+
+#[test]
+fn chunked_rendering_matches_one_shot() {
+ let b = BrushSettings {
+ size: 24.0,
+ seed: 9,
+ shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic::jitter(0.5), angle: Dynamic::jitter(1.0), ..Default::default() },
+ scattering: Scattering { enabled: true, scatter: Dynamic::jitter(1.0), both_axes: true, count: 2, ..Default::default() },
+ texture: Texture { enabled: true, depth: 0.5, ..Default::default() },
+ color_dynamics: ColorDynamics { enabled: true, hue_jitter: 0.5, ..Default::default() },
+ color: [1.0, 0.0, 0.0, 1.0],
+ ..brush()
+ };
+ let pts: Vec<StrokePoint> = (0..60).map(|i| StrokePoint::new(20.0 + i as f64 * 4.0, 60.0 + (i as f64 * 0.3).sin() * 30.0, 1.0)).collect();
+ let mut one = Surface::new(PixelFormat::RGBA8);
+ let d1 = render_stroke(&mut one, &b, &pts, None, false, 1.0);
+ let mut inc = Surface::new(PixelFormat::RGBA8);
+ let pre = inc.clone();
+ let mut r = StrokeRenderer::new(&b, Some(inc.format()), 1.0);
+ for ch in pts.chunks(7) {
+ r.push(ch);
+ r.composite(&pre, &mut inc, None, false, false);
+ }
+ r.finish();
+ r.composite(&pre, &mut inc, None, false, false);
+ assert_eq!(d1, r.bounds());
+ for y in d1.y0..d1.y1 {
+ for x in d1.x0..d1.x1 {
+ assert_eq!(one.pixel(x, y), inc.pixel(x, y), "({x},{y})");
+ }
+ }
+}
+
+#[test]
+fn paints_every_depth_and_model() {
+ let b = BrushSettings { size: 8.0, color: [1.0, 0.0, 0.0, 1.0], ..brush() };
+ for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk] {
+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for alpha in [true, false] {
+ let fmt = PixelFormat::new(mode, sample, alpha);
+ let mut s = Surface::with_default(fmt, &photocraft_raster::from_rgba(&fmt, [1.0, 1.0, 1.0, 1.0]));
+ let fancy = BrushSettings {
+ shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic::jitter(0.3), ..Default::default() },
+ color_dynamics: ColorDynamics { enabled: true, brightness_jitter: 0.1, ..Default::default() },
+ texture: Texture { enabled: true, depth: 0.2, ..Default::default() },
+ ..b.clone()
+ };
+ for br in [&b, &fancy] {
+ render_stroke(&mut s, br, &line(5.0, 40.0, 5.0), None, false, 1.0);
+ }
+ let c = s.rgba(20, 5);
+ let expect = photocraft_raster::to_rgba(&fmt, &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0]));
+ assert!((c[0] - expect[0]).abs() < 0.15 && (c[1] - expect[1]).abs() < 0.12, "{fmt:?} {c:?} vs {expect:?}");
+ assert_eq!(s.pixel(20, 30), s.pixel(5000, 5000), "{fmt:?} untouched");
+ }
+ }
+ }
+}
+
+#[test]
+fn blend_mode_and_dissolve() {
+ let mut s = Surface::new(PixelFormat::RGBA32F);
+ s.fill_rect(Rect::new(0, 0, 100, 20), &[0.5, 0.5, 0.5, 1.0]);
+ let b = BrushSettings { size: 10.0, color: [0.5, 0.5, 0.5, 1.0], mode: BlendMode::Multiply, ..brush() };
+ render_stroke(&mut s, &b, &line(10.0, 90.0, 10.0), None, false, 1.0);
+ assert!((s.rgba(50, 10)[0] - 0.25).abs() < 1e-4);
+ let mut s = Surface::new(PixelFormat::RGBA32F);
+ let b = BrushSettings { size: 30.0, opacity: 0.5, mode: BlendMode::Dissolve, ..brush() };
+ render_stroke(&mut s, &b, &line(20.0, 80.0, 20.0), None, false, 1.0);
+ let vals: Vec<f32> = (30..70).map(|x| s.rgba(x, 20)[3]).collect();
+ assert!(vals.iter().all(|&v| v == 0.0 || v == 1.0) && vals.contains(&0.0) && vals.contains(&1.0));
+}
+
+#[test]
+fn presets_render_and_round_trip() {
+ let presets = crate::presets::builtin();
+ assert!(presets.len() >= 12);
+ for p in &presets {
+ let j = serde_json::to_string(p).unwrap();
+ let back: BrushPreset = serde_json::from_str(&j).unwrap();
+ assert_eq!(&back, p, "{}", p.name);
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ let pts: Vec<StrokePoint> = (0..20).map(|i| StrokePoint { time: i as f64 * 16.0, ..StrokePoint::new(40.0 + i as f64 * 8.0, 60.0, 0.8) }).collect();
+ let dmg = render_stroke(&mut s, &p.brush, &pts, None, false, 1.0);
+ assert!(!dmg.is_empty(), "{}", p.name);
+ assert!(alpha_sum(&s, dmg) > 10.0, "{} painted nothing", p.name);
+ }
+ // Partial JSON fills defaults.
+ let b: BrushSettings = serde_json::from_str(r#"{"size": 50, "scattering": {"enabled": true, "scatter": {"jitter": 2}}, "pressure_size": false}"#).unwrap();
+ assert_eq!(b.size, 50.0);
+ assert!(b.scattering.enabled && b.scattering.count == 1 && !b.pressure_size);
+ assert_eq!(b.hardness, 1.0);
+}
+
+#[test]
+fn protect_texture_keeps_pattern() {
+ let presets = crate::presets::builtin();
+ let chalk = crate::presets::find(&presets, "chalk").unwrap().brush.clone();
+ let canvas = crate::presets::find(&presets, "Canvas Texture").unwrap().brush.clone();
+ let cur = BrushSettings { protect_texture: true, ..chalk.clone() };
+ let next = canvas.clone().with_protected_texture(&cur);
+ assert_eq!(next.texture.pattern, chalk.texture.pattern);
+ assert_eq!(next.texture.mode, canvas.texture.mode);
+ assert_eq!(canvas.clone().with_protected_texture(&chalk).texture.pattern, canvas.texture.pattern);
+}
diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs
index 45ca276cd..b1a48dbd2 100644
--- a/crates/paint/src/lib.rs
+++ b/crates/paint/src/lib.rs
@@ -1,58 +1,67 @@
-//! Brush engine v1: round dabs with hardness, spacing, pressure dynamics and stroke smoothing.
+//! Brush engine: Photoshop-grade brushes (computed and sampled tips, Shape Dynamics, Scattering,
+//! Texture, Dual Brush, Color Dynamics, Transfer, Brush Pose, Noise, Wet Edges, Build-up,
+//! Smoothing) plus the dab machinery shared by the retouching tools.
//!
//! Strokes are data ([`Stroke`]) so they can be recorded, replayed by automation, and tested
-//! deterministically. Dabs composite with "build-up up to stroke opacity" semantics: within one stroke,
-//! coverage accumulates with `max`, so overlapping dabs don't darken beyond the stroke's opacity
-//! (Photoshop's behaviour for Opacity, versus Flow which builds up).
+//! deterministically: every jitter is a hash of the brush seed and the dab index ([`rng`]).
+//! Dabs composite with "build-up up to stroke opacity" semantics: within one stroke, coverage
+//! accumulates with flow towards each dab's opacity ceiling, and the stroke composites once at the
+//! stroke opacity (Photoshop's Opacity versus Flow).
+//!
+//! Module map: [`brush`] (the serde model), [`dynamics`] (points → dabs), [`render`] (dabs →
+//! stroke buffer → pixels), [`presets`] (built-ins), [`mixer`] (Mixer Brush), [`replace`] (Color
+//! Replacement), [`retouch`] (sequential/accumulating helpers for the retouch tools).
#![forbid(unsafe_code)]
use photocraft_geom::{Point, Rect};
-use photocraft_raster::{Surface, to_rgba};
+use photocraft_raster::Surface;
use serde::{Deserialize, Serialize};
+pub mod brush;
+pub mod dynamics;
+pub mod mixer;
+pub mod presets;
+pub mod procedural;
+pub mod render;
+pub mod replace;
pub mod retouch;
+pub mod rng;
+pub mod tile;
+
+pub use brush::{
+ BrushPreset, BrushSettings, ColorDynamics, Control, DualBrush, Dynamic, MaskMode, Pattern, PatternStyle, Pose, Scattering, ShapeDynamics, Smoothing, Texture, TipShape, Transfer,
+};
+pub use render::{BrushContext, StrokeRenderer, render_stroke};
+pub use tile::GrayTile;
+/// One input sample. Missing stylus data defaults to "mouse": full pressure, no tilt/rotation.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
pub struct StrokePoint {
pub x: f64,
pub y: f64,
/// 0..1, 1 for mouse.
pub pressure: f32,
+ /// Degrees -90..90 (W3C Pointer Events `tiltX`/`tiltY`).
+ pub tilt_x: f32,
+ pub tilt_y: f32,
+ /// Barrel rotation in degrees 0..360.
+ pub rotation: f32,
+ /// Airbrush stylus wheel 0..1.
+ pub wheel: f32,
+ /// Timestamp in milliseconds (airbrush build-up and smoothing catch-up).
+ pub time: f64,
}
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct BrushSettings {
- /// Diameter in pixels.
- pub size: f32,
- /// 0 (soft) ..1 (hard).
- pub hardness: f32,
- /// Spacing between dabs as a fraction of the diameter.
- pub spacing: f32,
- /// Maximum coverage for the whole stroke.
- pub opacity: f32,
- /// Per-dab coverage.
- pub flow: f32,
- pub pressure_size: bool,
- pub pressure_opacity: bool,
- /// Straight RGBA colour (display RGB).
- pub color: [f32; 4],
- /// Erase instead of paint.
- pub erase: bool,
+impl Default for StrokePoint {
+ fn default() -> Self {
+ Self { x: 0.0, y: 0.0, pressure: 1.0, tilt_x: 0.0, tilt_y: 0.0, rotation: 0.0, wheel: 1.0, time: 0.0 }
+ }
}
-impl Default for BrushSettings {
- fn default() -> Self {
- Self {
- size: 20.0,
- hardness: 1.0,
- spacing: 0.1,
- opacity: 1.0,
- flow: 1.0,
- pressure_size: true,
- pressure_opacity: false,
- color: [0.0, 0.0, 0.0, 1.0],
- erase: false,
- }
+impl StrokePoint {
+ pub fn new(x: f64, y: f64, pressure: f32) -> Self {
+ Self { x, y, pressure, ..Default::default() }
}
}
@@ -62,48 +71,41 @@ pub struct Stroke {
pub points: Vec<StrokePoint>,
}
-/// A dab placed along the stroke.
+/// A dab placed along the stroke (after dynamics).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Dab {
pub center: Point,
pub radius: f32,
+ /// Flow: per-dab build-up amount.
pub alpha: f32,
+ /// Radians, counter-clockwise.
+ pub angle: f32,
+ pub roundness: f32,
+ pub flip_x: bool,
+ pub flip_y: bool,
+ /// Opacity ceiling this dab builds up to (Transfer › Opacity).
+ pub opacity: f32,
+ /// Straight RGBA paint colour (Color Dynamics).
+ pub color: [f32; 4],
+ /// Texture depth for per-tip texturing.
+ pub depth: f32,
+ /// Position in the stroke (0 = first).
+ pub index: u64,
}
-/// Place dabs along the polyline at `spacing × diameter` intervals, interpolating pressure.
-pub fn dabs(stroke: &Stroke) -> Vec<Dab> {
- let b = &stroke.brush;
- let mut out = Vec::new();
- let Some(first) = stroke.points.first() else { return out };
- let radius_at = |p: f32| {
- let s = if b.pressure_size { b.size * p.clamp(0.0, 1.0) } else { b.size };
- (s / 2.0).max(0.5)
- };
- let alpha_at = |p: f32| b.flow * if b.pressure_opacity { p.clamp(0.0, 1.0) } else { 1.0 };
- out.push(Dab { center: Point::new(first.x, first.y), radius: radius_at(first.pressure), alpha: alpha_at(first.pressure) });
- let mut carry = 0.0f64;
- for w in stroke.points.windows(2) {
- let (a, c) = (w[0], w[1]);
- let (dx, dy) = (c.x - a.x, c.y - a.y);
- let len = (dx * dx + dy * dy).sqrt();
- if len <= 0.0 {
- continue;
- }
- let mut t = carry;
- loop {
- let pr = a.pressure + (c.pressure - a.pressure) * (t / len) as f32;
- let step = (radius_at(pr) as f64 * 2.0 * b.spacing.max(0.01) as f64).max(0.5);
- t += step;
- if t > len {
- carry = t - len - step;
- carry = carry.max(0.0);
- break;
- }
- let f = t / len;
- let pr = a.pressure + (c.pressure - a.pressure) * f as f32;
- out.push(Dab { center: Point::new(a.x + dx * f, a.y + dy * f), radius: radius_at(pr), alpha: alpha_at(pr) });
- }
+impl Dab {
+ /// A plain round dab.
+ pub fn round(center: Point, radius: f32, alpha: f32) -> Self {
+ Self { center, radius, alpha, angle: 0.0, roundness: 1.0, flip_x: false, flip_y: false, opacity: 1.0, color: [0.0, 0.0, 0.0, 1.0], depth: 1.0, index: 0 }
}
+}
+
+/// All primary dabs of a stroke (smoothing, pose, spacing, build-up and dynamics applied).
+pub fn dabs(stroke: &Stroke) -> Vec<Dab> {
+ let mut g = dynamics::DabGenerator::new(&stroke.brush, 1.0);
+ let (mut out, mut dual) = (Vec::new(), Vec::new());
+ g.push(&stroke.points, &mut out, &mut dual);
+ g.finish(&mut out, &mut dual);
out
}
@@ -129,49 +131,7 @@ pub fn dab_coverage(d: f32, radius: f32, hardness: f32) -> f32 {
/// Rasterize a stroke onto `target`, optionally limited by a selection (grayscale coverage surface).
/// Returns the damaged rectangle.
pub fn apply_stroke(target: &mut Surface, stroke: &Stroke, selection: Option<&Surface>, lock_transparency: bool) -> Rect {
- let b = &stroke.brush;
- if stroke.points.is_empty() {
- return Rect::EMPTY;
- }
- // 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 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.sample_channel(x, y, 0));
- let k = (c * b.opacity * sel).min(1.0);
- if k <= 0.0 {
- continue;
- }
- let px = &mut region[i * n..(i + 1) * n];
- let dst = to_rgba(&fmt, px);
- let out = if b.erase {
- [dst[0], dst[1], dst[2], dst[3] * (1.0 - k)]
- } else {
- let sa = b.color[3] * k;
- let oa = sa + dst[3] * (1.0 - sa);
- let mut o = [0.0f32; 4];
- if oa > 0.0 {
- for ch in 0..3 {
- o[ch] = (b.color[ch] * sa + dst[ch] * dst[3] * (1.0 - sa)) / oa;
- }
- }
- o[3] = if lock_transparency { dst[3] } else { oa };
- if lock_transparency && dst[3] <= 0.0 {
- continue;
- }
- o
- };
- 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, &region);
- bounds
+ render_stroke(target, &stroke.brush, &stroke.points, selection, lock_transparency, 1.0)
}
/// Exponential moving-average smoothing of input points (Photoshop's "Smoothing" %, simplified).
@@ -182,7 +142,7 @@ pub fn smooth(points: &[StrokePoint], amount: f32) -> Vec<StrokePoint> {
for p in points {
let n = match cur {
None => *p,
- Some(c) => StrokePoint { x: c.x + (p.x - c.x) * a, y: c.y + (p.y - c.y) * a, pressure: p.pressure },
+ Some(c) => StrokePoint { x: c.x + (p.x - c.x) * a, y: c.y + (p.y - c.y) * a, ..*p },
};
out.push(n);
cur = Some(n);
@@ -201,7 +161,7 @@ mod tests {
fn stroke(points: &[(f64, f64)], size: f32) -> Stroke {
Stroke {
brush: BrushSettings { size, pressure_size: false, ..Default::default() },
- points: points.iter().map(|&(x, y)| StrokePoint { x, y, pressure: 1.0 }).collect(),
+ points: points.iter().map(|&(x, y)| StrokePoint::new(x, y, 1.0)).collect(),
}
}
@@ -285,7 +245,7 @@ mod tests {
#[test]
fn smoothing_keeps_endpoints() {
- let pts: Vec<StrokePoint> = (0..20).map(|i| StrokePoint { x: i as f64, y: if i % 2 == 0 { 0.0 } else { 10.0 }, pressure: 1.0 }).collect();
+ let pts: Vec<StrokePoint> = (0..20).map(|i| StrokePoint::new(i as f64, if i % 2 == 0 { 0.0 } else { 10.0 }, 1.0)).collect();
let s = smooth(&pts, 0.8);
assert_eq!(s.first(), pts.first());
assert_eq!(s.last(), pts.last());
@@ -306,3 +266,6 @@ mod tests {
}
}
}
+
+#[cfg(test)]
+mod brush_tests;
diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs
new file mode 100644
index 000000000..dcbc1acf5
--- /dev/null
+++ b/crates/paint/src/mixer.rs
@@ -0,0 +1,208 @@
+//! Mixer Brush: a reservoir of loaded paint plus a pickup well that mixes in canvas colour.
+//!
+//! Model (behavioural, our own): each dab samples the canvas colour under its footprint. The pickup
+//! colour `P` moves towards it by `wet`. The deposited colour mixes the reservoir `R` (weight
+//! `amount × (1 − mix·wet)`) with the pickup (weight `mix·wet`); it lands at `flow` times the total
+//! weight. The reservoir amount drains per dab unless `load` is 100 %, so low Load strokes dry out.
+//! A dry brush (`wet = 0`) paints only reservoir colour; an empty, wet brush smears canvas colour.
+
+use photocraft_raster::{Surface, from_rgba, to_rgba};
+use serde::{Deserialize, Serialize};
+
+use crate::Stroke;
+use crate::retouch::{alpha_index, apply_dab_stroke, over_native};
+use photocraft_geom::Rect;
+
+/// Fraction of the way the pickup colour moves towards the canvas colour per dab at 100 % Wet.
+pub const PICKUP_RATE: f32 = 0.25;
+
+/// Mixer Brush options (all 0..1).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct MixerSettings {
+ pub wet: f32,
+ pub load: f32,
+ pub mix: f32,
+ pub flow: f32,
+}
+
+impl Default for MixerSettings {
+ fn default() -> Self {
+ Self { wet: 0.5, load: 0.5, mix: 0.5, flow: 1.0 }
+ }
+}
+
+/// Paint carried between strokes (session tool state).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct MixerState {
+ /// Loaded paint (straight RGBA), None = clean/unloaded.
+ pub reservoir: Option<[f32; 4]>,
+ /// Remaining reservoir amount 0..1.
+ pub amount: f32,
+ /// Colour picked up from the canvas (straight RGBA), None = clean.
+ pub pickup: Option<[f32; 4]>,
+}
+
+impl MixerState {
+ /// Load the reservoir with a colour (full).
+ pub fn load(&mut self, color: [f32; 4]) {
+ self.reservoir = Some(color);
+ self.amount = 1.0;
+ }
+ /// Clean the brush (drop the picked-up colour).
+ pub fn clean(&mut self) {
+ self.pickup = None;
+ }
+}
+
+/// Paint a Mixer Brush stroke. `sample` is the surface colour is picked up from (the layer itself
+/// when None; a flattened composite for Sample All Layers). Returns the damaged rectangle.
+pub fn apply_mixer_stroke(
+ target: &mut Surface,
+ sample: Option<&Surface>,
+ stroke: &Stroke,
+ m: &MixerSettings,
+ state: &mut MixerState,
+ selection: Option<&Surface>,
+ lock_transparency: bool,
+) -> Rect {
+ let fmt = target.format();
+ let n = fmt.channels();
+ let a = alpha_index(&fmt);
+ let nc = fmt.mode.color_channels();
+ let native = |c: [f32; 4]| {
+ let mut v = from_rgba(&fmt, c);
+ if let Some(ai) = a {
+ v[ai] = 1.0;
+ }
+ v
+ };
+ let res = state.reservoir.map(native);
+ let mut amount = if res.is_some() { state.amount.clamp(0.0, 1.0) } else { 0.0 };
+ let mut pickup: Option<Vec<f32>> = state.pickup.map(native);
+ let (wet, mix, flow, load) = (m.wet.clamp(0.0, 1.0), m.mix.clamp(0.0, 1.0), m.flow.clamp(0.0, 1.0), m.load.clamp(0.0, 1.0));
+ let mut st = stroke.clone();
+ st.brush.opacity = 1.0;
+ let mut acc = vec![0.0f32; n];
+ let mut paint = vec![0.0f32; n];
+ let dmg = apply_dab_stroke(target, &st, selection, lock_transparency, 0, |work, fp| {
+ // Sample the canvas under the dab.
+ acc.iter_mut().for_each(|v| *v = 0.0);
+ let (mut wsum, mut asum) = (0.0f32, 0.0f32);
+ let r = fp.rect.intersect(&work.rect);
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ let w = fp.at(x, y);
+ if w <= 0.0 {
+ continue;
+ }
+ let px: Vec<f32> = match sample {
+ Some(s) => {
+ let v = s.pixel(x, y);
+ if s.format() == fmt { v } else { from_rgba(&fmt, s.rgba(x, y)) }
+ }
+ None => work.px(x, y).to_vec(),
+ };
+ let al = a.map_or(1.0, |ai| px[ai]);
+ for c in 0..nc {
+ acc[c] += px[c] * w * al;
+ }
+ wsum += w;
+ asum += w * al;
+ }
+ }
+ if asum > 1e-6 && wet > 0.0 {
+ let ca = asum / wsum.max(1e-6);
+ let canvas: Vec<f32> = (0..n).map(|c| if c < nc { acc[c] / asum } else { 1.0 }).collect();
+ pickup = Some(match pickup.take() {
+ None => canvas,
+ Some(p) => p.iter().zip(&canvas).map(|(p, c)| p + (c - p) * PICKUP_RATE * wet * ca).collect(),
+ });
+ }
+ let wr = if res.is_some() { amount * (1.0 - mix * wet) } else { 0.0 };
+ let wp = if pickup.is_some() { mix * wet } else { 0.0 };
+ let total = wr + wp;
+ if total > 1e-6 {
+ for c in 0..n {
+ let rv = res.as_ref().map_or(0.0, |v| v[c]);
+ let pv = pickup.as_ref().map_or(0.0, |v| v[c]);
+ paint[c] = (rv * wr + pv * wp) / total;
+ }
+ let dep = total.min(1.0) * flow;
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ let k = fp.at(x, y) * dep;
+ if k > 0.0 {
+ over_native(&fmt, work.px_mut(x, y), &paint, k, lock_transparency);
+ }
+ }
+ }
+ }
+ amount *= 1.0 - 0.08 * (1.0 - load);
+ });
+ state.amount = amount;
+ state.pickup = pickup.map(|p| to_rgba(&fmt, &p));
+ dmg
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{BrushSettings, StrokePoint};
+ use photocraft_color::PixelFormat;
+
+ fn stroke(y: f64) -> Stroke {
+ Stroke {
+ brush: BrushSettings { size: 8.0, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() },
+ points: vec![StrokePoint::new(4.0, y, 1.0), StrokePoint::new(196.0, y, 1.0)],
+ }
+ }
+
+ #[test]
+ fn low_load_runs_dry_and_full_load_does_not() {
+ for (load, expect_dry) in [(0.0, true), (1.0, false)] {
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ let mut st = MixerState::default();
+ st.load([1.0, 0.0, 0.0, 1.0]);
+ apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, load, mix: 0.0, flow: 1.0 }, &mut st, None, false);
+ let (start, end) = (s.rgba(10, 10)[3], s.rgba(190, 10)[3]);
+ assert!(start > 0.95, "{start}");
+ if expect_dry {
+ assert!(end < start * 0.6, "load {load}: {start} → {end}");
+ assert!(st.amount < 0.2);
+ } else {
+ assert!(end > 0.95, "{end}");
+ assert!((st.amount - 1.0).abs() < 1e-6);
+ }
+ }
+ }
+
+ #[test]
+ fn wet_brush_picks_up_and_smears_canvas_colour() {
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ // Blue canvas on the left half, white on the right.
+ s.fill_rect(Rect::new(0, 0, 100, 20), &[0.0, 0.0, 1.0, 1.0]);
+ s.fill_rect(Rect::new(100, 0, 200, 20), &[1.0, 1.0, 1.0, 1.0]);
+ let mut st = MixerState::default();
+ st.load([1.0, 0.0, 0.0, 1.0]);
+ apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 1.0, load: 0.3, mix: 0.9, flow: 1.0 }, &mut st, None, false);
+ // Blue is dragged into the white half.
+ let c = s.rgba(115, 10);
+ assert!(c[2] > c[1] + 0.05 && c[1] < 0.95, "{c:?}");
+ // The pickup well now holds a canvas-contaminated colour.
+ let p = st.pickup.unwrap();
+ assert!(p[2] > 0.2, "{p:?}");
+ st.clean();
+ assert!(st.pickup.is_none());
+ }
+
+ #[test]
+ fn dry_empty_brush_paints_nothing() {
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ let mut st = MixerState::default();
+ let dmg = apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, ..Default::default() }, &mut st, None, false);
+ assert!(!dmg.is_empty());
+ assert_eq!(s.rgba(50, 10)[3], 0.0);
+ }
+}
diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs
new file mode 100644
index 000000000..5017924f5
--- /dev/null
+++ b/crates/paint/src/presets.rs
@@ -0,0 +1,115 @@
+//! Built-in brush presets (our own designs; sampled tips and textures are generated procedurally).
+
+use crate::brush::*;
+use crate::procedural::{bristle_tip, chalk_tip, spatter_tip};
+
+fn preset(name: &str, brush: BrushSettings) -> BrushPreset {
+ BrushPreset { name: name.to_string(), brush, builtin: true }
+}
+
+/// The built-in preset set, in display order.
+pub fn builtin() -> Vec<BrushPreset> {
+ let base = BrushSettings { pressure_size: false, spacing: 0.25, ..Default::default() };
+ vec![
+ preset("Hard Round", BrushSettings { size: 30.0, hardness: 1.0, ..base.clone() }),
+ preset("Soft Round", BrushSettings { size: 45.0, hardness: 0.0, ..base.clone() }),
+ preset(
+ "Hard Round Pressure Size",
+ BrushSettings { size: 30.0, hardness: 1.0, shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic::controlled(Control::PenPressure), ..Default::default() }, ..base.clone() },
+ ),
+ preset(
+ "Soft Round Pressure Opacity",
+ BrushSettings { size: 45.0, hardness: 0.0, transfer: Transfer { enabled: true, opacity: Dynamic::controlled(Control::PenPressure), ..Default::default() }, ..base.clone() },
+ ),
+ preset("Airbrush Soft", BrushSettings { size: 80.0, hardness: 0.0, flow: 0.1, spacing: 0.1, build_up: true, build_up_rate: 25.0, ..base.clone() }),
+ preset("Hard Pencil", BrushSettings { size: 3.0, hardness: 1.0, aliased: true, spacing: 0.1, ..base.clone() }),
+ preset("Calligraphy Flat", BrushSettings { size: 28.0, hardness: 1.0, roundness: 0.2, angle: 45.0, spacing: 0.05, ..base.clone() }),
+ preset(
+ "Chalk",
+ BrushSettings {
+ size: 40.0,
+ tip: TipShape::Sampled(chalk_tip(64, 7)),
+ spacing: 0.2,
+ shape_dynamics: ShapeDynamics { enabled: true, angle: Dynamic::jitter(1.0), size: Dynamic { jitter: 0.15, ..Default::default() }, ..Default::default() },
+ texture: Texture { enabled: true, pattern: Pattern::Procedural { style: PatternStyle::Paper, size: 128, seed: 3 }, depth: 0.6, ..Default::default() },
+ ..base.clone()
+ },
+ ),
+ preset(
+ "Spatter",
+ BrushSettings {
+ size: 60.0,
+ tip: TipShape::Sampled(spatter_tip(64, 11, 14)),
+ spacing: 0.6,
+ shape_dynamics: ShapeDynamics {
+ enabled: true,
+ size: Dynamic { jitter: 0.6, minimum: 0.2, ..Default::default() },
+ angle: Dynamic::jitter(1.0),
+ flip_x_jitter: true,
+ flip_y_jitter: true,
+ ..Default::default()
+ },
+ scattering: Scattering { enabled: true, scatter: Dynamic::jitter(1.5), both_axes: true, count: 2, count_jitter: Dynamic::jitter(0.5) },
+ ..base.clone()
+ },
+ ),
+ preset(
+ "Dry Bristle",
+ BrushSettings {
+ size: 50.0,
+ tip: TipShape::Sampled(bristle_tip(64, 5)),
+ spacing: 0.04,
+ shape_dynamics: ShapeDynamics { enabled: true, angle: Dynamic::controlled(Control::Direction), ..Default::default() },
+ transfer: Transfer { enabled: true, flow: Dynamic { control: Control::Fade, fade_steps: 400, minimum: 0.1, ..Default::default() }, ..Default::default() },
+ ..base.clone()
+ },
+ ),
+ preset(
+ "Watercolor Wet Edges",
+ BrushSettings {
+ size: 60.0,
+ hardness: 0.3,
+ wet_edges: true,
+ texture: Texture { enabled: true, pattern: Pattern::Procedural { style: PatternStyle::Paper, size: 256, seed: 9 }, depth: 0.35, scale: 1.5, ..Default::default() },
+ ..base.clone()
+ },
+ ),
+ preset(
+ "Canvas Texture",
+ BrushSettings {
+ size: 50.0,
+ hardness: 0.8,
+ texture: Texture { enabled: true, pattern: Pattern::Procedural { style: PatternStyle::Canvas, size: 64, seed: 1 }, mode: MaskMode::Subtract, depth: 0.7, ..Default::default() },
+ ..base.clone()
+ },
+ ),
+ preset(
+ "Confetti",
+ BrushSettings {
+ size: 24.0,
+ hardness: 1.0,
+ roundness: 0.5,
+ spacing: 1.2,
+ shape_dynamics: ShapeDynamics { enabled: true, angle: Dynamic::jitter(1.0), size: Dynamic::jitter(0.5), ..Default::default() },
+ scattering: Scattering { enabled: true, scatter: Dynamic::jitter(3.0), both_axes: true, count: 3, ..Default::default() },
+ color_dynamics: ColorDynamics { enabled: true, per_tip: true, hue_jitter: 1.0, saturation_jitter: 0.2, purity: 0.5, ..Default::default() },
+ ..base.clone()
+ },
+ ),
+ preset(
+ "Dual Grain",
+ BrushSettings {
+ size: 50.0,
+ hardness: 0.6,
+ noise: true,
+ dual_brush: DualBrush { enabled: true, tip: TipShape::Sampled(spatter_tip(48, 23, 20)), size: 30.0, spacing: 0.3, scatter: 1.0, both_axes: true, count: 2, flip: true, ..Default::default() },
+ ..base
+ },
+ ),
+ ]
+}
+
+/// Find a preset by name (case-insensitive).
+pub fn find<'a>(presets: &'a [BrushPreset], name: &str) -> Option<&'a BrushPreset> {
+ presets.iter().find(|p| p.name.eq_ignore_ascii_case(name))
+}
diff --git a/crates/paint/src/procedural.rs b/crates/paint/src/procedural.rs
index a76e93aaf..1e1e93897 100644
--- a/crates/paint/src/procedural.rs
+++ b/crates/paint/src/procedural.rs
@@ -37,7 +37,7 @@ fn fbm(x: f32, y: f32, size: f32, cells: i32, octaves: u32, salt: u64) -> f32 {
pub fn pattern(style: PatternStyle, size: u32, seed: u32) -> PatternImage {
let n = size.clamp(8, 1024) as usize;
let s = n as f32;
- let salt = u64::from(seed) * 0x1000_0000_1B3 + 17;
+ let salt = u64::from(seed) * 0x0100_0000_01B3 + 17;
let mut data = vec![0.0f32; n * n];
for y in 0..n {
for x in 0..n {
diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs
new file mode 100644
index 000000000..08c001053
--- /dev/null
+++ b/crates/paint/src/render.rs
@@ -0,0 +1,573 @@
+//! Dab rasterisation and stroke compositing.
+//!
+//! A stroke paints into a sparse, tiled *stroke buffer* (coverage plus, with Color Dynamics, a
+//! premultiplied colour), exactly like a private stroke layer: dabs build up with flow up to their
+//! opacity ceiling, stroke-level masks (Dual Brush, Texture) apply when the buffer is composited,
+//! and the whole buffer composites onto the pre-stroke pixels at the stroke opacity. Because the
+//! buffer is sparse and compositing always starts from the pre-stroke pixels, strokes can be fed in
+//! chunks and re-composited incrementally for interactive painting (see [`StrokeRenderer`]).
+
+use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
+
+use photocraft_color::{BlendMode, PixelFormat};
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, from_rgba_into, to_rgba};
+
+use crate::brush::{BrushSettings, MaskMode, Pattern, TipShape};
+use crate::dynamics::DabGenerator;
+use crate::retouch::{Footprint, alpha_index, over_native};
+use crate::rng::hash2;
+use crate::tile::{Mips, PatternImage};
+use crate::{Dab, StrokePoint, dab_coverage};
+
+/// Edge of a stroke-buffer tile.
+pub const COV_TILE: i32 = 64;
+const NOISE_SALT: u64 = 0x006E_6F69_7365;
+
+#[inline]
+fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
+ let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+/// Combine brush coverage `v` with a mask value `t` (texture/dual tip) at `depth`.
+/// Every mode maps `v = 0` to 0 (a mask never adds paint where the brush has none).
+pub fn mask_combine(mode: MaskMode, v: f32, t: f32, d: f32) -> f32 {
+ if v <= 0.0 {
+ return 0.0;
+ }
+ let lerp = |a: f32, b: f32| a + (b - a) * d;
+ let r = match mode {
+ MaskMode::Multiply => v * (1.0 - d + d * t),
+ MaskMode::Subtract => (v - d * (1.0 - t)).max(0.0),
+ MaskMode::Darken => v.min(1.0 - d + d * t),
+ MaskMode::Overlay => {
+ let o = if v < 0.5 { 2.0 * v * t } else { 1.0 - 2.0 * (1.0 - v) * (1.0 - t) };
+ lerp(v, o)
+ }
+ MaskMode::ColorDodge => lerp(v, (v / (1.0 - t).max(1e-3)).min(1.0)),
+ MaskMode::ColorBurn => lerp(v, 1.0 - ((1.0 - v) / t.max(1e-3)).min(1.0)),
+ MaskMode::LinearBurn => lerp(v, (v + t - 1.0).max(0.0)),
+ MaskMode::HardMix => lerp(v, if v + t > 1.0 { 1.0 } else { 0.0 }),
+ MaskMode::LinearHeight => v * ((t - (1.0 - d * v)) * 4.0 + 0.5).clamp(0.0, 1.0),
+ MaskMode::Height => {
+ if t >= 1.0 - d * v {
+ v
+ } else {
+ 0.0
+ }
+ }
+ };
+ r.clamp(0.0, 1.0)
+}
+
+/// A stroke-ready brush: the settings plus prepared tip mips and texture.
+#[derive(Clone, Debug)]
+pub struct BrushContext {
+ pub brush: BrushSettings,
+ tip: Option<Arc<Mips>>,
+ dual_tip: Option<Arc<Mips>>,
+ texture: Option<Arc<PatternImage>>,
+}
+
+fn prepare_pattern(b: &BrushSettings) -> Option<Arc<PatternImage>> {
+ let t = &b.texture;
+ if !t.enabled {
+ return None;
+ }
+ let mut img = match &t.pattern {
+ Pattern::Procedural { style, size, seed } => crate::procedural::pattern(*style, *size, *seed),
+ Pattern::Tile(g) if g.is_valid() => PatternImage { width: g.width as usize, height: g.height as usize, data: g.to_f32() },
+ Pattern::Tile(_) => return None,
+ };
+ let (br, ct) = (t.brightness.clamp(-1.0, 1.0), t.contrast.clamp(-1.0, 1.0));
+ for v in &mut img.data {
+ let mut x = (*v - 0.5) * (1.0 + ct) + 0.5 + br;
+ x = x.clamp(0.0, 1.0);
+ *v = if t.invert { 1.0 - x } else { x };
+ }
+ Some(Arc::new(img))
+}
+
+impl BrushContext {
+ pub fn new(brush: &BrushSettings) -> Self {
+ let mips = |t: &TipShape| match t {
+ TipShape::Sampled(g) if g.is_valid() => Some(Arc::new(Mips::new(g))),
+ _ => None,
+ };
+ Self {
+ tip: mips(&brush.tip),
+ dual_tip: if brush.dual_brush.enabled { mips(&brush.dual_brush.tip) } else { None },
+ texture: prepare_pattern(brush),
+ brush: brush.clone(),
+ }
+ }
+
+ /// Texture value at a document pixel (bilinear, tiled).
+ #[inline]
+ pub fn texture_at(&self, x: i32, y: i32) -> f32 {
+ let Some(p) = &self.texture else { return 1.0 };
+ let s = self.brush.texture.scale.max(0.01);
+ if s == 1.0 {
+ // Pixel centres land exactly on texels at 100 %.
+ return p.data[y.rem_euclid(p.height as i32) as usize * p.width + x.rem_euclid(p.width as i32) as usize];
+ }
+ let (fx, fy) = ((x as f32 + 0.5) / s - 0.5, (y as f32 + 0.5) / s - 0.5);
+ let (x0, y0) = (fx.floor(), fy.floor());
+ let (tx, ty) = (fx - x0, fy - y0);
+ let a = p.sample_wrap(x0, y0) + (p.sample_wrap(x0 + 1.0, y0) - p.sample_wrap(x0, y0)) * tx;
+ let b = p.sample_wrap(x0, y0 + 1.0) + (p.sample_wrap(x0 + 1.0, y0 + 1.0) - p.sample_wrap(x0, y0 + 1.0)) * tx;
+ a + (b - a) * ty
+ }
+
+ /// Bounding rectangle of a dab (rotated sampled tips need the corner reach).
+ pub fn dab_rect(&self, d: &Dab, dual: bool) -> Rect {
+ let sampled = if dual { self.dual_tip.is_some() } else { self.tip.is_some() };
+ let reach = if sampled { d.radius * std::f32::consts::SQRT_2 } else { d.radius };
+ let rr = reach.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)
+ }
+
+ /// Rasterise a dab over `rect` into `out` (tip shape × noise × per-tip texture × wet edges × flow).
+ pub fn rasterize(&self, d: &Dab, dual: bool, rect: Rect, out: &mut Vec<f32>) {
+ let (w, h) = (rect.width() as usize, rect.height() as usize);
+ out.clear();
+ out.resize(w * h, 0.0);
+ let b = &self.brush;
+ let (hardness, mips) = if dual { (b.dual_brush.hardness, self.dual_tip.as_deref()) } else { (b.hardness, self.tip.as_deref()) };
+ let aliased = b.aliased && !dual;
+ let wet = b.wet_edges && !dual;
+ let noise = b.noise && !dual;
+ let tex_tip = !dual && b.texture.enabled && b.texture.each_tip && self.texture.is_some();
+ let (cx, cy) = (d.center.x as f32, d.center.y as f32);
+ let (sn, cs) = d.angle.sin_cos();
+ let (fx, fy) = (if d.flip_x { -1.0 } else { 1.0 }, if d.flip_y { -1.0 } else { 1.0 });
+ let r = d.radius;
+ let ro = d.roundness.max(0.5 / r).min(1.0);
+ let rm = (r * ro).max(0.5);
+ let reach2 = (rm + 0.5) * (rm + 0.5);
+ // Sampled-tip mapping.
+ let (level, inv_scale, tw, th) = match mips {
+ Some(m) => {
+ let (w0, h0, _) = &m.levels[0];
+ let big = *w0.max(h0) as f32;
+ (m.level_for(2.0 * r * ro.max(0.25)), big / (2.0 * r), *w0 as f32, *h0 as f32)
+ }
+ None => (0, 1.0, 1.0, 1.0),
+ };
+ for yy in 0..h {
+ let y = rect.y0 + yy as i32;
+ let dy = y as f32 + 0.5 - cy;
+ for xx in 0..w {
+ let x = rect.x0 + xx as i32;
+ let dx = x as f32 + 0.5 - cx;
+ // To y-up, rotate by -angle, flip.
+ let (ux, uy) = (dx, -dy);
+ let u = (ux * cs + uy * sn) * fx;
+ let v = (-ux * sn + uy * cs) * fy;
+ let (mut val, rn) = match mips {
+ None => {
+ let d2 = (u * ro).powi(2) + v * v;
+ if d2 >= reach2 {
+ continue;
+ }
+ let dd = d2.sqrt();
+ let val = if aliased { if dd <= rm { 1.0 } else { 0.0 } } else { dab_coverage(dd, rm, hardness) };
+ (val, dd / rm)
+ }
+ Some(m) => {
+ let (px, py) = (u * inv_scale + tw / 2.0, -(v / ro) * inv_scale + th / 2.0);
+ if px < -1.0 || py < -1.0 || px > tw + 1.0 || py > th + 1.0 {
+ continue;
+ }
+ let s = m.sample_clamped(level, px / tw, py / th);
+ let val = if aliased { if s >= 0.5 { 1.0 } else { 0.0 } } else { s };
+ (val, 1.0 - s)
+ }
+ };
+ if val <= 0.0 {
+ continue;
+ }
+ if noise && val < 1.0 {
+ let n = hash2(x, y, NOISE_SALT);
+ let hard = if n < val { 1.0 } else { 0.0 };
+ val += (hard - val) * 0.7;
+ }
+ if tex_tip {
+ val = mask_combine(b.texture.mode, val, self.texture_at(x, y), d.depth);
+ }
+ if wet {
+ val *= 0.5 + 0.5 * smoothstep(0.5, 1.0, rn);
+ }
+ out[yy * w + xx] = val * d.alpha;
+ }
+ }
+ }
+
+ /// One dab's dense footprint (for the sequential retouch tools).
+ pub fn footprint(&self, d: &Dab, index: usize) -> Footprint {
+ let rect = self.dab_rect(d, false);
+ let mut cov = Vec::new();
+ self.rasterize(d, false, rect, &mut cov);
+ Footprint { dab: *d, index, rect, cov }
+ }
+
+ /// Stroke-level masks applied to accumulated coverage `c` at a pixel.
+ #[inline]
+ pub fn stroke_mask(&self, c: f32, dual: Option<f32>, x: i32, y: i32) -> f32 {
+ let b = &self.brush;
+ let mut m = c;
+ if let Some(dv) = dual {
+ m = mask_combine(b.dual_brush.mode, m, dv, 1.0);
+ }
+ if self.texture.is_some() && !b.texture.each_tip {
+ m = mask_combine(b.texture.mode, m, self.texture_at(x, y), b.texture.depth.clamp(0.0, 1.0));
+ }
+ m
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Sparse stroke buffer
+// ---------------------------------------------------------------------------
+
+#[derive(Clone, Debug)]
+struct CovTile {
+ cov: Vec<f32>,
+ /// Premultiplied native colour channels (`nc` per pixel), empty without per-dab colour.
+ col: Vec<f32>,
+}
+
+/// A sparse tiled coverage (+ optional colour) buffer.
+#[derive(Clone, Debug, Default)]
+pub struct CoverageMap {
+ tiles: HashMap<(i32, i32), CovTile>,
+ nc: usize,
+ bounds: Rect,
+ dirty: HashSet<(i32, i32)>,
+}
+
+impl CoverageMap {
+ pub fn new(color_channels: usize) -> Self {
+ Self { nc: color_channels, ..Default::default() }
+ }
+ pub fn bounds(&self) -> Rect {
+ self.bounds
+ }
+ #[inline]
+ pub fn get(&self, x: i32, y: i32) -> f32 {
+ let (tx, ty) = (x.div_euclid(COV_TILE), y.div_euclid(COV_TILE));
+ self.tiles.get(&(tx, ty)).map_or(0.0, |t| t.cov[((y - ty * COV_TILE) * COV_TILE + (x - tx * COV_TILE)) as usize])
+ }
+
+ /// Accumulate dab values over `rect`: flow builds up towards the dab's opacity ceiling
+ /// (`c ← c + v·(ceil − c)`), or with `max` (wet edges). `color` = native colour for per-dab colour.
+ pub fn accumulate(&mut self, rect: Rect, vals: &[f32], ceil: f32, use_max: bool, color: Option<&[f32]>) {
+ if rect.is_empty() {
+ return;
+ }
+ self.bounds = self.bounds.union(&rect);
+ let w = rect.width() as usize;
+ let nc = self.nc;
+ let (t0x, t0y) = (rect.x0.div_euclid(COV_TILE), rect.y0.div_euclid(COV_TILE));
+ let (t1x, t1y) = ((rect.x1 - 1).div_euclid(COV_TILE), (rect.y1 - 1).div_euclid(COV_TILE));
+ let want_col = color.is_some() && nc > 0;
+ for ty in t0y..=t1y {
+ for tx in t0x..=t1x {
+ let tr = Rect::new(tx * COV_TILE, ty * COV_TILE, (tx + 1) * COV_TILE, (ty + 1) * COV_TILE).intersect(&rect);
+ if tr.is_empty() {
+ continue;
+ }
+ // Skip tiles this dab doesn't touch.
+ let any = (tr.y0..tr.y1).any(|y| {
+ let row = (y - rect.y0) as usize * w;
+ vals[row + (tr.x0 - rect.x0) as usize..row + (tr.x1 - rect.x0) as usize].iter().any(|&v| v > 0.0)
+ });
+ if !any {
+ continue;
+ }
+ let tile = self.tiles.entry((tx, ty)).or_insert_with(|| CovTile {
+ cov: vec![0.0; (COV_TILE * COV_TILE) as usize],
+ col: if want_col { vec![0.0; (COV_TILE * COV_TILE) as usize * nc] } else { Vec::new() },
+ });
+ if want_col && tile.col.is_empty() {
+ tile.col = vec![0.0; (COV_TILE * COV_TILE) as usize * nc];
+ }
+ self.dirty.insert((tx, ty));
+ for y in tr.y0..tr.y1 {
+ let row = (y - rect.y0) as usize * w;
+ let trow = ((y - ty * COV_TILE) * COV_TILE) as usize;
+ for x in tr.x0..tr.x1 {
+ let v = vals[row + (x - rect.x0) as usize];
+ if v <= 0.0 {
+ continue;
+ }
+ let ti = trow + (x - tx * COV_TILE) as usize;
+ let c = tile.cov[ti];
+ let nv = if use_max { c.max(v * ceil) } else if ceil > c { c + v * (ceil - c) } else { c };
+ if nv <= c {
+ continue;
+ }
+ if let (true, Some(col)) = (want_col, color) {
+ let k = if c < 1.0 { (nv - c) / (1.0 - c) } else { 0.0 };
+ let p = &mut tile.col[ti * nc..(ti + 1) * nc];
+ for i in 0..nc {
+ p[i] = col[i] * k + p[i] * (1.0 - k);
+ }
+ }
+ tile.cov[ti] = nv;
+ }
+ }
+ }
+ }
+ }
+
+ fn take_dirty(&mut self) -> Vec<(i32, i32)> {
+ let mut v: Vec<_> = self.dirty.drain().collect();
+ v.sort_unstable();
+ v
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Stroke renderer
+// ---------------------------------------------------------------------------
+
+/// Incremental stroke rendering: feed points, composite dirty tiles from the pre-stroke pixels.
+#[derive(Clone, Debug)]
+pub struct StrokeRenderer {
+ pub ctx: BrushContext,
+ generator: DabGenerator,
+ cov: CoverageMap,
+ dual: Option<CoverageMap>,
+ fmt: Option<PixelFormat>,
+ per_dab_color: bool,
+ dabs_done: usize,
+ scratch: Vec<f32>,
+ dab_buf: Vec<Dab>,
+ dual_buf: Vec<Dab>,
+ all_dabs: Option<Vec<Dab>>,
+}
+
+impl StrokeRenderer {
+ /// `fmt` = target pixel format (needed for per-dab colour); `zoom` for smoothing.
+ pub fn new(brush: &BrushSettings, fmt: Option<PixelFormat>, zoom: f32) -> Self {
+ let per_dab_color = brush.color_dynamics.enabled && !brush.erase && fmt.is_some();
+ let nc = if per_dab_color { fmt.map_or(0, |f| f.mode.color_channels()) } else { 0 };
+ Self {
+ ctx: BrushContext::new(brush),
+ generator: DabGenerator::new(brush, zoom),
+ cov: CoverageMap::new(nc),
+ dual: brush.dual_brush.enabled.then(|| CoverageMap::new(0)),
+ fmt,
+ per_dab_color,
+ dabs_done: 0,
+ scratch: Vec::new(),
+ dab_buf: Vec::new(),
+ dual_buf: Vec::new(),
+ all_dabs: None,
+ }
+ }
+
+ /// Keep a copy of every primary dab (for tests and sequential tools).
+ pub fn record_dabs(mut self) -> Self {
+ self.all_dabs = Some(Vec::new());
+ self
+ }
+ pub fn dabs(&self) -> &[Dab] {
+ self.all_dabs.as_deref().unwrap_or(&[])
+ }
+ pub fn dab_count(&self) -> usize {
+ self.dabs_done
+ }
+ /// Union of the dab rectangles so far.
+ pub fn bounds(&self) -> Rect {
+ self.cov.bounds
+ }
+
+ fn raster_pending(&mut self) {
+ let mut dabs = std::mem::take(&mut self.dab_buf);
+ let mut duals = std::mem::take(&mut self.dual_buf);
+ let wet = self.ctx.brush.wet_edges;
+ let mut native = [0.0f32; 8];
+ for d in &dabs {
+ let rect = self.ctx.dab_rect(d, false);
+ self.ctx.rasterize(d, false, rect, &mut self.scratch);
+ let col = match (self.per_dab_color, self.fmt) {
+ (true, Some(f)) => {
+ from_rgba_into(&f, d.color, &mut native);
+ Some(&native[..f.mode.color_channels()])
+ }
+ _ => None,
+ };
+ self.cov.accumulate(rect, &self.scratch, d.opacity, wet, col);
+ // Bounds track the full dab rectangle (even fully transparent parts), like the damage.
+ self.cov.bounds = self.cov.bounds.union(&rect);
+ }
+ if let Some(dm) = self.dual.as_mut() {
+ for d in &duals {
+ let rect = self.ctx.dab_rect(d, true);
+ self.ctx.rasterize(d, true, rect, &mut self.scratch);
+ dm.accumulate(rect, &self.scratch, 1.0, false, None);
+ }
+ }
+ self.dabs_done += dabs.len();
+ if let Some(all) = self.all_dabs.as_mut() {
+ all.extend_from_slice(&dabs);
+ }
+ dabs.clear();
+ duals.clear();
+ self.dab_buf = dabs;
+ self.dual_buf = duals;
+ }
+
+ /// Feed input points (any chunking gives the same result).
+ pub fn push(&mut self, pts: &[StrokePoint]) {
+ self.generator.push(pts, &mut self.dab_buf, &mut self.dual_buf);
+ self.raster_pending();
+ }
+
+ /// End of stroke (smoothing catch-up, a lone first point).
+ pub fn finish(&mut self) {
+ self.generator.finish(&mut self.dab_buf, &mut self.dual_buf);
+ self.raster_pending();
+ }
+
+ /// Final stroke coverage at a pixel (stroke-level masks applied, before opacity/selection).
+ pub fn coverage_at(&self, x: i32, y: i32) -> f32 {
+ let c = self.cov.get(x, y);
+ if c <= 0.0 {
+ return 0.0;
+ }
+ self.ctx.stroke_mask(c, self.dual.as_ref().map(|d| d.get(x, y)), x, y)
+ }
+
+ /// Dense final coverage over the stroke bounds.
+ pub fn dense_coverage(&self) -> (Rect, Vec<f32>) {
+ let b = self.bounds();
+ let w = b.width() as usize;
+ let mut out = vec![0.0f32; w * b.height() as usize];
+ for (&(tx, ty), t) in &self.cov.tiles {
+ let tr = Rect::new(tx * COV_TILE, ty * COV_TILE, (tx + 1) * COV_TILE, (ty + 1) * COV_TILE).intersect(&b);
+ for y in tr.y0..tr.y1 {
+ for x in tr.x0..tr.x1 {
+ let c = t.cov[((y - ty * COV_TILE) * COV_TILE + (x - tx * COV_TILE)) as usize];
+ if c > 0.0 {
+ out[(y - b.y0) as usize * w + (x - b.x0) as usize] = self.ctx.stroke_mask(c, self.dual.as_ref().map(|d| d.get(x, y)), x, y);
+ }
+ }
+ }
+ }
+ (b, out)
+ }
+
+ /// Composite the stroke buffer onto `target`, reading original pixels from `pre` (the
+ /// pre-stroke surface; pass a clone of the target taken before the first `push`). With
+ /// `all = false` only tiles touched since the last composite are processed (interactive use).
+ /// Returns the damaged rectangle.
+ pub fn composite(&mut self, pre: &Surface, target: &mut Surface, selection: Option<&Surface>, lock_transparency: bool, all: bool) -> Rect {
+ let keys: Vec<(i32, i32)> = if all {
+ self.cov.dirty.clear();
+ let mut k: Vec<_> = self.cov.tiles.keys().copied().collect();
+ k.sort_unstable();
+ k
+ } else {
+ self.cov.take_dirty()
+ };
+ if let Some(d) = self.dual.as_mut() {
+ d.dirty.clear();
+ }
+ let bounds = self.bounds();
+ let fmt = target.format();
+ let n = fmt.channels();
+ let a_idx = alpha_index(&fmt);
+ let nc = fmt.mode.color_channels();
+ let b = &self.ctx.brush;
+ let opacity = b.opacity.clamp(0.0, 1.0);
+ let mut src = [0.0f32; 8];
+ from_rgba_into(&fmt, b.color, &mut src);
+ if let Some(a) = a_idx {
+ src[a] = b.color[3];
+ }
+ let mut dmg = Rect::EMPTY;
+ let mut region = Vec::new();
+ for (tx, ty) in keys {
+ let Some(tile) = self.cov.tiles.get(&(tx, ty)) else { continue };
+ let tr = Rect::new(tx * COV_TILE, ty * COV_TILE, (tx + 1) * COV_TILE, (ty + 1) * COV_TILE).intersect(&bounds);
+ if tr.is_empty() {
+ continue;
+ }
+ pre.read_region_into(tr, &mut region);
+ let sel = selection.map(|s| (s.channels(), s.read_region(tr)));
+ let w = tr.width() as usize;
+ for y in tr.y0..tr.y1 {
+ for x in tr.x0..tr.x1 {
+ let ti = ((y - ty * COV_TILE) * COV_TILE + (x - tx * COV_TILE)) as usize;
+ let c = tile.cov[ti];
+ if c <= 0.0 {
+ continue;
+ }
+ let i = (y - tr.y0) as usize * w + (x - tr.x0) as usize;
+ let m = self.ctx.stroke_mask(c, self.dual.as_ref().map(|d| d.get(x, y)), x, y);
+ let s = sel.as_ref().map_or(1.0, |(sc, v)| v[i * sc]);
+ let mut k = (m * opacity * s).min(1.0);
+ if k <= 0.0 {
+ continue;
+ }
+ if b.mode == BlendMode::Dissolve {
+ k = if hash2(x, y, b.seed) < k { 1.0 } else { 0.0 };
+ if k == 0.0 {
+ continue;
+ }
+ }
+ let px = &mut region[i * n..(i + 1) * n];
+ if b.erase {
+ if let (Some(a), false) = (a_idx, lock_transparency) {
+ px[a] *= 1.0 - k;
+ }
+ continue;
+ }
+ if lock_transparency && a_idx.is_some_and(|a| px[a] <= 0.0) {
+ continue;
+ }
+ if self.per_dab_color && !tile.col.is_empty() {
+ let p = &tile.col[ti * nc..(ti + 1) * nc];
+ for ch in 0..nc {
+ src[ch] = p[ch] / c;
+ }
+ }
+ if matches!(b.mode, BlendMode::Normal | BlendMode::Dissolve) {
+ over_native(&fmt, px, &src[..n], k, lock_transparency);
+ } else {
+ let d = to_rgba(&fmt, px);
+ let sr = to_rgba(&fmt, &src[..n]);
+ let mut o = photocraft_color::blend::composite(b.mode, d, sr, 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(tr, &region);
+ dmg = dmg.union(&tr);
+ }
+ if all { bounds } else { dmg }
+ }
+}
+
+/// Render a whole stroke onto `target` (one-shot). Returns the damaged rectangle.
+pub fn render_stroke(target: &mut Surface, brush: &BrushSettings, points: &[StrokePoint], selection: Option<&Surface>, lock_transparency: bool, zoom: f32) -> Rect {
+ if points.is_empty() {
+ return Rect::EMPTY;
+ }
+ let pre = target.clone();
+ let mut r = StrokeRenderer::new(brush, Some(target.format()), zoom);
+ r.push(points);
+ r.finish();
+ r.composite(&pre, target, selection, lock_transparency, true)
+}
diff --git a/crates/paint/src/replace.rs b/crates/paint/src/replace.rs
new file mode 100644
index 000000000..bbc00087a
--- /dev/null
+++ b/crates/paint/src/replace.rs
@@ -0,0 +1,261 @@
+//! Color Replacement: recolour pixels similar to a sampled colour using a non-separable blend
+//! (Hue, Saturation, Color or Luminosity) with the foreground colour.
+
+use photocraft_color::BlendMode;
+use photocraft_color::blend::blend_rgb;
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, from_rgba_into, to_rgba};
+use serde::{Deserialize, Serialize};
+
+use crate::Stroke;
+use crate::retouch::{Region, apply_dab_stroke};
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ReplaceMode {
+ Hue,
+ Saturation,
+ #[default]
+ Color,
+ Luminosity,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Sampling {
+ /// Resample under the brush centre at every dab.
+ #[default]
+ Continuous,
+ /// Sample once, where the stroke starts.
+ Once,
+ /// Replace only colours near the background swatch.
+ BackgroundSwatch,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Limits {
+ /// Matching pixels anywhere under the brush.
+ Discontiguous,
+ /// Matching pixels connected to the brush centre.
+ #[default]
+ Contiguous,
+ /// Contiguous, and stop at edges (no soft tolerance falloff).
+ FindEdges,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct ReplaceSettings {
+ pub mode: ReplaceMode,
+ pub sampling: Sampling,
+ pub limits: Limits,
+ /// 0..1 (max per-channel RGB distance).
+ pub tolerance: f32,
+ pub anti_alias: bool,
+ /// Replacement (foreground) colour, straight RGBA.
+ pub color: [f32; 4],
+ /// Background swatch for [`Sampling::BackgroundSwatch`].
+ pub background: [f32; 4],
+}
+
+impl Default for ReplaceSettings {
+ fn default() -> Self {
+ Self { mode: ReplaceMode::Color, sampling: Sampling::Continuous, limits: Limits::Contiguous, tolerance: 0.3, anti_alias: true, color: [1.0, 0.0, 0.0, 1.0], background: [1.0; 4] }
+ }
+}
+
+fn dist(a: &[f32; 4], b: [f32; 3]) -> f32 {
+ (a[0] - b[0]).abs().max((a[1] - b[1]).abs()).max((a[2] - b[2]).abs())
+}
+
+/// Replace colours along a stroke. Returns the damaged rectangle.
+pub fn apply_color_replacement(target: &mut Surface, stroke: &Stroke, rs: &ReplaceSettings, selection: Option<&Surface>, lock_transparency: bool) -> Rect {
+ let fmt = target.format();
+ let n = fmt.channels();
+ let pre = target.clone();
+ let mode = match rs.mode {
+ ReplaceMode::Hue => BlendMode::Hue,
+ ReplaceMode::Saturation => BlendMode::Saturation,
+ ReplaceMode::Color => BlendMode::Color,
+ ReplaceMode::Luminosity => BlendMode::Luminosity,
+ };
+ let fg = [rs.color[0], rs.color[1], rs.color[2]];
+ let tol = rs.tolerance.clamp(0.0, 1.0);
+ let soft = rs.anti_alias && rs.limits != Limits::FindEdges;
+ let mut once: Option<[f32; 3]> = None;
+ let match_w = |d: f32| -> f32 {
+ if d > tol {
+ 0.0
+ } else if soft && tol > 0.0 {
+ // Soft falloff over the last quarter of the tolerance.
+ ((tol - d) / (tol * 0.25)).clamp(0.0, 1.0)
+ } else {
+ 1.0
+ }
+ };
+ apply_dab_stroke(target, stroke, selection, lock_transparency, 0, |work: &mut Region, fp| {
+ let (cx, cy) = (fp.dab.center.x.floor() as i32, fp.dab.center.y.floor() as i32);
+ let sampled = match rs.sampling {
+ Sampling::Continuous => {
+ let c = pre.rgba(cx, cy);
+ [c[0], c[1], c[2]]
+ }
+ Sampling::Once => *once.get_or_insert_with(|| {
+ let c = pre.rgba(cx, cy);
+ [c[0], c[1], c[2]]
+ }),
+ Sampling::BackgroundSwatch => [rs.background[0], rs.background[1], rs.background[2]],
+ };
+ let r = fp.rect.intersect(&work.rect);
+ if r.is_empty() {
+ return;
+ }
+ let (w, h) = (r.width() as usize, r.height() as usize);
+ // Per-pixel match weight.
+ let mut weight = vec![0.0f32; w * h];
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ if fp.at(x, y) <= 0.0 {
+ continue;
+ }
+ // Match against the pre-stroke colours, so pixels recoloured by earlier dabs of
+ // this stroke still count as the sampled colour.
+ let c = pre.rgba(x, y);
+ if c[3] <= 0.0 {
+ continue;
+ }
+ weight[(y - r.y0) as usize * w + (x - r.x0) as usize] = match_w(dist(&c, sampled));
+ }
+ }
+ if rs.limits != Limits::Discontiguous {
+ // Keep only the region connected to the centre (4-connected flood fill).
+ let mut keep = vec![false; w * h];
+ let start = (cx.clamp(r.x0, r.x1 - 1), cy.clamp(r.y0, r.y1 - 1));
+ let si = (start.1 - r.y0) as usize * w + (start.0 - r.x0) as usize;
+ if weight[si] > 0.0 {
+ let mut stack = vec![si];
+ keep[si] = true;
+ while let Some(i) = stack.pop() {
+ let (x, y) = (i % w, i / w);
+ let mut nb = |j: usize| {
+ if !keep[j] && weight[j] > 0.0 {
+ keep[j] = true;
+ stack.push(j);
+ }
+ };
+ if x > 0 {
+ nb(i - 1);
+ }
+ if x + 1 < w {
+ nb(i + 1);
+ }
+ if y > 0 {
+ nb(i - w);
+ }
+ if y + 1 < h {
+ nb(i + w);
+ }
+ }
+ }
+ for (wv, k) in weight.iter_mut().zip(&keep) {
+ if !k {
+ *wv = 0.0;
+ }
+ }
+ }
+ let mut enc = [0.0f32; 8];
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ let k = fp.at(x, y) * weight[(y - r.y0) as usize * w + (x - r.x0) as usize];
+ if k <= 0.0 {
+ continue;
+ }
+ let px = work.px_mut(x, y);
+ let c = to_rgba(&fmt, px);
+ let b = blend_rgb(mode, [c[0], c[1], c[2]], fg);
+ let o = [c[0] + (b[0] - c[0]) * k, c[1] + (b[1] - c[1]) * k, c[2] + (b[2] - c[2]) * k, c[3]];
+ from_rgba_into(&fmt, o, &mut enc);
+ px.copy_from_slice(&enc[..n]);
+ }
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{BrushSettings, StrokePoint};
+ use photocraft_color::PixelFormat;
+ use photocraft_color::blend::lum;
+
+ fn setup(fmt: PixelFormat) -> Surface {
+ let mut s = Surface::new(fmt);
+ // Left: mid green; right: dark blue.
+ s.fill_rect(Rect::new(0, 0, 40, 40), &photocraft_raster::from_rgba(&fmt, [0.2, 0.6, 0.2, 1.0]));
+ s.fill_rect(Rect::new(40, 0, 80, 40), &photocraft_raster::from_rgba(&fmt, [0.1, 0.1, 0.5, 1.0]));
+ s
+ }
+
+ fn stroke() -> Stroke {
+ Stroke {
+ brush: BrushSettings { size: 30.0, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() },
+ points: vec![StrokePoint::new(20.0, 20.0, 1.0), StrokePoint::new(60.0, 20.0, 1.0)],
+ }
+ }
+
+ #[test]
+ fn modes_follow_the_nonseparable_definitions() {
+ let fg = [1.0, 0.0, 0.0, 1.0];
+ for mode in [ReplaceMode::Hue, ReplaceMode::Saturation, ReplaceMode::Color, ReplaceMode::Luminosity] {
+ let mut s = setup(PixelFormat::RGBA32F);
+ let rs = ReplaceSettings { mode, sampling: Sampling::Once, limits: Limits::Discontiguous, tolerance: 0.1, color: fg, ..Default::default() };
+ apply_color_replacement(&mut s, &stroke(), &rs, None, false);
+ let c = s.rgba(20, 20);
+ let green = [0.2, 0.6, 0.2];
+ match mode {
+ // Hue/Color keep the luminosity of the original.
+ ReplaceMode::Hue | ReplaceMode::Color => {
+ assert!((lum([c[0], c[1], c[2]]) - lum(green)).abs() < 1e-3, "{mode:?} {c:?}");
+ assert!(c[0] > c[1], "{mode:?} turned red-ish {c:?}");
+ }
+ ReplaceMode::Saturation => assert!((lum([c[0], c[1], c[2]]) - lum(green)).abs() < 1e-3 && c[1] > c[0], "{c:?}"),
+ ReplaceMode::Luminosity => assert!((lum([c[0], c[1], c[2]]) - lum([1.0, 0.0, 0.0])).abs() < 1e-3, "{c:?}"),
+ }
+ // Sampling once on green: the blue half is outside the tolerance and untouched.
+ let b = s.rgba(60, 20);
+ assert!((b[2] - 0.5).abs() < 1e-3 && (b[0] - 0.1).abs() < 1e-3, "{mode:?} {b:?}");
+ }
+ }
+
+ #[test]
+ fn continuous_sampling_follows_the_cursor_and_swatch_limits() {
+ let mut s = setup(PixelFormat::RGBA8);
+ let rs = ReplaceSettings { mode: ReplaceMode::Color, sampling: Sampling::Continuous, limits: Limits::Contiguous, tolerance: 0.1, color: [1.0, 0.0, 0.0, 1.0], ..Default::default() };
+ apply_color_replacement(&mut s, &stroke(), &rs, None, false);
+ assert!(s.rgba(20, 20)[0] > 0.3 && s.rgba(70, 20)[0] > s.rgba(70, 20)[1], "both halves recoloured {:?} {:?}", s.rgba(20, 20), s.rgba(70, 20));
+ // Background swatch = white: nothing matches.
+ let mut s2 = setup(PixelFormat::RGBA8);
+ let rs2 = ReplaceSettings { sampling: Sampling::BackgroundSwatch, background: [1.0; 4], ..rs };
+ apply_color_replacement(&mut s2, &stroke(), &rs2, None, false);
+ assert_eq!(s2.rgba(20, 20), setup(PixelFormat::RGBA8).rgba(20, 20));
+ }
+
+ #[test]
+ fn contiguous_stops_at_disconnected_matches() {
+ let fmt = PixelFormat::RGBA32F;
+ let mut s = Surface::new(fmt);
+ s.fill_rect(Rect::new(0, 0, 60, 40), &[0.2, 0.6, 0.2, 1.0]);
+ // A blue wall column separates a green island at x 34..40.
+ s.fill_rect(Rect::new(30, 0, 34, 40), &[0.0, 0.0, 1.0, 1.0]);
+ let st = Stroke { points: vec![StrokePoint::new(20.0, 20.0, 1.0)], ..stroke() };
+ for (limits, island_changed) in [(Limits::Contiguous, false), (Limits::Discontiguous, true)] {
+ let mut t = s.clone();
+ let rs = ReplaceSettings { mode: ReplaceMode::Color, sampling: Sampling::Once, limits, tolerance: 0.05, color: [1.0, 0.0, 0.0, 1.0], ..Default::default() };
+ apply_color_replacement(&mut t, &st, &rs, None, false);
+ let changed = (t.rgba(34, 20)[0] - 0.2).abs() > 0.05;
+ assert_eq!(changed, island_changed, "{limits:?}");
+ assert!(t.rgba(20, 20)[0] > 0.3);
+ }
+ }
+}
diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs
index e5b5807e1..6c4e404ba 100644
--- a/crates/paint/src/retouch.rs
+++ b/crates/paint/src/retouch.rs
@@ -121,25 +121,14 @@ 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.
+/// Accumulated coverage of a whole stroke: dabs build up (`c ← c + d·(ceil − c)`, "flow"), capped at
+/// each dab's opacity ceiling; stroke-level masks (dual brush, texture) applied. Returns the stroke
+/// bounds and `width × height` coverage values. Uses the full brush engine (tips and dynamics).
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)
+ let mut r = crate::StrokeRenderer::new(&stroke.brush, None, 1.0);
+ r.push(&stroke.points);
+ r.finish();
+ r.dense_coverage()
}
/// Index of the alpha channel, if the format has one.
@@ -245,12 +234,13 @@ pub fn apply_dab_stroke(
if ds.is_empty() {
return Rect::EMPTY;
}
- let bounds = stroke_bounds(&ds);
+ let ctx = crate::BrushContext::new(&stroke.brush);
+ let bounds = ds.iter().fold(Rect::EMPTY, |r, d| r.union(&ctx.dab_rect(d, false)));
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));
+ effect(&mut work, &ctx.footprint(d, i));
}
let fmt = target.format();
let a = alpha_index(&fmt);
@@ -357,7 +347,7 @@ mod tests {
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(),
+ points: points.iter().map(|&(x, y)| StrokePoint::new(x, y, 1.0)).collect(),
}
}
diff --git a/crates/paint/src/tile.rs b/crates/paint/src/tile.rs
index b7b75022d..37bbf0b11 100644
--- a/crates/paint/src/tile.rs
+++ b/crates/paint/src/tile.rs
@@ -125,7 +125,7 @@ fn b64_decode(s: &str) -> Option<Vec<u8>> {
} as u32)
};
let s: Vec<u8> = s.bytes().filter(|c| !c.is_ascii_whitespace()).collect();
- if s.len() % 4 != 0 {
+ if !s.len().is_multiple_of(4) {
return None;
}
let mut out = Vec::with_capacity(s.len() / 4 * 3);
diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs
index ddc7baa61..fa597f3cb 100644
--- a/crates/psd/src/lib.rs
+++ b/crates/psd/src/lib.rs
@@ -49,7 +49,9 @@ pub mod header;
pub mod image_data;
mod io;
pub mod layer;
+pub mod metadata;
pub mod path;
+pub mod patterns;
pub mod pixels;
pub mod resources;
pub mod tagged;
diff --git a/crates/psd/src/metadata.rs b/crates/psd/src/metadata.rs
new file mode 100644
index 000000000..d105a2894
--- /dev/null
+++ b/crates/psd/src/metadata.rs
@@ -0,0 +1,97 @@
+//! `shmd` (metadata setting) layer block: a list of keyed sub-blocks, such as `cmls` (layer comp
+//! state, a versioned descriptor), `cust` and `mlst`.
+//!
+//! Layout (Adobe PSD spec, "Metadata setting"): u32 count, then per item the signature `8BIM`,
+//! a 4-byte key, a copy-on-sheet-duplication byte, 3 padding bytes, a u32 length and the data.
+//! Photoshop pads item data to an even length (the padding is part of the stored length), so
+//! parsing and writing are exact: `write(parse(b)) == b`.
+
+use crate::error::{PsdError, Result};
+use crate::io::{Reader, WriteExt};
+
+/// One `shmd` item.
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+pub struct MetadataItem {
+ /// Usually `8BIM`.
+ pub signature: [u8; 4],
+ /// Item key, e.g. `cmls`.
+ pub key: [u8; 4],
+ /// Copy on sheet duplication.
+ pub copy: bool,
+ /// The 3 bytes after the copy flag (zero in Photoshop files), kept for exactness.
+ pub reserved: [u8; 3],
+ /// Data including any padding counted in the stored length.
+ pub data: Vec<u8>,
+}
+
+impl MetadataItem {
+ /// A new item; `data` is zero-padded to an even length as Photoshop writes it.
+ pub fn new(key: [u8; 4], mut data: Vec<u8>) -> Self {
+ if data.len() % 2 == 1 {
+ data.push(0);
+ }
+ MetadataItem { signature: *b"8BIM", key, copy: false, reserved: [0; 3], data }
+ }
+}
+
+/// Parses `shmd` block data.
+pub fn parse_shmd(data: &[u8]) -> Result<Vec<MetadataItem>> {
+ let mut r = Reader::new(data);
+ let count = r.u32()?;
+ r.check_count(u64::from(count), 16)?;
+ let mut out = Vec::with_capacity(count as usize);
+ for _ in 0..count {
+ let signature = r.array()?;
+ let key = r.array()?;
+ let copy = r.u8()? != 0;
+ let reserved = r.array()?;
+ let len = r.u32()?;
+ let data = r.bytes_u64(u64::from(len))?.to_vec();
+ out.push(MetadataItem { signature, key, copy, reserved, data });
+ }
+ if !r.is_empty() {
+ return Err(PsdError::invalid("trailing bytes after metadata items"));
+ }
+ Ok(out)
+}
+
+/// Serializes `shmd` block data.
+pub fn write_shmd(items: &[MetadataItem]) -> Vec<u8> {
+ let mut out = Vec::new();
+ out.put_u32(items.len() as u32);
+ for it in items {
+ out.put(&it.signature);
+ out.put(&it.key);
+ out.push(u8::from(it.copy));
+ out.put(&it.reserved);
+ out.put_u32(it.data.len() as u32);
+ out.put(&it.data);
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn roundtrip_exact() {
+ let items = vec![MetadataItem::new(*b"cmls", vec![1, 2, 3]), MetadataItem { copy: true, ..MetadataItem::new(*b"cust", vec![9; 4]) }];
+ assert_eq!(items[0].data.len(), 4);
+ let bytes = write_shmd(&items);
+ assert_eq!(parse_shmd(&bytes).unwrap(), items);
+ assert_eq!(write_shmd(&parse_shmd(&bytes).unwrap()), bytes);
+ }
+
+ #[test]
+ fn malformed_is_an_error() {
+ assert!(parse_shmd(&[]).is_err());
+ assert!(parse_shmd(&[0, 0, 0, 9]).is_err());
+ let mut b = write_shmd(&[MetadataItem::new(*b"cmls", vec![0; 2])]);
+ b.push(0);
+ assert!(parse_shmd(&b).is_err());
+ b.truncate(b.len() - 3);
+ assert!(parse_shmd(&b).is_err());
+ }
+}
diff --git a/crates/psd/src/patterns.rs b/crates/psd/src/patterns.rs
new file mode 100644
index 000000000..53de5b106
--- /dev/null
+++ b/crates/psd/src/patterns.rs
@@ -0,0 +1,377 @@
+//! Patterns: the global `Patt` / `Pat2` / `Pat3` tagged blocks (8 / 16 / 32-bit documents) and
+//! standalone `.pat` files.
+//!
+//! Layout per the public Photoshop File Formats Specification ("Patterns" and "Virtual Memory
+//! Array List"):
+//!
+//! ```text
+//! pattern := version u32 (1), image mode u32, height i16, width i16,
+//! name (Unicode string), unique id (Pascal string, unpadded),
+//! [indexed: 256 × RGB palette], virtual memory array list
+//! VMA list := version u32 (3), length u32, rect (top, left, bottom, right i32),
+//! channel count u32, then count + 2 arrays (user mask, sheet mask)
+//! array := written u32 (0 = absent), length u32 (0 = absent), depth u32, rect,
+//! depth u16, compression u8 (0 raw, 1 PackBits RLE), data
+//! ```
+//!
+//! In the tagged blocks each pattern is prefixed by its u32 length and padded to 4 bytes; a
+//! `.pat` file is `8BPT`, version u16 (1), count u32, then the patterns without length prefixes.
+//! Photoshop writes the channel count as 24 and only marks the real channels as written; like
+//! ag-psd (MIT) we take the first written arrays as the colour channels and the next one as
+//! transparency.
+
+use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes};
+use crate::error::{PsdError, Result};
+use crate::header::Version;
+
+/// Largest pattern edge accepted (Photoshop's own limit is far lower).
+const MAX_EDGE: u32 = 30_000;
+
+/// One pattern tile with planar, big-endian samples.
+#[derive(Debug, Clone, PartialEq)]
+pub struct PsdPattern {
+ /// PSD colour mode number (1 gray, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab).
+ pub mode: u32,
+ /// Tile width in pixels.
+ pub width: u32,
+ /// Tile height in pixels.
+ pub height: u32,
+ /// Name without the trailing NUL (built-ins look like `$$$/Patterns/…=Water`).
+ pub name: String,
+ /// Unique id (usually a UUID).
+ pub id: String,
+ /// Indexed-colour palette (768 bytes, RGB triplets).
+ pub palette: Option<Vec<u8>>,
+ /// Bits per sample: 1, 8, 16 or 32.
+ pub depth: u16,
+ /// Decoded colour planes (`width × height` samples each).
+ pub channels: Vec<Vec<u8>>,
+ /// Decoded transparency plane, if any.
+ pub alpha: Option<Vec<u8>>,
+}
+
+/// Colour channels implied by a PSD colour mode.
+pub fn mode_channels(mode: u32) -> usize {
+ match mode {
+ 3 | 9 => 3,
+ 4 => 4,
+ _ => 1,
+ }
+}
+
+struct Rd<'a> {
+ b: &'a [u8],
+ p: usize,
+}
+
+impl<'a> Rd<'a> {
+ fn take(&mut self, n: usize) -> Result<&'a [u8]> {
+ let end = self.p.checked_add(n).ok_or(PsdError::LimitExceeded("pattern length overflow"))?;
+ if end > self.b.len() {
+ return Err(PsdError::UnexpectedEof { offset: self.p, needed: end - self.b.len() });
+ }
+ let s = &self.b[self.p..end];
+ self.p = end;
+ Ok(s)
+ }
+ fn u8(&mut self) -> Result<u8> {
+ Ok(self.take(1)?[0])
+ }
+ fn u16(&mut self) -> Result<u16> {
+ let s = self.take(2)?;
+ Ok(u16::from_be_bytes([s[0], s[1]]))
+ }
+ fn u32(&mut self) -> Result<u32> {
+ let s = self.take(4)?;
+ Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
+ }
+ fn i32(&mut self) -> Result<i32> {
+ Ok(self.u32()? as i32)
+ }
+ fn rect(&mut self) -> Result<[i32; 4]> {
+ Ok([self.i32()?, self.i32()?, self.i32()?, self.i32()?])
+ }
+}
+
+fn read_pattern(r: &mut Rd) -> Result<PsdPattern> {
+ let version = r.u32()?;
+ if version != 1 {
+ return Err(PsdError::invalid(format!("pattern version {version}")));
+ }
+ let mode = r.u32()?;
+ let _h = r.u16()?;
+ let _w = r.u16()?;
+ let n = r.u32()? as usize;
+ if n > 65_536 {
+ return Err(PsdError::LimitExceeded("pattern name length"));
+ }
+ let units: Vec<u16> = r.take(n * 2)?.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
+ let name = String::from_utf16_lossy(&units).trim_end_matches('\0').to_string();
+ let idl = r.u8()? as usize;
+ let id = String::from_utf8_lossy(r.take(idl)?).to_string();
+ let palette = if mode == 2 {
+ let p = r.take(768)?.to_vec();
+ // Some writers follow the palette with 4 extra bytes (ag-psd skips them).
+ if r.b.get(r.p..r.p + 4).is_some_and(|v| v != [0, 0, 0, 3]) {
+ r.take(4)?;
+ }
+ Some(p)
+ } else {
+ None
+ };
+ let vver = r.u32()?;
+ if vver != 3 {
+ return Err(PsdError::invalid(format!("virtual memory array list version {vver}")));
+ }
+ let len = r.u32()? as usize;
+ let body = r.take(len)?;
+ let mut v = Rd { b: body, p: 0 };
+ let [top, left, bottom, right] = v.rect()?;
+ let (w, h) = ((right - left).max(0) as u32, (bottom - top).max(0) as u32);
+ if w > MAX_EDGE || h > MAX_EDGE {
+ return Err(PsdError::LimitExceeded("pattern size"));
+ }
+ let count = v.u32()?;
+ if count > 64 {
+ return Err(PsdError::LimitExceeded("pattern channel count"));
+ }
+ let mut planes = Vec::new();
+ let mut depth = 8u16;
+ for _ in 0..count + 2 {
+ if v.p >= body.len() {
+ break;
+ }
+ if v.u32()? == 0 {
+ continue;
+ }
+ let alen = v.u32()? as usize;
+ if alen == 0 {
+ continue;
+ }
+ if alen < 23 {
+ return Err(PsdError::invalid("short virtual memory array"));
+ }
+ let d32 = v.u32()?;
+ let [ct, cl, cb, cr] = v.rect()?;
+ let d16 = v.u16()?;
+ let comp = v.u8()?;
+ let data = v.take(alen - 23)?;
+ let d = if matches!(d16, 1 | 8 | 16 | 32) { d16 } else { d32 as u16 };
+ if !matches!(d, 1 | 8 | 16 | 32) {
+ return Err(PsdError::invalid(format!("pattern depth {d}")));
+ }
+ depth = d;
+ let (cw, ch) = ((cr - cl).max(0) as usize, (cb - ct).max(0) as usize);
+ let layout = PlaneLayout { planes: 1, width: cw, height: ch, depth: d, version: Version::Psd };
+ let compression = if comp == 1 { Compression::Rle } else if comp == 0 { Compression::Raw } else { Compression::Unknown(u16::from(comp)) };
+ let plane = decode_planes(compression, data, &layout)?;
+ // Place a channel rect smaller than the pattern rect into a full plane.
+ let bpp = (usize::from(d) / 8).max(1);
+ let full = if d == 1 || (cw, ch) == (w as usize, h as usize) {
+ plane
+ } else {
+ let mut out = vec![0u8; w as usize * h as usize * bpp];
+ for y in 0..ch {
+ let ty = y as i32 + ct - top;
+ if ty < 0 || ty >= h as i32 {
+ continue;
+ }
+ for x in 0..cw {
+ let tx = x as i32 + cl - left;
+ if tx < 0 || tx >= w as i32 {
+ continue;
+ }
+ let s = (y * cw + x) * bpp;
+ let o = (ty as usize * w as usize + tx as usize) * bpp;
+ out[o..o + bpp].copy_from_slice(&plane[s..s + bpp]);
+ }
+ }
+ out
+ };
+ planes.push(full);
+ }
+ let nc = mode_channels(mode);
+ if planes.len() < nc {
+ return Err(PsdError::invalid("pattern has fewer channels than its colour mode"));
+ }
+ let alpha = (planes.len() > nc).then(|| planes.remove(nc));
+ planes.truncate(nc);
+ Ok(PsdPattern { mode, width: w, height: h, name, id, palette, depth, channels: planes, alpha })
+}
+
+fn write_pattern(p: &PsdPattern, out: &mut Vec<u8>) -> Result<()> {
+ if p.width > MAX_EDGE || p.height > MAX_EDGE || p.width > i16::MAX as u32 || p.height > i16::MAX as u32 {
+ return Err(PsdError::LimitExceeded("pattern size"));
+ }
+ out.extend_from_slice(&1u32.to_be_bytes());
+ out.extend_from_slice(&p.mode.to_be_bytes());
+ out.extend_from_slice(&(p.height as u16).to_be_bytes());
+ out.extend_from_slice(&(p.width as u16).to_be_bytes());
+ let units: Vec<u16> = p.name.encode_utf16().chain(std::iter::once(0)).collect();
+ out.extend_from_slice(&(units.len() as u32).to_be_bytes());
+ for u in units {
+ out.extend_from_slice(&u.to_be_bytes());
+ }
+ let id = p.id.as_bytes();
+ let idl = id.len().min(255);
+ out.push(idl as u8);
+ out.extend_from_slice(&id[..idl]);
+ if p.mode == 2 {
+ let mut pal = p.palette.clone().unwrap_or_default();
+ pal.resize(768, 0);
+ out.extend_from_slice(&pal);
+ }
+ let rect = [0i32, 0, p.height as i32, p.width as i32];
+ let mut body = Vec::new();
+ for v in rect {
+ body.extend_from_slice(&v.to_be_bytes());
+ }
+ const SLOTS: u32 = 24;
+ body.extend_from_slice(&SLOTS.to_be_bytes());
+ let layout = PlaneLayout { planes: 1, width: p.width as usize, height: p.height as usize, depth: p.depth, version: Version::Psd };
+ let array = |plane: &[u8], body: &mut Vec<u8>| -> Result<()> {
+ let (comp, data) = if p.depth == 8 { (1u8, encode_planes(Compression::Rle, plane, &layout)?) } else { (0u8, encode_planes(Compression::Raw, plane, &layout)?) };
+ body.extend_from_slice(&1u32.to_be_bytes());
+ body.extend_from_slice(&((23 + data.len()) as u32).to_be_bytes());
+ body.extend_from_slice(&u32::from(p.depth).to_be_bytes());
+ for v in rect {
+ body.extend_from_slice(&v.to_be_bytes());
+ }
+ body.extend_from_slice(&p.depth.to_be_bytes());
+ body.push(comp);
+ body.extend_from_slice(&data);
+ Ok(())
+ };
+ let nc = p.channels.len().min(SLOTS as usize);
+ for c in &p.channels[..nc] {
+ array(c, &mut body)?;
+ }
+ for _ in nc..SLOTS as usize {
+ body.extend_from_slice(&0u32.to_be_bytes());
+ }
+ // User mask slot: transparency; sheet mask slot: unused.
+ match &p.alpha {
+ Some(a) => array(a, &mut body)?,
+ None => body.extend_from_slice(&0u32.to_be_bytes()),
+ }
+ body.extend_from_slice(&0u32.to_be_bytes());
+ out.extend_from_slice(&3u32.to_be_bytes());
+ out.extend_from_slice(&(body.len() as u32).to_be_bytes());
+ out.extend_from_slice(&body);
+ Ok(())
+}
+
+/// Parses the data of a `Patt` / `Pat2` / `Pat3` global block.
+pub fn parse_pattern_block(data: &[u8]) -> Result<Vec<PsdPattern>> {
+ let mut r = Rd { b: data, p: 0 };
+ let mut out = Vec::new();
+ while r.p + 4 <= data.len() {
+ let len = r.u32()? as usize;
+ if len == 0 {
+ break;
+ }
+ let body = r.take(len)?;
+ out.push(read_pattern(&mut Rd { b: body, p: 0 })?);
+ let pad = (4 - len % 4) % 4;
+ r.p = (r.p + pad).min(data.len());
+ }
+ Ok(out)
+}
+
+/// Serializes patterns as `Patt` / `Pat2` / `Pat3` block data.
+pub fn write_pattern_block(patterns: &[PsdPattern]) -> Result<Vec<u8>> {
+ let mut out = Vec::new();
+ for p in patterns {
+ let mut one = Vec::new();
+ write_pattern(p, &mut one)?;
+ out.extend_from_slice(&(one.len() as u32).to_be_bytes());
+ let pad = (4 - one.len() % 4) % 4;
+ out.extend_from_slice(&one);
+ out.extend(std::iter::repeat_n(0u8, pad));
+ }
+ Ok(out)
+}
+
+/// Tagged-block key for patterns of a document at `depth` bits.
+pub fn block_key(depth: u16) -> [u8; 4] {
+ match depth {
+ 16 => *b"Pat2",
+ 32 => *b"Pat3",
+ _ => *b"Patt",
+ }
+}
+
+/// Parses a `.pat` pattern file.
+pub fn parse_pat_file(data: &[u8]) -> Result<Vec<PsdPattern>> {
+ let mut r = Rd { b: data, p: 0 };
+ let sig = r.take(4)?;
+ if sig != b"8BPT" {
+ return Err(PsdError::InvalidSignature { expected: "8BPT", found: [sig[0], sig[1], sig[2], sig[3]] });
+ }
+ let _version = r.u16()?;
+ let count = r.u32()?;
+ let mut out = Vec::new();
+ for _ in 0..count.min(100_000) {
+ out.push(read_pattern(&mut r)?);
+ }
+ Ok(out)
+}
+
+/// Writes a `.pat` pattern file.
+pub fn write_pat_file(patterns: &[PsdPattern]) -> Result<Vec<u8>> {
+ let mut out = b"8BPT".to_vec();
+ out.extend_from_slice(&1u16.to_be_bytes());
+ out.extend_from_slice(&(patterns.len() as u32).to_be_bytes());
+ for p in patterns {
+ write_pattern(p, &mut out)?;
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn pat(depth: u16, alpha: bool) -> PsdPattern {
+ let (w, h) = (5u32, 3u32);
+ let bpp = usize::from(depth / 8);
+ let plane = |s: u8| (0..w as usize * h as usize * bpp).map(|i| (i as u8).wrapping_mul(7).wrapping_add(s)).collect::<Vec<u8>>();
+ PsdPattern {
+ mode: 3,
+ width: w,
+ height: h,
+ name: "Test ✓".into(),
+ id: "0bd2d3ba-1234-11d4-8f8f-aabbccddeeff".into(),
+ palette: None,
+ depth,
+ channels: vec![plane(1), plane(2), plane(3)],
+ alpha: alpha.then(|| plane(9)),
+ }
+ }
+
+ #[test]
+ fn block_and_pat_file_round_trip_at_every_depth() {
+ for depth in [8, 16, 32] {
+ for alpha in [false, true] {
+ let ps = vec![pat(depth, alpha), PsdPattern { name: "Second".into(), ..pat(depth, false) }];
+ let blk = write_pattern_block(&ps).unwrap();
+ assert_eq!(blk.len() % 4, 0);
+ assert_eq!(parse_pattern_block(&blk).unwrap(), ps);
+ let f = write_pat_file(&ps).unwrap();
+ assert_eq!(parse_pat_file(&f).unwrap(), ps);
+ // Re-serialising is byte-stable.
+ assert_eq!(write_pattern_block(&parse_pattern_block(&blk).unwrap()).unwrap(), blk);
+ }
+ }
+ }
+
+ #[test]
+ fn malformed_input_errors_without_panicking() {
+ let blk = write_pattern_block(&[pat(8, true)]).unwrap();
+ for cut in [3, 10, 40, blk.len() - 5] {
+ let _ = parse_pattern_block(&blk[..cut]);
+ }
+ assert!(parse_pat_file(b"8BPS\0\x01").is_err());
+ assert!(parse_pattern_block(&[]).unwrap().is_empty());
+ }
+}
diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs
index 349e1ae07..991cf1c53 100644
--- a/crates/raster/src/lib.rs
+++ b/crates/raster/src/lib.rs
@@ -465,7 +465,7 @@ impl Surface {
out
}
- /// Convert to another pixel format (depth and/or model, naive colour conversion).
+ /// Convert to another pixel format (depth and/or model; colour models via [`convert_pixel`]).
pub fn convert(&self, to: PixelFormat) -> Surface {
let mut out = Surface::with_default(to, &convert_pixel(&self.format, &to, &self.default_pixel()));
let from_n = self.channels();
@@ -504,7 +504,8 @@ pub fn decode_pixel(format: &PixelFormat, bytes: &[u8]) -> Vec<f32> {
(0..format.channels()).map(|i| read_sample(bytes, format.sample, i)).collect()
}
-/// Convert one pixel between formats via RGBA (naive colour conversion, no ICC).
+/// Convert one pixel between formats via sRGB RGBA (CMYK through the built-in CMYK profile;
+/// the engine's mode conversions use the document's profiles instead).
pub fn convert_pixel(from: &PixelFormat, to: &PixelFormat, px: &[f32]) -> Vec<f32> {
if from.mode == to.mode {
let n = from.mode.color_channels();
@@ -523,7 +524,7 @@ pub fn to_rgba(format: &PixelFormat, px: &[f32]) -> [f32; 4] {
let a = if format.alpha { px[n] } else { 1.0 };
let rgb = match format.mode {
ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => [px[0]; 3],
- ColorMode::Cmyk => photocraft_color::convert::cmyk_to_rgb_naive([px[0], px[1], px[2], px[3]]),
+ ColorMode::Cmyk => photocraft_color::convert::cmyk_to_rgb([px[0], px[1], px[2], px[3]]),
ColorMode::Lab => photocraft_color::convert::lab_to_srgb([px[0] * 100.0, px[1] * 255.0 - 128.0, px[2] * 255.0 - 128.0]),
_ => [px[0], px[1], px[2]],
};
@@ -534,7 +535,7 @@ pub fn from_rgba(format: &PixelFormat, rgba: [f32; 4]) -> Vec<f32> {
let rgb = [rgba[0], rgba[1], rgba[2]];
let mut out: Vec<f32> = match format.mode {
ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => vec![photocraft_color::convert::rgb_to_gray(rgb)],
- ColorMode::Cmyk => photocraft_color::convert::rgb_to_cmyk_naive(rgb).to_vec(),
+ ColorMode::Cmyk => photocraft_color::convert::rgb_to_cmyk(rgb).to_vec(),
ColorMode::Lab => {
let l = photocraft_color::convert::srgb_to_lab(rgb);
vec![l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0]
@@ -558,7 +559,7 @@ pub fn from_rgba_into(format: &PixelFormat, rgba: [f32; 4], out: &mut [f32]) ->
1
}
ColorMode::Cmyk => {
- out[..4].copy_from_slice(&photocraft_color::convert::rgb_to_cmyk_naive(rgb));
+ out[..4].copy_from_slice(&photocraft_color::convert::rgb_to_cmyk(rgb));
4
}
ColorMode::Lab => {
diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs
index 59f171f11..d94e68f6f 100644
--- a/crates/text/src/lib.rs
+++ b/crates/text/src/lib.rs
@@ -19,6 +19,7 @@ pub mod layout;
pub mod psd;
pub mod raster;
pub mod render;
+pub mod warp;
use photocraft_color::PixelFormat;
use photocraft_doc::TextLayer;
@@ -69,7 +70,9 @@ impl TextEngine {
format: PixelFormat,
) -> (TextLayout, Rendered) {
let l = self.layout(layer, dpi);
- let r = render::rasterize(&l, &layer.transform, format, layer.antialias);
+ let warp = render::layout_warp(&l, layer.warp.as_ref());
+ let r =
+ render::rasterize_warped(&l, &layer.transform, format, layer.antialias, warp.as_ref());
(l, r)
}
diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs
index fb4a71c3e..c0909c6c6 100644
--- a/crates/text/src/psd.rs
+++ b/crates/text/src/psd.rs
@@ -140,10 +140,12 @@ pub fn text_layer_from_tysh(data: &[u8], dpi: f32) -> Option<TextLayer> {
Orientation::Horizontal
};
layer.antialias = match enum_value(&t.text, "AntA").as_deref() {
- Some("Anno") => AntiAlias::None,
+ Some("Anno" | "antiAliasNone") => AntiAlias::None,
Some("antiAliasSharp" | "AnSh") => AntiAlias::Sharp,
- Some("AnCr") => AntiAlias::Crisp,
- Some("AnSt") => AntiAlias::Strong,
+ Some("AnCr" | "antiAliasCrisp") => AntiAlias::Crisp,
+ Some("AnSt" | "antiAliasStrong") => AntiAlias::Strong,
+ Some("antiAliasPlatformGray") => AntiAlias::Windows,
+ Some("antiAliasPlatformLCD") => AntiAlias::WindowsLcd,
_ => AntiAlias::Smooth,
};
if let Some(w) = &t.warp {
@@ -334,6 +336,14 @@ fn char_style(base: Option<&E>, d: &E, fonts: &[String], k: f32) -> CharStyle {
s.strikethrough = flag("Strikethrough").unwrap_or(false);
s.ligatures = flag("Ligatures").unwrap_or(true);
s.discretionary_ligatures = flag("DLigatures").unwrap_or(false);
+ for (key, tag) in OPENTYPE_KEYS {
+ if flag(key) == Some(true) {
+ s.features.push(photocraft_doc::text::FontFeature {
+ tag: tag.to_string(),
+ value: 1,
+ });
+ }
+ }
s.kerning = if flag("AutoKerning") == Some(false) {
Kerning::Off
} else {
@@ -425,6 +435,19 @@ fn postscript_for(s: &CharStyle) -> String {
format!("{}-{style}", fam.replace(' ', ""))
}
+/// EngineData style keys for the Type › OpenType toggles and the OpenType feature each one turns
+/// on (the standard and discretionary ligature keys map to dedicated [`CharStyle`] fields).
+pub const OPENTYPE_KEYS: [(&str, &str); 8] = [
+ ("ContextualLigatures", "calt"),
+ ("Swash", "swsh"),
+ ("OldStyle", "onum"),
+ ("StylisticAlternates", "salt"),
+ ("Titling", "titl"),
+ ("Ornaments", "ornm"),
+ ("Ordinals", "ordn"),
+ ("Fractions", "frac"),
+];
+
fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E {
let c = &s.color;
let values = match c.mode {
@@ -446,7 +469,12 @@ fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E {
ColorMode::Grayscale => 0,
_ => 1,
};
- E::Dict(vec![
+ let mut opentype: Vec<(String, E)> = OPENTYPE_KEYS
+ .iter()
+ .filter(|(_, tag)| s.features.iter().any(|f| f.tag == *tag && f.value > 0))
+ .map(|(key, _)| (key.to_string(), E::Bool(true)))
+ .collect();
+ let mut dict = vec![
("Font".into(), E::Int(font as i64)),
("FontSize".into(), real(s.size_pt / k)),
("FauxBold".into(), E::Bool(s.faux_bold)),
@@ -478,7 +506,9 @@ fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E {
("Values".into(), E::Array(values)),
]),
),
- ])
+ ];
+ dict.append(&mut opentype);
+ E::Dict(dict)
}
fn paragraph_properties(p: &ParagraphStyle, k: f32) -> E {
@@ -615,6 +645,8 @@ pub fn build_engine_data(layer: &TextLayer, template: Option<E>, dpi: f32) -> E
AntiAlias::Crisp => 2,
AntiAlias::Strong => 3,
AntiAlias::Smooth => 4,
+ // EngineData has no platform modes; the `AntA` descriptor carries the exact value.
+ AntiAlias::Windows | AntiAlias::WindowsLcd => 1,
}),
);
if dict.get("UseFractionalGlyphWidths").is_none() {
@@ -767,6 +799,8 @@ pub fn build_tysh(layer: &TextLayer, dpi: f32, ink: Option<[f32; 4]>) -> Vec<u8>
AntiAlias::Crisp => "AnCr",
AntiAlias::Strong => "AnSt",
AntiAlias::Smooth => "AnSm",
+ AntiAlias::Windows => "antiAliasPlatformGray",
+ AntiAlias::WindowsLcd => "antiAliasPlatformLCD",
},
),
);
diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs
index cbfc72b3f..144ace683 100644
--- a/crates/text/src/render.rs
+++ b/crates/text/src/render.rs
@@ -10,6 +10,7 @@ use skrifa::{GlyphId, MetadataProvider};
use crate::layout::TextLayout;
use crate::raster::{Bounds, Coverage, LineSink, Pen, Xform, rect_to};
+use crate::warp::Warp;
/// Faux-italic slant in degrees (Photoshop-like).
pub const FAUX_ITALIC_DEG: f32 = 12.0;
@@ -24,13 +25,41 @@ pub struct Rendered {
pub rect: Rect,
}
+/// Bends text-space lines with a [`Warp`], then maps them through `post` into `inner`.
+struct WarpSink<'a, S: LineSink> {
+ inner: &'a mut S,
+ warp: &'a Warp,
+ post: Xform,
+}
+
+impl<S: LineSink> LineSink for WarpSink<'_, S> {
+ fn line(&mut self, p0: (f64, f64), p1: (f64, f64)) {
+ let len = ((p1.0 - p0.0).powi(2) + (p1.1 - p0.1).powi(2)).sqrt();
+ let n = ((len / self.warp.max_segment()).ceil() as usize).clamp(1, 256);
+ let map = |t: f64| {
+ let (x, y) = self
+ .warp
+ .apply(p0.0 + (p1.0 - p0.0) * t, p0.1 + (p1.1 - p0.1) * t);
+ self.post.apply(x, y)
+ };
+ let mut a = map(0.0);
+ for i in 1..=n {
+ let b = map(i as f64 / n as f64);
+ self.inner.line(a, b);
+ a = b;
+ }
+ }
+}
+
/// 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).
+/// when `color` is `None`) into `sink`, through `transform` (text space → sink space), bending
+/// the outlines with `warp` first (in text space).
fn draw(
layout: &TextLayout,
transform: &Xform,
sink: &mut impl LineSink,
only_color: Option<&Color>,
+ warp: Option<&Warp>,
) {
for g in &layout.glyphs {
let st = &layout.styles[g.style as usize];
@@ -80,14 +109,27 @@ fn draw(
&[(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 local = Xform([1.0, 0.0, 0.0, 1.0, ox * r, oy * r]).mul(&glyph);
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);
+ match warp {
+ Some(w) => {
+ let mut ws = WarpSink {
+ inner: &mut *sink,
+ warp: w,
+ post: *transform,
+ };
+ let mut pen = Pen::new(&mut ws, local);
+ if outline.draw(settings, &mut pen).is_ok() {
+ skrifa::outline::OutlinePen::close(&mut pen);
+ }
+ }
+ None => {
+ let mut pen = Pen::new(&mut *sink, transform.mul(&local));
+ if outline.draw(settings, &mut pen).is_ok() {
+ skrifa::outline::OutlinePen::close(&mut pen);
+ }
+ }
}
}
}
@@ -96,17 +138,42 @@ fn draw(
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,
- );
+ match warp {
+ Some(w) => {
+ let mut ws = WarpSink {
+ inner: &mut *sink,
+ warp: w,
+ post: *transform,
+ };
+ rect_to(
+ &mut ws,
+ &Xform::IDENTITY,
+ d.x0 as f64,
+ d.y0 as f64,
+ d.x1 as f64,
+ d.y1 as f64,
+ );
+ }
+ None => rect_to(
+ sink,
+ transform,
+ d.x0 as f64,
+ d.y0 as f64,
+ d.x1 as f64,
+ d.y1 as f64,
+ ),
+ }
}
}
+/// The warp to apply to `layout` (None when `warp` is absent, `warpNone` or flat).
+pub fn layout_warp(
+ layout: &TextLayout,
+ warp: Option<&photocraft_doc::text::TextWarp>,
+) -> Option<Warp> {
+ Warp::new(warp?, layout.bounds()?)
+}
+
/// Colour components in `format`'s model (without alpha).
fn color_in(format: &PixelFormat, c: &Color) -> Vec<f32> {
let n = format.mode.color_channels();
@@ -128,8 +195,13 @@ fn color_in(format: &PixelFormat, c: &Color) -> Vec<f32> {
/// Document-space bounds of the drawn text (integer pixel rectangle).
pub fn ink_rect(layout: &TextLayout, transform: &Affine) -> Rect {
+ ink_rect_warped(layout, transform, None)
+}
+
+/// [`ink_rect`] of warped text.
+pub fn ink_rect_warped(layout: &TextLayout, transform: &Affine, warp: Option<&Warp>) -> Rect {
let mut b = Bounds::default();
- draw(layout, &Xform(transform.m), &mut b, None);
+ draw(layout, &Xform(transform.m), &mut b, None, warp);
match b.rect {
Some([x0, y0, x1, y1]) => Rect::new(
x0.floor() as i32 - 1,
@@ -148,12 +220,23 @@ pub fn rasterize(
transform: &Affine,
format: PixelFormat,
antialias: AntiAlias,
+) -> Rendered {
+ rasterize_warped(layout, transform, format, antialias, None)
+}
+
+/// [`rasterize`] with the glyph outlines bent by `warp` (Type › Warp Text).
+pub fn rasterize_warped(
+ layout: &TextLayout,
+ transform: &Affine,
+ format: PixelFormat,
+ antialias: AntiAlias,
+ warp: Option<&Warp>,
) -> Rendered {
let format = PixelFormat {
alpha: true,
..format
};
- let rect = ink_rect(layout, transform);
+ let rect = ink_rect_warped(layout, transform, warp);
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 {
@@ -175,7 +258,7 @@ pub fn rasterize(
}
for c in &colors {
let mut cov = Coverage::new(w, h);
- draw(layout, &xf, &mut cov, Some(c));
+ draw(layout, &xf, &mut cov, Some(c), warp);
let cov = cov.finish();
let comps = color_in(&format, c);
let a = c.alpha.clamp(0.0, 1.0);
@@ -210,3 +293,104 @@ pub fn rasterize(
surface.prune();
Rendered { surface, rect }
}
+
+/// One element of a glyph outline in document space (see [`outlines`]).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum PathEl {
+ MoveTo([f64; 2]),
+ LineTo([f64; 2]),
+ QuadTo([f64; 2], [f64; 2]),
+ CurveTo([f64; 2], [f64; 2], [f64; 2]),
+ Close,
+}
+
+/// Records outline commands through a text→document map (and an optional warp).
+struct Recorder<'a> {
+ glyph: Xform,
+ post: Xform,
+ warp: Option<&'a Warp>,
+ out: Vec<PathEl>,
+}
+
+impl Recorder<'_> {
+ fn map(&self, x: f32, y: f32) -> [f64; 2] {
+ let (tx, ty) = self.glyph.apply(f64::from(x), f64::from(y));
+ let (tx, ty) = match self.warp {
+ Some(w) => w.apply(tx, ty),
+ None => (tx, ty),
+ };
+ let (dx, dy) = self.post.apply(tx, ty);
+ [dx, dy]
+ }
+}
+
+impl skrifa::outline::OutlinePen for Recorder<'_> {
+ fn move_to(&mut self, x: f32, y: f32) {
+ let p = self.map(x, y);
+ self.out.push(PathEl::MoveTo(p));
+ }
+ fn line_to(&mut self, x: f32, y: f32) {
+ let p = self.map(x, y);
+ self.out.push(PathEl::LineTo(p));
+ }
+ fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
+ let (c, p) = (self.map(cx0, cy0), self.map(x, y));
+ self.out.push(PathEl::QuadTo(c, p));
+ }
+ fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
+ let (a, b, p) = (self.map(cx0, cy0), self.map(cx1, cy1), self.map(x, y));
+ self.out.push(PathEl::CurveTo(a, b, p));
+ }
+ fn close(&mut self) {
+ self.out.push(PathEl::Close);
+ }
+}
+
+/// Glyph outlines of `layout` in document space (through `transform`, bent by `warp`), one
+/// element list per glyph, for Type › Create Work Path and Convert to Shape. Faux bold is not
+/// applied (Photoshop also converts the regular outline); faux italic and scaling are. Under a
+/// warp, control points are mapped directly, which is exact for straight segments and a close
+/// approximation for curves.
+pub fn outlines(layout: &TextLayout, transform: &Affine, warp: Option<&Warp>) -> Vec<Vec<PathEl>> {
+ let mut glyphs = Vec::new();
+ for g in &layout.glyphs {
+ let st = &layout.styles[g.style as usize];
+ 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 mut rec = Recorder {
+ glyph,
+ post: Xform(transform.m),
+ warp,
+ out: Vec::new(),
+ };
+ let settings = DrawSettings::unhinted(Size::new(face.size_px), LocationRef::new(&coords));
+ if outline.draw(settings, &mut rec).is_ok() && !rec.out.is_empty() {
+ glyphs.push(rec.out);
+ }
+ }
+ glyphs
+}
diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs
index 96b55ed4f..fd0626875 100644
--- a/crates/text/src/tests.rs
+++ b/crates/text/src/tests.rs
@@ -748,3 +748,106 @@ fn variable_font_axes() {
let heavy = ink(&mut e, 800.0);
assert!(heavy > light * 1.5, "{light} → {heavy}");
}
+
+#[test]
+fn warp_bends_rendered_text_and_outlines() {
+ use photocraft_doc::text::TextWarp;
+ let mut e = TextEngine::new();
+ let mut t = point("WARPED TEXT", 24.0);
+ t.transform = Affine::translate(20.0, 60.0);
+ let fmt = PixelFormat::RGBA8;
+ let (_, flat) = e.render(&t, 72.0, fmt);
+ t.warp = Some(TextWarp {
+ style: "warpArc".into(),
+ value: 60.0,
+ horizontal: true,
+ ..Default::default()
+ });
+ let (layout, arced) = e.render(&t, 72.0, fmt);
+ // An arc pushes the ends down: the warped ink is taller and pixels differ.
+ assert!(
+ arced.rect.height() > flat.rect.height() + 10,
+ "{:?} vs {:?}",
+ arced.rect,
+ flat.rect
+ );
+ assert!(alpha_sum(&arced.surface, arced.rect) > 0.0);
+ // Outlines follow the same warp: the first glyph's outline sits lower than the middle one's.
+ let warp = crate::render::layout_warp(&layout, t.warp.as_ref());
+ let outs = crate::render::outlines(&layout, &t.transform, warp.as_ref());
+ assert_eq!(
+ outs.len(),
+ layout.glyphs.iter().filter(|g| g.id != 0).count() - 1,
+ "space has no outline"
+ );
+ let low_y = |els: &Vec<crate::render::PathEl>| {
+ els.iter()
+ .filter_map(|e| match e {
+ crate::render::PathEl::MoveTo(p) | crate::render::PathEl::LineTo(p) => Some(p[1]),
+ _ => None,
+ })
+ .fold(f64::MIN, f64::max)
+ };
+ assert!(low_y(&outs[0]) > low_y(&outs[outs.len() / 2]) + 5.0);
+ // Unwarped outlines stay within the flat raster's bounds.
+ let flat_outs = crate::render::outlines(&layout, &t.transform, None);
+ let r = flat.rect;
+ for els in &flat_outs {
+ for el in els {
+ if let crate::render::PathEl::MoveTo(p) | crate::render::PathEl::LineTo(p) = el {
+ assert!(
+ p[0] >= f64::from(r.x0)
+ && p[0] <= f64::from(r.x1)
+ && p[1] >= f64::from(r.y0)
+ && p[1] <= f64::from(r.y1)
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn psd_round_trips_antialias_opentype_and_warp() {
+ use photocraft_doc::text::{AntiAlias, TextWarp};
+ let style = CharStyle {
+ font_family: "Inter".into(),
+ size_pt: 20.0,
+ features: vec![
+ FontFeature {
+ tag: "swsh".into(),
+ value: 1,
+ },
+ FontFeature {
+ tag: "frac".into(),
+ value: 1,
+ },
+ ],
+ discretionary_ligatures: true,
+ ..Default::default()
+ };
+ for aa in [
+ AntiAlias::Windows,
+ AntiAlias::WindowsLcd,
+ AntiAlias::Crisp,
+ AntiAlias::None,
+ ] {
+ let mut t = styled("1/2 Swash", style.clone());
+ t.antialias = aa;
+ t.warp = Some(TextWarp {
+ style: "warpFlag".into(),
+ value: -35.0,
+ horizontal_distortion: 10.0,
+ vertical_distortion: 0.0,
+ horizontal: false,
+ });
+ let bytes = crate::psd::build_tysh(&t, 72.0, None);
+ let back = crate::psd::text_layer_from_tysh(&bytes, 72.0).unwrap();
+ assert_eq!(back.antialias, aa);
+ assert_eq!(back.warp, t.warp);
+ let st = &back.char_runs()[0].style;
+ assert!(st.discretionary_ligatures);
+ let mut tags: Vec<&str> = st.features.iter().map(|f| f.tag.as_str()).collect();
+ tags.sort_unstable();
+ assert_eq!(tags, ["frac", "swsh"]);
+ }
+}
diff --git a/crates/text/src/warp.rs b/crates/text/src/warp.rs
new file mode 100644
index 000000000..9cd8968b3
--- /dev/null
+++ b/crates/text/src/warp.rs
@@ -0,0 +1,143 @@
+//! Warp Text: bends the glyph outlines of a type layer with one of Photoshop's fifteen warp
+//! styles (the PSD `warp` descriptor's `warpStyle`).
+//!
+//! The style math lives in `photocraft_geom::warp` (shared with Edit › Transform › Warp): our
+//! own closed-form approximations of each style's look (observed behaviour, not Adobe's
+//! formulas), the identity at `bend = 0` and continuous in `bend`. The mapping is evaluated per
+//! point; the renderer subdivides long segments so straight edges bend.
+
+use photocraft_doc::text::TextWarp;
+use photocraft_geom::warp::{StyleWarp, WarpStyle};
+
+/// Warp styles in Photoshop's menu order: (PSD `warpStyle` value, short id used by commands).
+pub const STYLES: [(&str, &str); 15] = [
+ ("warpArc", "arc"),
+ ("warpArcLower", "arcLower"),
+ ("warpArcUpper", "arcUpper"),
+ ("warpArch", "arch"),
+ ("warpBulge", "bulge"),
+ ("warpShellLower", "shellLower"),
+ ("warpShellUpper", "shellUpper"),
+ ("warpFlag", "flag"),
+ ("warpWave", "wave"),
+ ("warpFish", "fish"),
+ ("warpRise", "rise"),
+ ("warpFisheye", "fisheye"),
+ ("warpInflate", "inflate"),
+ ("warpSqueeze", "squeeze"),
+ ("warpTwist", "twist"),
+];
+
+/// PSD style name (`warpArc`) for a short id (`arc`, case-insensitive) or a PSD name.
+pub fn psd_style(id: &str) -> Option<&'static str> {
+ let l = id.to_ascii_lowercase();
+ if l == "none" || l == "warpnone" {
+ return Some("warpNone");
+ }
+ STYLES
+ .iter()
+ .find(|(psd, short)| psd.to_ascii_lowercase() == l || short.to_ascii_lowercase() == l)
+ .map(|(psd, _)| *psd)
+}
+
+/// A warp prepared for one layout: the shared style math of
+/// [`photocraft_geom::warp::StyleWarp`] (also used by Edit › Transform › Warp) over the text box.
+#[derive(Clone, Copy, Debug)]
+pub struct Warp(StyleWarp);
+
+impl Warp {
+ /// Prepares `w` for text whose bounds are `[x0, y0, x1, y1]` (text space). `None` for
+ /// `warpNone`, unknown styles, an all-zero warp or empty bounds.
+ pub fn new(w: &TextWarp, bounds: [f32; 4]) -> Option<Warp> {
+ let style = WarpStyle::parse(&w.style).filter(|s| s.is_preset() && s.psd_name() == w.style)?;
+ StyleWarp::new(
+ style,
+ f64::from(w.value),
+ f64::from(w.horizontal_distortion),
+ f64::from(w.vertical_distortion),
+ !w.horizontal,
+ bounds.map(f64::from),
+ )
+ .map(Warp)
+ }
+
+ /// Longest segment (text-space px) worth sending through [`Warp::apply`] unsplit.
+ pub fn max_segment(&self) -> f64 {
+ self.0.max_segment()
+ }
+
+ /// Maps a text-space point.
+ pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {
+ self.0.apply(x, y)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn warp(style: &str, value: f32) -> Warp {
+ let w = TextWarp {
+ style: psd_style(style).unwrap().into(),
+ value,
+ horizontal_distortion: 0.0,
+ vertical_distortion: 0.0,
+ horizontal: true,
+ };
+ Warp::new(&w, [0.0, -40.0, 200.0, 10.0]).unwrap()
+ }
+
+ #[test]
+ fn styles_resolve_and_none_is_identity() {
+ assert_eq!(psd_style("Arc"), Some("warpArc"));
+ assert_eq!(psd_style("warpTwist"), Some("warpTwist"));
+ assert_eq!(psd_style("none"), Some("warpNone"));
+ assert_eq!(psd_style("spiral"), None);
+ let none = TextWarp {
+ style: "warpNone".into(),
+ value: 50.0,
+ ..Default::default()
+ };
+ assert!(Warp::new(&none, [0.0, 0.0, 10.0, 10.0]).is_none());
+ let flat = TextWarp {
+ style: "warpArc".into(),
+ value: 0.0,
+ ..Default::default()
+ };
+ assert!(Warp::new(&flat, [0.0, 0.0, 10.0, 10.0]).is_none());
+ }
+
+ #[test]
+ fn every_style_is_continuous_and_fixes_the_centre_column() {
+ for (_, id) in STYLES {
+ let w = warp(id, 50.0);
+ let (x, y) = w.apply(100.0, -15.0);
+ assert!(x.is_finite() && y.is_finite(), "{id}");
+ // Tiny bends barely move anything.
+ let t = warp(id, 0.5);
+ let (x2, y2) = t.apply(20.0, 0.0);
+ assert!((x2 - 20.0).abs() < 2.0 && y2.abs() < 2.0, "{id}: {x2},{y2}");
+ }
+ }
+
+ #[test]
+ fn arc_raises_the_middle_relative_to_the_ends() {
+ let w = warp("arc", 50.0);
+ let mid = w.apply(100.0, -15.0);
+ let end = w.apply(0.0, -15.0);
+ assert!((mid.1 - -15.0).abs() < 1e-9, "centre stays put");
+ assert!(end.1 > mid.1 + 5.0, "ends drop below the centre: {end:?}");
+ assert!(end.0 > 0.0, "ends pull inwards along the arc");
+ // A negative bend smiles.
+ let s = warp("arc", -50.0);
+ assert!(s.apply(0.0, -15.0).1 < -20.0);
+ }
+
+ #[test]
+ fn bulge_and_squeeze_change_height_in_the_middle() {
+ let b = warp("bulge", 50.0);
+ assert!(b.apply(100.0, -40.0).1 < -50.0);
+ let s = warp("squeeze", 50.0);
+ assert!(s.apply(100.0, -40.0).1 > -40.0);
+ }
+}
diff --git a/crates/ui-egui/examples/fx_bench.rs b/crates/ui-egui/examples/fx_bench.rs
new file mode 100644
index 000000000..a9549ab28
--- /dev/null
+++ b/crates/ui-egui/examples/fx_bench.rs
@@ -0,0 +1,191 @@
+//! Layer-effect compositing benchmark: CPU (`photocraft-compose`) vs GPU (`photocraft-gpu`).
+//!
+//! ```sh
+//! cargo run --release -p photocraft-ui-egui --example fx_bench -- [--size 7360x4912] [--psd file.psd]
+//! ```
+//!
+//! Builds a synthetic document (default 36 MP) with text layers carrying drop shadow + stroke +
+//! bevel, a painted raster layer with effects and an adjustment layer on top, then times a full
+//! refresh (cold and warm effect caches) and the incremental cases the canvas sees: an adjustment
+//! tweak (full refresh, maps cached), a brush dab on a plain layer and a brush dab on the effect
+//! layer (damage rect grown by the effect reach). `--psd` times a real file instead.
+
+use std::time::Instant;
+
+use eframe::wgpu;
+use photocraft_color::{BlendMode, Color, ColorMode, SampleType};
+use photocraft_doc::{Adjustment, Bevel, BevelStyle, BevelTechnique, Contour, Document, Effect, FxCommon, FxPaint, Layer, LayerContent, StrokeFx, StrokePosition};
+use photocraft_geom::{Rect, Size};
+use serde_json::json;
+
+fn arg(args: &[String], name: &str) -> Option<String> {
+ args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())
+}
+
+fn block_on<F: std::future::Future>(f: F) -> F::Output {
+ let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
+ let mut f = std::pin::pin!(f);
+ loop {
+ if let std::task::Poll::Ready(v) = f.as_mut().poll(&mut cx) {
+ return v;
+ }
+ std::thread::yield_now();
+ }
+}
+
+fn effects() -> Vec<Effect> {
+ let Effect::DropShadow(mut ds) = Effect::default_drop_shadow() else { unreachable!() };
+ ds.distance = 12.0;
+ ds.size = 16.0;
+ vec![
+ Effect::DropShadow(ds),
+ Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size: 6.0, position: StrokePosition::Outside, paint: FxPaint::Color(Color::rgb(0.95, 0.85, 0.2)) }),
+ Effect::BevelEmboss(Bevel {
+ enabled: true,
+ style: BevelStyle::InnerBevel,
+ technique: BevelTechnique::Smooth,
+ depth: 1.0,
+ up: true,
+ size: 10.0,
+ soften: 2.0,
+ angle: 120.0,
+ altitude: 30.0,
+ use_global_light: true,
+ gloss_contour: Contour::Linear,
+ highlight: FxCommon::new(BlendMode::Screen, 0.75),
+ highlight_color: Color::WHITE,
+ shadow: FxCommon::new(BlendMode::Multiply, 0.75),
+ shadow_color: Color::BLACK,
+ }),
+ ]
+}
+
+fn synthetic(w: u32, h: u32) -> Document {
+ let mut d = Document::with_background("fx", Size::new(w, h), ColorMode::Rgb, SampleType::U8, Color::rgb(0.82, 0.86, 0.9));
+ // Some colour blocks on the background.
+ for i in 0..12 {
+ let x = (i * 613 % w as i32).max(0);
+ let y = (i * 389 % h as i32).max(0);
+ let c = [(i as f32 * 0.13) % 1.0, (i as f32 * 0.29) % 1.0, (i as f32 * 0.41) % 1.0, 1.0];
+ d.layers[0].surface_mut().unwrap().fill_rect(Rect::new(x, y, x + w as i32 / 5, y + h as i32 / 6), &c);
+ }
+ let mut paint = Layer::raster("paint", d.pixel_format());
+ paint.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 20, 20), &[0.0, 0.0, 0.0, 1.0]);
+ d.layers.push(paint);
+ let mut blob = Layer::raster("blob", d.pixel_format());
+ let (bw, bh) = (w as i32 / 4, h as i32 / 4);
+ for k in 0..40 {
+ let r = Rect::new(w as i32 / 2 - bw / 2 + k * 9, h as i32 / 2 - bh / 2 + k * 5, w as i32 / 2 + bw / 2 - k * 4, h as i32 / 2 + bh / 2 - k * 7);
+ blob.surface_mut().unwrap().fill_rect(r, &[0.2 + k as f32 * 0.01, 0.4, 0.8, 1.0]);
+ }
+ blob.effects.items = effects();
+ d.layers.push(blob);
+
+ // Text layers through the engine (real glyph rasterization).
+ let mut s = photocraft_engine::Session::new();
+ s.add_document(d, None);
+ let lines = ["Photocraft", "Layer Effects", "on the GPU", "Drop Shadow", "Stroke", "Bevel & Emboss", "36 megapixels", "interactive"];
+ let rows = lines.len() as u32;
+ for (i, t) in lines.iter().enumerate() {
+ let y = (h / (rows + 1)) * (i as u32 + 1);
+ let r = s.execute("type.create", json!({"x": (w / 12) as i32 + (i as i32 % 3) * 300, "y": y, "text": t, "size": (h / rows / 2).max(12), "color": "#d04020"}));
+ if let Err(e) = r {
+ eprintln!("type.create: {e}");
+ }
+ }
+ let mut doc = (*s.active().unwrap().doc).clone();
+ for l in &mut doc.layers {
+ if matches!(l.content, LayerContent::Text(_)) {
+ l.effects.items = effects();
+ }
+ }
+ let mut adj = Layer::new("curves", LayerContent::Adjustment(Adjustment::HueSaturation { hue: 10.0, saturation: 10.0, lightness: 0.0, colorize: false }));
+ adj.opacity = 0.9;
+ doc.layers.push(adj);
+ doc
+}
+
+struct Gpu {
+ device: wgpu::Device,
+ queue: wgpu::Queue,
+ comp: photocraft_gpu::Compositor,
+}
+
+fn gpu() -> Option<Gpu> {
+ let instance = wgpu::Instance::default();
+ let adapter = block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() })).ok()?;
+ eprintln!("adapter: {:?}", adapter.get_info().name);
+ let limits = adapter.limits();
+ let (device, queue) = block_on(adapter.request_device(&wgpu::DeviceDescriptor { required_limits: limits, ..Default::default() })).ok()?;
+ let comp = photocraft_gpu::Compositor::new(&device);
+ Some(Gpu { device, queue, comp })
+}
+
+fn gpu_time(g: &mut Gpu, doc: &Document, region: Rect) -> Result<f64, String> {
+ let t = Instant::now();
+ g.comp.render(&g.device, &g.queue, doc, region, |_, _| {}).map_err(|e| e.to_string())?;
+ let _ = g.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
+ Ok(t.elapsed().as_secs_f64() * 1000.0)
+}
+
+fn cpu_time(doc: &Document, region: Rect) -> f64 {
+ let t = Instant::now();
+ let b = photocraft_compose::render(doc, region);
+ std::hint::black_box(&b);
+ t.elapsed().as_secs_f64() * 1000.0
+}
+
+fn report(what: &str, region: Rect, cpu: Option<f64>, gpu: Result<f64, String>) {
+ let mp = region.width() as f64 * region.height() as f64 / 1e6;
+ let c = cpu.map_or("-".to_string(), |v| format!("{v:9.1} ms"));
+ let g = match gpu {
+ Ok(v) => format!("{v:9.1} ms"),
+ Err(e) => format!("unsupported ({e})"),
+ };
+ println!("{what:<40} {mp:7.2} MP cpu {c:>12} gpu {g}");
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let no_cpu = args.iter().any(|a| a == "--no-cpu");
+ let mut doc = if let Some(p) = arg(&args, "--psd") {
+ let bytes = std::fs::read(&p).expect("read --psd");
+ photocraft_io::import(&p, &bytes).expect("import").document
+ } else {
+ let (w, h) = arg(&args, "--size").and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))).unwrap_or((7360, 4912));
+ synthetic(w, h)
+ };
+ let full = doc.bounds();
+ println!("document {}x{} ({} layers)", doc.size.width, doc.size.height, doc.walk().len());
+ let mut g = gpu();
+ let mut gt = |doc: &Document, r: Rect| match g.as_mut() {
+ Some(g) => gpu_time(g, doc, r),
+ None => Err("no adapter".into()),
+ };
+ let cpu = |doc: &Document, r: Rect| if no_cpu { None } else { Some(cpu_time(doc, r)) };
+
+ photocraft_compose::purge_effect_cache();
+ report("full refresh, cold effect caches", full, cpu(&doc, full), gt(&doc, full));
+ report("full refresh, warm caches", full, cpu(&doc, full), gt(&doc, full));
+
+ // Adjustment tweak (maps unaffected).
+ if let Some(LayerContent::Adjustment(Adjustment::HueSaturation { hue, .. })) = doc.layers.last_mut().map(|l| &mut l.content) {
+ *hue += 5.0;
+ }
+ report("adjustment tweak (full refresh)", full, cpu(&doc, full), gt(&doc, full));
+
+ // Brush dab on a plain layer.
+ let margin = doc.walk().iter().map(|(_, _, l)| photocraft_compose::effects::margin(l)).max().unwrap_or(0);
+ let dab = Rect::new(full.width() as i32 / 3, full.height() as i32 / 3, full.width() as i32 / 3 + 64, full.height() as i32 / 3 + 64);
+ if let Some(l) = doc.layers.iter_mut().find(|l| l.name == "paint") {
+ l.surface_mut().unwrap().fill_rect(dab, &[0.1, 0.9, 0.1, 1.0]);
+ report("dab on a plain layer (damage rect)", dab, cpu(&doc, dab), gt(&doc, dab));
+ }
+ // Brush dab on the effect layer: its effects reach `margin` px beyond the dab.
+ let blob_dab = Rect::new(full.width() as i32 / 2 - 32, full.height() as i32 / 2 - 32, full.width() as i32 / 2 + 32, full.height() as i32 / 2 + 32);
+ if let Some(l) = doc.layers.iter_mut().find(|l| l.name == "blob") {
+ l.surface_mut().unwrap().fill_rect(blob_dab, &[0.9, 0.1, 0.1, 1.0]);
+ let r = blob_dab.inflate(margin).intersect(&full);
+ report("dab on the effect layer (damage + reach)", r, cpu(&doc, r), gt(&doc, r));
+ }
+}
diff --git a/crates/ui-egui/examples/parity.rs b/crates/ui-egui/examples/parity.rs
new file mode 100644
index 000000000..6548204a9
--- /dev/null
+++ b/crates/ui-egui/examples/parity.rs
@@ -0,0 +1,24 @@
+//! Print Photoshop menu parity and optionally write the Markdown report.
+//!
+//! ```sh
+//! cargo run -p photocraft-ui-egui --example parity -- [--write docs/parity.md] [--json]
+//! ```
+//! Usually run through `cargo xtask parity`.
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let p = photocraft_ui_egui::parity::compute();
+ if args.iter().any(|a| a == "--json") {
+ println!("{}", serde_json::to_string_pretty(&p).expect("serialize parity"));
+ return;
+ }
+ println!("Photoshop menu parity: {} / {} live ({:.1}%)", p.live, p.total, p.percent());
+ for m in &p.menus {
+ println!(" {:<8} {:>4} / {:<4}", m.menu, m.live, m.total);
+ }
+ if let Some(i) = args.iter().position(|a| a == "--write") {
+ let path = args.get(i + 1).expect("--write needs a path");
+ std::fs::write(path, p.to_markdown()).unwrap_or_else(|e| panic!("{path}: {e}"));
+ println!("wrote {path}");
+ }
+}
diff --git a/crates/ui-egui/src/adjust_ui.rs b/crates/ui-egui/src/adjust_ui.rs
new file mode 100644
index 000000000..629b318ce
--- /dev/null
+++ b/crates/ui-egui/src/adjust_ui.rs
@@ -0,0 +1,176 @@
+//! Properties-panel editors for the Selective Color and Color Lookup adjustment layers.
+//!
+//! Both commit through `layer.setAdjustment` (which merges these kinds' params into the current
+//! values). Selective Color previews live while a slider drags, via `app.live_adjust` carrying
+//! the full parameter set; Color Lookup commits on every change (its table isn't in the params).
+
+use photocraft_doc::{Adjustment, LayerId};
+use photocraft_engine::adjust_cmds::RANGES;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+use crate::widgets;
+
+const RANGE_LABELS: [&str; 9] = [
+ "Reds", "Yellows", "Greens", "Cyans", "Blues", "Magentas", "Whites", "Neutrals", "Blacks",
+];
+
+/// The full parameter set of a Selective Color adjustment (every range as `[c, m, y, k]`).
+pub fn selective_values(adj: &Adjustment) -> Value {
+ let Adjustment::SelectiveColor {
+ relative,
+ adjustments,
+ } = adj
+ else {
+ return json!({});
+ };
+ let mut v = json!({"method": if *relative { "relative" } else { "absolute" }});
+ for (i, key) in RANGES.iter().enumerate() {
+ v[*key] = json!(adjustments[i]);
+ }
+ v
+}
+
+pub fn selective_color_editor(
+ app: &mut PhotocraftApp,
+ ui: &mut egui::Ui,
+ id: LayerId,
+ adj: &Adjustment,
+) {
+ let t = Tokens::get(ui.ctx());
+ let committed = selective_values(adj);
+ let mut values = match &app.live_adjust {
+ Some((l, v)) if *l == id && v.get("reds").is_some() => v.clone(),
+ _ => committed,
+ };
+ let key = egui::Id::new(("selc-range", id.0));
+ let mut range: usize = ui.data(|d| d.get_temp(key)).unwrap_or(0);
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("Colors").color(t.text_dim));
+ let opts: Vec<(usize, &str)> = RANGE_LABELS.iter().copied().enumerate().collect();
+ if widgets::dropdown(
+ ui,
+ &format!("selc-colors-{}", id.0),
+ &mut range,
+ &opts,
+ 150.0,
+ ) {
+ ui.data_mut(|d| d.insert_temp(key, range));
+ }
+ });
+ ui.add_space(4.0);
+ let mut live = false;
+ let mut commit = false;
+ for (k, label) in ["Cyan", "Magenta", "Yellow", "Black"].iter().enumerate() {
+ let mut v = values[RANGES[range]][k].as_f64().unwrap_or(0.0) as f32;
+ let r = widgets::slider_row(ui, label, &mut v, -100.0..=100.0, "%", None);
+ if r.changed() {
+ values[RANGES[range]][k] = json!(v.round());
+ live = true;
+ }
+ if r.drag_stopped() || (r.changed() && !r.dragged()) {
+ commit = true;
+ }
+ }
+ ui.add_space(4.0);
+ let mut method = values["method"].as_str().unwrap_or("relative").to_string();
+ ui.horizontal(|ui| {
+ for (m, label) in [("relative", "Relative"), ("absolute", "Absolute")] {
+ if ui.radio(method == m, label).clicked() && method != m {
+ method = m.to_string();
+ values["method"] = json!(m);
+ commit = true;
+ }
+ }
+ });
+ if live {
+ app.live_adjust = Some((id, values.clone()));
+ }
+ if commit {
+ let mut p = values;
+ p["layer"] = json!(id.0);
+ let _ = app.run("layer.setAdjustment", p);
+ app.live_adjust = None;
+ }
+}
+
+pub fn color_lookup_editor(
+ app: &mut PhotocraftApp,
+ ui: &mut egui::Ui,
+ id: LayerId,
+ adj: &Adjustment,
+) {
+ let t = Tokens::get(ui.ctx());
+ let Adjustment::ColorLookup {
+ name,
+ lut,
+ size,
+ tetrahedral,
+ dither,
+ } = adj
+ else {
+ return;
+ };
+ let builtins = photocraft_engine::adjust_cmds::LOOKS;
+ let current = if lut.is_none() {
+ "none".to_string()
+ } else {
+ builtins
+ .iter()
+ .find(|b| b.1 == name)
+ .map_or_else(|| "custom".to_string(), |b| b.0.to_string())
+ };
+ let custom_label = format!("{name} ({size}³)");
+ let mut opts: Vec<(String, &str)> = vec![("none".into(), "Load 3D LUT…")];
+ opts.extend(builtins.iter().map(|(id, label)| (id.to_string(), *label)));
+ if current == "custom" {
+ opts.push(("custom".into(), custom_label.as_str()));
+ }
+ let mut sel = current.clone();
+ let mut params: Option<Value> = None;
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("3D LUT File").color(t.text_dim));
+ if widgets::dropdown(ui, &format!("clrl-{}", id.0), &mut sel, &opts, 170.0)
+ && sel != current
+ && sel != "custom"
+ {
+ params = Some(json!({"lut": sel}));
+ }
+ });
+ // A path field stands in for the platform file picker (the desktop app's File menu has one).
+ let path_key = egui::Id::new(("clrl-path", id.0));
+ let mut path: String = ui.data(|d| d.get_temp(path_key)).unwrap_or_default();
+ ui.horizontal(|ui| {
+ let r = ui.add(
+ egui::TextEdit::singleline(&mut path)
+ .hint_text(".cube / .3dl / .look path")
+ .desired_width(170.0),
+ );
+ if r.changed() {
+ ui.data_mut(|d| d.insert_temp(path_key, path.clone()));
+ }
+ if widgets::secondary_button(ui, "Load", 60.0).clicked() && !path.trim().is_empty() {
+ params = Some(json!({"file": path.trim()}));
+ }
+ });
+ ui.add_space(4.0);
+ let mut tet = *tetrahedral;
+ ui.horizontal(|ui| {
+ for (on, label) in [(false, "Trilinear"), (true, "Tetrahedral")] {
+ if ui.radio(tet == on, label).clicked() && tet != on {
+ tet = on;
+ params = Some(json!({"tetrahedral": on}));
+ }
+ }
+ });
+ let mut d = *dither;
+ if widgets::toggle(ui, &mut d, "Dither").changed() {
+ params = Some(json!({"dither": d}));
+ }
+ if let Some(mut p) = params {
+ p["layer"] = json!(id.0);
+ // Errors (an unreadable LUT file) land in the status bar.
+ let _ = app.run("layer.setAdjustment", p);
+ }
+}
diff --git a/crates/ui-egui/src/brush_panel.rs b/crates/ui-egui/src/brush_panel.rs
new file mode 100644
index 000000000..f8384b954
--- /dev/null
+++ b/crates/ui-egui/src/brush_panel.rs
@@ -0,0 +1,491 @@
+//! Window › Brush Settings (F5): Photoshop's floating brush panel. Section list with enable boxes
+//! on the left, the selected section's controls on the right, and a live stroke preview below.
+//! A second tab lists the brush presets. Edits go straight to the session brush (tool state, like
+//! the options bar); presets are applied through `tools.setBrush`.
+
+use std::sync::Arc;
+
+use egui::{Color32, CornerRadius, RichText, Sense, Stroke, vec2};
+use photocraft_engine::BrushSettings;
+use photocraft_engine::paint::{self, Control, Dynamic, MaskMode, Pattern, PatternStyle, StrokePoint};
+use serde_json::json;
+
+use crate::theme::{self, Tokens};
+use crate::{PhotocraftApp, icons, widgets};
+
+/// Sections in Photoshop's order. The bool says whether the section has an enable box.
+pub const SECTIONS: [(&str, bool); 13] = [
+ ("Brush Tip Shape", false),
+ ("Shape Dynamics", true),
+ ("Scattering", true),
+ ("Texture", true),
+ ("Dual Brush", true),
+ ("Color Dynamics", true),
+ ("Transfer", true),
+ ("Brush Pose", true),
+ ("Noise", true),
+ ("Wet Edges", true),
+ ("Build-up", true),
+ ("Smoothing", false),
+ ("Protect Texture", true),
+];
+
+/// The enable flag behind section `i` (None for Brush Tip Shape).
+pub fn section_flag(b: &mut BrushSettings, i: usize) -> Option<&mut bool> {
+ Some(match i {
+ 1 => &mut b.shape_dynamics.enabled,
+ 2 => &mut b.scattering.enabled,
+ 3 => &mut b.texture.enabled,
+ 4 => &mut b.dual_brush.enabled,
+ 5 => &mut b.color_dynamics.enabled,
+ 6 => &mut b.transfer.enabled,
+ 7 => &mut b.pose.enabled,
+ 8 => &mut b.noise,
+ 9 => &mut b.wet_edges,
+ 10 => &mut b.build_up,
+ 11 => return None,
+ 12 => &mut b.protect_texture,
+ _ => return None,
+ })
+}
+
+const CONTROLS: [(Control, &str); 8] = [
+ (Control::Off, "Off"),
+ (Control::Fade, "Fade"),
+ (Control::PenPressure, "Pen Pressure"),
+ (Control::PenTilt, "Pen Tilt"),
+ (Control::StylusWheel, "Stylus Wheel"),
+ (Control::Rotation, "Rotation"),
+ (Control::InitialDirection, "Initial Direction"),
+ (Control::Direction, "Direction"),
+];
+
+const MASK_MODES: [(MaskMode, &str); 10] = [
+ (MaskMode::Multiply, "Multiply"),
+ (MaskMode::Subtract, "Subtract"),
+ (MaskMode::Darken, "Darken"),
+ (MaskMode::Overlay, "Overlay"),
+ (MaskMode::ColorDodge, "Color Dodge"),
+ (MaskMode::ColorBurn, "Color Burn"),
+ (MaskMode::LinearBurn, "Linear Burn"),
+ (MaskMode::HardMix, "Hard Mix"),
+ (MaskMode::LinearHeight, "Linear Height"),
+ (MaskMode::Height, "Height"),
+];
+
+/// Percent slider over a 0..`max` fraction.
+fn pct(ui: &mut egui::Ui, label: &str, v: &mut f32, max: f32) -> bool {
+ let mut p = *v * 100.0;
+ let changed = widgets::slider_row(ui, label, &mut p, 0.0..=max * 100.0, "%", None).changed();
+ if changed {
+ *v = (p / 100.0).clamp(0.0, max);
+ }
+ changed
+}
+
+fn num(ui: &mut egui::Ui, label: &str, v: &mut f32, range: std::ops::RangeInclusive<f32>, suffix: &str) -> bool {
+ widgets::slider_row(ui, label, v, range, suffix, None).changed()
+}
+
+/// A jitter slider plus its Control dropdown (and the Fade step count when fading).
+fn dynamic(ui: &mut egui::Ui, id: &str, label: &str, d: &mut Dynamic, max: f32, minimum: Option<&str>) {
+ let t = Tokens::get(ui.ctx());
+ pct(ui, label, &mut d.jitter, max);
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Control:").color(t.text_dim));
+ widgets::dropdown(ui, id, &mut d.control, &CONTROLS, 130.0);
+ if d.control == Control::Fade {
+ let mut steps = d.fade_steps as f32;
+ if widgets::value_field(ui, &mut steps, 1.0..=9999.0, "", 52.0).changed() {
+ d.fade_steps = steps.round().clamp(1.0, 9999.0) as u32;
+ }
+ }
+ });
+ if let Some(m) = minimum {
+ pct(ui, m, &mut d.minimum, 1.0);
+ }
+ ui.add_space(4.0);
+}
+
+/// Size: a value field over a logarithmic slider (small sizes get most of the travel).
+fn size_row(ui: &mut egui::Ui, label: &str, size: &mut f32, max: f32) {
+ let t = Tokens::get(ui.ctx());
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(label).color(t.text_dim));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ widgets::value_field(ui, size, 1.0..=max, "px", 74.0);
+ });
+ });
+ let mut lv = size.max(1.0).ln();
+ if widgets::slider(ui, &mut lv, 0.0..=max.ln(), None).changed() {
+ *size = lv.exp().round().clamp(1.0, max);
+ }
+ ui.add_space(4.0);
+}
+
+fn tip_shape(ui: &mut egui::Ui, b: &mut BrushSettings) {
+ size_row(ui, "Size", &mut b.size, 5000.0);
+ ui.horizontal(|ui| {
+ widgets::checkbox(ui, &mut b.flip_x, "Flip X");
+ widgets::checkbox(ui, &mut b.flip_y, "Flip Y");
+ });
+ num(ui, "Angle", &mut b.angle, -180.0..=180.0, "°");
+ pct(ui, "Roundness", &mut b.roundness, 1.0);
+ if matches!(b.tip, paint::TipShape::Round) {
+ pct(ui, "Hardness", &mut b.hardness, 1.0);
+ }
+ let mut spacing_on = b.spacing > 0.0;
+ widgets::checkbox(ui, &mut spacing_on, "Spacing");
+ if spacing_on {
+ pct(ui, "Spacing", &mut b.spacing, 10.0);
+ b.spacing = b.spacing.max(0.01);
+ }
+}
+
+fn texture(ui: &mut egui::Ui, b: &mut BrushSettings) {
+ let tx = &mut b.texture;
+ let t = Tokens::get(ui.ctx());
+ if let Pattern::Procedural { style, size, .. } = &mut tx.pattern {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Pattern").color(t.text_dim));
+ let opts = [(PatternStyle::Paper, "Paper"), (PatternStyle::Canvas, "Canvas"), (PatternStyle::Noise, "Noise"), (PatternStyle::Dots, "Dots")];
+ widgets::dropdown(ui, "brush-pattern", style, &opts, 110.0);
+ });
+ let mut s = *size as f32;
+ if num(ui, "Pattern Size", &mut s, 16.0..=1024.0, "px") {
+ *size = s.round() as u32;
+ }
+ } else {
+ ui.label(RichText::new("Custom pattern").color(t.text_faint));
+ }
+ widgets::checkbox(ui, &mut tx.invert, "Invert");
+ pct(ui, "Scale", &mut tx.scale, 10.0);
+ let mut br = tx.brightness * 150.0;
+ if num(ui, "Brightness", &mut br, -150.0..=150.0, "") {
+ tx.brightness = br / 150.0;
+ }
+ let mut ct = tx.contrast * 50.0;
+ if num(ui, "Contrast", &mut ct, -50.0..=100.0, "") {
+ tx.contrast = ct / 50.0;
+ }
+ widgets::checkbox(ui, &mut tx.each_tip, "Texture Each Tip");
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Mode").color(t.text_dim));
+ widgets::dropdown(ui, "brush-texture-mode", &mut tx.mode, &MASK_MODES, 130.0);
+ });
+ pct(ui, "Depth", &mut tx.depth, 1.0);
+ if tx.each_tip {
+ dynamic(ui, "brush-depth-ctl", "Depth Jitter", &mut tx.depth_jitter, 1.0, Some("Minimum Depth"));
+ }
+}
+
+fn dual_brush(ui: &mut egui::Ui, b: &mut BrushSettings) {
+ let t = Tokens::get(ui.ctx());
+ let d = &mut b.dual_brush;
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Mode").color(t.text_dim));
+ widgets::dropdown(ui, "brush-dual-mode", &mut d.mode, &MASK_MODES, 130.0);
+ widgets::checkbox(ui, &mut d.flip, "Flip");
+ });
+ size_row(ui, "Size", &mut d.size, 2500.0);
+ pct(ui, "Hardness", &mut d.hardness, 1.0);
+ pct(ui, "Spacing", &mut d.spacing, 10.0);
+ pct(ui, "Scatter", &mut d.scatter, 10.0);
+ widgets::checkbox(ui, &mut d.both_axes, "Both Axes");
+ let mut c = d.count as f32;
+ if num(ui, "Count", &mut c, 1.0..=16.0, "") {
+ d.count = c.round() as u32;
+ }
+}
+
+fn color_dynamics(ui: &mut egui::Ui, b: &mut BrushSettings) {
+ let c = &mut b.color_dynamics;
+ widgets::checkbox(ui, &mut c.per_tip, "Apply Per Tip");
+ dynamic(ui, "brush-fgbg-ctl", "Foreground/Background Jitter", &mut c.fg_bg, 1.0, None);
+ pct(ui, "Hue Jitter", &mut c.hue_jitter, 1.0);
+ pct(ui, "Saturation Jitter", &mut c.saturation_jitter, 1.0);
+ pct(ui, "Brightness Jitter", &mut c.brightness_jitter, 1.0);
+ let mut p = c.purity * 100.0;
+ if num(ui, "Purity", &mut p, -100.0..=100.0, "%") {
+ c.purity = p / 100.0;
+ }
+}
+
+fn pose(ui: &mut egui::Ui, b: &mut BrushSettings) {
+ let p = &mut b.pose;
+ let mut tx = p.tilt_x * 100.0;
+ if num(ui, "Tilt X", &mut tx, -100.0..=100.0, "%") {
+ p.tilt_x = tx / 100.0;
+ }
+ let mut ty = p.tilt_y * 100.0;
+ if num(ui, "Tilt Y", &mut ty, -100.0..=100.0, "%") {
+ p.tilt_y = ty / 100.0;
+ }
+ widgets::checkbox(ui, &mut p.override_tilt, "Override Tilt");
+ num(ui, "Rotation", &mut p.rotation, 0.0..=360.0, "°");
+ widgets::checkbox(ui, &mut p.override_rotation, "Override Rotation");
+ pct(ui, "Pressure", &mut p.pressure, 1.0);
+ widgets::checkbox(ui, &mut p.override_pressure, "Override Pressure");
+}
+
+fn smoothing(ui: &mut egui::Ui, b: &mut BrushSettings) {
+ let s = &mut b.smoothing;
+ pct(ui, "Smoothing", &mut s.amount, 1.0);
+ widgets::checkbox(ui, &mut s.pulled_string, "Pulled String Mode");
+ widgets::checkbox(ui, &mut s.catch_up, "Stroke Catch-up");
+ widgets::checkbox(ui, &mut s.catch_up_on_end, "Catch-up on Stroke End");
+ widgets::checkbox(ui, &mut s.adjust_for_zoom, "Adjust for Zoom");
+}
+
+/// Controls for section `i`.
+pub fn section_body(ui: &mut egui::Ui, b: &mut BrushSettings, i: usize) {
+ let t = Tokens::get(ui.ctx());
+ let note = |ui: &mut egui::Ui, s: &str| {
+ ui.label(RichText::new(s).color(t.text_faint));
+ };
+ match i {
+ 0 => tip_shape(ui, b),
+ 1 => {
+ let sd = &mut b.shape_dynamics;
+ dynamic(ui, "brush-size-ctl", "Size Jitter", &mut sd.size, 1.0, Some("Minimum Diameter"));
+ dynamic(ui, "brush-angle-ctl", "Angle Jitter", &mut sd.angle, 1.0, None);
+ dynamic(ui, "brush-round-ctl", "Roundness Jitter", &mut sd.roundness, 1.0, Some("Minimum Roundness"));
+ widgets::checkbox(ui, &mut sd.flip_x_jitter, "Flip X Jitter");
+ widgets::checkbox(ui, &mut sd.flip_y_jitter, "Flip Y Jitter");
+ }
+ 2 => {
+ let sc = &mut b.scattering;
+ widgets::checkbox(ui, &mut sc.both_axes, "Both Axes");
+ dynamic(ui, "brush-scatter-ctl", "Scatter", &mut sc.scatter, 10.0, None);
+ let mut c = sc.count as f32;
+ if num(ui, "Count", &mut c, 1.0..=16.0, "") {
+ sc.count = c.round() as u32;
+ }
+ dynamic(ui, "brush-count-ctl", "Count Jitter", &mut sc.count_jitter, 1.0, None);
+ }
+ 3 => texture(ui, b),
+ 4 => dual_brush(ui, b),
+ 5 => color_dynamics(ui, b),
+ 6 => {
+ let tr = &mut b.transfer;
+ dynamic(ui, "brush-opacity-ctl", "Opacity Jitter", &mut tr.opacity, 1.0, Some("Minimum"));
+ dynamic(ui, "brush-flow-ctl", "Flow Jitter", &mut tr.flow, 1.0, Some("Minimum"));
+ }
+ 7 => pose(ui, b),
+ 8 => note(ui, "Adds grain to the soft edges of the brush tip."),
+ 9 => note(ui, "Watercolour look: lighter interior, darker rims."),
+ 10 => {
+ note(ui, "Airbrush: keeps painting while the pointer rests.");
+ num(ui, "Rate", &mut b.build_up_rate, 1.0..=200.0, "/s");
+ }
+ 11 => smoothing(ui, b),
+ _ => note(ui, "Keeps the current texture when switching presets."),
+ }
+}
+
+/// A stroke rendered with the brush (scaled down to fit), as RGBA8, for previews and preset rows.
+pub fn preview_pixels(b: &BrushSettings, w: u32, h: u32, color: [f32; 4]) -> Vec<u8> {
+ use photocraft_color::{ColorMode, PixelFormat, SampleType};
+ let mut brush = b.clone();
+ let k = ((h as f32 * 0.55) / brush.size.max(1.0)).min(1.0);
+ brush.size = (brush.size * k).max(1.0);
+ brush.dual_brush.size = (brush.dual_brush.size * k).max(1.0);
+ brush.color = color;
+ brush.erase = false;
+ brush.seed = 7;
+ // Photoshop's preview: an S-curve with pressure tapering in and out.
+ let n = 64;
+ let points: Vec<StrokePoint> = (0..=n)
+ .map(|i| {
+ let s = i as f64 / n as f64;
+ let x = 10.0 + s * (w as f64 - 20.0);
+ let y = h as f64 / 2.0 - (s * std::f64::consts::TAU).sin() * h as f64 * 0.22;
+ StrokePoint::new(x, y, (s * std::f64::consts::PI).sin().max(0.05) as f32)
+ })
+ .collect();
+ let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true);
+ let mut s = photocraft_raster::Surface::new(fmt);
+ paint::apply_stroke(&mut s, &paint::Stroke { brush, points }, None, false);
+ let r = photocraft_geom::Rect::new(0, 0, w as i32, h as i32);
+ let mut px = vec![[0.0f32; 4]; (w * h) as usize];
+ s.read_rgba_into(r, &mut px);
+ px.iter().flat_map(|p| p.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)).collect()
+}
+
+/// Texture for a brush preview, cached on the brush's JSON.
+fn preview_texture(ui: &egui::Ui, b: &BrushSettings, w: u32, h: u32, color: Color32) -> Arc<egui::TextureHandle> {
+ let mut key_b = b.clone();
+ key_b.color = [0.0; 4];
+ let sig = format!("{}{w}x{h}{color:?}", serde_json::to_string(&key_b).unwrap_or_default());
+ let id = egui::Id::new(("brush-preview", sig));
+ if let Some(tex) = ui.data(|d| d.get_temp::<Arc<egui::TextureHandle>>(id)) {
+ return tex;
+ }
+ let c = color.to_normalized_gamma_f32();
+ let px = preview_pixels(b, w, h, [c[0], c[1], c[2], 1.0]);
+ let img = egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &px);
+ let tex = Arc::new(ui.ctx().load_texture("brush-preview", img, egui::TextureOptions::LINEAR));
+ ui.data_mut(|d| d.insert_temp(id, tex.clone()));
+ tex
+}
+
+fn presets_tab(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let presets: Vec<(String, BrushSettings)> = app.session.tools.presets.iter().map(|p| (p.name.clone(), p.brush.clone())).collect();
+ // The current brush matches a preset when everything but its colour and size agrees.
+ let same = |a: &BrushSettings, b: &BrushSettings| BrushSettings { color: b.color, size: b.size, background: b.background, ..a.clone() } == *b;
+ let current = app.session.tools.brush.clone();
+ egui::ScrollArea::vertical().id_salt("brush-presets").max_height(360.0).auto_shrink([false, true]).show(ui, |ui| {
+ for (name, brush) in presets {
+ let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::click());
+ if same(&brush, &current) {
+ ui.painter().rect_filled(r, t.radius_sm, t.accent_soft);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(r, t.radius_sm, t.hover);
+ }
+ let tex = preview_texture(ui, &brush, 180, 36, t.text);
+ let ir = egui::Rect::from_min_size(r.left_top() + vec2(4.0, 2.0), vec2(180.0, 36.0));
+ ui.painter().image(tex.id(), ir, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE);
+ ui.painter().text(egui::pos2(ir.right() + 10.0, r.center().y), egui::Align2::LEFT_CENTER, &name, egui::FontId::proportional(12.0), t.text_dim);
+ if resp.clicked() {
+ let r = app.session.execute("tools.setBrush", json!({"preset": name}));
+ if let Err(e) = r {
+ app.ui.status = e.to_string();
+ }
+ }
+ }
+ });
+}
+
+pub fn window(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ if !app.ui.panels.brush_settings {
+ return;
+ }
+ let t = Tokens::get(ctx);
+ let frame = egui::Frame::NONE
+ .fill(t.card)
+ .stroke(Stroke::new(1.0, t.card_border))
+ .corner_radius(CornerRadius::same(t.radius_lg as u8))
+ .shadow(egui::Shadow { offset: [0, 10], blur: 30, spread: 0, color: t.shadow })
+ .inner_margin(egui::Margin::same(10));
+ let canvas = app.last_canvas_rect;
+ let mut open = true;
+ egui::Window::new("Brush Settings")
+ .id(egui::Id::new("brush-settings"))
+ .title_bar(false)
+ .resizable(false)
+ .frame(frame)
+ .default_pos(egui::pos2((canvas.right() - 500.0).max(canvas.left() + 8.0), canvas.top() + 40.0))
+ .show(ctx, |ui| {
+ ui.set_width(470.0);
+ ui.horizontal(|ui| {
+ let mut tab = app.ui.brush_tab;
+ for (i, name) in ["Brush Settings", "Brushes"].iter().enumerate() {
+ if widgets::pill_tab(ui, name, tab == i).clicked() {
+ tab = i;
+ }
+ }
+ app.ui.brush_tab = tab;
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if icons::button(ui, "x", 20.0, false, "Close").clicked() {
+ open = false;
+ }
+ });
+ });
+ ui.add_space(6.0);
+ widgets::hairline(ui);
+ ui.add_space(6.0);
+ if app.ui.brush_tab == 1 {
+ presets_tab(app, ui);
+ return;
+ }
+ let mut b = app.session.tools.brush.clone();
+ ui.horizontal_top(|ui| {
+ ui.vertical(|ui| {
+ ui.set_width(150.0);
+ ui.spacing_mut().item_spacing.y = 1.0;
+ for (i, (name, has_box)) in SECTIONS.iter().enumerate() {
+ let sel = app.ui.brush_section == i;
+ let (r, resp) = ui.allocate_exact_size(vec2(150.0, 21.0), Sense::click());
+ if sel {
+ ui.painter().rect_filled(r, t.radius_sm, t.accent_soft);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(r, t.radius_sm, t.hover);
+ }
+ let mut x = r.left() + 6.0;
+ if *has_box && let Some(flag) = section_flag(&mut b, i) {
+ let br = egui::Rect::from_center_size(egui::pos2(x + 6.0, r.center().y), vec2(12.0, 12.0));
+ let box_resp = ui.interact(br, ui.id().with(("brush-sec-box", i)), Sense::click());
+ if *flag {
+ ui.painter().rect_filled(br, 2.0, t.accent);
+ ui.painter().text(br.center(), egui::Align2::CENTER_CENTER, "✓", egui::FontId::proportional(10.0), Color32::WHITE);
+ } else {
+ ui.painter().rect_stroke(br, 2.0, Stroke::new(1.2, t.text_faint), egui::StrokeKind::Inside);
+ }
+ if box_resp.clicked() {
+ *flag = !*flag;
+ }
+ x += 18.0;
+ } else if i > 0 {
+ x += 18.0;
+ }
+ let color = if sel { t.text } else { t.text_dim };
+ ui.painter().text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, *name, theme::medium(12.0), color);
+ if resp.clicked() {
+ app.ui.brush_section = i;
+ }
+ }
+ });
+ widgets::vline(ui, 350.0);
+ ui.vertical(|ui| {
+ ui.set_width(290.0);
+ ui.label(RichText::new(SECTIONS[app.ui.brush_section.min(SECTIONS.len() - 1)].0).font(theme::semibold(12.5)).color(t.text));
+ ui.add_space(4.0);
+ egui::ScrollArea::vertical().id_salt("brush-section").max_height(330.0).auto_shrink([false, true]).show(ui, |ui| {
+ section_body(ui, &mut b, app.ui.brush_section);
+ });
+ });
+ });
+ ui.add_space(6.0);
+ widgets::hairline(ui);
+ ui.add_space(6.0);
+ let tex = preview_texture(ui, &b, 450, 72, t.text);
+ let (r, _) = ui.allocate_exact_size(vec2(450.0, 72.0), Sense::hover());
+ ui.painter().rect_filled(r, t.radius_sm, t.field);
+ ui.painter().image(tex.id(), r, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE);
+ if b != app.session.tools.brush {
+ app.session.tools.brush = b;
+ }
+ });
+ if !open {
+ app.ui.panels.brush_settings = false;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sections_with_boxes_have_flags() {
+ let mut b = BrushSettings::default();
+ for (i, (_, has_box)) in SECTIONS.iter().enumerate() {
+ assert_eq!(section_flag(&mut b, i).is_some(), *has_box, "{i}");
+ }
+ *section_flag(&mut b, 3).unwrap() = true;
+ assert!(b.texture.enabled);
+ }
+
+ #[test]
+ fn preview_draws_a_stroke_that_fits() {
+ let mut b = BrushSettings { size: 400.0, ..Default::default() };
+ let px = preview_pixels(&b, 120, 40, [1.0, 0.0, 0.0, 1.0]);
+ assert_eq!(px.len(), 120 * 40 * 4);
+ let covered = px.chunks_exact(4).filter(|p| p[3] > 128).count();
+ assert!(covered > 200 && covered < 120 * 40 / 2, "{covered}");
+ // Dynamics change the preview.
+ b.scattering.enabled = true;
+ b.scattering.scatter.jitter = 3.0;
+ assert_ne!(preview_pixels(&b, 120, 40, [1.0, 0.0, 0.0, 1.0]), px);
+ }
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index f4130c60b..a9f1f9e7c 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -24,6 +24,10 @@ pub struct CanvasCache {
pub preview_key: u64,
/// The current image lives in the GPU canvas (`gpu_canvas`) rather than `texture`.
pub on_gpu: bool,
+ /// Revision and preview key `texture` was rendered at. Tracked apart from the GPU canvas's
+ /// `revision`, so the Navigator never shows a stale CPU image after GPU-path edits.
+ pub tex_revision: u64,
+ pub tex_preview_key: u64,
}
/// An in-progress pointer gesture on the canvas.
@@ -49,18 +53,22 @@ pub struct ViewXform {
pub rect: Rect,
pub zoom: f32,
pub center: [f32; 2],
+ /// View › Flip Horizontal: the view is mirrored left-right (the document is not).
+ pub flip: bool,
}
impl ViewXform {
pub fn to_screen(&self, x: f32, y: f32) -> Pos2 {
- self.rect.center() + vec2((x - self.center[0]) * self.zoom, (y - self.center[1]) * self.zoom)
+ let sx = if self.flip { -1.0 } else { 1.0 };
+ self.rect.center() + vec2((x - self.center[0]) * self.zoom * sx, (y - self.center[1]) * self.zoom)
}
pub fn to_doc(&self, p: Pos2) -> [f64; 2] {
let d = (p - self.rect.center()) / self.zoom;
- [(d.x + self.center[0]) as f64, (d.y + self.center[1]) as f64]
+ let dx = if self.flip { -d.x } else { d.x };
+ [(dx + self.center[0]) as f64, (d.y + self.center[1]) as f64]
}
pub fn doc_rect(&self, r: DRect) -> Rect {
- Rect::from_min_max(self.to_screen(r.x0 as f32, r.y0 as f32), self.to_screen(r.x1 as f32, r.y1 as f32))
+ Rect::from_two_pos(self.to_screen(r.x0 as f32, r.y0 as f32), self.to_screen(r.x1 as f32, r.y1 as f32))
}
}
@@ -83,9 +91,15 @@ pub fn zoom_step(z: f32, dir: i32) -> f32 {
}
fn checker(app: &mut PhotocraftApp, ctx: &egui::Context) -> egui::TextureId {
+ // Preferences › Transparency & Gamut colours (the texture is rebuilt when they change).
+ let [ca, cb] = app.session.prefs().transparency_and_gamut.colors();
+ if app.prefs_rt.checker_key != Some([ca, cb]) {
+ app.prefs_rt.checker_key = Some([ca, cb]);
+ app.checker = None;
+ }
app.checker
.get_or_insert_with(|| {
- let (a, b) = (Color32::from_gray(255), Color32::from_gray(204));
+ let (a, b) = (Color32::from_rgb(ca[0], ca[1], ca[2]), Color32::from_rgb(cb[0], cb[1], cb[2]));
let img = egui::ColorImage::new([2, 2], vec![a, b, b, a]);
let opts = TextureOptions { magnification: egui::TextureFilter::Nearest, minification: egui::TextureFilter::Nearest, wrap_mode: egui::TextureWrapMode::Repeat, mipmap_mode: None };
ctx.load_texture("checker", img, opts)
@@ -150,6 +164,10 @@ fn display_doc(app: &PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>, u6
let key = 1 + params.to_string().bytes().fold(0u64, |h, b| h.wrapping_mul(31).wrapping_add(b as u64));
return (std::sync::Arc::new(doc), key);
}
+ // Duotone documents display through their inks.
+ if let Some(shown) = photocraft_engine::mode_cmds::display_document(&st.doc) {
+ return (std::sync::Arc::new(shown), 1 << 41);
+ }
(st.doc.clone(), 0)
}
@@ -160,9 +178,9 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize)
(st.revision, st.last_damage, st.doc.id)
};
let (doc, preview_key) = display_doc(app, idx);
- let cache = app.canvases.entry(id).or_insert(CanvasCache { revision: 0, texture: None, scale: 1.0, preview_key: 0, on_gpu: false });
- if cache.revision != revision || cache.texture.is_none() || cache.preview_key != preview_key {
- let partial = cache.texture.is_some() && cache.preview_key == preview_key && cache.revision + 1 == revision && cache.scale == 1.0 && last_damage.is_some();
+ let cache = app.canvases.entry(id).or_insert(CanvasCache { revision: 0, texture: None, scale: 1.0, preview_key: 0, on_gpu: false, tex_revision: 0, tex_preview_key: 0 });
+ if cache.tex_revision != revision || cache.texture.is_none() || cache.tex_preview_key != preview_key {
+ let partial = cache.texture.is_some() && cache.tex_preview_key == preview_key && cache.tex_revision + 1 == revision && cache.scale == 1.0 && last_damage.is_some();
let t0 = crate::gpu_canvas::now_ms();
if partial {
let r = last_damage.unwrap().intersect(&doc.bounds());
@@ -187,9 +205,8 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize)
cache.scale = scale;
app.perf.record("full", doc.size.width as u64 * doc.size.height as u64, t1 - t0, crate::gpu_canvas::now_ms() - t1);
}
- cache.revision = revision;
- cache.preview_key = preview_key;
- cache.on_gpu = false;
+ cache.tex_revision = revision;
+ cache.tex_preview_key = preview_key;
}
Some((cache.texture.as_ref()?.id(), cache.scale))
}
@@ -202,7 +219,7 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize) -> bool {
let Some((revision, last_damage, id)) = app.session.documents().get(idx).map(|st| (st.revision, st.last_damage, st.doc.id)) else { return false };
let (doc, preview_key) = display_doc(app, idx);
let size = [doc.size.width, doc.size.height];
- let cache = app.canvases.entry(id).or_insert(CanvasCache { revision: 0, texture: None, scale: 1.0, preview_key: 0, on_gpu: false });
+ let cache = app.canvases.entry(id).or_insert(CanvasCache { revision: 0, texture: None, scale: 1.0, preview_key: 0, on_gpu: false, tex_revision: 0, tex_preview_key: 0 });
let present = cache.on_gpu && gpu.has(id.0, size);
if present && cache.revision == revision && cache.preview_key == preview_key {
return true;
@@ -337,10 +354,35 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
start_screen(app, ui);
return;
}
- tabs(app, ui);
+ if !app.ui.view.hides_tabs() {
+ tabs(app, ui);
+ }
let Some(idx) = app.session.active_index() else { return };
let rect = ui.available_rect_before_wrap();
app.last_canvas_rect = rect;
+ let n = app.session.documents().len();
+ // Window › Arrange: tiled / n-up layouts show several documents side by side; the active one
+ // takes input, a click elsewhere activates that document.
+ if let Some(cells) = crate::view_cmds::cells(&app.ui.view.arrange, rect, n) {
+ let order: Vec<usize> = (0..n).map(|k| (idx + k) % n).collect();
+ let mut shown: Vec<(usize, Rect)> = order.into_iter().zip(cells).collect();
+ shown.sort_by_key(|(d, _)| *d);
+ let t = crate::theme::Tokens::get(ui.ctx());
+ for (d, cell) in shown {
+ let cell = cell.shrink(1.0);
+ let view = app.ui.views[d].clone();
+ let v = canvas_view(app, ui, d, cell, view, d == idx);
+ if d != idx {
+ app.ui.views[d] = v;
+ if ui.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| cell.contains(p))) {
+ app.session.set_active(d);
+ }
+ }
+ let stroke = if d == idx { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(160)) };
+ ui.painter().rect_stroke(cell, 0, stroke, egui::StrokeKind::Inside);
+ }
+ return;
+ }
let view = app.ui.views[idx].clone();
canvas_view(app, ui, idx, rect, view, true);
}
@@ -534,6 +576,37 @@ fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
});
}
+/// Lattice size of the canvas display LUT (Proof Colors / Gamut Warning).
+const DISPLAY_LUT: usize = 33;
+
+/// Keep the GPU display LUT of `doc` in step with its View › Proof Colors / Gamut Warning state.
+/// Returns the canvas `display` mode (0 none, 1 proof, 2 proof + gamut warning).
+fn sync_display_lut(app: &mut PhotocraftApp, ctx: &egui::Context, doc: &photocraft_doc::Document) -> u8 {
+ let Some(gpu) = app.gpu.as_ref() else { return 0 };
+ let pv = app.session.color.proof(doc.id);
+ let mode = if pv.gamut_warning { 2 } else { u8::from(pv.enabled) };
+ // Rebuild only when anything feeding the LUT changes.
+ let sig = if mode == 0 {
+ String::new()
+ } else {
+ format!("{mode} {} {:?} {} {} {} {:?} {:?}", pv.setup.profile.content_hash(), pv.setup.intent, pv.setup.bpc, pv.setup.simulate_paper, pv.gamut_threshold, doc.mode, doc.icc_profile.as_ref().map(|p| p.len()))
+ };
+ let key = egui::Id::new(("pc-display-lut", doc.id.0));
+ if ctx.data(|d| d.get_temp::<String>(key)).as_deref() == Some(sig.as_str()) {
+ return mode;
+ }
+ let lut = if mode == 0 { Ok(None) } else { app.session.color.canvas_lut(doc, DISPLAY_LUT) };
+ match lut {
+ Ok(bytes) => gpu.set_display_lut(doc.id.0, DISPLAY_LUT as u32, bytes.as_deref()),
+ Err(e) => {
+ app.ui.status = format!("Proof Colors: {e}");
+ gpu.set_display_lut(doc.id.0, DISPLAY_LUT as u32, None);
+ }
+ }
+ ctx.data_mut(|d| d.insert_temp(key, sig));
+ mode
+}
+
/// 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();
@@ -551,16 +624,27 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
if view.fit_pending && rect.width() > 50.0 {
fit_view(&mut view, &doc, rect.size());
}
- let xf = ViewXform { rect, zoom: view.zoom, center: view.center };
+ let flip = app.ui.view.flip_horizontal;
+ let xf = ViewXform { rect, zoom: view.zoom, center: view.center, flip };
+ let pixel_grid = app.ui.view.shows(app.ui.view.show.pixel_grid);
let response = ui.allocate_rect(rect, Sense::click_and_drag());
let painter = ui.painter_at(rect);
- paint_dots(ui, rect);
+ match crate::prefs_ui::pasteboard_color(app) {
+ Some(c) => {
+ ui.painter_at(rect).rect_filled(rect, 0.0, c);
+ }
+ None => paint_dots(ui, rect),
+ }
+ let border = app.session.prefs().interface.canvas_border;
+ let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow;
// Drop shadow, checkerboard, document image.
let img_rect = xf.doc_rect(doc.bounds());
// Live adjustment previews on big documents use a downsampled proxy (see proxy.rs).
let mut on_gpu = false;
+ // A flipped view draws through the CPU path (the GPU canvas shader has no mirroring).
if app.gpu.is_some()
+ && !flip
&& let Some((k, key)) = ensure_filter_preview(app, idx).or_else(|| ensure_proxy_preview(app, idx))
{
on_gpu = true;
@@ -569,12 +653,13 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
doc_size: [doc.size.width.div_ceil(k), doc.size.height.div_ceil(k)],
zoom: view.zoom * k as f32,
center: [view.center[0] / k as f32, view.center[1] / k as f32],
- shadow: { let t = crate::theme::Tokens::get(&ctx); !t.bevel && !t.pro },
+ shadow: { let t = crate::theme::Tokens::get(&ctx); !t.bevel && !t.pro && drop_shadow },
pixel_grid: false,
view_key: egui::Id::new(("pc-canvas-proxy", ctx.viewport_id(), idx)).value(),
+ display: 0,
};
crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params);
- } else if ensure_gpu(app, idx) {
+ } else if !flip && ensure_gpu(app, idx) {
on_gpu = true;
app.perf.gpu = true;
// Shadow, checkerboard, document and pixel grid in one custom shader (gpu_canvas.rs).
@@ -583,25 +668,39 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
doc_size: [doc.size.width, doc.size.height],
zoom: view.zoom,
center: view.center,
- shadow: { let t = crate::theme::Tokens::get(&ctx); !t.bevel && !t.pro },
- pixel_grid: true,
+ shadow: { let t = crate::theme::Tokens::get(&ctx); !t.bevel && !t.pro && drop_shadow },
+ pixel_grid,
view_key: egui::Id::new(("pc-canvas", ctx.viewport_id(), idx)).value(),
+ display: sync_display_lut(app, &ctx, &doc),
};
crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params);
} else {
- if !crate::theme::Tokens::get(&ctx).bevel {
+ if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow {
painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(img_rect, 0));
}
- let checker_id = checker(app, &ctx);
- let tiles = img_rect.size() / 16.0;
- painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE);
+ match app.session.prefs().transparency_and_gamut.square() {
+ Some(square) => {
+ let checker_id = checker(app, &ctx);
+ let tiles = img_rect.size() / (2.0 * square);
+ painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE);
+ }
+ None => {
+ painter.rect_filled(img_rect, 0.0, Color32::WHITE);
+ }
+ }
if let Some((tex, _scale)) = ensure_texture(app, &ctx, idx) {
- painter.image(tex, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
+ let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
+ painter.image(tex, img_rect, uv, Color32::WHITE);
}
}
+ // Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs).
+ if let Some(tex) = crate::channel_view::ensure(app, &ctx, idx) {
+ let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
+ painter.image(tex, img_rect, uv, Color32::WHITE);
+ }
// Pixel grid at high zoom (the GPU path draws its own).
- if !on_gpu && view.zoom >= 12.0 {
+ if !on_gpu && pixel_grid && view.zoom >= 12.0 {
let vis = img_rect.intersect(rect);
let a = xf.to_doc(vis.min);
let b = xf.to_doc(vis.max);
@@ -616,8 +715,17 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
}
+ // View › Show › Layer Edges: the active layer's content bounds.
+ if app.ui.view.shows(app.ui.view.show.layer_edges)
+ && let Some(st) = app.session.documents().get(idx)
+ && let Some(b) = st.active_layer.and_then(|id| st.doc.layer(id)).and_then(|l| l.surface()).map(|s| s.content_bounds())
+ && !b.is_empty()
+ {
+ painter.rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, Color32::from_rgb(0x2d, 0x8c, 0xeb)), egui::StrokeKind::Outside);
+ }
+
// Selection outline: true boundary, animated marching ants (cached per revision).
- if let Some(sel) = &doc.selection {
+ if let Some(sel) = doc.selection.as_ref().filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges)) {
// 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;
@@ -654,8 +762,15 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
{
let nz = (view.zoom * zoom_delta).clamp(0.01, 64.0);
zoom_about(&mut view, &xf, p, nz);
+ } else if scroll.y != 0.0
+ && app.session.prefs().general.zoom_with_scroll_wheel
+ && let Some(p) = pointer
+ {
+ // Preferences › General › Zoom with Scroll Wheel.
+ let nz = (view.zoom * (scroll.y / 200.0).exp()).clamp(0.01, 64.0);
+ zoom_about(&mut view, &xf, p, nz);
} else if scroll != Vec2::ZERO {
- view.center[0] -= scroll.x / view.zoom;
+ view.center[0] -= scroll.x / view.zoom * if flip { -1.0 } else { 1.0 };
view.center[1] -= scroll.y / view.zoom;
}
}
@@ -666,7 +781,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
if tool == Tool::Hand && response.dragged() {
let d = response.drag_delta();
- view.center[0] -= d.x / view.zoom;
+ view.center[0] -= d.x / view.zoom * if flip { -1.0 } else { 1.0 };
view.center[1] -= d.y / view.zoom;
} else if primary {
let mods = ui.input(|i| i.modifiers);
@@ -709,11 +824,17 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
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);
+ if app.ui.extras.grid && app.ui.view.extras {
+ crate::rulers::draw_grid(app, &painter, &xf, &doc);
+ }
+ if app.ui.view.shows(app.ui.view.show.canvas_guides) {
+ crate::rulers::draw_guides(app, &painter, &xf, &doc);
}
- crate::rulers::draw_guides(app, &painter, &xf, &doc);
draw_drag_preview(app, &painter, &xf);
+ crate::snap_ui::draw(app, &painter, &xf);
+ if border == photocraft_engine::prefs::CanvasBorder::Line {
+ painter.rect_stroke(img_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside);
+ }
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);
@@ -731,17 +852,42 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
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);
+ // Preferences › Cursors: brush tip outline (normal = the 50% contour, or
+ // full size), precise crosshair, or the standard pointer.
+ use photocraft_engine::prefs::PaintingCursor;
+ let cur = app.session.prefs().cursors.clone();
+ let painting = app.drag.is_some();
+ let brush = &app.session.tools.brush;
+ let full = (brush.size / 2.0 * view.zoom).max(1.0);
+ let r = if cur.painting == PaintingCursor::NormalTip { (full * (0.5 + 0.5 * brush.hardness.clamp(0.0, 1.0))).max(1.0) } else { full };
+ let crosshair = |len: f32| {
+ for (w, c) in [(2.5, Color32::from_black_alpha(140)), (1.0, Color32::from_white_alpha(220))] {
+ painter.line_segment([p - vec2(len, 0.0), p + vec2(len, 0.0)], Stroke::new(w, c));
+ painter.line_segment([p - vec2(0.0, len), p + vec2(0.0, len)], Stroke::new(w, c));
+ }
+ };
+ match cur.painting {
+ PaintingCursor::Standard => egui::CursorIcon::Default,
+ PaintingCursor::Precise => {
+ crosshair(6.0);
+ egui::CursorIcon::None
+ }
+ _ if painting && cur.show_only_crosshair_while_painting => {
+ crosshair(5.0);
+ egui::CursorIcon::None
+ }
+ _ => {
+ 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 cur.show_crosshair_in_brush_tip || r > 6.0 {
+ crosshair(3.0);
+ }
+ egui::CursorIcon::None
+ }
}
- egui::CursorIcon::None
}
+ // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool.
+ Tool::Move | Tool::Type | Tool::Eyedropper if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise => egui::CursorIcon::Crosshair,
Tool::Move => egui::CursorIcon::Move,
Tool::Hand => {
if response.dragged() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab }
@@ -771,7 +917,8 @@ fn zoom_about(view: &mut View, xf: &ViewXform, p: Pos2, new_zoom: f32) {
let before = xf.to_doc(p);
view.zoom = new_zoom;
let d = (p - xf.rect.center()) / new_zoom;
- view.center = [before[0] as f32 - d.x, before[1] as f32 - d.y];
+ let dx = if xf.flip { -d.x } else { d.x };
+ view.center = [before[0] as f32 - dx, before[1] as f32 - d.y];
}
/// Draw boundary segments as marching ants: white base, black dashes phased along x + y.
@@ -953,6 +1100,8 @@ 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) {
+ // View › Snap / Snap To and smart guides (snap_ui.rs).
+ let ev = crate::snap_ui::filter_event(app, ev, mods);
if crate::transform_tool::pointer(app, ev, mods) {
return;
}
@@ -1196,9 +1345,17 @@ pub fn commit_crop(app: &mut PhotocraftApp) {
}
/// "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" }
+pub fn paint_target(app: &PhotocraftApp) -> serde_json::Value {
+ use photocraft_engine::channel_cmds::ChannelTarget;
+ let Some(st) = app.session.active() else { return json!("pixels") };
+ // A targeted alpha channel (Channels panel) or Quick Mask mode wins over the layer.
+ match st.channel_view.target {
+ ChannelTarget::Alpha(i) if i < st.doc.channels.len() => return json!({ "channel": i }),
+ ChannelTarget::Composite if st.doc.quick_mask.is_some() => return json!("quickMask"),
+ _ => {}
+ }
+ let has_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some());
+ json!(if app.ui.mask_target && has_mask { "mask" } else { "pixels" })
}
/// `#rrggbb` for an sRGB colour (the engine's colour parameter notation).
@@ -1213,11 +1370,17 @@ mod tests {
#[test]
fn view_transform_roundtrip() {
- let xf = ViewXform { rect: Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)), zoom: 2.5, center: [320.0, 240.0] };
- let s = xf.to_screen(10.0, 20.0);
- let d = xf.to_doc(s);
- assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3);
- assert_eq!(xf.to_screen(320.0, 240.0), xf.rect.center());
+ for flip in [false, true] {
+ let xf = ViewXform { rect: Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)), zoom: 2.5, center: [320.0, 240.0], flip };
+ let s = xf.to_screen(10.0, 20.0);
+ let d = xf.to_doc(s);
+ assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3);
+ assert_eq!(xf.to_screen(320.0, 240.0), xf.rect.center());
+ // Flipped, document x grows to the left.
+ assert_eq!(xf.to_screen(330.0, 240.0).x > xf.rect.center().x, !flip);
+ let r = xf.doc_rect(DRect::new(0, 0, 10, 10));
+ assert!(r.width() > 0.0 && r.height() > 0.0);
+ }
}
#[test]
diff --git a/crates/ui-egui/src/channel_view.rs b/crates/ui-egui/src/channel_view.rs
new file mode 100644
index 000000000..9fd16e671
--- /dev/null
+++ b/crates/ui-egui/src/channel_view.rs
@@ -0,0 +1,240 @@
+//! Channel display on the canvas: alpha / spot / Quick Mask colour overlays, single colour
+//! channel views (grayscale) and hidden colour channels.
+//!
+//! The document composite (GPU or CPU) is untouched. When the Channels panel shows anything other
+//! than the plain composite, one extra texture is drawn over it: transparent overlay pixels when
+//! the composite stays visible, an opaque picture otherwise. The texture is keyed by document
+//! revision and view state and updated per damage rectangle while painting, so nothing is
+//! recomposited per frame.
+
+use egui::{Color32, TextureOptions};
+use photocraft_doc::{AlphaChannel, ColorMode, Document};
+use photocraft_engine::channel_cmds::{ChannelView, color_count};
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, from_rgba, to_rgba};
+
+use crate::PhotocraftApp;
+
+/// Largest overlay texture side; bigger documents show a downsampled overlay.
+const MAX_SIDE: u32 = 4096;
+
+pub struct Cache {
+ revision: u64,
+ key: u64,
+ factor: u32,
+ tex: egui::TextureHandle,
+}
+
+fn sample(s: &Surface, r: Rect, factor: u32) -> Vec<f32> {
+ let (w, h) = (r.width().div_ceil(factor), r.height().div_ceil(factor));
+ if factor == 1 {
+ let mut v = Vec::new();
+ s.read_region_into(r, &mut v);
+ let ch = s.channels();
+ return if ch > 1 { v.chunks_exact(ch).map(|p| p[0]).collect() } else { v };
+ }
+ let mut out = Vec::with_capacity((w * h) as usize);
+ let mut row = vec![0.0f32; w as usize];
+ for y in 0..h {
+ s.sample_row_strided(r.y0 + (y * factor) as i32, r.x0, factor as i32, 0, &mut row);
+ out.extend_from_slice(&row);
+ }
+ out
+}
+
+/// Composite RGBA (over white, like Photoshop's channel views) at `factor` stride.
+fn composite(doc: &Document, r: Rect, factor: u32) -> Vec<[f32; 4]> {
+ let buf = photocraft_compose::render(doc, r);
+ let (w, h) = (r.width().div_ceil(factor), r.height().div_ceil(factor));
+ let bw = r.width();
+ let mut out = Vec::with_capacity((w * h) as usize);
+ for y in 0..h {
+ for x in 0..w {
+ let p = buf.px[((y * factor) * bw + x * factor) as usize];
+ let a = p[3].clamp(0.0, 1.0);
+ out.push([p[0] * a + 1.0 - a, p[1] * a + 1.0 - a, p[2] * a + 1.0 - a, 1.0]);
+ }
+ }
+ out
+}
+
+/// The channel view of `r` (document pixels, sampled every `factor` px) as premultiplied pixels,
+/// or `None` when the plain composite is all there is to show. `in_color` shows single colour
+/// channels tinted instead of grayscale (Photoshop's "Show Channels in Color").
+pub fn render(doc: &Document, v: &ChannelView, r: Rect, factor: u32, in_color: bool) -> Option<Vec<Color32>> {
+ if v.is_plain(doc) || r.is_empty() {
+ return None;
+ }
+ let colors = color_count(doc);
+ let vis = v.visible_colors(colors);
+ let (w, h) = (r.width().div_ceil(factor), r.height().div_ceil(factor));
+ let n = (w * h) as usize;
+ let mut overlays: Vec<&AlphaChannel> = (0..doc.channels.len()).filter(|i| v.alpha_shown(*i)).map(|i| &doc.channels[i]).collect();
+ // Premultiplied RGBA accumulator.
+ let mut out: Vec<[f32; 4]> = if vis == 0 {
+ // No colour channel visible: the first visible alpha channel in grayscale.
+ let first = (!overlays.is_empty()).then(|| overlays.remove(0))?;
+ sample(&first.surface, r, factor).into_iter().map(|g| [g, g, g, 1.0]).collect()
+ } else if vis < colors {
+ let fmt = doc.pixel_format();
+ let mode = fmt.mode;
+ let shown: Vec<usize> = (0..colors).filter(|k| v.color_visible(*k)).collect();
+ composite(doc, r, factor)
+ .into_iter()
+ .map(|rgba| {
+ let mut native = from_rgba(&fmt, rgba);
+ if shown.len() == 1 && !in_color {
+ let x = native[shown[0]];
+ // Ink channels read dark where there is ink.
+ let g = if mode == ColorMode::Cmyk { 1.0 - x } else { x };
+ return [g, g, g, 1.0];
+ }
+ for (k, x) in native[..colors].iter_mut().enumerate() {
+ if !v.color_visible(k) {
+ // Hidden channels contribute nothing (Lab: neutral a/b).
+ *x = if mode == ColorMode::Lab && k > 0 { 0.5 } else { 0.0 };
+ }
+ }
+ let c = to_rgba(&fmt, &native);
+ [c[0], c[1], c[2], 1.0]
+ })
+ .collect()
+ } else {
+ vec![[0.0; 4]; n]
+ };
+ let quick = doc.quick_mask.as_ref().filter(|_| !v.quick_mask_hidden);
+ for ch in overlays.into_iter().chain(quick) {
+ let (color, opacity) = match ch.spot {
+ // Spot inks show more solid as solidity rises.
+ Some((ink, solidity)) => (ink, 0.5 + 0.5 * solidity),
+ None => (ch.color, ch.opacity),
+ };
+ let c = color.to_rgb();
+ for (o, val) in out.iter_mut().zip(sample(&ch.surface, r, factor)) {
+ let a = (ch.overlay_coverage(val.clamp(0.0, 1.0)) * opacity).clamp(0.0, 1.0);
+ for j in 0..3 {
+ o[j] = c[j] * a + o[j] * (1.0 - a);
+ }
+ o[3] = a + o[3] * (1.0 - a);
+ }
+ }
+ let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
+ Some(out.into_iter().map(|p| Color32::from_rgba_premultiplied(q(p[0]), q(p[1]), q(p[2]), q(p[3]))).collect())
+}
+
+fn view_key(v: &ChannelView, in_color: bool) -> u64 {
+ let s = serde_json::to_string(v).unwrap_or_default();
+ s.bytes().fold(in_color as u64 + 1, |h, b| h.wrapping_mul(1_099_511_628_211).wrapping_add(b as u64))
+}
+
+/// Make the channel-view texture of document `idx` current; `None` = nothing to draw.
+pub fn ensure(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Option<egui::TextureId> {
+ let st = app.session.documents().get(idx)?;
+ let doc = st.doc.clone();
+ let view = st.channel_view.clone();
+ let (revision, damage) = (st.revision, st.last_damage);
+ let id = doc.id.0;
+ if view.is_plain(&doc) {
+ app.channel_views.remove(&id);
+ return None;
+ }
+ let in_color = false;
+ let key = view_key(&view, in_color);
+ // Never exceed what the GPU accepts (egui panics on oversized textures).
+ let max_side = (ctx.input(|i| i.max_texture_side) as u32).clamp(256, MAX_SIDE);
+ let factor = doc.size.width.max(doc.size.height).div_ceil(max_side).max(1);
+ if let Some(c) = app.channel_views.get_mut(&id)
+ && c.key == key
+ && c.factor == factor
+ {
+ if c.revision == revision {
+ return Some(c.tex.id());
+ }
+ if c.revision + 1 == revision
+ && factor == 1
+ && let Some(d) = damage
+ {
+ let r = d.intersect(&doc.bounds());
+ if !r.is_empty()
+ && let Some(px) = render(&doc, &view, r, 1, in_color)
+ {
+ let img = egui::ColorImage::new([r.width() as usize, r.height() as usize], px);
+ c.tex.set_partial([r.x0 as usize, r.y0 as usize], img, TextureOptions::LINEAR);
+ }
+ c.revision = revision;
+ return Some(c.tex.id());
+ }
+ }
+ let b = doc.bounds();
+ let px = render(&doc, &view, b, factor, in_color)?;
+ let size = [b.width().div_ceil(factor) as usize, b.height().div_ceil(factor) as usize];
+ let img = egui::ColorImage::new(size, px);
+ match app.channel_views.get_mut(&id) {
+ Some(c) if c.tex.size() == size => {
+ c.tex.set(img, TextureOptions::LINEAR);
+ c.revision = revision;
+ c.key = key;
+ c.factor = factor;
+ }
+ _ => {
+ let tex = ctx.load_texture(format!("channel-view-{id}"), img, TextureOptions::LINEAR);
+ app.channel_views.insert(id, Cache { revision, key, factor, tex });
+ }
+ }
+ app.channel_views.get(&id).map(|c| c.tex.id())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_engine::Session;
+ use photocraft_engine::channel_cmds::ChannelTarget;
+ use serde_json::json;
+
+ fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 4})).unwrap();
+ s
+ }
+
+ #[test]
+ fn plain_composite_draws_nothing() {
+ let s = session();
+ let st = s.active().unwrap();
+ assert!(render(&st.doc, &st.channel_view, st.doc.bounds(), 1, false).is_none());
+ }
+
+ #[test]
+ fn quick_mask_overlay_is_red_over_masked_areas() {
+ let mut s = session();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap();
+ s.execute("select.editInQuickMaskMode", json!({})).unwrap();
+ let st = s.active().unwrap();
+ let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, false).unwrap();
+ assert_eq!(px[0], Color32::TRANSPARENT, "selected: no overlay");
+ assert_eq!(px[6], Color32::from_rgba_premultiplied(128, 0, 0, 128), "masked: 50% red");
+ }
+
+ #[test]
+ fn solo_alpha_is_grayscale_and_colour_channels_split() {
+ let mut s = session();
+ s.execute("edit.fill", json!({"color": "#ff8000"})).unwrap();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 2, "height": 4})).unwrap();
+ s.execute("channel.new", json!({"fill": "selection"})).unwrap();
+ let st = s.active().unwrap();
+ assert_eq!(st.channel_view.target, ChannelTarget::Alpha(0));
+ let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, false).unwrap();
+ assert_eq!((px[0], px[5]), (Color32::WHITE, Color32::BLACK));
+ // Green alone: grayscale of the green channel; with blue hidden only.
+ s.execute("channel.target", json!({"channel": "green"})).unwrap();
+ let st = s.active().unwrap();
+ let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, false).unwrap();
+ assert_eq!(px[0], Color32::from_gray(128));
+ s.execute("channel.target", json!({"channel": "composite"})).unwrap();
+ s.execute("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap();
+ let st = s.active().unwrap();
+ let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 2, false).unwrap();
+ assert_eq!(px.len(), 4 * 2);
+ assert_eq!(px[0], Color32::from_rgb(0, 128, 0));
+ }
+}
diff --git a/crates/ui-egui/src/channels_panel.rs b/crates/ui-egui/src/channels_panel.rs
new file mode 100644
index 000000000..c38b4e0be
--- /dev/null
+++ b/crates/ui-egui/src/channels_panel.rs
@@ -0,0 +1,269 @@
+//! The Channels panel (tab of the Layers card): composite, colour, alpha / spot and Quick Mask
+//! rows with thumbnails and eye toggles. Every action is an engine command (`channel.*`,
+//! `select.loadSelection`, `select.saveSelection`, …); the targeted channel and the eyes live in
+//! the engine's `DocState::channel_view`, so agents see the same state through `inspect`.
+
+use egui::{Align2, Color32, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2};
+use photocraft_doc::ColorIndicates;
+use photocraft_engine::channel_cmds::{self, ChannelTarget};
+use serde_json::{Value, json};
+
+use crate::theme::{self, Tokens};
+use crate::{PhotocraftApp, icons, widgets};
+
+#[derive(Clone, Copy, PartialEq)]
+enum Row {
+ Composite,
+ Color(usize),
+ Alpha(usize),
+ QuickMask,
+}
+
+impl Row {
+ /// The channel reference the engine commands take.
+ fn reference(self) -> Value {
+ match self {
+ Row::Composite => json!("composite"),
+ Row::Color(k) => json!({ "color": k }),
+ Row::Alpha(i) => json!(i),
+ Row::QuickMask => json!("quickMask"),
+ }
+ }
+}
+
+/// ⌘ = new selection, ⌘⇧ add, ⌘⌥ subtract, ⌘⌥⇧ intersect (Photoshop's thumbnail ⌘-clicks).
+pub fn load_operation(m: egui::Modifiers) -> &'static str {
+ match (m.shift, m.alt) {
+ (true, true) => "intersect",
+ (true, false) => "add",
+ (false, true) => "subtract",
+ _ => "new",
+ }
+}
+
+pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let Some(st) = app.session.active() else {
+ ui.add_space(6.0);
+ ui.label(RichText::new("No document").color(t.text_faint));
+ return;
+ };
+ let doc = st.doc.clone();
+ let view = st.channel_view.clone();
+ let mode = doc.pixel_format().mode;
+ let colors = mode.color_channels();
+ let quick = doc.quick_mask.is_some();
+ let ctx = ui.ctx().clone();
+ let thumbs = app.channel_thumbs(&ctx);
+ let mut rows = vec![Row::Composite];
+ if colors > 1 {
+ rows.extend((0..colors).map(Row::Color));
+ }
+ rows.extend((0..doc.channels.len()).map(Row::Alpha));
+ if quick {
+ rows.push(Row::QuickMask);
+ }
+ let shown_colors = if colors > 1 { colors } else { 0 };
+ let mut actions: Vec<(String, Value)> = Vec::new();
+ let footer = 34.0;
+ egui::ScrollArea::vertical().max_height((ui.available_height() - footer).max(60.0)).auto_shrink([false, true]).show(ui, |ui| {
+ for row in rows {
+ let (name, thumb_idx, slot, visible, selected) = match row {
+ Row::Composite => (channel_cmds::composite_name(mode).to_string(), 0, Some(2), view.visible_colors(colors) == colors, view.target == ChannelTarget::Composite && !quick),
+ Row::Color(k) => (channel_cmds::color_names(mode)[k].to_string(), 1 + k, Some(3 + k), view.color_visible(k), (view.target == ChannelTarget::Composite && !quick) || view.target == ChannelTarget::Color(k)),
+ Row::Alpha(i) => (doc.channels[i].name.clone(), 1 + shown_colors + i, Some(3 + shown_colors + i).filter(|s| *s <= 9), view.alpha_shown(i), view.target == ChannelTarget::Alpha(i)),
+ Row::QuickMask => ("Quick Mask".to_string(), 1 + shown_colors + doc.channels.len(), None, !view.quick_mask_hidden, view.target == ChannelTarget::Composite),
+ };
+ let row_h = if t.pro { 36.0 } else { 40.0 };
+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click());
+ let painter = ui.painter_at(rect.expand(1.0));
+ if selected {
+ painter.rect_filled(rect, if t.pro { 0.0 } else { t.radius }, if t.pro { t.row_selected } else { t.hover });
+ } else if resp.hovered() {
+ painter.rect_filled(rect, if t.pro { 0.0 } else { t.radius }, t.hover.gamma_multiply(0.5));
+ }
+ if t.pro {
+ painter.line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator));
+ painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator));
+ }
+ let eye = Rect::from_min_size(pos2(rect.left() + 6.0, rect.center().y - 11.0), vec2(22.0, 22.0));
+ let eye_resp = ui.interact(eye, ui.id().with(("chan-eye", format!("{:?}", row.reference()))), Sense::click());
+ icons::paint(ui, eye, if visible { "eye" } else { "eye-off" }, 14.0, if visible { t.icon } else { t.text_faint });
+ if eye_resp.clicked() {
+ actions.push(("channel.setVisible".into(), json!({ "channel": row.reference(), "visible": !visible })));
+ }
+ let ts = if t.pro { 28.0 } else { 30.0 };
+ let thumb = Rect::from_min_size(pos2(rect.left() + 36.0, rect.center().y - ts / 2.0), vec2(ts, ts));
+ if let Some(tex) = thumbs.get(thumb_idx) {
+ painter.image(*tex, thumb, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
+ }
+ // Spot channels: a swatch of the ink on the thumbnail corner.
+ if let Row::Alpha(i) = row
+ && let Some((ink, _)) = doc.channels[i].spot
+ {
+ let c = ink.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8);
+ painter.rect_filled(Rect::from_min_size(thumb.right_bottom() - vec2(9.0, 9.0), vec2(9.0, 9.0)), 0.0, Color32::from_rgb(c[0], c[1], c[2]));
+ }
+ painter.rect_stroke(thumb, 0.0, Stroke::new(1.0, if t.pro { Color32::from_gray(20) } else { t.field_border }), StrokeKind::Outside);
+ let italic = row == Row::QuickMask || matches!(row, Row::Alpha(i) if doc.channels[i].spot.is_some());
+ let mut job = egui::text::LayoutJob::default();
+ let font = if selected && !t.pro { theme::medium(12.5) } else { egui::FontId::proportional(12.0) };
+ job.append(&name, 0.0, egui::TextFormat { font_id: font, color: t.text, italics: italic, ..Default::default() });
+ let galley = painter.layout_job(job);
+ let text_pos = pos2(thumb.right() + 10.0, rect.center().y - galley.size().y / 2.0);
+ painter.galley(text_pos, galley, t.text);
+ if let Some(slot) = slot {
+ painter.text(pos2(rect.right() - 8.0, rect.center().y), Align2::RIGHT_CENTER, crate::shortcuts::pretty(&format!("Cmd+{slot}")), theme::mono(11.0), t.text_faint);
+ }
+ let rename_id = egui::Id::new(("chan-rename", doc.id.0, format!("{:?}", row.reference())));
+ if resp.clicked() && !eye_resp.clicked() {
+ let m = ui.input(|i| i.modifiers);
+ if m.command {
+ actions.push(("select.loadSelection".into(), json!({ "channel": row.reference(), "operation": load_operation(m) })));
+ } else {
+ let target = if row == Row::QuickMask { json!("composite") } else { row.reference() };
+ actions.push(("channel.target".into(), json!({ "channel": target })));
+ }
+ }
+ if let Row::Alpha(i) = row {
+ if resp.double_clicked() {
+ ctx.data_mut(|d| d.insert_temp(rename_id, name.clone()));
+ }
+ if let Some(mut text) = ctx.data(|d| d.get_temp::<String>(rename_id)) {
+ let edit_rect = Rect::from_min_max(pos2(text_pos.x - 3.0, rect.center().y - 11.0), pos2(rect.right() - 36.0, rect.center().y + 11.0));
+ let te = ui.put(edit_rect, egui::TextEdit::singleline(&mut text).font(egui::FontId::proportional(12.5)));
+ te.request_focus();
+ let (enter, esc) = ui.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)));
+ if esc {
+ ctx.data_mut(|d| d.remove::<String>(rename_id));
+ } else if enter || te.lost_focus() {
+ ctx.data_mut(|d| d.remove::<String>(rename_id));
+ if !text.trim().is_empty() && text != name {
+ actions.push(("channel.rename".into(), json!({ "channel": i, "name": text.trim() })));
+ }
+ } else {
+ ctx.data_mut(|d| d.insert_temp(rename_id, text));
+ }
+ }
+ }
+ resp.context_menu(|ui| {
+ ui.set_min_width(210.0);
+ let a = &mut actions;
+ match row {
+ Row::Alpha(i) => {
+ let ch = &doc.channels[i];
+ item(ui, a, "Duplicate Channel", "channel.duplicate", json!({ "channel": i }));
+ item(ui, a, "Delete Channel", "channel.delete", json!({ "channel": i }));
+ item(ui, a, "Rename Channel…", "ui.renameChannel", json!(i));
+ ui.separator();
+ if ch.spot.is_some() {
+ item(ui, a, "Merge Spot Channel", "channel.mergeSpot", json!({ "channel": i }));
+ item(ui, a, "Convert to Alpha Channel", "channel.options", json!({ "channel": i, "indicates": "masked" }));
+ } else {
+ indicates_items(ui, a, json!(i), ch.indicates);
+ overlay_colors(ui, a, json!(i));
+ }
+ }
+ Row::QuickMask => {
+ item(ui, a, "Exit Quick Mask", "select.editInQuickMaskMode", json!({ "on": false }));
+ indicates_items(ui, a, json!("quickMask"), doc.quick_mask.as_ref().map(|q| q.indicates).unwrap_or_default());
+ overlay_colors(ui, a, json!("quickMask"));
+ }
+ Row::Composite | Row::Color(_) => {
+ item(ui, a, "Duplicate Channel", "channel.duplicate", json!({ "channel": row.reference() }));
+ }
+ }
+ ui.separator();
+ item(ui, a, "New Channel…", "channel.new", json!({}));
+ item(ui, a, "New Spot Channel…", "channel.newSpot", json!({}));
+ ui.separator();
+ item(ui, a, "Split Channels", "channel.split", json!({}));
+ item(ui, a, "Merge Channels…", "channel.merge", json!({}));
+ });
+ }
+ });
+ ui.add_space(4.0);
+ widgets::hairline(ui);
+ ui.add_space(2.0);
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
+ let target_ref = match view.target {
+ ChannelTarget::Alpha(i) => json!(i),
+ ChannelTarget::Color(k) => json!({ "color": k }),
+ ChannelTarget::Composite => json!("composite"),
+ };
+ if icons::button(ui, "circle-dashed", 26.0, false, "Load channel as selection").clicked() {
+ actions.push(("select.loadSelection".into(), json!({ "channel": target_ref })));
+ }
+ if icons::button(ui, "square-dashed", 26.0, false, "Save selection as channel").clicked() {
+ actions.push(("select.saveSelection".into(), json!({})));
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if icons::button(ui, "trash", 26.0, false, "Delete current channel").clicked() {
+ actions.push(("channel.delete".into(), json!({})));
+ }
+ if icons::button(ui, "plus", 26.0, false, "Create new channel").clicked() {
+ actions.push(("channel.new".into(), json!({})));
+ }
+ });
+ });
+ for (id, p) in actions {
+ if id == "ui.renameChannel" {
+ if let Some(i) = p.as_u64().and_then(|i| doc.channels.get(i as usize)) {
+ let row = Row::Alpha(p.as_u64().unwrap_or(0) as usize);
+ ctx.data_mut(|d| d.insert_temp(egui::Id::new(("chan-rename", doc.id.0, format!("{:?}", row.reference()))), i.name.clone()));
+ }
+ continue;
+ }
+ let _ = app.run(&id, p);
+ }
+}
+
+fn item(ui: &mut egui::Ui, actions: &mut Vec<(String, Value)>, label: &str, cmd: &str, p: Value) {
+ if ui.button(label).clicked() {
+ actions.push((cmd.into(), p));
+ ui.close();
+ }
+}
+
+/// Channel Options › Color Indicates.
+fn indicates_items(ui: &mut egui::Ui, actions: &mut Vec<(String, Value)>, channel: Value, current: ColorIndicates) {
+ let masked = current == ColorIndicates::MaskedAreas;
+ let check = |on: bool, s: &str| if on { format!("✓ {s}") } else { s.to_string() };
+ item(ui, actions, &check(masked, "Color Indicates Masked Areas"), "channel.options", json!({ "channel": channel.clone(), "indicates": "masked" }));
+ item(ui, actions, &check(!masked, "Color Indicates Selected Areas"), "channel.options", json!({ "channel": channel, "indicates": "selected" }));
+}
+
+/// Overlay colour presets (Channel Options › Color) and opacity.
+fn overlay_colors(ui: &mut egui::Ui, actions: &mut Vec<(String, Value)>, channel: Value) {
+ ui.menu_button("Overlay Color", |ui| {
+ for (label, hex) in [("Red", "#ff0000"), ("Green", "#00c000"), ("Blue", "#0050ff"), ("Cyan", "#00d0e0"), ("Magenta", "#e000c0"), ("Yellow", "#f0d000")] {
+ if ui.button(label).clicked() {
+ actions.push(("channel.options".into(), json!({ "channel": channel.clone(), "color": hex })));
+ ui.close();
+ }
+ }
+ });
+ ui.menu_button("Overlay Opacity", |ui| {
+ for o in [25, 50, 75, 100] {
+ if ui.button(format!("{o}%")).clicked() {
+ actions.push(("channel.options".into(), json!({ "channel": channel.clone(), "opacity": o })));
+ ui.close();
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn modifier_operations() {
+ let m = |shift, alt| egui::Modifiers { command: true, shift, alt, ..Default::default() };
+ assert_eq!(load_operation(m(false, false)), "new");
+ assert_eq!(load_operation(m(true, false)), "add");
+ assert_eq!(load_operation(m(false, true)), "subtract");
+ assert_eq!(load_operation(m(true, true)), "intersect");
+ }
+}
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 2fe364f4c..27b8733f8 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -73,6 +73,12 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
"engine.execute" | "ui.menu.invoke" => {
let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
let params = p.get("params").cloned().unwrap_or(json!({}));
+ // `engine.execute` is programmatic: engine commands run directly with their default
+ // params and never open a dialog (an agent would otherwise get a modal instead of a
+ // result). `ui.menu.invoke` behaves like a menu click, so it may open the dialog.
+ if req.method == "engine.execute" && photocraft_engine::commands::find(id).is_some() {
+ return wrap(app.run(id, params));
+ }
wrap(crate::menus::invoke(app, ctx, id, params))
}
"engine.commands" => wrap(app.run("command.list", json!({}))),
@@ -133,6 +139,12 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
None => return err(format!("unknown theme `{name}` (studio, studioLight, classic)")),
}
}
+ if let Some(i) = u("brushSection") {
+ app.ui.brush_section = (i as usize).min(crate::brush_panel::SECTIONS.len() - 1);
+ }
+ if let Some(i) = u("brushTab") {
+ app.ui.brush_tab = (i as usize).min(1);
+ }
if let Some(size) = p.get("brushSize").and_then(Value::as_f64) {
app.session.tools.brush.size = size as f32;
}
@@ -335,3 +347,32 @@ pub fn save_screenshot(app: &mut PhotocraftApp, image: &egui::ColorImage, path:
Err(e) => json!({"ok": false, "error": e}),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value {
+ let (req, _rx) = ControlRequest::new(method, params);
+ match handle(app, ctx, &req) {
+ Outcome::Done(v) => v,
+ _ => panic!("{method}: expected an immediate reply"),
+ }
+ }
+
+ #[test]
+ fn engine_execute_runs_with_defaults_but_menu_invoke_opens_the_dialog() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ app.run("file.new", json!({"width": 32, "height": 32})).unwrap();
+ app.run("edit.fill", json!({"color": "#808080"})).unwrap();
+ let rev = app.session.active().unwrap().revision;
+ let r = call(&mut app, &ctx, "engine.execute", json!({"command": "filter.blur.gaussianBlur"}));
+ assert!(!r.to_string().contains("\"dialog\""), "engine.execute opened a dialog: {r}");
+ assert!(app.session.active().unwrap().revision > rev, "engine.execute didn't run the filter");
+ let rev = app.session.active().unwrap().revision;
+ let r = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "filter.blur.gaussianBlur"}));
+ assert!(r.to_string().contains("dialog"), "ui.menu.invoke should open the dialog: {r}");
+ assert_eq!(app.session.active().unwrap().revision, rev, "opening a dialog must not edit the document");
+ }
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 7c1df6da9..490105d1e 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -12,9 +12,14 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let mut fields = d.fields.clone();
let mut outcome: Option<bool> = None; // Some(true)=OK, Some(false)=Cancel
let title = title(&d);
- let modal = egui::Modal::new(egui::Id::new(("dialog", d.id))).show(ctx, |ui| {
+ // Photoshop doesn't dim the window behind dialogs: previews must be judged at true contrast.
+ let modal = egui::Modal::new(egui::Id::new(("dialog", d.id))).backdrop_color(egui::Color32::TRANSPARENT).show(ctx, |ui| {
ui.set_min_width(380.0);
- ui.set_max_width(if d.kind == DialogKind::LayerStyle || d.fields.contains_key("__export") { 600.0 } else { 440.0 });
+ let wide = crate::prefs_ui::width(&d.fields);
+ if let Some(w) = wide {
+ ui.set_min_width(w.min(460.0));
+ }
+ ui.set_max_width(wide.unwrap_or(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,9 +31,11 @@ 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 crate::prefs_ui::owns(&fields) => crate::prefs_ui::body(app, ui, &mut fields),
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 if fields.contains_key("__form") => crate::view_cmds::form_body(ui, &mut fields),
DialogKind::Command => command_fields(ui, &mut fields),
DialogKind::LayerStyle => crate::layer_style::body(ui, &mut fields),
DialogKind::Error => {
@@ -99,11 +106,13 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
}
r
}
+ DialogKind::Command if crate::prefs_ui::owns(&d.fields) => crate::prefs_ui::confirm(app, &d.fields),
DialogKind::Command if d.fields.contains_key("__export") => crate::export_dialog::confirm(app, &d.fields),
DialogKind::Command => {
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))
+ let (cmd, params) = crate::smart_ui::confirm_command(&d.fields, cmd, crate::filter_dialog::params_of(&d.fields));
+ app.run(&cmd, params)
}
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.rs
index 858dc1fb2..ee4b7cb72 100644
--- a/crates/ui-egui/src/export_dialog.rs
+++ b/crates/ui-egui/src/export_dialog.rs
@@ -27,6 +27,39 @@ pub fn open(app: &mut PhotocraftApp) -> Result<u64, String> {
Ok(app.ui.open_dialog(DialogKind::Command, f))
}
+/// Layer › Export As…: the same dialog for just the active layer (trimmed to its pixels).
+pub fn open_layer(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Result<u64, String> {
+ let st = app.session.active().ok_or("no document")?;
+ let ldoc = photocraft_engine::layer_menu_cmds::layer_document(&st.doc, layer).map_err(|e| e.to_string())?;
+ let id = open(app)?;
+ if let Some(d) = app.ui.dialogs.iter_mut().find(|d| d.id == id) {
+ d.fields.insert("__layer".into(), json!(layer.0));
+ d.fields.insert("__label".into(), json!(format!("Export As: {}", ldoc.name)));
+ d.fields.insert("__w".into(), json!(ldoc.size.width));
+ d.fields.insert("__h".into(), json!(ldoc.size.height));
+ }
+ Ok(id)
+}
+
+/// Layer › Quick Export as PNG.
+pub fn quick_export_layer_png(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> 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));
+ f.insert("__layer".into(), json!(layer.0));
+ confirm(app, &f)
+}
+
+/// The document a dialog exports: the whole image, or one layer (`__layer`).
+fn source_document(app: &PhotocraftApp, f: &Map<String, Value>) -> Result<Arc<Document>, String> {
+ let st = app.session.active().ok_or("no document")?;
+ match f.get("__layer").and_then(Value::as_u64) {
+ Some(id) => photocraft_engine::layer_menu_cmds::layer_document(&st.doc, photocraft_doc::LayerId(id)).map(Arc::new).map_err(|e| e.to_string()),
+ None => Ok(st.doc.clone()),
+ }
+}
+
fn s(f: &Map<String, Value>, k: &str) -> String {
f.get(k).and_then(Value::as_str).unwrap_or_default().to_string()
}
@@ -111,20 +144,23 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
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());
+ let (bw, bh) = (n(f, "__w", f64::from(doc.size.width)) as f32, n(f, "__h", f64::from(doc.size.height)) as f32);
+ let (w, h) = ((bw * sc / 100.0).round(), (bh * 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 layer = f.get("__layer").and_then(Value::as_u64);
+ let key = egui::Id::new(("export-preview", doc.id.0, app.session.active().map_or(0, |s| s.revision), layer));
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 src = source_document(app, f).unwrap_or_else(|_| doc.clone());
+ let size = estimate(app, &src, f);
+ let img = photocraft_compose::thumbnail(&export_document(&src, f, Some(360)).unwrap_or_else(|_| (*src).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())));
@@ -147,8 +183,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
/// 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 doc = source_document(app, f)?;
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}");
diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs
index 35b6ea9ff..42ca4577d 100644
--- a/crates/ui-egui/src/filter_dialog.rs
+++ b/crates/ui-egui/src/filter_dialog.rs
@@ -15,8 +15,16 @@ use crate::theme::Tokens;
pub enum Kind {
Range { min: f32, max: f32, default: f32 },
Choice(Vec<String>),
- Bool,
+ Bool(bool),
Int { default: i64 },
+ /// Free text (e.g. a file path).
+ Text,
+ /// One of the open documents (stored as its index).
+ Document,
+ /// A row-major grid of integers (`int[25]` = 5×5).
+ Grid(usize),
+ /// Structured JSON (pins, curve points…): settable through the command, not shown in the dialog.
+ Json,
}
#[derive(Clone, Debug, PartialEq)]
@@ -30,15 +38,23 @@ pub struct Param {
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":`.
+ // Split on commas that start a new `"key":` (not inside strings or brackets).
let mut parts: Vec<String> = Vec::new();
let mut cur = String::new();
let mut in_str = false;
+ let mut depth = 0i32;
for ch in inner.chars() {
if ch == '"' {
in_str = !in_str;
}
- if ch == ',' && !in_str {
+ if !in_str {
+ match ch {
+ '[' | '{' => depth += 1,
+ ']' | '}' => depth -= 1,
+ _ => {}
+ }
+ }
+ if ch == ',' && !in_str && depth == 0 {
parts.push(std::mem::take(&mut cur));
} else {
cur.push(ch);
@@ -57,8 +73,16 @@ pub fn parse_spec(spec: &str) -> Vec<Param> {
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(rest) = v.strip_prefix("bool") {
+ Kind::Bool(rest.trim_start_matches('=').trim() == "true")
+ } else if v == "text" {
+ Kind::Text
+ } else if v == "doc" {
+ Kind::Document
+ } else if v == "json" || v.starts_with('[') || v.starts_with('{') {
+ Kind::Json
+ } else if let Some(n) = v.strip_prefix("int[").and_then(|r| r.strip_suffix(']')).and_then(|n| n.parse().ok()) {
+ Kind::Grid(n)
} 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);
@@ -78,11 +102,28 @@ pub fn parse_spec(spec: &str) -> Vec<Param> {
/// 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")
+ matches!(key, "radius" | "distance" | "cellSize" | "horizontal" | "vertical" | "height" | "wavelengthMin" | "wavelengthMax" | "amplitudeMin" | "amplitudeMax" | "maxRadius" | "size" | "blur" | "speed")
}
+/// Commands outside `filter.*` that get the schema dialog *with* live preview.
+pub const PREVIEWED: &[&str] = &[
+ "image.adjustments.selectiveColor",
+ "image.adjustments.colorLookup",
+ "image.adjustments.shadowsHighlights",
+ "image.adjustments.replaceColor",
+ "image.adjustments.matchColor",
+ "image.adjustments.hdrToning",
+ "image.rotation.arbitrary",
+ "image.mode.indexedColor",
+ "image.mode.bitmap",
+ "image.mode.duotone",
+ "layer.matting.defringe",
+ "layer.matting.colorDecontaminate",
+ "layer.layerStyle.scaleEffects",
+];
+
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())
+ (command.starts_with("filter.") || command.starts_with("select.modify.") || PREVIEWED.contains(&command) || matches!(command, "image.trim" | "view.newGuide" | "select.refineEdge" | "edit.assignProfile" | "edit.convertToProfile" | "view.proofSetup" | "layer.layerStyle.globalLight" | "image.mode.colorTable")) && 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> {
@@ -91,18 +132,31 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
fields.insert("__command".into(), json!(command));
fields.insert("__label".into(), json!(spec.label));
fields.insert("__filter".into(), json!(true));
- if command.starts_with("filter.") {
+ if command.starts_with("filter.") || PREVIEWED.contains(&command) {
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::Bool(default) => json!(default),
Kind::Int { default } => json!(default),
+ Kind::Text => json!(""),
+ Kind::Document => json!(-1),
+ // Identity kernel: 1 in the centre.
+ Kind::Grid(n) => json!((0..*n).map(|i| i64::from(i == *n / 2)).collect::<Vec<_>>()),
+ // Colour inputs come from the current swatches, so the proxy preview matches the result.
+ Kind::Json if p.key == "foreground" => json!(app.session.tools.foreground),
+ Kind::Json if p.key == "background" => json!(app.session.tools.background),
+ Kind::Json => continue,
};
fields.insert(p.key, v);
}
+ if parse_spec(spec.params).iter().any(|p| p.kind == Kind::Document) {
+ // The document picker lists every open document (params refer to them by index).
+ let names: Vec<String> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();
+ fields.insert("__docs".into(), json!(names));
+ }
let id = app.ui.open_dialog(crate::state::DialogKind::Command, fields);
Some(id)
}
@@ -162,11 +216,54 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
f.insert(p.key.clone(), json!(cur));
});
}
- Kind::Bool => {
- let mut b = f.get(&p.key).and_then(Value::as_bool).unwrap_or(false);
+ Kind::Bool(default) => {
+ let mut b = f.get(&p.key).and_then(Value::as_bool).unwrap_or(default);
crate::widgets::checkbox(ui, &mut b, &label(&p.key));
f.insert(p.key, json!(b));
}
+ Kind::Text => {
+ let mut v = f.get(&p.key).and_then(Value::as_str).unwrap_or_default().to_string();
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(label(&p.key)).color(t.text_dim));
+ ui.add(egui::TextEdit::singleline(&mut v).desired_width(200.0));
+ });
+ if v.is_empty() {
+ f.remove(&p.key);
+ } else {
+ f.insert(p.key, json!(v));
+ }
+ }
+ Kind::Document => {
+ let names: Vec<String> = f.get("__docs").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
+ let cur = f.get(&p.key).and_then(Value::as_i64).unwrap_or(-1);
+ let mut sel = cur.to_string();
+ let mut opts: Vec<(String, &str)> = vec![("-1".to_string(), "None")];
+ opts.extend(names.iter().enumerate().map(|(i, n)| (i.to_string(), n.as_str())));
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(label(&p.key)).color(t.text_dim));
+ crate::widgets::dropdown(ui, &format!("flt-{cmd}-{}", p.key), &mut sel, &opts, 170.0);
+ });
+ match sel.parse::<i64>() {
+ Ok(i) if i >= 0 => f.insert(p.key, json!(i)),
+ _ => f.insert(p.key, json!(-1)),
+ };
+ }
+ Kind::Grid(n) => {
+ let side = (n as f32).sqrt().round().max(1.0) as usize;
+ let mut vals: Vec<f32> = f.get(&p.key).and_then(Value::as_array).map(|a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect()).unwrap_or_default();
+ vals.resize(n, 0.0);
+ ui.label(egui::RichText::new(label(&p.key)).color(t.text_dim));
+ egui::Grid::new(format!("flt-grid-{cmd}-{}", p.key)).spacing([4.0, 4.0]).show(ui, |ui| {
+ for (i, v) in vals.iter_mut().enumerate() {
+ crate::widgets::value_field(ui, v, -999.0..=999.0, "", 44.0);
+ if (i + 1) % side == 0 {
+ ui.end_row();
+ }
+ }
+ });
+ f.insert(p.key, json!(vals.iter().map(|v| v.round() as i64).collect::<Vec<_>>()));
+ }
+ Kind::Json => {}
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| {
@@ -186,7 +283,9 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
/// 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())
+ // A document picker left at "None" (-1) means "not given".
+ let unset = |k: &str, v: &Value| k == "mapDocument" && v.as_i64() == Some(-1);
+ Value::Object(f.iter().filter(|(k, v)| !k.starts_with("__") && !unset(k, v)).map(|(k, v)| (k.clone(), v.clone())).collect())
}
/// Compute a preview document: run `command` with `params` on the proxy (scaled) copy of `doc`.
@@ -231,10 +330,23 @@ mod tests {
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[2].kind, Kind::Bool(false));
assert_eq!(p[3].kind, Kind::Int { default: 0 });
assert_eq!(p[4].kind, Kind::Int { default: 0 });
assert!(parse_spec("{}").is_empty());
+ let p = parse_spec(r#"{"lighting":bool=true,"kernel":int[25],"pins":json,"points":[[0,0],[1,0]],"mapPath":text,"mapDocument":doc,"scale":1..9999=1}"#);
+ let kinds: Vec<&Kind> = p.iter().map(|p| &p.kind).collect();
+ assert_eq!(kinds, [&Kind::Bool(true), &Kind::Grid(25), &Kind::Json, &Kind::Json, &Kind::Text, &Kind::Document, &Kind::Range { min: 1.0, max: 9999.0, default: 1.0 }]);
+ }
+
+ #[test]
+ fn new_filters_have_dialogs_or_run_directly() {
+ for id in ["filter.stylize.oilPaint", "filter.blur.lensBlur", "filter.blurGallery.irisBlur", "filter.other.custom", "filter.distort.displace", "filter.pixelate.mezzotint", "filter.render.lightingEffects"] {
+ assert!(has_dialog(id), "{id}");
+ }
+ for id in ["filter.pixelate.facet", "filter.pixelate.fragment", "filter.video.ntscColors"] {
+ assert!(!has_dialog(id), "{id}");
+ }
}
#[test]
diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs
index 883d94bd5..d5f2cb3d9 100644
--- a/crates/ui-egui/src/gpu_canvas.rs
+++ b/crates/ui-egui/src/gpu_canvas.rs
@@ -30,7 +30,8 @@ use eframe::wgpu::util::DeviceExt as _;
/// Default tile side; documents up to this size (and the device limit) use a single texture.
pub const DEFAULT_TILE: u32 = 8192;
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
-const VIEW_UNIFORM_SIZE: u64 = 64;
+const VIEW_UNIFORM_SIZE: u64 = 112;
+const VIEW_FLOATS: usize = 28;
const TILE_UNIFORM_SIZE: u64 = 16;
/// Parameters for drawing one document view. Positions are in egui points.
@@ -50,6 +51,9 @@ pub struct ViewParams {
pub pixel_grid: bool,
/// Distinguishes views painted in the same frame (main canvas, extra windows).
pub view_key: u64,
+ /// Display transform: 0 none, 1 the document's display LUT (Proof Colors), 2 LUT plus the
+ /// gamut warning (see [`GpuCanvas::set_display_lut`]).
+ pub display: u8,
}
/// Uploads documents to the GPU and paints them. Cheap to clone.
@@ -62,15 +66,28 @@ pub struct GpuCanvas {
impl GpuCanvas {
/// Create pipelines and register resources with the egui renderer.
pub fn new(rs: &RenderState) -> Self {
+ Self::with_tile(rs, None)
+ }
+
+ /// Like [`GpuCanvas::new`] with a preferred texture tile side (`PHOTOCRAFT_GPU_TILE` wins).
+ pub fn with_tile(rs: &RenderState, tile: Option<u32>) -> Self {
let max = rs.device.limits().max_texture_dimension_2d;
let env_tile = std::env::var("PHOTOCRAFT_GPU_TILE").ok().and_then(|v| v.parse::<u32>().ok());
- let tile = env_tile.unwrap_or(DEFAULT_TILE).clamp(64, max);
- let res = Resources::new(&rs.device, rs.target_format);
+ let tile = env_tile.or(tile).unwrap_or(DEFAULT_TILE).clamp(64, max);
+ let res = Resources::new(&rs.device, &rs.queue, rs.target_format);
rs.renderer.write().callback_resources.insert(res);
log::info!("gpu canvas: target {:?}, max texture {max}, tile {tile}", rs.target_format);
Self { rs: rs.clone(), tile }
}
+ /// Set the checkerboard and gamut warning colours.
+ pub fn set_style(&self, style: CanvasStyle) {
+ let mut r = self.rs.renderer.write();
+ if let Some(res) = r.callback_resources.get_mut::<Resources>() {
+ res.style = style;
+ }
+ }
+
/// Whether document `doc` has been uploaded with this size.
pub fn has(&self, doc: u64, size: [u32; 2]) -> bool {
let r = self.rs.renderer.read();
@@ -214,6 +231,25 @@ impl GpuCanvas {
}
}
+ /// Set (or clear with `None`) the display LUT of document `doc`: `size`³ RGBA8 texels, red
+ /// fastest. RGB is the display colour for each lattice input; alpha 255 marks out-of-gamut
+ /// colours for the gamut warning.
+ pub fn set_display_lut(&self, doc: u64, size: u32, rgba: Option<&[u8]>) {
+ let (device, queue) = (&self.rs.device, &self.rs.queue);
+ let mut renderer = self.rs.renderer.write();
+ let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return };
+ match rgba {
+ None => {
+ res.luts.remove(&doc);
+ }
+ Some(bytes) => {
+ assert_eq!(bytes.len(), (size * size * size * 4) as usize, "set_display_lut: buffer size mismatch");
+ let bg = lut_bind_group(device, queue, &res.lut_bgl, size, bytes);
+ res.luts.insert(doc, bg);
+ }
+ }
+ }
+
/// Add the paint callback drawing `params` into `rect` (clipped by the painter's clip rect).
pub fn paint(painter: &egui::Painter, rect: egui::Rect, params: ViewParams) {
painter.add(egui_wgpu::Callback::new_paint_callback(rect, CanvasCallback { rect, params }));
@@ -333,12 +369,64 @@ struct Resources {
compositor: Option<photocraft_gpu::Compositor>,
encode_bgl: wgpu::BindGroupLayout,
encode_pipeline: wgpu::RenderPipeline,
+ lut_bgl: wgpu::BindGroupLayout,
+ /// Display LUTs per document (Proof Colors / Gamut Warning); `identity_lut` otherwise.
+ luts: HashMap<u64, wgpu::BindGroup>,
+ identity_lut: wgpu::BindGroup,
+ /// Transparency checkerboard and gamut warning colours (Preferences › Transparency & Gamut).
+ style: CanvasStyle,
+}
+
+/// Canvas colours from Preferences › Transparency & Gamut.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct CanvasStyle {
+ /// Checker square side in points (0 = no checkerboard: transparency shows white).
+ pub checker_square: f32,
+ pub checker_light: [f32; 3],
+ pub checker_dark: [f32; 3],
+ pub gamut_color: [f32; 3],
+ /// Gamut warning opacity 0..1.
+ pub gamut_opacity: f32,
+}
+
+impl Default for CanvasStyle {
+ fn default() -> Self {
+ Self { checker_square: 8.0, checker_light: [1.0; 3], checker_dark: [0.8; 3], gamut_color: [0.5; 3], gamut_opacity: 1.0 }
+ }
+}
+
+/// A `size`³ RGBA8 3D texture bound for the canvas shader.
+fn lut_bind_group(device: &wgpu::Device, queue: &wgpu::Queue, bgl: &wgpu::BindGroupLayout, size: u32, bytes: &[u8]) -> wgpu::BindGroup {
+ let extent = wgpu::Extent3d { width: size, height: size, depth_or_array_layers: size };
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("pc_display_lut"),
+ size: extent,
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D3,
+ format: FORMAT,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
+ bytes,
+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size * 4), rows_per_image: Some(size) },
+ extent,
+ );
+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+ device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_display_lut"), layout: bgl, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }] })
+}
+
+/// The 2³ identity LUT (unused unless a document has none and `display` is set).
+fn identity_lut_bytes() -> Vec<u8> {
+ (0..8).flat_map(|i| [if i & 1 != 0 { 255 } else { 0 }, if i & 2 != 0 { 255 } else { 0 }, if i & 4 != 0 { 255 } else { 0 }, 0]).collect()
}
struct ViewGpu {
buffer: wgpu::Buffer,
bind_group: wgpu::BindGroup,
- frame_data: [f32; 16],
+ frame_data: [f32; VIEW_FLOATS],
}
struct DocTextures {
@@ -394,12 +482,19 @@ fn pipeline(device: &wgpu::Device, label: &str, layout: &wgpu::PipelineLayout, m
}
impl Resources {
- fn new(device: &wgpu::Device, target: wgpu::TextureFormat) -> Self {
+ fn new(device: &wgpu::Device, queue: &wgpu::Queue, target: wgpu::TextureFormat) -> Self {
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_canvas"), source: wgpu::ShaderSource::Wgsl(CANVAS_WGSL.into()) });
let vis = wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT;
let view_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_canvas_view"), entries: &[uniform_entry(0, VIEW_UNIFORM_SIZE, vis), sampler_entry(1)] });
let tile_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_canvas_tile"), entries: &[texture_entry(0), uniform_entry(1, TILE_UNIFORM_SIZE, vis)] });
- let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_canvas"), bind_group_layouts: &[Some(&view_bgl), Some(&tile_bgl)], immediate_size: 0 });
+ let lut_entry = wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture { multisampled: false, sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D3 },
+ count: None,
+ };
+ let lut_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_display_lut"), entries: &[lut_entry] });
+ let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_canvas"), bind_group_layouts: &[Some(&view_bgl), Some(&tile_bgl), Some(&lut_bgl)], immediate_size: 0 });
let shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_canvas_shadow"), bind_group_layouts: &[Some(&view_bgl)], immediate_size: 0 });
// Premultiplied "over", with egui's alpha rule (keeps a transparent window's alpha sane).
let blend = wgpu::BlendState {
@@ -432,7 +527,12 @@ impl Resources {
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);
+ let identity_lut = lut_bind_group(device, queue, &lut_bgl, 2, &identity_lut_bytes());
Self {
+ lut_bgl,
+ luts: HashMap::new(),
+ identity_lut,
+ style: CanvasStyle::default(),
view_bgl,
tile_bgl,
shadow_pipeline,
@@ -574,16 +674,21 @@ impl CanvasCallback {
([ox, oy], scale)
}
- fn uniforms(&self, screen: [u32; 2], ppp: f32, out_linear: bool) -> [f32; 16] {
+ fn uniforms(&self, screen: [u32; 2], ppp: f32, out_linear: bool, style: &CanvasStyle) -> [f32; VIEW_FLOATS] {
let p = &self.params;
let (origin, scale) = self.placement(ppp);
let (mode, lod) = filter_mode(scale);
let grid = if p.pixel_grid && p.zoom >= 8.0 { 0.16 } else { 0.0 };
+ let square = if style.checker_square > 0.0 { (style.checker_square * ppp).round().max(1.0) } else { 0.0 };
+ let (l, d, g) = (style.checker_light, style.checker_dark, style.gamut_color);
[
screen[0] as f32, screen[1] as f32, scale, ppp,
origin[0], origin[1], p.doc_size[0] as f32, p.doc_size[1] as f32,
- mode, lod, grid, (8.0 * ppp).round().max(1.0),
- (self.rect.min.x * ppp).round(), (self.rect.min.y * ppp).round(), 0.0, if out_linear { 1.0 } else { 0.0 },
+ mode, lod, grid, square,
+ (self.rect.min.x * ppp).round(), (self.rect.min.y * ppp).round(), p.display as f32, if out_linear { 1.0 } else { 0.0 },
+ l[0], l[1], l[2], style.gamut_opacity,
+ d[0], d[1], d[2], 0.0,
+ g[0], g[1], g[2], 0.0,
]
}
}
@@ -591,7 +696,7 @@ impl CanvasCallback {
impl CallbackTrait for CanvasCallback {
fn prepare(&self, device: &wgpu::Device, queue: &wgpu::Queue, screen: &ScreenDescriptor, _encoder: &mut wgpu::CommandEncoder, resources: &mut CallbackResources) -> Vec<wgpu::CommandBuffer> {
let Some(res) = resources.get_mut::<Resources>() else { return Vec::new() };
- let data = self.uniforms(screen.size_in_pixels, screen.pixels_per_point, res.out_linear);
+ let data = self.uniforms(screen.size_in_pixels, screen.pixels_per_point, res.out_linear, &res.style);
let (bgl, sampler) = (&res.view_bgl, &res.sampler);
let v = res.views.entry(self.params.view_key).or_insert_with(|| {
let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("pc_canvas_view"), size: VIEW_UNIFORM_SIZE, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
@@ -600,7 +705,7 @@ impl CallbackTrait for CanvasCallback {
layout: bgl,
entries: &[wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) }],
});
- ViewGpu { buffer, bind_group, frame_data: [f32::NAN; 16] }
+ ViewGpu { buffer, bind_group, frame_data: [f32::NAN; VIEW_FLOATS] }
});
if v.frame_data != data {
queue.write_buffer(&v.buffer, 0, &f32_bytes(&data));
@@ -633,6 +738,7 @@ impl CallbackTrait for CanvasCallback {
let (cx0, cy0) = (clip.left_px as f32, clip.top_px as f32);
let (cx1, cy1) = (cx0 + clip.width_px as f32, cy0 + clip.height_px as f32);
pass.set_pipeline(&res.tile_pipeline);
+ pass.set_bind_group(2, res.luts.get(&self.params.doc).unwrap_or(&res.identity_lut), &[]);
for t in &doc.tiles {
let [tx, ty, tw, th] = t.rect.map(|v| v as f32);
let (x0, y0) = (origin[0] + tx * scale, origin[1] + ty * scale);
@@ -651,7 +757,10 @@ struct View {
a: vec4<f32>, // screen_w, screen_h, scale (device px per doc px), pixels_per_point
b: vec4<f32>, // doc origin x, y (device px), doc w, h (doc px)
c: vec4<f32>, // filter mode, lod, grid alpha, checker square (device px)
- d: vec4<f32>, // checker anchor x, y (device px), unused, output linear (sRGB target)
+ d: vec4<f32>, // checker anchor x, y (device px), display (0 none, 1 LUT, 2 LUT + gamut), output linear
+ e: vec4<f32>, // checker light rgb, gamut warning opacity
+ f: vec4<f32>, // checker dark rgb
+ g: vec4<f32>, // gamut warning rgb
};
struct Tile { r: vec4<f32> }; // x, y, w, h in doc px
@@ -659,6 +768,7 @@ struct Tile { r: vec4<f32> }; // x, y, w, h in doc px
@group(0) @binding(1) var samp: sampler;
@group(1) @binding(0) var tex: texture_2d<f32>;
@group(1) @binding(1) var<uniform> tile: Tile;
+@group(2) @binding(0) var lut: texture_3d<f32>;
struct VOut { @builtin(position) pos: vec4<f32> };
@@ -729,9 +839,12 @@ fn vs_tile(@builtin(vertex_index) vi: u32) -> VOut {
}
fn checker(p: vec2<f32>) -> vec3<f32> {
+ if (view.c.w <= 0.0) {
+ return vec3(1.0);
+ }
let c = floor((p - view.d.xy) / view.c.w);
let odd = fract((c.x + c.y) * 0.5) > 0.25;
- return select(vec3(1.0), vec3(0.8), odd);
+ return select(view.e.xyz, view.f.xyz, odd);
}
@fragment
@@ -755,6 +868,14 @@ fn fs_tile(in: VOut) -> @location(0) vec4<f32> {
let f = clamp((tt - i - 0.5) * scale + 0.5, vec2(0.0), vec2(1.0));
col = textureSampleLevel(tex, samp, (i + 0.5 + f) / size, 0.0);
}
+ if (view.d.z > 0.5 && col.a > 0.0) {
+ // Proof Colors / Gamut Warning: the document's display LUT (alpha flags out-of-gamut).
+ let n = f32(textureDimensions(lut).x);
+ let c = clamp(col.rgb / col.a, vec3(0.0), vec3(1.0));
+ let l = textureSampleLevel(lut, samp, (c * (n - 1.0) + 0.5) / n, 0.0);
+ let shown = select(l.rgb, mix(l.rgb, view.g.xyz, view.e.w), view.d.z > 1.5 && l.a > 0.5);
+ col = vec4(shown * col.a, col.a);
+ }
var rgb = col.rgb + checker(p) * (1.0 - col.a);
let grid = view.c.z;
if (grid > 0.0) {
diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rs
index 133fbbe7a..cca14f062 100644
--- a/crates/ui-egui/src/layer_style.rs
+++ b/crates/ui-egui/src/layer_style.rs
@@ -16,9 +16,14 @@ enum P {
Blend,
Choice(&'static [(&'static str, &'static str)]),
Check,
+ /// A pattern from the dialog's `patternList` field (`[[id, name], …]`).
+ Pattern,
}
/// Effect kinds in Photoshop's list order: (command kind, label, params).
+/// The Blending Options page id (not an effect).
+pub const BLENDING: &str = "blendingOptions";
+
pub const KINDS: &[(&str, &str)] = &[
("bevelEmboss", "Bevel & Emboss"),
("stroke", "Stroke"),
@@ -27,6 +32,7 @@ pub const KINDS: &[(&str, &str)] = &[
("satin", "Satin"),
("colorOverlay", "Color Overlay"),
("gradientOverlay", "Gradient Overlay"),
+ ("patternOverlay", "Pattern Overlay"),
("outerGlow", "Outer Glow"),
("dropShadow", "Drop Shadow"),
];
@@ -45,8 +51,10 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {
"stroke" => &[("size", "Size", P::Slider(1.0, 250.0, "px")), ("position", "Position", P::Choice(POS)), ("blend", "Blend Mode", P::Blend), ("opacity", "Opacity", P::Slider(0.0, 100.0, "%")), ("color", "Color", P::Color)],
"colorOverlay" => &[("blend", "Blend Mode", P::Blend), ("color", "Color", P::Color), ("opacity", "Opacity", P::Slider(0.0, 100.0, "%"))],
"gradientOverlay" => &[("blend", "Blend Mode", P::Blend), ("opacity", "Opacity", P::Slider(0.0, 100.0, "%")), ("from", "From", P::Color), ("to", "To", P::Color), ("reverse", "Reverse", P::Check), ("style", "Style", P::Choice(GSTYLE)), ("angle", "Angle", P::Slider(-180.0, 180.0, "°")), ("scale", "Scale", P::Slider(10.0, 150.0, "%"))],
+ "patternOverlay" => &[("blend", "Blend Mode", P::Blend), ("opacity", "Opacity", P::Slider(0.0, 100.0, "%")), ("pattern", "Pattern", P::Pattern), ("angle", "Angle", P::Slider(-180.0, 180.0, "°")), ("scale", "Scale", P::Slider(1.0, 1000.0, "%")), ("link", "Link with Layer", P::Check)],
"bevelEmboss" => &[("style", "Style", P::Choice(BSTYLE)), ("depth", "Depth", P::Slider(1.0, 1000.0, "%")), ("direction", "Direction", P::Choice(DIR)), ("size", "Size", P::Slider(0.0, 250.0, "px")), ("soften", "Soften", P::Slider(0.0, 16.0, "px")), ("angle", "Angle", P::Slider(-180.0, 180.0, "°")), ("altitude", "Altitude", P::Slider(0.0, 90.0, "°"))],
"satin" => &[("blend", "Blend Mode", P::Blend), ("color", "Color", P::Color), ("opacity", "Opacity", P::Slider(0.0, 100.0, "%")), ("angle", "Angle", P::Slider(-180.0, 180.0, "°")), ("distance", "Distance", P::Slider(0.0, 250.0, "px")), ("size", "Size", P::Slider(0.0, 250.0, "px")), ("invert", "Invert", P::Check)],
+ BLENDING => &[("blend", "Blend Mode", P::Blend), ("opacity", "Opacity", P::Slider(0.0, 100.0, "%")), ("fillOpacity", "Fill Opacity", P::Slider(0.0, 100.0, "%"))],
_ => &[],
}
}
@@ -60,6 +68,7 @@ fn defaults(kind: &str) -> Value {
"stroke" => json!({"size": 3, "position": "outside", "blend": "Normal", "opacity": 100, "color": "#000000"}),
"colorOverlay" => json!({"blend": "Normal", "color": "#ff0000", "opacity": 100}),
"gradientOverlay" => json!({"blend": "Normal", "opacity": 100, "from": "#000000", "to": "#ffffff", "reverse": false, "style": "linear", "angle": 90, "scale": 100}),
+ "patternOverlay" => json!({"blend": "Normal", "opacity": 100, "pattern": "", "angle": 0, "scale": 100, "link": true}),
"bevelEmboss" => json!({"style": "inner", "depth": 100, "direction": "up", "size": 5, "soften": 0, "angle": 120, "altitude": 30}),
"satin" => json!({"blend": "Multiply", "color": "#000000", "opacity": 50, "angle": 19, "distance": 11, "size": 14, "invert": true}),
_ => json!({}),
@@ -99,7 +108,7 @@ fn values_of(e: &Effect) -> Value {
set(&mut v, "color", json!(hex(&s.color)));
set(&mut v, "angle", json!(s.angle));
set(&mut v, "distance", json!(s.distance));
- set(&mut v, if matches!(e, Effect::DropShadow(_)) { "spread" } else { "choke" }, json!(s.spread));
+ set(&mut v, if matches!(e, Effect::DropShadow(_)) { "spread" } else { "choke" }, json!((s.spread * 100.0).round()));
set(&mut v, "size", json!(s.size));
}
Effect::OuterGlow(g) | Effect::InnerGlow(g) => {
@@ -108,8 +117,9 @@ fn values_of(e: &Effect) -> Value {
if let FxPaint::Color(c) = &g.paint {
set(&mut v, "color", json!(hex(c)));
}
- set(&mut v, if matches!(e, Effect::OuterGlow(_)) { "spread" } else { "choke" }, json!(g.spread));
+ set(&mut v, if matches!(e, Effect::OuterGlow(_)) { "spread" } else { "choke" }, json!((g.spread * 100.0).round()));
set(&mut v, "size", json!(g.size));
+ set(&mut v, "range", json!((g.range * 100.0).round()));
}
Effect::Stroke(s) => {
set(&mut v, "blend", json!(s.common.blend.label()));
@@ -146,7 +156,16 @@ fn values_of(e: &Effect) -> Value {
set(&mut v, "altitude", json!(b.altitude));
set(&mut v, "direction", json!(if b.up { "up" } else { "down" }));
}
- Effect::PatternOverlay { .. } => {}
+ Effect::PatternOverlay { common, name, id, scale, angle, link, phase } => {
+ set(&mut v, "blend", json!(common.blend.label()));
+ set(&mut v, "opacity", json!((common.opacity * 100.0).round()));
+ set(&mut v, "pattern", json!(if id.is_empty() { name } else { id }));
+ set(&mut v, "scale", json!((scale * 100.0).round()));
+ set(&mut v, "angle", json!(angle));
+ set(&mut v, "link", json!(link));
+ set(&mut v, "phaseX", json!(phase.0));
+ set(&mut v, "phaseY", json!(phase.1));
+ }
}
v
}
@@ -155,6 +174,7 @@ fn values_of(e: &Effect) -> Value {
pub fn initial_fields(layer: &Layer, select: Option<&str>) -> Map<String, Value> {
let mut f = Map::new();
f.insert("layer".into(), json!(layer.id.0));
+ f.insert(format!("p:{BLENDING}"), json!({"blend": layer.blend.label(), "opacity": (layer.opacity * 100.0).round(), "fillOpacity": (layer.fill_opacity * 100.0).round()}));
let mut first = None;
for &(kind, _) in KINDS {
let existing = layer.effects.items.iter().find(|e| kind_of(e) == kind);
@@ -175,12 +195,32 @@ pub fn initial_fields(layer: &Layer, select: Option<&str>) -> Map<String, Value>
pub fn open(app: &mut PhotocraftApp, select: Option<&str>) -> Option<u64> {
let st = app.session.active()?;
let layer = st.doc.layer(st.active_layer?)?.clone();
- Some(app.ui.open_dialog(crate::state::DialogKind::LayerStyle, initial_fields(&layer, select)))
+ let mut f = initial_fields(&layer, select);
+ f.insert("patternList".into(), pattern_list(app));
+ Some(app.ui.open_dialog(crate::state::DialogKind::LayerStyle, f))
+}
+
+/// `[[id, name], …]` of the patterns a style can use (document's, then the library's).
+pub fn pattern_list(app: &PhotocraftApp) -> Value {
+ let mut out: Vec<Value> = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ let doc_pats = app.session.active().map(|d| d.doc.patterns.clone()).unwrap_or_default();
+ for p in doc_pats.iter().chain(app.session.patterns.items.iter()) {
+ if seen.insert(p.id.clone()) {
+ out.push(json!([p.id, p.display_name()]));
+ }
+ }
+ Value::Array(out)
}
/// Apply the dialog: replace the layer's effects with the enabled ones.
pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
let layer = f.get("layer").cloned().unwrap_or(Value::Null);
+ if let Some(Value::Object(bo)) = f.get(&format!("p:{BLENDING}")) {
+ let mut p = Value::Object(bo.clone());
+ p["layer"] = layer.clone();
+ app.run("layer.layerStyle.blendingOptions", p)?;
+ }
let _ = app.run("layer.layerStyle.clear", json!({"layer": layer}));
for &(kind, _) in KINDS {
if f.get(&format!("on:{kind}")).and_then(Value::as_bool) == Some(true) {
@@ -201,7 +241,11 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
ui.vertical(|ui| {
ui.set_width(190.0);
ui.label(RichText::new("Styles").color(t.text_faint));
- ui.label(RichText::new("Blending Options").color(t.text_dim));
+ // Blending Options page (layer blend mode, opacity and fill opacity).
+ let bo = ui.add(egui::Label::new(RichText::new("Blending Options").color(if selected == BLENDING { t.text } else { t.text_dim })).sense(Sense::click()));
+ if bo.clicked() {
+ f.insert("selected".into(), json!(BLENDING));
+ }
ui.add_space(4.0);
for &(kind, label) in KINDS {
let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 26.0), Sense::click());
@@ -237,7 +281,7 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
// Right: parameters of the selected effect.
ui.vertical(|ui| {
ui.set_width(330.0);
- let label = KINDS.iter().find(|k| k.0 == selected).map(|k| k.1).unwrap_or("");
+ let label = KINDS.iter().find(|k| k.0 == selected).map(|k| k.1).unwrap_or(if selected == BLENDING { "Blending Options" } else { "" });
ui.label(RichText::new(label).font(crate::theme::semibold(14.0)).color(t.text));
ui.add_space(6.0);
let pkey = format!("p:{selected}");
@@ -280,6 +324,21 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
}
});
}
+ P::Pattern => {
+ let list: Vec<(String, String)> = f
+ .get("patternList")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_str()?.to_string()))).collect())
+ .unwrap_or_default();
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(label).color(t.text_dim));
+ let mut cur = p.get(key).and_then(Value::as_str).filter(|c| !c.is_empty()).map(str::to_string).or_else(|| list.first().map(|l| l.0.clone())).unwrap_or_default();
+ let opts: Vec<(String, &str)> = list.iter().map(|(id, n)| (id.clone(), n.as_str())).collect();
+ if widgets::dropdown(ui, &format!("fx-{selected}-{key}"), &mut cur, &opts, 180.0) || p.get(key).and_then(Value::as_str).is_none_or(str::is_empty) {
+ p[key] = json!(cur);
+ }
+ });
+ }
P::Check => {
let mut b = p.get(key).and_then(Value::as_bool).unwrap_or(false);
if widgets::checkbox(ui, &mut b, label).changed() {
@@ -334,4 +393,19 @@ mod tests {
assert_eq!(f["on:stroke"], true);
assert_eq!(f["on:dropShadow"], false);
}
+
+ #[test]
+ fn percent_fields_round_trip_through_the_engine() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("layer.layerStyle.outerGlow", json!({"spread": 6, "range": 40})).unwrap();
+ s.execute("layer.layerStyle.dropShadow", json!({"spread": 12, "add": true})).unwrap();
+ let st = s.active().unwrap();
+ let l = st.doc.layer(st.active_layer.unwrap()).unwrap();
+ let f = initial_fields(l, None);
+ assert_eq!(f["p:outerGlow"]["spread"], json!(6.0));
+ assert_eq!(f["p:outerGlow"]["range"], json!(40.0));
+ assert_eq!(f["p:dropShadow"]["spread"], json!(12.0));
+ }
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index d3b3ca161..1d6c84dad 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -7,7 +7,11 @@
#![forbid(unsafe_code)]
pub mod actions;
+pub mod adjust_ui;
+pub mod brush_panel;
pub mod canvas;
+pub mod channel_view;
+pub mod channels_panel;
pub mod control;
pub mod dialogs;
pub mod export_dialog;
@@ -22,8 +26,12 @@ pub mod palette;
pub mod proxy;
pub mod retouch_ui;
pub mod rulers;
+pub mod smart_ui;
pub mod panels;
+pub mod parity;
pub mod shortcuts;
+pub mod prefs_ui;
+pub mod snap_ui;
mod sizing;
pub mod state;
pub mod theme;
@@ -31,6 +39,7 @@ pub mod tone;
pub mod transform_tool;
pub mod type_tool;
pub mod vector_ui;
+pub mod view_cmds;
pub mod widgets;
mod icon_data;
@@ -63,6 +72,18 @@ pub type ClipboardSetFn = Box<dyn FnMut(u32, u32, &[u8]) -> Result<(), String>>;
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>)>>>;
+/// Read the saved preferences text (`None` when there is none yet).
+pub type LoadTextFn = Box<dyn FnMut() -> Option<String>>;
+/// Persist the preferences text.
+pub type SaveTextFn = Box<dyn FnMut(&str) -> Result<(), String>>;
+/// Autosave a document snapshot for crash recovery: (snapshot, revision, original path).
+pub type AutosaveFn = Box<dyn FnMut(&std::sync::Arc<Document>, u64, Option<&str>) -> Result<(), String>>;
+/// Drop the recovery data of a document (by `DocId` value) once it is saved or closed.
+pub type DiscardAutosaveFn = Box<dyn FnMut(u64)>;
+/// Load recoverable documents left by a previous session: (original path, document).
+pub type RecoverFn = Box<dyn FnMut() -> Vec<(Option<String>, Document)>>;
+/// Append text to a file (History Log).
+pub type AppendTextFn = Box<dyn FnMut(&str, &str) -> Result<(), String>>;
/// Platform services injected by the app binary (file dialogs, codecs), keeping this crate free of
/// I/O dependencies.
@@ -85,6 +106,16 @@ pub struct Services {
/// 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>,
+ /// Preferences persistence: the platform config directory on native, browser storage on
+ /// the web (see `prefs_ui`).
+ pub load_prefs: Option<LoadTextFn>,
+ pub save_prefs: Option<SaveTextFn>,
+ /// Crash-recovery autosave (Preferences › File Handling) and recovery at launch.
+ pub autosave: Option<AutosaveFn>,
+ pub discard_autosave: Option<DiscardAutosaveFn>,
+ pub recover: Option<RecoverFn>,
+ /// History Log text file output.
+ pub append_text: Option<AppendTextFn>,
}
pub struct PhotocraftApp {
@@ -143,19 +174,23 @@ pub struct PhotocraftApp {
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>)>,
+ /// Channels panel overlays / channel views drawn over the canvas, per document id.
+ pub(crate) channel_views: HashMap<u64, channel_view::Cache>,
/// 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>,
/// Frame and canvas-upload timings (exposed via `ui.inspect`).
pub perf: gpu_canvas::Perf,
+ /// Preferences, autosave and snapping runtime state (see `prefs_ui`, `snap_ui`).
+ pub(crate) prefs_rt: prefs_ui::Runtime,
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
live_tokens: theme::live::LiveTokens,
}
impl PhotocraftApp {
pub fn new(session: Session, services: Services) -> Self {
- Self {
+ let mut app = Self {
session,
ui: UiState::default(),
services,
@@ -182,6 +217,7 @@ impl PhotocraftApp {
filter_preview: None,
synthetic: Vec::new(),
channel_thumbs: None,
+ channel_views: HashMap::new(),
type_layout: None,
guide_drag: None,
hover_doc: None,
@@ -192,15 +228,22 @@ impl PhotocraftApp {
doc_hist: None,
gpu: None,
perf: Default::default(),
+ prefs_rt: Default::default(),
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
live_tokens: theme::live::LiveTokens::from_env(),
- }
+ };
+ // Saved preferences (and recovered documents) are in place before the first frame.
+ prefs_ui::load(&mut app);
+ app
}
/// Draw the document canvas on the GPU (custom WGSL shader) instead of via egui textures.
/// Call from the app creator with `cc.wgpu_render_state`; without it the CPU path is used.
pub fn set_wgpu(&mut self, rs: eframe::egui_wgpu::RenderState) {
- self.gpu = Some(gpu_canvas::GpuCanvas::new(&rs));
+ // Preferences › Performance › cache tile size (PHOTOCRAFT_GPU_TILE still overrides).
+ let tile = self.session.prefs().performance.cache_tile_size;
+ self.gpu = Some(gpu_canvas::GpuCanvas::with_tile(&rs, Some(tile)));
+ self.prefs_rt.gpu_style = None;
}
/// Attach a control channel (requests arrive from a transport thread: TCP, stdin, tests).
@@ -247,9 +290,14 @@ impl PhotocraftApp {
pub fn open_bytes(&mut self, name: &str, bytes: &[u8]) -> Result<(), String> {
let import = self.services.import.as_ref().ok_or("no importer configured")?;
let doc = import(name, bytes)?;
- self.session.add_document(doc, Some(name.to_string()));
+ // Edit › Color Settings policies apply on open; mismatches can ask what to do.
+ let (_, color) = self.session.open_document(doc, Some(name.to_string()));
self.sync_views();
self.ui.status = format!("Opened {name}");
+ let ask = color.get("ask").and_then(Value::as_bool) == Some(true);
+ if ask && (color.get("mismatch").and_then(Value::as_bool) == Some(true) || color.get("missing").is_some()) {
+ prefs_ui::open_mismatch(self, &color);
+ }
Ok(())
}
@@ -263,6 +311,11 @@ impl PhotocraftApp {
}
pub fn save_as(&mut self, path: Option<String>) -> Result<String, String> {
+ // Edit Contents documents save back into their smart object.
+ if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") {
+ self.run("layer.smartObjects.saveContents", serde_json::json!({}))?;
+ return Ok("smart object".into());
+ }
let st = self.session.active().ok_or("no document")?;
let suggested = st.path.clone().unwrap_or_else(|| format!("{}.psd", st.doc.name));
let path = match path {
@@ -376,6 +429,7 @@ impl eframe::App for PhotocraftApp {
}
self.collect_screenshots(ctx);
self.issue_screenshots(ctx);
+ prefs_ui::tick(self, 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 {
@@ -416,22 +470,33 @@ impl eframe::App for PhotocraftApp {
return;
}
let t0 = gpu_canvas::now_ms();
- panels::title_bar(self, ui);
- if self.ui.panels.options_bar {
+ // View › Screen Mode › Full Screen Mode: only the image, on black (F or Esc returns).
+ let chrome = !self.ui.view.hides_chrome();
+ if !chrome && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
+ let _ = menus::invoke(self, &ctx, "view.screenMode.standard", serde_json::json!({}));
+ }
+ if chrome {
+ panels::title_bar(self, ui);
+ }
+ if chrome && self.ui.panels.options_bar {
panels::options_bar(self, ui);
}
- if self.ui.panels.status_bar {
+ if chrome && self.ui.panels.status_bar {
panels::status_bar(self, ui);
}
- if self.ui.panels.toolbar {
+ if chrome && self.ui.panels.toolbar {
panels::toolbar(self, ui);
}
- panels::right_dock(self, ui);
+ if chrome {
+ panels::right_dock(self, ui);
+ }
let t = theme::Tokens::get(&ctx);
- egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.canvas)).show(ui, |ui| {
+ let backdrop = if chrome { prefs_ui::pasteboard_color(self).unwrap_or(t.canvas) } else { egui::Color32::BLACK };
+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(backdrop)).show(ui, |ui| {
canvas::document_area(self, ui);
});
panels::properties_window(self, &ctx);
+ brush_panel::window(self, &ctx);
palette::show(self, &ctx);
dialogs::show(self, &ctx);
canvas::extra_windows(self, &ctx);
@@ -595,7 +660,8 @@ impl PhotocraftApp {
}
impl PhotocraftApp {
- /// Composite + per-channel grayscale thumbnails of the active document (cached per revision).
+ /// Channels panel thumbnails of the active document (cached per revision): the composite,
+ /// each colour channel (when there is more than one), each alpha channel, then the Quick Mask.
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());
@@ -614,12 +680,38 @@ impl PhotocraftApp {
}
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"),
- ];
+ let fmt = doc.pixel_format();
+ let colors = fmt.mode.color_channels();
+ let mut texs = vec![make(&|p| egui::Color32::from_rgb(p[0], p[1], p[2]), "composite")];
+ if colors > 1 {
+ for k in 0..colors {
+ let cmyk = fmt.mode == photocraft_doc::ColorMode::Cmyk;
+ texs.push(make(
+ &|p| {
+ let rgba = [p[0], p[1], p[2], 255].map(|v| f32::from(v) / 255.0);
+ let x = photocraft_raster::from_rgba(&fmt, rgba)[k];
+ let g = if cmyk { 1.0 - x } else { x };
+ egui::Color32::from_gray((g.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)
+ },
+ &format!("c{k}"),
+ ));
+ }
+ }
+ // Alpha channels and the Quick Mask, sampled at thumbnail resolution.
+ let (dw, dh) = (doc.size.width.max(1) as f32, doc.size.height.max(1) as f32);
+ for (i, ch) in doc.channels.iter().chain(doc.quick_mask.as_ref()).enumerate() {
+ 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 sx = ((x as f32 + 0.5) * dw / w as f32) as i32;
+ let sy = ((y as f32 + 0.5) * dh / h as f32) as i32;
+ let v = ch.surface.sample_channel(sx, sy, 0);
+ px[(y + oy) * side + x + ox] = egui::Color32::from_gray((v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
+ }
+ }
+ texs.push(ctx.load_texture(format!("chan-a{i}"), egui::ColorImage::new([side, side], px), egui::TextureOptions::LINEAR));
+ }
self.channel_thumbs = Some((id, rev, texs));
}
self.channel_thumbs.as_ref().map(|(_, _, t)| t.iter().map(|t| t.id()).collect()).unwrap_or_default()
diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs
index 218eec3a0..9fe73cd80 100644
--- a/crates/ui-egui/src/menu_catalog.rs
+++ b/crates/ui-egui/src/menu_catalog.rs
@@ -185,7 +185,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["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"], "Black & White…", Some("Cmd+Alt+Shift+B"), "image.adjustments.blackWhite"),
(&["Image", "Adjustments"], "Photo Filter…", None, "image.adjustments.photoFilter"),
(&["Image", "Adjustments"], "Channel Mixer…", None, "image.adjustments.channelMixer"),
(&["Image", "Adjustments"], "Color Lookup…", None, "image.adjustments.colorLookup"),
@@ -210,13 +210,13 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["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"], "180°", None, "image.imageRotation.180"),
+ (&["Image", "Image Rotation"], "90° Clockwise", None, "image.imageRotation.90cw"),
+ (&["Image", "Image Rotation"], "90° Counter Clockwise", None, "image.imageRotation.90ccw"),
(&["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", "Image Rotation"], "Flip Canvas Horizontal", None, "image.imageRotation.flipCanvasHorizontal"),
+ (&["Image", "Image Rotation"], "Flip Canvas Vertical", None, "image.imageRotation.flipCanvasVertical"),
(&["Image"], "Crop", None, "image.crop"),
(&["Image"], "Trim…", None, "image.trim"),
(&["Image"], "Reveal All", None, "image.revealAll"),
@@ -252,8 +252,8 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["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"], "Duplicate Layer…", None, "layer.duplicate"),
+ (&["Layer", "Delete"], "Layer", None, "layer.delete"),
(&["Layer", "Delete"], "Hidden Layers", None, "layer.delete.hiddenLayers"),
(&["Layer"], "---", None, "---"),
(&["Layer"], "Quick Export as PNG", Some("Cmd+Shift+'"), "layer.quickExportAsPng"),
@@ -261,7 +261,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["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"], "Bevel & Emboss…", None, "layer.layerStyle.bevelEmboss"),
(&["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"),
@@ -298,7 +298,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["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"], "Black & White…", None, "layer.newAdjustmentLayer.blackWhite"),
(&["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"),
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 205f9c7e7..c95ce95c8 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -15,11 +15,21 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
("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")),
+ ("file.export.quickExportAsPng", "Quick Export as PNG", &["File", "Export"], None),
+ ("edit.transform.scale", "Scale", &["Edit", "Transform"], None),
+ ("edit.transform.rotate", "Rotate", &["Edit", "Transform"], None),
+ ("edit.transform.skew", "Skew", &["Edit", "Transform"], None),
+ ("edit.transform.distort", "Distort", &["Edit", "Transform"], None),
+ ("edit.transform.perspective", "Perspective", &["Edit", "Transform"], None),
+ ("select.selectAndMask", "Select and Mask…", &["Select"], Some("Cmd+Alt+R")),
("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.extras", "Extras", &["View"], Some("Cmd+H")),
+ ("view.show.targetPath", "Target Path", &["View", "Show"], Some("Cmd+Shift+H")),
+ ("view.screenMode.cycle", "Cycle Screen Mode", &[], Some("F")),
("view.zoomIn", "Zoom In", &["View"], Some("Cmd+=")),
("view.zoomOut", "Zoom Out", &["View"], Some("Cmd+-")),
("view.fitOnScreen", "Fit on Screen", &["View"], Some("Cmd+0")),
@@ -29,6 +39,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
("window.toggle.history", "History", &["Window"], None),
("window.toggle.properties", "Properties", &["Window"], None),
("window.toggle.color", "Color", &["Window"], Some("F6")),
+ ("window.toggle.brushSettings", "Brush Settings", &["Window"], Some("F5")),
("window.toggle.navigator", "Navigator", &["Window"], None),
("window.toggle.toolbar", "Tools", &["Window"], None),
("window.toggle.options", "Options", &["Window"], None),
@@ -41,9 +52,92 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
("help.about", "About Photocraft", &["Help"], None),
];
+/// Photoshop's Window › <panel> ids for the panels the shell already has, as `window.toggle.*`.
+fn panel_alias(id: &str) -> Option<&'static str> {
+ Some(match id.strip_prefix("window.panel.")? {
+ "layers" => "window.toggle.layers",
+ "history" => "window.toggle.history",
+ "properties" | "adjustments" => "window.toggle.properties",
+ "color" | "swatches" => "window.toggle.color",
+ "navigator" | "info" | "histogram" => "window.toggle.navigator",
+ "tools" => "window.toggle.toolbar",
+ "options" => "window.toggle.options",
+ "brushSettings" | "brushes" => "window.toggle.brushSettings",
+ _ => return None,
+ })
+}
+
+/// View › Proof Setup presets we can simulate, as `view.proofSetup` profiles.
+fn proof_preset(id: &str) -> Option<&'static str> {
+ Some(match id.strip_prefix("view.proofSetup.")? {
+ "workingCmyk" => "working-cmyk",
+ "internetStandardRgb" | "monitorRgb" => "srgb",
+ _ => return None,
+ })
+}
+
+/// Window › Workspace presets by id.
+fn workspace_name(id: &str) -> Option<&'static str> {
+ Some(match id.strip_prefix("window.workspace.")? {
+ "essentials" | "resetWorkspace" => "",
+ "photography" => "Photography",
+ "painting" => "Painting",
+ "graphicAndWeb" => "Graphic and Web",
+ "pixelArt" => "Pixel Art",
+ "motion" => "Motion",
+ _ => return None,
+ })
+}
+
/// Run a command id from any source (menu, shortcut, palette, automation).
pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
+ if id == "view.proofSetup.custom" {
+ return Ok(json!({"dialog": crate::filter_dialog::open(app, "view.proofSetup")}));
+ }
+ if id == "window.panel.brushes" {
+ // Window › Brushes opens the Brush Settings window on its presets tab.
+ app.ui.panels.brush_settings = true;
+ app.ui.brush_tab = 1;
+ return Ok(Value::Null);
+ }
+ if id == "window.panel.brushSettings" {
+ app.ui.brush_tab = 0;
+ }
+ // View/Window/Type shell items, and dialogs/pickers in front of File commands.
+ // Edit › Preferences, Keyboard Shortcuts, Color Settings and other Edit dialogs.
+ if let Some(r) = crate::prefs_ui::invoke(app, ctx, id, &params) {
+ return r;
+ }
+ if let Some(r) = crate::view_cmds::invoke(app, ctx, id, &params) {
+ return r;
+ }
+ if let Some(profile) = proof_preset(id) {
+ // View › Proof Setup presets: set the proof profile and turn Proof Colors on.
+ app.run("view.proofSetup", json!({"profile": profile}))?;
+ return app.run("view.proofColors", json!({"on": true}));
+ }
+ if let Some(alias) = panel_alias(id) {
+ return invoke(app, ctx, alias, params);
+ }
+ if let Some(ws) = workspace_name(id) {
+ // Reset re-applies the current workspace; Essentials is the default layout.
+ match (ws, id) {
+ (_, "window.workspace.resetWorkspace") => {}
+ ("", _) => app.ui.workspace = "Essentials".into(),
+ (name, _) => app.ui.workspace = name.into(),
+ }
+ apply_workspace(app);
+ return Ok(json!({"workspace": app.ui.workspace}));
+ }
match id {
+ // Layer › Rename Layer from a menu starts in-place renaming in the Layers panel.
+ "layer.renameLayer" if params.get("name").is_none() => {
+ let st = app.session.active().ok_or("no document")?;
+ let id = params.get("layer").and_then(Value::as_u64).or(st.active_layer.map(|l| l.0)).ok_or("no active layer")?;
+ let name = st.doc.layer(photocraft_doc::LayerId(id)).map(|l| l.name.clone()).ok_or("no such layer")?;
+ ctx.data_mut(|d| d.insert_temp(egui::Id::new(("rename", id)), name));
+ Ok(Value::Null)
+ }
"file.new" if params.as_object().is_none_or(|o| o.is_empty()) => {
let d = app.ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields());
Ok(json!({"dialog": d}))
@@ -96,6 +190,21 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
"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),
+ // Layer › Export As… / Quick Export as PNG: the export pipeline on just the active layer.
+ l if matches!(l, "layer.exportAs" | "layer.quickExportAsPng") && params.as_object().is_none_or(|o| o.is_empty()) => {
+ let layer = app.session.active().and_then(|d| d.active_layer).ok_or("no active layer")?;
+ if l == "layer.exportAs" { Ok(json!({"dialog": crate::export_dialog::open_layer(app, layer)?})) } else { crate::export_dialog::quick_export_layer_png(app, layer) }
+ }
+ "layer.layerStyle.blendingOptions" if params.as_object().is_none_or(|o| o.is_empty()) => {
+ crate::layer_style::open(app, Some(crate::layer_style::BLENDING)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string())
+ }
+ // Layer Content Options…: the adjustment / fill controls live in Properties.
+ "layer.layerContentOptions" => {
+ let r = app.run(id, params)?;
+ app.ui.panels.properties = true;
+ app.ui.dock_tabs.properties = 0;
+ Ok(r)
+ }
// 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()) => {
@@ -129,6 +238,17 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
"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}))
}
+ // Edit › Transform › Warp from the menu: interactive Warp mode (with params: the engine).
+ "edit.transform.warp" | "layer.smartObjects.warp" if params.as_object().is_none_or(|o| o.is_empty()) => {
+ crate::transform_tool::begin_warp(app, ctx).map(|_| json!({"transform": app.ui.transform}))
+ }
+ // Split warps edit the mesh of an active Warp session.
+ "edit.transform.splitWarpCrosswise" | "edit.transform.splitWarpHorizontally" | "edit.transform.splitWarpVertically" | "edit.transform.removeWarpSplit"
+ if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()) && params.get("warp").is_none() =>
+ {
+ let at = params.get("at").and_then(Value::as_array).and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?]));
+ crate::transform_tool::split(app, id, at).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")?}))
}
@@ -152,11 +272,19 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
"navigator" => &mut p.navigator,
"toolbar" => &mut p.toolbar,
"options" => &mut p.options_bar,
+ "brushSettings" => &mut p.brush_settings,
_ => return Err(format!("unknown panel in {t}")),
};
*slot = !*slot;
Ok(Value::Null)
}
+ // Layer › Layer Style › <effect>… opens the Layer Style dialog on that effect.
+ ls if params.as_object().is_none_or(|o| o.is_empty())
+ && ls.strip_prefix("layer.layerStyle.").is_some_and(|k| crate::layer_style::KINDS.iter().any(|(kind, _)| *kind == k)) =>
+ {
+ let kind = &ls["layer.layerStyle.".len()..];
+ crate::layer_style::open(app, Some(kind)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string())
+ }
_ => app.run(id, params),
}
}
@@ -178,11 +306,18 @@ fn open_path(_app: &mut PhotocraftApp, path: &str) -> Result<Value, String> {
}
pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
+ if let Some(e) = crate::view_cmds::is_enabled(app, id) {
+ return e;
+ }
match id {
"file.open" | "help.about" | "edit.search" => true,
i if i.starts_with("window.theme.") => true,
"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 panel_alias(i).is_some() || workspace_name(i).is_some() => true,
+ i if proof_preset(i).is_some() => app.session.active().is_some(),
+ // "Custom…" is the full Proof Setup dialog.
+ "view.proofSetup.custom" => 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(),
@@ -196,6 +331,21 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
/// 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(c) = crate::view_cmds::checked(app, id) {
+ return Some(c);
+ }
+ if let Some(alias) = panel_alias(id) {
+ return checked(app, alias);
+ }
+ if id == "view.proofColors" || id == "view.gamutWarning" {
+ let d = app.session.active()?;
+ let pv = app.session.color.proof(d.doc.id);
+ return Some(if id == "view.proofColors" { pv.enabled } else { pv.gamut_warning });
+ }
+ if id.starts_with("window.workspace.") && id != "window.workspace.resetWorkspace" {
+ let want = workspace_name(id)?;
+ return Some(app.ui.workspace == if want.is_empty() { "Essentials" } else { want });
+ }
if let Some(m) = id.strip_prefix("image.mode.") {
let d = &app.session.active()?.doc;
return match m {
@@ -227,6 +377,7 @@ fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
"window.toggle.navigator" => p.navigator,
"window.toggle.toolbar" => p.toolbar,
"window.toggle.options" => p.options_bar,
+ "window.toggle.brushSettings" => p.brush_settings,
_ => return None,
})
}
@@ -240,11 +391,20 @@ pub struct MenuItem {
pub shortcut: Option<String>,
pub enabled: bool,
pub checked: Option<bool>,
+ /// Edit › Menus colour (red, orange, …).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub color: Option<String>,
+}
+
+/// Is `id` implemented by the engine or the shell (a live menu item)? Shared by the menus and
+/// the parity report ([`crate::parity`]).
+pub fn is_live(id: &str) -> bool {
+ photocraft_engine::commands::find(id).is_some() || UI_COMMANDS.iter().any(|c| c.0 == id) || panel_alias(id).is_some() || workspace_name(id).is_some() || proof_preset(id).is_some() || id == "view.proofSetup.custom" || crate::view_cmds::handles(id)
}
pub fn menu_items(app: &PhotocraftApp) -> Vec<MenuItem> {
// 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 known = is_live;
let mut items: Vec<MenuItem> = crate::menu_catalog::CATALOG
.iter()
.map(|&(path, label, sc, id)| MenuItem {
@@ -254,15 +414,16 @@ pub fn menu_items(app: &PhotocraftApp) -> Vec<MenuItem> {
shortcut: sc.map(Into::into),
enabled: known(id) && is_enabled(app, id),
checked: checked(app, id),
+ color: None,
})
.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 {
- 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) });
+ 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), color: None });
}
for c in photocraft_engine::command_specs().iter().filter(|c| !c.menu.is_empty()) {
- 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 });
+ 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, color: None });
}
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('…')));
@@ -273,9 +434,40 @@ pub fn menu_items(app: &PhotocraftApp) -> Vec<MenuItem> {
items.insert(at, e);
}
}
+ // Edit › Keyboard Shortcuts overrides, Edit › Menus hidden items and colours.
+ let prefs = app.session.prefs();
+ if !prefs.shortcuts.is_empty() {
+ for it in &mut items {
+ if prefs.shortcuts.contains_key(&it.id) {
+ it.shortcut = prefs.shortcut(&it.id, None).map(str::to_string);
+ }
+ }
+ }
+ if !prefs.menus.hidden.is_empty() {
+ items.retain(|i| !prefs.menus.hidden.contains(&i.id));
+ }
+ if prefs.interface.show_menu_colors {
+ for it in &mut items {
+ it.color = prefs.menus.colors.get(&it.id).cloned();
+ }
+ }
items
}
+/// Background tint of an Edit › Menus colour name.
+fn menu_tint(name: &str) -> Option<egui::Color32> {
+ Some(match name {
+ "red" => egui::Color32::from_rgb(190, 60, 60),
+ "orange" => egui::Color32::from_rgb(200, 120, 40),
+ "yellow" => egui::Color32::from_rgb(190, 170, 40),
+ "green" => egui::Color32::from_rgb(60, 150, 70),
+ "blue" => egui::Color32::from_rgb(50, 110, 200),
+ "violet" => egui::Color32::from_rgb(130, 80, 190),
+ "gray" => egui::Color32::from_rgb(120, 120, 120),
+ _ => return None,
+ })
+}
+
pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let items = menu_items(app);
let mut clicked: Option<String> = None;
@@ -336,6 +528,9 @@ fn render_level(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &
text = format!("{} {}", if c { "✔" } else { " " }, text);
}
let mut b = egui::Button::new(text);
+ if let Some(tint) = it.color.as_deref().and_then(menu_tint) {
+ b = b.fill(tint.gamma_multiply(0.55));
+ }
if let Some(sc) = &it.shortcut {
b = b.shortcut_text(crate::shortcuts::pretty(sc));
}
@@ -375,3 +570,53 @@ pub fn apply_workspace(app: &mut PhotocraftApp) {
p.history = history;
p.properties = props;
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn window_panel_and_workspace_ids_drive_the_shell() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ assert!(!app.ui.panels.history);
+ invoke(&mut app, &ctx, "window.panel.history", Value::Null).unwrap();
+ assert!(app.ui.panels.history);
+ assert_eq!(checked(&app, "window.panel.history"), Some(true));
+ invoke(&mut app, &ctx, "window.workspace.painting", Value::Null).unwrap();
+ assert_eq!(app.ui.workspace, "Painting");
+ assert!(!app.ui.panels.properties);
+ assert_eq!(checked(&app, "window.workspace.painting"), Some(true));
+ invoke(&mut app, &ctx, "window.workspace.essentials", Value::Null).unwrap();
+ assert!(app.ui.panels.properties);
+ // Live in the menu, and no duplicate "Layers" entry from the window.toggle.* commands.
+ let items = menu_items(&app);
+ assert!(items.iter().any(|i| i.id == "window.panel.layers" && i.enabled));
+ assert_eq!(items.iter().filter(|i| i.path == ["Window"] && i.label == "Layers").count(), 1);
+ assert!(items.iter().any(|i| i.id == "edit.stroke"));
+ }
+
+ #[test]
+ fn proof_setup_presets_and_checkmarks() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
+ app.sync_views();
+ assert_eq!(checked(&app, "view.proofColors"), Some(false));
+ invoke(&mut app, &ctx, "view.proofSetup.workingCmyk", Value::Null).unwrap();
+ assert_eq!(checked(&app, "view.proofColors"), Some(true));
+ invoke(&mut app, &ctx, "view.gamutWarning", json!({"on": true})).unwrap();
+ assert_eq!(checked(&app, "view.gamutWarning"), Some(true));
+ let doc = app.session.active().unwrap().doc.clone();
+ let lut = app.session.color.canvas_lut(&doc, 9).unwrap().unwrap();
+ assert_eq!(lut.len(), 9 * 9 * 9 * 4);
+ // Pure sRGB green is outside coated CMYK; mid grey is inside.
+ let at = |r: usize, g: usize, b: usize| lut[(r + g * 9 + b * 81) * 4 + 3];
+ assert_eq!((at(0, 8, 0), at(4, 4, 4)), (255, 0));
+ // Custom… opens the generated Proof Setup dialog with a profile choice.
+ assert!(invoke(&mut app, &ctx, "view.proofSetup.custom", Value::Null).unwrap()["dialog"].is_u64());
+ let spec = photocraft_engine::commands::find("edit.convertToProfile").unwrap();
+ let params = crate::filter_dialog::parse_spec(spec.params);
+ assert!(matches!(&params[0].kind, crate::filter_dialog::Kind::Choice(c) if c[0] == "srgb" && !c.iter().any(|v| v.contains('/'))));
+ }
+}
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index a2776f81e..5540abbc4 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -420,11 +420,29 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
widgets::checkbox(ui, &mut tc, "Show Transform Controls");
widgets::vline(ui, 22.0);
ui.spacing_mut().item_spacing.x = 0.0;
- for (icon, tip) in [("panels-top-left", "Align left edges"), ("app-window", "Align horizontal centers"), ("panel-right", "Align right edges")] {
- let _ = icons::button(ui, icon, 24.0, false, tip);
+ for (icon, tip, cmd) in [("panels-top-left", "Align left edges", "layer.align.leftEdges"), ("app-window", "Align horizontal centers", "layer.align.horizontalCenters"), ("panel-right", "Align right edges", "layer.align.rightEdges")] {
+ let on = app.session.is_enabled(cmd);
+ if ui.add_enabled_ui(on, |ui| icons::button(ui, icon, 24.0, false, tip)).inner.clicked() {
+ let _ = app.run(cmd, json!({}));
+ }
}
ui.add_space(6.0);
- let _ = icons::button(ui, "ellipsis", 24.0, false, "Align and distribute");
+ let more = icons::button(ui, "ellipsis", 24.0, false, "Align and distribute");
+ egui::Popup::menu(&more).show(|ui| {
+ ui.set_min_width(200.0);
+ let mut section = |ui: &mut egui::Ui, title: &str, prefix: &str| {
+ ui.label(egui::RichText::new(title).small().color(t.text_dim));
+ for c in photocraft_engine::command_specs().iter().filter(|c| c.id.starts_with(prefix)) {
+ if ui.add_enabled(app.session.is_enabled(c.id), egui::Button::new(c.label)).clicked() {
+ let _ = app.run(c.id, json!({}));
+ ui.close();
+ }
+ }
+ };
+ section(ui, "Align", "layer.align.");
+ ui.separator();
+ section(ui, "Distribute", "layer.distribute.");
+ });
}
Tool::RectMarquee | Tool::EllipseMarquee => hint(ui, "Drag to select · ⇧ add · ⌥ subtract · ⇧⌥ intersect · click to deselect"),
Tool::Move => hint(ui, "Drag to move the active layer"),
@@ -627,6 +645,12 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
return;
};
let (rev, size) = (st.revision, st.doc.size);
+ // Positions and sizes in the ruler unit (Preferences › Units & Rulers).
+ let units = app.session.prefs().units_and_rulers.clone();
+ let dpi = st.doc.resolution_dpi as f64;
+ let fx = move |px: f64| units.format(px, dpi, size.width as f64);
+ let units_y = app.session.prefs().units_and_rulers.clone();
+ let fy = move |px: f64| units_y.format(px, dpi, size.height as f64);
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)| {
@@ -666,10 +690,10 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
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()));
+ row(&mut cols[0], "X:", pos.map_or_else(dash, |p| fx(p.0 as f64)));
+ row(&mut cols[0], "Y:", pos.map_or_else(dash, |p| fy(p.1 as f64)));
+ row(&mut cols[1], "W:", sel.map_or_else(dash, |r| fx(r.width() as f64)));
+ row(&mut cols[1], "H:", sel.map_or_else(dash, |r| fy(r.height() as f64)));
});
widgets::hairline(ui);
ui.label(RichText::new(format!("Doc: {} × {} px", size.width, size.height)).color(t.text_dim).size(11.5));
@@ -813,6 +837,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let doc = st.doc.clone();
let active = st.active_layer;
let active_layer = active.and_then(|id| doc.layer(id)).cloned();
+ let selection = st.selected_layers();
let mut actions: Vec<(String, Value)> = Vec::new();
let t = Tokens::get(ui.ctx());
@@ -908,10 +933,12 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
continue;
}
}
- layer_row(app, &ctx, ui, &doc, l, *depth, active == Some(l.id), &mut actions);
+ let row = RowSel { selected: selection.contains(&l.id), primary: active == Some(l.id), multi: selection.len() > 1 };
+ layer_row(app, &ctx, ui, &doc, l, *depth, row, &mut actions);
if !l.effects.items.is_empty() {
effect_rows(app, ui, l, *depth);
}
+ crate::smart_ui::filter_rows(app, ui, l, *depth, &mut actions);
}
});
// End any layer drag after every row has had a chance to accept the drop.
@@ -987,8 +1014,30 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
}
+/// How a Layers panel row is selected: in the (multi-)selection, the primary/active layer, and
+/// whether several layers are selected.
+#[derive(Clone, Copy)]
+struct RowSel {
+ selected: bool,
+ primary: bool,
+ multi: bool,
+}
+
+/// `layer.select` mode for a click with these modifiers (Photoshop: ⌘-click toggles, ⇧-click
+/// selects a range, a plain click selects one layer).
+fn select_mode(m: egui::Modifiers) -> &'static str {
+ if m.command {
+ "toggle"
+ } else if m.shift {
+ "range"
+ } else {
+ "replace"
+ }
+}
+
#[allow(clippy::too_many_arguments)]
-fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, doc: &photocraft_doc::Document, l: &Layer, depth: usize, selected: bool, actions: &mut Vec<(String, Value)>) {
+fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, doc: &photocraft_doc::Document, l: &Layer, depth: usize, row: RowSel, actions: &mut Vec<(String, Value)>) {
+ let selected = row.selected;
let t = Tokens::get(ctx);
let row_h = if t.pro { 36.0 } else { 46.0 };
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click_and_drag());
@@ -1023,7 +1072,7 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do
}
let ts = if t.pro { 28.0 } else { 34.0 };
let 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);
+ draw_layer_thumb(app, ctx, ui, doc, l, thumb, row.primary);
x += ts + 6.0;
let mut mask_rect = None;
if let Some(m) = &l.mask {
@@ -1034,8 +1083,8 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do
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 {
+ // Photoshop frames the targeted thumbnail (pixels or mask) of the active layer with corner brackets.
+ if row.primary {
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);
@@ -1071,11 +1120,26 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do
if l.blend != BlendMode::Normal && l.blend != BlendMode::PassThrough {
painter.text(pos2(rect.right() - 30.0, rect.center().y), Align2::RIGHT_CENTER, l.blend.label(), egui::FontId::proportional(10.5), t.text_faint);
}
- if l.locks.transparency || l.locks.position || l.locks.all {
+ let locked = l.locks.transparency || l.locks.position || l.locks.all;
+ if locked {
icons::paint(ui, Rect::from_center_size(pos2(rect.right() - 14.0, rect.center().y), vec2(14.0, 14.0)), "lock", 12.0, t.text_faint);
}
- if resp.clicked() && !eye_resp.clicked() {
- actions.push(("layer.select".into(), json!({"layer": l.id.0})));
+ if l.link_group.is_some() {
+ let x = rect.right() - if locked { 30.0 } else { 14.0 };
+ icons::paint(ui, Rect::from_center_size(pos2(x, rect.center().y), vec2(14.0, 14.0)), "link", 12.0, t.text_faint);
+ }
+ // ⌘-click a layer or mask thumbnail loads its transparency / mask as a selection (⇧ add,
+ // ⌥ subtract, ⇧⌥ intersect) instead of changing the layer selection.
+ let thumb_load = resp.clicked().then(|| (ui.input(|i| i.modifiers), resp.interact_pointer_pos())).and_then(|(m, pos)| {
+ let p = pos.filter(|_| m.command)?;
+ let on_mask = mask_rect.is_some_and(|r| r.expand(2.0).contains(p));
+ (on_mask || thumb.expand(2.0).contains(p)).then(|| json!({"channel": if on_mask { "mask" } else { "transparency" }, "layer": l.id.0, "operation": crate::channels_panel::load_operation(m)}))
+ });
+ if let Some(p) = thumb_load {
+ actions.push(("select.loadSelection".into(), p));
+ } else if resp.clicked() && !eye_resp.clicked() {
+ let mode = select_mode(ui.input(|i| i.modifiers));
+ actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode})));
// 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));
@@ -1083,7 +1147,7 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do
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 {
+ } else if on_thumb || !row.primary {
actions.push(("ui.maskTarget".into(), json!(false)));
}
}
@@ -1112,15 +1176,21 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do
resp.context_menu(|ui| {
ui.set_min_width(200.0);
let id = l.id.0;
+ // Right-clicking inside a multi-selection keeps it and acts on every selected layer.
+ let on_set = row.multi && selected;
let mut item = |ui: &mut egui::Ui, label: &str, cmd: &str| {
if ui.button(label).clicked() {
- actions.push(("layer.select".into(), json!({"layer": id})));
- actions.push((cmd.into(), json!({"layer": id})));
+ if on_set {
+ actions.push((cmd.into(), json!({})));
+ } else {
+ actions.push(("layer.select".into(), json!({"layer": id})));
+ actions.push((cmd.into(), json!({"layer": id})));
+ }
ui.close();
}
};
- item(ui, "Duplicate Layer", "layer.duplicate");
- item(ui, "Delete Layer", "layer.delete");
+ item(ui, if on_set { "Duplicate Layers" } else { "Duplicate Layer" }, "layer.duplicate");
+ item(ui, if on_set { "Delete Layers" } else { "Delete Layer" }, "layer.delete");
ui.separator();
if l.clipped {
item(ui, "Release Clipping Mask", "layer.releaseClippingMask");
@@ -1134,7 +1204,12 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do
}
ui.separator();
item(ui, "Group Layers", "layer.groupLayers");
- item(ui, "Merge Down", "layer.mergeDown");
+ if on_set {
+ item(ui, "Merge Layers", "layer.mergeLayers");
+ item(ui, "Link Layers", "layer.linkLayers");
+ } else {
+ item(ui, "Merge Down", "layer.mergeDown");
+ }
if ui.button("Flatten Image").clicked() {
actions.push(("layer.flattenImage".into(), json!({})));
ui.close();
@@ -1177,40 +1252,11 @@ fn draw_layer_thumb(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &egui::Ui,
}
let stroke = if t.pro { Stroke::new(1.0, Color32::from_gray(20)) } else if selected { Stroke::new(1.5, t.text) } else { Stroke::new(1.0, t.field_border) };
p.rect_stroke(rect, CornerRadius::same(if t.pro { 0 } else { 5 }), stroke, StrokeKind::Outside);
+ crate::smart_ui::thumb_badge(ui, l, rect);
}
fn channels(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
- let Some(st) = app.session.active() else {
- empty(ui, "No document");
- return;
- };
- 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() {
- 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));
- }
- }
+ crate::channels_panel::show(app, ui);
}
fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
@@ -1439,7 +1485,11 @@ fn adjustment_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId,
}
ui.add_space(4.0);
}
- if adjustment_sliders(kind).is_empty() && !tone && kind != "invert" {
+ if kind == "selectiveColor" {
+ crate::adjust_ui::selective_color_editor(app, ui, id, adj);
+ } else if kind == "colorLookup" {
+ crate::adjust_ui::color_lookup_editor(app, ui, id, adj);
+ } else 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 {
@@ -1547,7 +1597,7 @@ fn adjustments_grid(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
ui.label(RichText::new("Add an adjustment").color(t.text_dim));
ui.add_space(4.0);
- let items: [(&str, &str, &str); 14] = [
+ let items: [(&str, &str, &str); 16] = [
("brightnessContrast", "sun", "Brightness/Contrast"),
("levels", "gauge", "Levels"),
("curves", "pen-tool", "Curves"),
@@ -1562,6 +1612,8 @@ fn adjustments_grid(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
("posterize", "layers", "Posterize"),
("threshold", "square", "Threshold"),
("gradientMap", "palette", "Gradient Map"),
+ ("selectiveColor", "swatch-book", "Selective Color"),
+ ("colorLookup", "grid-3x3", "Color Lookup"),
];
let mut run = None;
ui.horizontal_wrapped(|ui| {
diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/parity.rs
new file mode 100644
index 000000000..e1197326f
--- /dev/null
+++ b/crates/ui-egui/src/parity.rs
@@ -0,0 +1,102 @@
+//! Photoshop menu parity: how much of [`crate::menu_catalog::CATALOG`] is live.
+//!
+//! `cargo xtask parity` prints this report and writes `docs/parity.md`. A test keeps the live
+//! count from regressing below [`FLOOR`].
+
+use crate::menu_catalog::CATALOG;
+use crate::menus::is_live;
+
+/// Minimum number of live catalog items. Raise it when parity grows; never lower it.
+pub const FLOOR: usize = 513;
+
+/// One top-level menu's coverage.
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct MenuParity {
+ pub menu: String,
+ pub live: usize,
+ pub total: usize,
+ /// Labels (with submenu path) of items not implemented yet.
+ pub missing: Vec<String>,
+}
+
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct Parity {
+ pub live: usize,
+ pub total: usize,
+ pub menus: Vec<MenuParity>,
+}
+
+impl Parity {
+ pub fn percent(&self) -> f64 {
+ if self.total == 0 { 0.0 } else { 100.0 * self.live as f64 / self.total as f64 }
+ }
+
+ /// The report as Markdown (the body of `docs/parity.md`).
+ pub fn to_markdown(&self) -> String {
+ let mut s = String::new();
+ s.push_str("# Photoshop menu parity\n\n");
+ s.push_str("Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Photoshop's menu tree) and the live command registry. Do not edit by hand.\n\n");
+ s.push_str(&format!("**{} of {} menu items live ({:.1}%).**\n\n", self.live, self.total, self.percent()));
+ s.push_str("| Menu | Live | Total | % |\n|---|---:|---:|---:|\n");
+ for m in &self.menus {
+ let pct = if m.total == 0 { 0.0 } else { 100.0 * m.live as f64 / m.total as f64 };
+ s.push_str(&format!("| {} | {} | {} | {:.0}% |\n", m.menu, m.live, m.total, pct));
+ }
+ s.push_str("\n## Not yet implemented\n");
+ for m in self.menus.iter().filter(|m| !m.missing.is_empty()) {
+ s.push_str(&format!("\n### {} ({})\n\n", m.menu, m.missing.len()));
+ for item in &m.missing {
+ s.push_str(&format!("- {item}\n"));
+ }
+ }
+ s
+ }
+}
+
+/// Compute coverage of the Photoshop menu catalog (separators excluded; duplicate ids counted once).
+pub fn compute() -> Parity {
+ let mut menus: Vec<MenuParity> = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ for &(path, label, _, id) in CATALOG {
+ if id == "---" || !seen.insert(id) {
+ continue;
+ }
+ let top = path.first().copied().unwrap_or("?");
+ let m = match menus.iter().position(|m| m.menu == top) {
+ Some(i) => &mut menus[i],
+ None => {
+ menus.push(MenuParity { menu: top.to_string(), live: 0, total: 0, missing: Vec::new() });
+ menus.last_mut().expect("just pushed")
+ }
+ };
+ m.total += 1;
+ if is_live(id) {
+ m.live += 1;
+ } else {
+ let mut full: Vec<&str> = path[1..].to_vec();
+ full.push(label);
+ m.missing.push(format!("{} (`{id}`)", full.join(" › ")));
+ }
+ }
+ Parity { live: menus.iter().map(|m| m.live).sum(), total: menus.iter().map(|m| m.total).sum(), menus }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parity_does_not_regress() {
+ let p = compute();
+ assert!(p.total > 500, "catalog shrank: {}", p.total);
+ assert!(p.live >= FLOOR, "menu parity regressed: {} live < floor {FLOOR}", p.live);
+ }
+
+ #[test]
+ fn markdown_lists_every_missing_item() {
+ let p = compute();
+ let md = p.to_markdown();
+ let listed = md.lines().filter(|l| l.starts_with("- ")).count();
+ assert_eq!(listed, p.total - p.live);
+ }
+}
diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs
new file mode 100644
index 000000000..677f88e48
--- /dev/null
+++ b/crates/ui-egui/src/prefs_ui.rs
@@ -0,0 +1,1090 @@
+//! Edit › Preferences, Keyboard Shortcuts and Menus, Color Settings and the rest of the Edit
+//! menu's dialogs, plus the shell side of preferences: loading and saving them through
+//! [`crate::Services`], applying the interface theme, autosave and crash recovery, and the
+//! history log.
+//!
+//! The values live in the engine ([`photocraft_engine::prefs::Preferences`], so agents read and
+//! change them with `prefs.get` / `prefs.set`); this module only edits a working copy in a dialog
+//! and commits it with those commands on OK.
+
+use std::collections::{BTreeMap, HashMap};
+
+use egui::{Color32, RichText, Sense, vec2};
+use photocraft_doc::DocId;
+use photocraft_engine::prefs::{self, SECTIONS, Theme};
+use photocraft_engine::snap::{SnapLine, SnapTargets};
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::state::DialogKind;
+use crate::theme::{ThemeKind, Tokens};
+
+/// Shell runtime state for preferences, autosave and snapping (not serialised).
+#[derive(Default)]
+pub struct Runtime {
+ loaded: bool,
+ saved_rev: u64,
+ theme_pref: Option<Theme>,
+ next_autosave_ms: f64,
+ autosaved: HashMap<DocId, u64>,
+ log_len: usize,
+ /// Snapping state of the drag in progress (see `snap_ui`).
+ pub(crate) snap: Option<crate::snap_ui::ActiveSnap>,
+ pub(crate) snap_lines: Vec<SnapLine>,
+ pub(crate) guide_targets: Option<((DocId, u64), SnapTargets)>,
+ /// Checkerboard colours the cached CPU checker texture was built with.
+ pub(crate) checker_key: Option<[[u8; 3]; 2]>,
+ /// Style last sent to the GPU canvas.
+ pub(crate) gpu_style: Option<crate::gpu_canvas::CanvasStyle>,
+}
+
+/// The GPU canvas colours from Preferences › Transparency & Gamut.
+pub fn canvas_style(app: &PhotocraftApp) -> crate::gpu_canvas::CanvasStyle {
+ let t = &app.session.prefs().transparency_and_gamut;
+ let [l, d] = t.colors();
+ let f = |c: [u8; 3]| c.map(|v| v as f32 / 255.0);
+ let g = prefs::parse_hex(&t.gamut_warning_color).unwrap_or([128; 3]);
+ crate::gpu_canvas::CanvasStyle { checker_square: t.square().unwrap_or(0.0), checker_light: f(l), checker_dark: f(d), gamut_color: f(g), gamut_opacity: t.gamut_warning_opacity as f32 / 100.0 }
+}
+
+/// Pasteboard colour from Preferences › Interface (`None` = the theme's default canvas).
+pub fn pasteboard_color(app: &PhotocraftApp) -> Option<Color32> {
+ use prefs::CanvasColor;
+ let i = &app.session.prefs().interface;
+ Some(match i.canvas_color {
+ CanvasColor::Default => return None,
+ CanvasColor::Black => Color32::BLACK,
+ CanvasColor::DarkGray => Color32::from_gray(40),
+ CanvasColor::MediumGray => Color32::from_gray(83),
+ CanvasColor::LightGray => Color32::from_gray(184),
+ CanvasColor::Custom => color_of(&i.canvas_custom_color),
+ })
+}
+
+fn theme_kind(t: Theme) -> ThemeKind {
+ match t {
+ Theme::Pro => ThemeKind::Pro,
+ Theme::Studio => ThemeKind::Studio,
+ Theme::StudioLight => ThemeKind::StudioLight,
+ Theme::Classic => ThemeKind::Classic,
+ }
+}
+
+fn theme_pref(k: ThemeKind) -> Theme {
+ match k {
+ ThemeKind::Pro => Theme::Pro,
+ ThemeKind::Studio => Theme::Studio,
+ ThemeKind::StudioLight => Theme::StudioLight,
+ ThemeKind::Classic => Theme::Classic,
+ }
+}
+
+// ------------------------------------------------------------------ lifecycle
+
+/// Load saved preferences (once) and recover autosaved documents. Called when the app is
+/// created.
+pub fn load(app: &mut PhotocraftApp) {
+ if app.prefs_rt.loaded {
+ return;
+ }
+ app.prefs_rt.loaded = true;
+ if let Some(text) = app.services.load_prefs.as_mut().and_then(|f| f())
+ && let Err(e) = app.session.load_prefs_json(&text)
+ {
+ app.ui.status = format!("Preferences were reset: {e}");
+ }
+ app.prefs_rt.saved_rev = app.session.prefs.rev();
+ if app.session.prefs().file_handling.recover_on_launch
+ && let Some(recover) = app.services.recover.as_mut()
+ {
+ let docs = recover();
+ let n = docs.len();
+ for (path, doc) in docs {
+ app.session.add_document(doc, path);
+ // Recovered documents are unsaved.
+ if let Some(st) = app.session.active_mut() {
+ st.saved_revision = 0;
+ }
+ }
+ if n > 0 {
+ app.sync_views();
+ app.ui.status = format!("Recovered {n} document{}", if n == 1 { "" } else { "s" });
+ }
+ }
+}
+
+/// Per-frame upkeep: theme sync, persistence, autosave and the history log.
+pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ if !app.prefs_rt.loaded {
+ load(app);
+ }
+ // Interface theme: a preference change applies to the UI; a theme picked from the Window
+ // menu is stored as the preference.
+ let pref = app.session.prefs().interface.theme;
+ if app.prefs_rt.theme_pref != Some(pref) {
+ app.prefs_rt.theme_pref = Some(pref);
+ if app.ui.theme != theme_kind(pref) {
+ app.set_theme(ctx, theme_kind(pref));
+ }
+ } else if theme_pref(app.ui.theme) != pref {
+ let t = theme_pref(app.ui.theme);
+ app.session.prefs.edit(|p| p.interface.theme = t);
+ app.prefs_rt.theme_pref = Some(t);
+ }
+ if app.session.prefs.rev() != app.prefs_rt.saved_rev {
+ app.prefs_rt.saved_rev = app.session.prefs.rev();
+ let text = app.session.prefs_to_json();
+ if let Some(save) = app.services.save_prefs.as_mut()
+ && let Err(e) = save(&text)
+ {
+ app.ui.status = format!("Couldn't save preferences: {e}");
+ }
+ }
+ let style = canvas_style(app);
+ if let Some(gpu) = app.gpu.as_ref()
+ && app.prefs_rt.gpu_style != Some(style)
+ {
+ gpu.set_style(style);
+ app.prefs_rt.gpu_style = Some(style);
+ }
+ autosave(app);
+ history_log(app);
+}
+
+/// Background autosave of documents with unsaved changes every N minutes (File Handling).
+fn autosave(app: &mut PhotocraftApp) {
+ let fh = &app.session.prefs().file_handling;
+ let (on, minutes) = (fh.autosave, fh.autosave_minutes.max(1));
+ if app.services.autosave.is_none() {
+ return;
+ }
+ let now = crate::gpu_canvas::now_ms();
+ // Saved or closed documents drop their recovery data.
+ let live: HashMap<DocId, bool> = app.session.documents().iter().map(|d| (d.doc.id, d.is_dirty())).collect();
+ let stale: Vec<DocId> = app.prefs_rt.autosaved.keys().filter(|id| live.get(id) != Some(&true)).copied().collect();
+ for id in stale {
+ app.prefs_rt.autosaved.remove(&id);
+ if let Some(d) = app.services.discard_autosave.as_mut() {
+ d(id.0);
+ }
+ }
+ if !on {
+ return;
+ }
+ let interval = minutes as f64 * 60_000.0;
+ if app.prefs_rt.next_autosave_ms == 0.0 || app.prefs_rt.next_autosave_ms > now + interval {
+ app.prefs_rt.next_autosave_ms = now + interval;
+ return;
+ }
+ if now < app.prefs_rt.next_autosave_ms {
+ return;
+ }
+ app.prefs_rt.next_autosave_ms = now + interval;
+ let jobs: Vec<_> = app.session.documents().iter().filter(|d| d.is_dirty() && app.prefs_rt.autosaved.get(&d.doc.id) != Some(&d.revision)).map(|d| (d.doc.clone(), d.revision, d.path.clone())).collect();
+ for (doc, rev, path) in jobs {
+ if let Some(save) = app.services.autosave.as_mut() {
+ match save(&doc, rev, path.as_deref()) {
+ Ok(()) => {
+ app.prefs_rt.autosaved.insert(doc.id, rev);
+ }
+ Err(e) => app.ui.status = format!("Autosave failed: {e}"),
+ }
+ }
+ }
+}
+
+/// Force the autosave timer to fire on the next tick (tests, `prefs` changes).
+pub fn autosave_now(app: &mut PhotocraftApp) {
+ app.prefs_rt.next_autosave_ms = f64::MIN_POSITIVE;
+}
+
+/// History Log preference: append executed commands to a text file.
+fn history_log(app: &mut PhotocraftApp) {
+ let n = app.session.journal.len();
+ if n <= app.prefs_rt.log_len {
+ app.prefs_rt.log_len = n;
+ return;
+ }
+ let hl = app.session.prefs().history_log.clone();
+ let start = app.prefs_rt.log_len;
+ app.prefs_rt.log_len = n;
+ if !hl.enabled || hl.file_path.is_empty() || hl.destination == prefs::LogDestination::Metadata {
+ return;
+ }
+ let Some(append) = app.services.append_text.as_mut() else { return };
+ let mut text = String::new();
+ for (id, params) in &app.session.journal[start..] {
+ let label = photocraft_engine::commands::find(id).map_or(id.as_str(), |c| c.label).trim_end_matches('…');
+ match hl.detail {
+ prefs::LogDetail::SessionsOnly => {
+ if matches!(id.as_str(), "file.new" | "file.open" | "file.close" | "file.openAs") {
+ text.push_str(&format!("{label}\n"));
+ }
+ }
+ prefs::LogDetail::Concise => text.push_str(&format!("{label}\n")),
+ prefs::LogDetail::Detailed => text.push_str(&format!("{label} {id} {params}\n")),
+ }
+ }
+ if !text.is_empty() {
+ let _ = append(&hl.file_path, &text);
+ }
+}
+
+// ------------------------------------------------------------------ shortcuts
+
+/// The shortcut in effect for a menu item: the user's override, else `default`.
+pub fn effective_shortcut(app: &PhotocraftApp, id: &str, default: Option<&str>) -> Option<String> {
+ app.session.prefs().shortcut(id, default).map(str::to_string)
+}
+
+/// Every shortcut-bearing command (engine registry plus shell commands): (id, label, menu path,
+/// default shortcut), menu items first in Photoshop order.
+pub fn shortcut_items(app: &PhotocraftApp) -> Vec<(String, String, Vec<String>, Option<String>)> {
+ let mut out: Vec<(String, String, Vec<String>, Option<String>)> = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ for it in crate::menus::menu_items(app) {
+ if it.label == "---" || !seen.insert(it.id.clone()) {
+ continue;
+ }
+ let default = default_shortcut(&it.id).or(it.shortcut.clone().filter(|_| !app.session.prefs().shortcuts.contains_key(&it.id)));
+ out.push((it.id, it.label, it.path, default));
+ }
+ for c in photocraft_engine::command_specs() {
+ if seen.insert(c.id.to_string()) && c.shortcut.is_some() {
+ out.push((c.id.into(), c.label.into(), c.menu.iter().map(|s| s.to_string()).collect(), c.shortcut.map(Into::into)));
+ }
+ }
+ out
+}
+
+/// Default (unmodified) shortcut of a command id.
+pub fn default_shortcut(id: &str) -> Option<String> {
+ crate::menus::UI_COMMANDS
+ .iter()
+ .find(|c| c.0 == id)
+ .and_then(|c| c.3)
+ .or_else(|| photocraft_engine::commands::find(id).and_then(|c| c.shortcut))
+ .or_else(|| crate::menu_catalog::CATALOG.iter().find(|c| c.3 == id).and_then(|c| c.2))
+ .map(str::to_string)
+}
+
+/// Text of a key press for the shortcut editor (`Cmd+Shift+K`), `None` for bare modifiers.
+pub fn shortcut_text(key: egui::Key, m: egui::Modifiers) -> Option<String> {
+ let mut parts = Vec::new();
+ if m.command || m.mac_cmd {
+ parts.push("Cmd".to_string());
+ }
+ if m.ctrl && !m.command {
+ parts.push("Ctrl".into());
+ }
+ if m.alt {
+ parts.push("Alt".into());
+ }
+ if m.shift {
+ parts.push("Shift".into());
+ }
+ let name = match key {
+ egui::Key::Equals => "=",
+ egui::Key::Minus => "-",
+ egui::Key::OpenBracket => "[",
+ egui::Key::CloseBracket => "]",
+ egui::Key::Semicolon => ";",
+ egui::Key::Quote => "'",
+ egui::Key::Plus => "",
+ k => k.name(),
+ };
+ parts.push(name.to_string());
+ prefs::normalize_shortcut(&parts.join("+"))
+}
+
+// ------------------------------------------------------------------ menu routing
+
+/// Shell front ends for Edit-menu commands invoked without parameters (dialogs, pickers).
+/// `None` when `id` isn't handled here.
+pub fn invoke(app: &mut PhotocraftApp, _ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ let empty = params.as_object().is_none_or(|o| o.is_empty());
+ if !empty {
+ return None;
+ }
+ if let Some(section) = id.strip_prefix("edit.preferences.") {
+ return Some(Ok(json!({"dialog": open_preferences(app, section)})));
+ }
+ let dialog = |d: Option<u64>| Some(d.map(|d| json!({"dialog": d})).ok_or_else(|| "not available".to_string()));
+ match id {
+ "edit.keyboardShortcuts" => Some(Ok(json!({"dialog": open_shortcuts(app, 0)}))),
+ "edit.menus" => Some(Ok(json!({"dialog": open_shortcuts(app, 1)}))),
+ "edit.toolbar" => Some(Ok(json!({"dialog": open_shortcuts(app, 2)}))),
+ "edit.colorSettings" => {
+ let d = crate::filter_dialog::open(app, "edit.colorSettings");
+ if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) {
+ let cur = serde_json::to_value(&app.session.color.settings).unwrap_or_default();
+ for (k, v) in cur.as_object().into_iter().flatten() {
+ if dm.fields.contains_key(k) {
+ dm.fields.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ dialog(d)
+ }
+ "edit.fade" | "edit.findAndReplaceText" | "edit.defineBrushPreset" | "edit.defineCustomShape" | "edit.autoAlignLayers" | "edit.autoBlendLayers" => {
+ if !app.session.is_enabled(id) {
+ return Some(Err(photocraft_engine::commands::find(id).map_or("not available".into(), |c| format!("{} is not available right now", c.label.trim_end_matches('…')))));
+ }
+ let d = crate::filter_dialog::open(app, id);
+ if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) {
+ // Optional parameters the generic dialog can't express keep their defaults.
+ for k in ["reference", "path"] {
+ dm.fields.remove(k);
+ }
+ }
+ dialog(d)
+ }
+ "edit.contentAwareFill" => {
+ if !app.session.is_enabled(id) {
+ return Some(Err("Content-Aware Fill needs a selection on a pixel layer".into()));
+ }
+ let d = crate::filter_dialog::open(app, id);
+ if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) {
+ dm.fields.insert("__preview".into(), json!(true));
+ for k in ["margin", "seed", "channel"] {
+ dm.fields.remove(k);
+ }
+ }
+ dialog(d)
+ }
+ "edit.contentAwareScale" => {
+ let st = app.session.active()?;
+ let b = match &st.doc.selection {
+ Some(s) => s.content_bounds(),
+ None => st.active_layer.and_then(|l| st.doc.layer(l)).and_then(|l| l.surface()).map(|s| s.content_bounds()).unwrap_or_default(),
+ };
+ let d = crate::filter_dialog::open(app, id);
+ if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) {
+ dm.fields.insert("width".into(), json!(b.width()));
+ dm.fields.insert("height".into(), json!(b.height()));
+ dm.fields.remove("scaleX");
+ dm.fields.remove("scaleY");
+ dm.fields.insert("__preview".into(), json!(true));
+ }
+ dialog(d)
+ }
+ "edit.presets.presetManager" => Some(Ok(json!({"dialog": open_kind(app, "presets", "Preset Manager", json!({"kind": "brushes", "selected": 0, "newName": ""}))}))),
+ "edit.presets.exportImportPresets" => Some(Ok(json!({"dialog": open_kind(app, "presetsIO", "Export/Import Presets", json!({"action": "export", "brushes": true, "customShapes": true}))}))),
+ _ => None,
+ }
+}
+
+fn open_kind(app: &mut PhotocraftApp, kind: &str, label: &str, fields: Value) -> u64 {
+ let mut f = Map::new();
+ f.insert("__prefsui".into(), json!(kind));
+ f.insert("__label".into(), json!(label));
+ if let Value::Object(m) = fields {
+ f.extend(m);
+ }
+ app.ui.open_dialog(DialogKind::Command, f)
+}
+
+/// Is this a dialog rendered by this module?
+pub fn owns(fields: &Map<String, Value>) -> bool {
+ fields.contains_key("__prefsui")
+}
+
+/// Max dialog width for our dialogs.
+pub fn width(fields: &Map<String, Value>) -> Option<f32> {
+ match fields.get("__prefsui").and_then(Value::as_str)? {
+ "prefs" => Some(780.0),
+ "shortcuts" => Some(720.0),
+ _ => Some(460.0),
+ }
+}
+
+/// Open Edit › Preferences on `section`.
+pub fn open_preferences(app: &mut PhotocraftApp, section: &str) -> u64 {
+ let section = if SECTIONS.iter().any(|(id, _)| *id == section) { section } else { "general" };
+ let values = app.session.prefs().to_json();
+ let working: Map<String, Value> = SECTIONS.iter().filter_map(|(id, _)| Some((id.to_string(), values.get(id)?.clone()))).collect();
+ let order = field_order(app.session.prefs(), &working);
+ open_kind(app, "prefs", "Preferences", json!({"section": section, "values": working, "__order": order}))
+}
+
+/// Each section's keys in declaration order (JSON objects sort their keys; the serialised text
+/// keeps the struct's order, which groups related settings like Photoshop's dialog).
+fn field_order(p: &prefs::Preferences, sections: &Map<String, Value>) -> Value {
+ let text = serde_json::to_string(p).unwrap_or_default();
+ let mut out = Map::new();
+ for (id, v) in sections {
+ let Some(start) = text.find(&format!("\"{id}\":{{")) else { continue };
+ let body = &text[start..];
+ let end = body.find('}').unwrap_or(body.len());
+ let region = &body[..end];
+ let mut keys: Vec<(usize, String)> = v.as_object().into_iter().flatten().map(|(k, _)| (region.find(&format!("\"{k}\":")).unwrap_or(usize::MAX), k.clone())).collect();
+ keys.sort();
+ out.insert(id.clone(), json!(keys.into_iter().map(|(_, k)| k).collect::<Vec<_>>()));
+ }
+ Value::Object(out)
+}
+
+/// Open Keyboard Shortcuts and Menus on a tab (0 shortcuts, 1 menus, 2 toolbar).
+pub fn open_shortcuts(app: &mut PhotocraftApp, tab: u64) -> u64 {
+ let p = app.session.prefs();
+ let fields = json!({
+ "tab": tab,
+ "filter": "",
+ "overrides": p.shortcuts,
+ "hidden": p.menus.hidden,
+ "colors": p.menus.colors,
+ "toolbarHidden": p.toolbar.hidden,
+ "selected": "",
+ "capture": false,
+ "message": "",
+ });
+ open_kind(app, "shortcuts", "Keyboard Shortcuts and Menus", fields)
+}
+
+/// Open the Embedded Profile Mismatch prompt for the active document.
+pub fn open_mismatch(app: &mut PhotocraftApp, report: &Value) -> u64 {
+ let msg = if report.get("missing").and_then(Value::as_bool) == Some(true) {
+ format!("The document does not have an embedded colour profile. Working space: {}.", report["working"].as_str().unwrap_or("?"))
+ } else {
+ format!("The document has an embedded colour profile that does not match the working space.\nEmbedded: {}\nWorking: {}", report["embedded"].as_str().unwrap_or("?"), report["working"].as_str().unwrap_or("?"))
+ };
+ let action = match report["action"].as_str() {
+ Some("converted") => "convert",
+ Some("discarded") => "discard",
+ _ => "preserve",
+ };
+ open_kind(app, "mismatch", "Embedded Profile Mismatch", json!({"message": msg, "action": action, "applied": action, "missing": report.get("missing").is_some()}))
+}
+
+// ------------------------------------------------------------------ bodies
+
+/// Render one of our dialogs' bodies.
+pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") {
+ "prefs" => prefs_body(ui, f),
+ "shortcuts" => shortcuts_body(app, ui, f),
+ "presets" => presets_body(app, ui, f),
+ "presetsIO" => presets_io_body(ui, f),
+ "mismatch" => mismatch_body(ui, f),
+ _ => {}
+ }
+}
+
+fn humanize(key: &str) -> String {
+ 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.extend(ch.to_lowercase());
+ } else {
+ s.push(ch);
+ }
+ }
+ s.replace("Psd", "PSD").replace("Gpu", "GPU").replace("Ui ", "UI ").replace("Mb", "(MB)").replace("Exif", "EXIF").replace("Hud", "HUD")
+}
+
+fn choice_label(v: &str) -> String {
+ match v {
+ "cm" => "Centimeters".into(),
+ "mm" => "Millimeters".into(),
+ "100" => "100%".into(),
+ "200" => "200%".into(),
+ "8" => "8 Bits/Channel".into(),
+ "16" => "16 Bits/Channel".into(),
+ "postScript" => "PostScript (72 points/inch)".into(),
+ "traditional" => "Traditional (72.27 points/inch)".into(),
+ v => humanize(v),
+ }
+}
+
+fn color_of(s: &str) -> Color32 {
+ prefs::parse_hex(s).map_or(Color32::GRAY, |c| Color32::from_rgb(c[0], c[1], c[2]))
+}
+
+/// Preferences: section list on the left, the section's settings on the right.
+fn prefs_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let mut section = f.get("section").and_then(Value::as_str).unwrap_or("general").to_string();
+ let mut values = f.get("values").cloned().unwrap_or(Value::Null);
+ ui.horizontal_top(|ui| {
+ // Section list.
+ ui.vertical(|ui| {
+ ui.set_width(170.0);
+ for (id, title) in SECTIONS {
+ let sel = section == id;
+ let (rect, resp) = ui.allocate_exact_size(vec2(170.0, 22.0), Sense::click());
+ if sel {
+ ui.painter().rect_filled(rect, t.radius_sm, t.row_selected);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(rect, t.radius_sm, t.hover);
+ }
+ ui.painter().text(rect.left_center() + vec2(8.0, 0.0), egui::Align2::LEFT_CENTER, title, crate::theme::medium(12.5), if sel { t.text } else { t.text_dim });
+ if resp.clicked() {
+ section = id.to_string();
+ }
+ }
+ });
+ crate::widgets::vline(ui, 420.0);
+ ui.vertical(|ui| {
+ ui.set_width(540.0);
+ let title = SECTIONS.iter().find(|(id, _)| *id == section).map_or("General", |(_, t)| *t);
+ ui.label(RichText::new(title).font(crate::theme::semibold(14.0)).color(t.text));
+ ui.add_space(6.0);
+ egui::ScrollArea::vertical().max_height(390.0).id_salt("prefs-scroll").show(ui, |ui| {
+ let order: Vec<String> = f.get("__order").and_then(|o| o.get(&section)).and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
+ if let Some(obj) = values.get_mut(&section).and_then(Value::as_object_mut) {
+ section_fields(ui, &section, obj, &order);
+ }
+ ui.add_space(8.0);
+ if crate::widgets::secondary_button(ui, "Reset Section", 110.0).clicked()
+ && let Some(def) = prefs::Preferences::default().get(&section)
+ {
+ values[&section] = def;
+ }
+ });
+ });
+ });
+ f.insert("section".into(), json!(section));
+ f.insert("values".into(), values);
+}
+
+/// Generic editor for a section's fields: checkboxes, dropdowns for choices, colour swatches,
+/// number fields with the preference's range, text fields.
+fn section_fields(ui: &mut egui::Ui, section: &str, obj: &mut Map<String, Value>, order: &[String]) {
+ let t = Tokens::get(ui.ctx());
+ let mut keys: Vec<String> = order.iter().filter(|k| obj.contains_key(*k)).cloned().collect();
+ keys.extend(obj.keys().filter(|k| !order.contains(k)).cloned());
+ egui::Grid::new(("prefs-grid", section)).num_columns(2).spacing([14.0, 7.0]).show(ui, |ui| {
+ for k in keys {
+ let path = format!("{section}.{k}");
+ let v = obj.get(&k).cloned().unwrap_or(Value::Null);
+ let label = humanize(&k);
+ match &v {
+ Value::Bool(b) => {
+ ui.label("");
+ let mut b = *b;
+ crate::widgets::checkbox(ui, &mut b, &label);
+ obj.insert(k, json!(b));
+ }
+ Value::String(s) if prefs::choices(&path).is_some() => {
+ ui.label(RichText::new(label).color(t.text_dim));
+ let opts = prefs::choices(&path).unwrap_or(&[]);
+ let labels: Vec<String> = opts.iter().map(|o| choice_label(o)).collect();
+ let pairs: Vec<(String, &str)> = opts.iter().map(|o| o.to_string()).zip(labels.iter().map(String::as_str)).collect();
+ let mut cur = s.clone();
+ crate::widgets::dropdown(ui, &format!("pref-{path}"), &mut cur, &pairs, 220.0);
+ obj.insert(k, json!(cur));
+ }
+ Value::String(s) if prefs::is_color(&path) => {
+ ui.label(RichText::new(label).color(t.text_dim));
+ let c = prefs::parse_hex(s).unwrap_or([128, 128, 128]);
+ let mut rgb = c;
+ ui.horizontal(|ui| {
+ ui.color_edit_button_srgb(&mut rgb);
+ ui.label(RichText::new(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])).font(crate::theme::mono(11.5)).color(t.text_dim));
+ });
+ obj.insert(k, json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])));
+ let _ = color_of(s);
+ }
+ Value::String(s) => {
+ ui.label(RichText::new(label).color(t.text_dim));
+ let mut s = s.clone();
+ ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0));
+ obj.insert(k, json!(s));
+ }
+ Value::Number(n) => {
+ ui.label(RichText::new(label).color(t.text_dim));
+ let (lo, hi) = prefs::range(&path).unwrap_or((-1e9, 1e9));
+ if n.is_u64() || n.is_i64() {
+ let mut x = n.as_i64().unwrap_or(0);
+ ui.add(egui::DragValue::new(&mut x).range(lo as i64..=hi as i64));
+ obj.insert(k, json!(x));
+ } else {
+ let mut x = n.as_f64().unwrap_or(0.0);
+ ui.add(egui::DragValue::new(&mut x).range(lo..=hi).speed(0.1).max_decimals(3));
+ obj.insert(k, json!(x));
+ }
+ }
+ Value::Array(items) if k == "disks" => {
+ ui.label(RichText::new("Scratch disks").color(t.text_dim));
+ let mut items = items.clone();
+ ui.vertical(|ui| {
+ for d in &mut items {
+ ui.horizontal(|ui| {
+ let mut on = d.get("enabled").and_then(Value::as_bool).unwrap_or(false);
+ let mut path = d.get("path").and_then(Value::as_str).unwrap_or("").to_string();
+ crate::widgets::checkbox(ui, &mut on, "");
+ ui.add(egui::TextEdit::singleline(&mut path).desired_width(240.0));
+ *d = json!({"enabled": on, "path": path});
+ });
+ }
+ if ui.small_button("Add disk").clicked() {
+ items.push(json!({"enabled": true, "path": ""}));
+ }
+ });
+ obj.insert(k, Value::Array(items));
+ }
+ Value::Array(items) => {
+ ui.label(RichText::new(label).color(t.text_dim));
+ ui.label(RichText::new(format!("{} item{}", items.len(), if items.len() == 1 { "" } else { "s" })).color(t.text_faint));
+ if !items.is_empty() && ui.small_button("Clear").clicked() {
+ obj.insert(k, json!([]));
+ }
+ }
+ _ => continue,
+ }
+ ui.end_row();
+ }
+ });
+}
+
+/// Keyboard Shortcuts and Menus: a searchable list of commands by menu with editable shortcuts
+/// (click a shortcut, press keys; ⌫ removes it), menu visibility and colours, toolbar tools.
+fn shortcuts_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let mut tab = f.get("tab").and_then(Value::as_u64).unwrap_or(0);
+ ui.horizontal(|ui| {
+ for (i, name) in ["Keyboard Shortcuts", "Menus", "Toolbar"].iter().enumerate() {
+ if crate::widgets::pill_tab(ui, name, tab == i as u64).clicked() {
+ tab = i as u64;
+ f.insert("capture".into(), json!(false));
+ }
+ }
+ });
+ f.insert("tab".into(), json!(tab));
+ ui.add_space(6.0);
+ if tab == 2 {
+ toolbar_tab(ui, f);
+ return;
+ }
+ let mut filter = f.get("filter").and_then(Value::as_str).unwrap_or("").to_string();
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Search").color(t.text_dim));
+ ui.add(egui::TextEdit::singleline(&mut filter).desired_width(260.0).hint_text("command or shortcut"));
+ });
+ f.insert("filter".into(), json!(filter));
+ let mut overrides: BTreeMap<String, String> = f.get("overrides").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
+ let mut hidden: Vec<String> = f.get("hidden").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
+ let mut colors: BTreeMap<String, String> = f.get("colors").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
+ let mut selected = f.get("selected").and_then(Value::as_str).unwrap_or("").to_string();
+ let mut capture = f.get("capture").and_then(Value::as_bool).unwrap_or(false);
+ let mut message = f.get("message").and_then(Value::as_str).unwrap_or("").to_string();
+ let items = shortcut_items(app);
+ let eff = |overrides: &BTreeMap<String, String>, id: &str, def: &Option<String>| -> Option<String> {
+ match overrides.get(id) {
+ Some(s) if s.is_empty() => None,
+ Some(s) => Some(s.clone()),
+ None => def.clone(),
+ }
+ };
+ // Key capture for the selected command.
+ if capture && tab == 0 && !selected.is_empty() {
+ let pressed = ui.input(|i| i.events.iter().find_map(|e| match e {
+ egui::Event::Key { key, pressed: true, modifiers, .. } => Some((*key, *modifiers)),
+ _ => None,
+ }));
+ if let Some((key, m)) = pressed {
+ ui.input_mut(|i| {
+ i.consume_key(m, key);
+ });
+ if key == egui::Key::Escape {
+ capture = false;
+ } else if matches!(key, egui::Key::Backspace | egui::Key::Delete) && m.is_none() {
+ overrides.insert(selected.clone(), String::new());
+ capture = false;
+ message = "Shortcut removed.".into();
+ } else if let Some(sc) = shortcut_text(key, m) {
+ let clash: Vec<String> = items.iter().filter(|(id, _, _, def)| *id != selected && eff(&overrides, id, def).as_deref().and_then(prefs::normalize_shortcut) == Some(sc.clone())).map(|(_, label, path, _)| format!("{} › {}", path.join(" › "), label.trim_end_matches('…'))).collect();
+ overrides.insert(selected.clone(), sc.clone());
+ message = if clash.is_empty() { format!("{} assigned.", crate::shortcuts::pretty(&sc)) } else { format!("{} is already in use by {} and will be removed from it when you click OK.", crate::shortcuts::pretty(&sc), clash.join(", ")) };
+ capture = false;
+ }
+ }
+ }
+ let needle = filter.to_ascii_lowercase();
+ egui::ScrollArea::vertical().max_height(420.0).id_salt("shortcuts-scroll").show(ui, |ui| {
+ let mut last_top = String::new();
+ egui::Grid::new("shortcut-grid").num_columns(3).spacing([12.0, 3.0]).striped(true).show(ui, |ui| {
+ for (id, label, path, def) in &items {
+ let cur = eff(&overrides, id, def);
+ let hay = format!("{} {} {}", path.join(" "), label, cur.clone().unwrap_or_default()).to_ascii_lowercase();
+ if !needle.is_empty() && !hay.contains(&needle) && !id.to_ascii_lowercase().contains(&needle) {
+ continue;
+ }
+ if tab == 0 && path.is_empty() && def.is_none() && cur.is_none() {
+ continue;
+ }
+ let top = path.first().cloned().unwrap_or_else(|| "Other".into());
+ if top != last_top {
+ ui.label(RichText::new(&top).font(crate::theme::semibold(12.5)).color(t.text));
+ ui.label("");
+ ui.label("");
+ ui.end_row();
+ last_top = top;
+ }
+ let name = if path.len() > 1 { format!("{} › {}", path[1..].join(" › "), label) } else { label.clone() };
+ let sel = selected == *id;
+ if ui.selectable_label(sel, RichText::new(format!(" {name}")).color(t.text_dim)).clicked() {
+ selected = id.clone();
+ }
+ if tab == 0 {
+ let text = if sel && capture { "Press keys…".to_string() } else { cur.as_deref().map(crate::shortcuts::pretty).unwrap_or_default() };
+ let changed = overrides.contains_key(id);
+ let r = ui.add(egui::Button::new(RichText::new(text).size(12.0).color(if changed { t.accent_text } else { t.text })).min_size(vec2(120.0, 18.0)));
+ if r.clicked() {
+ selected = id.clone();
+ capture = true;
+ message.clear();
+ }
+ ui.label(if changed { RichText::new("modified").color(t.text_faint).size(10.5) } else { RichText::new("") });
+ } else {
+ let mut visible = !hidden.contains(id);
+ crate::widgets::checkbox(ui, &mut visible, "Visible");
+ if visible {
+ hidden.retain(|h| h != id);
+ } else if !hidden.contains(id) {
+ hidden.push(id.clone());
+ }
+ let mut col = colors.get(id).cloned().unwrap_or_else(|| "none".into());
+ let opts: Vec<(String, &str)> = ["none", "red", "orange", "yellow", "green", "blue", "violet", "gray"].iter().map(|c| (c.to_string(), *c)).collect();
+ crate::widgets::dropdown(ui, &format!("menu-color-{id}"), &mut col, &opts, 90.0);
+ if col == "none" {
+ colors.remove(id);
+ } else {
+ colors.insert(id.clone(), col);
+ }
+ }
+ ui.end_row();
+ }
+ });
+ });
+ ui.add_space(6.0);
+ if tab == 0 {
+ ui.horizontal(|ui| {
+ let has_sel = !selected.is_empty();
+ if ui.add_enabled(has_sel, egui::Button::new("Use Default")).clicked() {
+ overrides.remove(&selected);
+ message = "Default restored.".into();
+ }
+ if ui.add_enabled(has_sel, egui::Button::new("Delete Shortcut")).clicked() {
+ overrides.insert(selected.clone(), String::new());
+ message = "Shortcut removed.".into();
+ }
+ if ui.button("Reset All to Defaults").clicked() {
+ overrides.clear();
+ message = "All shortcuts reset to Photoshop defaults.".into();
+ }
+ });
+ } else if ui.button("Show All Menu Items").clicked() {
+ hidden.clear();
+ colors.clear();
+ }
+ if !message.is_empty() {
+ ui.label(RichText::new(&message).color(if message.contains("already in use") { t.warning } else { t.text_dim }));
+ }
+ f.insert("overrides".into(), json!(overrides));
+ f.insert("hidden".into(), json!(hidden));
+ f.insert("colors".into(), json!(colors));
+ f.insert("selected".into(), json!(selected));
+ f.insert("capture".into(), json!(capture));
+ f.insert("message".into(), json!(message));
+}
+
+fn toolbar_tab(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let mut hidden: Vec<String> = f.get("toolbarHidden").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
+ egui::ScrollArea::vertical().max_height(380.0).id_salt("toolbar-scroll").show(ui, |ui| {
+ egui::Grid::new("toolbar-grid").num_columns(2).spacing([16.0, 4.0]).show(ui, |ui| {
+ for tool in crate::state::Tool::ALL {
+ let name = format!("{tool:?}");
+ let mut on = !hidden.contains(&name);
+ crate::widgets::checkbox(ui, &mut on, tool.label());
+ if on {
+ hidden.retain(|h| *h != name);
+ } else if !hidden.contains(&name) {
+ hidden.push(name);
+ }
+ let k = tool.key();
+ ui.label(if k == '\0' { String::new() } else { k.to_string() });
+ ui.end_row();
+ }
+ });
+ });
+ if ui.button("Restore Defaults").clicked() {
+ hidden.clear();
+ }
+ f.insert("toolbarHidden".into(), json!(hidden));
+}
+
+fn presets_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let mut kind = f.get("kind").and_then(Value::as_str).unwrap_or("brushes").to_string();
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Preset Type").color(t.text_dim));
+ let opts = [("brushes".to_string(), "Brushes"), ("customShapes".to_string(), "Custom Shapes"), ("patterns".to_string(), "Patterns")];
+ crate::widgets::dropdown(ui, "preset-kind", &mut kind, &opts, 180.0);
+ });
+ let list = app.session.execute("edit.presets.presetManager", json!({"kind": kind})).ok().and_then(|v| v.get(&kind).cloned()).and_then(|v| serde_json::from_value::<Vec<String>>(v).ok()).unwrap_or_default();
+ let mut selected = f.get("selected").and_then(Value::as_u64).unwrap_or(0) as usize;
+ egui::ScrollArea::vertical().max_height(260.0).id_salt("preset-list").show(ui, |ui| {
+ for (i, name) in list.iter().enumerate() {
+ if ui.selectable_label(i == selected, name).clicked() {
+ selected = i;
+ f.insert("newName".into(), json!(name));
+ }
+ }
+ if list.is_empty() {
+ ui.label(RichText::new("No presets of this type.").color(t.text_faint));
+ }
+ });
+ let mut new_name = f.get("newName").and_then(Value::as_str).unwrap_or("").to_string();
+ ui.horizontal(|ui| {
+ ui.add(egui::TextEdit::singleline(&mut new_name).desired_width(200.0));
+ if ui.add_enabled(selected < list.len() && !new_name.trim().is_empty(), egui::Button::new("Rename")).clicked() {
+ let _ = app.run("edit.presets.presetManager", json!({"action": "rename", "kind": kind, "index": selected, "newName": new_name}));
+ }
+ if ui.add_enabled(selected < list.len(), egui::Button::new("Delete")).clicked() {
+ let _ = app.run("edit.presets.presetManager", json!({"action": "delete", "kind": kind, "index": selected}));
+ }
+ });
+ f.insert("kind".into(), json!(kind));
+ f.insert("selected".into(), json!(selected));
+ f.insert("newName".into(), json!(new_name));
+}
+
+fn presets_io_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let mut action = f.get("action").and_then(Value::as_str).unwrap_or("export").to_string();
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Action").color(t.text_dim));
+ crate::widgets::dropdown(ui, "presets-io", &mut action, &[("export".to_string(), "Export Presets"), ("import".to_string(), "Import Presets")], 180.0);
+ });
+ for (k, label) in [("brushes", "Brushes"), ("customShapes", "Custom Shapes")] {
+ let mut on = f.get(k).and_then(Value::as_bool).unwrap_or(true);
+ crate::widgets::checkbox(ui, &mut on, label);
+ f.insert(k.into(), json!(on));
+ }
+ f.insert("action".into(), json!(action));
+}
+
+fn mismatch_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ ui.label(RichText::new(f.get("message").and_then(Value::as_str).unwrap_or("")).color(t.text));
+ ui.add_space(6.0);
+ let mut action = f.get("action").and_then(Value::as_str).unwrap_or("preserve").to_string();
+ let missing = f.get("missing").and_then(Value::as_bool).unwrap_or(false);
+ let opts: &[(&str, &str)] = if missing {
+ &[("preserve", "Leave as is (don't color manage)"), ("assignWorking", "Assign working space")]
+ } else {
+ &[("preserve", "Use the embedded profile (instead of the working space)"), ("convert", "Convert document's colors to the working space"), ("discard", "Discard the embedded profile (don't color manage)")]
+ };
+ for (v, label) in opts {
+ ui.radio_value(&mut action, v.to_string(), *label);
+ }
+ f.insert("action".into(), json!(action));
+}
+
+// ------------------------------------------------------------------ confirm
+
+/// OK on one of our dialogs.
+pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") {
+ "prefs" => {
+ let values = f.get("values").cloned().unwrap_or(Value::Null);
+ app.run("prefs.set", json!({"path": "", "value": values}))
+ }
+ "shortcuts" => {
+ let overrides = f.get("overrides").cloned().unwrap_or(json!({}));
+ // Shortcuts moved to another command are taken from their old owner (shell
+ // commands included, which the engine doesn't know).
+ let mut ov: BTreeMap<String, String> = serde_json::from_value(overrides).unwrap_or_default();
+ let items = shortcut_items(app);
+ let changed: Vec<(String, String)> = ov.iter().filter(|(_, s)| !s.is_empty()).map(|(k, s)| (k.clone(), s.clone())).collect();
+ for (id, sc) in changed {
+ for (other, _, _, def) in &items {
+ if *other != id && !ov.contains_key(other) && def.as_deref().and_then(prefs::normalize_shortcut).as_deref() == prefs::normalize_shortcut(&sc).as_deref() {
+ ov.insert(other.clone(), String::new());
+ }
+ }
+ }
+ let hidden = f.get("hidden").cloned().unwrap_or(json!([]));
+ let colors = f.get("colors").cloned().unwrap_or(json!({}));
+ let toolbar = f.get("toolbarHidden").cloned().unwrap_or(json!([]));
+ app.run("edit.keyboardShortcuts", json!({"reset": true, "set": ov, "allowUnknown": true, "removeConflicts": false}))?;
+ app.run("prefs.set", json!({"values": {"menus": {"hidden": hidden, "colors": colors}, "toolbar": {"hidden": toolbar}}}))
+ }
+ "presets" => Ok(Value::Null),
+ "presetsIO" => {
+ let kinds: Vec<&str> = ["brushes", "customShapes"].into_iter().filter(|k| f.get(*k).and_then(Value::as_bool).unwrap_or(true)).collect();
+ if f.get("action").and_then(Value::as_str) == Some("import") {
+ let (name, bytes) = app.services.pick_open.as_mut().and_then(|p| p()).ok_or("cancelled")?;
+ let text = String::from_utf8(bytes).map_err(|_| format!("{name} is not a preset file"))?;
+ app.run("edit.presets.exportImportPresets", json!({"action": "import", "kinds": kinds, "data": text}))
+ } else {
+ let out = app.run("edit.presets.exportImportPresets", json!({"action": "export", "kinds": kinds}))?;
+ let text = serde_json::to_string_pretty(&out["data"]).map_err(|e| e.to_string())?;
+ let path = app.services.pick_save.as_mut().and_then(|p| p("Presets.pcpresets")).ok_or("cancelled")?;
+ let write = app.services.write.as_mut().ok_or("no writer configured")?;
+ write(&path, text.as_bytes())?;
+ app.ui.status = format!("Exported presets to {path}");
+ Ok(json!({"path": path}))
+ }
+ }
+ "mismatch" => {
+ let action = f.get("action").and_then(Value::as_str).unwrap_or("preserve");
+ let applied = f.get("applied").and_then(Value::as_str).unwrap_or("preserve");
+ if action == applied {
+ return Ok(json!({"action": action}));
+ }
+ app.run("color.profileMismatch", json!({"action": action}))
+ }
+ _ => Err("unknown dialog".into()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::{Arc, Mutex};
+
+ fn app_with_store() -> (PhotocraftApp, Arc<Mutex<Option<String>>>) {
+ app_with_saved(None)
+ }
+
+ fn app_with_saved(text: Option<String>) -> (PhotocraftApp, Arc<Mutex<Option<String>>>) {
+ let store: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(text));
+ let (a, b) = (store.clone(), store.clone());
+ let services = crate::Services {
+ load_prefs: Some(Box::new(move || a.lock().unwrap().clone())),
+ save_prefs: Some(Box::new(move |s: &str| {
+ *b.lock().unwrap() = Some(s.to_string());
+ Ok(())
+ })),
+ ..Default::default()
+ };
+ (PhotocraftApp::new(photocraft_engine::Session::new(), services), store)
+ }
+
+ #[test]
+ fn preferences_persist_through_services_and_theme_follows() {
+ let (mut app, store) = app_with_store();
+ let ctx = egui::Context::default();
+ tick(&mut app, &ctx);
+ app.run("prefs.set", json!({"values": {"interface.theme": "studioLight", "performance.historyStates": 12}})).unwrap();
+ tick(&mut app, &ctx);
+ assert_eq!(app.ui.theme, ThemeKind::StudioLight);
+ let saved = store.lock().unwrap().clone().unwrap();
+ assert!(saved.contains("\"historyStates\": 12"));
+ // A new app instance loads them.
+ let (mut app2, store2) = app_with_saved(Some(saved));
+ tick(&mut app2, &ctx);
+ assert_eq!(app2.session.prefs().performance.history_states, 12);
+ assert_eq!(app2.ui.theme, ThemeKind::StudioLight);
+ // Picking a theme from the Window menu becomes the preference.
+ crate::menus::invoke(&mut app2, &ctx, "window.theme.classic", json!({})).unwrap();
+ tick(&mut app2, &ctx);
+ assert_eq!(app2.session.prefs().interface.theme, Theme::Classic);
+ assert!(store2.lock().unwrap().as_ref().unwrap().contains("classic"));
+ }
+
+ #[test]
+ fn preferences_dialog_round_trip() {
+ let (mut app, _) = app_with_store();
+ let ctx = egui::Context::default();
+ let r = crate::menus::invoke(&mut app, &ctx, "edit.preferences.cursors", json!({})).unwrap();
+ let id = r["dialog"].as_u64().unwrap();
+ let d = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().clone();
+ assert_eq!(d.fields["section"], "cursors");
+ let mut values = d.fields["values"].clone();
+ values["cursors"]["painting"] = json!("fullSizeTip");
+ values["unitsAndRulers"]["rulers"] = json!("inches");
+ app.ui.dialog_mut(id).unwrap().fields.insert("values".into(), values);
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ assert_eq!(app.session.prefs().cursors.painting, prefs::PaintingCursor::FullSizeTip);
+ assert_eq!(app.session.prefs().units_and_rulers.rulers, prefs::Unit::Inches);
+ // Invalid values are rejected and nothing changes.
+ let id = open_preferences(&mut app, "performance");
+ let mut values = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["values"].clone();
+ values["performance"]["historyStates"] = json!(0);
+ app.ui.dialog_mut(id).unwrap().fields.insert("values".into(), values);
+ assert!(crate::dialogs::confirm(&mut app, id).is_err());
+ assert_eq!(app.session.prefs().performance.history_states, 50);
+ }
+
+ #[test]
+ fn shortcut_dialog_moves_shortcuts_and_shell_dispatch_follows() {
+ let (mut app, _) = app_with_store();
+ let ctx = egui::Context::default();
+ let id = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ // ⌘O (File › Open, a shell command) given to Layer › New › Layer.
+ app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!({"layer.new.layer": "Cmd+O"}));
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ assert_eq!(effective_shortcut(&app, "layer.new.layer", None).as_deref(), Some("Cmd+O"));
+ assert_eq!(effective_shortcut(&app, "file.open", Some("Cmd+O")), None, "taken from File › Open");
+ // Menu items show the effective shortcut.
+ let items = crate::menus::menu_items(&app);
+ assert!(items.iter().any(|i| i.id == "layer.new.layer" && i.shortcut.as_deref() == Some("Cmd+O")));
+ assert!(items.iter().any(|i| i.id == "file.open" && i.shortcut.is_none()));
+ assert_eq!(shortcut_text(egui::Key::K, egui::Modifiers { command: true, shift: true, ..Default::default() }).as_deref(), Some("Cmd+Shift+K"));
+ }
+
+ #[test]
+ fn hidden_menu_items_disappear() {
+ let (mut app, _) = app_with_store();
+ app.run("edit.menus", json!({"hide": ["edit.fade"]})).unwrap();
+ assert!(!crate::menus::menu_items(&app).iter().any(|i| i.id == "edit.fade"));
+ }
+
+ #[test]
+ fn autosave_runs_for_dirty_documents() {
+ type Saved = Arc<Mutex<Vec<(u64, u64)>>>;
+ let saved: Saved = Arc::default();
+ let s2 = saved.clone();
+ let services = crate::Services {
+ autosave: Some(Box::new(move |doc: &Arc<photocraft_doc::Document>, rev: u64, _path: Option<&str>| {
+ s2.lock().unwrap().push((doc.id.0, rev));
+ Ok(())
+ })),
+ ..Default::default()
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
+ let ctx = egui::Context::default();
+ app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
+ tick(&mut app, &ctx);
+ autosave_now(&mut app);
+ tick(&mut app, &ctx);
+ assert!(saved.lock().unwrap().is_empty(), "clean documents are not autosaved");
+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ autosave_now(&mut app);
+ tick(&mut app, &ctx);
+ assert_eq!(saved.lock().unwrap().len(), 1);
+ autosave_now(&mut app);
+ tick(&mut app, &ctx);
+ assert_eq!(saved.lock().unwrap().len(), 1, "unchanged since the last autosave");
+ app.run("prefs.set", json!({"path": "fileHandling.autosave", "value": false})).unwrap();
+ app.run("edit.fill", json!({"color": "#00ff00"})).unwrap();
+ autosave_now(&mut app);
+ tick(&mut app, &ctx);
+ assert_eq!(saved.lock().unwrap().len(), 1, "autosave off");
+ }
+
+ #[test]
+ fn edit_dialogs_open() {
+ let (mut app, _) = app_with_store();
+ let ctx = egui::Context::default();
+ app.run("file.new", json!({"width": 32, "height": 32})).unwrap();
+ app.sync_views();
+ let d = crate::menus::invoke(&mut app, &ctx, "edit.colorSettings", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ assert_eq!(app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["workingRgb"], "srgb");
+ assert!(crate::menus::invoke(&mut app, &ctx, "edit.fade", json!({})).is_err());
+ app.run("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap();
+ let d = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ assert_eq!(app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["__preview"], true);
+ crate::dialogs::confirm(&mut app, d).unwrap();
+ let d = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareScale", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ assert_eq!(app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["width"], 8);
+ let d = crate::menus::invoke(&mut app, &ctx, "edit.presets.presetManager", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ assert!(crate::dialogs::confirm(&mut app, d).is_ok());
+ }
+}
diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/rulers.rs
index 04ab3e57e..f42c118a4 100644
--- a/crates/ui-egui/src/rulers.rs
+++ b/crates/ui-egui/src/rulers.rs
@@ -11,8 +11,41 @@ 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 `#rrggbb` preference colour.
+fn pref_color(s: &str, fallback: Color32) -> Color32 {
+ photocraft_engine::prefs::parse_hex(s).map_or(fallback, |c| Color32::from_rgb(c[0], c[1], c[2]))
+}
+
+/// Draw a line in a Guides/Grid preference style (lines, dashed lines, dots).
+fn styled_line(painter: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke, style: photocraft_engine::prefs::LineStyle) {
+ use photocraft_engine::prefs::LineStyle;
+ match style {
+ LineStyle::Lines => {
+ painter.line_segment([a, b], stroke);
+ }
+ LineStyle::Dashed => {
+ painter.extend(egui::Shape::dashed_line(&[a, b], stroke, 4.0, 3.0));
+ }
+ LineStyle::Dots => {
+ painter.extend(egui::Shape::dotted_line(&[a, b], stroke.color, 3.0, 0.6));
+ }
+ }
+}
+
+/// Ruler step in units so labelled ticks are at least `min` units apart: …0.1, 0.25, 0.5, 1, 2, 5,
+/// 10… (whole steps only for pixels).
+fn nice_step(min: f64, whole: bool) -> f64 {
+ let mut step = if whole { 1.0 } else { 0.001 };
+ loop {
+ for m in [1.0, 2.0, 2.5, 5.0] {
+ if (m != 2.5 || !whole) && step * m >= min {
+ return step * m;
+ }
+ }
+ step *= 10.0;
+ }
+}
/// A guide being dragged: from a ruler (new) or an existing one (index).
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -28,37 +61,33 @@ pub fn content_rect(app: &PhotocraftApp, rect: Rect) -> Rect {
}
/// Tick step (document px) so major ticks are at least ~60 screen px apart: 1, 2, 5, 10, 20, 50…
+#[cfg(test)]
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;
- }
+ nice_step(60.0 / zoom.max(1e-4) as f64, true)
}
-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;
+/// View › Show › Grid, from Preferences › Guides, Grid & Slices (spacing, subdivisions, colour,
+/// style). Photoshop's default is a gridline every inch with 4 subdivisions.
+pub fn draw_grid(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) {
+ let g = &app.session.prefs().guides_grid_and_slices;
+ let ppi = app.session.prefs().units_and_rulers.point_size.per_inch();
+ let major = g.major_px(doc.resolution_dpi.max(1.0) as f64, doc.size.width as f64, ppi);
+ let minor = major / g.subdivisions.max(1) as f64;
+ let base = pref_color(&g.grid_color, Color32::from_gray(140));
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 {
+ for (step, alpha) in [(minor, 0.45f32), (major, 1.0)] {
+ if step * (xf.zoom as f64) < 6.0 || (alpha < 1.0 && g.subdivisions <= 1) {
continue;
}
- let st = Stroke::new(1.0, Color32::from_rgba_unmultiplied(128, 128, 128, alpha));
+ let st = Stroke::new(1.0, base.gamma_multiply(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);
+ styled_line(painter, xf.to_screen(x as f32, 0.0), xf.to_screen(x as f32, h as f32), st, g.grid_style);
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);
+ styled_line(painter, xf.to_screen(0.0, y as f32), xf.to_screen(w as f32, y as f32), st, g.grid_style);
y += step;
}
}
@@ -67,13 +96,15 @@ pub fn draw_grid(painter: &egui::Painter, xf: &ViewXform, doc: &Document) {
pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) {
let clip = painter.clip_rect();
let drag = app.guide_drag;
+ let g = &app.session.prefs().guides_grid_and_slices;
+ let (guide, style) = (pref_color(&g.guide_color, Color32::from_rgb(74, 255, 255)), g.guide_style);
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));
+ styled_line(painter, pos2(x, clip.top()), pos2(x, clip.bottom()), Stroke::new(1.0, color), style);
} 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));
+ styled_line(painter, pos2(clip.left(), y), pos2(clip.right(), y), Stroke::new(1.0, color), style);
}
};
if app.ui.extras.guides {
@@ -82,12 +113,12 @@ pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,
if drag.is_some_and(|d| d.vertical == vertical && d.index == Some(i)) {
continue;
}
- line(vertical, *p as f64, GUIDE);
+ line(vertical, *p as f64, guide);
}
}
}
if let Some(d) = drag {
- line(d.vertical, d.pos, GUIDE);
+ line(d.vertical, d.pos, guide);
}
}
@@ -143,38 +174,49 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
}
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);
+ // Preferences › Units & Rulers: labels in the ruler unit (percent of the document's side).
+ let ur = &app.session.prefs().units_and_rulers;
+ let (unit, ppi) = (ur.rulers, ur.point_size.per_inch());
+ let (dpi, size) = app.session.active().map_or((72.0, [1.0, 1.0]), |d| (d.doc.resolution_dpi.max(1.0) as f64, [d.doc.size.width as f64, d.doc.size.height as f64]));
+ let whole = unit == photocraft_engine::prefs::Unit::Pixels;
+ let label = |v: f64, step: f64| -> String {
+ if step >= 1.0 || whole { format!("{}", v.round() as i64) } else { crate::widgets::fmt_num2(v) }
+ };
+ for (vertical, extent) in [(false, size[0]), (true, size[1])] {
+ let px_per_unit = unit.to_px(1.0, dpi, extent, ppi).max(1e-9);
+ let step = nice_step(60.0 / (xf.zoom as f64 * px_per_unit).max(1e-6), whole);
+ let (d0, d1) = if vertical { (xf.to_doc(left.left_top())[1], xf.to_doc(left.left_bottom())[1]) } else { (xf.to_doc(top.left_top())[0], xf.to_doc(top.right_top())[0]) };
+ let (u0, u1) = (d0 / px_per_unit, d1 / px_per_unit);
+ let mut v = (u0 / step).floor() * step;
+ while v <= u1 {
+ let at = |u: f64| -> f32 {
+ let px = (u * px_per_unit) as f32;
+ if vertical { xf.to_screen(0.0, px).y } else { xf.to_screen(px, 0.0).x }
+ };
+ let c = at(v);
+ if vertical {
+ p.line_segment([pos2(left.right() - RULER, c), pos2(left.right(), c)], tick);
+ // Labels stacked, as in Photoshop.
+ for (i, ch) in label(v, step).chars().enumerate() {
+ p.text(pos2(left.left() + 3.0, c + 2.0 + i as f32 * 8.5), Align2::LEFT_TOP, ch, font.clone(), t.text_dim);
+ }
+ } else {
+ p.line_segment([pos2(c, top.bottom() - RULER), pos2(c, top.bottom())], tick);
+ p.text(pos2(c + 2.0, top.top() + 1.0), Align2::LEFT_TOP, label(v, step), font.clone(), t.text_dim);
+ }
+ for k in 1..10 {
+ let m = at(v + step * k as f64 / 10.0);
+ let len = if k == 5 { 6.0 } else { 3.0 };
+ if vertical {
+ p.line_segment([pos2(left.right() - len, m), pos2(left.right(), m)], tick);
+ } else {
+ p.line_segment([pos2(m, top.bottom() - len), pos2(m, top.bottom())], tick);
+ }
+ }
+ v += step;
}
- v += step;
}
// Pointer position markers.
if let Some(h) = ui.ctx().pointer_hover_pos().filter(|h| full.contains(*h)) {
@@ -190,7 +232,8 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
}
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] } });
+ let pos = crate::snap_ui::snap_guide(app, vertical, if vertical { d[0] } else { d[1] });
+ app.guide_drag = Some(GuideDrag { vertical, index: None, pos });
}
if resp.drag_stopped()
&& let Some(d) = app.guide_drag.take()
@@ -205,6 +248,15 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
mod tests {
use super::*;
+ #[test]
+ fn unit_steps_allow_fractions() {
+ assert_eq!(nice_step(0.3, false), 0.5);
+ assert_eq!(nice_step(0.2, false), 0.2);
+ assert_eq!(nice_step(0.22, false), 0.25);
+ assert_eq!(nice_step(0.3, true), 1.0);
+ assert_eq!(nice_step(23.0, true), 50.0);
+ }
+
#[test]
fn ticks_follow_1_2_5_series() {
assert_eq!(tick_step(1.0), 100.0);
diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs
index 155c26ff2..9bb064d2f 100644
--- a/crates/ui-egui/src/shortcuts.rs
+++ b/crates/ui-egui/src/shortcuts.rs
@@ -75,10 +75,19 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
// 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.
+ // Edit › Keyboard Shortcuts overrides replace the defaults (and can bind any menu item).
+ let prefs = app.session.prefs();
let mut all: Vec<(String, KeyboardShortcut)> = crate::menus::UI_COMMANDS
.iter()
- .filter_map(|(id, _, _, sc)| Some((id.to_string(), parse((*sc)?)?)))
- .chain(photocraft_engine::command_specs().iter().filter_map(|c| Some((c.id.to_string(), parse(c.shortcut?)?))))
+ .filter_map(|(id, _, _, sc)| Some((id.to_string(), parse(prefs.shortcut(id, *sc)?)?)))
+ .chain(photocraft_engine::command_specs().iter().filter_map(|c| Some((c.id.to_string(), parse(prefs.shortcut(c.id, c.shortcut)?)?))))
+ .chain(
+ prefs
+ .shortcuts
+ .iter()
+ .filter(|(id, sc)| !sc.is_empty() && photocraft_engine::commands::find(id).is_none() && !crate::menus::UI_COMMANDS.iter().any(|c| c.0 == id.as_str()))
+ .filter_map(|(id, sc)| Some((id.clone(), parse(sc)?))),
+ )
.filter(|(_, sc)| sc.modifiers != Modifiers::NONE || !matches!(sc.logical_key, Key::X | Key::D))
.collect();
all.sort_by_key(|(_, sc)| std::cmp::Reverse(sc.modifiers.shift as u8 + sc.modifiers.alt as u8 + sc.modifiers.command as u8));
@@ -124,12 +133,17 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
return;
}
}
- // Tool keys; pressing the key of the current group cycles within it (Photoshop's Shift+key cycle).
+ // Tool keys; pressing the key of the current group cycles within it. With Preferences ›
+ // Tools › Use Shift Key for Tool Switch, only ⇧+key cycles and the plain key keeps the
+ // group's current tool.
+ let shift_switch = app.session.prefs().tools.use_shift_key_for_tool_switch;
for t in Tool::ALL {
let Some(k) = Key::from_name(&t.key().to_string()) else { continue };
- if pressed(k) {
+ let cycle_shift = shift_switch && ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, k));
+ if cycle_shift || 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) if shift_switch && !cycle_shift => group[i],
Some(i) => group[(i + 1) % group.len()],
None => group[0],
};
diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs
index 53d22764d..100e5763a 100644
--- a/crates/ui-egui/src/sizing.rs
+++ b/crates/ui-egui/src/sizing.rs
@@ -10,7 +10,33 @@ 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 UNITS: [(&str, &str); 7] = [("px", "Pixels"), ("percent", "Percent"), ("in", "Inches"), ("cm", "Centimeters"), ("mm", "Millimeters"), ("pt", "Points"), ("pica", "Picas")];
+
+/// Dialog unit for the Units & Rulers preference.
+fn pref_unit(u: photocraft_engine::prefs::Unit) -> &'static str {
+ use photocraft_engine::prefs::Unit;
+ match u {
+ Unit::Pixels => "px",
+ Unit::Percent => "percent",
+ Unit::Inches => "in",
+ Unit::Centimeters => "cm",
+ Unit::Millimeters => "mm",
+ Unit::Points => "pt",
+ Unit::Picas => "pica",
+ }
+}
+
+/// Image Size resampling for Preferences › General › Image Interpolation.
+fn pref_resample(i: photocraft_engine::prefs::Interpolation) -> &'static str {
+ use photocraft_engine::prefs::Interpolation;
+ match i {
+ Interpolation::Nearest => "nearest",
+ Interpolation::Bilinear => "bilinear",
+ Interpolation::BicubicSharper => "lanczos",
+ Interpolation::PreserveDetails => "preserveDetails",
+ _ => "bicubic",
+ }
+}
const ANCHORS: [&str; 9] = ["topLeft", "top", "topRight", "left", "center", "right", "bottomLeft", "bottom", "bottomRight"];
pub fn is_sizing(command: &str) -> bool {
@@ -18,6 +44,8 @@ pub fn is_sizing(command: &str) -> bool {
}
pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
+ let unit = pref_unit(app.session.prefs().units_and_rulers.rulers);
+ let resample = pref_resample(app.session.prefs().general.image_interpolation);
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…");
@@ -28,14 +56,14 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
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("__unit".into(), json!(unit));
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"));
+ f.insert("resample".into(), json!(resample));
} else {
f.insert("relative".into(), json!(false));
f.insert("anchor".into(), json!("center"));
@@ -54,6 +82,9 @@ fn to_unit(px: f64, unit: &str, orig: f64, res: f64) -> f64 {
"percent" => px / orig.max(1.0) * 100.0,
"in" => px / res.max(1.0),
"cm" => px / res.max(1.0) * 2.54,
+ "mm" => px / res.max(1.0) * 25.4,
+ "pt" => px / res.max(1.0) * 72.0,
+ "pica" => px / res.max(1.0) * 6.0,
_ => px,
}
}
@@ -63,6 +94,9 @@ fn from_unit(v: f64, unit: &str, orig: f64, res: f64) -> f64 {
"percent" => v * orig / 100.0,
"in" => v * res,
"cm" => v / 2.54 * res,
+ "mm" => v / 25.4 * res,
+ "pt" => v / 72.0 * res,
+ "pica" => v / 6.0 * res,
_ => v,
}
}
@@ -329,7 +363,7 @@ mod tests {
#[test]
fn unit_conversions_round_trip() {
- for unit in ["px", "percent", "in", "cm"] {
+ for unit in ["px", "percent", "in", "cm", "mm", "pt", "pica"] {
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}");
}
diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rs
new file mode 100644
index 000000000..f1bbbe612
--- /dev/null
+++ b/crates/ui-egui/src/smart_ui.rs
@@ -0,0 +1,106 @@
+//! Layers-panel pieces for smart objects: the thumbnail badge and the Smart Filters sub-rows
+//! (eye toggles; double-click a filter to re-open its dialog with the recorded parameters).
+
+use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};
+use photocraft_doc::{Layer, LayerContent, SmartObject};
+use serde_json::{Value, json};
+
+use crate::theme::Tokens;
+use crate::{PhotocraftApp, icons};
+
+/// Smart-object badge in the bottom-right corner of a layer thumbnail.
+pub fn thumb_badge(ui: &egui::Ui, l: &Layer, thumb: Rect) {
+ if !matches!(l.content, LayerContent::Smart(_)) {
+ return;
+ }
+ let t = Tokens::get(ui.ctx());
+ let r = Rect::from_min_size(pos2(thumb.right() - 9.0, thumb.bottom() - 9.0), vec2(11.0, 11.0));
+ ui.painter().rect_filled(r, 2.0, t.field);
+ ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
+ icons::paint(ui, r, "app-window", 9.0, t.icon);
+}
+
+/// The display name of a smart filter (its command's label without the ellipsis).
+fn filter_label(command: &str) -> String {
+ photocraft_engine::commands::find(command).map_or_else(|| command.rsplit('.').next().unwrap_or(command).to_string(), |c| c.label.trim_end_matches('…').to_string())
+}
+
+/// Smart Filters header + one row per filter (top filter first, as in Photoshop) under a smart
+/// layer. Edits are queued in `actions` as engine commands.
+pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize, actions: &mut Vec<(String, Value)>) {
+ let LayerContent::Smart(sm) = &l.content else { return };
+ if sm.smart_filters.is_empty() {
+ return;
+ }
+ let t = Tokens::get(ui.ctx());
+ let indent = 30.0 + depth as f32 * 14.0 + 34.0;
+ let rows = std::iter::once(None).chain((0..sm.smart_filters.len()).rev().map(Some));
+ for index in rows {
+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.35));
+ }
+ if t.pro {
+ ui.painter().line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator));
+ }
+ let (name, on) = match index {
+ None => ("Smart Filters".to_string(), sm.filters_enabled),
+ Some(i) => (filter_label(&sm.smart_filters[i].command), sm.smart_filters[i].visible && sm.filters_enabled),
+ };
+ let eye = Rect::from_min_size(pos2(rect.left() + 6.0, rect.center().y - 9.0), vec2(18.0, 18.0));
+ let eye_resp = ui.interact(eye, ui.id().with(("sf-eye", l.id.0, index)), Sense::click());
+ let shown = match index {
+ None => sm.filters_enabled,
+ Some(i) => sm.smart_filters[i].visible,
+ };
+ icons::paint(ui, eye, if shown { "eye" } else { "eye-off" }, 12.0, if shown { t.icon } else { t.text_faint });
+ if eye_resp.clicked() {
+ actions.push(match index {
+ None => ("layer.smartFilter.disableSmartFilters".into(), json!({"layer": l.id.0})),
+ Some(i) => ("layer.smartFilter.setVisible".into(), json!({"layer": l.id.0, "index": i})),
+ });
+ }
+ let x = rect.left() + indent + if index.is_none() { 0.0 } else { 16.0 };
+ if index.is_none() {
+ let sw = Rect::from_center_size(pos2(x - 12.0, rect.center().y), vec2(14.0, 10.0));
+ ui.painter().rect_filled(sw, 1.0, if sm.filter_mask.as_ref().is_some_and(|m| m.enabled) { Color32::from_gray(200) } else { Color32::WHITE });
+ ui.painter().rect_stroke(sw, 1.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
+ }
+ ui.painter().text(pos2(x, rect.center().y), Align2::LEFT_CENTER, name, egui::FontId::proportional(11.5), if on { t.text_dim } else { t.text_faint });
+ if let Some(i) = index
+ && resp.double_clicked()
+ {
+ open_editor(app, l.id.0, sm, i);
+ }
+ }
+}
+
+/// Re-opens a smart filter's dialog with its recorded parameters; OK runs
+/// `layer.smartFilter.setParams` instead of adding another filter (see `dialogs::confirm`).
+pub fn open_editor(app: &mut PhotocraftApp, layer: u64, sm: &SmartObject, index: usize) {
+ let Some(f) = sm.smart_filters.get(index) else { return };
+ if !crate::filter_dialog::has_dialog(&f.command) {
+ return;
+ }
+ let Some(id) = crate::filter_dialog::open(app, &f.command) else { return };
+ if let Some(d) = app.ui.dialog_mut(id) {
+ // The live preview would stack a second copy of the filter on the smart object.
+ d.fields.remove("__preview");
+ d.fields.insert("__smartFilter".into(), json!({"layer": layer, "index": index}));
+ if let Value::Object(p) = &f.params {
+ for (k, v) in p {
+ if d.fields.contains_key(k) {
+ d.fields.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ }
+}
+
+/// The command a confirmed filter dialog runs: smart-filter edits update the recorded filter.
+pub fn confirm_command(fields: &serde_json::Map<String, Value>, command: String, params: Value) -> (String, Value) {
+ match fields.get("__smartFilter") {
+ Some(sf) => ("layer.smartFilter.setParams".into(), json!({"layer": sf["layer"], "index": sf["index"], "params": params})),
+ None => (command, params),
+ }
+}
diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs
new file mode 100644
index 000000000..665a4af8d
--- /dev/null
+++ b/crates/ui-egui/src/snap_ui.rs
@@ -0,0 +1,388 @@
+//! Snapping in the shell: builds [`photocraft_engine::snap`] targets from View › Snap To and the
+//! document, snaps tool gestures (Move tool, marquees, crop, shapes, pen anchors, Free Transform
+//! handles and guides), and draws smart guides (magenta alignment lines) while layers move.
+//!
+//! Snapping is on when View › Snap (⇧⌘;) is; holding Ctrl while dragging turns it off for that
+//! drag, as in Photoshop. Smart guides follow View › Show › Smart Guides and also snap the Move
+//! tool to other layers' edges and centres. The threshold is 8 screen pixels at the current zoom.
+
+use egui::{Color32, Stroke, pos2};
+use photocraft_doc::LayerId;
+use photocraft_engine::snap::{SnapKind, SnapLine, SnapOptions, SnapTargets, layer_rect, union};
+
+use crate::PhotocraftApp;
+use crate::canvas::{ToolEvent, ViewXform};
+use crate::state::Tool;
+
+/// Snap distance in screen pixels.
+pub const SNAP_PX: f64 = 8.0;
+
+/// What the current drag snaps.
+#[derive(Clone, Debug, PartialEq)]
+pub enum Gesture {
+ /// A point (marquee corner, crop or shape corner, pen anchor, transform handle).
+ Point,
+ /// Layers being moved: their bounds at the start of the drag.
+ Move { rect: [f64; 4] },
+ /// Free Transform box dragged from inside: its bounds at the start of the drag.
+ TransformMove { rect: [f64; 4] },
+ /// A guide being moved with the Move tool.
+ Guide,
+}
+
+/// Snapping state of the drag in progress.
+#[derive(Clone, Debug)]
+pub struct ActiveSnap {
+ pub gesture: Gesture,
+ pub start: [f64; 2],
+ pub targets: SnapTargets,
+ /// Layer alignments only (smart guides), used when View › Snap is off.
+ pub smart: SnapTargets,
+ pub disabled: bool,
+}
+
+/// Snap To options from the View menu and the Guides/Grid preferences.
+pub fn options(app: &PhotocraftApp) -> SnapOptions {
+ let st = &app.ui.view.snap_to;
+ let e = &app.ui.extras;
+ let grid_step = app.session.active().map_or(18.0, |d| {
+ let g = &app.session.prefs().guides_grid_and_slices;
+ let ppi = app.session.prefs().units_and_rulers.point_size.per_inch();
+ g.major_px(d.doc.resolution_dpi as f64, d.doc.size.width as f64, ppi) / g.subdivisions.max(1) as f64
+ });
+ SnapOptions { guides: st.guides && e.guides, grid: st.grid && e.grid, layers: st.layers, document: st.document_bounds, selection: true, grid_step }
+}
+
+/// Snap tolerance in document pixels at the current zoom.
+pub fn tolerance(app: &PhotocraftApp) -> f64 {
+ SNAP_PX / app.current_zoom().max(0.01) as f64
+}
+
+fn smart_on(app: &PhotocraftApp) -> bool {
+ app.ui.view.shows(app.ui.view.show.smart_guides)
+}
+
+fn snap_on(app: &PhotocraftApp) -> bool {
+ app.ui.extras.snap
+}
+
+/// Targets of the active document (smart = layer alignments only).
+fn build(app: &PhotocraftApp, exclude: &[LayerId], smart: bool) -> SnapTargets {
+ let Some(st) = app.session.active() else { return SnapTargets::default() };
+ let opts = if smart { SnapOptions { guides: false, grid: false, layers: true, document: true, selection: false, grid_step: 0.0 } } else { options(app) };
+ let t = SnapTargets::from_document(&st.doc, &opts, exclude);
+ if smart { t.filtered(SnapKind::is_smart) } else { t }
+}
+
+/// Union of the selected layers' bounds (what the Move tool drags).
+fn moving_rect(app: &PhotocraftApp) -> Option<[f64; 4]> {
+ let st = app.session.active()?;
+ union(st.selected_layers().into_iter().filter_map(|id| layer_rect(&st.doc, id)))
+}
+
+fn is_point_tool(t: Tool) -> bool {
+ matches!(t, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Crop | Tool::ObjectSelection | Tool::Pen | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::Type)
+}
+
+fn quad_rect(q: &[[f64; 2]; 4]) -> [f64; 4] {
+ let xs = q.iter().map(|p| p[0]);
+ let ys = q.iter().map(|p| p[1]);
+ [xs.clone().fold(f64::MAX, f64::min), ys.clone().fold(f64::MAX, f64::min), xs.fold(f64::MIN, f64::max), ys.fold(f64::MIN, f64::max)]
+}
+
+/// Is `p` inside the quad (even-odd)?
+fn in_quad(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool {
+ let mut inside = 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] {
+ inside = !inside;
+ }
+ }
+ inside
+}
+
+/// Near a Free Transform corner or edge handle (within 8 screen px)?
+fn near_handle(q: &[[f64; 2]; 4], p: [f64; 2], tol: f64) -> bool {
+ (0..4).any(|i| {
+ let (a, b) = (q[i], q[(i + 1) % 4]);
+ let mid = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0];
+ [a, mid].iter().any(|h| (h[0] - p[0]).hypot(h[1] - p[1]) <= tol)
+ })
+}
+
+/// Start snapping for a drag beginning at `p` (called on pointer down).
+fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) {
+ app.prefs_rt.snap = None;
+ app.prefs_rt.snap_lines.clear();
+ if app.session.active().is_none() {
+ return;
+ }
+ let tool = app.ui.tool;
+ let tol = tolerance(app);
+ let gesture = if let Some(t) = &app.ui.transform {
+ if near_handle(&t.quad, p, tol) {
+ Some((Gesture::Point, vec![LayerId(t.layer)]))
+ } else if in_quad(&t.quad, p) {
+ Some((Gesture::TransformMove { rect: quad_rect(&t.quad) }, vec![LayerId(t.layer)]))
+ } else {
+ None
+ }
+ } else if tool == Tool::Move && crate::rulers::guide_at(app, p[0], p[1]).is_some() {
+ Some((Gesture::Guide, Vec::new()))
+ } else if tool == Tool::Move {
+ let exclude = app.session.active().map(|s| s.selected_layers()).unwrap_or_default();
+ moving_rect(app).map(|rect| (Gesture::Move { rect }, exclude))
+ } else if is_point_tool(tool) {
+ Some((Gesture::Point, Vec::new()))
+ } else {
+ None
+ };
+ let Some((gesture, exclude)) = gesture else { return };
+ let mut targets = if snap_on(app) { build(app, &exclude, false) } else { SnapTargets::default() };
+ if gesture == Gesture::Guide {
+ // A guide never snaps to itself (or other guides).
+ targets = targets.filtered(|k| k != SnapKind::Guide);
+ }
+ let smart = if matches!(gesture, Gesture::Move { .. }) && smart_on(app) { build(app, &exclude, true) } else { SnapTargets::default() };
+ app.prefs_rt.snap = Some(ActiveSnap { gesture, start: p, targets, smart, disabled: mods.ctrl && !mods.mac_cmd });
+}
+
+/// Round to whole pixels when Preferences › Tools asks vector tools and transforms to snap to
+/// the pixel grid.
+fn pixel_round(app: &PhotocraftApp, p: [f64; 2]) -> [f64; 2] {
+ if app.session.prefs().tools.snap_vector_tools_and_transforms_to_pixel_grid && matches!(app.ui.tool, Tool::Pen | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line) {
+ [p[0].round(), p[1].round()]
+ } else {
+ p
+ }
+}
+
+/// Snap one pointer position for the active gesture; records the alignment lines.
+fn apply(app: &mut PhotocraftApp, p: [f64; 2]) -> [f64; 2] {
+ let tol = tolerance(app);
+ let Some(snap) = app.prefs_rt.snap.as_ref() else { return p };
+ if snap.disabled {
+ app.prefs_rt.snap_lines.clear();
+ return p;
+ }
+ let (out, lines) = match &snap.gesture {
+ Gesture::Point | Gesture::Guide => snap.targets.snap_point(p, tol),
+ Gesture::Move { rect } | Gesture::TransformMove { rect } => {
+ let d = [p[0] - snap.start[0], p[1] - snap.start[1]];
+ let moved = [rect[0] + d[0], rect[1] + d[1], rect[2] + d[0], rect[3] + d[1]];
+ let set = if snap.targets.is_empty() { &snap.smart } else { &snap.targets };
+ let (adj, lines) = set.snap_rect(moved, tol);
+ ([p[0] + adj[0], p[1] + adj[1]], lines)
+ }
+ };
+ app.prefs_rt.snap_lines = lines;
+ out
+}
+
+/// Snap a tool event's coordinates (called by `canvas::tool_event` before the tools see it).
+pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> ToolEvent {
+ match ev {
+ ToolEvent::Down { x, y, pressure } => {
+ begin(app, [x, y], mods);
+ // Moves snap their delta, which is zero at the start: keep the press point.
+ let p = match app.prefs_rt.snap.as_ref().map(|s| &s.gesture) {
+ Some(Gesture::Point) => {
+ let q = apply(app, [x, y]);
+ pixel_round(app, q)
+ }
+ _ => [x, y],
+ };
+ ToolEvent::Down { x: p[0], y: p[1], pressure }
+ }
+ ToolEvent::Move { x, y, pressure } => {
+ if app.prefs_rt.snap.is_none() {
+ return ev;
+ }
+ if let Some(s) = app.prefs_rt.snap.as_mut() {
+ s.disabled = mods.ctrl && !mods.mac_cmd;
+ }
+ let q = apply(app, [x, y]);
+ let p = pixel_round(app, q);
+ ToolEvent::Move { x: p[0], y: p[1], pressure }
+ }
+ ToolEvent::Up { x, y } => {
+ if app.prefs_rt.snap.is_none() {
+ return ev;
+ }
+ let q = apply(app, [x, y]);
+ let p = pixel_round(app, q);
+ app.prefs_rt.snap = None;
+ app.prefs_rt.snap_lines.clear();
+ ToolEvent::Up { x: p[0], y: p[1] }
+ }
+ }
+}
+
+/// Snap a guide being dragged out of a ruler (`vertical` guides snap their x).
+pub fn snap_guide(app: &mut PhotocraftApp, vertical: bool, pos: f64) -> f64 {
+ if !snap_on(app) {
+ return pos;
+ }
+ let Some(st) = app.session.active() else { return pos };
+ let key = (st.doc.id, st.revision);
+ if app.prefs_rt.guide_targets.as_ref().is_none_or(|(k, _)| *k != key) {
+ let t = build(app, &[], false).filtered(|k| k != SnapKind::Guide);
+ app.prefs_rt.guide_targets = Some((key, t));
+ }
+ let tol = tolerance(app);
+ let t = app.prefs_rt.guide_targets.as_ref().map(|(_, t)| t);
+ t.and_then(|t| t.nearest(vertical, pos, tol)).map_or(pos, |t| t.pos)
+}
+
+fn hex_color(s: &str, fallback: Color32) -> Color32 {
+ photocraft_engine::prefs::parse_hex(s).map_or(fallback, |c| Color32::from_rgb(c[0], c[1], c[2]))
+}
+
+/// Draw smart guides (and the moving bounds) for the drag in progress.
+pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
+ let Some(snap) = &app.prefs_rt.snap else { return };
+ let smart_color = hex_color(&app.session.prefs().guides_grid_and_slices.smart_guide_color, Color32::from_rgb(255, 0, 255));
+ // The moved layers' bounds follow the Move tool (Free Transform draws its own box).
+ if let (Gesture::Move { rect }, Some(d)) = (&snap.gesture, app.drag.as_ref().and_then(|d| d.points.last()).map(|p| [p[0] - snap.start[0], p[1] - snap.start[1]])) {
+ let r = egui::Rect::from_two_pos(xf.to_screen((rect[0] + d[0]) as f32, (rect[1] + d[1]) as f32), xf.to_screen((rect[2] + d[0]) as f32, (rect[3] + d[1]) as f32));
+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, crate::theme::Tokens::get(painter.ctx()).accent), egui::StrokeKind::Middle);
+ }
+ if !smart_on(app) {
+ return;
+ }
+ for l in &app.prefs_rt.snap_lines {
+ if !l.kind.is_smart() {
+ continue;
+ }
+ draw_line(painter, xf, l, smart_color);
+ }
+}
+
+fn draw_line(painter: &egui::Painter, xf: &ViewXform, l: &SnapLine, color: Color32) {
+ let (a, b) = if l.vertical { (xf.to_screen(l.pos as f32, l.from as f32), xf.to_screen(l.pos as f32, l.to as f32)) } else { (xf.to_screen(l.from as f32, l.pos as f32), xf.to_screen(l.to as f32, l.pos as f32)) };
+ painter.line_segment([pos2(a.x.round() + 0.5, a.y.round() + 0.5), pos2(b.x.round() + 0.5, b.y.round() + 0.5)], Stroke::new(1.0, color));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn app_with_box() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
+ app.sync_views();
+ app.ui.views[0].zoom = 1.0;
+ app.ui.views[0].fit_pending = false;
+ // Two boxes: a target at (300..350, 200..260) and the moving one at (40..90, 40..80).
+ app.run("layer.new.layer", json!({"name": "target"})).unwrap();
+ app.run("select.rect", json!({"x": 300, "y": 200, "width": 50, "height": 60})).unwrap();
+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ app.run("layer.new.layer", json!({"name": "mover"})).unwrap();
+ app.run("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap();
+ app.run("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ app.run("select.deselect", json!({})).unwrap();
+ app
+ }
+
+ fn mover_bounds(app: &PhotocraftApp) -> photocraft_geom::Rect {
+ let st = app.session.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds()
+ }
+
+ #[test]
+ fn move_tool_snaps_to_other_layer_edges_with_smart_guides() {
+ let mut app = app_with_box();
+ app.ui.tool = Tool::Move;
+ let m = egui::Modifiers::NONE;
+ crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m);
+ // Drag so the mover's left edge lands 3 px right of the target's (x = 303).
+ crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m);
+ assert!(app.prefs_rt.snap_lines.iter().any(|l| l.vertical && l.pos == 300.0 && l.kind.is_smart()), "{:?}", app.prefs_rt.snap_lines);
+ crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m);
+ assert_eq!(mover_bounds(&app).x0, 300);
+ assert!(app.prefs_rt.snap.is_none());
+ }
+
+ #[test]
+ fn ctrl_or_snap_off_disables_snapping() {
+ let mut app = app_with_box();
+ app.ui.tool = Tool::Move;
+ app.ui.view.show.smart_guides = false;
+ app.ui.extras.snap = false;
+ let m = egui::Modifiers::NONE;
+ crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m);
+ crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m);
+ assert_eq!(mover_bounds(&app).x0, 303);
+ app.ui.extras.snap = true;
+ let ctrl = egui::Modifiers { ctrl: true, ..Default::default() };
+ crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, ctrl);
+ crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 62.0, y: 60.0 }, ctrl);
+ assert_eq!(mover_bounds(&app).x0, 305, "no snap to the target's right edge at 350? (moved freely)");
+ }
+
+ #[test]
+ fn marquee_corner_snaps_to_guides_and_document_edges() {
+ let mut app = app_with_box();
+ app.run("view.newGuide", json!({"orientation": "vertical", "position": 120})).unwrap();
+ app.ui.tool = Tool::RectMarquee;
+ let m = egui::Modifiers::NONE;
+ crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 3.0, y: 2.0, pressure: 1.0 }, m);
+ crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 116.0, y: 50.0 }, m);
+ let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds();
+ assert_eq!((sel.x0, sel.y0, sel.x1), (0, 0, 120));
+ // Zoomed in to 800%, 4 px is beyond the 1 px threshold: no snap.
+ app.ui.views[0].zoom = 8.0;
+ crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m);
+ crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 116.0, y: 50.0 }, m);
+ let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds();
+ assert_eq!(sel.x1, 116);
+ }
+
+ #[test]
+ fn free_transform_drags_and_handles_snap() {
+ let mut app = app_with_box();
+ let ctx = egui::Context::default();
+ crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap();
+ assert!(app.ui.transform.is_some());
+ let m = egui::Modifiers::NONE;
+ // Drag from inside the box (40..90 × 40..80) so its left edge lands 2 px from x = 300.
+ // (Away from the centre, which holds the reference point.)
+ crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, m);
+ crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 312.0, y: 50.0 }, m);
+ let q = app.ui.transform.as_ref().unwrap().quad;
+ assert!((q[0][0] - 300.0).abs() < 1e-6, "{q:?}");
+ // The right-edge handle snaps to the target's right edge (x = 350).
+ crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[1][0], y: (q[1][1] + q[2][1]) / 2.0, pressure: 1.0 }, m);
+ crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 353.0, y: 60.0 }, m);
+ let q = app.ui.transform.as_ref().unwrap().quad;
+ assert!((q[1][0] - 350.0).abs() < 1e-6, "{q:?}");
+ crate::transform_tool::commit(&mut app);
+ assert_eq!(mover_bounds(&app).x0, 300);
+ }
+
+ #[test]
+ fn guides_snap_to_layer_edges() {
+ let mut app = app_with_box();
+ assert_eq!(snap_guide(&mut app, true, 297.0), 300.0);
+ assert_eq!(snap_guide(&mut app, false, 150.0), 150.0, "document centre");
+ assert_eq!(snap_guide(&mut app, false, 170.0), 170.0);
+ app.ui.extras.snap = false;
+ assert_eq!(snap_guide(&mut app, true, 297.0), 297.0);
+ }
+
+ #[test]
+ fn grid_snapping_uses_preferences() {
+ let mut app = app_with_box();
+ app.ui.extras.grid = true;
+ app.run("prefs.set", json!({"values": {"guidesGridAndSlices.gridlineEvery": 100, "guidesGridAndSlices.gridUnit": "pixels", "guidesGridAndSlices.subdivisions": 4}})).unwrap();
+ assert_eq!(options(&app).grid_step, 25.0);
+ app.ui.tool = Tool::RectMarquee;
+ let m = egui::Modifiers::NONE;
+ crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 152.0, y: 127.0, pressure: 1.0 }, m);
+ crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 199.0, y: 176.0 }, m);
+ let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds();
+ assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (150, 125, 200, 175));
+ }
+}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 72d53e02a..6cf335905 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -185,11 +185,14 @@ pub struct Panels {
pub toolbar: bool,
pub options_bar: bool,
pub status_bar: bool,
+ /// Window › Brush Settings (F5): floating, like Photoshop's.
+ #[serde(default)]
+ pub brush_settings: bool,
}
impl Default for Panels {
fn default() -> Self {
- Self { layers: true, history: false, properties: true, color: true, navigator: false, toolbar: true, options_bar: true, status_bar: true }
+ Self { layers: true, history: false, properties: true, color: true, navigator: false, toolbar: true, options_bar: true, status_bar: true, brush_settings: false }
}
}
@@ -340,6 +343,9 @@ pub struct TransformSession {
/// Reference point (rotation / ⌥-scale centre).
pub pivot: [f64; 2],
pub interpolation: String,
+ /// Warp mode (Edit › Transform › Warp): the warp being edited over `rect`, in document px.
+ #[serde(default)]
+ pub warp: Option<photocraft_geom::warp::Warp>,
}
/// In-progress inline type editing (Type tool). Offsets are character indices.
@@ -418,6 +424,9 @@ pub struct UiState {
/// View extras: rulers (⌘R), grid (⌘'), guides (⌘;), snapping (⇧⌘;), locked guides (⌥⌘;).
#[serde(default)]
pub extras: Extras,
+ /// View / Window / Type preferences: screen mode, Extras, Show and Snap To, flip, arrangement.
+ #[serde(default)]
+ pub view: crate::view_cmds::ViewOptions,
pub panels: Panels,
/// Views per open document (index-aligned with the session's documents).
pub views: Vec<View>,
@@ -427,6 +436,11 @@ pub struct UiState {
pub workspace: String,
pub palette_open: bool,
pub dock_tabs: DockTabs,
+ /// Brush Settings: selected section (0 = Brush Tip Shape) and tab (0 settings, 1 Brushes).
+ #[serde(default)]
+ pub brush_section: usize,
+ #[serde(default)]
+ pub brush_tab: usize,
/// Marquee options-bar mode: 0 new, 1 add, 2 subtract, 3 intersect (modifier keys override).
#[serde(default)]
pub selection_mode: u8,
@@ -456,6 +470,7 @@ impl Default for UiState {
clone_source: None,
clone_offset: None,
extras: Extras::default(),
+ view: Default::default(),
actions: Default::default(),
layer_filter: Vec::new(),
pen: None,
@@ -468,6 +483,8 @@ impl Default for UiState {
workspace: "Essentials".into(),
palette_open: false,
dock_tabs: DockTabs::default(),
+ brush_section: 0,
+ brush_tab: 0,
selection_mode: 0,
tool_options: ToolOptions::default(),
polygon: Vec::new(),
diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs
index b88d7db8c..5d0b470b1 100644
--- a/crates/ui-egui/src/transform_tool.rs
+++ b/crates/ui-egui/src/transform_tool.rs
@@ -10,6 +10,7 @@ use std::sync::Arc;
use egui::{Color32, CursorIcon, Pos2, Stroke, pos2, vec2};
use photocraft_algo::transform::Homography;
use photocraft_doc::{Document, LayerContent, LayerId};
+use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};
use serde_json::json;
use crate::PhotocraftApp;
@@ -24,6 +25,8 @@ pub struct TransformPreview {
pub texture: egui::TextureHandle,
pub opacity: f32,
gesture: Option<Gesture>,
+ /// Warp-mode drag: (control point, pointer start, mesh points at the start).
+ warp_drag: Option<(usize, [f64; 2], Vec<[f64; 2]>)>,
}
fn corners(r: [f64; 4]) -> [[f64; 2]; 4] {
@@ -60,7 +63,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>
}
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.transform_preview = Some(TransformPreview { session, doc: Arc::new(pd), texture, opacity: layer.opacity * layer.fill_opacity, gesture: None, warp_drag: None });
app.ui.transform = Some(TransformSession {
session,
layer: id.0,
@@ -68,10 +71,52 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>
quad: corners(rect),
pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0],
interpolation: "bicubic".into(),
+ warp: None,
});
Ok(())
}
+/// Start (or switch an active Free Transform into) Warp mode.
+pub fn begin_warp(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {
+ if app.ui.transform.is_none() {
+ begin(app, ctx)?;
+ }
+ enter_warp(app);
+ Ok(())
+}
+
+/// Switch to Warp mode: a smart object's existing warp (when the box is untouched), else a
+/// custom mesh following the current box (so a transform made first carries over).
+pub fn enter_warp(app: &mut PhotocraftApp) {
+ let existing = app.session.active().and_then(|d| d.doc.layer(LayerId(app.ui.transform.as_ref()?.layer)).and_then(photocraft_engine::warp_cmds::smart_warp_doc_space));
+ let Some(t) = app.ui.transform.as_mut() else { return };
+ if t.warp.is_some() {
+ return;
+ }
+ if t.quad == corners(t.rect)
+ && let Some(w) = existing
+ {
+ t.rect = w.bounds;
+ t.quad = corners(w.bounds);
+ t.warp = Some(w);
+ return;
+ }
+ let h = Homography::rect_to_quad(t.rect, t.quad).unwrap_or(Homography::IDENTITY);
+ let mesh = BezierMesh::identity(t.rect, 1, 1).map_points(|p| {
+ let (x, y) = h.apply(p[0], p[1]);
+ [x, y]
+ });
+ t.warp = Some(Warp::custom(mesh, t.rect));
+}
+
+/// Leave Warp mode (back to the box; warp edits are dropped, like Photoshop's mode toggle on an
+/// untouched warp).
+pub fn leave_warp(app: &mut PhotocraftApp) {
+ if let Some(t) = app.ui.transform.as_mut() {
+ t.warp = None;
+ }
+}
+
/// 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);
@@ -119,6 +164,15 @@ fn contains(l: &photocraft_doc::Layer, id: LayerId) -> bool {
pub fn commit(app: &mut PhotocraftApp) {
let Some(t) = app.ui.transform.take() else { return };
app.transform_preview = None;
+ if let Some(w) = &t.warp {
+ if w.is_identity() {
+ return;
+ }
+ if let Err(e) = app.run("edit.transform.warp", json!({"layer": t.layer, "rect": t.rect, "warp": w, "interpolation": t.interpolation})) {
+ app.ui.status = e;
+ }
+ return;
+ }
if t.quad == corners(t.rect) {
return; // untouched: nothing to do (Photoshop adds no history step either)
}
@@ -185,6 +239,10 @@ struct Gesture {
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;
+ if t.warp.is_some() {
+ warp_pointer(app, ev, tol);
+ return true;
+ }
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 }),
@@ -301,10 +359,79 @@ fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods: egui::Mod
}
}
+/// Index of the warp control point within `tol` of `p` (nearest).
+fn warp_hit(w: &Warp, p: [f64; 2], tol: f64) -> Option<usize> {
+ let m = w.mesh.as_ref()?;
+ m.points
+ .iter()
+ .enumerate()
+ .map(|(i, q)| (i, ((q[0] - p[0]).powi(2) + (q[1] - p[1]).powi(2)).sqrt()))
+ .filter(|(_, d)| *d < tol)
+ .min_by(|a, b| a.1.total_cmp(&b.1))
+ .map(|(i, _)| i)
+}
+
+/// Drags a warp control point. Anchors (patch corners) carry their handles along, as in
+/// Photoshop. Preset warps turn into a custom mesh on the first drag.
+fn warp_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tol: f64) {
+ let (Some(t), Some(pv)) = (app.ui.transform.as_mut(), app.transform_preview.as_mut()) else { return };
+ let Some(w) = t.warp.as_mut() else { return };
+ match ev {
+ ToolEvent::Down { x, y, .. } => {
+ if w.mesh.is_none() || w.style != WarpStyle::Custom {
+ let mesh = w.to_mesh(1, 1);
+ *w = Warp::custom(mesh, w.bounds);
+ }
+ pv.warp_drag = warp_hit(w, [x, y], tol).map(|i| (i, [x, y], w.mesh.as_ref().map(|m| m.points.clone()).unwrap_or_default()));
+ }
+ ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => {
+ if let (Some((i, start, pts0)), Some(m)) = (&pv.warp_drag, w.mesh.as_mut()) {
+ let (dx, dy) = (x - start[0], y - start[1]);
+ let nx = m.nx();
+ let (ci, cj) = (i % nx, i / nx);
+ let ny = m.ny();
+ let mut moved = vec![*i];
+ if ci % 3 == 0 && cj % 3 == 0 {
+ for (di, dj) in [(-1i64, 0i64), (1, 0), (0, -1), (0, 1)] {
+ let (a, b) = (ci as i64 + di, cj as i64 + dj);
+ if a >= 0 && b >= 0 && (a as usize) < nx && (b as usize) < ny {
+ moved.push(b as usize * nx + a as usize);
+ }
+ }
+ }
+ for k in moved {
+ m.points[k] = [pts0[k][0] + dx, pts0[k][1] + dy];
+ }
+ }
+ if matches!(ev, ToolEvent::Up { .. }) {
+ pv.warp_drag = None;
+ }
+ }
+ }
+}
+
+/// Applies a split-warp command to the mesh being edited (at the box centre unless `at`).
+pub fn split(app: &mut PhotocraftApp, id: &str, at: Option<[f64; 2]>) -> Result<(), String> {
+ let Some(w) = app.ui.transform.as_ref().and_then(|t| t.warp.clone()) else { return Err("not warping".into()) };
+ let mut p = json!({"warp": w});
+ if let Some(a) = at {
+ p["at"] = json!(a);
+ }
+ let r = app.session.execute(id, p).map_err(|e| e.to_string())?;
+ let nw: Warp = serde_json::from_value(r["warp"].clone()).map_err(|e| e.to_string())?;
+ if let Some(t) = app.ui.transform.as_mut() {
+ t.warp = Some(nw);
+ }
+ Ok(())
+}
+
/// 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;
+ if let Some(w) = &t.warp {
+ return Some(if w.style != WarpStyle::Custom || warp_hit(w, p, tol).is_some() { CursorIcon::Crosshair } else { CursorIcon::Default });
+ }
Some(match hit(t, p, tol) {
Hit::Corner(0 | 2) => CursorIcon::ResizeNwSe,
Hit::Corner(_) => CursorIcon::ResizeNeSw,
@@ -320,6 +447,10 @@ pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option<CursorIcon> {
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(w) = &t.warp {
+ draw_warp(painter, xf, t, w, pv);
+ return;
+ }
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;
@@ -358,6 +489,87 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform
painter.line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::WHITE));
}
+/// Warp preview (the moving pixels on a fine textured mesh) plus the control mesh: grid curves at
+/// patch boundaries and thirds, anchors (squares), handles and their arms.
+fn draw_warp(painter: &egui::Painter, xf: &ViewXform, t: &TransformSession, w: &Warp, pv: &TransformPreview) {
+ let scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32);
+ let r = t.rect;
+ let n = 32;
+ 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) = w.map(r[0] + u * (r[2] - r[0]), r[1] + v * (r[3] - r[1]));
+ 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 line = Stroke::new(1.0, accent);
+ let thin = Stroke::new(0.75, accent.gamma_multiply(0.7));
+ let m = w.to_mesh(1, 1);
+ let curve = |fixed_u: Option<f64>, fixed_v: Option<f64>| -> Vec<Pos2> {
+ (0..=40)
+ .map(|k| {
+ let s = k as f64 / 40.0;
+ let p = m.eval(fixed_u.unwrap_or(s), fixed_v.unwrap_or(s));
+ scr(p)
+ })
+ .collect()
+ };
+ // Patch boundaries (solid) and thirds (thin), like Photoshop's 3×3 grid per patch.
+ for (k, win) in m.us.windows(2).enumerate() {
+ for third in [1.0, 2.0] {
+ painter.add(egui::Shape::line(curve(Some(win[0] + (win[1] - win[0]) * third / 3.0), None), thin));
+ }
+ if k == 0 {
+ painter.add(egui::Shape::line(curve(Some(win[0]), None), line));
+ }
+ painter.add(egui::Shape::line(curve(Some(win[1]), None), line));
+ }
+ for (k, win) in m.vs.windows(2).enumerate() {
+ for third in [1.0, 2.0] {
+ painter.add(egui::Shape::line(curve(None, Some(win[0] + (win[1] - win[0]) * third / 3.0)), thin));
+ }
+ if k == 0 {
+ painter.add(egui::Shape::line(curve(None, Some(win[0])), line));
+ }
+ painter.add(egui::Shape::line(curve(None, Some(win[1])), line));
+ }
+ if w.style != WarpStyle::Custom {
+ return; // presets are edited from the options bar
+ }
+ let (nx, ny) = (m.nx(), m.ny());
+ for j in 0..ny {
+ for i in 0..nx {
+ let p = scr(m.point(i, j));
+ let anchor = i % 3 == 0 && j % 3 == 0;
+ let handle = (i % 3 == 0) != (j % 3 == 0);
+ if anchor {
+ 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, line, egui::StrokeKind::Inside);
+ } else if handle {
+ // Arm to the nearest anchor along the row/column.
+ let (ai, aj) = if i % 3 == 0 { (i, if j % 3 == 1 { j - 1 } else { j + 1 }) } else { (if i % 3 == 1 { i - 1 } else { i + 1 }, j) };
+ painter.line_segment([scr(m.point(ai, aj)), p], line);
+ painter.circle_filled(p, 3.5, Color32::WHITE);
+ painter.circle_stroke(p, 3.5, line);
+ } else {
+ painter.circle_filled(p, 2.5, accent);
+ }
+ }
+ }
+}
+
/// 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]);
@@ -372,6 +584,10 @@ fn readout(t: &TransformSession) -> (f64, f64, f64, f64) {
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());
+ if let Some(w) = t.warp.clone() {
+ warp_options_bar(app, ui, &w);
+ return;
+ }
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));
@@ -435,6 +651,81 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if crate::icons::button(ui, "ban", 24.0, false, "Cancel transform (Esc)").clicked() {
cancel(app);
}
+ crate::widgets::vline(ui, 22.0);
+ if crate::icons::button(ui, "grid-3x3", 24.0, false, "Switch between free transform and warp modes").clicked() {
+ enter_warp(app);
+ }
+ });
+}
+
+/// Options bar in Warp mode: style, bend and distortions, split buttons, mode toggle, ✓ / ⊘.
+fn warp_options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) {
+ let tk = crate::theme::Tokens::get(ui.ctx());
+ let lbl = |ui: &mut egui::Ui, s: &str| {
+ ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0));
+ };
+ lbl(ui, "Warp:");
+ let mut style = w.style;
+ let opts: Vec<(WarpStyle, &str)> = WarpStyle::all().map(|s| (s, s.label())).collect();
+ if crate::widgets::dropdown(ui, "warp-style", &mut style, &opts, 120.0)
+ && let Some(t) = app.ui.transform.as_mut()
+ {
+ let b = t.rect;
+ t.warp = Some(match style {
+ WarpStyle::Custom => Warp::custom(w.to_mesh(1, 1), b),
+ WarpStyle::None => Warp::custom(BezierMesh::identity(b, 1, 1), b),
+ s => Warp { style: s, bend: if w.style.is_preset() { w.bend } else { 50.0 }, ..Warp::none(b) },
+ });
+ }
+ if w.style.is_preset() {
+ let mut vertical = w.vertical;
+ if crate::widgets::checkbox(ui, &mut vertical, "Vertical").changed()
+ && let Some(Some(cur)) = app.ui.transform.as_mut().map(|t| t.warp.as_mut())
+ {
+ cur.vertical = vertical;
+ }
+ let fields: [(&str, f64); 3] = [("Bend:", w.bend), ("H:", w.h_distort), ("V:", w.v_distort)];
+ for (k, (name, v)) in fields.iter().enumerate() {
+ lbl(ui, name);
+ let mut f = *v as f32;
+ if crate::widgets::value_field(ui, &mut f, -100.0..=100.0, "%", 58.0).changed()
+ && let Some(Some(cur)) = app.ui.transform.as_mut().map(|t| t.warp.as_mut())
+ {
+ match k {
+ 0 => cur.bend = f64::from(f),
+ 1 => cur.h_distort = f64::from(f),
+ _ => cur.v_distort = f64::from(f),
+ }
+ }
+ }
+ } else {
+ crate::widgets::vline(ui, 22.0);
+ lbl(ui, "Split:");
+ for (id, label) in [
+ ("edit.transform.splitWarpCrosswise", "Crosswise"),
+ ("edit.transform.splitWarpVertically", "Vertical"),
+ ("edit.transform.splitWarpHorizontally", "Horizontal"),
+ ("edit.transform.removeWarpSplit", "Remove"),
+ ] {
+ if crate::widgets::secondary_button(ui, label, 0.0).clicked()
+ && let Err(e) = split(app, id, None)
+ {
+ app.ui.status = e;
+ }
+ }
+ }
+ 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 warp (↩)").clicked() {
+ commit(app);
+ }
+ if crate::icons::button(ui, "ban", 24.0, false, "Cancel warp (Esc)").clicked() {
+ cancel(app);
+ }
+ crate::widgets::vline(ui, 22.0);
+ if crate::icons::button(ui, "grid-3x3", 24.0, true, "Switch between free transform and warp modes").clicked() {
+ leave_warp(app);
+ }
});
}
@@ -466,7 +757,7 @@ 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() }
+ 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(), warp: None }
}
fn drag(s: &mut TransformSession, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) {
@@ -543,4 +834,41 @@ mod tests {
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());
}
+
+ #[test]
+ fn warp_mode_drags_anchor_with_handles_splits_and_commits() {
+ 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, 32, 32), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let ctx = egui::Context::default();
+ begin_warp(&mut app, &ctx).unwrap();
+ let w = app.ui.transform.as_ref().unwrap().warp.clone().unwrap();
+ assert!(w.is_identity());
+ // Drag the bottom-right anchor (point 15) by (+10, +6): its two handles follow.
+ warp_pointer(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, 2.0);
+ warp_pointer(&mut app, ToolEvent::Up { x: 42.0, y: 38.0 }, 2.0);
+ let m = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.clone().unwrap();
+ assert_eq!(m.points[15], [42.0, 38.0]);
+ let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9;
+ assert!(near(m.points[14], [24.0 + 10.0, 38.0]), "{:?}", m.points[14]);
+ assert!(near(m.points[11], [42.0, 24.0 + 6.0]), "{:?}", m.points[11]);
+ split(&mut app, "edit.transform.splitWarpCrosswise", None).unwrap();
+ assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap().nx(), 7);
+ 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.x1 >= 41 && b.y1 >= 37, "{b:?}");
+ assert!(app.ui.transform.is_none());
+ // Toggling back to the box drops the warp.
+ begin_warp(&mut app, &ctx).unwrap();
+ leave_warp(&mut app);
+ assert!(app.ui.transform.as_ref().unwrap().warp.is_none());
+ }
}
diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs
index d6a110094..8edc7c058 100644
--- a/crates/ui-egui/src/vector_ui.rs
+++ b/crates/ui-egui/src/vector_ui.rs
@@ -339,14 +339,41 @@ fn color_of(f: &photocraft_doc::Fill) -> Option<Color32> {
}
/// 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> {
+fn swatch(ui: &mut egui::Ui, fill: Option<&photocraft_doc::Fill>, 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) => {
+ let current = fill.and_then(color_of);
+ match (current, fill) {
+ (Some(c), _) => {
ui.painter().rect_filled(r, 2.0, c);
}
- None => {
+ (None, Some(photocraft_doc::Fill::Gradient { stops, .. })) if !stops.is_empty() => {
+ // Gradient fills preview as a left-to-right ramp through their stops.
+ let rgb = |c: &photocraft_doc::Color| {
+ let v = c.to_rgba8();
+ Color32::from_rgb(v[0], v[1], v[2])
+ };
+ let mut mesh = egui::Mesh::default();
+ let mut ramp: Vec<(f32, Color32)> = stops.iter().map(|(p, c)| (p.clamp(0.0, 1.0), rgb(c))).collect();
+ ramp.insert(0, (0.0, ramp[0].1));
+ ramp.push((1.0, ramp[ramp.len() - 1].1));
+ for (i, (p, c)) in ramp.iter().enumerate() {
+ let x = r.left() + r.width() * p;
+ mesh.colored_vertex(egui::pos2(x, r.top()), *c);
+ mesh.colored_vertex(egui::pos2(x, r.bottom()), *c);
+ if i > 0 {
+ let k = (i as u32) * 2;
+ mesh.add_triangle(k - 2, k - 1, k);
+ mesh.add_triangle(k - 1, k, k + 1);
+ }
+ }
+ ui.painter().add(mesh);
+ }
+ (None, Some(_)) => {
+ // Pattern fill: a neutral checker hint.
+ crate::widgets::checker(ui.painter(), r, 4.0);
+ }
+ (None, 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)));
@@ -360,7 +387,7 @@ fn swatch(ui: &mut egui::Ui, current: Option<Color32>, tip: &str) -> Option<Stri
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() {
+ if fill.is_some() && ui.button("No Color").clicked() {
out = Some("none".into());
}
});
@@ -382,12 +409,12 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra
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") {
+ if let Some(c) = swatch(ui, sh.fill.as_ref(), "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") {
+ if let Some(c) = swatch(ui, sh.stroke.as_ref().map(|s| &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);
diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs
new file mode 100644
index 000000000..261a82f95
--- /dev/null
+++ b/crates/ui-egui/src/view_cmds.rs
@@ -0,0 +1,829 @@
+//! Shell-side View, Window and Type menu items: screen modes, Extras and the Show / Snap To
+//! toggles, zoom presets, view flipping, document arrangement (tiles, n-up, floating windows,
+//! Match Zoom/Location), panel shortcuts that pick the right dock tab, type UI preferences, and
+//! the picker/dialog front ends of the engine's File commands.
+//!
+//! Everything here is view or window state ([`ViewOptions`], serde, part of `UiState`, so the
+//! control channel reads and drives it). Anything that changes a document is an engine command;
+//! this module only opens its dialog or file picker first.
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::state::DialogKind;
+
+/// View › Show flags (Photoshop defaults).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Show {
+ pub layer_edges: bool,
+ pub selection_edges: bool,
+ pub target_path: bool,
+ pub pixel_grid: bool,
+ pub smart_guides: bool,
+ pub brush_preview: bool,
+ pub slices: bool,
+ pub notes: bool,
+ pub mesh: bool,
+ pub edit_pins: bool,
+ pub count: bool,
+ pub canvas_guides: bool,
+ pub artboard_guides: bool,
+}
+
+impl Default for Show {
+ fn default() -> Self {
+ Self { layer_edges: false, selection_edges: true, target_path: true, pixel_grid: true, smart_guides: true, brush_preview: true, slices: true, notes: true, mesh: false, edit_pins: true, count: true, canvas_guides: true, artboard_guides: true }
+ }
+}
+
+/// View › Snap To targets (snapping itself is the `view.snap` master switch).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct SnapTo {
+ pub guides: bool,
+ pub grid: bool,
+ pub layers: bool,
+ pub slices: bool,
+ pub document_bounds: bool,
+}
+
+impl Default for SnapTo {
+ fn default() -> Self {
+ Self { guides: true, grid: true, layers: true, slices: true, document_bounds: true }
+ }
+}
+
+/// View-, window- and type-preference state of the shell.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct ViewOptions {
+ /// "standard" | "fullScreenWithMenuBar" | "fullScreen" (View › Screen Mode, F cycles).
+ pub screen_mode: String,
+ /// View › Extras (⌘H): master switch for guides, grid, edges and other overlays.
+ pub extras: bool,
+ pub show: Show,
+ pub snap_to: SnapTo,
+ /// View › Flip Horizontal: mirror the view only (the document is untouched).
+ pub flip_horizontal: bool,
+ /// View › Pixel Aspect Ratio preset id ("square", "d1DvNtsc", …) and its correction toggle.
+ pub pixel_aspect: String,
+ pub pixel_aspect_correction: bool,
+ pub pattern_preview: bool,
+ pub pixel_art_preview: bool,
+ /// Window › Arrange layout of the document area: "tabs" or a tile/n-up layout id.
+ pub arrange: String,
+ /// Type › Font Preview Size: "small" | "medium" | "large" | "extraLarge" | "huge".
+ pub font_preview_size: String,
+ /// Type › Language Options: "defaultFeatures" | "eastAsianFeatures" | "middleEasternFeatures",
+ /// and the Middle Eastern & South Asian composer.
+ pub language_features: String,
+ pub middle_eastern_composer: bool,
+}
+
+impl Default for ViewOptions {
+ fn default() -> Self {
+ Self {
+ screen_mode: "standard".into(),
+ extras: true,
+ show: Show::default(),
+ snap_to: SnapTo::default(),
+ flip_horizontal: false,
+ pixel_aspect: "square".into(),
+ pixel_aspect_correction: false,
+ pattern_preview: false,
+ pixel_art_preview: false,
+ arrange: "tabs".into(),
+ font_preview_size: "medium".into(),
+ language_features: "defaultFeatures".into(),
+ middle_eastern_composer: false,
+ }
+ }
+}
+
+impl ViewOptions {
+ /// Is an overlay with this Show flag visible (Extras on and the flag on)?
+ pub fn shows(&self, flag: bool) -> bool {
+ self.extras && flag
+ }
+ pub fn hides_chrome(&self) -> bool {
+ self.screen_mode == "fullScreen"
+ }
+ pub fn hides_tabs(&self) -> bool {
+ self.screen_mode != "standard"
+ }
+}
+
+const SCREEN_MODES: [&str; 3] = ["standard", "fullScreenWithMenuBar", "fullScreen"];
+const PIXEL_ASPECTS: [&str; 8] = ["square", "d1DvNtsc", "d1DvPal", "d1DvNtscWidescreen", "hdv1080", "d1DvPalWidescreen", "dvcproHd1080", "anamorphic2To1"];
+const FONT_PREVIEW: [&str; 5] = ["small", "medium", "large", "extraLarge", "huge"];
+const LANGUAGE: [&str; 3] = ["defaultFeatures", "eastAsianFeatures", "middleEasternFeatures"];
+/// Window › Arrange layouts drawn by [`cells`].
+const LAYOUTS: [&str; 10] = ["tileAllVertically", "tileAllHorizontally", "twoUpVertical", "twoUpHorizontal", "threeUpVertical", "threeUpHorizontal", "threeUpStacked", "fourUp", "sixUp", "tile"];
+
+/// Pixel aspect ratio (width / height of a pixel) of a preset id.
+pub fn pixel_aspect_ratio(id: &str) -> f32 {
+ match id {
+ "d1DvNtsc" => 0.91,
+ "d1DvPal" => 1.09,
+ "d1DvNtscWidescreen" => 1.21,
+ "hdv1080" => 1.33,
+ "d1DvPalWidescreen" => 1.46,
+ "dvcproHd1080" => 1.5,
+ "anamorphic2To1" => 2.0,
+ _ => 1.0,
+ }
+}
+
+fn show_slot<'a>(s: &'a mut Show, key: &str) -> Option<&'a mut bool> {
+ Some(match key {
+ "layerEdges" => &mut s.layer_edges,
+ "selectionEdges" => &mut s.selection_edges,
+ "targetPath" => &mut s.target_path,
+ "pixelGrid" => &mut s.pixel_grid,
+ "smartGuides" => &mut s.smart_guides,
+ "brushPreview" => &mut s.brush_preview,
+ "slices" => &mut s.slices,
+ "notes" => &mut s.notes,
+ "mesh" => &mut s.mesh,
+ "editPins" => &mut s.edit_pins,
+ "count" => &mut s.count,
+ "canvasGuides" => &mut s.canvas_guides,
+ "artboardGuides" => &mut s.artboard_guides,
+ _ => return None,
+ })
+}
+
+fn snap_slot<'a>(s: &'a mut SnapTo, key: &str) -> Option<&'a mut bool> {
+ Some(match key {
+ "guides" => &mut s.guides,
+ "grid" => &mut s.grid,
+ "layers" => &mut s.layers,
+ "slices" => &mut s.slices,
+ "documentBounds" => &mut s.document_bounds,
+ _ => return None,
+ })
+}
+
+/// Window › <panel>: (panel, dock tab) for panels that live as tabs of a dock card.
+fn panel_tab(app: &PhotocraftApp, id: &str) -> Option<(&'static str, usize)> {
+ let pro = app.ui.theme == crate::theme::ThemeKind::Pro;
+ Some(match id {
+ "window.panel.info" => ("navigator", 2),
+ "window.panel.histogram" => ("navigator", 1),
+ "window.panel.navigator" => ("navigator", 0),
+ "window.panel.actions" => ("history", 1),
+ "window.panel.history" => ("history", 0),
+ "window.panel.channels" => ("layers", 1),
+ "window.panel.paths" => ("layers", 2),
+ "window.panel.layers" => ("layers", 0),
+ "window.panel.adjustments" => ("properties", 1),
+ "window.panel.properties" | "window.panel.character" | "window.panel.paragraph" | "type.panels.character" | "type.panels.paragraph" => ("properties", 0),
+ "window.panel.swatches" => ("color", usize::from(pro)),
+ "window.panel.color" => ("color", usize::from(!pro)),
+ _ => return None,
+ })
+}
+
+fn panel_state<'a>(app: &'a mut PhotocraftApp, panel: &str) -> (&'a mut bool, &'a mut usize) {
+ let (p, t) = (&mut app.ui.panels, &mut app.ui.dock_tabs);
+ match panel {
+ "navigator" => (&mut p.navigator, &mut t.navigator),
+ "history" => (&mut p.history, &mut t.history),
+ "layers" => (&mut p.layers, &mut t.layers),
+ "color" => (&mut p.color, &mut t.color),
+ _ => (&mut p.properties, &mut t.properties),
+ }
+}
+
+/// Ids handled here (live menu items).
+pub fn handles(id: &str) -> bool {
+ if let Some(k) = id.strip_prefix("view.show.") {
+ return show_slot(&mut Show::default(), k).is_some() || k == "all";
+ }
+ if let Some(k) = id.strip_prefix("view.snapTo.") {
+ return snap_slot(&mut SnapTo::default(), k).is_some() || k == "all" || k == "none";
+ }
+ if let Some(k) = id.strip_prefix("view.screenMode.") {
+ return SCREEN_MODES.contains(&k) || k == "cycle";
+ }
+ if let Some(k) = id.strip_prefix("view.pixelAspectRatio.") {
+ return PIXEL_ASPECTS.contains(&k);
+ }
+ if let Some(k) = id.strip_prefix("type.fontPreviewSize.") {
+ return FONT_PREVIEW.contains(&k);
+ }
+ if let Some(k) = id.strip_prefix("type.languageOptions.") {
+ return LANGUAGE.contains(&k) || k == "middleEasternAndSouthAsianComposer";
+ }
+ if let Some(k) = id.strip_prefix("window.arrange.") {
+ return LAYOUTS.contains(&k) || matches!(k, "consolidateAllToTabs" | "cascade" | "floatInWindow" | "floatAllInWindows" | "newWindowForDocument" | "matchZoom" | "matchLocation" | "matchRotation" | "matchAll");
+ }
+ matches!(
+ id,
+ "view.extras"
+ | "view.twoHundredPercent"
+ | "view.printSize"
+ | "view.fitLayersOnScreen"
+ | "view.flipHorizontal"
+ | "view.pixelAspectRatioCorrection"
+ | "view.patternPreview"
+ | "view.pixelArtPreview"
+ | "window.panel.layers"
+ | "window.panel.history"
+ | "window.panel.navigator"
+ | "window.panel.properties"
+ | "window.panel.color"
+ | "window.panel.actions"
+ | "window.panel.channels"
+ | "window.panel.paths"
+ | "window.panel.character"
+ | "window.panel.paragraph"
+ | "window.panel.info"
+ | "window.panel.histogram"
+ | "window.panel.swatches"
+ | "window.panel.adjustments"
+ | "type.panels.character"
+ | "type.panels.paragraph"
+ )
+}
+
+pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ if !handles(id) && !wraps(id) {
+ return None;
+ }
+ let doc = app.session.active().is_some();
+ Some(match id {
+ "view.screenMode.cycle" => app.ui.text_edit.is_none(),
+ "view.twoHundredPercent" | "view.printSize" | "view.fitLayersOnScreen" => doc,
+ i if i.starts_with("window.arrange.") => match &i["window.arrange.".len()..] {
+ "consolidateAllToTabs" => true,
+ "floatInWindow" | "newWindowForDocument" => doc,
+ "matchZoom" | "matchLocation" | "matchRotation" | "matchAll" => app.session.documents().len() > 1 || !app.ui.windows.is_empty(),
+ _ => app.session.documents().len() > 1 || (doc && matches!(&i["window.arrange.".len()..], "floatAllInWindows" | "cascade" | "tile" | "tileAllVertically" | "tileAllHorizontally")),
+ },
+ i if wraps(i) => app.session.is_enabled(i),
+ _ => true,
+ })
+}
+
+pub fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ let o = &app.ui.view;
+ if let Some(k) = id.strip_prefix("view.show.") {
+ let mut s = o.show;
+ return show_slot(&mut s, k).map(|b| *b);
+ }
+ if let Some(k) = id.strip_prefix("view.snapTo.") {
+ let mut s = o.snap_to;
+ return snap_slot(&mut s, k).map(|b| *b);
+ }
+ if let Some(k) = id.strip_prefix("view.screenMode.") {
+ return SCREEN_MODES.contains(&k).then(|| o.screen_mode == k);
+ }
+ if let Some(k) = id.strip_prefix("view.pixelAspectRatio.") {
+ return PIXEL_ASPECTS.contains(&k).then(|| o.pixel_aspect == k);
+ }
+ if let Some(k) = id.strip_prefix("type.fontPreviewSize.") {
+ return FONT_PREVIEW.contains(&k).then(|| o.font_preview_size == k);
+ }
+ if let Some(k) = id.strip_prefix("type.languageOptions.") {
+ return if k == "middleEasternAndSouthAsianComposer" { Some(o.middle_eastern_composer) } else { LANGUAGE.contains(&k).then(|| o.language_features == k) };
+ }
+ if let Some(k) = id.strip_prefix("window.arrange.")
+ && LAYOUTS.contains(&k)
+ {
+ return Some(o.arrange == k);
+ }
+ if let Some((panel, tab)) = panel_tab(app, id) {
+ let (p, t) = (&app.ui.panels, &app.ui.dock_tabs);
+ let (vis, cur) = match panel {
+ "navigator" => (p.navigator, t.navigator),
+ "history" => (p.history, t.history),
+ "layers" => (p.layers, t.layers),
+ "color" => (p.color, t.color),
+ _ => (p.properties, t.properties),
+ };
+ return Some(vis && cur == tab);
+ }
+ if let Some(c) = type_checked(app, id) {
+ return Some(c);
+ }
+ Some(match id {
+ "view.extras" => o.extras,
+ "view.flipHorizontal" => o.flip_horizontal,
+ "view.pixelAspectRatioCorrection" => o.pixel_aspect_correction,
+ "view.patternPreview" => o.pattern_preview,
+ "view.pixelArtPreview" => o.pixel_art_preview,
+ _ => return None,
+ })
+}
+
+/// Checkmarks of the Type menu's anti-aliasing, orientation and OpenType items.
+fn type_checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ use photocraft_doc::LayerContent;
+ let st = app.session.active()?;
+ let LayerContent::Text(t) = &st.doc.layer(st.active_layer?)?.content else { return None };
+ if let Some(k) = id.strip_prefix("type.antiAlias.") {
+ return Some(photocraft_engine::type_extra_cmds::aa_name(t.antialias) == k);
+ }
+ if let Some(k) = id.strip_prefix("type.orientation.") {
+ return Some((t.orientation == photocraft_doc::text::Orientation::Vertical) == (k == "vertical"));
+ }
+ let tag = match id.strip_prefix("type.openType.")? {
+ "standardLigatures" => "liga",
+ "contextualAlternates" => "calt",
+ "discretionaryLigatures" => "dlig",
+ "swash" => "swsh",
+ "oldstyle" => "onum",
+ "stylisticAlternates" => "salt",
+ "titlingAlternates" => "titl",
+ "ornaments" => "ornm",
+ "ordinals" => "ordn",
+ "fractions" => "frac",
+ _ => return None,
+ };
+ Some(t.char_runs().first().is_some_and(|r| photocraft_engine::type_extra_cmds::feature_on(&r.style, tag)))
+}
+
+/// Engine commands that get a dialog or file picker here when invoked without parameters.
+fn wraps(id: &str) -> bool {
+ matches!(
+ id,
+ "file.openAs"
+ | "file.saveACopy"
+ | "file.placeEmbedded"
+ | "file.placeLinked"
+ | "file.closeAll"
+ | "file.closeOthers"
+ | "file.fileInfo"
+ | "file.automate.fitImage"
+ | "file.automate.conditionalModeChange"
+ | "file.automate.batch"
+ | "file.scripts.imageProcessor"
+ | "file.scripts.loadFilesIntoStack"
+ | "file.export.layersToFiles"
+ | "file.export.colorLookupTables"
+ | "view.newGuideLayout"
+ | "type.warpText"
+ | "type.pasteLoremIpsum"
+ )
+}
+
+fn no_params(p: &Value) -> bool {
+ p.as_object().is_none_or(|o| o.is_empty())
+}
+
+/// Run a View/Window/Type shell command, or front an engine command with its dialog. `None` when
+/// `id` isn't ours.
+pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ if wraps(id) {
+ return front(app, id, params);
+ }
+ if !handles(id) {
+ return None;
+ }
+ Some(run(app, ctx, id, params))
+}
+
+fn flag_param(p: &Value, cur: bool) -> bool {
+ p.get("on").and_then(Value::as_bool).unwrap_or(!cur)
+}
+
+fn run(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, p: &Value) -> Result<Value, String> {
+ if let Some((panel, tab)) = panel_tab(app, id) {
+ let (vis, cur) = panel_state(app, panel);
+ // Like Photoshop: choosing a visible panel's menu item again hides it.
+ if *vis && *cur == tab && !id.starts_with("type.panels.") {
+ *vis = false;
+ } else {
+ *vis = true;
+ *cur = tab;
+ }
+ return Ok(json!({"panel": panel, "tab": tab, "visible": *vis}));
+ }
+ let o = &mut app.ui.view;
+ if let Some(k) = id.strip_prefix("view.show.") {
+ if k == "all" {
+ o.show = Show { layer_edges: true, mesh: true, ..Show::default() };
+ o.extras = true;
+ app.ui.extras.grid = true;
+ app.ui.extras.guides = true;
+ return Ok(json!(true));
+ }
+ let slot = show_slot(&mut o.show, k).ok_or("unknown Show item")?;
+ *slot = flag_param(p, *slot);
+ let v = *slot;
+ if v {
+ // Showing an item turns Extras back on, as in Photoshop.
+ o.extras = true;
+ }
+ return Ok(json!(v));
+ }
+ if let Some(k) = id.strip_prefix("view.snapTo.") {
+ if k == "all" || k == "none" {
+ let on = k == "all";
+ o.snap_to = SnapTo { guides: on, grid: on, layers: on, slices: on, document_bounds: on };
+ return Ok(json!(on));
+ }
+ let slot = snap_slot(&mut o.snap_to, k).ok_or("unknown Snap To item")?;
+ *slot = flag_param(p, *slot);
+ return Ok(json!(*slot));
+ }
+ if let Some(k) = id.strip_prefix("view.screenMode.") {
+ let next = if k == "cycle" {
+ let i = SCREEN_MODES.iter().position(|m| *m == o.screen_mode).unwrap_or(0);
+ SCREEN_MODES[(i + 1) % SCREEN_MODES.len()]
+ } else {
+ k
+ };
+ o.screen_mode = next.to_string();
+ // Both full-screen modes take the whole display; the menu bar stays in the first.
+ ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(next != "standard"));
+ return Ok(json!({"screenMode": next}));
+ }
+ if let Some(k) = id.strip_prefix("view.pixelAspectRatio.") {
+ o.pixel_aspect = k.to_string();
+ return Ok(json!({"pixelAspectRatio": pixel_aspect_ratio(k)}));
+ }
+ if let Some(k) = id.strip_prefix("type.fontPreviewSize.") {
+ o.font_preview_size = k.to_string();
+ return Ok(json!(k));
+ }
+ if let Some(k) = id.strip_prefix("type.languageOptions.") {
+ if k == "middleEasternAndSouthAsianComposer" {
+ o.middle_eastern_composer = flag_param(p, o.middle_eastern_composer);
+ return Ok(json!(o.middle_eastern_composer));
+ }
+ o.language_features = k.to_string();
+ return Ok(json!(k));
+ }
+ if let Some(k) = id.strip_prefix("window.arrange.") {
+ return arrange(app, k);
+ }
+ match id {
+ "view.extras" => {
+ o.extras = flag_param(p, o.extras);
+ Ok(json!(o.extras))
+ }
+ "view.flipHorizontal" => {
+ o.flip_horizontal = flag_param(p, o.flip_horizontal);
+ Ok(json!(o.flip_horizontal))
+ }
+ "view.pixelAspectRatioCorrection" => {
+ o.pixel_aspect_correction = flag_param(p, o.pixel_aspect_correction);
+ Ok(json!(o.pixel_aspect_correction))
+ }
+ "view.patternPreview" => {
+ o.pattern_preview = flag_param(p, o.pattern_preview);
+ Ok(json!(o.pattern_preview))
+ }
+ "view.pixelArtPreview" => {
+ o.pixel_art_preview = flag_param(p, o.pixel_art_preview);
+ Ok(json!(o.pixel_art_preview))
+ }
+ "view.twoHundredPercent" | "view.printSize" => {
+ let i = app.session.active_index().ok_or("no document")?;
+ // Print Size assumes Photoshop's default 72 ppi screen resolution.
+ let dpi = app.session.active().map_or(72.0, |d| d.doc.resolution_dpi.max(1.0));
+ let z = if id == "view.twoHundredPercent" { 2.0 } else { 72.0 / dpi };
+ app.ui.views[i].zoom = z.clamp(0.01, 64.0);
+ Ok(json!({"zoom": app.ui.views[i].zoom}))
+ }
+ "view.fitLayersOnScreen" => fit_layers(app),
+ _ => Err(format!("unhandled {id}")),
+ }
+}
+
+/// View › Fit Layer(s) on Screen: zoom and centre on the selected layers' bounds.
+fn fit_layers(app: &mut PhotocraftApp) -> Result<Value, String> {
+ let i = app.session.active_index().ok_or("no document")?;
+ let st = app.session.active().ok_or("no document")?;
+ let mut b = photocraft_geom::Rect::EMPTY;
+ for id in st.selected_layers() {
+ if let Some(r) = st.doc.layer(id).and_then(|l| l.surface()).map(|s| s.content_bounds()) {
+ b = if b.is_empty() { r } else { b.union(&r) };
+ }
+ }
+ if b.is_empty() {
+ b = st.doc.bounds();
+ }
+ let area = app.last_canvas_rect.size();
+ let area = if area.x > 50.0 { area } else { egui::vec2(1200.0, 800.0) };
+ let v = &mut app.ui.views[i];
+ v.zoom = ((area.x - 40.0) / b.width().max(1) as f32).min((area.y - 40.0) / b.height().max(1) as f32).clamp(0.01, 64.0);
+ v.center = [(b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0];
+ v.fit_pending = false;
+ Ok(json!({"zoom": v.zoom, "bounds": [b.x0, b.y0, b.x1, b.y1]}))
+}
+
+fn float_window(app: &mut PhotocraftApp, doc: usize, offset: usize) -> u64 {
+ let wid = app.ui.alloc_id();
+ let mut view = app.ui.views.get(doc).cloned().unwrap_or_default();
+ view.fit_pending = offset > 0 || view.fit_pending;
+ app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true });
+ wid
+}
+
+fn arrange(app: &mut PhotocraftApp, k: &str) -> Result<Value, String> {
+ if LAYOUTS.contains(&k) {
+ app.ui.view.arrange = k.to_string();
+ // Each document fits its new cell.
+ app.ui.views.iter_mut().for_each(|v| v.fit_pending = true);
+ return Ok(json!({"arrange": k}));
+ }
+ match k {
+ "consolidateAllToTabs" => {
+ app.ui.view.arrange = "tabs".into();
+ app.ui.windows.clear();
+ Ok(json!({"arrange": "tabs"}))
+ }
+ "newWindowForDocument" | "floatInWindow" => {
+ let doc = app.session.active_index().ok_or("no document")?;
+ Ok(json!({"window": float_window(app, doc, 0)}))
+ }
+ "floatAllInWindows" | "cascade" => {
+ let n = app.session.documents().len();
+ let ids: Vec<u64> = (0..n).map(|d| float_window(app, d, d)).collect();
+ Ok(json!({"windows": ids}))
+ }
+ "matchZoom" | "matchLocation" | "matchRotation" | "matchAll" => {
+ let i = app.session.active_index().ok_or("no document")?;
+ let src = app.ui.views[i].clone();
+ let (zoom, loc) = (matches!(k, "matchZoom" | "matchAll"), matches!(k, "matchLocation" | "matchAll"));
+ let apply = |v: &mut crate::state::View| {
+ if zoom {
+ v.zoom = src.zoom;
+ }
+ if loc {
+ v.center = src.center;
+ }
+ v.fit_pending = false;
+ };
+ app.ui.views.iter_mut().for_each(apply);
+ app.ui.windows.iter_mut().for_each(|w| apply(&mut w.view));
+ // Views never rotate in Photocraft, so Match Rotation has nothing to align.
+ Ok(json!({"zoom": src.zoom, "center": src.center, "rotation": 0}))
+ }
+ _ => Err(format!("unknown arrangement {k}")),
+ }
+}
+
+/// Screen rectangles for `n` documents in an arrangement (`None` = tabs). The active document
+/// always gets a cell; n-up layouts show that many documents starting from the active one.
+pub fn cells(layout: &str, rect: egui::Rect, n: usize) -> Option<Vec<egui::Rect>> {
+ if n < 2 || !LAYOUTS.contains(&layout) {
+ return None;
+ }
+ let grid = |cols: usize, rows: usize, count: usize| -> Vec<egui::Rect> {
+ let (w, h) = (rect.width() / cols as f32, rect.height() / rows as f32);
+ (0..count.min(cols * rows)).map(|i| egui::Rect::from_min_size(rect.min + egui::vec2((i % cols) as f32 * w, (i / cols) as f32 * h), egui::vec2(w, h))).collect()
+ };
+ Some(match layout {
+ "tileAllVertically" => grid(n, 1, n),
+ "tileAllHorizontally" => grid(1, n, n),
+ "twoUpVertical" => grid(2, 1, 2),
+ "twoUpHorizontal" => grid(1, 2, 2),
+ "threeUpVertical" => grid(3, 1, 3),
+ "threeUpHorizontal" => grid(1, 3, 3),
+ "threeUpStacked" => {
+ let half = rect.width() / 2.0;
+ let left = egui::Rect::from_min_size(rect.min, egui::vec2(half, rect.height()));
+ let r = egui::Rect::from_min_max(egui::pos2(rect.min.x + half, rect.min.y), rect.max);
+ let top = egui::Rect::from_min_max(r.min, egui::pos2(r.max.x, r.center().y));
+ let bottom = egui::Rect::from_min_max(egui::pos2(r.min.x, r.center().y), r.max);
+ vec![left, top, bottom]
+ }
+ "fourUp" => grid(2, 2, 4),
+ "sixUp" => grid(3, 2, 6),
+ _ => {
+ let cols = (n as f32).sqrt().ceil() as usize;
+ grid(cols, n.div_ceil(cols), n)
+ }
+ })
+}
+
+// ---------- dialogs and pickers in front of engine commands ----------
+
+/// A generic form dialog that runs `command` with its fields on OK (rendered by [`form_body`]).
+fn form(app: &mut PhotocraftApp, command: &str, label: &str, fields: Value, choices: Value) -> u64 {
+ let mut f = Map::new();
+ f.insert("__command".into(), json!(command));
+ f.insert("__label".into(), json!(label));
+ f.insert("__form".into(), json!(true));
+ f.insert("__choices".into(), choices);
+ if let Value::Object(m) = fields {
+ f.extend(m);
+ }
+ app.ui.open_dialog(DialogKind::Command, f)
+}
+
+fn label_of(key: &str) -> String {
+ let mut out = String::new();
+ for (i, c) in key.chars().enumerate() {
+ if i == 0 {
+ out.extend(c.to_uppercase());
+ } else if c.is_uppercase() {
+ out.push(' ');
+ out.extend(c.to_lowercase());
+ } else {
+ out.push(c);
+ }
+ }
+ out
+}
+
+/// Body of a `__form` dialog: text fields, number fields, checkboxes and `__choices` dropdowns.
+pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let choices = f.get("__choices").cloned().unwrap_or(Value::Null);
+ let keys: Vec<String> = f.keys().filter(|k| !k.starts_with("__")).cloned().collect();
+ egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
+ for k in keys {
+ let v = f.get(&k).cloned().unwrap_or(Value::Null);
+ let new = match &v {
+ Value::Array(_) | Value::Object(_) | Value::Null => continue,
+ Value::Bool(b) => {
+ ui.label("");
+ let mut b = *b;
+ ui.checkbox(&mut b, label_of(&k));
+ json!(b)
+ }
+ Value::String(s) => {
+ ui.label(label_of(&k));
+ let mut s = s.clone();
+ match choices.get(&k).and_then(Value::as_array) {
+ Some(opts) => {
+ let opts: Vec<(String, String)> = opts.iter().filter_map(Value::as_str).map(|o| (o.to_string(), label_of(o))).collect();
+ let refs: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect();
+ crate::widgets::dropdown(ui, &format!("form-{k}"), &mut s, &refs, 200.0);
+ }
+ None => {
+ ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0));
+ }
+ }
+ json!(s)
+ }
+ Value::Number(n) => {
+ ui.label(label_of(&k));
+ if let Some(mut i) = n.as_i64() {
+ ui.add(egui::DragValue::new(&mut i));
+ json!(i)
+ } else {
+ let mut x = n.as_f64().unwrap_or(0.0);
+ ui.add(egui::DragValue::new(&mut x).speed(0.5));
+ json!(x)
+ }
+ }
+ };
+ f.insert(k, new);
+ ui.end_row();
+ }
+ });
+}
+
+/// Folder the batch dialogs start from: next to the active document, else the working directory.
+fn default_dir(app: &PhotocraftApp) -> String {
+ app.session
+ .active()
+ .and_then(|d| d.path.as_deref())
+ .and_then(|p| p.rfind(['/', '\\']).map(|i| p[..i].to_string()))
+ .unwrap_or_else(|| ".".into())
+}
+
+fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ if id == "file.closeAll" || id == "file.closeOthers" {
+ // Keep the remaining document's view (views are index-aligned with documents).
+ let keep = app.session.active_index().and_then(|i| app.ui.views.get(i).cloned());
+ let r = app.run(id, params.clone());
+ if r.is_ok() {
+ app.ui.views = if id == "file.closeAll" { Vec::new() } else { keep.into_iter().collect() };
+ app.ui.windows.clear();
+ app.sync_views();
+ }
+ return Some(r);
+ }
+ if id == "type.pasteLoremIpsum" && no_params(params) {
+ // While typing, paste at the caret.
+ if let Some(te) = app.ui.text_edit.clone() {
+ let r = app.run(id, json!({"layer": te.layer, "at": te.caret, "coalesce": te.session}));
+ if let (Ok(v), Some(te)) = (&r, app.ui.text_edit.as_mut())
+ && let Some(c) = v.get("caret").and_then(Value::as_u64)
+ {
+ te.caret = c as usize;
+ te.anchor = c as usize;
+ }
+ return Some(r);
+ }
+ return None;
+ }
+ if !no_params(params) {
+ return None;
+ }
+ let doc = app.session.active().map(|d| (d.doc.size.width, d.doc.size.height, d.doc.name.clone()));
+ let dir = default_dir(app);
+ let label = photocraft_engine::commands::find(id).map_or(id, |c| c.label);
+ let dialog = |app: &mut PhotocraftApp, fields: Value, choices: Value| Some(Ok(json!({"dialog": form(app, id, label, fields, choices)})));
+ match id {
+ "file.openAs" => {
+ app.open_dialog_file();
+ Some(Ok(Value::Null))
+ }
+ "file.saveACopy" => Some(save_a_copy(app)),
+ "file.placeEmbedded" | "file.placeLinked" => {
+ let (name, bytes) = app.services.pick_open.as_mut().and_then(|f| f())?;
+ let linked = (id == "file.placeLinked").then(|| name.clone());
+ let r = photocraft_engine::file_cmds::place_bytes(&mut app.session, &name, bytes, linked, &json!({})).map_err(|e| e.to_string());
+ app.sync_views();
+ Some(r)
+ }
+ "file.fileInfo" => {
+ let info = app.session.execute("file.fileInfo", json!({})).ok()?;
+ let kw = info["keywords"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; ")).unwrap_or_default();
+ dialog(
+ app,
+ json!({"title": info["title"], "author": info["author"], "authorTitle": info["authorTitle"], "description": info["description"], "keywords": kw, "copyright": info["copyright"], "copyrightStatus": info["copyrightStatus"], "copyrightUrl": info["copyrightUrl"]}),
+ json!({"copyrightStatus": ["unknown", "copyrighted", "publicDomain"]}),
+ )
+ }
+ "file.automate.fitImage" => {
+ let (w, h, _) = doc?;
+ dialog(app, json!({"width": w, "height": h, "dontEnlarge": false}), json!({}))
+ }
+ "file.automate.conditionalModeChange" => dialog(app, json!({"from": "any", "to": "rgb"}), json!({"from": ["any", "rgb", "grayscale", "cmyk", "lab", "indexed", "bitmap", "duotone", "multichannel"], "to": ["rgb", "grayscale", "cmyk", "lab"]})),
+ "view.newGuideLayout" => dialog(app, json!({"columns": 8, "gutter": 20, "rows": 0, "rowGutter": 0, "margin": 0, "centerColumns": false, "clearExisting": false}), json!({})),
+ "type.warpText" => {
+ let styles: Vec<&str> = std::iter::once("none").chain(photocraft_text::warp::STYLES.iter().map(|(_, s)| *s)).collect();
+ dialog(app, json!({"style": "arc", "orientation": "horizontal", "bend": 50.0, "horizontalDistortion": 0.0, "verticalDistortion": 0.0}), json!({"style": styles, "orientation": ["horizontal", "vertical"]}))
+ }
+ "file.export.layersToFiles" => {
+ let (_, _, name) = doc?;
+ dialog(app, json!({"dir": dir, "prefix": name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a), "format": "png", "visibleOnly": true}), json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]}))
+ }
+ "file.export.colorLookupTables" => {
+ let (_, _, name) = doc?;
+ let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string();
+ dialog(app, json!({"path": format!("{dir}/{stem}.cube"), "size": 33, "title": stem}), json!({}))
+ }
+ "file.scripts.loadFilesIntoStack" => dialog(app, json!({"paths": dir}), json!({})),
+ "file.scripts.imageProcessor" => dialog(app, json!({"input": dir, "output": format!("{dir}/processed"), "format": "jpg", "quality": 8, "width": 0, "height": 0, "convertToSrgb": true}), json!({"format": ["jpg", "png", "psd", "tiff"]})),
+ "file.automate.batch" => {
+ let a = &app.ui.actions;
+ let action = a.selected.and_then(|i| a.list.get(i)).or(a.list.first());
+ let Some(action) = action else {
+ return Some(Err("record an action in the Actions panel first".into()));
+ };
+ let steps: Vec<Value> = action.steps.iter().map(|(id, p)| json!([id, p])).collect();
+ let name = action.name.clone();
+ dialog(app, json!({"action": name, "steps": steps, "input": dir, "output": format!("{dir}/batch"), "format": "same"}), json!({"format": ["same", "png", "jpg", "psd", "tiff"]}))
+ }
+ // Channel workflow dialogs (see channels_panel.rs for the channel references).
+ "select.saveSelection" | "select.loadSelection" | "image.applyImage" | "image.calculations" => {
+ let st = app.session.active()?;
+ let d = &st.doc;
+ let mode = d.pixel_format().mode;
+ let mut chans: Vec<String> = vec![photocraft_engine::channel_cmds::composite_name(mode).to_string()];
+ if mode.color_channels() > 1 {
+ chans.extend(photocraft_engine::channel_cmds::color_names(mode).iter().map(|n| n.to_string()));
+ }
+ chans.extend(d.channels.iter().map(|c| c.name.clone()));
+ let alphas: Vec<String> = std::iter::once("new".to_string()).chain(d.channels.iter().map(|c| c.name.clone())).collect();
+ let blends = ["multiply", "screen", "normal", "overlay", "softLight", "hardLight", "darken", "lighten", "colorDodge", "colorBurn", "linearBurn", "linearDodge", "difference", "exclusion", "add", "subtract"];
+ let mut load = chans.clone();
+ load.extend(["transparency", "mask", "selection"].map(String::from));
+ match id {
+ "select.saveSelection" => dialog(app, json!({"channel": "new", "name": "", "operation": "new"}), json!({"channel": alphas, "operation": ["new", "replace", "add", "subtract", "intersect"]})),
+ "select.loadSelection" => {
+ let first = d.channels.first().map_or_else(|| chans[0].clone(), |c| c.name.clone());
+ dialog(app, json!({"channel": first, "invert": false, "operation": "new"}), json!({"channel": load, "operation": ["new", "add", "subtract", "intersect"]}))
+ }
+ "image.applyImage" => {
+ let mut masks = vec!["none".to_string()];
+ masks.extend(load.iter().cloned());
+ dialog(app, json!({"sourceChannel": chans[0], "sourceInvert": false, "blending": "multiply", "opacity": 100.0, "preserveTransparency": false, "maskChannel": "none"}), json!({"sourceChannel": load, "blending": blends, "maskChannel": masks}))
+ }
+ _ => dialog(app, json!({"source1Channel": chans[0], "source1Invert": false, "source2Channel": chans[0], "source2Invert": false, "blending": "multiply", "opacity": 100.0, "result": "newChannel"}), json!({"source1Channel": load.clone(), "source2Channel": load, "blending": blends, "result": ["newChannel", "newDocument", "selection"]})),
+ }
+ }
+ _ => None,
+ }
+}
+
+/// File › Save a Copy: pick a name, encode with the export service, write; the document's path
+/// and saved state are untouched.
+fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {
+ let st = app.session.active().ok_or("no document")?;
+ let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a).to_string();
+ let suggested = format!("{stem} copy.psd");
+ let path = app.services.pick_save.as_mut().and_then(|f| f(&suggested)).ok_or("cancelled")?;
+ let export = app.services.export.as_ref().ok_or("no exporter configured")?;
+ let doc = app.session.active().ok_or("no document")?.doc.clone();
+ let bytes = export(&doc, &path, &crate::ExportSettings::default())?;
+ let write = app.services.write.as_mut().ok_or("no writer configured")?;
+ write(&path, &bytes)?;
+ app.ui.status = format!("Saved a copy as {path}");
+ Ok(json!({"path": path}))
+}
+
+#[cfg(test)]
+#[path = "view_cmds/tests.rs"]
+mod tests;
diff --git a/crates/ui-egui/src/view_cmds/tests.rs b/crates/ui-egui/src/view_cmds/tests.rs
new file mode 100644
index 000000000..d1cb4202a
--- /dev/null
+++ b/crates/ui-egui/src/view_cmds/tests.rs
@@ -0,0 +1,164 @@
+use super::*;
+use crate::menus::{invoke as menu, is_live, menu_items};
+
+fn app_with(n: usize) -> (PhotocraftApp, egui::Context) {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ for i in 0..n {
+ app.run("file.new", json!({"width": 100 + i as u32 * 10, "height": 80})).unwrap();
+ }
+ app.sync_views();
+ (app, egui::Context::default())
+}
+
+fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ menu_items(app).into_iter().find(|i| i.id == id).and_then(|i| i.checked)
+}
+
+#[test]
+fn show_snap_extras_and_screen_modes_are_state() {
+ let (mut app, ctx) = app_with(1);
+ for id in ["view.show.layerEdges", "view.show.pixelGrid", "view.snapTo.layers", "view.extras", "view.screenMode.fullScreen", "view.flipHorizontal", "window.arrange.fourUp", "type.fontPreviewSize.huge", "type.languageOptions.eastAsianFeatures"] {
+ assert!(is_live(id), "{id}");
+ }
+ assert_eq!(checked(&app, "view.show.layerEdges"), Some(false));
+ menu(&mut app, &ctx, "view.show.layerEdges", json!({})).unwrap();
+ assert!(app.ui.view.show.layer_edges);
+ assert_eq!(checked(&app, "view.show.layerEdges"), Some(true));
+ menu(&mut app, &ctx, "view.extras", json!({})).unwrap();
+ assert!(!app.ui.view.extras && !app.ui.view.shows(app.ui.view.show.layer_edges));
+ // Showing any item turns Extras back on.
+ menu(&mut app, &ctx, "view.show.mesh", json!({})).unwrap();
+ assert!(app.ui.view.extras);
+ menu(&mut app, &ctx, "view.snapTo.none", json!({})).unwrap();
+ assert!(!app.ui.view.snap_to.guides && !app.ui.view.snap_to.document_bounds);
+ menu(&mut app, &ctx, "view.snapTo.grid", json!({})).unwrap();
+ assert_eq!(checked(&app, "view.snapTo.grid"), Some(true));
+ // F cycles the screen modes.
+ for want in ["fullScreenWithMenuBar", "fullScreen", "standard"] {
+ menu(&mut app, &ctx, "view.screenMode.cycle", json!({})).unwrap();
+ assert_eq!(app.ui.view.screen_mode, want);
+ }
+ menu(&mut app, &ctx, "view.screenMode.fullScreen", json!({})).unwrap();
+ assert!(app.ui.view.hides_chrome() && app.ui.view.hides_tabs());
+ assert_eq!(checked(&app, "view.screenMode.fullScreen"), Some(true));
+ menu(&mut app, &ctx, "view.pixelAspectRatio.anamorphic2To1", json!({})).unwrap();
+ assert_eq!(pixel_aspect_ratio(&app.ui.view.pixel_aspect), 2.0);
+ // State serializes with the rest of the UI (control channel).
+ let v = serde_json::to_value(&app.ui).unwrap();
+ assert_eq!(v["view"]["screen_mode"], "fullScreen");
+ assert_eq!(v["view"]["show"]["layer_edges"], true);
+}
+
+#[test]
+fn zoom_presets_and_fit_layers() {
+ let (mut app, ctx) = app_with(1);
+ menu(&mut app, &ctx, "view.twoHundredPercent", json!({})).unwrap();
+ assert_eq!(app.ui.views[0].zoom, 2.0);
+ app.run("image.imageSize", json!({"resolution": 144, "resample": "none"})).unwrap();
+ menu(&mut app, &ctx, "view.printSize", json!({})).unwrap();
+ assert_eq!(app.ui.views[0].zoom, 0.5);
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.run("select.rect", json!({"x": 10, "y": 20, "width": 10, "height": 10})).unwrap();
+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ menu(&mut app, &ctx, "view.fitLayersOnScreen", json!({})).unwrap();
+ assert_eq!(app.ui.views[0].center, [15.0, 25.0]);
+ assert!(app.ui.views[0].zoom > 10.0);
+}
+
+#[test]
+fn arrange_layouts_floating_windows_and_matching() {
+ let (mut app, ctx) = app_with(3);
+ assert!(cells("tabs", egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 600.0)), 3).is_none());
+ menu(&mut app, &ctx, "window.arrange.threeUpStacked", json!({})).unwrap();
+ assert_eq!(checked(&app, "window.arrange.threeUpStacked"), Some(true));
+ let c = cells(&app.ui.view.arrange, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 600.0)), 3).unwrap();
+ assert_eq!(c.len(), 3);
+ assert_eq!(c[0].height(), 600.0);
+ assert_eq!(c[1].height(), 300.0);
+ let six = cells("sixUp", egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 600.0)), 3).unwrap();
+ assert_eq!((six.len(), six[1].min.x), (6, 300.0));
+ menu(&mut app, &ctx, "window.arrange.floatAllInWindows", json!({})).unwrap();
+ assert_eq!(app.ui.windows.len(), 3);
+ app.ui.views[2].zoom = 3.0;
+ app.ui.views[2].center = [1.0, 2.0];
+ menu(&mut app, &ctx, "window.arrange.matchAll", json!({})).unwrap();
+ assert!(app.ui.views.iter().all(|v| v.zoom == 3.0 && v.center == [1.0, 2.0]));
+ assert!(app.ui.windows.iter().all(|w| w.view.zoom == 3.0));
+ menu(&mut app, &ctx, "window.arrange.consolidateAllToTabs", json!({})).unwrap();
+ assert!(app.ui.windows.is_empty());
+ assert_eq!(app.ui.view.arrange, "tabs");
+ menu(&mut app, &ctx, "window.arrange.newWindowForDocument", json!({})).unwrap();
+ assert_eq!(app.ui.windows.len(), 1);
+}
+
+#[test]
+fn window_panels_select_dock_tabs() {
+ let (mut app, ctx) = app_with(1);
+ menu(&mut app, &ctx, "window.panel.info", json!({})).unwrap();
+ assert!(app.ui.panels.navigator && app.ui.dock_tabs.navigator == 2);
+ assert_eq!(checked(&app, "window.panel.info"), Some(true));
+ assert_eq!(checked(&app, "window.panel.histogram"), Some(false));
+ menu(&mut app, &ctx, "window.panel.histogram", json!({})).unwrap();
+ assert_eq!(app.ui.dock_tabs.navigator, 1);
+ menu(&mut app, &ctx, "window.panel.actions", json!({})).unwrap();
+ assert!(app.ui.panels.history && app.ui.dock_tabs.history == 1);
+ menu(&mut app, &ctx, "window.panel.paths", json!({})).unwrap();
+ assert_eq!(app.ui.dock_tabs.layers, 2);
+ // Again on the visible tab hides the panel.
+ menu(&mut app, &ctx, "window.panel.paths", json!({})).unwrap();
+ assert!(!app.ui.panels.layers);
+ menu(&mut app, &ctx, "type.panels.character", json!({})).unwrap();
+ assert!(app.ui.panels.properties && app.ui.dock_tabs.properties == 0);
+ for id in ["window.panel.channels", "window.panel.swatches", "window.panel.adjustments", "window.panel.paragraph"] {
+ assert!(is_live(id), "{id}");
+ }
+}
+
+#[test]
+fn type_menu_checkmarks_follow_the_layer() {
+ let (mut app, ctx) = app_with(1);
+ assert!(!crate::menus::is_enabled(&app, "type.antiAlias.crisp"));
+ app.run("type.create", json!({"x": 10, "y": 50, "text": "Type", "size": 24})).unwrap();
+ menu(&mut app, &ctx, "type.antiAlias.crisp", json!({})).unwrap();
+ assert_eq!(checked(&app, "type.antiAlias.crisp"), Some(true));
+ assert_eq!(checked(&app, "type.antiAlias.smooth"), Some(false));
+ menu(&mut app, &ctx, "type.openType.fractions", json!({})).unwrap();
+ assert_eq!(checked(&app, "type.openType.fractions"), Some(true));
+ assert_eq!(checked(&app, "type.openType.standardLigatures"), Some(true));
+ assert_eq!(checked(&app, "type.orientation.horizontal"), Some(true));
+}
+
+#[test]
+fn engine_commands_open_their_dialogs() {
+ let (mut app, ctx) = app_with(2);
+ let d = menu(&mut app, &ctx, "file.automate.fitImage", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ let dlg = app.ui.dialog_mut(d).unwrap();
+ assert_eq!(dlg.fields["width"], 110);
+ dlg.fields.insert("width".into(), json!(55));
+ dlg.fields.insert("height".into(), json!(1000));
+ crate::dialogs::confirm(&mut app, d).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.size.width, 55);
+ let d = menu(&mut app, &ctx, "file.fileInfo", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ app.ui.dialog_mut(d).unwrap().fields.insert("title".into(), json!("Wheat Field"));
+ crate::dialogs::confirm(&mut app, d).unwrap();
+ assert_eq!(app.run("file.fileInfo", json!({})).unwrap()["title"], "Wheat Field");
+ let d = menu(&mut app, &ctx, "view.newGuideLayout", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ assert_eq!(app.ui.dialog_mut(d).unwrap().fields["columns"], 8);
+ app.ui.dialog_mut(d).unwrap().fields.insert("columns".into(), json!(2));
+ app.ui.dialog_mut(d).unwrap().fields.insert("gutter".into(), json!(10));
+ crate::dialogs::confirm(&mut app, d).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![0.0, 22.5, 32.5, 55.0]);
+ app.run("type.create", json!({"x": 5, "y": 40, "text": "Warp", "size": 20})).unwrap();
+ let d = menu(&mut app, &ctx, "type.warpText", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ crate::dialogs::confirm(&mut app, d).unwrap();
+ assert!(app.run("type.info", json!({})).unwrap()["warp"]["style"] == "warpArc");
+ // Batch needs a recorded action.
+ assert!(menu(&mut app, &ctx, "file.automate.batch", json!({})).is_err());
+ // Close Others keeps the active document's view.
+ app.ui.views[1].zoom = 4.0;
+ menu(&mut app, &ctx, "file.closeOthers", json!({})).unwrap();
+ assert_eq!(app.ui.views.len(), 1);
+ assert_eq!(app.ui.views[0].zoom, 4.0);
+ menu(&mut app, &ctx, "file.closeAll", json!({})).unwrap();
+ assert!(app.ui.views.is_empty() && app.session.documents().is_empty());
+}
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 7cebb4ced..d661322d3 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -121,6 +121,8 @@ pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive
}
let suffix_w = if suffix.is_empty() { 0.0 } else { 16.0 };
let field = Rect::from_min_max(rect.min + vec2(4.0, 2.0), rect.max - vec2(4.0 + suffix_w, 2.0));
+ // Small ranges (gamma 0.01–9.99, 0–1 centres) need two decimals and a finer drag, like Photoshop.
+ let fine = range.end() - range.start() <= 10.0;
// new_child (not scope_builder): a scope would move the parent cursor back to the child rect.
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(field));
let resp = {
@@ -133,7 +135,7 @@ pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive
ui.style_mut().visuals.widgets.hovered.weak_bg_fill = Color32::TRANSPARENT;
ui.style_mut().override_font_id = Some(theme::mono(12.0));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- ui.add_sized(field.size(), egui::DragValue::new(value).range(range).speed(0.5).custom_formatter(|v, _| fmt_num(v)))
+ ui.add_sized(field.size(), egui::DragValue::new(value).range(range).speed(if fine { 0.01 } else { 0.5 }).custom_formatter(|v, _| if fine { fmt_num2(v) } else { fmt_num(v) }))
})
.inner
}
@@ -409,8 +411,22 @@ pub fn fmt_num(v: f64) -> String {
if (r - r.round()).abs() < 1e-9 { format!("{}", r.round() as i64) } else { format!("{r:.1}") }
}
+/// Two-decimal variant of [`fmt_num`] for small ranges: `1.05`, `0.78`, `2`.
+pub fn fmt_num2(v: f64) -> String {
+ let r = (v * 100.0).round() / 100.0;
+ format!("{r:.2}").trim_end_matches('0').trim_end_matches('.').to_string()
+}
+
#[cfg(test)]
mod tests {
+ #[test]
+ fn two_decimal_numbers_trim_zeros() {
+ assert_eq!(super::fmt_num2(1.05), "1.05");
+ assert_eq!(super::fmt_num2(0.78), "0.78");
+ assert_eq!(super::fmt_num2(0.5), "0.5");
+ assert_eq!(super::fmt_num2(2.0), "2");
+ }
+
#[test]
fn numbers_drop_trailing_zero() {
assert_eq!(super::fmt_num(100.0), "100");
diff --git a/docs/architecture.md b/docs/architecture.md
index a40f74436..a7049d0c9 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -79,7 +79,8 @@ photocraft/
├─ crates/
│ │ ── foundation (no_std-friendly where practical, wasm-safe) ──
│ ├─ geom/ photocraft-geom points, rects, affine/perspective, tile coords, bezier (kurbo)
-│ ├─ color/ photocraft-color pixel formats, color spaces, ICC (moxcms), blend-mode math (scalar reference)
+│ ├─ cms/ photocraft-cms pure-Rust ICC colour management: profiles, transforms, intents, BPC, soft proof, 3D LUTs
+│ ├─ color/ photocraft-color pixel formats, color spaces, blend-mode math (scalar reference); conversions via cms
│ ├─ raster/ photocraft-raster tiled COW surfaces, masks, mip pyramids, damage regions, pixel iterators
│ │ ── document ──
│ ├─ doc/ photocraft-doc document model: layer tree, masks, effects, channels, paths, guides, metadata (pure data + serde)
@@ -121,6 +122,8 @@ photocraft/
└─ plan/ this directory
```
+**What exists today.** This layout is the target design. Built so far: `geom`, `cms`, `color`, `raster`, `psd`, `codecs`, `doc`, `ops`, `algo`, `paint`, `text`, `vector`, `compose`, `gpu`, `format`, `io`, `engine`, `ui-egui`, `automation`, `testkit`, and the three apps. Not yet split out: `viewport` and `tools` live inside `ui-egui` and `engine`; `platform` services are function hooks injected by each app (`ui_egui::Services`); `adobe-assets`, `raw` and `ml` are not started.
+
**Crate granularity:** start with the crates above. Split `algo` into `-adjust`, `-filters`, `-select`, `-inpaint` and `-warp` once any module passes about 10k lines, or once compile times hurt. Its internal module boundaries should already follow those lines.
**Naming:** directories are short and packages are prefixed `photocraft-`. `photocraft-psd` gets a neutral, publishable name (such as `psd-rw`) if we release it to crates.io.
@@ -312,7 +315,7 @@ Both backends consume the same plan. This is the only place that encodes Photosh
### 7.3 Color
- Blending happens in document space by default, which is Photoshop-compatible. A per-document "linear light blending" option is also available.
-- **Display transform:** compose the ICC transforms with moxcms, then bake them into a 1D + 3D LUT that the viewport's final pass applies.
+- **Display transform:** compose the ICC transforms with `photocraft-cms`, then bake them into a 3D LUT that the canvas shader's final pass applies (Proof Colors and Gamut Warning work this way today).
- **HDR/EDR output** (an `rgba16float` surface with an extended-range colorspace) is a later-phase feature. The interfaces already carry `f32` pixels.
### 7.4 Oracle
@@ -478,7 +481,7 @@ schemars = "1"
blake3 = "1"
zstd = "*" # native; ruzstd for wasm decode
# color / codecs
-moxcms = "*"
+# ICC: our own photocraft-cms (pure Rust)
image = { version = "*", default-features = false }
jxl-oxide = "*"
# gpu
diff --git a/docs/contributing.md b/docs/contributing.md
index eea5488cd..7f6efa613 100644
--- a/docs/contributing.md
+++ b/docs/contributing.md
@@ -2,10 +2,24 @@
- **Language:** Rust only. No JavaScript or TypeScript. On the web, `wasm-bindgen` generates a small loader; never hand-write JS.
- **Licence:** contributions are MIT OR Apache-2.0 (workspace default; see `plan/` for the pending licence decision).
-- **Clean-room:** do not copy code, shaders, icons or other assets from proprietary software (Photon Studio, Photoshop). Match behaviour and look by observation and public specs. Only use assets with permissive licences, and record them next to the asset (e.g. `assets/fonts/OFL-*.txt`, `assets/icons/LICENSE-lucide.txt`).
-- **Commands, not handlers:** new features are engine commands with tests, and the UI calls them.
+- **Clean-room:** do not copy code, shaders, icons, ICC profiles or other assets from proprietary software (Photon Studio, Photoshop). Match behaviour and look by observation and public specs. Only use assets with permissive licences, and record them next to the asset (e.g. `assets/fonts/OFL-*.txt`, `assets/icons/LICENSE-lucide.txt`, `docs/images/SOURCES.md`).
+- **Commands, not handlers:** new features are engine commands with tests, and the UI calls them (checklist below).
- **Layering:** `cargo xtask layers` must pass. Register new crates in `xtask/src/layers.rs`.
-- **Tests:** required for every change. Format code needs round-trip and malformed-input tests.
+- **Tests:** required for every change. Format code needs round-trip and malformed-input tests. Pixel code is tested at 8, 16 and 32-bit.
- **Style:** `cargo fmt`, and `cargo clippy -- -D warnings`. Match surrounding code. Comments explain *why*.
-- **UI:** use `theme::Tokens` and `widgets::*`. Verify visually through the control channel before submitting, and attach before/after screenshots to PRs.
+- **UI:** use `theme::Tokens` and `widgets::*`. Verify visually (offscreen `snapshot` example or the control channel) before submitting, and attach before/after screenshots to PRs.
- **Commits:** small, focused, with a clear subject line.
+
+## Adding a command
+
+1. **Find the id.** Search `crates/ui-egui/src/menu_catalog.rs` for the Photoshop menu item. Using its id makes the menu item live with no UI work. Commands without a Photoshop menu entry use a descriptive id in the same style (`layer.smartFilter.delete`) and an empty menu path.
+2. **Algorithm** goes in the lowest crate that fits (`algo` for imaging, `paint`, `vector`, `text`, `cms`), with unit tests. It takes depth-agnostic surfaces (`photocraft-raster`), works per tile, and is deterministic (seeded randomness).
+3. **Command** goes in an engine module (`crates/engine/src/<area>_cmds.rs`) exposing `specs()`, registered with `v.extend(...)` in `commands.rs`. Fill in:
+ - `id`, `label`, `menu` path and Photoshop's default `shortcut`,
+ - a params doc string such as `{"radius":px=4,"mode":"a|b"="a"}` (this is what agents read through `commands` / `command_list`),
+ - an `enabled` predicate (greys the menu item out),
+ - `run`, which returns a JSON result and records exactly **one** history step (use `coalesce` for drags and typing sessions).
+4. **Respect the context:** active selection (feathered), layer vs mask target, locks, the colour model and depth.
+5. **Tests** in the module: behaviour, undo/redo, disabled states, bad params, several depths.
+6. **Dialog** (if it has parameters): filters and adjustments get schema-driven dialogs with live preview (`ui-egui/src/filter_dialog.rs`, `dialogs.rs`).
+7. Run `cargo xtask parity` and commit the updated `docs/parity.md`.
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 3f8305adf..ce1f0e50b 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -17,10 +17,10 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
## Methods
-- `engine.execute {command, params}`: run any engine or UI command by id
+- `engine.execute {command, params}`: run any engine or UI command by id. Engine commands run directly with their default params and never open a dialog. Use `ui.menu.invoke` for menu-click behaviour, which opens a command's dialog when no params are given
- `engine.commands`: list commands with enablement
-- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, menu tree, window size)
-- `ui.set {tool?, panels?, dockTabs?, maskTarget?, zoom?, center?, dark?}`: change UI state
+- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, menu tree, window size). `view` holds the View/Window/Type preferences: `screen_mode`, `extras`, `show` and `snap_to` flags, `flip_horizontal`, `arrange` (Window › Arrange layout), pixel aspect, font preview size, language options
+- `ui.set {tool?, panels?, dockTabs?, maskTarget?, zoom?, center?, fit?, theme?, brushSize?, brushSection?, brushTab?}`: change UI state (`brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes)
- `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
@@ -42,6 +42,8 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
|---|---|
| `file.new` | `{"width":1920,"height":1080,"mode":"rgb","depth":8,"background":"white"}` |
| `layer.new.layer` | `{"name":"Ink"}` |
+| `layer.select` | `{"layer":id,"mode":"replace\|toggle\|range\|add"}`: ⌘-click = toggle, ⇧-click = range; `document.inspect` reports `selectedLayers` and a per-layer `selected` flag |
+| `channel.target` / `channel.setVisible` | Channels panel target and eyes (`"composite"`, colour name, alpha index or name, `"quickMask"`). `document.inspect` (and `channel.list`) report `channels`: composite/colour/alpha rows with visibility, channel options, `quickMask`, `target`. Pixel commands without a `target` param follow the targeted channel |
| `layer.setProps` | `{"layer":id?,"name":…,"visible":…,"opacity":0..1,"blend":"Multiply"}` |
| `layer.newAdjustmentLayer.hueSaturation` | `{"hue":30,"saturation":10}` |
| `paint.stroke` | `{"points":[[x,y,pressure],…],"size":20,"color":"#ff0000"}` |
@@ -51,6 +53,48 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
UI-level commands (`file.open`, `file.save`, `view.zoomIn`, `window.theme.pro`, `edit.search`, …) are also accepted by `engine.execute` and `ui.menu.invoke`.
+## Preferences
+
+Preferences (Edit › Preferences, grouped like Photoshop's dialog sections) live in the engine, so
+the same commands work in the app, the CLI and headless MCP. Paths are dotted camelCase keys:
+`<section>.<key>`, with sections `general`, `interface`, `workspace`, `tools`, `historyLog`,
+`fileHandling`, `export`, `performance`, `scratchDisks`, `cursors`, `transparencyAndGamut`,
+`unitsAndRulers`, `guidesGridAndSlices`, `plugIns`, `type`, `enhancedControls`, `rawDefaults`,
+`integrations`, plus `shortcuts.<command id>`, `menus` (`hidden`, `colors.<id>`), `toolbar`
+(`hidden`, `order`) and `colorSettings` (Edit › Color Settings).
+
+| Command | Params |
+|---|---|
+| `prefs.get` | `{"path":"performance.historyStates"}`; no path returns everything |
+| `prefs.set` | `{"path":"cursors.painting","value":"precise"}` or `{"values":{"unitsAndRulers.rulers":"cm","guidesGridAndSlices.gridColor":"#ff8800"}}`. Values are validated (choices, ranges, `#rrggbb` colours, shortcut syntax); a batch applies all or nothing. A section path takes an object and merges it key by key |
+| `prefs.reset` | `{"path":"performance"}` (a section or key); no path resets everything |
+| `edit.preferences.<section>` | the section's values; in the app (no params) it opens the Preferences dialog on that section |
+| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. In the app it opens Keyboard Shortcuts and Menus |
+| `edit.menus` / `edit.toolbar` | `{"hide":["edit.fade"],"show":[…],"color":{"edit.fill":"red"},"reset":false}` / `{"hidden":["Sponge"],"order":[…]}` |
+| `edit.colorSettings` | `{"workingRgb":"display-p3","workingCmyk":"coated-cmyk","workingGray":"sgray","policyRgb":"preserve\|convert\|off",…,"askOnMismatch":true,"intent":"perceptual","bpc":true}`; honoured when opening files (`file.openAs`, the app's File › Open) and by Image › Mode and "working" profile specs. `color.profileMismatch {"action":"preserve\|convert\|discard\|assignWorking"}` answers the mismatch prompt |
+
+Values the app honours live: history states (every open document), effect-cache budget, interface
+theme, canvas colour and border, checkerboard size and colours (CPU and GPU canvas), gamut warning
+colour and opacity, guide/grid/smart-guide colours and styles, grid spacing and subdivisions, ruler
+units (rulers, Info panel, Image Size default unit), image interpolation (Image Size default),
+painting and other cursors, zoom with scroll wheel, Use Shift Key for Tool Switch, keyboard
+shortcuts, hidden and coloured menu items, autosave interval and crash recovery, and the history
+log text file. GPU on/off and the GPU tile size apply at the next launch.
+
+The desktop app stores them in `preferences.json` in the platform config directory (macOS
+`~/Library/Application Support/Photocraft`, Windows `%APPDATA%\Photocraft`, Linux
+`$XDG_CONFIG_HOME/photocraft`; override with `PHOTOCRAFT_CONFIG_DIR`); autosaves go to its
+`Recovery` folder. The web build keeps them in `localStorage`.
+
+## Snapping
+
+With View › Snap on, tool gestures snap to the View › Snap To targets (guides and grid while they
+are shown, layer edges and centres, document bounds and centre, selection edges) within 8 screen
+pixels: Move tool drags (the moved layers' bounds), marquee, crop, shape, type-box and pen points,
+Free Transform handles and drags inside the box, and guides. Holding Ctrl disables snapping for
+the drag. With View › Show › Smart Guides on, the Move tool also snaps to other layers and draws
+magenta alignment lines. `ui.pointer` drives the same code, so agents get identical results.
+
## MCP bridge
`photocraft-automation` provides an MCP server built on the official Rust SDK (`rmcp`). It runs in one of two modes:
diff --git a/docs/development.md b/docs/development.md
index 518615ace..daced0c23 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -13,6 +13,7 @@ cargo run --release -p photocraft -- --control 7878 img.jpg # with the JSON cont
cargo test --workspace # everything
cargo xtask ci # fmt + clippy + tests + layers + wasm
cargo xtask stats # tests and lines per crate
+cargo xtask parity # Photoshop menu coverage -> docs/parity.md
```
Image code is slow at `opt-level 0`, so the workspace profile builds dependencies at `opt-level 2`. Use `--release` for anything interactive.
@@ -24,6 +25,7 @@ Image code is slow at `opt-level 0`, so the workspace profile builds dependencie
| `PHOTOCRAFT_CONTROL_PORT` | Same as `--control <port>` |
| `PHOTOCRAFT_CPU_CANVAS=1` | Force the CPU canvas path instead of the wgpu shader canvas |
| `PHOTOCRAFT_GPU_TILE=2048` | Force GPU canvas tiling (tests tile seams) |
+| `PHOTOCRAFT_FX_NOCACHE=1` | Bypass the layer-effect map cache (`compose::effect_maps`) |
| `PHOTOCRAFT_THEME_FILE=tokens.json` | **Debug builds only:** live design-token overrides, re-read on change |
### Live design tokens
@@ -113,6 +115,13 @@ cargo build --release -p photocraft-cli
claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp
```
+`doc_inspect` (and the engine command `document.inspect`) reports the layer tree with kinds,
+bounds, masks, selection, effects (`effects.items[].kind`), smart filters (`smartFilters[]`), type
+text, adjustment settings, channels and history, so agents can verify what they did without a
+screenshot. `crates/automation/tests/agent_tasks.rs` is the reference: ten realistic edit tasks
+(title card, colour grade, undo/redo, editable smart blur, masks, saved selections, align, layer
+export, resize/crop, CMYK + native save) driven purely over MCP.
+
A typical agent loop:
1. `doc_open {path}`
@@ -121,6 +130,25 @@ A typical agent loop:
4. `doc_render_preview` to check the result
5. `doc_save {path:"out.pcraft"}`
+## Colour management
+
+`crates/cms` is our own pure-Rust ICC engine (v2/v4 parsing, matrix/TRC and LUT profiles, all four
+intents, black point compensation). It ships CC0 built-in profiles, including a synthetic
+"Photocraft Coated CMYK", because Adobe's CMYK profiles are proprietary (see `crates/cms/README.md`).
+
+- Documents carry an optional embedded ICC profile (`Document::icc_profile`); `edit.assignProfile`
+ and `edit.convertToProfile` change it. Mode changes (`image.mode.*`) convert through cms.
+- **Proof Colors** (⌘Y), **Proof Setup** and **Gamut Warning** (⇧⌘Y) bake a 3D LUT
+ (`cms::Lut3d`) that the canvas shader applies; the document pixels never change.
+- Convert colours with `photocraft_cms::transform::cached(src, dst, opts)`: transforms are cached
+ process-wide and integer buffers use precomputed tables or a device link.
+
+## Menu parity
+
+`cargo xtask parity` compares Photoshop's menu tree (`crates/ui-egui/src/menu_catalog.rs`) with
+the live command registry (`menus::is_live`) and rewrites [`docs/parity.md`](parity.md). The test
+`parity::tests::parity_does_not_regress` fails if the live count drops below `parity::FLOOR`.
+
## Testing strategy
- **Unit and property tests** in every crate. proptest is used for tile COW, regions and codecs.
@@ -136,7 +164,9 @@ A typical agent loop:
## Performance notes
- The canvas is presented by a custom WGSL shader (`ui-egui/src/gpu_canvas.rs`): mip-mapped/nearest sampling, procedural checkerboard, pixel grid, tiling. Brush strokes upload only their damage rect.
-- **Compositing is still CPU** (`photocraft-compose`). Live adjustment previews on large documents use a downsampled proxy (`ui-egui/src/proxy.rs`). The GPU compositor is milestone M5.
+- **The canvas composites on the GPU** (`photocraft-gpu`, driven from `gpu_canvas.rs`). Anything the GPU planner can't express (layer effects, layers clipped to pass-through groups, documents over the texture limit) returns `Unsupported` and falls back to the CPU compositor (`photocraft-compose`), which is also the reference for export and tests.
+- **Layer effects** are expensive. `compose::effect_maps` caches shadow, glow, bevel and satin maps per layer state (LRU, 768 MB budget).
+- Live adjustment previews on large documents use a downsampled proxy (`ui-egui/src/proxy.rs`).
- `ui.inspect` returns `perf` timings (UI ms per frame, composite ms, upload ms).
- Never scan full surfaces per frame. Cache per document revision (`PhotocraftApp::cached_bounds`). An uncached `content_bounds()` on a 36 MP layer once cost 77 ms per frame.
diff --git a/docs/images/SOURCES.md b/docs/images/SOURCES.md
index 6505d0473..75d17a556 100644
--- a/docs/images/SOURCES.md
+++ b/docs/images/SOURCES.md
@@ -3,5 +3,13 @@
| File | Content | Source / licence |
|---|---|---|
| `photocraft-demo.jpg` | Photocraft UI screenshot (rendered offscreen with `cargo run -p photocraft-ui-egui --example snapshot`) editing *The Great Wave off Kanagawa*, Katsushika Hokusai, c. 1831 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Tsunami_by_hokusai_19th_century.jpg). UI: this project. |
+| `photocraft-layer-styles.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Earthrise*, William Anders, Apollo 8, 24 December 1968 (NASA photograph) | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:NASA-Apollo8-Dec24-Earthrise.jpg). UI: this project. |
+| `photocraft-masks.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Girl with a Pearl Earring*, Johannes Vermeer, c. 1665 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:1665_Girl_with_a_Pearl_Earring.jpg). UI: this project. |
+| `photocraft-vector.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Water Lilies*, Claude Monet, 1906 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Claude_Monet_-_Water_Lilies_-_1906,_Ryerson.jpg). UI: this project. |
+| `photocraft-filters.jpg` | Photocraft UI screenshot (offscreen snapshot) with *The Starry Night*, Vincent van Gogh, 1889 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg). UI: this project. |
+| `photocraft-adjustments.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Impression, Sunrise*, Claude Monet, 1872 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Monet_-_Impression,_Sunrise.jpg). UI: this project. |
+| `photocraft-transform.jpg` | Photocraft UI screenshot (offscreen snapshot) with *The Tetons and the Snake River*, Ansel Adams, 1942 (U.S. National Archives) | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Adams_The_Tetons_and_the_Snake_River.jpg). UI: this project. |
+| `photocraft-type.jpg` | Photocraft UI screenshot (offscreen snapshot) with *Among the Sierra Nevada, California*, Albert Bierstadt, 1868 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Albert_Bierstadt_-_Among_the_Sierra_Nevada,_California_-_Google_Art_Project.jpg). UI: this project. |
+| `photocraft-export-light.jpg` | Photocraft UI screenshot (offscreen snapshot) with *The Kiss*, Gustav Klimt, 1907–1908 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Gustav_Klimt_016.jpg). UI: this project. |
Screenshots must use famous public-domain artwork (or content made in the app), never personal photos.
diff --git a/docs/images/photocraft-adjustments.jpg b/docs/images/photocraft-adjustments.jpg
new file mode 100644
index 000000000..cb72a6ddf
Binary files /dev/null and b/docs/images/photocraft-adjustments.jpg differ
diff --git a/docs/images/photocraft-export-light.jpg b/docs/images/photocraft-export-light.jpg
new file mode 100644
index 000000000..96679ff27
Binary files /dev/null and b/docs/images/photocraft-export-light.jpg differ
diff --git a/docs/images/photocraft-filters.jpg b/docs/images/photocraft-filters.jpg
new file mode 100644
index 000000000..146dda9e1
Binary files /dev/null and b/docs/images/photocraft-filters.jpg differ
diff --git a/docs/images/photocraft-layer-styles.jpg b/docs/images/photocraft-layer-styles.jpg
new file mode 100644
index 000000000..05b6c0a57
Binary files /dev/null and b/docs/images/photocraft-layer-styles.jpg differ
diff --git a/docs/images/photocraft-masks.jpg b/docs/images/photocraft-masks.jpg
new file mode 100644
index 000000000..b02f4b082
Binary files /dev/null and b/docs/images/photocraft-masks.jpg differ
diff --git a/docs/images/photocraft-transform.jpg b/docs/images/photocraft-transform.jpg
new file mode 100644
index 000000000..d6f6de54e
Binary files /dev/null and b/docs/images/photocraft-transform.jpg differ
diff --git a/docs/images/photocraft-type.jpg b/docs/images/photocraft-type.jpg
new file mode 100644
index 000000000..12de24212
Binary files /dev/null and b/docs/images/photocraft-type.jpg differ
diff --git a/docs/images/photocraft-vector.jpg b/docs/images/photocraft-vector.jpg
new file mode 100644
index 000000000..578dc6244
Binary files /dev/null and b/docs/images/photocraft-vector.jpg differ
diff --git a/docs/parity.md b/docs/parity.md
new file mode 100644
index 000000000..84e3b51ce
--- /dev/null
+++ b/docs/parity.md
@@ -0,0 +1,153 @@
+# Photoshop menu parity
+
+Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Photoshop's menu tree) and the live command registry. Do not edit by hand.
+
+**518 of 625 menu items live (82.9%).**
+
+| Menu | Live | Total | % |
+|---|---:|---:|---:|
+| File | 25 | 50 | 50% |
+| Edit | 71 | 75 | 95% |
+| Image | 50 | 61 | 82% |
+| Layer | 140 | 160 | 88% |
+| Type | 41 | 44 | 93% |
+| Select | 22 | 25 | 88% |
+| Filter | 66 | 75 | 88% |
+| View | 59 | 74 | 80% |
+| Window | 44 | 61 | 72% |
+
+## Not yet implemented
+
+### File (25)
+
+- Export › Export Preferences… (`file.export.exportPreferences`)
+- Export › Save for Web (Legacy)… (`file.export.saveForWebLegacy`)
+- Export › Artboards to Files… (`file.export.artboardsToFiles`)
+- Export › Artboards to PDF… (`file.export.artboardsToPdf`)
+- Export › Layer Comps to Files… (`file.export.layerCompsToFiles`)
+- Export › Data Sets as Files… (`file.export.dataSetsAsFiles`)
+- Export › Paths to Illustrator… (`file.export.pathsToIllustrator`)
+- Export › Render Video… (`file.export.renderVideo`)
+- Generate › Image Assets (`file.generate.imageAssets`)
+- Package… (`file.package`)
+- Automate › Create Droplet… (`file.automate.createDroplet`)
+- Automate › Crop and Straighten Photos (`file.automate.cropAndStraightenPhotos`)
+- Automate › Contact Sheet II… (`file.automate.contactSheetII`)
+- Automate › Lens Correction… (`file.automate.lensCorrection`)
+- Automate › Merge to HDR Pro… (`file.automate.mergeToHdrPro`)
+- Automate › Photomerge… (`file.automate.photomerge`)
+- Scripts › Script Events Manager… (`file.scripts.scriptEventsManager`)
+- Scripts › Statistics… (`file.scripts.statistics`)
+- Scripts › Browse… (`file.scripts.browse`)
+- Import › Variable Data Sets… (`file.import.variableDataSets`)
+- Import › Video Frames to Layers… (`file.import.videoFramesToLayers`)
+- Import › Notes… (`file.import.notes`)
+- Import › WIA Support… (`file.import.wiaSupport`)
+- Print… (`file.print`)
+- Print One Copy (`file.printOneCopy`)
+
+### Edit (4)
+
+- Check Spelling… (`edit.checkSpelling`)
+- Puppet Warp (`edit.puppetWarp`)
+- Perspective Warp (`edit.perspectiveWarp`)
+- Presets › Migrate Presets (`edit.presets.migratePresets`)
+
+### Image (11)
+
+- Mode › Multichannel (`image.mode.multichannel`)
+- Variables › Define… (`image.variables.define`)
+- Variables › Data Sets… (`image.variables.dataSets`)
+- Apply Data Set… (`image.applyDataSet`)
+- Trap… (`image.trap`)
+- Analysis › Set Measurement Scale… (`image.analysis.setMeasurementScale`)
+- Analysis › Select Data Points… (`image.analysis.selectDataPoints`)
+- Analysis › Record Measurements (`image.analysis.recordMeasurements`)
+- Analysis › Ruler Tool (`image.analysis.rulerTool`)
+- Analysis › Count Tool (`image.analysis.countTool`)
+- Analysis › Place Scale Marker… (`image.analysis.placeScaleMarker`)
+
+### Layer (20)
+
+- New › Artboard… (`layer.new.artboard`)
+- New › Artboard from Group… (`layer.new.artboardFromGroup`)
+- New › Artboard from Layers… (`layer.new.artboardFromLayers`)
+- New › Frame from Layers (`layer.new.frameFromLayers`)
+- Smart Objects › Perspective Warp (`layer.smartObjects.perspectiveWarp`)
+- Smart Objects › Puppet Warp (`layer.smartObjects.puppetWarp`)
+- Video Layers › New Blank Video Layer (`layer.videoLayers.newBlankVideoLayer`)
+- Video Layers › New Video Layer from File… (`layer.videoLayers.newVideoLayerFromFile`)
+- Video Layers › Insert Blank Frame (`layer.videoLayers.insertBlankFrame`)
+- Video Layers › Duplicate Frame (`layer.videoLayers.duplicateFrame`)
+- Video Layers › Delete Frame (`layer.videoLayers.deleteFrame`)
+- Video Layers › Replace Footage… (`layer.videoLayers.replaceFootage`)
+- Video Layers › Interpret Footage… (`layer.videoLayers.interpretFootage`)
+- Video Layers › Show Altered Video (`layer.videoLayers.showAlteredVideo`)
+- Video Layers › Restore Frame (`layer.videoLayers.restoreFrame`)
+- Video Layers › Restore All Frames (`layer.videoLayers.restoreAllFrames`)
+- Video Layers › Reload Frame (`layer.videoLayers.reloadFrame`)
+- Video Layers › Rasterize (`layer.videoLayers.rasterize`)
+- Rasterize › Video (`layer.rasterize.video`)
+- New Layer Based Slice (`layer.newLayerBasedSlice`)
+
+### Type (3)
+
+- Panels › Glyphs Panel (`type.panels.glyphs`)
+- Panels › Character Styles Panel (`type.panels.characterStyles`)
+- Panels › Paragraph Styles Panel (`type.panels.paragraphStyles`)
+
+### Select (3)
+
+- Isolate Layers (`select.isolateLayers`)
+- Sky (`select.sky`)
+- Transform Selection (`select.transformSelection`)
+
+### Filter (9)
+
+- Filter Gallery… (`filter.filterGallery`)
+- Camera Raw Filter… (`filter.cameraRaw`)
+- Adaptive Wide Angle… (`filter.adaptiveWideAngle`)
+- Lens Correction… (`filter.lensCorrection`)
+- Liquify… (`filter.liquify`)
+- Vanishing Point… (`filter.vanishingPoint`)
+- Render › Flame… (`filter.render.flame`)
+- Render › Picture Frame… (`filter.render.pictureFrame`)
+- Render › Tree… (`filter.render.tree`)
+
+### View (15)
+
+- Proof Setup › Working Cyan Plate (`view.proofSetup.workingCyanPlate`)
+- Proof Setup › Working Magenta Plate (`view.proofSetup.workingMagentaPlate`)
+- Proof Setup › Working Yellow Plate (`view.proofSetup.workingYellowPlate`)
+- Proof Setup › Working Black Plate (`view.proofSetup.workingBlackPlate`)
+- Proof Setup › Working CMY Plate (`view.proofSetup.workingCmyPlate`)
+- Proof Setup › Legacy Macintosh RGB (`view.proofSetup.legacyMacintoshRgb`)
+- Proof Setup › Color Blindness — Protanopia-type (`view.proofSetup.colorBlindnessProtanopia`)
+- Proof Setup › Color Blindness — Deuteranopia-type (`view.proofSetup.colorBlindnessDeuteranopia`)
+- Pixel Aspect Ratio › Custom Pixel Aspect Ratio… (`view.pixelAspectRatio.custom`)
+- 32-bit Preview Options… (`view.thirtyTwoBitPreviewOptions`)
+- Fit Artboard on Screen (`view.fitArtboardOnScreen`)
+- Show › Show Extras Options… (`view.show.showExtrasOptions`)
+- Clear Selected Artboard Guides (`view.clearSelectedArtboardGuides`)
+- Lock Slices (`view.lockSlices`)
+- Clear Slices (`view.clearSlices`)
+
+### Window (17)
+
+- Workspace › New Workspace… (`window.workspace.newWorkspace`)
+- Workspace › Delete Workspace… (`window.workspace.deleteWorkspace`)
+- Workspace › Lock Workspace (`window.workspace.lockWorkspace`)
+- Character Styles (`window.panel.characterStyles`)
+- Clone Source (`window.panel.cloneSource`)
+- Glyphs (`window.panel.glyphs`)
+- Gradients (`window.panel.gradients`)
+- Layer Comps (`window.panel.layerComps`)
+- Measurement Log (`window.panel.measurementLog`)
+- Modifier Keys (`window.panel.modifierKeys`)
+- Notes (`window.panel.notes`)
+- Paragraph Styles (`window.panel.paragraphStyles`)
+- Patterns (`window.panel.patterns`)
+- Shapes (`window.panel.shapes`)
+- Styles (`window.panel.styles`)
+- Timeline (`window.panel.timeline`)
+- Tool Presets (`window.panel.toolPresets`)
diff --git a/docs/roadmap.md b/docs/roadmap.md
index c0ff96286..c701aa723 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -2,19 +2,41 @@
Status legend: ✅ done · 🟡 in progress · ⬜ not started. Updated 2026-09-30.
-| M | Status | Notes |
+**Parity metric:** `cargo xtask parity` measures how much of Photoshop's menu tree is live and
+writes [`parity.md`](parity.md). It is the headline number for "how close are we", next to the PSD
+composite oracle and the test count.
+
+| M | Status | Where we are |
|---|---|---|
-| M0 Skeleton | ✅ | workspace, xtask (layers/wasm/ci/stats/corpus), CI workflow |
-| M1 Foundation | ✅ | geom, color (27 blend modes), raster (COW tiles, any depth), doc, ops |
+| M0 Skeleton | ✅ | workspace, xtask (layers / wasm / ci / stats / corpus / parity), CI workflow |
+| M1 Foundation | ✅ | geom, color (27 blend modes), raster (COW tiles, any depth), doc, ops, cms (ICC) |
| M2 PSD v1 | ✅ | photocraft-psd: 134/135 real files byte-exact round trip |
-| M3 Viewer app | 🟡 | egui shell with Pro/Studio/Classic themes, codecs (13 formats), io, native app; web build pending |
-| M4 Native format + engine | 🟡 | engine + command registry done; `.pcraft` bundle and CLI pending |
-| M5 GPU compositor | 🟡 | GPU canvas presentation (WGSL) done; GPU compositing pending |
-| M6 Paint + select | 🟡 | brush v1, eraser, marquee, move done; tablet input, lasso/wand, transform pending |
-| M7 Adjust + filters | 🟡 | 14 adjustment layers; filters pending |
-| M8 PSD v2 | 🟡 | adjustments, fills, raw-preserved text/smart/shape; composite oracle 82/135 |
-| M9 Text, vector, styles | 🟡 | layer effects in progress |
-| M10–M12 | ⬜ | smart features, automation/MCP, pro parity |
+| M3 Viewer app | ✅ | egui shell (Pro / Studio / Classic themes), 13+ codecs, native and web (trunk) builds |
+| M4 Native format + engine | ✅ | 500+ commands, `.pcraft` (incremental, autosave, crash recovery), CLI, persistent preferences |
+| M5 GPU compositor | 🟡 | wgpu compositor drives the canvas; layer effects, pattern fills and a few clip cases fall back to the CPU |
+| M6 Paint + select | 🟡 | brush engine, all selection tools, multi-layer selection, snapping + smart guides, free transform + warp; native tablet backends pending |
+| M7 Adjust + filters | 🟡 | 16 adjustment layers + destructive-only adjustments, 70+ filters incl. Blur Gallery, Actions record/replay, Fade |
+| M8 PSD v2 | 🟡 | adjustments (incl. Selective Color, Color Lookup), fills, effects, patterns, text, shapes, smart objects, alpha channels; oracle 102/170 |
+| M9 Text, vector, styles | 🟡 | type engine + Warp Text, shapes / pen / paths, all 10 effects on CPU; GPU effects pending |
+| M10 Smart features | 🟡 | classical Select Subject / Object, content-aware fill and scale, healing, auto-align / auto-blend; ML backend not started |
+| M11 Automation + formats | 🟡 | MCP (headless + live bridge), batch, Image Processor, prefs over MCP; DoD test passes (10 agent tasks over MCP, `automation/tests/agent_tasks.rs`); JP2 / DICOM / DPX / C2PA pending |
+| M12 Pro parity | 🟡 | CMYK / Lab / Indexed / Bitmap / Duotone, ICC + soft proofing, channels + Quick Mask, smart-object stack modes; print, HDR, photomerge, timeline, artboards, layer comps pending |
+
+**Menu parity: 518 / 625 (82.9%)** on 2026-10-01, up from 224 (35.8%) the day before. See [`parity.md`](parity.md).
+
+## Current focus (infrastructure before the long tail)
+
+Landed on 2026-10-01: multi-layer selection, live smart objects + smart filters, alpha channels +
+Quick Mask, patterns, Warp, preferences, snapping, ~33 filters, the remaining core adjustments.
+
+Next:
+1. **Fidelity**: the PSD oracle (102/170). Linked-pattern phase origin, layer effects (bevel,
+ satin, multi-stroke), grayscale adjustments; PSD link groups; Photoshop smart filters in `SoLd`.
+2. **Layer Comps and Artboards** (File/Layer/View items and export depend on them).
+3. **GPU layer effects** (the last big CPU fallback on the canvas).
+4. **Puppet Warp, Perspective Warp, Liquify, Vanishing Point, Camera Raw / Lens Correction**.
+5. **Panels**: Patterns, Styles, Glyphs, Character/Paragraph Styles, Timeline; Custom Shape tool.
+6. Print, Photomerge, Merge to HDR, video layers.
## Milestone definitions
@@ -36,4 +58,3 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on
| **M11** | Automation + formats | MCP server, batch, scripting, remaining formats (JP2, DICOM, DPX…), C2PA | An agent completes 10 scripted edit tasks via MCP |
| **M12** | Pro parity | CMYK/Lab UI, print, HDR display, photomerge/HDR merge, timeline, layer comps, artboards, symmetry, neural filters | `xtask parity` ≥ 90% of Photoshop menu checklist |
-**Today's target: M0 + M1 + M2 + an M3 vertical slice.**
diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs
index 753707507..af9533072 100644
--- a/xtask/src/layers.rs
+++ b/xtask/src/layers.rs
@@ -34,6 +34,7 @@ impl Class {
/// prefix.
pub const TABLE: &[(&str, Class)] = &[
("geom", Class::Layer(0)),
+ ("cms", Class::Layer(0)),
("color", Class::Layer(0)),
("raster", Class::Layer(0)),
("psd", Class::Standalone),
@@ -69,7 +70,7 @@ pub const TABLE: &[(&str, Class)] = &[
/// The L0 foundation is a small chain: `raster` builds on `color` and
/// `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"]];
+pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["geom", "cms", "color", "raster"], &["compose", "gpu"]];
fn intra_layer_allowed(from: &str, to: &str) -> bool {
let (from, to) = (short_name(from), short_name(to));
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index 4d841fc29..c1c2a700e 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -19,6 +19,7 @@ commands:
corpus [--download]
show where test corpora live; --download fetches PngSuite into corpus/pngsuite
stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`)
+ parity Photoshop menu parity; rewrites docs/parity.md
";
fn main() -> ExitCode {
@@ -30,6 +31,7 @@ fn main() -> ExitCode {
Some("ci") => cmd_ci(),
Some("corpus") => cmd_corpus(rest.contains(&"--download")),
Some("stats") => stats::run(&root(), rest.contains(&"--exact")),
+ Some("parity") => cmd_parity(),
Some("-h" | "--help" | "help") | None => {
print!("{USAGE}");
Ok(())
@@ -164,6 +166,12 @@ fn cmd_wasm() -> Result<(), String> {
}
}
+fn cmd_parity() -> Result<(), String> {
+ let mut c = cargo();
+ c.args(["run", "-q", "-p", "photocraft-ui-egui", "--example", "parity", "--", "--write", "docs/parity.md"]);
+ run(c, "cargo run -p photocraft-ui-egui --example parity")
+}
+
fn cmd_ci() -> Result<(), String> {
type Step = (&'static str, Box<dyn Fn() -> Result<(), String>>);
let steps: Vec<Step> = vec![