Merge remote-tracking branch 'upstream/main' into feat/arrange-drag-borders

This commit is contained in:
Claude committed 2026-11-02 19:39:34 +00:00
commit df1aaaac4c
201 files changed
+7583 -729

No files matched your search

+8 -1
View File
@@ -120,7 +120,8 @@ Artwork shown in the screenshots (all public domain, via Wikimedia Commons; deta
## Test data (not committed, not shipped)
`corpus/` is gitignored and no test fixtures are committed to the repository.
`corpus/` is gitignored and no test fixtures are committed to the repository, except the small
synthetic parser fixtures listed under *Synthetic parser test fixtures* below.
`cargo xtask corpus --all` fetches every corpus at the pinned commits in `xtask/src/corpus_pins.rs`
and verifies each file against the sha256 lists in `xtask/*.sha256`, with the upstream licence
next to the files:
@@ -140,6 +141,12 @@ next to the files:
Files copied into `corpus/` by hand (tiff, exr, raw) must be MIT, BSD or CC0.
## Synthetic parser test fixtures
| Path | Title | Author | Source | License |
|---|---|---|---|---|
| `crates/psd/tests/fixtures/atn/*.atn` | Independently encoded ATN version-16 parser fixtures | PhotoCraft contributors | Original synthetic test data; wire layout documented in `crates/psd/src/atn.rs`; provenance in the adjacent README | MIT OR Apache-2.0 |
## Embedded-vector editor source
The external SVG watcher, engine/UI handoff and bounded SVG rendering in this change
Generated
+55 -31
View File
@@ -1388,6 +1388,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-pcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b8f7d93b00dfb8f172938f3d2d796ae62dcfe123#b8f7d93b00dfb8f172938f3d2d796ae62dcfe123"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-print"
version = "0.1.0"
@@ -4963,7 +4973,7 @@ dependencies = [
[[package]]
name = "photocraft"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"arboard",
"async-io",
@@ -5018,7 +5028,7 @@ dependencies = [
[[package]]
name = "photocraft-affinity"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"crc32fast",
"flate2",
@@ -5028,7 +5038,7 @@ dependencies = [
[[package]]
name = "photocraft-algo"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"criterion",
"photocraft-color",
@@ -5043,7 +5053,7 @@ dependencies = [
[[package]]
name = "photocraft-automation"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"base64 0.23.1",
"cap-std",
@@ -5068,7 +5078,7 @@ dependencies = [
[[package]]
name = "photocraft-cli"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"clap",
"clap_complete",
@@ -5087,7 +5097,7 @@ dependencies = [
[[package]]
name = "photocraft-cms"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"moxcms",
"rayon",
@@ -5095,7 +5105,7 @@ dependencies = [
[[package]]
name = "photocraft-codecs"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"craft-jpeg",
"exr",
@@ -5119,7 +5129,7 @@ dependencies = [
[[package]]
name = "photocraft-color"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"photocraft-cms",
"serde",
@@ -5127,7 +5137,7 @@ dependencies = [
[[package]]
name = "photocraft-compose"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"criterion",
"photocraft-cms",
@@ -5143,7 +5153,7 @@ dependencies = [
[[package]]
name = "photocraft-doc"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -5154,7 +5164,7 @@ dependencies = [
[[package]]
name = "photocraft-engine"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -5196,9 +5206,10 @@ dependencies = [
[[package]]
name = "photocraft-format"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"blake3",
"craft-pcraft-format",
"crc32fast",
"exacl",
"flate2",
@@ -5219,14 +5230,14 @@ dependencies = [
[[package]]
name = "photocraft-geom"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"serde",
]
[[package]]
name = "photocraft-gpu"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"bytemuck",
"half",
@@ -5246,14 +5257,14 @@ dependencies = [
[[package]]
name = "photocraft-heif"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"heic-rs",
]
[[package]]
name = "photocraft-io"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"blake3",
"craft-docpath",
@@ -5289,18 +5300,18 @@ dependencies = [
[[package]]
name = "photocraft-ipp"
version = "0.18.0"
version = "0.19.0"
[[package]]
name = "photocraft-ops"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"photocraft-doc",
]
[[package]]
name = "photocraft-paint"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"photocraft-cms",
"photocraft-color",
@@ -5314,7 +5325,7 @@ dependencies = [
[[package]]
name = "photocraft-plugins"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -5330,8 +5341,9 @@ dependencies = [
[[package]]
name = "photocraft-psd"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"encoding_rs",
"flate2",
"photocraft-psd",
"proptest",
@@ -5341,7 +5353,7 @@ dependencies = [
[[package]]
name = "photocraft-raster"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -5352,7 +5364,7 @@ dependencies = [
[[package]]
name = "photocraft-raw"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"flate2",
"image",
@@ -5367,7 +5379,7 @@ dependencies = [
[[package]]
name = "photocraft-tablet"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"block2 0.6.2",
"objc2 0.6.5",
@@ -5379,7 +5391,7 @@ dependencies = [
[[package]]
name = "photocraft-testkit"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"memory-stats",
"serde_json",
@@ -5387,7 +5399,7 @@ dependencies = [
[[package]]
name = "photocraft-text"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"flate2",
"parley",
@@ -5402,7 +5414,7 @@ dependencies = [
[[package]]
name = "photocraft-ui-egui"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"base64 0.23.1",
"craft-print",
@@ -5447,7 +5459,7 @@ dependencies = [
[[package]]
name = "photocraft-vector"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"photocraft-color",
"photocraft-doc",
@@ -5458,7 +5470,7 @@ dependencies = [
[[package]]
name = "photocraft-web"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"eframe",
"egui",
@@ -5480,7 +5492,7 @@ dependencies = [
[[package]]
name = "photocraft-web-boot"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"flate2",
"js-sys",
@@ -6650,6 +6662,17 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "sctk-adwaita"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
dependencies = [
"log",
"smithay-client-toolkit 0.19.2",
"tiny-skia",
]
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -8919,6 +8942,7 @@ dependencies = [
"raw-window-handle",
"redox_syscall 0.4.1",
"rustix 0.38.44",
"sctk-adwaita",
"smithay-client-toolkit 0.19.2",
"smol_str",
"tracing",
@@ -9196,7 +9220,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xtask"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"chrono",
"serde",
+3 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"]
[workspace.package]
version = "0.18.0"
version = "0.19.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -42,6 +42,7 @@ photocraft-ipp = { path = "crates/ipp" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
thiserror = "2"
@@ -53,6 +54,7 @@ clap_mangen = { version = "0.3.3", features = ["env"] }
arc-swap = "1"
bytemuck = { version = "1", features = ["derive"] }
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] }
encoding_rs = { version = "0.8", default-features = false, features = ["alloc"] }
image = { version = "0.25", default-features = false }
# Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg.
zune-core = "0.5"
+31
View File
@@ -23,6 +23,37 @@ https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (today BIZ UDP
BIZ UDMincho; not the web build), under the SIL Open Font License 1.1. Their licence texts
ship with the package as OFL-<family>.txt.
Linux Wayland window decorations
-------------------------------
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
for vector window controls. Its title-font features are disabled: no Cantarell
font is embedded by this dependency and no font file is added to this repo.
sctk-adwaita's MIT licence:
MIT License
Copyright (c) 2022 Bartłomiej Maryńczak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The egui-icons font subset is embedded from epaint_default_fonts by crates/ui-egui/build.rs
and registered in the native and web fallback stacks by crates/ui-egui/src/egui_fonts.rs.
It is a subset of emoji-icon-font by John Slegers; the same upstream MIT license applies.
+10 -1
View File
@@ -396,13 +396,22 @@ stand on its own.
| | App | What it's for | Code | Learn more |
|:-:|---|---|---|---|
| <img src="https://raw.githubusercontent.com/storytold/photocraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png" alt="" width="32" height="32"> | **PhotoCraft** | **Image editing: layers, masks, type and real PSD files · you are here** | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) |
| <img src="https://raw.githubusercontent.com/storytold/photocraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png" alt="" width="32" height="32"> | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) |
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
| <img src="https://raw.githubusercontent.com/storytold/filmcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.filmcraft.png" alt="" width="32" height="32"> | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
+1
View File
@@ -122,6 +122,7 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md).
| Date | Entry |
|---|---|
| 2026-10-21 | Linux can use font-free Adwaita controls when System Title Bar is selected, while the integrated CSD title bar remains the default (as in #4439). Saved preferences are respected; startup and preference-dialog regressions cover both choices (#6266). |
| 2026-10-17 | Object Finder classifies background by boundary coverage, retaining large enclosed foregrounds and rejecting surrounding backdrop (#6548); learned segmentation remains open (#2788) |
| 2026-10-10 | Full re-measure against Photoshop 2026 27.11.0 (installed bundle inspected): breadth ~76%, ready ~45%, alpha. Progress docs reorganized (`parity.md` → `parity-checklist.md`, `parity-estimate.md` merged into `target-app-parity.md`). 0.6.0 released. |
| 2026-10-09 | Remove tool, Rotate View, crop rotation; OpenRaster and Paint.NET; 39 Affinity documents in the corpus |
+2
View File
@@ -1,6 +1,8 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
fn main() {
// May re-execute this process with glibc tuned to return freed document memory (#8743).
photocraft_engine::malloc_tuning::apply();
// `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must reach clap,
// not panic before anything is printed (issue #1108).
let code = photocraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr());
+2
View File
@@ -1,6 +1,8 @@
//! The crate's integration tests, linked into one test binary.
mod cli;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod malloc_tuning;
mod man_and_completions;
mod orientation;
@@ -0,0 +1,41 @@
//! The binary re-executes itself with glibc's trim threshold set (#8743), keeping its arguments
//! and a value the user set.
use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
use photocraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR};
/// The environment of a running `serve` once it answered a request, as `NAME=value` entries.
fn serve_environ(set: Option<&str>) -> Vec<String> {
let mut cmd = Command::new(crate::binary());
for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] {
cmd.env_remove(var);
}
if let Some(v) = set {
cmd.env(TRIM_THRESHOLD_VAR, v);
}
let mut child = cmd.arg("serve").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
let mut stdin = child.stdin.take().unwrap();
writeln!(stdin, r#"{{"id":1,"method":"session.list"}}"#).unwrap();
let mut reply = String::new();
BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap();
assert!(reply.contains(r#""id":1"#), "serve answered after the re-exec: {reply}");
// The same process: `exec` keeps the PID, so this is the re-executed program's environment.
let environ = std::fs::read(format!("/proc/{}/environ", child.id())).unwrap();
drop(stdin);
child.wait().unwrap();
environ.split(|&b| b == 0).map(|e| String::from_utf8_lossy(e).into_owned()).collect()
}
#[test]
fn sets_the_trim_threshold() {
let env = serve_environ(None);
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}={TRIM_THRESHOLD}")), "{env:?}");
}
#[test]
fn keeps_a_value_the_user_set() {
let env = serve_environ(Some("999999"));
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}=999999")), "{env:?}");
}
+1 -1
View File
@@ -100,7 +100,7 @@ futures-lite = "=2.6.1"
async-io = "=2.6.0"
# Open the window through Xwayland for a pen on Wayland (`tablet.rs`, #639): eframe doesn't
# re-export winit's `EventLoopBuilderExtX11`. Already in Cargo.lock (eframe); pinned exactly.
winit = { version = "=0.30.13", default-features = false, features = ["x11"] }
winit = { version = "=0.30.13", default-features = false, features = ["wayland-csd-adwaita-notitle", "x11"] }
# Safe Win32 wrappers on Windows: the pointer position for file drops (`cursor.rs`,
# GetCursorPos) and the window frame for the custom title bar (`window_frame.rs`, window styles),
+9 -7
View File
@@ -535,18 +535,20 @@ impl Sentinel {
/// file, read before the window opens; `Auto` when the file or value is missing or unknown.
#[cfg(any(target_os = "linux", test))]
pub fn read_display_server(path: Option<&Path>) -> photocraft_engine::prefs::LinuxDisplayServer {
read_performance(path).map(|performance| performance.linux_display_server).unwrap_or_default()
}
/// The preferences file's Performance section, read as the app reads it: a value of the wrong
/// type keeps its default without resetting the others. `None` without a file or section.
fn read_performance(path: Option<&Path>) -> Option<photocraft_engine::prefs::Performance> {
let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
v.get("performance")
.and_then(|p| serde_json::from_value::<photocraft_engine::prefs::Performance>(p.clone()).ok())
.map(|performance| performance.linux_display_server)
.unwrap_or_default()
v.get("performance").cloned().map(photocraft_engine::prefs::read_section)
}
/// Preferences › Performance › Graphics Adapter (`performance.gpuAdapter`), read before the window
/// opens; empty (automatic) when the file or value is missing.
/// opens; empty (automatic) when the file or value is missing or not text.
pub fn read_gpu_adapter(path: Option<&Path>) -> String {
let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
v.get("performance").and_then(|p| p.get("gpuAdapter")).and_then(Value::as_str).unwrap_or("").chars().take(256).collect()
read_performance(path).map(|performance| performance.gpu_adapter.chars().take(256).collect()).unwrap_or_default()
}
/// Preferences › Performance › Low-Latency Drawing (`performance.lowLatencyDrawing`, off unless
+4
View File
@@ -37,6 +37,8 @@ fn display_server_preference_is_read_before_the_window_opens() {
// Unknown values, other types, broken JSON and a missing file all start as Auto.
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"wayland"}}"#), LinuxDisplayServer::Auto);
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":11}}"#), LinuxDisplayServer::Auto);
// A bad value beside it resets only itself, as when the app loads the file (#6611).
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11","cacheLevels":"four"}}"#), LinuxDisplayServer::X11);
assert_eq!(read("{not json"), LinuxDisplayServer::Auto);
assert_eq!(read_display_server(Some(&dir.join("missing.json"))), LinuxDisplayServer::Auto);
assert_eq!(read_display_server(None), LinuxDisplayServer::Auto);
@@ -210,6 +212,8 @@ fn gpu_adapter_is_read_before_the_window_opens() {
};
assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia"}}"#), "nvidia");
assert_eq!(read(r#"{"performance":{"gpuAdapter":7}}"#), "");
// A bad value beside it resets only itself, as when the app loads the file (#6611).
assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia","cacheLevels":"four"}}"#), "nvidia");
assert_eq!(read(r#"{"performance":{}}"#), "");
assert_eq!(read("not json"), "");
assert_eq!(read_gpu_adapter(None), "");
+12 -6
View File
@@ -80,9 +80,9 @@ use photocraft_ui_egui::PhotocraftApp;
use photocraft_ui_egui::os_window::APP_ID;
/// Windows and Linux: no OS title bar; the app's top bar is the title bar, with its own caption
/// buttons and edge resizing (`photocraft_ui_egui::titlebar`), as Photoshop does on Windows. macOS
/// keeps its traffic lights over the integrated title strip.
/// Windows and Linux can use the app's title bar, with its own caption buttons and edge resizing
/// (`photocraft_ui_egui::titlebar`); the preference below selects the mode. macOS always keeps its
/// system traffic lights over the integrated title strip.
const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
/// Whether this start draws its own title bar: Windows and Linux do, unless Preferences ›
@@ -340,7 +340,10 @@ fn write_start_marker(sentinel: &gpu_startup::SharedSentinel, plan: &gpu_startup
}
fn main() -> eframe::Result {
// First, so the panic hook and every start-up warning are recorded (`logging`).
// Before anything starts a thread: may re-execute this process with glibc tuned to return
// the memory of closed documents (#8743).
photocraft_engine::malloc_tuning::apply();
// Then, so the panic hook and every start-up warning are recorded (`logging`).
let logger = logging::install();
crash_guard::install_hook();
#[cfg(not(target_arch = "wasm32"))]
@@ -943,9 +946,12 @@ mod tests {
let dir = std::env::temp_dir().join(format!("pc-titlebar-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("prefs.json");
assert_eq!(super::custom_titlebar(None), super::CUSTOM_TITLEBAR, "no preferences file: the default");
let default_custom = super::CUSTOM_TITLEBAR;
assert_eq!(super::custom_titlebar(None), default_custom, "no preferences file: the platform default");
std::fs::write(&file, "not json").unwrap();
assert_eq!(super::custom_titlebar(Some(&file)), super::CUSTOM_TITLEBAR, "an unreadable file: the default");
assert_eq!(super::custom_titlebar(Some(&file)), default_custom, "an unreadable file: the platform default");
std::fs::write(&file, r#"{"interface":{}}"#).unwrap();
assert_eq!(super::custom_titlebar(Some(&file)), default_custom, "an older preference file: the platform default");
std::fs::write(&file, r#"{"interface":{"systemTitleBar":true}}"#).unwrap();
assert!(!super::custom_titlebar(Some(&file)));
assert_eq!(super::native_options(false).viewport.decorations, Some(true));
+11
View File
@@ -291,6 +291,17 @@ sync_github_name = true
[people.dylanmtaylor]
sync_github_name = true
[people.Yuki-init]
display_name = "[email protected]"
sync_github_name = false
[people.sn-o-w]
real_name = "Cristian Silaghi"
sync_github_name = false
[people.regexer]
sync_github_name = true
[people.SimoneRecchia]
real_name = "Simone Recchia"
display_name = "Simone Recchia"
+32 -15
View File
@@ -1,7 +1,7 @@
//! Blurs: Gaussian, box, motion, radial, surface.
use photocraft_geom::Rect;
use photocraft_raster::Interrupt;
use photocraft_raster::{Interrupt, scratch};
use crate::image::{Edge, Image, premultiply, unpremultiply};
use crate::photo_util::{par_map, par_rows};
@@ -78,7 +78,7 @@ pub(crate) fn conv_sep(src: &Image, out: Rect, kx: &[f32], ky: &[f32], alpha: bo
// Premultiplied copy of the needed source window.
let win = Rect::new(out.x0 - rx, out.y0 - ry, out.x1 + rx, out.y1 + ry);
let ww = win.width() as usize;
let mut p = vec![0.0f32; ww * win.height() as usize * n];
let mut p = scratch::Buf::new(ww * win.height() as usize * n, 0.0f32);
for y in win.y0..win.y1 {
for x in win.x0..win.x1 {
let o = ((y - win.y0) as usize * ww + (x - win.x0) as usize) * n;
@@ -89,7 +89,7 @@ pub(crate) fn conv_sep(src: &Image, out: Rect, kx: &[f32], ky: &[f32], alpha: bo
}
premultiply(&mut p, n, alpha);
// Horizontal pass: (ow × th).
let mut tmp = vec![0.0f32; ow * th * n];
let mut tmp = scratch::Buf::new(ow * th * n, 0.0f32);
for ty in 0..th {
let row = &p[ty * ww * n..(ty + 1) * ww * n];
let dst = &mut tmp[ty * ow * n..(ty + 1) * ow * n];
@@ -113,7 +113,7 @@ pub(crate) fn conv_sep(src: &Image, out: Rect, kx: &[f32], ky: &[f32], alpha: bo
}
}
// Vertical pass.
let mut res = vec![0.0f32; ow * oh * n];
let mut res = scratch::take(ow * oh * n, 0.0f32);
for oy in 0..oh {
let d = &mut res[oy * ow * n..(oy + 1) * ow * n];
for (i, kv) in ky.iter().enumerate() {
@@ -182,11 +182,27 @@ pub(crate) fn box_widths(params: &FilterParams) -> Option<Vec<usize>> {
}
/// Scratch buffers of one worker for [`box_blur`].
#[derive(Default)]
struct Scratch {
line: Vec<f32>,
next: Vec<f32>,
acc: Vec<f32>,
/// The source row being read (horizontal passes only).
row: Vec<f32>,
}
impl Scratch {
/// Buffers with room for lines of `line` floats (and the shorter ones after the first pass).
fn new(line: usize, row: usize) -> Self {
Scratch { line: scratch::take_cap(line), next: scratch::take_cap(line), acc: Vec::new(), row: scratch::take_cap(row) }
}
}
impl Drop for Scratch {
fn drop(&mut self) {
scratch::give(std::mem::take(&mut self.line));
scratch::give(std::mem::take(&mut self.next));
scratch::give(std::mem::take(&mut self.row));
}
}
/// One running-sum box pass of radius `r` along a line of elements of `w` floats each (a pixel's
@@ -252,7 +268,7 @@ fn box_pass_px<const N: usize>(src: &[f32], dst: &mut [f32], r: usize) {
/// `dst` unfinished) when `ctl` is cancelled before a pass: a column strip's passes take tens of
/// milliseconds on a tall image, too long to finish once cancelled (#6205).
fn line_passes(dst: &mut [f32], w: usize, radii: &[usize], s: &mut Scratch, ctl: &Interrupt) {
let Scratch { line, next, acc } = s;
let Scratch { line, next, acc, .. } = s;
let Some(len) = dst.len().checked_div(w) else { return };
let mut tail: usize = radii.iter().sum();
for (k, &r) in radii.iter().enumerate() {
@@ -306,21 +322,21 @@ pub(crate) fn box_blur(
// Horizontal passes over `used`'s rows only (the repeated rows above and below it would just
// repeat their results), for the output columns. Each row is extended to the passes' reach by
// repeating its end pixels.
let mut h = vec![0.0f32; used.height() as usize * ow * n];
let mut h = scratch::Buf::new(used.height() as usize * ow * n, 0.0f32);
let (left, right) = ((used.x0 - out.x0.saturating_sub(reach)) as usize, (out.x1.saturating_add(reach) - used.x1) as usize);
par_rows(&mut h, ow * ROWS_PER_TASK, n, |task, chunk| {
let (mut row, mut s) = (Vec::new(), Scratch::default());
let mut s = Scratch::new((used.width() as usize + left + right) * n, used.width() as usize * n);
for (k, dst) in chunk.chunks_exact_mut(ow * n).enumerate() {
if ctl.cancelled() {
return;
}
let y = used.y0 + (task * ROWS_PER_TASK + k) as i32;
read(Rect::new(used.x0, y, used.x1, y + 1), &mut row);
premultiply(&mut row, n, alpha);
let (Some(first), Some(last)) = (row.get(..n), row.get(row.len().saturating_sub(n)..)) else { return };
read(Rect::new(used.x0, y, used.x1, y + 1), &mut s.row);
premultiply(&mut s.row, n, alpha);
let (Some(first), Some(last)) = (s.row.get(..n), s.row.get(s.row.len().saturating_sub(n)..)) else { return };
s.line.clear();
(0..left).for_each(|_| s.line.extend_from_slice(first));
s.line.extend_from_slice(&row);
s.line.extend_from_slice(&s.row);
(0..right).for_each(|_| s.line.extend_from_slice(last));
line_passes(dst, n, &radii, &mut s, ctl);
}
@@ -336,11 +352,11 @@ pub(crate) fn box_blur(
}
let (sx, w) = ((t.x0 - out.x0) as usize * n, t.width() as usize * n);
let row = |y: usize| &h[y * stride + sx..y * stride + sx + w];
let mut s = Scratch::default();
let mut s = Scratch::new((rows + top + bottom) * w, 0);
(0..top).for_each(|_| s.line.extend_from_slice(row(0)));
(0..rows).for_each(|y| s.line.extend_from_slice(row(y)));
(0..bottom).for_each(|_| s.line.extend_from_slice(row(rows - 1)));
let mut res = vec![0.0f32; oh * w];
let mut res = scratch::take(oh * w, 0.0f32);
line_passes(&mut res, w, &radii, &mut s, ctl);
if ctl.cancelled() {
return (t, Vec::new());
@@ -367,7 +383,7 @@ fn box_passes(src: &Image, out: Rect, alpha: bool, boxes: &[usize]) -> Vec<f32>
buf.extend_from_slice(src.row(r));
};
let ow = out.width() as usize * n;
let mut res = vec![0.0f32; ow * out.height() as usize];
let mut res = scratch::take(ow * out.height() as usize, 0.0f32);
if res.is_empty() {
return res;
}
@@ -376,6 +392,7 @@ fn box_passes(src: &Image, out: Rect, alpha: bool, boxes: &[usize]) -> Vec<f32>
for (dst, s) in res.chunks_exact_mut(ow).zip(data.chunks_exact(w)) {
dst[x0..x0 + w].copy_from_slice(s);
}
scratch::give(data);
}
res
}
+3 -2
View File
@@ -204,7 +204,7 @@ fn direct_boxes(img: &Image, out: Rect, boxes: &[usize], alpha: bool) -> Vec<f32
let rect = out.inflate(left);
cur = Image { rect, ch: img.ch, data: conv_sep(&cur, rect, &k, &k, alpha) };
}
cur.data
cur.into_data()
}
/// Noisy pixels over `r` (alpha varying, some fully transparent).
@@ -481,7 +481,8 @@ fn line_passes_stop_between_passes_when_cancelled() {
let reach: usize = radii.iter().sum();
let line: Vec<f32> = (0..(len + 2 * reach) * w).map(|i| (i % 7) as f32 + 1.0).collect();
let run = |ctl: &Interrupt| {
let mut s = Scratch { line: line.clone(), ..Scratch::default() };
let mut s = Scratch::new(0, 0);
s.line.extend_from_slice(&line);
let mut dst = vec![0.0f32; len * w];
line_passes(&mut dst, w, &radii, &mut s, ctl);
dst
+25 -4
View File
@@ -1,7 +1,7 @@
//! Interleaved `f32` image regions and sampling helpers.
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use photocraft_raster::{Surface, scratch};
/// How samples outside an image are read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -14,8 +14,9 @@ pub enum Edge {
Wrap,
}
/// A rectangle of interleaved, normalized samples.
#[derive(Clone, Debug, PartialEq)]
/// A rectangle of interleaved, normalized samples. The samples come from, and go back to, the
/// scratch pool.
#[derive(Debug, PartialEq)]
pub struct Image {
pub rect: Rect,
/// Channels per pixel (alpha last when the surface has alpha).
@@ -23,6 +24,20 @@ pub struct Image {
pub data: Vec<f32>,
}
impl Clone for Image {
fn clone(&self) -> Self {
let mut data = scratch::take(self.data.len(), 0.0f32);
data.copy_from_slice(&self.data);
Image { rect: self.rect, ch: self.ch, data }
}
}
impl Drop for Image {
fn drop(&mut self) {
scratch::give(std::mem::take(&mut self.data));
}
}
impl Image {
/// Reads `rect` from a surface.
pub fn read(s: &Surface, rect: Rect) -> Self {
@@ -53,9 +68,15 @@ impl Image {
img
}
/// The samples, taken out of the image (it can't be destructured: it returns them to the
/// pool on drop).
pub fn into_data(mut self) -> Vec<f32> {
std::mem::take(&mut self.data)
}
/// 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] }
Image { rect, ch, data: scratch::take(rect.width() as usize * rect.height() as usize * ch, 0.0) }
}
#[inline]
+5 -1
View File
@@ -1269,7 +1269,10 @@ fn apply_tiled_with_impl(
}
for (t, data) in results {
match data {
TileData::Samples(data) => out.write_region(t, &data),
TileData::Samples(data) => {
out.write_region(t, &data);
photocraft_raster::scratch::give(data);
}
TileData::Encoded(data) => out.write_interleaved(t, &data),
}
}
@@ -1324,6 +1327,7 @@ fn apply_box_blur(
mix_selection(data, *t, sel, &Image::read(surface, *t), fmt.alpha);
}
s.write_region(*t, data);
photocraft_raster::scratch::give(std::mem::take(data));
}
};
#[cfg(not(target_arch = "wasm32"))]
+6 -1
View File
@@ -267,7 +267,12 @@ fn malformed_inputs_and_allocations_stop_gracefully() {
assert!(crate::apply_in_with(&s, &p, rect, rect, None, rect, &Interrupt::NONE).is_none());
assert_eq!(crate::apply_in(&s, &p, rect, rect, None, rect), s);
}
for bad in [Image { ch: 0, ..src.clone() }, Image { data: vec![0.0], ..src.clone() }, Image { rect: Rect::new(5, 0, 0, 2), ..src.clone() }] {
let with = |edit: &dyn Fn(&mut Image)| {
let mut bad = src.clone();
edit(&mut bad);
bad
};
for bad in [with(&|i| i.ch = 0), with(&|i| i.data = vec![0.0]), with(&|i| i.rect = Rect::new(5, 0, 0, 2))] {
assert!(exact::run(&bad, rect, &ctx, 100.0, 1.0, 0.0, &Interrupt::NONE).is_none());
}
for rect in [Rect::new(i32::MIN, 0, i32::MAX, 2), Rect::new(0, 0, 300_000, 300_000), Rect::new(2, 0, 0, 2)] {
+1
View File
@@ -521,6 +521,7 @@ fn warp(
outp[o + a] = al as f32;
}
}
photocraft_raster::scratch::give(px);
Ok(any.then_some((*t, outp)))
};
// Each tile is written as soon as it is warped, so only the tiles in flight hold their `f32`
+2
View File
@@ -358,6 +358,8 @@ impl Headless {
if let Some(d) = self.session.close(i) {
self.writers.remove(&d.doc.id.0);
}
// The closed document's buffers went to the scratch pool: hand them back to the OS.
photocraft_raster::scratch::release();
Ok(self.session_list())
}
+4 -2
View File
@@ -254,8 +254,10 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them
ms in release). Image data cut off by the end of the file decodes with
`DecodeWarning::Truncated`; a file far too small for its declared size (more than any
compression could expand) is refused before allocating.
* YCbCr, CIE Lab, signed integers and compressions that the `tiff` crate lacks (CCITT,
JPEG-in-TIFF) return `Unsupported`.
* YCbCr with three 8- or 16-bit samples decodes to RGB. YCbCr with other sample counts or
bit depths returns `Unsupported`. JPEG-compressed YCbCr uses the full-range JFIF conversion.
* 8/16-bit CIELab and ICCLab decode to the Lab channel layout.
* Signed integer samples and unsupported compression methods return `Unsupported`.
* **TIFF encode** writes classic TIFF, or BigTIFF when `EncodeOptions::tiff_bigtiff` is set or
the file could pass 4 GiB. `Metadata::extra_samples` (up to 16) are written after the colour
and alpha samples, with their `kind` in the ExtraSamples tag (a reserved `kind` above 2 is
+1
View File
@@ -168,6 +168,7 @@ mod bands;
mod decode;
mod encode;
mod tags;
mod ycbcr;
pub use decode::TiffBands;
pub(crate) use decode::{decode, decode_page, orientation};
+33 -5
View File
@@ -2,6 +2,7 @@ use std::borrow::Cow;
use super::bands::{Tally, convert_ab, decode_bands, extra_sample_indices, refill_zeroed, split_extra_samples, zeroed};
use super::tags::{F, TAG_IMAGE_SOURCE_DATA, TAG_PHOTOSHOP, TAG_XMP, TEXT_TAGS, photoshop_tags};
use super::ycbcr::YCbCr;
use super::{
ChannelLayout, ChunkType, CodecError, DecodeWarning, Decoder, ExifDirs, File, Ifd, Image, Limits, Metadata, Read, SampleType, Seek, SeekFrom, Tag,
camera_raw, err, ifd, io, map_err, tiff_exif,
@@ -185,6 +186,9 @@ impl<'a> TiffBands<'a> {
// Missing chunks leave their rows as they are: they must start empty in every group.
buf = refill_zeroed(buf, len)?;
tally = tally + decode_bands(p, self.b, &mut buf, band, first, &mut [], 0)?;
if let Some(c) = p.ycbcr {
c.convert(&mut buf, p.lay.out_channels(), p.lay.out);
}
if let Some(signed) = p.lab {
convert_ab(&mut buf, p.lay.out_channels(), p.lay.out, signed, false);
}
@@ -520,6 +524,20 @@ fn header_patches(
Ok(patches)
}
/// Lab and YCbCr are converted after decoding, from 8 or 16-bit samples only: Lab needs at least
/// its three colour samples, YCbCr exactly three.
fn check_converted_model(photometric: u64, spp: u64, bits: u64, src: Src) -> Result<(), CodecError> {
let (name, samples_ok) = match photometric {
8 | 9 => ("Lab", spp >= 3),
6 => ("YCbCr", spp == 3),
_ => return Ok(()),
};
if samples_ok && matches!(src, Src::U8 | Src::U16) {
return Ok(());
}
Err(CodecError::unsupported(F, format!("{name} image with {spp} samples of {bits} bits")))
}
/// A directory checked and laid out for decoding, before any pixel is read.
pub(super) struct Prepared {
w: u32,
@@ -531,6 +549,8 @@ pub(super) struct Prepared {
tl: tiff::decoder::Limits,
/// Lab samples: `Some(true)` for CIELab (a* and b* stored signed), `Some(false)` for ICCLab.
lab: Option<bool>,
/// YCbCr samples: the conversion to RGB (#10316).
ycbcr: Option<YCbCr>,
/// The colour samples of a pixel in the file's colour model.
color: usize,
/// The ExtraSamples tag (0 unspecified, 1 associated alpha, 2 unassociated alpha).
@@ -567,6 +587,9 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
if tally.decoded == 0 && tally.missing > 0 {
return Err(err("the image data is missing (cut off or past the end of the file)"));
}
if let Some(c) = p.ycbcr {
c.convert(&mut data, p.lay.out_channels(), p.lay.out);
}
if let Some(signed) = p.lab {
convert_ab(&mut data, p.lay.out_channels(), p.lay.out, signed, false);
}
@@ -642,15 +665,17 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
// `tiff` crate as RGB, then labelled Lab with a* and b* in PhotoCraft's encoding
// (`convert_ab`).
let lab = matches!(photometric, 8 | 9);
if lab && (spp < 3 || !matches!(src, Src::U8 | Src::U16)) {
return Err(CodecError::unsupported(F, format!("Lab image with {spp} samples of {bits} bits")));
}
// YCbCr (6), as scanners and cameras write it (usually JPEG-compressed with subsampled
// chroma): the `tiff` crate decodes and upsamples the samples, and they are turned into RGB
// after decoding (#10316).
let ycbcr = photometric == 6;
check_converted_model(photometric, spp, bits, src)?;
// TIFF 6.0 lets any extra sample be the alpha (#1349). For RGB and CMYK the `tiff` crate
// returns the alpha only when it is the first extra sample: otherwise it is asked for every
// sample (as multiband gray) and the colour and alpha samples are picked here. An alpha
// position past the samples the file has is ignored.
let color: usize = match photometric {
2 | 8 | 9 => 3,
2 | 6 | 8 | 9 => 3,
5 => 4,
_ => 1,
};
@@ -686,6 +711,7 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
(if gray_alpha { ChannelLayout::GrayA } else { ChannelLayout::Gray }, usize::from(num_samples))
}
tiff::ColorType::RGB(_) => (ChannelLayout::Rgb, 3),
tiff::ColorType::YCbCr(_) if ycbcr => (ChannelLayout::Rgb, 3),
tiff::ColorType::RGBA(_) => (ChannelLayout::Rgba, 4),
tiff::ColorType::CMYK(_) => (ChannelLayout::Cmyk, 4),
tiff::ColorType::CMYKA(_) => (ChannelLayout::CmykA, 5),
@@ -729,8 +755,9 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
// strip or tile tables point at inside the file count (and never more than the file), so
// padding the file while pointing the chunks past its end does not raise the bound: the
// banded decoder has no whole-image `max_alloc` to fall back on.
let compression = f.tag_uint(dir, ifd::TAG_COMPRESSION).unwrap_or(1);
let stored = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(spp).saturating_mul(bits).div_ceil(8);
let ratio: u64 = match f.tag_uint(dir, ifd::TAG_COMPRESSION).unwrap_or(1) {
let ratio: u64 = match compression {
1 => 4,
32773 => 130,
4 => cw.clamp(4096, 65_535),
@@ -814,6 +841,7 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
patches,
tl,
lab: lab.then_some(photometric == 8),
ycbcr: ycbcr.then(|| YCbCr::of(f, dir, compression, if out == SampleType::U16 { 65535.0 } else { 255.0 })),
color,
extra_kinds: extra,
extras_over_limit,
+222
View File
@@ -0,0 +1,222 @@
//! YCbCr (PhotometricInterpretation 6) to RGB, after the `tiff` crate has decoded the samples.
//!
//! The crate decompresses JPEG data and upsamples subsampled chroma, but hands back the stored
//! Y, Cb and Cr values. This module turns them into RGB in place: ReferenceBlackWhite scales the
//! codes and YCbCrCoefficients gives the luma weights. JPEG-compressed data (compression 7) uses
//! the JPEG (JFIF) conversion, full range with the BT.601 weights, and ignores both tags, as
//! libtiff does when it asks the JPEG library for RGB.
//!
//! # Sources
//!
//! - TIFF Revision 6.0 (Final, June 3, 1992), Section 21 "YCbCr Images", pp. 89–92; the
//! YCbCrCoefficients field and its inverse equations are on pp. 90–91:
//! `R = Cr·(2 - 2·LumaRed) + Y`, `B = Cb·(2 - 2·LumaBlue) + Y`,
//! `G = (Y - LumaBlue·B - LumaRed·R) / LumaGreen`.
//! <https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf>
//! - libtiff, `libtiff/tif_color.c`: `TIFFYCbCrToRGBInit` (tables) and `TIFFYCbCrtoRGB` (per pixel).
//! <https://gitlab.com/libtiff/libtiff/-/blob/master/libtiff/tif_color.c>
//!
//! # Green: a compatibility choice
//!
//! Red and blue follow the spec. Green follows libtiff, which rewrites the spec's equation as
//! `G = Y - (LumaRed·(2 - 2·LumaRed) / LumaGreen)·Cr - (LumaBlue·(2 - 2·LumaBlue) / LumaGreen)·Cb`,
//! adding Y unscaled. The two agree only when the weights sum to 1. Every standard set does
//! (the spec's own examples, BT.601 and BT.709), but the spec only calls the weights "the
//! proportions of red, green, and blue respectively in luminance" and does not require the sum.
//! For other weights the spec's equation scales Y in green by `(1 - LumaRed - LumaBlue) / LumaGreen`,
//! which tints neutral grays.
//!
//! PhotoCraft deliberately follows libtiff here (decided in PR #10319, for issue #10316), so such
//! files open as they do in libtiff-based tools (ImageMagick, GIMP) and grays stay neutral. This is
//! a contributor choice, not a requirement of the spec; the test
//! `weights_that_do_not_sum_to_one_keep_grays_neutral` in `tests/it/tiff_ycbcr.rs` pins it.
use super::{File, Ifd, SampleType};
const TAG_YCBCR_COEFFICIENTS: u16 = 529;
const TAG_REFERENCE_BLACK_WHITE: u16 = 532;
/// BT.601 luma weights: the TIFF default for YCbCrCoefficients.
const BT601: [f64; 3] = [0.299, 0.587, 0.114];
/// How one file's YCbCr codes map to RGB.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct YCbCr {
/// Luma weights of red, green and blue.
luma: [f64; 3],
/// Black and white codes of Y, Cb and Cr.
ref_bw: [f64; 6],
}
impl YCbCr {
/// The conversion for directory `dir`, whose samples have `max` as their largest code
/// (255 or 65535). Missing or unusable tags fall back to the TIFF defaults.
pub(super) fn of(f: &File<'_>, dir: &Ifd, compression: u64, max: f64) -> Self {
let defaults = Self::defaults(max);
if compression == 7 {
return defaults;
}
let luma = f
.tag_f64s(dir, TAG_YCBCR_COEFFICIENTS, 3)
.and_then(|v| <[f64; 3]>::try_from(v).ok())
.filter(|l| l.iter().all(|c| c.is_finite() && *c > 0.0 && *c < 1.0))
.unwrap_or(defaults.luma);
let ref_bw = f
.tag_f64s(dir, TAG_REFERENCE_BLACK_WHITE, 6)
.and_then(|v| <[f64; 6]>::try_from(v).ok())
.filter(|r| r.iter().all(|v| v.is_finite()) && r.as_chunks::<2>().0.iter().all(|[black, white]| (white - black).abs() > f64::EPSILON))
.unwrap_or(defaults.ref_bw);
YCbCr { luma, ref_bw }
}
/// TIFF's defaults: BT.601 weights, full-range luma, chroma centred on the middle code.
fn defaults(max: f64) -> Self {
let mid = (max + 1.0) / 2.0;
YCbCr { luma: BT601, ref_bw: [0.0, max, mid, max, mid, max] }
}
/// Converts interleaved Y, Cb, Cr pixels of `channels` samples (the first three are the
/// colour) to R, G, B in place. Other sample types are left as they are.
pub(super) fn convert(self, data: &mut [u8], channels: usize, sample: SampleType) {
match sample {
SampleType::U8 => {
let t = Tables::new(&self, 255);
for_each_pixel(data, channels, |px| {
if let [y, cb, cr, ..] = px {
let [r, g, b] = t.rgb(usize::from(*y), usize::from(*cb), usize::from(*cr));
(*y, *cb, *cr) = (r as u8, g as u8, b as u8);
}
});
}
SampleType::U16 => {
let t = Tables::new(&self, 65535);
for_each_pixel(data, channels * 2, |px| {
if let [y0, y1, b0, b1, r0, r1, ..] = px {
let get = |a: u8, b: u8| usize::from(u16::from_ne_bytes([a, b]));
let [r, g, b] = t.rgb(get(*y0, *y1), get(*b0, *b1), get(*r0, *r1));
[*y0, *y1] = (r as u16).to_ne_bytes();
[*b0, *b1] = (g as u16).to_ne_bytes();
[*r0, *r1] = (b as u16).to_ne_bytes();
}
});
}
_ => {}
}
}
}
/// Runs `f` on every `stride`-byte pixel, in parallel on native targets.
fn for_each_pixel(data: &mut [u8], stride: usize, f: impl Fn(&mut [u8]) + Sync + Send) {
if stride == 0 {
return;
}
#[cfg(not(target_arch = "wasm32"))]
{
use rayon::prelude::*;
// Bands of whole pixels, so each task has a useful amount of work.
let band = stride.saturating_mul(1 << 14);
data.par_chunks_mut(band).for_each(|b| b.chunks_exact_mut(stride).for_each(&f));
}
#[cfg(target_arch = "wasm32")]
data.chunks_exact_mut(stride).for_each(f);
}
/// Per-code contributions, so a pixel costs a few additions.
struct Tables {
max: f64,
/// Scaled luma of each Y code.
y: Vec<f64>,
/// Red and green contributions of each Cr code.
cr_r: Vec<f64>,
cr_g: Vec<f64>,
/// Green and blue contributions of each Cb code.
cb_g: Vec<f64>,
cb_b: Vec<f64>,
}
impl Tables {
fn new(c: &YCbCr, max: u32) -> Self {
let m = f64::from(max);
let [lr, lg, lb] = c.luma;
let [y_black, y_white, cb_black, cb_white, cr_black, cr_white] = c.ref_bw;
// TIFF 6.0: chroma codes span ±(max + 1) / 2 - 1 around the black code; with the
// default ReferenceBlackWhite that is the code minus the middle code.
let half = (m + 1.0) / 2.0 - 1.0;
let codes = || (0..=max).map(f64::from);
let y = codes().map(|v| (v - y_black) * m / (y_white - y_black)).collect();
let cb: Vec<f64> = codes().map(|v| (v - cb_black) * half / (cb_white - cb_black)).collect();
let cr: Vec<f64> = codes().map(|v| (v - cr_black) * half / (cr_white - cr_black)).collect();
// R = Y + (2 - 2·Lr)·Cr and B = Y + (2 - 2·Lb)·Cb (TIFF 6.0 p. 91); green as libtiff:
// G = Y - (Lr·(2 - 2·Lr) / Lg)·Cr - (Lb·(2 - 2·Lb) / Lg)·Cb (see the module notes).
let (kr, kb) = (2.0 - 2.0 * lr, 2.0 - 2.0 * lb);
Tables {
max: m,
y,
cr_r: cr.iter().map(|v| kr * v).collect(),
cr_g: cr.iter().map(|v| -lr * kr * v / lg).collect(),
cb_g: cb.iter().map(|v| -lb * kb * v / lg).collect(),
cb_b: cb.iter().map(|v| kb * v).collect(),
}
}
/// R, G and B of one pixel, rounded and clamped to the code range.
fn rgb(&self, y: usize, cb: usize, cr: usize) -> [u32; 3] {
let at = |t: &[f64], i: usize| t.get(i).copied().unwrap_or(0.0);
let yv = at(&self.y, y);
// Green adds Y unscaled, as libtiff does (see "Green: a compatibility choice" above).
let r = yv + at(&self.cr_r, cr);
let g = yv + at(&self.cr_g, cr) + at(&self.cb_g, cb);
let b = yv + at(&self.cb_b, cb);
[r, g, b].map(|v| v.round().clamp(0.0, self.max) as u32)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn convert(c: &YCbCr, px: [u8; 3]) -> [u8; 3] {
let mut d = px.to_vec();
c.convert(&mut d, 3, SampleType::U8);
[d[0], d[1], d[2]]
}
#[test]
fn jfif_conversion_matches_known_colours() {
let c = YCbCr::defaults(255.0);
assert_eq!(convert(&c, [0, 128, 128]), [0, 0, 0]);
assert_eq!(convert(&c, [255, 128, 128]), [255, 255, 255]);
assert_eq!(convert(&c, [128, 128, 128]), [128, 128, 128]);
// Pure red, green and blue as JFIF encodes them.
assert_eq!(convert(&c, [76, 85, 255]), [254, 0, 0]);
assert_eq!(convert(&c, [150, 44, 21]), [0, 255, 1]);
assert_eq!(convert(&c, [29, 255, 107]), [0, 0, 254]);
}
#[test]
fn sixteen_bit_and_extra_samples() {
let c = YCbCr::defaults(65535.0);
let mut d: Vec<u8> = [65535u16, 32768, 32768, 1234].iter().flat_map(|v| v.to_ne_bytes()).collect();
c.convert(&mut d, 4, SampleType::U16);
let v: Vec<u16> = d.as_chunks::<2>().0.iter().map(|b| u16::from_ne_bytes(*b)).collect();
assert_eq!(v, [65535, 65535, 65535, 1234]);
}
#[test]
fn studio_range_reference_black_white() {
// Y 16–235, chroma 128 ± 112 (ITU-R BT.601 studio range).
let c = YCbCr { luma: BT601, ref_bw: [16.0, 235.0, 128.0, 240.0, 128.0, 240.0] };
assert_eq!(convert(&c, [16, 128, 128]), [0, 0, 0]);
assert_eq!(convert(&c, [235, 128, 128]), [255, 255, 255]);
}
#[test]
fn odd_buffers_do_not_panic() {
let c = YCbCr::defaults(255.0);
let mut d = vec![1u8, 2];
c.convert(&mut d, 3, SampleType::U8);
c.convert(&mut d, 0, SampleType::U8);
c.convert(&mut d, 0, SampleType::U16);
assert_eq!(d, [1, 2]);
}
}
+20 -5
View File
@@ -236,18 +236,33 @@ impl<'a> File<'a> {
/// The first value of a numeric tag as a float: RATIONAL, FLOAT, DOUBLE or an integer.
pub fn tag_f64(&self, ifd: &Ifd, tag: u16) -> Option<f64> {
self.float(ifd.get(tag)?, 0)
}
/// The values of a numeric tag as floats, when it holds exactly `n` (`None` for any other
/// count or an unreadable value).
pub fn tag_f64s(&self, ifd: &Ifd, tag: u16, n: u64) -> Option<Vec<f64>> {
let e = ifd.get(tag)?;
if e.count == 0 {
if e.count != n {
return None;
}
(0..n).map(|i| self.float(e, i)).collect()
}
/// Value `i` of a numeric entry as a float: RATIONAL, FLOAT, DOUBLE or an integer.
fn float(&self, e: &Entry, i: u64) -> Option<f64> {
if i >= e.count {
return None;
}
let at = e.value_at.checked_add(i.checked_mul(type_size(e.ty)?)?)?;
match e.ty {
5 => {
let (n, d) = (self.u32_at(e.value_at)?, self.u32_at(e.value_at.checked_add(4)?)?);
let (n, d) = (self.u32_at(at)?, self.u32_at(at.checked_add(4)?)?);
(d != 0).then(|| f64::from(n) / f64::from(d))
}
11 => Some(f64::from(f32::from_bits(self.u32_at(e.value_at)?))),
12 => Some(f64::from_bits(self.u64_at(e.value_at)?)),
_ => self.uint(e, 0).map(|v| v as f64),
11 => Some(f64::from(f32::from_bits(self.u32_at(at)?))),
12 => Some(f64::from_bits(self.u64_at(at)?)),
_ => self.uint(e, i).map(|v| v as f64),
}
}
+1
View File
@@ -31,6 +31,7 @@ mod tiff_lab;
mod tiff_pages;
mod tiff_photoshop;
mod tiff_regressions;
mod tiff_ycbcr;
mod webp_frames;
mod webp_lossy;
mod xpm;
+259
View File
@@ -0,0 +1,259 @@
//! YCbCr TIFFs (PhotometricInterpretation 6), as scanners write them: JPEG-compressed with 2×2
//! chroma subsampling, and uncompressed with ReferenceBlackWhite and YCbCrCoefficients (#10316).
//! Every file here is hand-built by `common::tiffgen`.
use crate::common::sample_icc;
use crate::common::tiffgen::*;
use photocraft_codecs::*;
const COMPRESSION: u16 = 259;
const SUBSAMPLING: u16 = 530;
const YCBCR_COEFFICIENTS: u16 = 529;
const REFERENCE_BLACK_WHITE: u16 = 532;
const ICC_PROFILE: u16 = 34675;
/// A directory whose Compression is `c`.
fn compressed(mut d: Dir, c: u64) -> Dir {
d.entries.retain(|e| e.0 != COMPRESSION);
d.tag(COMPRESSION, SHORT, &[c])
}
/// A little-endian RATIONAL value for `tiffgen`.
fn rational(num: u32, den: u32) -> u64 {
u64::from(num) | (u64::from(den) << 32)
}
/// The image's pixels as RGB bytes.
fn rgb(img: &Image) -> Vec<u8> {
img.to_rgba8().as_chunks::<4>().0.iter().flat_map(|[r, g, b, _]| [*r, *g, *b]).collect()
}
/// A smooth colour test card, `w`×`h` RGB.
fn card(w: u32, h: u32) -> Vec<u8> {
let mut v = Vec::new();
for y in 0..h {
for x in 0..w {
v.extend([(x * 255 / (w - 1)) as u8, (y * 255 / (h - 1)) as u8, (255 - x * 255 / (w - 1)) as u8]);
}
}
v
}
/// A 4:2:0 baseline JPEG stream of `rgb`.
fn jpeg(rgb: &[u8], w: u32, h: u32) -> Vec<u8> {
let img = Image::from_raw(w, h, ChannelLayout::Rgb, SampleType::U8, rgb.to_vec()).unwrap();
encode(&img, Format::Jpeg, &EncodeOptions { jpeg_chroma_subsampling: true, ..Default::default() }).unwrap()
}
#[test]
fn jpeg_compressed_ycbcr_with_subsampled_chroma_reads_as_rgb() {
let (w, h) = (32, 24);
let stream = jpeg(&card(w, h), w, h);
// The stream really is subsampled: the luma component samples 2×2 in the frame header.
let sof = stream.windows(2).position(|m| m == [0xFF, 0xC0]).expect("baseline frame header");
assert_eq!(stream[sof + 11], 0x22, "luma sampling factors");
let dir = compressed(strips(w, h, 8, 3, 6, h, &stream), 7).tag(SUBSAMPLING, SHORT, &[2, 2]);
let file = build(true, false, &[dir], &[0]).bytes;
let img = decode(&file).unwrap();
assert_eq!((img.width(), img.height(), img.layout(), img.sample_type()), (w, h, ChannelLayout::Rgb, SampleType::U8));
// The oracle: the same JPEG stream decoded to RGB by an independent decoder.
let want = image::load_from_memory_with_format(&stream, image::ImageFormat::Jpeg).unwrap().to_rgb8().into_raw();
let worst = rgb(&img).iter().zip(&want).map(|(g, o)| g.abs_diff(*o)).max().unwrap();
assert!(worst <= 2, "largest difference from the oracle: {worst}");
}
#[test]
fn uncompressed_ycbcr_uses_the_default_conversion() {
// Black, white, mid gray and JFIF's pure red, without subsampling.
let px = [0, 128, 128, 255, 128, 128, 128, 128, 128, 76, 85, 255];
let dir = strips(4, 1, 8, 3, 6, 1, &px).tag(SUBSAMPLING, SHORT, &[1, 1]);
let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap();
assert_eq!(img.layout(), ChannelLayout::Rgb);
assert_eq!(rgb(&img), [0, 0, 0, 255, 255, 255, 128, 128, 128, 254, 0, 0]);
}
#[test]
fn reference_black_white_sets_the_code_range() {
// Studio range: Y 16–235, chroma 128 ± 112.
let rbw = [rational(16, 1), rational(235, 1), rational(128, 1), rational(240, 1), rational(128, 1), rational(240, 1)];
let dir = strips(2, 1, 8, 3, 6, 1, &[16, 128, 128, 235, 128, 128]).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(REFERENCE_BLACK_WHITE, RATIONAL, &rbw);
let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap();
assert_eq!(rgb(&img), [0, 0, 0, 255, 255, 255]);
}
#[test]
fn weights_that_do_not_sum_to_one_keep_grays_neutral() {
// 0.25 each (sum 0.75): TIFF 6.0's full inverse would scale green's Y by (1 − Lr − Lb) / Lg
// = 2 and give mid gray G 255 (clamped). Like libtiff, green keeps Y, so gray stays gray, and
// the weights still set the chroma terms: R = Y + 1.5·Cr, B = Y + 1.5·Cb.
let weights = [rational(1, 4), rational(1, 4), rational(1, 4)];
let dir = strips(2, 1, 8, 3, 6, 1, &[128, 128, 128, 128, 64, 192]).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(YCBCR_COEFFICIENTS, RATIONAL, &weights);
let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap();
// Green for the second pixel: 128 − (Lb·1.5/Lg)·Cb − (Lr·1.5/Lg)·Cr = 128 + 96 − 96.
assert_eq!(rgb(&img), [128, 128, 128, 224, 128, 32]);
}
#[test]
fn ycbcr_coefficients_set_the_luma_weights() {
// Weights 0.25, 0.5, 0.25 with Cb −64 and Cr +64: R = Y + 1.5·Cr, B = Y + 1.5·Cb, and G keeps Y
// (BT.601 would give R 218 and B 15).
let weights = [rational(1, 4), rational(1, 2), rational(1, 4)];
let dir = strips(1, 1, 8, 3, 6, 1, &[128, 64, 192]).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(YCBCR_COEFFICIENTS, RATIONAL, &weights);
let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap();
assert_eq!(rgb(&img), [224, 128, 32]);
}
#[test]
fn ycbcr_tags_with_the_wrong_count_use_the_defaults() {
// Four weights and seven black/white codes: both tags are malformed, so BT.601 and full range
// apply (the weights alone would give 224, 128, 32).
let weights = [rational(1, 4), rational(1, 2), rational(1, 4), rational(1, 4)];
let rbw = [rational(16, 1), rational(235, 1), rational(128, 1), rational(240, 1), rational(128, 1), rational(240, 1), rational(0, 1)];
let dir = strips(1, 1, 8, 3, 6, 1, &[128, 64, 192]).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(YCBCR_COEFFICIENTS, RATIONAL, &weights).tag(
REFERENCE_BLACK_WHITE,
RATIONAL,
&rbw,
);
let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap();
assert_eq!(rgb(&img), [218, 104, 15]);
}
#[test]
fn sixteen_bit_ycbcr_reads_as_rgb() {
let px: Vec<u8> = [65535u16, 32768, 32768, 0, 32768, 32768].iter().flat_map(|v| v.to_le_bytes()).collect();
let dir = strips(2, 1, 16, 3, 6, 1, &px).tag(SUBSAMPLING, SHORT, &[1, 1]);
let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap();
assert_eq!((img.layout(), img.sample_type()), (ChannelLayout::Rgb, SampleType::U16));
let n = img.to_normalized();
assert!(n[..3].iter().all(|&v| v == 1.0) && n[3..].iter().all(|&v| v == 0.0), "{n:?}");
}
#[test]
#[cfg(target_pointer_width = "64")]
fn sixteen_bit_ycbcr_bands_match_whole_decode_with_a_missing_last_strip() {
// On 32-bit targets max_alloc also bounds the whole image, so a small allocation cap
// cannot force these tiny strips into separate output groups there.
let (w, h, rows) = (4u32, 5u32, 2u32);
let pixels = [[0u16, 32768, 32768], [65535, 32768, 32768], [19595, 21710, 65535], [32768, 40960, 24576]];
let samples: Vec<u16> = (0..w * h).flat_map(|i| pixels[i as usize % pixels.len()]).collect();
let weights = [rational(1, 4), rational(1, 2), rational(1, 4)];
let icc = sample_icc(512);
for little in [true, false] {
for missing in [false, true] {
let dir = strips(w, h, 16, 3, 6, rows, &u16s(&samples, little)).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(YCBCR_COEFFICIENTS, RATIONAL, &weights).bytes(
ICC_PROFILE,
UNDEFINED,
&icc,
);
let mut file = build(little, false, &[dir], &[0]);
if missing {
let past = file.bytes.len() as u64 + 4096;
patch_value(&mut file, little, false, 0, 273, 2, past);
}
let want = decode_with(&file.bytes, &DecodeOptions { keep_orientation: true, ..Default::default() }).unwrap();
let limits = Limits { max_alloc: u64::from(w * rows * 3 * 2), ..Limits::banded() };
let mut bands = TiffBands::open(&file.bytes, None, &limits).unwrap();
assert_eq!((bands.dimensions(), bands.layout(), bands.sample_type()), ((w, h), ChannelLayout::Rgb, SampleType::U16));
let mut got = Image::new(w, h, bands.layout(), bands.sample_type()).unwrap();
let mut positions = Vec::new();
bands
.decode(|x, y, group: &Image| -> Result<(), CodecError> {
positions.push((x, y, group.height()));
assert_eq!((x, group.width(), group.layout(), group.sample_type()), (0, w, ChannelLayout::Rgb, SampleType::U16));
let at = y as usize * w as usize * 3 * 2;
got.data_mut()[at..at + group.data().len()].copy_from_slice(group.data());
Ok(())
})
.unwrap();
assert_eq!(positions, [(0, 0, 2), (0, 2, 2), (0, 4, 1)], "one output group per strip, including the short last strip");
assert_eq!(got.data(), want.data(), "little endian: {little}, missing last strip: {missing}");
assert_eq!(bands.icc, want.icc);
assert_eq!(bands.meta, want.meta);
assert_eq!(bands.warnings, want.warnings);
assert_eq!(bands.warnings.iter().any(|w| matches!(w, DecodeWarning::Truncated { .. })), missing);
}
}
}
#[test]
fn unsupported_ycbcr_files_fail_cleanly() {
// Four samples (an extra sample next to YCbCr).
let four = strips(1, 1, 8, 4, 6, 1, &[128, 128, 128, 255]).tag(SUBSAMPLING, SHORT, &[1, 1]);
assert!(decode(&build(true, false, &[four], &[0]).bytes).is_err());
// Subsampled chroma without JPEG compression (the default subsampling is 2×2).
let sub = strips(2, 2, 8, 3, 6, 2, &[128; 12]);
assert!(decode(&build(true, false, &[sub], &[0]).bytes).is_err());
// A JPEG strip that is not JPEG data.
let junk = compressed(strips(16, 16, 8, 3, 6, 16, &[0x5A; 64]), 7).tag(SUBSAMPLING, SHORT, &[2, 2]);
assert!(decode(&build(true, false, &[junk], &[0]).bytes).is_err());
// Coefficients and ReferenceBlackWhite that would divide by zero fall back to the defaults.
let bad = strips(1, 1, 8, 3, 6, 1, &[255, 128, 128])
.tag(SUBSAMPLING, SHORT, &[1, 1])
.tag(YCBCR_COEFFICIENTS, RATIONAL, &[rational(0, 1), rational(0, 0), rational(5, 1)])
.tag(REFERENCE_BLACK_WHITE, RATIONAL, &[rational(7, 1); 6]);
let img = decode(&build(true, false, &[bad], &[0]).bytes).unwrap();
assert_eq!(&img.to_rgba8()[..3], &[255, 255, 255]);
}
#[test]
fn tiled_jpeg_ycbcr_keeps_its_icc_profile() {
// Two 16×16 tiles, each its own 4:2:0 JPEG stream, and an embedded profile, like a scanner's
// tiled output.
let (w, h, t) = (32u32, 16u32, 16u32);
let px = card(w, h);
let tile = |tx: u32| -> Vec<u8> {
(0..t)
.flat_map(|y| {
let at = ((y * w + tx * t) * 3) as usize;
px[at..at + (t * 3) as usize].to_vec()
})
.collect()
};
let streams = [jpeg(&tile(0), t, t), jpeg(&tile(1), t, t)];
let icc = sample_icc(512);
let dir = Dir { entries: base(w, h, 8, 3, 6), chunks: streams.to_vec(), tiled: true };
let dir = compressed(dir, 7).tag(322, SHORT, &[u64::from(t)]).tag(323, SHORT, &[u64::from(t)]).tag(SUBSAMPLING, SHORT, &[2, 2]).bytes(
ICC_PROFILE,
UNDEFINED,
&icc,
);
let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap();
assert_eq!((img.width(), img.height(), img.layout()), (w, h, ChannelLayout::Rgb));
assert_eq!(img.icc.as_deref(), Some(icc.as_slice()), "the embedded profile is kept");
// The oracle: each tile's stream decoded by an independent decoder, placed side by side.
let tiles: Vec<Vec<u8>> = streams.iter().map(|s| image::load_from_memory_with_format(s, image::ImageFormat::Jpeg).unwrap().to_rgb8().into_raw()).collect();
let row = (t * 3) as usize;
let want: Vec<u8> = (0..t as usize).flat_map(|y| [&tiles[0][y * row..(y + 1) * row], &tiles[1][y * row..(y + 1) * row]].concat()).collect();
let worst = rgb(&img).iter().zip(&want).map(|(g, o)| g.abs_diff(*o)).max().unwrap();
assert!(worst <= 2, "largest difference from the oracle: {worst}");
}
#[test]
fn big_endian_sixteen_bit_ycbcr_reads_as_rgb() {
// White, black, and red as full-range 16-bit YCbCr (Y 0.299·65535, Cb 32768 − 0.1687·65535, Cr max).
let px = [65535u16, 32768, 32768, 0, 32768, 32768, 19595, 21710, 65535];
let dir = strips(3, 1, 16, 3, 6, 1, &u16s(&px, false)).tag(SUBSAMPLING, SHORT, &[1, 1]);
let file = build(false, false, &[dir], &[0]).bytes;
assert_eq!(&file[..2], b"MM");
let img = decode(&file).unwrap();
assert_eq!((img.layout(), img.sample_type()), (ChannelLayout::Rgb, SampleType::U16));
let n = img.to_normalized();
let want = [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0];
assert!(n.iter().zip(want).all(|(g, w)| (g - w).abs() < 2.0 / 255.0), "{n:?}");
}
#[test]
fn planar_ycbcr_reads_as_rgb_in_both_byte_orders() {
// The pixels of the default-conversion test, one plane per component.
let px = [0u8, 128, 128, 255, 128, 128, 128, 128, 128, 76, 85, 255];
for little in [true, false] {
let dir = Dir { entries: base(4, 1, 8, 3, 6), chunks: planar_strips(&px, 4, 1, 3, 1, 1), tiled: false }.tag(278, LONG, &[1]).tag(284, SHORT, &[2]).tag(
SUBSAMPLING,
SHORT,
&[1, 1],
);
let img = decode(&build(little, false, &[dir], &[0]).bytes).unwrap();
assert_eq!(rgb(&img), [0, 0, 0, 255, 255, 255, 128, 128, 128, 254, 0, 0], "little endian: {little}");
}
}
+13 -2
View File
@@ -32,6 +32,7 @@ use std::borrow::Cow;
use photocraft_doc::{Knockout, Layer, LayerContent};
use photocraft_geom::Rect;
use crate::extents::recycle_mask;
use crate::{Buffer, Ctx, composite_atop, composite_layer, effects, mask_vals, render_content};
/// Where a layer stack sits, for knockouts: at the document's top level, and/or inside an
@@ -157,6 +158,7 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl
if target.rect != backdrop.rect || shape.len() != backdrop.px.len() {
// Never reached (targets are built over the backdrop's rect); compositing without the
// knockout beats a wrong pixel or a panic.
recycle_mask(Some(shape));
draw(backdrop);
return;
}
@@ -172,7 +174,10 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl
}
let knocked = (layer.opacity < 1.0).then(|| backdrop.clone());
draw(backdrop);
let Some(knocked) = knocked else { return };
let Some(knocked) = knocked else {
recycle_mask(Some(shape));
return;
};
let rest = 1.0 - layer.opacity.clamp(0.0, 1.0);
for (((p, b), k), s) in backdrop.px.iter_mut().zip(&before.px).zip(&knocked.px).zip(&shape) {
if *s <= 0.0 {
@@ -186,6 +191,7 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl
let a = pm[3].clamp(0.0, 1.0);
*p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] };
}
recycle_mask(Some(shape));
}
/// Composite a clipping group's clipped layers atop `base` (the base's isolated content, Blend
@@ -220,7 +226,12 @@ pub(crate) fn composite_clipped_individually(layer: &Layer, clipped: &[Layer], b
let op = layer.opacity.clamp(0.0, 1.0);
let clip: Vec<f32> = match render_content(layer, rect, cx) {
Some(b) => b.px.iter().map(|p| p[3] * op).collect(),
None => mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]).iter().map(|m| m * op).collect(),
None => {
let mv = mask_vals(layer, rect, cx);
let clip = mv.as_ref().map_or_else(|| vec![op; n], |m| m.iter().map(|m| m * op).collect());
recycle_mask(mv);
clip
}
};
if clip.len() != n {
return;
+4 -4
View File
@@ -395,7 +395,7 @@ fn shapeless_stroke_tile_skips_match_full_region_across_blending_settings() {
.unwrap();
let mut band_pixels = Vec::with_capacity(whole.px.len());
for band in bands {
band_pixels.extend(band.px);
band_pixels.extend(band.into_px());
}
assert_eq!(whole.px, band_pixels, "banded: {depth:?}, {position:?}, {blend:?}, fill={fill}, blend_if={blend_if}");
}
@@ -639,7 +639,7 @@ fn transparency_shapes_off_ignores_masks_and_reaches_groups() {
l.mask = Some(LayerMask { surface: photocraft_raster::Surface::with_default(PixelFormat::GRAY8, &[77.0 / 255.0]), ..LayerMask::reveal_all() });
l.advanced.transparency_shapes = tsl;
d.layers.push(l);
render(&d, d.bounds()).px
render(&d, d.bounds()).into_px()
};
let (off, on) = (render_with(false), render_with(true));
assert!(off.iter().zip(&on).all(|(a, b)| close(*a, *b)), "{mode:?} ({depth:?}): a mask isn't the layer's transparency");
@@ -691,13 +691,13 @@ fn transparency_shapes_off_keeps_the_base_alpha_under_a_clipped_knockout() {
base.advanced.transparency_shapes = false;
base.vector_mask = Some(photocraft_doc::vector::VectorMask { feather: 1.5, ..photocraft_doc::vector::VectorMask::new(square.clone()) });
d.layers.push(base);
let alone = render(&d, d.bounds()).px;
let alone = render(&d, d.bounds()).into_px();
let mut red = solid(&d, "red", full(&d), [1.0, 0.0, 0.0, 0.5]);
red.clipped = true;
let mut knock = knocker(&d, k);
knock.clipped = true;
d.layers.extend([red, knock]);
let got = render(&d, d.bounds()).px;
let got = render(&d, d.bounds()).into_px();
let what = format!("{k:?} ({depth:?})");
for (i, (g, a)) in got.iter().zip(&alone).enumerate() {
if i % 12 < 6 {
+4
View File
@@ -27,6 +27,7 @@ use photocraft_doc::adjust::ToneSpace;
use photocraft_doc::{Adjustment, Document, Knockout, Layer, LayerContent};
use photocraft_geom::Rect;
use super::extents::recycle_mask;
use super::{Ctx, RENDER_TILE, advanced, empty_in, mask_vals, pattern};
#[path = "cmyk_split.rs"]
@@ -355,6 +356,7 @@ fn apply_mask(l: &Layer, buf: &mut CmykBuffer, cx: &Ctx) {
for (p, k) in buf.px.iter_mut().zip(&m) {
p[4] *= clean(*k).max(0.0);
}
recycle_mask(Some(m));
}
}
@@ -425,6 +427,7 @@ fn mix_adjusted(l: &Layer, base: &mut CmykBuffer, adjusted: &CmykBuffer, cx: &Ct
*v = if k >= 1.0 { b } else { *v + (b - *v) * k };
}
}
recycle_mask(mv);
}
/// Rounds to the document's levels after an adjustment layer, as the compositor does (on the
@@ -534,6 +537,7 @@ fn composite_layer(l: &Layer, clipped: &[Layer], backdrop: &mut CmykBuffer, cx:
[0.0; 5]
};
}
recycle_mask(mv);
}
return;
}
+26 -10
View File
@@ -1,6 +1,6 @@
use super::content::{channel_weights, empty_in, recycle_buffer, render_content, restore_channels, scratch_buffer, surface_to_buffer};
use super::content::{channel_weights, empty_in, render_content, restore_channels, surface_to_buffer};
use super::ctx::Ctx;
use super::extents::{effects_frame, mask_k, mask_vals, shapeless_stroke_bounds};
use super::extents::{effects_frame, mask_k, mask_vals, recycle_mask, shapeless_stroke_bounds};
use super::fx_cache::effect_maps;
use super::{BlendMode, Buffer, Fill, Layer, LayerContent, Rect, Surface, advanced, blend, effects, psblend, shape_split};
@@ -339,6 +339,7 @@ pub(crate) fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mu
}
blend_span_fill(dst, &row, rect.x0, y, layer.blend, layer.opacity, layer.fill_opacity, gamma);
}
recycle_mask(mv);
}
pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) {
@@ -389,6 +390,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
[0.0; 4]
};
}
recycle_mask(mv);
}
// A Frame's stroke over the frame's content, at the group's opacity.
if let Some(stroke) = shape_split::frame_stroke(layer, cx.canvas, cx.depth) {
@@ -425,9 +427,10 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
if let LayerContent::Adjustment(adj) = &layer.content {
let mv = mask_vals(layer, rect, cx);
if mv.as_ref().is_some_and(|values| values.iter().all(|&value| opacity * value <= 0.0)) {
recycle_mask(mv);
return;
}
let mut adjusted = scratch_buffer(rect);
let mut adjusted = Buffer::transparent(rect);
adjusted.px.copy_from_slice(&backdrop.px);
cx.apply_adjustment(adj, &mut adjusted);
// Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result.
@@ -455,7 +458,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(k), layer.blend, fill),
}
}
recycle_buffer(adjusted);
recycle_mask(mv);
return;
}
@@ -469,6 +472,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
if let (Some(m), Some(b)) = (&hide, &before) {
advanced::apply_hiding_mask(backdrop, b, m);
}
recycle_mask(hide);
return;
}
if let Some((mut content, stroke, mask)) = shape_parts(layer, clipped, rect, cx) {
@@ -478,6 +482,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
p[3] *= mask_k(&mask, i);
}
blend_layer_into(backdrop, &content, layer, cx, 1.0);
recycle_mask(mask);
return;
}
if !matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_))
@@ -512,7 +517,6 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
let Some(mut content) = render_content(layer, rect, cx) else { return };
advanced::composite_clipped(clipped, &mut content, cx);
blend_layer_into(backdrop, &content, layer, cx, text_gamma(layer));
recycle_buffer(content);
}
/// A layer with effects (and its clipping group) onto `backdrop`.
@@ -521,7 +525,7 @@ fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buff
// Neighbourhoods are already captured by the full-region effect maps;
// content and effect application only need the output rectangle.
// A stroked shape's vector stroke stays above its clipped layers and interior effects.
let (mut content, vstroke) = match split_parts(layer, rect, cx) {
let (mut content, parts) = match split_parts(layer, rect, cx) {
Some((fill, stroke, mask)) => (fill, Some((stroke, mask))),
None => {
let Some(content) = render_content(layer, rect, cx) else { return };
@@ -529,9 +533,12 @@ fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buff
}
};
advanced::composite_clipped(clipped, &mut content, cx);
let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() });
let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() });
let maps = effect_maps(layer, rect, cx);
effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke);
if let Some((_, mask)) = parts {
recycle_mask(mask);
}
}
/// The coverage-mixing gamma of a layer: the text blending gamma
@@ -605,6 +612,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
p[c] += (bl[c] - p[c]) * k;
}
}
recycle_mask(mv);
return;
}
if effects::has_effects(layer) {
@@ -615,21 +623,28 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
let hide = advanced::hiding_mask(layer, rect, cx);
let src = advanced::effects_source(layer);
let layer = src.as_ref();
let (content, vstroke) = match split_parts(layer, rect, cx) {
let (content, parts) = match split_parts(layer, rect, cx) {
Some((fill, stroke, mask)) => (fill, Some((stroke, mask))),
None => {
let Some(content) = render_content(layer, rect, cx) else { return };
let Some(content) = render_content(layer, rect, cx) else {
recycle_mask(hide);
return;
};
(content, None)
}
};
let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() });
let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() });
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, rect, cx);
effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke);
if let Some((_, mask)) = parts {
recycle_mask(mask);
}
if let Some(m) = &hide {
let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() };
advanced::apply_hiding_mask(&mut opaque, &plain, m);
}
recycle_mask(hide);
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]];
@@ -689,6 +704,7 @@ fn blend_layer_into(backdrop: &mut Buffer, src: &Buffer, layer: &Layer, cx: &Ctx
let alpha = (s[3] / m).clamp(0.0, 1.0);
*b = psblend::composite_fill(mode, *b, [s[0], s[1], s[2], m], opacity, fill * alpha, gamma);
}
recycle_mask(mv);
}
/// [`blend_into_g`] for a layer's own `opacity` and `fill`: Fill is part of the blend for
+15 -48
View File
@@ -1,63 +1,29 @@
use super::composite::{adjustment_quantum, blend_into, composite_stack};
use super::ctx::Ctx;
use super::extents::{effect_shape, effect_source_bounds, mask_vals, shapeless_stroke_bounds, transparent_outside};
use super::extents::{effect_shape, effect_source_bounds, mask_vals, recycle_mask, shapeless_stroke_bounds, transparent_outside};
use super::fx_cache::effect_maps;
use super::{BlendMode, Buffer, Document, Fill, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern, shape_split};
/// Tile size for parallel rendering (tile results are independent).
pub const RENDER_TILE: i32 = 256;
// One tile of scratch per worker; nested rendering takes its own buffer.
thread_local! {
static SCRATCH: std::cell::RefCell<Vec<[f32; 4]>> = const { std::cell::RefCell::new(Vec::new()) };
}
pub(crate) fn scratch_buffer(rect: Rect) -> Buffer {
if rect.width() as usize * rect.height() as usize > (RENDER_TILE * RENDER_TILE) as usize {
return Buffer::transparent(rect);
}
let mut px = SCRATCH.with(|slot| std::mem::take(&mut *slot.borrow_mut()));
px.resize(rect.width() as usize * rect.height() as usize, [0.0; 4]);
Buffer { rect, px }
}
pub(crate) fn recycle_buffer(buf: Buffer) {
if buf.px.capacity() <= (RENDER_TILE * RENDER_TILE) as usize {
SCRATCH.with(|slot| {
let mut slot = slot.borrow_mut();
if slot.capacity() < buf.px.capacity() {
*slot = buf.px;
}
});
}
}
#[cfg(test)]
#[test]
fn scratch_reuse_preserves_pixels_and_bounds_retention() {
SCRATCH.with(|slot| slot.borrow_mut().clear());
let rect = Rect::new(-2, -3, 18, 11);
fn scratch_reuse_preserves_pixels() {
// 256 × 256 pixels of [f32; 4] (1 MiB): over `MIN_POOLED_BYTES`, so the pool keeps it.
let rect = Rect::new(-2, -3, 254, 253);
for fmt in [photocraft_color::PixelFormat::RGBA8, photocraft_color::PixelFormat::RGBA16, photocraft_color::PixelFormat::RGBA32F] {
let s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.8]);
let buf = surface_to_scratch(&s, rect);
let mut buf = surface_to_scratch(&s, rect);
assert_eq!(buf, surface_to_buffer(&s, rect));
let ptr = buf.px.as_ptr();
recycle_buffer(buf);
let reused = surface_to_scratch(&Surface::new(fmt), rect);
assert_eq!(reused.px.as_ptr(), ptr);
buf.px.fill([1.0; 4]);
// A dropped buffer goes back to the pool; the next one must come out cleared.
drop(buf);
let reused = Buffer::transparent(rect);
assert!(reused.px.iter().all(|p| p == &[0.0; 4]));
let nested = scratch_buffer(rect);
let nested = Buffer::transparent(rect);
assert_ne!(nested.px.as_ptr(), reused.px.as_ptr());
recycle_buffer(nested);
recycle_buffer(reused);
}
let cached = SCRATCH.with(|slot| slot.borrow().as_ptr());
let huge = scratch_buffer(Rect::new(0, 0, RENDER_TILE + 1, RENDER_TILE));
recycle_buffer(huge);
SCRATCH.with(|slot| {
assert_eq!(slot.borrow().as_ptr(), cached);
assert!(slot.borrow().capacity() <= (RENDER_TILE * RENDER_TILE) as usize);
});
}
/// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer.
@@ -93,6 +59,7 @@ pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buff
for (p, k) in buf.px.iter_mut().zip(&m) {
p[3] *= k;
}
recycle_mask(Some(m));
}
// A Frame's stroke lies over its masked content; the frame doesn't clip it.
if let Some(stroke) = shape_split::frame_stroke(layer, cx.canvas, cx.depth) {
@@ -125,13 +92,13 @@ pub fn stroke_frame(doc: &Document, layer: &Layer, st: &photocraft_doc::StrokeFx
}
pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer {
let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize];
s.read_rgba_into(rect, &mut px);
Buffer { rect, px }
let mut buf = Buffer::transparent(rect);
s.read_rgba_into(rect, &mut buf.px);
buf
}
fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer {
let mut buf = scratch_buffer(rect);
let mut buf = Buffer::transparent(rect);
s.read_rgba_into(rect, &mut buf.px);
buf
}
+10 -2
View File
@@ -134,6 +134,7 @@ pub(crate) fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec<f32> {
out[i] = v * mask_k(&mv, i);
}
}
recycle_mask(mv);
out
}
@@ -283,13 +284,13 @@ pub(crate) fn mask_vals(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Vec<f32>>
if masks::has_feather(layer)
&& let Some(s) = masks::combined_mask(layer, cx.canvas)
{
let mut v = Vec::new();
let mut v = photocraft_raster::scratch::take_cap(rect.width() as usize * rect.height() as usize);
s.read_region_into(rect, &mut v);
return Some(v);
}
let vector = layer.vector_mask.as_ref().map(|vm| cx.vector_masks.values(vm, rect));
let Some(m) = layer.mask.as_ref() else { return vector };
let mut v = Vec::new();
let mut v = photocraft_raster::scratch::take_cap(rect.width() as usize * rect.height() as usize);
m.values_into(rect, &mut v);
if let Some(vm) = vector {
for (a, b) in v.iter_mut().zip(vm) {
@@ -299,6 +300,13 @@ pub(crate) fn mask_vals(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Vec<f32>>
Some(v)
}
/// Hand a [`mask_vals`] result back to the scratch pool once its tile is done.
pub(crate) fn recycle_mask(m: Option<Vec<f32>>) {
if let Some(v) = m {
photocraft_raster::scratch::give(v);
}
}
#[inline]
pub(crate) fn mask_k(m: &Option<Vec<f32>>, i: usize) -> f32 {
m.as_ref().map_or(1.0, |v| v[i])
+24 -3
View File
@@ -84,18 +84,39 @@ pub use render::{
};
/// Straight-alpha RGBA float buffer covering a rectangle.
#[derive(Clone, Debug, PartialEq)]
///
/// The pixel storage comes from, and goes back to, the scratch pool.
#[derive(Debug, PartialEq)]
pub struct Buffer {
pub rect: Rect,
pub px: Vec<[f32; 4]>,
}
impl Clone for Buffer {
fn clone(&self) -> Self {
let mut px = photocraft_raster::scratch::take(self.px.len(), [0.0; 4]);
px.copy_from_slice(&self.px);
Self { rect: self.rect, px }
}
}
impl Drop for Buffer {
fn drop(&mut self) {
photocraft_raster::scratch::give(std::mem::take(&mut self.px));
}
}
impl Buffer {
pub fn transparent(rect: Rect) -> Self {
Self { rect, px: vec![[0.0; 4]; rect.width() as usize * rect.height() as usize] }
Self::filled(rect, [0.0; 4])
}
pub fn filled(rect: Rect, c: [f32; 4]) -> Self {
Self { rect, px: vec![c; rect.width() as usize * rect.height() as usize] }
Self { rect, px: photocraft_raster::scratch::take(rect.width() as usize * rect.height() as usize, c) }
}
/// The pixels, taken out of the buffer (it can't be destructured: it returns them to the
/// pool on drop).
pub fn into_px(mut self) -> Vec<[f32; 4]> {
std::mem::take(&mut self.px)
}
#[inline]
pub fn get(&self, x: i32, y: i32) -> [f32; 4] {
+2 -3
View File
@@ -229,14 +229,12 @@ pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::P
let mut s = Surface::new(fmt);
let n = fmt.channels();
let empty = s.default_pixel();
let mut data = Vec::new();
let _ = render_bands(doc, rect, 0, |band| -> Result<(), ()> {
let band = match background {
Some(bg) => band.over_background(bg),
None => band,
};
data.clear();
data.resize(band.px.len() * n, 0.0);
let mut data = photocraft_raster::scratch::take(band.px.len() * n, 0.0f32);
photocraft_color::convert::with_cmyk_space(space.as_ref(), || {
for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) {
if fmt.alpha && (p[3] <= 0.0 || p[3].is_nan()) && empty.len() == n {
@@ -247,6 +245,7 @@ pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::P
}
});
s.write_region(band.rect, &data);
photocraft_raster::scratch::give(data);
Ok(())
});
s.prune();
+1 -1
View File
@@ -115,7 +115,7 @@ fn soft_shape_matches_an_equal_vector_mask() {
fn soft_shape_keeps_its_stroke_crisp() {
let stroke = ShapeStroke { width: 4.0, paint: Fill::Solid(Color::rgb(1.0, 0.0, 0.0)), ..ShapeStroke::default() };
let d = shape_doc(SampleType::U8, 0.5, 10.0, Some(stroke));
let px = render(&d, Rect::new(0, 100, 200, 101)).px;
let px = render(&d, Rect::new(0, 100, 200, 101)).into_px();
// Centred 4 px stroke over x = 48..52: opaque red.
for x in [48, 49, 50, 51] {
let p = px[x];
+10 -10
View File
@@ -3001,7 +3001,7 @@ fn levels_steps_match_photoshop() {
let px = xs.iter().map(|&x| f32::from(x) / 255.0).map(|v| [v, v, v, 1.0]).collect();
let mut b = Buffer { rect: Rect::new(0, 0, xs.len() as i32, 1), px };
adjust::apply_depth(adj, &mut b, adjust::Transfer::Srgb, Some(SampleType::U8));
b.px
b.into_px()
};
let rgb = levels(ch(0.0, 213.0, 1.22, 48.0, 255.0), [ch(0.0, 255.0, 0.47, 0.0, 194.0), id.clone(), ch(61.0, 255.0, 0.47, 0.0, 213.0)]);
let xs = [2, 8, 9, 15, 16, 43, 45, 48, 55, 61, 72, 79, 84, 89, 90, 101, 106, 120, 150, 180, 200];
@@ -3364,7 +3364,7 @@ fn render_bands_cover_the_rect_in_order() {
render_bands(&d, r, 100, |b| -> Result<(), ()> {
assert_eq!((b.rect.x0, b.rect.x1), (r.x0, r.x1));
rows.push((b.rect.y0, b.rect.y1));
px.extend(b.px);
px.extend(b.into_px());
Ok(())
})
.unwrap();
@@ -4469,13 +4469,13 @@ fn dissolve_adjustment_resolves_opacity_to_binary_coverage() {
layer.blend = BlendMode::Dissolve;
layer.opacity = 0.5;
d.layers.push(layer);
let pixels = render(&d, d.bounds()).px;
let pixels = render(&d, d.bounds()).into_px();
let black = pixels.iter().filter(|p| p[0] < 0.01).count();
let white = pixels.iter().filter(|p| p[0] > 0.99).count();
assert!(black > 0 && white > 0, "Dissolve must select both original and adjusted pixels");
assert_eq!(black + white, pixels.len(), "no intermediate gray pixels");
d.layers.last_mut().unwrap().blend = BlendMode::Normal;
let continuous = render(&d, d.bounds()).px;
let continuous = render(&d, d.bounds()).into_px();
assert!(continuous.iter().all(|p| (p[0] - 0.5).abs() < E), "Normal remains continuously interpolated");
}
@@ -4486,14 +4486,14 @@ fn clipped_dissolve_fill_matches_opaque_unclipped_coverage() {
fill.blend = BlendMode::Dissolve;
fill.opacity = 0.5;
d.layers.push(fill);
let control = render(&d, d.bounds()).px;
let control = render(&d, d.bounds()).into_px();
d.layers.last_mut().unwrap().clipped = true;
let clipped = render(&d, d.bounds()).px;
let clipped = render(&d, d.bounds()).into_px();
assert_eq!(clipped, control, "clipping over a fully opaque base must preserve dissolve pixels");
let black = clipped.iter().filter(|p| p[0] < 0.01).count();
assert!(black > 0 && black < clipped.len());
d.layers.last_mut().unwrap().blend = BlendMode::Normal;
let continuous = render(&d, d.bounds()).px;
let continuous = render(&d, d.bounds()).into_px();
assert!(continuous.iter().all(|p| (p[0] - 0.5).abs() < E));
}
@@ -4504,17 +4504,17 @@ fn dissolve_color_overlay_preserves_binary_layer_coverage() {
layer.blend = BlendMode::Dissolve;
layer.opacity = 0.5;
d.layers.push(layer);
let control = render(&d, d.bounds()).px;
let control = render(&d, d.bounds()).into_px();
d.layers
.last_mut()
.unwrap()
.effects
.items
.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::BLACK });
let styled = render(&d, d.bounds()).px;
let styled = render(&d, d.bounds()).into_px();
assert_eq!(styled, control, "an identity overlay should not turn dissolve pixels gray");
d.layers.last_mut().unwrap().blend = BlendMode::Normal;
let continuous = render(&d, d.bounds()).px;
let continuous = render(&d, d.bounds()).into_px();
assert!(continuous.iter().all(|p| (p[0] - 0.5).abs() < E));
}
+27
View File
@@ -0,0 +1,27 @@
use photocraft_compose::Buffer;
use photocraft_geom::Rect;
use photocraft_raster::scratch;
/// Restores idle release even when an assertion fails.
struct IdleReleaseOff;
impl Drop for IdleReleaseOff {
fn drop(&mut self) {
scratch::release();
scratch::set_idle_release(true);
}
}
/// Runs in its own binary so other compositor tests cannot consume the pooled allocation.
#[test]
fn dropped_buffer_storage_is_reused() {
scratch::set_idle_release(false);
let _idle = IdleReleaseOff;
scratch::release();
let rect = Rect::from_xywh(0, 0, 256, 256);
let buf = Buffer::transparent(rect);
let ptr = buf.px.as_ptr();
drop(buf);
let reused = Buffer::transparent(rect);
assert_eq!(reused.px.as_ptr(), ptr);
assert!(reused.px.iter().all(|p| *p == [0.0; 4]));
}
+11
View File
@@ -318,6 +318,17 @@ pub enum LiveShape {
to: [f64; 2],
weight: f64,
},
/// Editable vector arrow with parameters preserved by serde in the project document.
ArrowLine {
from: [f64; 2],
to: [f64; 2],
weight: f64,
start: bool,
end: bool,
width: f64,
length: f64,
concavity: f64,
},
}
/// A shape layer: a filled and/or stroked path.
+1 -1
View File
@@ -25,7 +25,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let path = std::env::args().nth(1).ok_or("provide a local image path")?;
let bytes = photocraft_format::read::read_file(std::path::Path::new(&path))?;
let doc = photocraft_io::import(&path, &bytes)?.document;
let px = photocraft_compose::flatten(&doc).px;
let px = photocraft_compose::flatten(&doc).into_px();
println!("{}", json!({"width":doc.size.width,"height":doc.size.height,"preview_factor":1}));
for count in [8usize, 16, 32, 64, 128, 256] {
for run in 0..4 {
+18 -4
View File
@@ -106,6 +106,12 @@ pub struct ActionState {
/// Steps run by the current top-level script and everything it calls.
#[serde(skip)]
pub script_steps: u64,
/// Sets made with New Set (`actions.newSet`), or loaded from an `.atn` with no actions, that
/// hold no action yet: the Actions panel shows them as empty folders. Save Actions… writes one
/// to an `.atn` as Photoshop does, but the preset store keeps sets through their actions, so
/// an empty one isn't remembered past the session.
#[serde(skip)]
pub sets: Vec<String>,
/// Bumped whenever `list` changes, so the preset store can skip unchanged writes.
#[serde(skip)]
pub rev: u64,
@@ -333,7 +339,7 @@ fn from_step(p: &Value, len: usize) -> Result<usize> {
fn list(s: &mut Session, _p: &Value) -> Result<Value> {
let actions: Vec<Value> = s.actions.list.iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect();
let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.get(i).map(|a| a.name.clone()));
Ok(json!({"actions": actions, "recording": recording}))
Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording}))
}
fn get(s: &mut Session, p: &Value) -> Result<Value> {
@@ -366,7 +372,15 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {
if s.actions.list.iter().any(|action| action.name == name) {
return Err(bad("actions.record", "an action with this name already exists"));
}
s.actions.list.push(Action::new(name, Vec::new()));
let set = match p.get("set") {
None | Some(Value::Null) => None,
// An existing set, empty ones included, keeps its exact name (an older actions.json or
// a `.atn` may pad it); a new one is trimmed.
Some(Value::String(n)) if crate::actions_edit_cmds::set_names(s).contains(n) => Some(n.clone()),
Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()),
Some(_) => return Err(bad("actions.record", "\"set\" must be a set name or null")),
};
s.actions.list.push(Action { set, ..Action::new(name, Vec::new()) });
s.actions.touch();
s.actions.list.len() - 1
};
@@ -746,7 +760,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "List Actions",
menu: &[],
shortcut: None,
params: "{} → {actions:[{name, steps:count, set:name|null}], recording:name|null}",
params: "{} → {actions:[{name, steps:count, set:name|null}], sets:[name…] (every set in panel order, empty ones too), recording:name|null}",
enabled: always,
run: list,
journal: false,
@@ -766,7 +780,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Record Action",
menu: &[],
shortcut: None,
params: r##"{"name":str? (new action, default "Action N")} or {"action":name|index} (append) → {action, index}"##,
params: r##"{"name":str? (new action, default "Action N"),"set":name? (the set it goes in, as New Action records into the selected set)} or {"action":name|index} (append) → {action, index}"##,
enabled: always,
run: record,
journal: false,
@@ -1176,3 +1176,35 @@ fn arrange_that_cannot_move_is_a_noop_in_playback() {
assert_eq!(played["ran"], 0, "{played}");
assert!(played["failed"].is_object(), "{played}");
}
/// #10459 review: recording into an existing set keeps that set's exact name, even one with
/// surrounding spaces (from an older actions.json); a new set name is trimmed.
#[test]
fn record_keeps_an_existing_sets_exact_name() {
let mut s = Session::new();
s.actions.list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) });
s.execute("actions.record", json!({"name": "New", "set": " Web "})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
let set_of = |s: &Session, n: &str| s.actions.list.iter().find(|a| a.name == n).and_then(|a| a.set.clone());
assert_eq!(set_of(&s, "New").as_deref(), Some(" Web "), "the existing set");
s.execute("actions.record", json!({"name": "Fresh", "set": " Print "})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
assert_eq!(set_of(&s, "Fresh").as_deref(), Some("Print"), "a new set is trimmed");
}
/// CodeRabbit review on #10459: an empty set loaded from a `.atn` (or made by New Set) keeps its
/// exact name too, so the first action recorded into it lands in that folder and saves with it.
#[test]
fn record_keeps_an_empty_loaded_sets_exact_name() {
let mut src = Session::new();
src.actions.sets.push(" Web ".into());
let saved = src.execute("actions.save", json!({"set": " Web "})).unwrap();
let mut s = Session::new();
assert_eq!(s.execute("actions.load", json!({"data": saved["data"]})).unwrap()["set"], " Web ");
s.execute("actions.record", json!({"name": "First", "set": " Web "})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
let set = s.actions.list.iter().find(|a| a.name == "First").and_then(|a| a.set.clone());
assert_eq!(set.as_deref(), Some(" Web "));
assert_eq!(crate::actions_edit_cmds::set_names(&s), [" Web "], "one folder, not a trimmed second one");
assert_eq!(s.execute("actions.save", json!({"set": " Web "})).unwrap()["actions"], json!(["First"]));
}
+61 -1
View File
@@ -1,6 +1,7 @@
//! Editing an action's steps and its set, as the Actions panel does beyond recording:
//! `actions.insert` (Photoshop's Insert Stop… and Insert Menu Item…), `actions.dialog` (the
//! panel's dialog toggle column) and `actions.assignSet` (which set folder an action sits in).
//! panel's dialog toggle column), `actions.assignSet` (which set folder an action sits in) and
//! `actions.newSet` (New Set…, an empty set folder).
//!
//! All three refuse to run during playback, commit pending recorded steps first, and keep the
//! per-step flag sets (`disabled`, `dialogs`) in step with the moved indices, like
@@ -126,6 +127,33 @@ fn assign_set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(result)
}
/// Every set name, in the Actions panel's order: the sets of the actions as they first appear,
/// then the empty ones New Set made.
pub fn set_names(s: &Session) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
s.actions.list.iter().filter_map(|a| a.set.as_ref()).chain(&s.actions.sets).filter(|set| seen.insert(set.as_str())).cloned().collect()
}
/// New Set…: an empty set folder, named `name` or "Set N" (the first number no set has), that New
/// Action can record into.
fn new_set(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.newSet";
not_playing(s, cmd)?;
let names = set_names(s);
let name = match p.get("name") {
None | Some(Value::Null) => (1u32..).map(|n| format!("Set {n}")).find(|n| !names.contains(n)).ok_or_else(|| bad(cmd, "no free set name"))?,
Some(Value::String(n)) if !n.trim().is_empty() => n.trim().to_string(),
Some(Value::String(_)) => return Err(bad(cmd, "`name` is empty")),
Some(_) => return Err(bad(cmd, "`name` must be a string")),
};
if names.contains(&name) {
return Err(bad(cmd, format!("a set named `{name}` already exists")));
}
s.actions.sets.push(name.clone());
s.actions.touch();
Ok(json!({"set": name}))
}
/// The conditions of Photoshop's Insert Conditional, by their string ids.
pub const CONDITIONS: &[&str] = &[
"always",
@@ -285,6 +313,16 @@ pub fn specs() -> Vec<CommandSpec> {
run: assign_set,
journal: false,
},
CommandSpec {
id: "actions.newSet",
label: "New Set",
menu: &[],
shortcut: None,
params: r##"{"name":str? (default "Set N")} → {set}. An empty set folder in the Actions panel, as Photoshop's New Set… makes; New Action records into the selected set (actions.record's `set`). Save Actions… (actions.save's `set`) writes it even while empty; it is remembered between sessions once it holds an action."##,
enabled: always,
run: new_set,
journal: false,
},
]
}
@@ -412,6 +450,28 @@ mod tests {
}
}
#[test]
fn new_set_makes_an_empty_folder_that_new_actions_record_into() {
let mut s = session_with(&["select.all"]);
s.execute("actions.assignSet", json!({"action": "A", "set": "Set 1"})).unwrap();
// Numbered past the sets the actions already have.
assert_eq!(s.execute("actions.newSet", json!({})).unwrap()["set"], "Set 2");
assert_eq!(s.execute("actions.newSet", json!({"name": " Retouch "})).unwrap()["set"], "Retouch");
assert_eq!(set_names(&s), ["Set 1", "Set 2", "Retouch"]);
// CodeRabbit on batch 11: Actions List names the empty sets too, so an agent can find them.
assert_eq!(s.execute("actions.list", json!({})).unwrap()["sets"], json!(["Set 1", "Set 2", "Retouch"]));
assert!(s.execute("actions.newSet", json!({"name": "Set 1"})).is_err(), "a set an action is in");
assert!(s.execute("actions.newSet", json!({"name": "Retouch"})).is_err(), "an empty set");
assert!(s.execute("actions.newSet", json!({"name": " "})).is_err());
// New Action into the empty set.
let r = s.execute("actions.record", json!({"set": "Retouch"})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
let i = r["index"].as_u64().unwrap() as usize;
assert_eq!(s.actions.list[i].set.as_deref(), Some("Retouch"));
assert_eq!(set_names(&s), ["Set 1", "Retouch", "Set 2"], "Retouch now holds an action");
assert!(s.execute("actions.record", json!({"set": 3})).is_err());
}
#[test]
fn assign_set_moves_an_action_between_folders() {
let mut s = session_with(&["select.all"]);
+3 -3
View File
@@ -459,9 +459,9 @@ fn stats_pixels(doc: &Document, layer: Option<u64>, use_selection: bool) -> Resu
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
photocraft_compose::render_layer(l, area).into_px()
}
None => photocraft_compose::flatten(doc).px,
None => photocraft_compose::flatten(doc).into_px(),
};
let mask = doc.selection.as_ref().filter(|_| use_selection).map(|sel| photocraft_algo::selection::mask_from_surface(Some(sel), area));
Ok((px, mask))
@@ -521,7 +521,7 @@ fn hdr_toning(s: &mut Session, p: &Value) -> Result<Value> {
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;
let mut px = buf.into_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();
+1 -1
View File
@@ -480,7 +480,7 @@ fn smart_session() -> Session {
}
fn flatten(s: &Session) -> Vec<[f32; 4]> {
photocraft_compose::flatten(doc(s)).px
photocraft_compose::flatten(doc(s)).into_px()
}
fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 {
+3 -3
View File
@@ -40,7 +40,7 @@ mod tables;
#[cfg(test)]
use adjustments::{levels_from, selective_from};
pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, parse_function_key};
pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, import_with_encoding, parse_function_key};
#[cfg(test)]
use convert::{MAX_NAME_CHARS, export_item, normalise};
#[cfg(test)]
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Load Actions…",
menu: &[],
shortcut: None,
params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name? (override the file's set name),"replace":bool=true (replace the actions of a set of the same name)} → {set, actions:[names], steps, unsupported:[{action, step, event, name}], functionKeys:[{action, key}], warnings}. Photoshop steps PhotoCraft cannot play become actions.photoshopStep steps (kept for Save Actions; they fail at playback with the step's name); tool selections and other steps with no document effect are imported switched off. Layer references by name replay in any document."##,
params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name? (override the file's set name),"replace":bool=true (replace the actions of a set of the same name),"encoding":"auto"|label="auto" (the encoding of 8-bit step names: shift_jis, gbk, big5, euc-kr, windows-1252, macintosh…; auto works it out)} → {set, actions:[names], steps, unsupported:[{action, step, event, name}], functionKeys:[{action, key}], warnings, encoding}. Photoshop steps PhotoCraft cannot play become actions.photoshopStep steps (kept for Save Actions; they fail at playback with the step's name); tool selections and other steps with no document effect are imported switched off. Layer references by name replay in any document."##,
enabled: always,
run: load,
journal: false,
@@ -112,7 +112,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Save Actions…",
menu: &[],
shortcut: None,
params: r##"{"path":".atn file"? (else the bytes come back as base64 `data`),"set":name? (that set's actions; default: every action, as the set "PhotoCraft Actions"),"action":name|index? (one action),"skipUnsupported":bool=false (leave out steps with no Photoshop equivalent instead of failing)} → {set, actions:[names], steps, bytes, skipped:[{action, step, id}], path|data}"##,
params: r##"{"path":".atn file"? (else the bytes come back as base64 `data`),"set":name? (that set's actions, none for an empty New Set set; default: every action, as the set "PhotoCraft Actions"),"action":name|index? (one action),"skipUnsupported":bool=false (leave out steps with no Photoshop equivalent instead of failing)} → {set, actions:[names], steps, bytes, skipped:[{action, step, id}], path|data}"##,
enabled: always,
run: save,
journal: false,
+30 -2
View File
@@ -66,6 +66,20 @@ fn levels_entry(chan: Option<&str>, p: &Value) -> Descriptor {
e
}
/// Whether the Levels settings in `p` (the master curve and every channel object) name both ends
/// of each range they touch, or neither. `levels_entry` writes a whole `Inpt` or `Otpt` pair and
/// fills the end a partial edit left out with 0 or 255, so replaying `inBlack: 31` alone would
/// also reset a retained Input White (#8530). A value given in a shape the writer can't read (a
/// text endpoint, a channel that isn't an object) would be left out, so it isn't complete either.
pub(super) fn levels_complete(p: &Value) -> bool {
let shaped =
|v: &Value| ["inBlack", "inWhite", "gamma", "outBlack", "outWhite"].iter().all(|k| v.get(*k).is_none_or(|x| x.is_null() || jnum(v, k).is_some()));
let pairs_whole =
|v: &Value| [("inBlack", "inWhite"), ("outBlack", "outWhite")].iter().all(|(low, high)| jnum(v, low).is_some() == jnum(v, high).is_some());
let whole = |v: &Value| shaped(v) && pairs_whole(v);
whole(p) && CHANNELS.iter().filter_map(|(_, k)| p.get(*k).filter(|v| !v.is_null())).all(|v| v.is_object() && whole(v))
}
pub(super) fn levels_to(p: &Value) -> Option<Descriptor> {
let mut entries = vec![D::Descriptor(levels_entry(None, p))];
for (_, k) in CHANNELS {
@@ -395,6 +409,18 @@ macro_rules! adj_fields {
};
}
const VIBRANCE: &[F] = &[F("vibrance", "vibrance", Kind::Long), F("Strt", "saturation", Kind::Long)];
/// Vibrance. Photoshop's recording also carries `temperature` and `tint`, which our Vibrance has
/// no params for: with either one non-zero the step stays a kept Photoshop step (saved back
/// unchanged) instead of playing and saving without them.
fn vibrance_from(d: &Descriptor) -> Option<Value> {
if ["temperature", "tint"].iter().any(|k| get_num(d, k).is_some_and(|v| v != 0.0)) {
return None;
}
fields_from(d, VIBRANCE).map(Value::Object)
}
const ADJUSTMENTS: &[Adjustment] = &[
Adjustment { class: "Lvls", suffix: "levels", from: levels_from, to: levels_to },
Adjustment { class: "Crvs", suffix: "curves", from: curves_from, to: curves_to },
@@ -404,7 +430,7 @@ const ADJUSTMENTS: &[Adjustment] = &[
adj_fields!("Pstr", "posterize", &[F("Lvls", "levels", Kind::Long)]),
adj_fields!("Invr", "invert", &[]),
Adjustment { class: "ClrB", suffix: "colorBalance", from: color_balance_from, to: color_balance_to },
adj_fields!("Vbrn", "vibrance", &[F("vibrance", "vibrance", Kind::Long), F("Strt", "saturation", Kind::Long)]),
Adjustment { class: "vibrance", suffix: "vibrance", from: vibrance_from, to: |p| fields_to(p, VIBRANCE, desc("vibrance")) },
adj_fields!("Exps", "exposure", &[F("Exps", "exposure", Kind::Dbl), F("Ofst", "offset", Kind::Dbl), F("gammaCorrection", "gamma", Kind::Dbl)]),
Adjustment { class: "PhtF", suffix: "photoFilter", from: |d| fields_from(d, PHOTO_FILTER_FIELDS).map(Value::Object), to: photo_filter_to },
adj_fields!("BanW", "blackWhite", BW),
@@ -417,7 +443,9 @@ const ADJUSTMENTS: &[Adjustment] = &[
/// Photoshop (#8481): a Make whose Black & White type is `BlnW` fails ("the command Make is not
/// currently available"), `BanW` runs. Import keeps accepting them so actions saved before still
/// load; export never writes them.
const LEGACY_CLASSES: &[(&str, &str)] = &[("BlnW", "BanW")];
/// `Vbrn` is a code PhotoCraft invented for Vibrance: Photoshop records the class by its string id
/// `vibrance` (#8534), and refuses the `Vbrn` code (#8383).
const LEGACY_CLASSES: &[(&str, &str)] = &[("BlnW", "BanW"), ("Vbrn", "vibrance")];
/// The adjustment with Photoshop class `c`, or the one an old PhotoCraft class stands for.
pub(super) fn adjustment_by_class(c: &str) -> Option<&'static Adjustment> {
+19 -9
View File
@@ -23,15 +23,18 @@ pub struct Imported {
pub function_keys: Vec<(String, String)>,
pub unsupported: Vec<Unsupported>,
pub warnings: Vec<String>,
/// The encoding the file's 8-bit step names were read in (`"GBK"`, `"Shift_JIS"`,
/// `"macintosh"`…); `None` when none needed one.
pub encoding: Option<String>,
}
fn photoshop_step(item: &AtnItem) -> (String, Value) {
fn photoshop_step(item: &AtnItem, label: String) -> (String, Value) {
let descriptor = item.descriptor.as_ref().map(|d| photocraft_paint::tile::b64_encode(&d.to_bytes()));
let event_kind = match &item.event {
AtnEvent::Code(_) => "code",
AtnEvent::Name(_) => "name",
};
(PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": item.label(), "descriptor": descriptor}))
(PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": label, "descriptor": descriptor}))
}
/// Integral floats become integers (`2.0` → `2`), as the commands' own docs and recordings
@@ -61,7 +64,7 @@ pub(super) fn clip_name(s: &str) -> String {
s.chars().take(MAX_NAME_CHARS).collect()
}
fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec<Unsupported>) -> Action {
fn convert_action(file: &AtnFile, a: &AtnAction, set: &str, unsupported: &mut Vec<Unsupported>) -> Action {
let name = clip_name(&a.name.to_string_lossy());
let mut action = Action::new(name.clone(), Vec::new());
action.set = Some(clip_name(set));
@@ -74,8 +77,9 @@ fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec<Unsupported>)
let (new_steps, enabled) = match mapped {
Mapped::Steps(s) => (s, item.enabled),
Mapped::Unsupported { harmless } => {
unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: item.label() });
(vec![photoshop_step(item)], item.enabled && !harmless)
let label = file.item_label(item);
unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: label.clone() });
(vec![photoshop_step(item, label)], item.enabled && !harmless)
}
};
for mut s in new_steps {
@@ -96,12 +100,18 @@ fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec<Unsupported>)
/// Convert a `.atn` file. Fails only when the file is unreadable: every step imports, as a
/// command or as a kept Photoshop step.
pub fn import(bytes: &[u8]) -> std::result::Result<Imported, String> {
let file = atn::parse(bytes).map_err(|e| e.to_string())?;
import_with_encoding(bytes, None)
}
/// [`import`], reading 8-bit step names in `encoding` (a label such as `"shift_jis"` or
/// `"gbk"`) instead of working it out. An unknown label fails.
pub fn import_with_encoding(bytes: &[u8], encoding: Option<&str>) -> std::result::Result<Imported, String> {
let file = atn::parse_with_encoding(bytes, encoding).map_err(|e| e.to_string())?;
let set = file.name.to_string_lossy();
let set = if set.trim().is_empty() { DEFAULT_SET.to_string() } else { clip_name(&set) };
let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), ..Default::default() };
let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), encoding: file.encoding.clone(), ..Default::default() };
for a in &file.actions {
let action = convert_action(a, &set, &mut out.unsupported);
let action = convert_action(&file, a, &set, &mut out.unsupported);
if a.function_key > 0 {
out.function_keys.push((action.name.clone(), function_key_name(a.function_key, a.shift, a.command)));
}
@@ -205,7 +215,7 @@ pub fn export(
skip_unsupported: bool,
) -> std::result::Result<(Vec<u8>, Vec<Skipped>), String> {
let mut skipped = Vec::new();
let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new() };
let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new(), ..Default::default() };
for a in actions {
let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() };
if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) {
+6 -3
View File
@@ -8,8 +8,8 @@ use super::steps_doc::{
place_from, place_to, profile_from, profile_to, purge_from, purge_to, reset_from, reset_to, save_from, save_to, stop_from, stop_to,
};
use super::steps_image::{
GALLERY_IDS, REFINE_EDGE, RIPPLE_SIZE, SMART_BRUSH, apply_image_from, apply_image_to, color_range_from, color_range_to, gallery_from, gallery_to,
has_refine_strokes, radial_blur_from, radial_blur_to, refine_edge_to, transform_from, transform_to,
GALLERY_IDS, REFINE_EDGE, RIPPLE_SIZE, SMART_BRUSH, apply_image_from, apply_image_to, camera_raw_from, camera_raw_to, color_range_from, color_range_to,
gallery_from, gallery_to, has_refine_strokes, radial_blur_from, radial_blur_to, refine_edge_to, transform_from, transform_to,
};
use super::steps_layer::{
STROKE, apply_comp_from, apply_comp_to, clear_from, clear_to, delete_from, delete_to, duplicate_from, duplicate_to, fill_from, fill_to, flip_from, flip_to,
@@ -251,6 +251,9 @@ pub(super) const EVENTS: &[Event] = &[
ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::ExactLong)]),
ev!("Dfs ", "diffuse", "Diffuse", "filter.stylize.diffuse", &[F("Md ", "mode", Kind::Enum("DfsM", DIFFUSE_MODE)), F("FlRs", "seed", Kind::Long)]),
Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to },
// What Photoshop needs in a written step (process version, the full settings set) is
// unverified, so only an imported step saves back, as its recorded descriptor while unedited.
Event { code: "", name: "Adobe Camera Raw Filter", label: "Camera Raw Filter", ids: &[crate::lens_cmds::RAW], from: camera_raw_from, to: camera_raw_to },
// Adjustments (Image › Adjustments).
Event {
code: "",
@@ -275,7 +278,7 @@ pub(super) const EVENTS: &[Event] = &[
adjustment_event!("Pstr", "Pstr", "posterize", "Posterize"),
adjustment_event!("Invr", "Invr", "invert", "Invert"),
adjustment_event!("ClrB", "ClrB", "colorBalance", "Color Balance"),
adjustment_event!("Vbrn", "Vbrn", "vibrance", "Vibrance"),
adjustment_event!("Vbrn", "vibrance", "vibrance", "Vibrance"),
adjustment_event!("Exps", "Exps", "exposure", "Exposure"),
// Photoshop runs Photo Filter by name only: `PhtF` is the class, not an event (#8301).
adjustment_event!("", "PhtF", "photoFilter", "Photo Filter"),
+22 -6
View File
@@ -1,4 +1,4 @@
use super::convert::{UniqueNames, export, import};
use super::convert::{UniqueNames, export, import_with_encoding};
use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json};
pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
@@ -6,8 +6,14 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
if s.actions.recording.is_some() || s.actions.playing > 0 {
return Err(bad(cmd, "stop recording or playing before loading actions"));
}
let encoding = match p.get("encoding") {
None | Some(Value::Null) => None,
Some(Value::String(e)) if e == "auto" => None,
Some(Value::String(e)) if !e.is_empty() => Some(e.as_str()),
Some(_) => return Err(bad(cmd, "encoding must be \"auto\" or a label such as shift_jis, gbk, big5, euc-kr, windows-1252, macintosh")),
};
let (bytes, _) = crate::preset_import_cmds::file_bytes(p, cmd, ".atn file")?;
let mut imp = import(&bytes).map_err(|e| bad(cmd, e))?;
let mut imp = import_with_encoding(&bytes, encoding).map_err(|e| bad(cmd, e))?;
match p.get("set") {
None | Some(Value::Null) => {}
Some(Value::String(n)) if !n.trim().is_empty() => {
@@ -59,6 +65,11 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
}
}
s.actions.list.extend(added);
// A set saved with no actions (Photoshop saves an empty set) is an empty folder, like one New
// Set made.
if !s.actions.list.iter().any(|a| a.set.as_deref() == Some(imp.set.as_str())) && !s.actions.sets.contains(&imp.set) {
s.actions.sets.push(imp.set.clone());
}
let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect();
if !keys.is_empty() {
s.edit_prefs(|prefs| {
@@ -77,6 +88,7 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
"unsupported": imp.unsupported,
"functionKeys": keys.iter().map(|(n, k)| json!({"action": n, "key": k})).collect::<Vec<_>>(),
"warnings": imp.warnings,
"encoding": imp.encoding.as_deref().unwrap_or("UTF-8"),
}))
}
@@ -90,6 +102,9 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
};
let set_param = match p.get("set") {
None | Some(Value::Null) => None,
// A set is found by its exact name, as `actions.record` finds it: one loaded from a
// Photoshop file or an older actions.json may have surrounding spaces. Others are trimmed.
Some(Value::String(n)) if crate::actions_edit_cmds::set_names(s).contains(n) => Some(n.clone()),
Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()),
Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")),
};
@@ -99,16 +114,17 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
(set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a])
} else if let Some(set) = set_param {
let list: Vec<&Action> = s.actions.list.iter().filter(|a| a.set.as_deref() == Some(set.as_str())).collect();
if list.is_empty() {
// An empty set New Set made is written with no actions, as Photoshop saves one.
if list.is_empty() && !s.actions.sets.contains(&set) {
return Err(bad(cmd, format!("no actions in a set named `{set}`")));
}
(set, list)
} else {
if s.actions.list.is_empty() {
return Err(bad(cmd, "there are no actions to save"));
}
(DEFAULT_SET.to_string(), s.actions.list.iter().collect())
};
if actions.is_empty() {
return Err(bad(cmd, "there are no actions to save"));
}
let names: Vec<String> = actions.iter().map(|a| a.name.clone()).collect();
let keys: Vec<(String, String)> =
s.prefs().shortcuts.iter().filter_map(|(k, v)| k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX).map(|n| (n.to_string(), v.clone()))).collect();
+189 -2
View File
@@ -1,6 +1,6 @@
use super::descriptors::{
PX, Target, ang, class, code, desc, enm, get_bool, get_enum, get_num, get_obj, get_ref, jbool, jnum, jstr, layer_ref, layer_target, long, pct, px,
ref_class, target, trimmed,
PX, Target, ang, class, code, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, get_ref, jbool, jnum, jstr, layer_ref, layer_target, long, num,
pct, px, ref_class, target, trimmed,
};
use super::events::pixel_target;
use super::fields::{F, Kind, Mapped, fields_from, fields_to, step};
@@ -249,6 +249,193 @@ pub(super) fn apply_image_to(_: &str, p: &Value) -> Option<Descriptor> {
pub(super) const RIPPLE_SIZE: &[(&str, &str)] = &[("Sml", "small"), ("Mdm", "medium"), ("Lrg", "large")];
/// Camera Raw Filter's scalar sliders. Every one is an integer in recorded steps except `Ex12`
/// and `ShpR` (doubles); the layout is from 62 recorded steps in 14 sets (#6745) and matches the
/// verified PSD Smart Filter mapping (`photocraft-io`'s `camera_raw_map.rs`).
const CAMERA_RAW: &[F] = &[
F("Temp", "temperature", Kind::Long),
F("Tint", "tint", Kind::Long),
F("Ex12", "exposure", Kind::Dbl),
F("Cr12", "contrast", Kind::Long),
F("Hi12", "highlights", Kind::Long),
F("Sh12", "shadows", Kind::Long),
F("Wh12", "whites", Kind::Long),
F("Bk12", "blacks", Kind::Long),
F("CrTx", "texture", Kind::Long),
F("Cl12", "clarity", Kind::Long),
F("Dhze", "dehaze", Kind::Long),
F("Vibr", "vibrance", Kind::Long),
F("Strt", "saturation", Kind::Long),
F("PC_H", "curveHighlights", Kind::Long),
F("PC_L", "curveLights", Kind::Long),
F("PC_D", "curveDarks", Kind::Long),
F("PC_S", "curveShadows", Kind::Long),
F("CgBl", "gradeBlending", Kind::Long),
F("STB ", "gradeBalance", Kind::Long),
F("Shrp", "sharpenAmount", Kind::Long),
F("ShpR", "sharpenRadius", Kind::Dbl),
F("ShpD", "sharpenDetail", Kind::Long),
F("ShpM", "sharpenMasking", Kind::Long),
F("LNR ", "noiseLuminance", Kind::Long),
F("LNRD", "noiseLuminanceDetail", Kind::Long),
F("CNR ", "noiseColor", Kind::Long),
F("CNRD", "noiseColorDetail", Kind::Long),
F("GRNA", "grainAmount", Kind::Long),
F("GRNS", "grainSize", Kind::Long),
F("GRNF", "grainRoughness", Kind::Long),
F("PCVA", "vignetteAmount", Kind::Long),
F("PCVM", "vignetteMidpoint", Kind::Long),
F("PCVR", "vignetteRoundness", Kind::Long),
F("PCVF", "vignetteFeather", Kind::Long),
F("PCVH", "vignetteHighlights", Kind::Long),
];
/// The range a Camera Raw Filter descriptor key's value can take, as `filter.cameraRaw` and the
/// PSD Smart Filter mapping (`photocraft-io`'s `camera_raw_map.rs`) accept it.
fn camera_raw_range(key: &str) -> std::ops::RangeInclusive<f64> {
match key {
"Ex12" => -5.0..=5.0,
"ShpR" => 0.5..=3.0,
"Shrp" => 0.0..=150.0,
"STSH" | "STHH" | "CgMH" | "CgGH" => 0.0..=360.0,
"PC_1" | "PC_2" | "PC_3" | "ShpD" | "ShpM" | "LNR " | "LNRD" | "CNR " | "CNRD" | "STSS" | "STHS" | "CgMS" | "CgGS" | "CgBl" | "GRNA" | "GRNS"
| "GRNF" | "PCVM" | "PCVF" | "PCVH" => 0.0..=100.0,
_ => -100.0..=100.0,
}
}
/// The hidden param an imported Camera Raw Filter step keeps its recorded descriptor in, so
/// Save Actions writes the step back unchanged while its settings are the ones it imported with.
const CAMERA_RAW_DESCRIPTOR: &str = "__atnDescriptor";
/// The colour grading wheels' keys, the tone curve splits and the vignette style.
const CAMERA_RAW_GRADES: &[&str] =
&["STSH", "STSS", "CgSL", "CgMH", "CgMS", "CgML", "STHH", "STHS", "CgHL", "CgGH", "CgGS", "CgGL", "PC_1", "PC_2", "PC_3", "PCVS"];
/// A recorded Camera Raw Filter step (`Adobe Camera Raw Filter`) as `filter.cameraRaw` (#6745).
/// Settings the command has no counterpart for refuse the step rather than replaying a different
/// look: the Calibration panel, a white balance other than Custom, the controls the PSD mapping
/// keeps only at their neutral values, and any key outside this table (lens, geometry, profile,
/// masks…), as the PSD mapping's `known_key` does, and a process version the PSD mapping hasn't
/// verified (Camera Raw renders each version differently).
pub(super) fn camera_raw_from(d: &Descriptor) -> Mapped {
const CALIBRATION: &[&str] = &["RHue", "RSat", "GHue", "GSat", "BHue", "BSat", "BlkB"];
const NEUTRAL_ONLY: &[(&str, f64)] =
&[("LNRC", 0.0), ("CNRS", 50.0), ("MDis", 0.0), ("VigA", 0.0), ("VigM", 50.0), ("crfs", 100.0), ("TMMs", 0.0), ("PGTM", 0.0), ("RGBt", 0.0)];
const OTHER: &[&str] = &["CrVe", "PrVe", "PrVN", "WBal", "Crv ", "CrvR", "CrvG", "CrvB"];
let known = |k: &str| {
(k.len() == 4 && ["HA_", "SA_", "LA_"].iter().any(|p| k.starts_with(p)) && ["R", "O", "Y", "G", "A", "B", "P", "M"].iter().any(|c| k.ends_with(c)))
|| CAMERA_RAW.iter().any(|F(f, ..)| *f == k)
|| CAMERA_RAW_GRADES.contains(&k)
|| OTHER.contains(&k)
|| CALIBRATION.contains(&k)
|| NEUTRAL_ONLY.iter().any(|(n, _)| *n == k)
};
// An empty step (no descriptor) would play as a no-op, and a key the table doesn't know may
// be active processing (lens, geometry, profile, masks) that playback would leave out.
if d.items.is_empty() || d.items.iter().any(|(k, _)| !std::str::from_utf8(k.as_bytes()).is_ok_and(known)) {
return Mapped::Unsupported { harmless: false };
}
let version = (get_num(d, "PrVN"), get_num(d, "PrVe"));
let verified = [(5.0, 184_549_376.0), (6.0, 251_920_384.0)].iter().any(|(n, v)| version == (Some(*n), Some(*v)));
if !verified || !matches!(d.get("CrVe"), Some(D::Text(_))) {
return Mapped::Unsupported { harmless: false };
}
let active = |k: &str, neutral: f64| d.get(k).is_some() && get_num(d, k) != Some(neutral);
let custom_wb = d.get("WBal").is_none() || get_enum(d, "WBal").as_deref() == Some("Cst");
if !custom_wb || CALIBRATION.iter().any(|k| active(k, 0.0)) || NEUTRAL_ONLY.iter().any(|(k, n)| active(k, *n)) {
return Mapped::Unsupported { harmless: false };
}
// A value that is recorded but isn't a number, or lies outside the slider's range, can't
// replay: `fields_from` and `nums` would drop it (or read it as 0), and playback would clamp
// it, so the step would play a different look. The ranges are the PSD mapping's.
let unreadable = |k: &str| match (d.get(k), get_num(d, k)) {
(None, _) => false,
(Some(_), None) => true,
(Some(_), Some(v)) => k != "PCVS" && !(v.is_finite() && camera_raw_range(k).contains(&v)),
};
let grouped = ["HA_", "SA_", "LA_"].iter().flat_map(|p| ["R", "O", "Y", "G", "A", "B", "P", "M"].map(|c| format!("{p}{c}")));
if CAMERA_RAW.iter().any(|F(k, ..)| unreadable(k)) || grouped.into_iter().any(|k| unreadable(&k)) || CAMERA_RAW_GRADES.iter().any(|k| unreadable(k)) {
return Mapped::Unsupported { harmless: false };
}
let Some(mut m) = fields_from(d, CAMERA_RAW) else { return Mapped::Unsupported { harmless: false } };
let nums = |keys: &[&str]| -> Option<Vec<Value>> {
let v: Vec<Option<f64>> = keys.iter().map(|k| get_num(d, k)).collect();
// Absent members keep the command's defaults only when the whole group is absent.
if v.iter().all(Option::is_none) { None } else { Some(v.into_iter().map(|n| Value::from(n.unwrap_or(0.0))).collect()) }
};
// The splits are one setting: all three, or none (the defaults); a partial set can't replay,
// nor can splits outside 0..=100 or out of order, which would build a different curve.
match (get_num(d, "PC_1"), get_num(d, "PC_2"), get_num(d, "PC_3")) {
(Some(a), Some(b), Some(c)) if (0.0..=100.0).contains(&a) && a < b && b < c && c <= 100.0 => {
m.insert("curveSplits".into(), json!([a, b, c]));
}
(Some(_), Some(_), Some(_)) => return Mapped::Unsupported { harmless: false },
_ if ["PC_1", "PC_2", "PC_3"].iter().any(|k| d.get(k).is_some()) => return Mapped::Unsupported { harmless: false },
_ => {}
}
for (prefix, param) in [("HA_", "hslHue"), ("SA_", "hslSat"), ("LA_", "hslLum")] {
let keys: Vec<String> = ["R", "O", "Y", "G", "A", "B", "P", "M"].iter().map(|c| format!("{prefix}{c}")).collect();
if let Some(v) = nums(&keys.iter().map(String::as_str).collect::<Vec<_>>()) {
m.insert(param.into(), Value::Array(v));
}
}
for (keys, param) in [
(["STSH", "STSS", "CgSL"], "gradeShadows"),
(["CgMH", "CgMS", "CgML"], "gradeMidtones"),
(["STHH", "STHS", "CgHL"], "gradeHighlights"),
(["CgGH", "CgGS", "CgGL"], "gradeGlobal"),
] {
if let Some(v) = nums(&keys) {
m.insert(param.into(), json!({"hue": v[0], "sat": v[1], "lum": v[2]}));
}
}
match get_num(d, "PCVS") {
None => {}
Some(n) => match [(1.0, "highlightPriority"), (2.0, "colorPriority"), (3.0, "paintOverlay")].iter().find(|(k, _)| *k == n) {
Some((_, style)) => {
m.insert("vignetteStyle".into(), json!(style));
}
None => return Mapped::Unsupported { harmless: false },
},
}
// Point curves: flat `[in0, out0, in1, out1, …]` lists on 0..255, as the command's pairs.
for (key, param) in [("Crv ", "pointCurve"), ("CrvR", "pointCurveRed"), ("CrvG", "pointCurveGreen"), ("CrvB", "pointCurveBlue")] {
if d.get(key).is_none() {
continue;
}
let Some(list) = get_list(d, key) else { return Mapped::Unsupported { harmless: false } };
let Some(flat) = list.iter().map(num).collect::<Option<Vec<f64>>>() else { return Mapped::Unsupported { harmless: false } };
// Odd lengths, and curves `filter.cameraRaw` refuses (one point, out of range, inputs not
// increasing), stay Photoshop steps rather than failing on playback.
let points: Vec<[f32; 2]> = flat.as_chunks::<2>().0.iter().map(|[a, b]| [*a as f32, *b as f32]).collect();
if flat.len() % 2 != 0 || photocraft_algo::camera_raw::validate_curve(&points).is_err() {
return Mapped::Unsupported { harmless: false };
}
let identity = flat == [0.0, 0.0, 255.0, 255.0];
if !identity {
m.insert(param.into(), Value::Array(flat.as_chunks::<2>().0.iter().map(|[a, b]| json!([a, b])).collect()));
}
}
m.insert(CAMERA_RAW_DESCRIPTOR.into(), json!(photocraft_paint::tile::b64_encode(&d.to_bytes())));
step(crate::lens_cmds::RAW, Value::Object(m))
}
/// An imported Camera Raw Filter step back as its recorded descriptor, unchanged. Only while the
/// params are still what that descriptor imports as: an edited step, or one PhotoCraft recorded,
/// has no verified Photoshop form and Save Actions refuses it.
pub(super) fn camera_raw_to(_: &str, p: &Value) -> Option<Descriptor> {
let d = Descriptor::from_bytes(&photocraft_paint::tile::b64_decode(jstr(p, CAMERA_RAW_DESCRIPTOR)?)?).ok()?;
let Mapped::Steps(steps) = camera_raw_from(&d) else { return None };
let [(_, imported)] = steps.as_slice() else { return None };
let (mut a, mut b) = (imported.clone(), p.clone());
for v in [&mut a, &mut b] {
super::convert::normalise(v);
v.as_object_mut()?.remove(CAMERA_RAW_DESCRIPTOR);
}
(a == b).then_some(d)
}
/// Whether a Select and Mask step carries Refine Edge Brush strokes or the workspace's tool
/// edits (Quick Selection, Brush, Lasso…), which no descriptor holds.
pub(super) fn has_refine_strokes(p: &Value) -> bool {
@@ -499,6 +499,11 @@ pub(super) fn stroke_to(_: &str, p: &Value) -> Option<Descriptor> {
}
let mut params = if p.is_null() { Map::new() } else { p.as_object()?.clone() };
params.insert("width".into(), Value::from(crate::extra_cmds::stroke_width(p)));
// Photoshop opens the Stroke dialog for a descriptor that leaves out a setting, even with
// dialogs off (#8303), so the command's defaults for the ones left out are written too.
for (key, default) in [("location", json!("center")), ("opacity", json!(100)), ("mode", json!("Normal")), ("preserveTransparency", json!(false))] {
params.entry(key).or_insert(default);
}
fields_to(&Value::Object(params), STROKE, desc("null"))
}
+29 -9
View File
@@ -1,4 +1,4 @@
use super::adjustments::{HUE_RANGES, adjustment_by_class, adjustment_by_suffix, adjustment_steps};
use super::adjustments::{HUE_RANGES, adjustment_by_class, adjustment_by_suffix, adjustment_steps, levels_complete};
use super::descriptors::{
PX, Target, ang, class, class_ref, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, get_ref, get_text, jbool, jnum,
jstr, layer_ref, layer_target, long, name_ref, pct, px, ref_class, target, target_ref, text, trimmed,
@@ -9,14 +9,23 @@ use super::tables::{LABEL_COLORS, MODES, blend_label, blend_ps, lookup, lookup_b
use super::{D, Descriptor, Id, Map, ReferenceItem, Value, json};
/// A `patternLayer` descriptor's pattern, scale, angle and link as the params of
/// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. The pattern goes by name: ids differ
/// between Photoshop's library and one rebuilt from the same `.pat` file. None for a pattern
/// recorded without a name or id.
/// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. A pattern recorded with both an id
/// and a name goes by the id with the name as `patternName`: ids differ between Photoshop's
/// library and one rebuilt from the same `.pat` file, while names may collide. None for a
/// pattern recorded without a name or id.
fn pattern_params(t: &Descriptor) -> Option<Map<String, Value>> {
let mut p = Map::new();
if let Some(ptrn) = get_obj(t, "Ptrn") {
let key = get_text(ptrn, "Nm ").filter(|n| !n.is_empty()).or_else(|| get_text(ptrn, "Idnt").filter(|i| !i.is_empty()))?;
p.insert("pattern".into(), key.into());
let name = get_text(ptrn, "Nm ").filter(|n| !n.is_empty());
match (get_text(ptrn, "Idnt").filter(|i| !i.is_empty()), name) {
(Some(id), Some(name)) => {
p.insert("pattern".into(), id.into());
p.insert("patternName".into(), name.into());
}
(key, name) => {
p.insert("pattern".into(), key.or(name)?.into());
}
}
}
if let Some(s) = get_num(t, "Scl ") {
p.insert("scale".into(), s.into());
@@ -33,8 +42,10 @@ fn pattern_params(t: &Descriptor) -> Option<Map<String, Value>> {
/// The `patternLayer` descriptor for [`pattern_params`]' params.
fn pattern_desc(p: &Value) -> Option<Descriptor> {
let mut t = desc("patternLayer");
if let Some(n) = jstr(p, "pattern") {
t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n))));
match (jstr(p, "pattern"), jstr(p, "patternName")) {
(Some(id), Some(n)) => t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)).with("Idnt", text(id)))),
(Some(n), None) | (None, Some(n)) => t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)))),
(None, None) => {}
}
if let Some(s) = jnum(p, "scale") {
t = t.with("Scl ", pct(s));
@@ -757,12 +768,19 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
desc("null").with("null", r).with("filterFX", D::Descriptor(desc("filterFX").with("blendOptions", D::Descriptor(opts))))
}
"layer.setAdjustment" => {
// The event edits the current adjustment layer: a step that names its layer or
// document would play back on whichever one is active instead (#8532). A null
// `layer` or `document` is the target one, as the command reads it.
if ["layer", "document"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return None;
}
// The adjustment kind isn't in the params: Photoshop needs it, so only steps that
// name one (`kind`) export.
let kind = jstr(p, "kind")?;
// `layer.setAdjustment` changes only the settings it names. Color Balance and
// Hue/Saturation descriptors carry every setting, filling absent ones with defaults,
// so a partial edit would replay as one that also resets the rest (#8531).
// so a partial edit would replay as one that also resets the rest (#8531). Levels writes
// each range whole, so one end alone resets the other (#8530).
// Present and of the shape the writer reads: anything else it would write as 0.
let number = |p: &Value, k: &str| p.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite);
let numbers = |p: &Value, keys: &[&str]| keys.iter().all(|k| number(p, k));
@@ -784,6 +802,8 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
r.is_object() && numbers(r, &["hue", "saturation", "lightness"]) && bounds
})
}
// Both ends of each range it names (#8530).
"levels" => levels_complete(p),
_ => true,
};
if !complete {
+631 -1
View File
@@ -45,6 +45,7 @@ fn layer_steps_with_string_id_blend_modes_import_with_their_mode() {
..Default::default()
}],
warnings: vec![],
..Default::default()
};
let imp = import(&atn::write(&file).unwrap()).unwrap();
assert!(imp.unsupported.is_empty(), "{:?}", imp.unsupported.iter().map(|u| &u.event).collect::<Vec<_>>());
@@ -116,6 +117,7 @@ fn sample() -> AtnFile {
AtnAction { name: UnicodeString::new_nul("Finish"), items: vec![item("Invs", "Inverse", None)], ..Default::default() },
],
warnings: Vec::new(),
..Default::default()
}
}
@@ -428,7 +430,8 @@ fn a_selective_color_step_in_the_scalar_form_keeps_its_values() {
/// A setting Photoshop's event has no field for is dropped by export, and the step then plays back
/// as a different edit: Crystallize's `seed` (#7668), Radial Blur's centre, Minimum's and
/// Maximum's `preserve`. Such a step is refused, as one with no equivalent event already is.
/// Maximum's `preserve`. Such a step is refused, as one with no equivalent event already is. So is
/// an adjustment edit that names its layer: the event edits the active one (#8532).
#[test]
fn a_setting_the_event_cannot_hold_is_refused() {
for (id, params) in [
@@ -436,6 +439,8 @@ fn a_setting_the_event_cannot_hold_is_refused() {
("filter.blur.radialBlur", json!({"amount": 10, "centerX": 0.25, "centerY": 0.5})),
("filter.other.minimum", json!({"radius": 4, "preserve": "roundness"})),
("filter.other.maximum", json!({"radius": 4, "preserve": "roundness"})),
("layer.setAdjustment", json!({"kind": "exposure", "layer": "Target_existing", "exposure": -0.75, "offset": 0.035, "gamma": 1.37})),
("layer.setAdjustment", json!({"kind": "exposure", "document": 2, "exposure": -0.75})),
] {
let mut s = Session::new();
s.actions.list.push(Action::new("A", vec![(id.into(), params)]));
@@ -460,6 +465,9 @@ fn settings_at_the_value_the_event_plays_still_export() {
("filter.blur.radialBlur", json!({"amount": 10})),
("filter.other.minimum", json!({"radius": 4, "preserve": "squareness"})),
("filter.other.maximum", json!({"radius": 4})),
("layer.setAdjustment", json!({"kind": "exposure", "exposure": -0.75, "offset": 0.035, "gamma": 1.37})),
("layer.setAdjustment", json!({"kind": "exposure", "layer": null, "exposure": -0.75})),
("layer.setAdjustment", json!({"kind": "exposure", "document": null, "exposure": -0.75})),
// `preserve` reaches the filter through a comparison with the exact string "roundness",
// so these play as squareness -- replay's own value -- and lose nothing by export (#7759
// review).
@@ -659,6 +667,7 @@ fn every_mapped_command_exports_and_imports_back() {
("select.loadSelection", json!({"channel": "targeted"})),
("layer.newFillLayer.pattern", json!({"pattern": "Debaser-Distressed-Dark", "scale": 50, "angle": 0, "link": true})),
("layer.fill.pattern.set", json!({"pattern": "1 -R2.jpg"})),
("layer.newFillLayer.pattern", json!({"pattern": "b7a3c1d2-0000-4000-8000-000000000001", "patternName": "Twin", "scale": 50})),
("image.mode.bitmap", json!({"method": "threshold"})),
("image.imageSize", json!({"resolution": 1200, "resample": "preserveDetails", "keepPrintSize": true})),
("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false})),
@@ -774,6 +783,8 @@ fn every_mapped_command_exports_and_imports_back() {
"filter.sharpen.sharpen",
"filter.sharpen.sharpenEdges",
"filter.sharpen.sharpenMore",
// Saves back only as the descriptor it was loaded from (loaded_camera_raw_filter_steps_save_back_unchanged).
"filter.cameraRaw",
];
let unexpected: Vec<&str> = missing.iter().copied().filter(|id| !allowed.contains(id)).collect();
assert!(unexpected.is_empty(), "add round-trip cases for {unexpected:?}");
@@ -836,6 +847,27 @@ fn bucket_keeps_an_explicit_color_through_atn() {
}
}
/// A Stroke step that leaves settings at their defaults still writes them (#8303): Photoshop
/// opens the Stroke dialog for a descriptor without its blend mode, even with dialogs off.
#[test]
fn stroke_writes_the_defaults_it_leaves_out() {
let exported = |params: Value| export_item("edit.stroke", &params, "S").and_then(|item| item.descriptor).unwrap();
let d = exported(json!({"width": 2, "location": "inside", "color": "#d03060", "opacity": 63}));
assert_eq!(get_enum(&d, "Md ").as_deref(), Some("Nrml"), "{d:?}");
assert_eq!(get_enum(&d, "Lctn").as_deref(), Some("Insd"), "an explicit setting is kept");
assert_eq!(get_num(&d, "Opct"), Some(63.0));
let d = exported(json!({"width": 2}));
assert_eq!(get_enum(&d, "Lctn").as_deref(), Some("Cntr"), "{d:?}");
assert_eq!(get_num(&d, "Opct"), Some(100.0));
assert_eq!(get_enum(&d, "Md ").as_deref(), Some("Nrml"));
assert!(get_bool(&d, "PrsT") == Some(false), "{d:?}");
// An explicit mode is kept, and the step imports back to the same stroke.
let p = json!({"width": 3, "location": "outside", "mode": "Multiply", "opacity": 40, "color": "#000000", "preserveTransparency": true});
let d = exported(p.clone());
let Mapped::Steps(steps) = (event_for(&AtnEvent::Code(*b"Strk")).unwrap().from)(&d) else { panic!("{d:?}") };
assert_eq!(steps[0].1, json!({"width": 3.0, "location": "outside", "mode": "Multiply", "opacity": 40.0, "color": "#000000", "preserveTransparency": true}));
}
/// `image.adjustments.photoFilter` exported to .atn and imported back → its params, or None.
fn photo_filter_round_trip(params: Value) -> Option<Value> {
let item = export_item("image.adjustments.photoFilter", &params, "S")?;
@@ -962,6 +994,7 @@ fn unsupported_shapes_become_photoshop_steps_not_errors() {
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
warnings: vec![],
..Default::default()
};
let imp = import(&atn::write(&file).unwrap()).unwrap();
let ids: Vec<&str> = imp.actions[0].steps.iter().map(|(id, _)| id.as_str()).collect();
@@ -985,6 +1018,7 @@ fn save_preserves_the_kind_of_unsupported_atn_events() {
..Default::default()
}],
warnings: vec![],
..Default::default()
};
let mut session = Session::new();
session.execute("actions.load", json!({"data": b64(&atn::write(&source).unwrap())})).unwrap();
@@ -1060,6 +1094,7 @@ fn retouching_set_events_map_to_their_commands() {
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
warnings: vec![],
..Default::default()
};
let imp = import(&atn::write(&file).unwrap()).unwrap();
let steps = &imp.actions[0].steps;
@@ -1352,6 +1387,7 @@ fn remaining_events_import_in_their_photoshop_shapes() {
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
warnings: vec![],
..Default::default()
};
let imp = import(&atn::write(&file).unwrap()).unwrap();
let steps = &imp.actions[0].steps;
@@ -1440,6 +1476,7 @@ fn remaining_events_import_in_their_photoshop_shapes() {
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
warnings: vec![],
..Default::default()
};
let rest = import(&atn::write(&file).unwrap()).unwrap();
let rest_steps = &rest.actions[0].steps;
@@ -1478,6 +1515,7 @@ fn remaining_events_import_in_their_photoshop_shapes() {
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
warnings: vec![],
..Default::default()
};
let more = import(&atn::write(&file).unwrap()).unwrap();
let more_steps = &more.actions[0].steps;
@@ -1596,6 +1634,7 @@ fn set_of(name: &str, actions: Vec<(&str, Vec<AtnItem>)>) -> String {
expanded: false,
actions: actions.into_iter().map(|(n, items)| AtnAction { name: UnicodeString::new_nul(n), items, ..Default::default() }).collect(),
warnings: vec![],
..Default::default()
};
b64(&atn::write(&file).unwrap())
}
@@ -2280,6 +2319,54 @@ fn partial_color_balance_and_hue_saturation_edits_refuse_strict_export() {
}
}
/// Levels, like Color Balance and Hue/Saturation: the descriptor writes both ends of the Input and
/// of the Output range, filling the end an edit did not name with 0 or 255, so replaying
/// `inBlack: 31` alone would also reset a retained Input White (#8530). Strict export refuses it;
/// a pair given whole, or none of it, still exports and round-trips.
#[test]
fn partial_levels_edits_refuse_strict_export() {
let one = |p: Value| Action { name: "Probe".into(), steps: vec![("layer.setAdjustment".into(), p)], ..Default::default() };
for p in [
json!({"kind": "levels", "inBlack": 31}),
json!({"kind": "levels", "inWhite": 239}),
json!({"kind": "levels", "outBlack": 10}),
json!({"kind": "levels", "outWhite": 240}),
json!({"kind": "levels", "inBlack": 31, "inWhite": 239, "outWhite": 240}),
json!({"kind": "levels", "red": {"inBlack": 2}}),
json!({"kind": "levels", "inBlack": 1, "inWhite": 250, "blue": {"outBlack": 3}}),
// A value of the wrong shape is no value: the other end is then alone.
json!({"kind": "levels", "inBlack": 31, "inWhite": "239"}),
// CodeRabbit on batch 11: both ends of the wrong shape, or a channel that isn't an object,
// would be written as nothing too.
json!({"kind": "levels", "inBlack": "31", "inWhite": "239"}),
json!({"kind": "levels", "gamma": "1.2"}),
json!({"kind": "levels", "red": 5}),
json!({"kind": "levels", "green": [0, 255]}),
json!({"kind": "levels", "blue": {"outBlack": "3", "outWhite": "250"}}),
] {
let err = export("Audit8", &[&one(p.clone())], &[], false).unwrap_err();
assert!(err.contains("`layer.setAdjustment`"), "{p}: {err}");
let (_, skipped) = export("Audit8", &[&one(p.clone())], &[], true).unwrap();
assert_eq!(skipped, vec![Skipped { action: "Probe".into(), step: 0, id: "layer.setAdjustment".into() }], "{p}");
}
for p in [
json!({"kind": "levels", "inBlack": 31, "inWhite": 239}),
json!({"kind": "levels", "outBlack": 10, "outWhite": 240}),
json!({"kind": "levels", "inBlack": 31, "inWhite": 239, "outBlack": 10, "outWhite": 240, "gamma": 1.2}),
json!({"kind": "levels", "gamma": 0.8}),
json!({"kind": "levels", "inBlack": 1, "inWhite": 250, "red": {"inBlack": 2, "inWhite": 200}}),
] {
let (bytes, skipped) = export("Audit8", &[&one(p.clone())], &[], false).unwrap_or_else(|e| panic!("{p}: {e}"));
assert!(skipped.is_empty(), "{p}");
let steps = import(&bytes).unwrap().actions[0].steps.clone();
let (id, back) = steps.first().unwrap();
assert_eq!(id, "layer.setAdjustment");
for k in ["inBlack", "inWhite", "outBlack", "outWhite"] {
assert_eq!(back.get(k), p.get(k), "{p}: {k} in {back}");
}
}
}
/// Photoshop's Close has no document target: a Close of a specific document must not be
/// exported as a plain Close, which would close the active document on playback.
#[test]
@@ -2306,6 +2393,7 @@ fn fractional_translation_only_transform_keeps_offset_and_interpolation() {
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item("transform", "Transform", Some(d))], ..Default::default() }],
warnings: vec![],
..Default::default()
};
let imp = import(&atn::write(&file).unwrap()).unwrap();
assert!(imp.unsupported.is_empty());
@@ -2718,12 +2806,105 @@ fn adjustment_layer_reset_still_resets() {
..Default::default()
}],
warnings: vec![],
..Default::default()
};
let steps = import(&atn::write(&file).unwrap()).unwrap().actions.remove(0).steps;
assert_eq!(steps[0], ("layer.setAdjustment".to_string(), json!({})));
assert_eq!(steps[1].1, json!({"midtones": [10, 0, 0], "kind": "colorBalance"}));
}
/// Photoshop's Properties panel records an edit of an existing Vibrance layer with the string
/// class `vibrance`, not the `Vbrn` code: both import as the same `layer.setAdjustment` (#8534).
#[test]
fn adjustment_layer_set_accepts_the_vibrance_string_class() {
let set = |class: &str| {
let t = desc(class).with("temperature", long(0.0)).with("tint", long(0.0)).with("vibrance", long(28.0)).with("Strt", long(-7.0));
desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor(t))
};
let file = AtnFile {
name: UnicodeString::new_nul("Vibrance"),
expanded: false,
actions: vec![AtnAction {
name: UnicodeString::new_nul("A"),
items: vec![item("set", "Set", Some(set("vibrance"))), item("set", "Set", Some(set("Vbrn")))],
..Default::default()
}],
warnings: vec![],
..Default::default()
};
let action = import(&atn::write(&file).unwrap()).unwrap().actions.remove(0);
assert_eq!(action.steps[0].0, "layer.setAdjustment", "{:?}", action.steps);
assert_eq!(action.steps[0].1, json!({"vibrance": 28, "saturation": -7, "kind": "vibrance"}));
assert_eq!(action.steps[0], action.steps[1]);
}
/// A Vibrance Set and Make as Photoshop records them (class `vibrance`) save back with that
/// class, not the `Vbrn` code Photoshop refuses (#8383); old PhotoCraft files with `Vbrn` still
/// load and now save with `vibrance` too.
#[test]
fn vibrance_adjustment_layer_steps_save_with_the_string_class() {
let set = |class: &str| {
let t = desc(class).with("temperature", long(0.0)).with("tint", long(0.0)).with("vibrance", long(28.0)).with("Strt", long(-7.0));
desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor(t))
};
let make = |class: &str| {
let t = desc(class).with("vibrance", long(10.0)).with("Strt", long(5.0));
desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(t))))
};
let data = set_of(
"Vibrance",
vec![(
"A",
vec![
item("set", "Set", Some(set("vibrance"))),
item("Mk ", "Make", Some(make("vibrance"))),
item("set", "Set", Some(set("Vbrn"))),
item("Mk ", "Make", Some(make("Vbrn"))),
],
)],
);
let mut s = Session::new();
let loaded = s.execute("actions.load", json!({"data": data})).unwrap();
assert_eq!(loaded["unsupported"], json!([]), "{loaded}");
let steps = &s.actions.list[0].steps;
assert_eq!(steps[1], ("layer.newAdjustmentLayer.vibrance".to_string(), json!({"vibrance": 10, "saturation": 5})), "{steps:?}");
assert_eq!((&steps[0], &steps[1]), (&steps[2], &steps[3]), "the old `Vbrn` class imports the same");
let saved = s.execute("actions.save", json!({"set": "Vibrance"})).unwrap();
assert_eq!(saved["skipped"], json!([]));
let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap();
let file = atn::parse(&bytes).unwrap();
let items = &file.actions[0].items;
assert_eq!(items.len(), 4);
for pair in items.chunks(2) {
let t = get_obj(pair[0].descriptor.as_ref().unwrap(), "T ").unwrap();
assert!(t.class_id.is("vibrance"), "Set class {:?}", t.class_id);
let ty = get_obj(pair[1].descriptor.as_ref().unwrap(), "Usng").and_then(|u| get_obj(u, "Type")).unwrap();
assert!(ty.class_id.is("vibrance"), "Make class {:?}", ty.class_id);
}
let mut reloaded = Session::new();
reloaded.execute("actions.load", json!({"data": saved["data"]})).unwrap();
assert_eq!(reloaded.actions.list[0].steps, s.actions.list[0].steps);
}
/// Our Vibrance has no `temperature` or `tint`: a recorded Vibrance Set or Make with either one
/// non-zero stays a kept Photoshop step and saves back unchanged instead of losing them.
#[test]
fn vibrance_steps_with_temperature_or_tint_save_back_unchanged() {
let t = || desc("vibrance").with("temperature", long(0.0)).with("tint", long(12.0)).with("vibrance", long(28.0)).with("Strt", long(-7.0));
let set = desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor(t()));
let warm = desc("vibrance").with("temperature", long(-20.0)).with("vibrance", long(5.0));
let make = desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(warm))));
let data = set_of("Vibrance", vec![("A", vec![item("set", "Set", Some(set.clone())), item("Mk ", "Make", Some(make.clone()))])]);
let mut s = Session::new();
s.execute("actions.load", json!({"data": data})).unwrap();
assert!(s.actions.list[0].steps.iter().all(|(id, _)| id == "actions.photoshopStep"), "{:?}", s.actions.list[0].steps);
let saved = s.execute("actions.save", json!({"set": "Vibrance"})).unwrap();
let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap();
let file = atn::parse(&bytes).unwrap();
assert_eq!(file.actions[0].items[0].descriptor, Some(set));
assert_eq!(file.actions[0].items[1].descriptor, Some(make));
}
/// A Free Transform recorded against an unlinked mask or an alpha channel must not export as a
/// layer transform that moves the layer's pixels on replay (#7195).
#[test]
@@ -3063,12 +3244,207 @@ fn hue_saturation_uses_photoshops_hue_key() {
assert_eq!(p["hue"], json!(30), "{p}");
}
/// #6745: a recorded Camera Raw Filter step (`Adobe Camera Raw Filter`, the layout of 62 real
/// recordings) imports as `filter.cameraRaw` with its sliders, colour mixer, grading wheels,
/// vignette style and point curves, and plays. One that uses the Calibration panel (or noise
/// settings the command lacks) stays a Photoshop step rather than replaying a different look.
#[test]
fn camera_raw_filter_steps_import_as_filter_camera_raw() {
let int = |v: i32| D::Integer(v);
// Every step carries the version keys a recording has (a verified process version).
let cr = || desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", int(5)).with("PrVe", int(184_549_376));
let mut d = cr()
.with("WBal", enm("WBal", "Cst "))
.with("Temp", int(12))
.with("Tint", int(-4))
.with("Ex12", D::Double(0.35))
.with("Cr12", int(10))
.with("Hi12", int(-30))
.with("Sh12", int(25))
.with("Cl12", int(8))
.with("Vibr", int(15))
.with("PC_1", int(20))
.with("PC_2", int(50))
.with("PC_3", int(80))
.with("STSH", int(210))
.with("STSS", int(12))
.with("CgSL", int(0))
.with("CgBl", int(60))
.with("STB ", int(-10))
.with("Shrp", int(40))
.with("ShpR", D::Double(1.2))
.with("LNR ", int(20))
.with("LNRC", int(0))
.with("CNR ", int(25))
.with("CNRS", int(50))
.with("PCVA", int(-20))
.with("PCVS", int(2))
.with("Crv ", D::List([0, 0, 64, 50, 255, 255].map(int).to_vec()))
.with("CrvR", D::List([0, 0, 255, 255].map(int).to_vec()));
for (k, v) in ["R", "O", "Y", "G", "A", "B", "P", "M"].iter().zip(1..) {
d = d.with(&format!("HA_{k}"), int(v));
}
d = d.with("SA_O", int(-15));
let calibrated = cr().with("Ex12", D::Double(0.2)).with("RHue", int(8));
let smoothed = cr().with("CNR ", int(25)).with("CNRS", int(70));
let auto_wb = cr().with("WBal", enm("WBal", "Atmt")).with("Temp", int(5));
let partial_splits = cr().with("PC_1", int(20));
let odd_curve = cr().with("Crv ", int(3));
// Review of #8714: values that would replay differently, or fail to play, stay Photoshop steps.
let reversed_splits = cr().with("PC_1", int(80)).with("PC_2", int(50)).with("PC_3", int(20));
let split_past_100 = cr().with("PC_1", int(20)).with("PC_2", int(50)).with("PC_3", int(120));
let one_point_curve = cr().with("Crv ", D::List([0, 0].map(int).to_vec()));
let unordered_curve = cr().with("CrvG", D::List([0, 0, 128, 90, 64, 50, 255, 255].map(int).to_vec()));
let text_contrast = cr().with("Cr12", D::Text(UnicodeString::new_nul("ten")));
let text_hue = cr().with("HA_R", D::Text(UnicodeString::new_nul("red")));
let text_grade = cr().with("STSH", D::Text(UnicodeString::new_nul("blue")));
let exposure_past_5 = cr().with("Ex12", D::Double(6.0));
let negative_sharpening = cr().with("Shrp", int(-10));
// CodeRabbit on batch 11: a process version the PSD mapping hasn't verified renders differently.
let unknown_version =
desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", int(4)).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2));
let no_version_number = desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2));
let mismatched_pair =
desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", int(6)).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2));
let no_camera_raw_version = desc("null").with("PrVN", int(5)).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2));
let items = vec![
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(d)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(calibrated)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(smoothed)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(auto_wb)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(partial_splits)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(odd_curve)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(reversed_splits)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(split_past_100)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(one_point_curve)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(unordered_curve)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_contrast)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_hue)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_grade)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(exposure_past_5)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(negative_sharpening)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(unknown_version)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(no_version_number)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(mismatched_pair)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(no_camera_raw_version)),
];
let file = AtnFile {
name: UnicodeString::new_nul("Looks"),
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul("Warm"), items, ..Default::default() }],
warnings: vec![],
..Default::default()
};
let imp = import(&atn::write(&file).unwrap()).unwrap();
let steps = &imp.actions[0].steps;
let (id, p) = &steps[0];
assert_eq!(id, "filter.cameraRaw");
// The recorded descriptor rides along, so Save Actions can write the step back.
let mut p = p.clone();
assert!(p.as_object_mut().unwrap().remove("__atnDescriptor").is_some(), "{p}");
assert_eq!(
p,
json!({
"temperature": 12, "tint": -4, "exposure": 0.35, "contrast": 10, "highlights": -30, "shadows": 25,
"clarity": 8, "vibrance": 15, "curveSplits": [20, 50, 80],
"hslHue": [1, 2, 3, 4, 5, 6, 7, 8], "hslSat": [0, -15, 0, 0, 0, 0, 0, 0],
"gradeShadows": {"hue": 210, "sat": 12, "lum": 0}, "gradeBlending": 60, "gradeBalance": -10,
"sharpenAmount": 40, "sharpenRadius": 1.2, "noiseLuminance": 20, "noiseColor": 25,
"vignetteAmount": -20, "vignetteStyle": "colorPriority", "pointCurve": [[0, 0], [64, 50], [255, 255]]
})
);
for (k, (id, _)) in steps.iter().enumerate().skip(1) {
assert_eq!(id, PHOTOSHOP_STEP, "step {k}");
}
assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::<Vec<_>>(), (1..=18).collect::<Vec<_>>());
// The imported step plays.
let mut s = Session::new();
s.execute("file.new", json!({"width": 16, "height": 12})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
s.execute(id, p.clone()).unwrap();
}
/// Review of #8714: a Camera Raw Filter step that was loaded saves back as the recorded step,
/// byte for byte, as it did while it was a kept Photoshop step; once edited (or when PhotoCraft
/// recorded it) Save Actions refuses it as before. The loaded step plays.
#[test]
fn loaded_camera_raw_filter_steps_save_back_unchanged() {
let recorded = desc("null")
.with("CrVe", D::Text(UnicodeString::new_nul("16.1.1")))
.with("PrVN", D::Integer(5))
.with("PrVe", D::Integer(184_549_376))
.with("WBal", enm("WBal", "Cst "))
.with("Ex12", D::Double(0.35))
.with("Cr12", D::Integer(10))
.with("Crv ", D::List([0, 0, 64, 50, 255, 255].map(D::Integer).to_vec()));
let file = one_action(vec![item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(recorded.clone()))]);
let mut s = Session::new();
let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap();
assert_eq!(loaded["unsupported"], json!([]), "{loaded}");
assert_eq!(s.actions.list[0].steps[0].0, "filter.cameraRaw");
let saved_step = |r: &Value| {
let saved = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
saved.actions[0].items.first().map(|i| (i.event.clone(), i.descriptor.clone()))
};
// Strict save, and the Actions panel's save (which skips what can't be written).
for skip in [false, true] {
let r = s.execute("actions.save", json!({"action": "A", "skipUnsupported": skip})).unwrap();
assert_eq!(r["skipped"], json!([]), "{r}");
assert_eq!(saved_step(&r), Some((AtnEvent::name("Adobe Camera Raw Filter"), Some(recorded.clone()))));
}
// It plays.
s.execute("file.new", json!({"width": 16, "height": 12})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
assert_eq!(played["ran"], 1, "{played}");
assert!(played.get("failed").is_none(), "{played}");
// Edited, it no longer matches what was recorded.
let original = s.actions.list[0].steps[0].1.clone();
s.actions.list[0].steps[0].1["exposure"] = json!(1.5);
let e = s.execute("actions.save", json!({"action": "A"})).unwrap_err().to_string();
assert!(e.contains("filter.cameraRaw"), "{e}");
// Recorded by PhotoCraft: no descriptor to write back.
s.actions.list[0].steps[0].1 = original;
s.actions.list[0].steps[0].1.as_object_mut().unwrap().remove("__atnDescriptor");
let r = s.execute("actions.save", json!({"action": "A", "skipUnsupported": true})).unwrap();
assert_eq!(r["skipped"].as_array().unwrap().len(), 1, "{r}");
}
/// Review of #8714: a Camera Raw Filter step with a key the table doesn't map (an Upright
/// setting, a profile name, any other panel) or with no settings at all stays a Photoshop step
/// and is reported, rather than replaying without that processing.
#[test]
fn camera_raw_filter_steps_with_unknown_keys_stay_photoshop_steps() {
let cr = || desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", D::Integer(5)).with("PrVe", D::Integer(184_549_376));
let upright = cr().with("Ex12", D::Double(0.2)).with("PerV", D::Integer(20));
let profile = cr().with("Cr12", D::Integer(10)).with("LookName", D::Text(UnicodeString::new_nul("B&W 05")));
let file = one_action(vec![
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(upright.clone())),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(profile)),
item("Adobe Camera Raw Filter", "Camera Raw Filter", None),
item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(cr().with("Ex12", D::Double(0.2)))),
]);
let mut s = Session::new();
let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap();
let unsupported: Vec<u64> = loaded["unsupported"].as_array().unwrap().iter().map(|u| u["step"].as_u64().unwrap()).collect();
assert_eq!(unsupported, [0, 1, 2], "{loaded}");
let ids: Vec<&str> = s.actions.list[0].steps.iter().map(|(id, _)| id.as_str()).collect();
assert_eq!(ids, [PHOTOSHOP_STEP, PHOTOSHOP_STEP, PHOTOSHOP_STEP, "filter.cameraRaw"]);
// Kept, it still saves back as recorded.
let r = s.execute("actions.save", json!({"action": "A"})).unwrap();
let saved = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(saved.actions[0].items[0].descriptor, Some(upright));
}
fn one_action(items: Vec<AtnItem>) -> AtnFile {
AtnFile {
name: UnicodeString::new_nul("Saves"),
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
warnings: vec![],
..Default::default()
}
}
@@ -3167,6 +3543,7 @@ fn long_names_are_clipped_instead_of_copied_into_every_diagnostic() {
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul(&long), items: unknown(50), ..Default::default() }],
warnings: vec![],
..Default::default()
};
let imp = import(&atn::write(&file).unwrap()).unwrap();
assert_eq!(imp.set.chars().count(), MAX_NAME_CHARS);
@@ -3175,3 +3552,256 @@ fn long_names_are_clipped_instead_of_copied_into_every_diagnostic() {
assert_eq!(imp.unsupported.len(), 50);
assert!(imp.unsupported.iter().all(|u| u.action.chars().count() == MAX_NAME_CHARS));
}
/// A Pattern Fill step whose `Ptrn` holds `id` and `name`, as the reference application records it.
fn pattern_fill_step(id: &str, name: &str) -> AtnItem {
let t = desc("patternLayer").with("Ptrn", D::Descriptor(desc("Ptrn").with("Idnt", text(id)).with("Nm ", text(name))));
item(
"Mk ",
"Make",
Some(desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t))))),
)
}
/// Defines a 4×4 pattern of `color` named `name` in `s`'s library from its active document.
fn define_pattern(s: &mut Session, color: &str, name: &str) -> String {
s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap();
s.execute("edit.definePattern", json!({"name": name})).unwrap()["pattern"].as_str().unwrap().to_string()
}
fn pixel(s: &mut Session) -> Vec<f64> {
let v = s.execute("document.pixel", json!({"x": 1, "y": 1})).unwrap();
v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap()).collect()
}
/// A Pattern Fill step whose `Ptrn` names both an installed id and a display name shared by
/// another pattern plays the pattern with that id; a foreign id falls back to the name.
#[test]
fn pattern_fill_prefers_an_installed_id_over_a_colliding_name() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
let mut define = |color: &str| {
s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap();
s.execute("edit.definePattern", json!({"name": "Twin"})).unwrap()["pattern"].as_str().unwrap().to_string()
};
let red = define("#ff0000");
let blue = define("#0000ff");
assert_ne!(red, blue);
s.patterns.items.retain(|p| p.id == red || p.id == blue);
s.patterns.items.sort_by_key(|p| p.id != blue);
let fill_step = |id: &str| {
let t = desc("patternLayer").with("Ptrn", D::Descriptor(desc("Ptrn").with("Idnt", text(id)).with("Nm ", text("Twin"))));
item(
"Mk ",
"Make",
Some(desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t))))),
)
};
let data = set_of("Pat", vec![("Installed", vec![fill_step(&red)]), ("Foreign", vec![fill_step("not-installed-id")])]);
let r = s.execute("actions.load", json!({"data": data})).unwrap();
assert!(r["unsupported"].as_array().is_none_or(|u| u.is_empty()), "{r}");
for (action, want) in [("Installed", [1.0, 0.0, 0.0, 1.0]), ("Foreign", [0.0, 0.0, 1.0, 1.0])] {
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
let r = s.execute("actions.play", json!({"action": action})).unwrap();
assert!(r.get("failed").is_none(), "{r}");
let v = s.execute("document.pixel", json!({"x": 1, "y": 1})).unwrap();
let got: Vec<f64> = v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap()).collect();
assert_eq!(got, want, "{action}");
}
}
/// The recorded id is looked up by id alone, in the document and then the library, before any
/// name: a document pattern *named* like the id does not beat the library pattern with that id,
/// and a foreign id that happens to be another pattern's name falls back to the recorded name.
/// An id and a name of the same pattern play it.
#[test]
fn pattern_fill_ids_beat_names_across_document_and_library() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
let red = define_pattern(&mut s, "#ff0000", "Red");
define_pattern(&mut s, "#0000ff", "Blue");
let green = define_pattern(&mut s, "#00ff00", &red);
let data = set_of(
"Pat",
vec![
("IdWins", vec![pattern_fill_step(&red, "Blue")]),
("NameFallback", vec![pattern_fill_step("Red", "Blue")]),
("Same", vec![pattern_fill_step(&red, "Red")]),
],
);
s.execute("actions.load", json!({"data": data})).unwrap();
// Only the playback document holds the green pattern named like the red one's id.
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
s.execute("layer.newFillLayer.pattern", json!({"pattern": green})).unwrap();
s.execute("pattern.delete", json!({"pattern": green})).unwrap();
assert!(s.active().unwrap().doc.patterns.iter().any(|p| p.id == green && p.name == red));
assert_eq!(pixel(&mut s), [0.0, 1.0, 0.0, 1.0]);
for (action, want) in [("IdWins", [1.0, 0.0, 0.0, 1.0]), ("NameFallback", [0.0, 0.0, 1.0, 1.0]), ("Same", [1.0, 0.0, 0.0, 1.0])] {
let r = s.execute("actions.play", json!({"action": action})).unwrap();
assert!(r.get("failed").is_none(), "{action}: {r}");
assert_eq!(pixel(&mut s), want, "{action}");
}
}
/// CodeRabbit on batch 11: a pattern step that names its pattern only by `patternName` exports
/// that name, rather than a step with no pattern (which plays the current one).
#[test]
fn pattern_steps_named_only_by_pattern_name_export_the_name() {
let one = Action { name: "P".into(), steps: vec![("layer.newFillLayer.pattern".into(), json!({"patternName": "Checkerboard"}))], ..Default::default() };
let (bytes, skipped) = export("Pat", &[&one], &[], false).unwrap();
assert!(skipped.is_empty());
let steps = import(&bytes).unwrap().actions[0].steps.clone();
assert_eq!(steps[0].0, "layer.newFillLayer.pattern");
assert_eq!(steps[0].1["pattern"], json!("Checkerboard"), "{}", steps[0].1);
}
/// CodeRabbit on batch 11: when the recorded id is installed nowhere, the recorded name is looked
/// up as a name only. A pattern whose id equals that name text doesn't beat the one named so.
#[test]
fn pattern_fill_name_fallback_matches_names_not_ids() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
let red = define_pattern(&mut s, "#ff0000", "Red");
// Green is named like the red pattern's id.
define_pattern(&mut s, "#00ff00", &red);
let data = set_of("Pat", vec![("NameIsAnId", vec![pattern_fill_step("5e1c0000-aaaa-4bbb-8ccc-000000000000", &red)])]);
s.execute("actions.load", json!({"data": data})).unwrap();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
let r = s.execute("actions.play", json!({"action": "NameIsAnId"})).unwrap();
assert!(r.get("failed").is_none(), "{r}");
assert_eq!(pixel(&mut s), [0.0, 1.0, 0.0, 1.0]);
}
/// A recorded pattern installed neither by id nor by name fails with an error that names the
/// pattern, from the imported step and from the Pattern Fill dialog's command alike.
#[test]
fn pattern_fill_missing_everywhere_names_the_pattern() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
define_pattern(&mut s, "#ff0000", "Red");
let data = set_of("Pat", vec![("Missing", vec![pattern_fill_step("5e1c0000-aaaa-4bbb-8ccc-000000000000", "My Wood")])]);
s.execute("actions.load", json!({"data": data})).unwrap();
let r = s.execute("actions.play", json!({"action": "Missing"})).unwrap();
let err = r["failed"]["error"].as_str().unwrap_or_default();
assert!(err.contains("\"My Wood\""), "{r}");
s.execute("layer.newFillLayer.pattern", json!({"pattern": "Red"})).unwrap();
let e = s.execute("layer.fill.pattern.set", json!({"pattern": "5e1c0000-aaaa-4bbb-8ccc-000000000000", "patternName": "My Wood"})).unwrap_err();
assert!(e.to_string().contains("\"My Wood\""), "{e}");
}
/// FredApps review on #10459: a set whose name has surrounding spaces (a Photoshop `.atn` or an
/// older actions.json can have one, and New Action records into it under that exact name) saves
/// by that name. `actions.save` used to trim it and then find no set.
#[test]
fn save_finds_a_set_by_its_exact_name_with_spaces() {
let mut s = Session::new();
s.actions.list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) });
s.execute("actions.record", json!({"name": "New", "set": " Web "})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
let saved = s.execute("actions.save", json!({"set": " Web "})).unwrap();
assert_eq!((&saved["set"], &saved["actions"]), (&json!(" Web "), &json!(["Old", "New"])));
// The file keeps the name, as Photoshop's does.
let mut reloaded = Session::new();
let r = reloaded.execute("actions.load", json!({"data": saved["data"]})).unwrap();
assert_eq!(r["set"], " Web ");
// Other names are still trimmed.
s.execute("actions.assignSet", json!({"action": "Old", "set": "Print"})).unwrap();
assert_eq!(s.execute("actions.save", json!({"set": " Print "})).unwrap()["set"], "Print");
}
/// FredApps review on #10459: Save Actions… on an empty set made with New Set writes it, as
/// Photoshop saves an empty set to the `.atn`, and loading that file brings the empty set back.
#[test]
fn an_empty_new_set_saves_and_loads_back() {
let mut s = Session::new();
s.execute("actions.newSet", json!({"name": "Later"})).unwrap();
let saved = s.execute("actions.save", json!({"set": "Later"})).unwrap();
assert_eq!((&saved["set"], &saved["actions"], &saved["steps"]), (&json!("Later"), &json!([]), &json!(0)));
let mut other = Session::new();
let r = other.execute("actions.load", json!({"data": saved["data"]})).unwrap();
assert_eq!((&r["set"], &r["actions"]), (&json!("Later"), &json!([])));
assert_eq!(crate::actions_edit_cmds::set_names(&other), ["Later"], "an empty folder");
other.execute("actions.load", json!({"data": saved["data"]})).unwrap();
assert_eq!(crate::actions_edit_cmds::set_names(&other), ["Later"], "loaded twice, still one folder");
// New Action records into it as into any set, and it saves with that action.
other.execute("actions.record", json!({"name": "Now", "set": "Later"})).unwrap();
other.execute("actions.stop", json!({})).unwrap();
assert_eq!(other.execute("actions.save", json!({"set": "Later"})).unwrap()["actions"], json!(["Now"]));
// A set that doesn't exist is still refused, and so is saving every action when there is none.
let err = s.execute("actions.save", json!({"set": "Nope"})).unwrap_err().to_string();
assert!(err.contains("no actions in a set named `Nope`"), "{err}");
let err = Session::new().execute("actions.save", json!({})).unwrap_err().to_string();
assert!(err.contains("there are no actions to save"), "{err}");
}
/// A set from Chinese Photoshop: UTF-16 set and action names, a step name in GBK (可选颜色,
/// the bytes from #6743) on an event PhotoCraft has no command for, with no descriptor.
fn gbk_set() -> Vec<u8> {
let step = AtnItem { dictionary: b"\xbf\xc9\xd1\xa1\xd1\xd5\xc9\xab".to_vec(), ..item("syntheticFill", "", None) };
let file = AtnFile {
name: UnicodeString::new_nul("相馆"),
actions: vec![AtnAction { name: UnicodeString::new_nul("调白"), items: vec![step], ..Default::default() }],
..Default::default()
};
atn::write(&file).unwrap()
}
#[test]
fn load_decodes_legacy_step_names() {
let mut s = Session::new();
let r = s.execute("actions.load", json!({"data": b64(&gbk_set())})).unwrap();
assert_eq!(r["encoding"], "GBK", "{r}");
assert_eq!(r["unsupported"][0]["name"], "可选颜色", "{r}");
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
let played = s.execute("actions.play", json!({"action": "调白"})).unwrap();
assert!(played["failed"]["error"].as_str().unwrap().contains("可选颜色"), "{played}");
}
#[test]
fn load_keeps_windows_1252_symbols() {
// Windows Photoshop step names with no Unicode copy: Mac Roman reads ° and » as ∞ and ª,
// which must not win ("50 ∞", "Grˆfle ª"). Save Actions writes the names back as that text.
let steps = vec![
AtnItem { dictionary: b"50 \xb0".to_vec(), ..item("syntheticFill", "", None) },
AtnItem { dictionary: b"Gr\xf6\xdfe \xbb".to_vec(), ..item("syntheticFill", "", None) },
];
let file = AtnFile {
name: UnicodeString::new_nul("Größe ändern"),
actions: vec![AtnAction { name: UnicodeString::new_nul("Logo"), items: steps, ..Default::default() }],
..Default::default()
};
let mut s = Session::new();
let r = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap();
assert_eq!(r["encoding"], "windows-1252", "{r}");
assert_eq!(r["unsupported"][0]["name"], "50 °", "{r}");
assert_eq!(r["unsupported"][1]["name"], "Größe »", "{r}");
let saved = s.execute("actions.save", json!({"set": "Größe ändern"})).unwrap();
let saved = atn::parse(&photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap()).unwrap();
let names: Vec<String> = saved.actions[0].items.iter().map(|i| saved.item_label(i)).collect();
assert_eq!(names, ["50 °", "Größe »"]);
}
#[test]
fn load_encoding_override() {
let mut s = Session::new();
let r = s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": "shift_jis"})).unwrap();
assert_eq!(r["encoding"], "Shift_JIS", "{r}");
let r = s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": "auto"})).unwrap();
assert_eq!(r["encoding"], "GBK", "{r}");
}
#[test]
fn load_reports_utf8() {
let mut s = Session::new();
let r = s.execute("actions.load", json!({"data": b64(&atn::write(&sample()).unwrap())})).unwrap();
assert_eq!(r["encoding"], "UTF-8", "{r}");
}
#[test]
fn load_rejects_bad_encodings() {
let mut s = Session::new();
for bad in [json!(3), json!(""), json!("nope"), json!("replacement"), json!(["gbk"])] {
assert!(s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": bad})).is_err(), "{bad}");
}
assert!(s.actions.list.is_empty(), "nothing is loaded when the encoding is bad");
}
+1 -1
View File
@@ -36,7 +36,7 @@ pub fn faces_in(doc: &Document, active: Option<LayerId>, all_layers: bool, min_s
surf.read_rgba_into(area, &mut px);
px
}
None => photocraft_compose::render(doc, area).px,
None => photocraft_compose::render(doc, area).into_px(),
};
let found = detect(&px, w, h, min_score)?;
let (x0, y0) = (area.x0 as f32, area.y0 as f32);
+5 -2
View File
@@ -45,8 +45,11 @@ pub(crate) use open::{import, tag_exr_colorspace};
use paths::is_file;
#[cfg(test)]
use paths::openable_name;
pub use paths::{extension, holds, holds_at, is_template, layered_extension, list_images, losses_at, same_file, saves_in_place, template_name, untitled_name};
pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, portable_device_name, read_file, sanitize, stem, write_file};
pub use paths::{
extension, holds, holds_at, is_template, layered_extension, list_images, losses_at, portable_device_name, same_file, saves_in_place, template_name,
untitled_name,
};
pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, read_file, sanitize, stem, write_file};
use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatten_all_masks, image_processor, load_files_into_stack};
use save::save_a_copy;
pub(crate) use save::{SaveOpts, encode, save_doc};
+1 -1
View File
@@ -212,7 +212,7 @@ pub(crate) fn sanitize(name: &str) -> String {
/// `name` with a `_` before its first dot when it is a Windows device name (`nul` → `nul_`,
/// `com1.v2` → `com1_.v2`); a `_` at the end would leave the device stem in place.
pub(crate) fn portable_device_name(name: String) -> String {
pub fn portable_device_name(name: String) -> String {
if !is_windows_device_name(&name) {
return name;
}
+1 -1
View File
@@ -230,7 +230,7 @@ fn mask_all_objects(s: &mut Session, p: &Value) -> Result<Value> {
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_compose::render(self.0, r).into_px()
}
}
photocraft_algo::segment::subject::select_subject(&Composite(&doc), doc.bounds())
@@ -757,11 +757,11 @@ fn applying_a_feathered_mask_preserves_its_soft_composite() {
Ok(())
})
.unwrap();
let before = photocraft_compose::flatten(doc(&s)).px;
let before = photocraft_compose::flatten(doc(&s)).into_px();
assert!(before[15 * 40 + 19][3] > 0.0 && before[15 * 40 + 19][3] < 1.0, "mask must start with a soft edge");
s.execute("layer.layerMask.apply", json!({})).unwrap();
assert!(active(&s).mask.is_none(), "Apply removes the pixel mask");
let after = photocraft_compose::flatten(doc(&s)).px;
let after = photocraft_compose::flatten(doc(&s)).into_px();
for (a, b) in before.iter().zip(&after) {
assert!((a[3] - b[3]).abs() <= 1.0 / 255.0 + 1e-5, "depth {depth}: alpha {a:?} became {b:?}");
}
@@ -791,13 +791,13 @@ fn from_transparency_preserves_mask_coverage_outside_the_canvas() {
for depth in DEPTHS {
let mut s = session(depth, "rgb");
paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]);
let before = photocraft_compose::flatten(doc(&s)).px;
let before = photocraft_compose::flatten(doc(&s)).into_px();
s.execute("layer.translate", json!({"dx": 20})).unwrap();
s.execute("layer.layerMask.fromTransparency", json!({})).unwrap();
let mask = active(&s).mask.as_ref().unwrap();
assert!((mask.value(50, 10) - 0.5).abs() < 1.0 / 255.0 + 1e-6, "off-canvas mask at depth {depth}");
s.execute("layer.translate", json!({"dx": -20})).unwrap();
let after = photocraft_compose::flatten(doc(&s)).px;
let after = photocraft_compose::flatten(doc(&s)).into_px();
for (a, b) in before.iter().zip(&after) {
assert!((a[3] - b[3]).abs() <= 1.0 / 255.0 + 1e-6, "alpha changed at depth {depth}: {a:?} -> {b:?}");
}
@@ -44,7 +44,7 @@ fn modes_toggle_and_show_in_inspect_without_history() {
fn a_mask_view_never_alters_pixels() {
let (mut s, masked, _) = session();
let before = s.active().unwrap().doc.clone();
let px = |s: &Session| photocraft_compose::render(&s.active().unwrap().doc, Rect::new(0, 0, 40, 20)).px;
let px = |s: &Session| photocraft_compose::render(&s.active().unwrap().doc, Rect::new(0, 0, 40, 20)).into_px();
let composite = px(&s);
for mode in ["gray", "overlay", "toggleOverlay", "toggleGray", "off"] {
s.execute(ID, json!({"layer": masked, "mode": mode})).unwrap();
+1 -1
View File
@@ -186,7 +186,7 @@ fn with_released_movement_locks<R>(l: &mut Layer, f: impl FnOnce(&mut Layer) ->
/// 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 }
if opaque { buf.over_background([1.0, 1.0, 1.0]).into_px() } else { buf.into_px() }
}
/// Replace the document's layers by one 8-bit layer holding `px` in `mode`'s storage format.
+2 -2
View File
@@ -568,7 +568,7 @@ fn bitmap_budgets_a_conversion_at_the_document_resolution_too() {
/// The Bitmap conversion of `d` the pre-#8477 way, from one full-canvas composite over white.
fn bitmap_oracle(d: &Document, method: Option<BitmapMethod>, custom: Option<(&[f32], usize, usize)>) -> Vec<f32> {
let px = photocraft_compose::flatten(d).over_background([1.0; 3]).px;
let px = photocraft_compose::flatten(d).over_background([1.0; 3]).into_px();
let mut gray: Vec<f32> = px.iter().map(|q| photocraft_color::convert::rgb_to_gray([q[0], q[1], q[2]])).collect();
let w = d.size.width as usize;
match (method, custom) {
@@ -730,7 +730,7 @@ fn duotone_to_colour_modes_keeps_the_ink_colours() {
s.execute("image.mode.duotone", cfg.clone()).unwrap();
let before = s.active().unwrap().doc.clone();
let gray: Vec<f32> = (0..16).map(|x| before.layers[0].surface().unwrap().pixel(x, 1)[0]).collect();
let shown = photocraft_compose::render(&display_document(&before).unwrap(), Rect::from_xywh(0, 1, 16, 1)).px;
let shown = photocraft_compose::render(&display_document(&before).unwrap(), Rect::from_xywh(0, 1, 16, 1)).into_px();
s.execute(&format!("image.mode.{mode}"), json!({})).unwrap();
let d = doc(&s);
assert!(d.duotone.is_none(), "{ctx}");
+30 -7
View File
@@ -182,12 +182,35 @@ pub fn resolve(s: &Session, key: &str) -> Option<Pattern> {
pub(crate) fn resolve_param(s: &Session, cmd: &str, p: &Value) -> Result<Pattern> {
let key = p.get("pattern").and_then(Value::as_str).unwrap_or("");
if let Some(pat) = resolve(s, key) {
return paintable(cmd, pat);
}
match library_pattern(s, key).map(|lp| full(s, lp)) {
Some(Err(e)) => Err(bad(cmd, e)),
_ => Err(bad(cmd, format!("no pattern \"{key}\" (see pattern.list)"))),
resolve_or_named(s, key, p).map_err(|e| bad(cmd, e)).and_then(|pat| paintable(cmd, pat))
}
/// The pattern `key` names, or with a `patternName` in `p` (an imported action's pattern recorded
/// with both an id and a name) the pattern with id `key`: the active document's, then the
/// library's, by id alone, and only when that id is installed nowhere the one `patternName`
/// names, as the reference application plays such a step. The error says why: no such pattern,
/// or a saved library pattern whose pixels can't be read.
pub(crate) fn resolve_or_named(s: &Session, key: &str, p: &Value) -> std::result::Result<Pattern, String> {
use photocraft_doc::pattern::find;
let name = p.get("patternName").and_then(Value::as_str).filter(|n| !n.is_empty());
// `find` with an empty name looks up the id alone; both empty find nothing.
let in_doc = |id: &str, name: &str| s.active().and_then(|d| find(&d.doc.patterns, id, name)).map(|p| (p, false));
let by_key = |k: &str| in_doc(k, k).or_else(|| library_pattern(s, k).map(|p| (p, true)));
let found = match name {
// The name is a name: another pattern whose id happens to equal it doesn't count.
Some(n) => in_doc(key, "")
.or_else(|| find(&s.patterns.items, key, "").map(|p| (p, true)))
.or_else(|| in_doc("", n))
.or_else(|| find(&s.patterns.items, "", n).map(|p| (p, true))),
None => by_key(key),
};
match found {
Some((pat, false)) => Ok(pat.clone()),
Some((pat, true)) => full(s, pat),
None => Err(match name {
Some(n) => format!("no pattern \"{n}\" (id \"{key}\"; see pattern.list)"),
None => format!("no pattern \"{key}\" (see pattern.list)"),
}),
}
}
@@ -588,7 +611,7 @@ pub fn specs() -> Vec<CommandSpec> {
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]?,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)}"##,
params: r##"{"pattern":id|name?=first library pattern,"patternName":name? (then `pattern` is an id; the name is used when no pattern has that id),"scale":1..1000=100,"angle":deg=0,"link":bool=true,"phase":[x,y]?,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)}"##,
enabled: has_doc,
journal: true,
run: new_fill_layer,
+2 -2
View File
@@ -37,7 +37,7 @@ fn edited(s: &Session, base: &Fill, p: &Value) -> Result<(Fill, Option<Pattern>)
let (mut scale, mut angle, mut link, mut phase, mut pat) = (*scale, *angle, *link, *phase, None);
if let Some(v) = p.get("pattern").filter(|v| !v.is_null()) {
let key = v.as_str().filter(|k| !k.is_empty()).ok_or_else(|| bad("`pattern` is a pattern id or name"))?;
pat = Some(crate::pattern_cmds::resolve(s, key).ok_or_else(|| bad(format!("no pattern \"{key}\" (see pattern.list)")))?);
pat = Some(crate::pattern_cmds::resolve_or_named(s, key, p).map_err(bad)?);
}
if let Some(v) = num("scale", SCALE_RANGE)? {
scale = v / 100.0;
@@ -139,7 +139,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Pattern Fill…",
menu: &[],
shortcut: None,
params: r##"{"layer":id? (default active; a Pattern Fill layer),"document":id? (reject a stale dialog),"pattern":id|name?,"scale":1..1000?,"angle":-180..180?,"link":bool?,"phase":[x,y]? (Snap to Origin: [0,0])}; omitted values keep the layer's"##,
params: r##"{"layer":id? (default active; a Pattern Fill layer),"document":id? (reject a stale dialog),"pattern":id|name?,"patternName":name? (then `pattern` is an id; the name is used when no pattern has that id),"scale":1..1000?,"angle":-180..180?,"link":bool?,"phase":[x,y]? (Snap to Origin: [0,0])}; omitted values keep the layer's"##,
enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()),
run: set,
journal: true,
+71 -13
View File
@@ -117,14 +117,30 @@ fn import_abr(s: &mut Session, p: &Value) -> Result<Value> {
)
}
fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io::abr_map::AbrImport) -> Result<Value> {
// Re-importing a file replaces its group instead of duplicating it.
if p.get("replace").and_then(Value::as_bool).unwrap_or(true) {
s.tools.presets.retain(|x| x.builtin || x.group != group);
/// `name`, or `name (2)`, `name (3)`… when `taken` says it is in use.
fn free_group(name: &str, taken: impl Fn(&str) -> bool) -> String {
if !taken(name) {
return name.to_string();
}
(2..=u32::MAX).map(|i| format!("{name} ({i})")).find(|g| !taken(g)).unwrap_or_else(|| name.to_string())
}
fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io::abr_map::AbrImport) -> Result<Value> {
// A file whose name matches a group already in the library becomes a new group beside it, as
// in Photoshop, unless `replace` asks to drop that group's own presets first: the group name
// is only the file name, and the library is outside document history (#10640).
let group = if p.get("replace").and_then(Value::as_bool).unwrap_or(false) {
s.tools.presets.retain(|x| x.builtin || x.group != group);
group
} else {
// One pass over the library, not one per numbered candidate.
let groups: std::collections::HashSet<&str> = s.tools.presets.iter().map(|x| x.group.as_str()).collect();
free_group(&group, |g| groups.contains(g))
};
let mut taken = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str()));
let mut names = Vec::with_capacity(imp.presets.len());
for mut preset in imp.presets {
preset.group.clone_from(&group);
preset.name = taken.unique(&preset.name);
names.push(preset.name.clone());
s.tools.presets.push(preset);
@@ -243,7 +259,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Import Brushes…",
menu: &[],
shortcut: None,
params: r##"{"path":".abr file"?,"data":base64 bytes?,"group":string?=file name,"replace":bool=true (replace a group of the same name),"select":bool=false (make the first imported preset current)} → {group, imported, count, folders (nested folders kept from the file), version, warnings}"##,
params: r##"{"path":".abr file"?,"data":base64 bytes?,"group":string?=file name,"replace":bool=false (first delete the non-built-in presets of a group of the same name; false imports beside it as <group> (2)),"select":bool=false (make the first imported preset current)} → {group, imported, count, folders (nested folders kept from the file), version, warnings}"##,
enabled: always,
run: import_abr,
journal: true,
@@ -263,7 +279,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Import Gradients…",
menu: &[],
shortcut: None,
params: r##"{"path":".grd file"?,"data":base64 bytes?,"group":string?=file name,"replace":bool=true (replace a group of the same name)}"##,
params: r##"{"path":".grd file"?,"data":base64 bytes?,"group":string?=file name,"replace":bool=false (first delete a group of the same name; false imports beside it as <group> (2))} → {group, imported, count, warnings}"##,
enabled: always,
run: import_grd,
journal: true,
@@ -362,9 +378,13 @@ fn import_grd(s: &mut Session, p: &Value) -> Result<Value> {
}
let names: Vec<String> = items.iter().map(|g| g.name.clone()).collect();
let st = &mut s.presets;
if p.get("replace").and_then(Value::as_bool).unwrap_or(true) {
// As with brushes: a new group beside one of the same name unless `replace` (#10640).
let group = if p.get("replace").and_then(Value::as_bool).unwrap_or(false) {
st.gradients.retain(|g| g.name != group);
}
group
} else {
free_group(&group, |g| st.gradients.iter().any(|x| x.name == g))
};
st.gradients.push(Group::new(&group, items));
s.presets_changed();
Ok(json!({"group": group, "imported": names, "count": names.len(), "warnings": warnings}))
@@ -406,8 +426,8 @@ mod tests {
assert_eq!(s.tools.presets.len(), before + 2);
assert!(s.tools.presets.iter().filter(|p| p.group == "Legacy").all(|p| !p.builtin));
assert!(matches!(s.tools.brush.tip, photocraft_paint::TipShape::Sampled(_)));
// Re-import replaces the group.
s.execute("brush.presets.importAbr", json!({"data": data, "group": "Legacy"})).unwrap();
// Re-import with `replace` replaces the group.
s.execute("brush.presets.importAbr", json!({"data": data, "group": "Legacy", "replace": true})).unwrap();
assert_eq!(s.tools.presets.len(), before + 2);
// Imported presets paint.
s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
@@ -426,6 +446,40 @@ mod tests {
std::fs::remove_dir_all(&dir).ok();
}
/// Importing a file named like an existing group keeps that group's brushes, edited or moved
/// in ones included: the new brushes become "Kit (2)", "Kit (3)"… Only `replace` drops them (#10640).
#[test]
fn reimport_keeps_the_groups_brushes_unless_replace() {
let mut s = Session::new();
let data = photocraft_paint::tile::b64_encode(&abr_v2());
let builtin = s.tools.presets.iter().filter(|p| p.builtin).count();
s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit"})).unwrap();
// The user's own brush moved into the group.
let mut own = s.tools.presets.iter().find(|p| p.group == "Kit").unwrap().clone();
own.name = "My Ink".into();
s.tools.presets.push(own);
let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit"})).unwrap();
assert_eq!(r["group"], "Kit (2)");
let in_group = |s: &Session, g: &str| s.tools.presets.iter().filter(|p| p.group == g).count();
assert_eq!((in_group(&s, "Kit"), in_group(&s, "Kit (2)")), (3, 2));
let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit", "replace": false})).unwrap();
assert_eq!(r["group"], "Kit (3)");
assert!(s.tools.presets.iter().any(|p| p.name == "My Ink" && p.group == "Kit"));
// `replace` drops only that group's non-built-in presets.
let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit", "replace": true})).unwrap();
assert_eq!(r["group"], "Kit");
assert_eq!((in_group(&s, "Kit"), in_group(&s, "Kit (2)"), in_group(&s, "Kit (3)")), (2, 2, 2));
assert!(!s.tools.presets.iter().any(|p| p.name == "My Ink"));
assert_eq!(s.tools.presets.iter().filter(|p| p.builtin).count(), builtin);
}
#[test]
fn free_group_numbers_past_taken_names() {
let taken = ["Kit", "Kit (2)"];
assert_eq!(free_group("Set", |g| taken.contains(&g)), "Set");
assert_eq!(free_group("Kit", |g| taken.contains(&g)), "Kit (3)");
}
#[test]
fn bad_params_fail_gracefully() {
let mut s = Session::new();
@@ -472,10 +526,14 @@ mod tests {
let g = s.presets.gradients.iter().find(|g| g.name == "Fire").unwrap();
assert_eq!(g.items[0].stops, vec![(0.0, StopColor::Foreground), (1.0, StopColor::Rgb([1.0, 0.0, 0.0]))]);
assert_eq!(g.items[0].opacity, vec![(0.0, 1.0), (1.0, 0.0)]);
// Re-import replaces the group.
// Re-import adds a group beside it (#10640); with `replace` it replaces the group.
let n = s.presets.gradients.len();
s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Fire"})).unwrap();
assert_eq!(s.presets.gradients.len(), n);
let r = s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Fire"})).unwrap();
assert_eq!(r["group"], "Fire (2)");
assert_eq!(s.presets.gradients.len(), n + 1);
s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Fire", "replace": true})).unwrap();
assert_eq!(s.presets.gradients.len(), n + 1);
assert_eq!(s.presets.gradients.iter().filter(|g| g.name == "Fire").count(), 1);
for p in [json!({}), json!({"data": "@@"}), json!({"data": photocraft_paint::tile::b64_encode(b"8BGR\0\x03")}), json!({"path": "/nope.grd"})] {
assert!(s.execute("gradient.presets.importGrd", p.clone()).is_err(), "{p}");
}
+1 -1
View File
@@ -40,7 +40,7 @@ struct CompositeSampler<'a>(&'a Document);
impl Sampler for CompositeSampler<'_> {
fn rgba(&self, r: Rect) -> Vec<[f32; 4]> {
photocraft_compose::render(self.0, r).px
photocraft_compose::render(self.0, r).into_px()
}
}
+1 -1
View File
@@ -70,7 +70,7 @@ fn sample_pixels(s: &Session, all_layers: bool, window: Option<Rect>) -> Result<
surf.read_rgba_into(area, &mut px);
Ok((area, px))
}
_ => Ok((area, photocraft_compose::render(&d.doc, area).px)),
_ => Ok((area, photocraft_compose::render(&d.doc, area).into_px())),
}
}
@@ -39,7 +39,7 @@ pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photoc
let mut one = l.clone();
one.blend = BlendMode::Normal;
one.clipped = false;
photocraft_compose::render_layer(&one, bounds).px
photocraft_compose::render_layer(&one, bounds).into_px()
})
.collect();
if frames.is_empty() {
+1 -1
View File
@@ -110,7 +110,7 @@ fn paint(s: &mut Session) {
}
fn flat(s: &Session) -> Vec<[f32; 4]> {
photocraft_compose::flatten(&s.active().unwrap().doc).px
photocraft_compose::flatten(&s.active().unwrap().doc).into_px()
}
fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 {
+1 -1
View File
@@ -49,7 +49,7 @@ struct CompositeSampler<'a>(&'a Document);
impl Sampler for CompositeSampler<'_> {
fn rgba(&self, r: Rect) -> Vec<[f32; 4]> {
photocraft_compose::render(self.0, r).px
photocraft_compose::render(self.0, r).into_px()
}
}
@@ -366,7 +366,7 @@ fn off_from_fresh(s: &Session) -> f32 {
let st = s.active().unwrap();
let mut fresh: Document = (*st.doc).clone();
fresh.layer_mut(st.active_layer.unwrap()).unwrap().fill_cache = None;
let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).px, photocraft_compose::render(&fresh, fresh.bounds()).px);
let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).into_px(), photocraft_compose::render(&fresh, fresh.bounds()).into_px());
a.iter().zip(&b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs())).fold(0.0, f32::max)
}
+2 -2
View File
@@ -98,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Shape Layer",
["Layer", "New"],
leak(format!(
r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"##
r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":0..100=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"##
)),
has_doc,
shape_create
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Shape",
[],
leak(format!(
r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"##
r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":0..100? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"##
)),
has_layer,
shape_edit
+43 -5
View File
@@ -357,13 +357,51 @@ pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&L
}
"line" => {
let (pf, pto, pw) = match prev {
Some(LiveShape::Line { from, to, weight }) => (Some(*from), Some(*to), *weight),
Some(LiveShape::Line { from, to, weight }) | Some(LiveShape::ArrowLine { from, to, weight, .. }) => (Some(*from), Some(*to), *weight),
_ => (None, None, 1.0),
};
LiveShape::Line {
from: nums::<2>(p, "from").or(pf).ok_or_else(|| bad(cmd, "`from`: [x, y] is required"))?,
to: nums::<2>(p, "to").or(pto).ok_or_else(|| bad(cmd, "`to`: [x, y] is required"))?,
weight: f64p(p, "weight").unwrap_or(pw).max(0.0),
let from = nums::<2>(p, "from").or(pf).ok_or_else(|| bad(cmd, "`from`: [x, y] is required"))?;
let to = nums::<2>(p, "to").or(pto).ok_or_else(|| bad(cmd, "`to`: [x, y] is required"))?;
let weight = f64p(p, "weight").unwrap_or(pw).max(0.0);
let arrow_fields = ["arrowStart", "arrowEnd", "arrowWidth", "arrowLength", "arrowConcavity"];
let is_arrow = matches!(prev, Some(LiveShape::ArrowLine { .. })) || arrow_fields.iter().any(|k| p.get(*k).is_some());
if is_arrow {
let (ps, pe, pwidth, plen, pc) = match prev {
Some(LiveShape::ArrowLine { start, end, width, length, concavity, .. }) => (*start, *end, *width, *length, *concavity),
_ => (false, false, 52.0, 50.0, 0.0),
};
let dim = |key: &str, fallback: f64, min: f64, max: f64| -> Result<f64> {
let value = match p.get(key) {
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be numeric")))?,
None => fallback,
};
// Preserve scaled arrowhead dimensions when editing other properties.
let preserved_scaled_size = p.get(key).is_none() && matches!(key, "arrowWidth" | "arrowLength") && value.is_finite();
let value = if preserved_scaled_size { value.max(min) } else { value };
if !value.is_finite() || (!preserved_scaled_size && !(min..=max).contains(&value)) {
return Err(bad(cmd, format!("`{key}` must be within {min}..={max}")));
}
Ok(value)
};
// Reject invalid flag types rather than silently using defaults.
let flag = |key: &str, fallback: bool| -> Result<bool> {
match p.get(key) {
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, format!("`{key}` must be a boolean"))),
None => Ok(fallback),
}
};
LiveShape::ArrowLine {
from,
to,
weight,
start: flag("arrowStart", ps)?,
end: flag("arrowEnd", pe)?,
width: dim("arrowWidth", pwidth, 1.0, 4096.0)?,
length: dim("arrowLength", plen, 1.0, 4096.0)?,
concavity: dim("arrowConcavity", pc, 0.0, 100.0)?,
}
} else {
LiveShape::Line { from, to, weight }
}
}
o => return Err(bad(cmd, format!("unknown kind `{o}`"))),
+268 -2
View File
@@ -80,7 +80,7 @@ fn live_kind(l: &LiveShape) -> &'static str {
LiveShape::Ellipse { .. } => "ellipse",
LiveShape::Polygon { star_ratio, .. } if *star_ratio < 1.0 => "star",
LiveShape::Polygon { .. } => "polygon",
LiveShape::Line { .. } => "line",
LiveShape::Line { .. } | LiveShape::ArrowLine { .. } => "line",
}
}
@@ -148,12 +148,61 @@ pub(crate) fn shift_shape(doc: &Document, sh: &mut ShapeLayer, dx: f64, dy: f64)
}
}
/// Returns arrow-local scales when the transformed axes remain perpendicular.
fn arrow_axis_scales(a: &Affine, from: [f64; 2], to: [f64; 2]) -> Option<(f64, f64)> {
let [m0, m1, m2, m3, _, _] = a.m;
let (dx, dy) = (to[0] - from[0], to[1] - from[1]);
let old_length = dx.hypot(dy);
if !old_length.is_finite() || old_length <= 1e-12 {
return None;
}
let (ux, uy) = (dx / old_length, dy / old_length);
let (ax, ay) = (m0 * ux + m2 * uy, m1 * ux + m3 * uy);
let (px, py) = (-m0 * uy + m2 * ux, -m1 * uy + m3 * ux);
let axial = ax.hypot(ay);
let perpendicular = px.hypot(py);
if !axial.is_finite() || !perpendicular.is_finite() || axial <= 1e-12 || perpendicular <= 1e-12 {
return None;
}
let dot = ax * px + ay * py;
(dot.abs() <= 1e-10 * axial * perpendicular).then_some((axial, perpendicular))
}
/// Applies an affine transform to a shape's path, keeping the live shape when the transform
/// is a translation plus axis-aligned scale (otherwise the shape stops being parametric).
pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {
// Check original arrow dimensions before transforming the path.
// Parameters already clamped by arrow_line cannot faithfully
// regenerate the transformed geometry.
if let Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, .. }) = sh.live.as_ref()
&& (*start || *end)
{
let original_length = (to[0] - from[0]).hypot(to[1] - from[1]);
if !weight.is_finite()
|| *weight < 0.1
|| !width.is_finite()
|| *width < 1.0
|| !length.is_finite()
|| *length < 1.0
|| !original_length.is_finite()
|| original_length < 1.0
{
sh.live = None;
}
}
sh.path = sh.path.transform(a);
let [m0, m1, m2, m3, tx, ty] = a.m;
let axis_aligned = m1.abs() < 1e-12 && m2.abs() < 1e-12 && m0 > 0.0 && m3 > 0.0;
// The path has already received the exact affine transform. Drop live arrow
// parameters if later edits would regenerate a different, unskewed head.
if let Some(LiveShape::ArrowLine { from, to, .. }) = sh.live.as_ref()
&& (to[0] - from[0]).hypot(to[1] - from[1]) > 1e-12
&& arrow_axis_scales(a, *from, *to).is_none()
{
sh.live = None;
}
sh.live = match (sh.live.take(), axis_aligned) {
(Some(l), true) => {
let r = |r: [f64; 4]| [r[0] * m0 + tx, r[1] * m3 + ty, r[2] * m0, r[3] * m3];
@@ -167,6 +216,22 @@ pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {
LiveShape::Polygon { rect, sides, star_ratio, corner_radius } => {
LiveShape::Polygon { rect: r(rect), sides, star_ratio, corner_radius: corner_radius * m0.min(m3) }
}
LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity } => {
let (dx, dy) = (to[0] - from[0], to[1] - from[1]);
let old_len = dx.hypot(dy);
let new_len = (dx * m0).hypot(dy * m3);
let perpendicular_scale = if old_len > 0.0 && new_len > 0.0 { m0 * m3 * old_len / new_len } else { m0.min(m3) };
LiveShape::ArrowLine {
from: pt(from),
to: pt(to),
weight: weight * perpendicular_scale,
start,
end,
width: width * perpendicular_scale,
length: length * if old_len > 0.0 { new_len / old_len } else { m0.min(m3) },
concavity,
}
}
LiveShape::Line { from, to, weight } => {
// Live-shape edits regenerate the line's filled bar from its parameters.
// Keep the weight in sync with a positive scale of the path, or an
@@ -195,11 +260,61 @@ pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {
}
LiveShape::Ellipse { rect } => Some(LiveShape::Ellipse { rect: r(rect) }),
LiveShape::Line { from, to, weight } => Some(LiveShape::Line { from: pt(from), to: pt(to), weight: weight * k }),
LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity } => {
// Flips and quarter-turns can have different axial and perpendicular
// scales; using the smaller axis for both loses arrowhead length.
let (axial_scale, perpendicular_scale) = arrow_axis_scales(a, from, to).unwrap_or((k, k));
Some(LiveShape::ArrowLine {
from: pt(from),
to: pt(to),
weight: weight * perpendicular_scale,
start,
end,
width: width * perpendicular_scale,
length: length * axial_scale,
concavity,
})
}
_ => None,
}
}
// Arbitrary rotations and other orthogonal-axis affine transforms also
// preserve arrow geometry and should keep their editable live parameters.
(Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity }), false) => {
arrow_axis_scales(a, from, to).map(|(axial_scale, perpendicular_scale)| {
let pt = |p: [f64; 2]| [m0 * p[0] + m2 * p[1] + tx, m1 * p[0] + m3 * p[1] + ty];
LiveShape::ArrowLine {
from: pt(from),
to: pt(to),
weight: weight * perpendicular_scale,
start,
end,
width: width * perpendicular_scale,
length: length * axial_scale,
concavity,
}
})
}
_ => None,
};
// Keep the exact transformed outline. Remove live arrow parameters
// when minimum-size constraints would alter its regenerated geometry.
if let Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, .. }) = sh.live.as_ref()
&& (*start || *end)
{
let line_length = (to[0] - from[0]).hypot(to[1] - from[1]);
if !weight.is_finite()
|| *weight < 0.1
|| !width.is_finite()
|| *width < 1.0
|| !length.is_finite()
|| *length < 1.0
|| !line_length.is_finite()
|| line_length < 1.0
{
sh.live = None;
}
}
sh.psd_raw = None;
}
@@ -360,7 +475,23 @@ pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result<Value> {
sh.live = None;
sh.psd_raw = None;
}
let geom_keys = ["kind", "rect", "radii", "radius", "sides", "starRatio", "cornerRadius", "from", "to", "weight"];
let geom_keys = [
"kind",
"rect",
"radii",
"radius",
"sides",
"starRatio",
"cornerRadius",
"from",
"to",
"weight",
"arrowStart",
"arrowEnd",
"arrowWidth",
"arrowLength",
"arrowConcavity",
];
if geom_keys.iter().any(|k| p.get(*k).is_some()) {
let kind = p.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| sh.live.as_ref().map(|l| live_kind(l).to_string()));
let kind = kind.ok_or_else(|| bad(CMD, "this shape has no live-shape parameters; pass `kind` or `path`"))?;
@@ -572,3 +703,138 @@ pub(super) fn selection_to_shape(s: &mut Session, p: &Value) -> Result<Value> {
}
shape_create(s, &q)
}
#[cfg(test)]
mod arrow_affine_regression_tests {
use super::*;
#[test]
fn forty_five_degree_rotation_retains_live_arrow_and_geometry() {
let live =
LiveShape::ArrowLine { from: [0.0, 0.0], to: [100.0, 0.0], weight: 8.0, start: false, end: true, width: 31.0, length: 31.0, concavity: 50.0 };
let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() };
let mut a = Affine::translate(0.0, 0.0);
let c = std::f64::consts::FRAC_PI_4.cos();
let s = std::f64::consts::FRAC_PI_4.sin();
a.m = [c, s, -s, c, 0.0, 0.0];
transform_shape(&mut sh, &a);
let Some(LiveShape::ArrowLine { width, length, .. }) = sh.live.as_ref() else {
panic!("Arrow must remain parametrically editable after 45-degree rotation");
};
assert!((*width - 31.0).abs() < 1e-9);
assert!((*length - 31.0).abs() < 1e-9);
let rebuilt = vector::shapes::live_path(sh.live.as_ref().unwrap());
assert_eq!(sh.path.subpaths.len(), rebuilt.subpaths.len());
for (existing, generated) in sh.path.subpaths.iter().zip(rebuilt.subpaths.iter()) {
assert_eq!(existing.knots.len(), generated.knots.len());
for (a, b) in existing.knots.iter().zip(generated.knots.iter()) {
assert!((a.anchor.x - b.anchor.x).abs() < 1e-8);
assert!((a.anchor.y - b.anchor.y).abs() < 1e-8);
}
}
}
#[test]
fn subpixel_scale_keeps_transformed_path_but_drops_unreproducible_live_parameters() {
let live = LiveShape::ArrowLine { from: [0.0, 0.0], to: [100.0, 0.0], weight: 5.0, start: false, end: true, width: 31.0, length: 31.0, concavity: 0.0 };
let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() };
let mut a = Affine::translate(0.0, 0.0);
a.m = [0.01, 0.0, 0.0, 0.01, 0.0, 0.0];
let expected_path = sh.path.transform(&a);
transform_shape(&mut sh, &a);
assert_eq!(sh.path, expected_path);
assert!(sh.live.is_none());
}
#[test]
fn headless_arrow_survives_nonuniform_diagonal_scale() {
let live =
LiveShape::ArrowLine { from: [0.0, 0.0], to: [100.0, 100.0], weight: 5.0, start: false, end: false, width: 52.0, length: 50.0, concavity: 0.0 };
let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() };
let mut a = Affine::translate(0.0, 0.0);
a.m = [2.0, 0.0, 0.0, 1.0, 0.0, 0.0];
let expected_path = sh.path.transform(&a);
transform_shape(&mut sh, &a);
assert_eq!(sh.path, expected_path);
assert!(sh.live.is_none());
}
#[test]
fn zero_length_headless_arrow_survives_scale() {
let live = LiveShape::ArrowLine { from: [0.0, 0.0], to: [0.0, 0.0], weight: 5.0, start: false, end: false, width: 52.0, length: 50.0, concavity: 0.0 };
let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() };
let mut a = Affine::translate(0.0, 0.0);
a.m = [2.0, 0.0, 0.0, 1.0, 0.0, 0.0];
let expected_path = sh.path.transform(&a);
transform_shape(&mut sh, &a);
assert_eq!(sh.path, expected_path);
assert!(matches!(sh.live, Some(LiveShape::ArrowLine { start: false, end: false, .. })));
}
#[test]
fn headless_short_arrow_remains_editable_after_scaling() {
let live = LiveShape::ArrowLine { from: [0.0, 0.0], to: [0.5, 0.0], weight: 0.05, start: false, end: false, width: 31.0, length: 31.0, concavity: 0.0 };
let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() };
let mut a = Affine::translate(0.0, 0.0);
a.m = [0.5, 0.0, 0.0, 0.5, 0.0, 0.0];
let expected = sh.path.transform(&a);
transform_shape(&mut sh, &a);
assert_eq!(sh.path, expected);
assert!(matches!(sh.live, Some(LiveShape::ArrowLine { start: false, end: false, .. })));
}
#[test]
fn scale_above_minimum_still_keeps_live_arrow_editable() {
let live = LiveShape::ArrowLine { from: [0.0, 0.0], to: [100.0, 0.0], weight: 5.0, start: false, end: true, width: 31.0, length: 31.0, concavity: 0.0 };
let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() };
let mut a = Affine::translate(0.0, 0.0);
a.m = [0.5, 0.0, 0.0, 0.5, 0.0, 0.0];
transform_shape(&mut sh, &a);
let Some(LiveShape::ArrowLine { width, length, .. }) = sh.live else {
panic!("Ordinary scaling must preserve editable arrow parameters");
};
assert!((width - 15.5).abs() < 1e-9);
assert!((length - 15.5).abs() < 1e-9);
}
#[test]
fn reflected_horizontal_arrow_uses_axial_scale_for_head_length() {
let mut a = Affine::translate(0.0, 0.0);
a.m = [-2.0, 0.0, 0.0, 1.0, 0.0, 0.0];
let (axial, perpendicular) = arrow_axis_scales(&a, [0.0, 0.0], [100.0, 0.0]).unwrap();
assert!((axial - 2.0).abs() < 1e-10);
assert!((perpendicular - 1.0).abs() < 1e-10);
}
#[test]
fn anisotropic_diagonal_arrow_cannot_remain_parametric() {
let mut a = Affine::translate(0.0, 0.0);
a.m = [2.0, 0.0, 0.0, 1.0, 0.0, 0.0];
assert!(arrow_axis_scales(&a, [0.0, 0.0], [100.0, 100.0]).is_none());
}
#[test]
fn uniform_scale_preserves_diagonal_arrow_axes() {
let mut a = Affine::translate(0.0, 0.0);
a.m = [2.0, 0.0, 0.0, 2.0, 0.0, 0.0];
let (axial, perpendicular) = arrow_axis_scales(&a, [0.0, 0.0], [100.0, 100.0]).unwrap();
assert!((axial - 2.0).abs() < 1e-10);
assert!((perpendicular - 2.0).abs() < 1e-10);
}
}
+144
View File
@@ -1238,3 +1238,147 @@ fn triangles_and_polygons_take_a_corner_radius_kept_through_edits_and_scaling()
s.execute("shape.edit", json!({"layer": id, "transform": [0.5, 0, 0, 0.5, 0, 0]})).unwrap();
assert!(matches!(live(&s), Some(LiveShape::Polygon { corner_radius, .. }) if (corner_radius - 5.0).abs() < 1e-9));
}
#[test]
fn arrowhead_flags_reject_wrong_types_without_mutation() {
let mut s = session(160, 120, 8);
let id = s
.execute(
"shape.create",
json!({
"kind": "line",
"from": [10, 20],
"to": [120, 20],
"arrowStart": true,
"arrowEnd": false
}),
)
.unwrap()["layer"]
.as_u64()
.unwrap();
let original_doc = s.active().unwrap().doc.clone();
let original_history = s.active().unwrap().history.past_len();
for key in ["arrowStart", "arrowEnd"] {
for invalid in [json!("true"), json!(null), json!(1), json!([])] {
let mut create = json!({
"kind": "line",
"from": [10, 40],
"to": [120, 40]
});
create[key] = invalid.clone();
assert!(s.execute("shape.create", create).is_err(), "{key} must reject {invalid}");
let mut edit = json!({"layer": id});
edit[key] = invalid.clone();
assert!(s.execute("shape.edit", edit).is_err(), "{key} edit must reject {invalid}");
assert_eq!(s.active().unwrap().doc, original_doc);
assert_eq!(s.active().unwrap().history.past_len(), original_history);
}
}
// Valid boolean values remain accepted.
s.execute(
"shape.edit",
json!({
"layer": id,
"arrowStart": false,
"arrowEnd": true
}),
)
.unwrap();
}
#[test]
fn arrowhead_dimensions_reject_invalid_values_without_mutation() {
let mut s = session(160, 120, 8);
let id = s
.execute(
"shape.create",
json!({
"kind": "line",
"from": [10, 20],
"to": [120, 20],
"arrowEnd": true
}),
)
.unwrap()["layer"]
.as_u64()
.unwrap();
let original_doc = s.active().unwrap().doc.clone();
let original_history = s.active().unwrap().history.past_len();
for (key, invalids) in [
("arrowWidth", [json!("52"), json!(null), json!([]), json!(0), json!(4097)]),
("arrowLength", [json!("50"), json!(null), json!([]), json!(0), json!(4097)]),
("arrowConcavity", [json!("0"), json!(null), json!([]), json!(-1), json!(101)]),
] {
for invalid in invalids {
let mut create = json!({
"kind": "line",
"from": [10, 40],
"to": [120, 40]
});
create[key] = invalid.clone();
assert!(s.execute("shape.create", create).is_err(), "{key} create must reject {invalid}");
assert_eq!(s.active().unwrap().doc, original_doc, "{key} create changed document");
assert_eq!(s.active().unwrap().history.past_len(), original_history, "{key} create changed history");
let mut edit = json!({"layer": id});
edit[key] = invalid.clone();
assert!(s.execute("shape.edit", edit).is_err(), "{key} edit must reject {invalid}");
assert_eq!(s.active().unwrap().doc, original_doc, "{key} edit changed document");
assert_eq!(s.active().unwrap().history.past_len(), original_history, "{key} edit changed history");
}
}
}
#[test]
fn headless_diagonal_arrow_preserves_geometry_after_nonuniform_scale() {
let mut s = session(400, 400, 8);
let created = s
.execute(
"shape.create",
json!({
"kind": "line",
"from": [40.0, 40.0],
"to": [140.0, 140.0],
"weight": 5.0,
"arrowStart": false,
"arrowEnd": false
}),
)
.unwrap();
let id = created["layer"].as_u64().unwrap();
let transformed = s
.execute(
"shape.edit",
json!({
"layer": id,
"transform": [2.0, 0.0, 0.0, 1.0, 0.0, 0.0]
}),
)
.unwrap();
assert_ne!(transformed["path"], created["path"]);
assert!(transformed["live"].is_null());
let before = s.active().unwrap().doc.clone();
// Editing live parameters must not regenerate a different shape.
assert!(s.execute("shape.edit", json!({"layer": id, "weight": 8.0}),).is_err());
assert_eq!(s.active().unwrap().doc, before);
let info = s.execute("shape.info", json!({"layer": id})).unwrap();
assert_eq!(info["path"], transformed["path"]);
}
+1 -1
View File
@@ -229,7 +229,7 @@ fn animated_gif_keeps_transparency() {
// Each frame has a transparent index and is cleared before the next (disposal 2).
let packed: Vec<u8> = gif.windows(4).filter(|w| w[..3] == [0x21, 0xF9, 0x04]).map(|w| w[3]).collect();
assert_eq!(packed, [0x09, 0x09]);
let px = photocraft_compose::flatten(&photocraft_io::import("t.gif", &gif).unwrap().document).px;
let px = photocraft_compose::flatten(&photocraft_io::import("t.gif", &gif).unwrap().document).into_px();
assert_eq!(px[0][3], 0.0, "the corner stays transparent");
assert_eq!(px[3 * 8 + 3], [1.0, 0.0, 0.0, 1.0], "the square stays red");
}
+1 -1
View File
@@ -61,7 +61,7 @@ pub(super) fn adjust(surface: &mut Surface, colors: ColorChannels, adjustment: &
.collect(),
};
adjust::apply_in(&scalar, &mut buf, transfer, depth, mode);
Arc::new(IntegerTable { adjusted: buf.px.into_iter().map(|p| p[0]).collect(), encoded: Vec::new() })
Arc::new(IntegerTable { adjusted: buf.px.iter().map(|p| p[0]).collect(), encoded: Vec::new() })
})
});
let mut component = Component { index, scalar, table, lab_invert };
+3 -3
View File
@@ -157,7 +157,7 @@ fn replayed(s: &mut Session, id: LayerId, params: serde_json::Value) -> Vec<[f32
})
.unwrap();
let doc = &s.active().unwrap().doc;
photocraft_compose::render(doc, doc.bounds()).px
photocraft_compose::render(doc, doc.bounds()).into_px()
}
#[test]
@@ -202,12 +202,12 @@ fn smart_displace_keeps_a_relative_map_path() {
png(&d.join("map.png"), |_| [255, 255, 255]);
let (mut s, id) = document(&d, &d.join("ramp.png"));
let path = d.join("map.png").to_string_lossy().into_owned();
let unfiltered = photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()).px;
let unfiltered = photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()).into_px();
s.execute("filter.distort.displace", json!({"layer": id.0, "mapPath": path, "horizontal": 50, "vertical": 0})).unwrap();
let state = |s: &Session| {
let doc = &s.active().unwrap().doc;
let Some(LayerContent::Smart(sm)) = doc.layer(id).map(|l| &l.content) else { panic!("a smart object") };
(sm.smart_filters[0].params.clone(), photocraft_compose::render(doc, doc.bounds()).px)
(sm.smart_filters[0].params.clone(), photocraft_compose::render(doc, doc.bounds()).into_px())
};
let (params, displaced) = state(&s);
assert_eq!(params["mapPath"], json!(path));
+2
View File
@@ -397,6 +397,8 @@ pub(crate) fn keep_alpha(old: &photocraft_raster::Surface, new: &mut photocraft_
}
}
s.write_region(*r, &v);
photocraft_raster::scratch::give(o);
photocraft_raster::scratch::give(v);
true
})
.reduce(|| true, |a, b| a && b);
+50 -9
View File
@@ -277,6 +277,16 @@ impl Running {
}
}
/// A cancelled job's worker that may still be unwinding.
#[cfg(not(target_arch = "wasm32"))]
struct Draining {
handle: std::thread::JoinHandle<()>,
doc: Option<DocId>,
/// Its document closed: the worker still holds that document's snapshot, so the scratch
/// pool is released again once it exits (the release at close came too early, #10479).
release: bool,
}
/// The session's job table (see the module docs).
#[derive(Default)]
pub struct Jobs {
@@ -292,7 +302,7 @@ pub struct Jobs {
recent: Vec<JobInfo>,
/// Workers of cancelled jobs that may still be unwinding (native).
#[cfg(not(target_arch = "wasm32"))]
draining: Vec<std::thread::JoinHandle<()>>,
draining: Vec<Draining>,
/// The context inline job work runs under (see [`Session::set_inline_job_ctx`]).
inline: Option<JobCtx>,
}
@@ -673,7 +683,17 @@ impl Session {
}
}
#[cfg(not(target_arch = "wasm32"))]
self.jobs.draining.retain(|h| !h.is_finished());
{
let mut release = false;
self.jobs.draining.retain(|d| {
let done = d.handle.is_finished();
release |= done && d.release;
!done
});
if release {
photocraft_raster::scratch::release();
}
}
std::mem::take(&mut self.jobs.events)
}
@@ -706,8 +726,8 @@ impl Session {
job.ctx.cancel();
self.end_job(&job, JobOutcome::Cancelled);
#[cfg(not(target_arch = "wasm32"))]
if let Some(h) = job.handle {
self.jobs.draining.push(h);
if let Some(handle) = job.handle {
self.jobs.draining.push(Draining { handle, doc: job.doc, release: false });
}
true
}
@@ -754,8 +774,15 @@ impl Session {
/// cancel latency with it). Native only; returns at once on wasm.
pub fn join_cancelled_jobs(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
for h in self.jobs.draining.drain(..) {
let _ = h.join();
{
let mut release = false;
for d in self.jobs.draining.drain(..) {
let _ = d.handle.join();
release |= d.release;
}
if release {
photocraft_raster::scratch::release();
}
}
}
@@ -774,6 +801,11 @@ impl Session {
for id in ids {
self.cancel_job(id);
}
// Workers cancelled now, or earlier and still unwinding, hold the closing document.
#[cfg(not(target_arch = "wasm32"))]
for d in self.jobs.draining.iter_mut().filter(|d| d.doc == Some(doc)) {
d.release = true;
}
}
/// Run the command `id`: inline, or (with `background`) as a job when it is one.
@@ -857,6 +889,7 @@ impl Session {
// being recorded, nor move the recording mark past the entries it is about to replace.
let recording = if spec.journal && crate::actions_cmds::replayable(id) { self.actions.recording.take() } else { None };
let before = self.active().map(|st| st.doc.clone());
let docs_before: Vec<_> = self.docs.iter().map(|st| st.doc.id).collect();
// Last-resort guard (AGENTS.md, Never crash): a command that panics anyway fails with an
// error instead of taking the app down. `edit` only commits a document after its closure
// returns, so the documents are unchanged.
@@ -876,7 +909,7 @@ impl Session {
self.hint_before = None;
}
let pending = self.jobs.pending.take();
match (r, pending) {
let out = match (r, pending) {
(Err(e), Some(job)) => {
job.ctx.cancel();
Err(e)
@@ -893,8 +926,8 @@ impl Session {
Ok(Started::Job(jid))
}
(Ok(v), None) => {
if let Some(before) = before {
self.add_relayout_damage(&before);
if let Some(before) = &before {
self.add_relayout_damage(before);
}
if let Some((doc_id, layer_id)) = new_fx_target
&& let Some(st) = self.active_mut()
@@ -910,7 +943,15 @@ impl Session {
self.after_command(id, params, spec.journal, Some(nested_from), pre_selected.as_deref());
Ok(Started::Done(v))
}
};
// A closed document's freed buffers went to the scratch pool (`before` kept the active
// one alive until here): hand them back to the OS (#10479). Compared by id, since Split
// and Merge Channels close documents while opening others.
if docs_before.iter().any(|id| !self.docs.iter().any(|st| st.doc.id == *id)) {
drop(before);
photocraft_raster::scratch::release();
}
out
}
/// Grows the damage a command reported for the pixels it changed by what effects laid out
+1
View File
@@ -29,6 +29,7 @@ pub mod kys;
pub mod layer_place;
pub mod layer_style;
pub mod link_watch;
pub mod malloc_tuning;
pub mod new_layer;
mod param_check;
mod pixels;
+81
View File
@@ -0,0 +1,81 @@
//! glibc malloc tuning for the native binaries (#8743).
//!
//! With glibc's defaults, the memory of a closed document stays with the process: freeing a large
//! buffer raises glibc's dynamic mmap threshold (up to 32 MiB), so later tile buffers come from the
//! heap, whose freed pages glibc keeps for reuse instead of giving them back. A session that opened
//! and closed a 5400 × 7200 document held ~540 MiB afterwards; with `MALLOC_TRIM_THRESHOLD_` set it
//! went back to ~20 MiB, and the peak was lower too. Setting the threshold explicitly turns the
//! dynamic adjustment off (mallopt(3)), so large buffers are mapped and unmapped on their own and
//! the heap top is trimmed as it is freed. Mapping fresh pages on every call is slow, so the large
//! short-lived buffers come from `photocraft_raster::scratch` instead, which reuses them and
//! releases them when a document closes or the pool goes idle (#10479).
//!
//! glibc reads its tunables once, when the process starts, and changing the environment from Rust
//! needs `unsafe` (and comes too late), so [`apply`] re-executes the binary with the variable set:
//! the same process (PID), arguments, `argv[0]` and environment, on Linux with glibc only. A value
//! the user or a package already set, for this or another malloc tunable, is left alone, so setting
//! `MALLOC_TRIM_THRESHOLD_` to anything opts out. Programs PhotoCraft starts inherit the variable.
use std::ffi::OsString;
/// The glibc environment variable [`apply`] sets.
pub const TRIM_THRESHOLD_VAR: &str = "MALLOC_TRIM_THRESHOLD_";
/// Its value: glibc's own default trim threshold (128 KiB), now fixed instead of dynamic.
pub const TRIM_THRESHOLD: &str = "131072";
/// glibc malloc variables that mean someone tuned malloc themselves.
const MALLOC_VARS: [&str; 5] = [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX"];
/// Whether a start-up should re-execute with [`TRIM_THRESHOLD_VAR`] set, given the environment:
/// only when no malloc variable or `glibc.malloc.*` tunable is set (which also ends the re-exec).
pub fn needs_restart(var: impl Fn(&str) -> Option<OsString>) -> bool {
if MALLOC_VARS.iter().any(|v| var(v).is_some()) {
return false;
}
!var("GLIBC_TUNABLES").is_some_and(|t| t.to_string_lossy().contains("glibc.malloc."))
}
/// Re-execute this binary with [`TRIM_THRESHOLD_VAR`] set when [`needs_restart`] says so. Call it
/// first in `main`, before any thread starts. It returns only when nothing needed to change or the
/// re-exec failed, and then the process carries on with glibc's defaults.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub fn apply() {
use std::os::unix::process::CommandExt;
if !needs_restart(|k| std::env::var_os(k)) {
return;
}
let Ok(exe) = std::env::current_exe() else { return };
let mut args = std::env::args_os();
let mut cmd = std::process::Command::new(exe);
if let Some(argv0) = args.next() {
cmd.arg0(argv0);
}
// `exec` replaces the process and only returns on failure.
let err = cmd.args(args).env(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD).exec();
eprintln!("PhotoCraft: could not restart with {TRIM_THRESHOLD_VAR} set ({err}); memory of closed documents may not be returned to the system");
}
/// Nothing to tune off glibc.
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
pub fn apply() {}
#[cfg(test)]
mod tests {
use super::*;
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
}
#[test]
fn restarts_only_without_malloc_tuning() {
assert!(needs_restart(env(&[])));
assert!(needs_restart(env(&[("HOME", "/home/a"), ("GLIBC_TUNABLES", "glibc.cpu.hwcaps=-AVX2")])));
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD)])), "the re-executed process stops");
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, "")])), "any value opts out");
assert!(!needs_restart(env(&[("MALLOC_MMAP_THRESHOLD_", "1048576")])));
assert!(!needs_restart(env(&[("MALLOC_ARENA_MAX", "2")])));
assert!(!needs_restart(env(&[("GLIBC_TUNABLES", "glibc.malloc.trim_threshold=0")])));
}
}
+10 -3
View File
@@ -115,6 +115,7 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surf
let tr = tc.rect().intersect(&r);
let out = adjusted(&one, tr, adj, selection, mode);
one.write_region(tr, &out);
photocraft_raster::scratch::give(out);
one.take_tiles(tc.rect())
})
.collect();
@@ -184,6 +185,7 @@ pub(crate) fn adjust_mask_with_transfer(
for t in &tiles {
let out = adjusted_with_transfer(s, *t, adj, Some(sel), mode, transfer);
s.write_region(*t, &out);
photocraft_raster::scratch::give(out);
}
if !tiles.is_empty() {
s.prune();
@@ -197,7 +199,9 @@ pub(crate) fn adjust_mask_with_transfer(
// So only the stored tiles are adjusted, not the (possibly huge) rectangle around them.
let stored: Vec<Rect> = s.tiles().map(|(c, _)| c.rect()).collect();
for r in stored {
out.write_region(r, &adjusted_with_transfer(s, r, adj, None, mode, transfer));
let data = adjusted_with_transfer(s, r, adj, None, mode, transfer);
out.write_region(r, &data);
photocraft_raster::scratch::give(data);
}
out.prune();
*s = out;
@@ -233,7 +237,10 @@ fn adjusted_with_transfer(
}
let n = fmt.channels();
let raw = s.read_region(r);
let mut buf = Buffer { rect: r, px: raw.chunks_exact(n).map(|p| to_rgba(&fmt, p)).collect() };
let mut px = photocraft_raster::scratch::take_cap(raw.len() / n.max(1));
px.extend(raw.chunks_exact(n).map(|p| to_rgba(&fmt, p)));
photocraft_raster::scratch::give(raw);
let mut buf = Buffer { rect: r, px };
let orig = buf.clone();
// 32-bit documents get the float behaviour of an adjustment layer there (Levels doesn't clip);
// integer depths keep the unrounded, clipped curves, except that 16-bit Posterize and
@@ -311,7 +318,7 @@ pub(crate) fn mix_through_selection(
selection: Option<&Surface>,
) -> Vec<f32> {
let w = (r.width() as usize).max(1);
let mut out = Vec::with_capacity(orig.len() * fmt.channels());
let mut out = photocraft_raster::scratch::take_cap(orig.len() * fmt.channels());
// The selection's coverage (channel 0) one row at a time, each of its tiles looked up once
// per row rather than once per pixel.
let mut coverage = vec![1.0f32; w];
+3 -2
View File
@@ -295,7 +295,8 @@ pub struct Interface {
pub show_bounding_box_when_dragging_layer: bool,
/// Windows and Linux: use the system's title bar and window buttons instead of PhotoCraft's
/// own one-row title bar (tiling window managers, desktops that draw their own decorations;
/// #1271, #1316). Read when the app starts. macOS always uses the system's.
/// #1271, #1316). The integrated title bar remains the default on Linux and Windows;
/// the system frame is opt-in. Read when the app starts. macOS always uses the system's.
pub system_title_bar: bool,
/// Show the active document's file name in the title bar and the OS window title. The tabs
/// already name the file, so this can be turned off for a plain "PhotoCraft" title (#5037).
@@ -449,7 +450,7 @@ pub use shortcuts::{
reserved_shortcut,
};
use store::read_lenient;
pub use store::{InvalidPref, PREFS_VERSION, PrefsStore};
pub use store::{InvalidPref, PREFS_VERSION, PrefsStore, read_section};
pub use validate::{HIDDEN_UNTIL_IMPLEMENTED, LINUX_ONLY, SECTIONS, choices, gpu_adapter_matches, is_color, is_hidden, parse_hex, range};
use validate::{check_value, get_path, keyed, set_path};
+10
View File
@@ -75,6 +75,16 @@ where
}
}
/// One section of a preferences file (`performance`, …) read as [`Session::load_prefs_json`]
/// reads it: a value of the wrong type keeps its default and the rest still loads (#6611).
/// Startup reads the graphics settings with it before a session exists.
pub fn read_section<T>(v: Value) -> T
where
T: Default + Serialize + for<'de> Deserialize<'de>,
{
read_lenient(v, &[], &mut Vec::new())
}
/// [`read_lenient`]'s walk: lay `file` over the object at `at` inside `root`, key by key, so that
/// `root` always reads (`fits`).
fn lay_over(
+16
View File
@@ -1,5 +1,21 @@
use super::*;
#[test]
fn system_title_bar_defaults_to_integrated_and_preserves_saved_choices() {
let default = false;
assert_eq!(Interface::default().system_title_bar, default);
for saved in [json!({}), json!({"interface": {}})] {
let prefs: Preferences = serde_json::from_value(saved).unwrap();
assert_eq!(prefs.interface.system_title_bar, default);
}
for saved in [false, true] {
let prefs: Preferences = serde_json::from_value(json!({"interface": {"systemTitleBar": saved}})).unwrap();
assert_eq!(prefs.interface.system_title_bar, saved);
let restored: Preferences = serde_json::from_value(prefs.to_json()).unwrap();
assert_eq!(restored.interface.system_title_bar, saved);
}
}
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
+3 -1
View File
@@ -239,7 +239,9 @@ fn invert(base: Option<&Surface>, canvas: Rect) -> Option<Surface> {
if r.is_empty() {
continue;
}
let inverted: Vec<f32> = b.read_region(r).chunks_exact(ch).map(|px| 1.0 - px.first().copied().unwrap_or(0.0).clamp(0.0, 1.0)).collect();
let read = b.read_region(r);
let inverted: Vec<f32> = read.chunks_exact(ch).map(|px| 1.0 - px.first().copied().unwrap_or(0.0).clamp(0.0, 1.0)).collect();
photocraft_raster::scratch::give(read);
s.write_region(r, &inverted);
}
}
+2 -2
View File
@@ -814,7 +814,7 @@ fn fill_layer_pixel_rewrites_refresh_the_effect_maps() {
.unwrap();
let render = |s: &Session| {
let d = &s.active().unwrap().doc;
photocraft_compose::render(d, d.bounds()).px
photocraft_compose::render(d, d.bounds()).into_px()
};
// Give the layer the cached-pixels state a PSD import produces (the cache is what Image
// › Transform & friends rewrite in place, without touching the Fill spec).
@@ -901,7 +901,7 @@ fn group_effect_maps_follow_child_visibility_and_opacity() {
.unwrap();
let render = |s: &Session| {
let d = &s.active().unwrap().doc;
photocraft_compose::render(d, d.bounds()).px
photocraft_compose::render(d, d.bounds()).into_px()
};
let mut prev = render(&s); // populate the effect-map cache
type Edit = (&'static str, fn(&mut photocraft_doc::Layer));
@@ -24,7 +24,7 @@ fn fixture(depth: u32) -> Session {
/// Compare the actual flattened document rather than just the imported parameters.
fn pixels(s: &Session) -> Vec<[f32; 4]> {
photocraft_compose::flatten(&s.active().unwrap().doc).px
photocraft_compose::flatten(&s.active().unwrap().doc).into_px()
}
/// Fractions remain valid native edits; strict integer ATN conversion must refuse them.
+1 -1
View File
@@ -24,7 +24,7 @@ fn fixture(depth: u32) -> Session {
/// Flatten the active document to compare direct, native and ATN playback pixels.
fn pixels(s: &Session) -> Vec<[f32; 4]> {
photocraft_compose::flatten(&s.active().unwrap().doc).px
photocraft_compose::flatten(&s.active().unwrap().doc).into_px()
}
/// Fractions are valid native edits, but the existing integer event cannot carry them.
@@ -37,7 +37,7 @@ fn doc_bounds() -> photocraft_doc::Rect {
}
fn pixels(s: &Session) -> Vec<[f32; 4]> {
photocraft_compose::flatten(&s.active().unwrap().doc).px
photocraft_compose::flatten(&s.active().unwrap().doc).into_px()
}
fn check_cases(id: &str, cases: &[Value], require_effect: bool) {
+1 -1
View File
@@ -23,7 +23,7 @@ fn fixture(depth: u32) -> Session {
/// Compare the flattened document, including alpha, rather than only imported JSON.
fn pixels(s: &Session) -> Vec<[f32; 4]> {
photocraft_compose::flatten(&s.active().unwrap().doc).px
photocraft_compose::flatten(&s.active().unwrap().doc).into_px()
}
/// Direct execution, native playback and strict binary ATN playback must agree exactly.
+1 -1
View File
@@ -124,7 +124,7 @@ fn photoshop_oracles_rerendered() {
}
};
let Ok(merged) = photocraft_io::merged_composite(&file) else { continue };
let ours = photocraft_compose::flatten(&doc).px;
let ours = photocraft_compose::flatten(&doc).into_px();
let (m, bad) = max_diff(&ours, &merged);
let group = name.split(['/', '\\']).next().unwrap_or(".").to_string();
let g = groups.entry(group).or_default();
+114
View File
@@ -0,0 +1,114 @@
//! One integration-test process keeps the process-wide scratch pool isolated from parallel unit
//! tests (#10479).
use photocraft_engine::Session;
use photocraft_engine::jobs::Started;
use photocraft_raster::scratch;
use serde_json::json;
use std::sync::{Mutex, PoisonError};
static SERIAL: Mutex<()> = Mutex::new(());
/// Holds the test lock with the pool's idle release off, so a slow runner can't empty the pool
/// between a command and the check after it; the release comes back on when dropped.
struct Quiet {
_serial: std::sync::MutexGuard<'static, ()>,
}
impl Quiet {
/// Locks the test process and disables idle pool release for this guard's lifetime.
fn new() -> Self {
let _serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner);
scratch::set_idle_release(false);
Quiet { _serial }
}
}
impl Drop for Quiet {
fn drop(&mut self) {
scratch::set_idle_release(true);
}
}
#[test]
/// Verifies closing one or all documents releases their scratch buffers.
fn closing_a_document_leaves_none_of_its_buffers_in_the_pool() {
let _q = Quiet::new();
for close in ["file.close", "file.closeAll"] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 1024, "height": 1024})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap();
// Dispatch holds the active document across the command; its tiles must not land in
// the pool after the release.
s.execute(close, json!({})).unwrap();
assert_eq!(scratch::retained_bytes(), 0, "{close}");
}
}
#[test]
/// Verifies a command that keeps its document does not release unrelated pooled buffers.
fn commands_that_keep_their_documents_keep_the_pool() {
let _q = Quiet::new();
let mut s = Session::new();
s.execute("file.new", json!({"width": 1024, "height": 1024})).unwrap();
scratch::give(vec![0u8; scratch::MIN_POOLED_BYTES]);
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
assert!(scratch::retained_bytes() > 0);
}
#[test]
/// Verifies a cancelled worker releases its document buffers after it exits.
fn a_cancelled_job_of_a_closed_document_returns_its_buffers_once_it_exits() {
let _q = Quiet::new();
let mut s = Session::new();
s.execute("file.new", json!({"width": 2048, "height": 2048})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
let Started::Job(_) = s.start("filter.blur.gaussianBlur", json!({"radius": 60})).unwrap() else {
panic!("Gaussian Blur runs as a background job");
};
// Closing cancels the job, but its worker still holds the document until it exits.
s.close(0);
scratch::give(vec![0u8; scratch::MIN_POOLED_BYTES]);
s.join_cancelled_jobs();
assert_eq!(scratch::retained_bytes(), 0);
}
#[test]
/// Verifies cancelling a job before document close still releases its buffers.
fn a_job_cancelled_before_its_document_closes_still_returns_its_buffers() {
let _q = Quiet::new();
let mut s = Session::new();
s.execute("file.new", json!({"width": 2048, "height": 2048})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
let Started::Job(id) = s.start("filter.blur.gaussianBlur", json!({"radius": 60})).unwrap() else {
panic!("Gaussian Blur runs as a background job");
};
// Cancelled first: the worker is already off the running list when the document closes.
assert!(s.cancel_job(id));
s.close(0);
scratch::give(vec![0u8; scratch::MIN_POOLED_BYTES]);
s.join_cancelled_jobs();
assert_eq!(scratch::retained_bytes(), 0);
}
/// Verifies polling alone releases buffers after a closed document's cancelled worker exits.
#[test]
fn a_cancelled_job_of_a_closed_document_is_released_by_polling() {
let _q = Quiet::new();
let mut s = Session::new();
s.execute("file.new", json!({"width": 2048, "height": 2048})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
let Started::Job(_) = s.start("filter.blur.gaussianBlur", json!({"radius": 60})).unwrap() else {
panic!("Gaussian Blur runs as a background job");
};
s.close(0);
// Seed after close so the close path cannot satisfy the assertion.
scratch::give(vec![0u8; scratch::MIN_POOLED_BYTES]);
assert!(scratch::retained_bytes() > 0);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while scratch::retained_bytes() > 0 && std::time::Instant::now() < deadline {
s.poll_jobs();
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert_eq!(scratch::retained_bytes(), 0);
}
+1
View File
@@ -15,6 +15,7 @@ photocraft-color = { workspace = true }
photocraft-raster = { workspace = true }
photocraft-doc = { workspace = true }
photocraft-codecs = { workspace = true }
craft-pcraft-format = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, features = ["unbounded_depth", "float_roundtrip"] }
thiserror = { workspace = true }
+1 -1
View File
@@ -451,7 +451,7 @@ fn sweep_orphans(recovery_dir: &Path, min_age: std::time::Duration) {
}
// Anything at the sidecar's path (even a broken one) keeps the bundle.
let has_sidecar = std::fs::symlink_metadata(recovery_dir.join(format!("{key}.json"))).is_ok();
let parts = [path.clone(), path.join("tiles"), path.join("blobs")];
let parts = [path.clone(), path.join(craft_pcraft_format::TILES_DIR), path.join(craft_pcraft_format::BLOBS_DIR)];
// A committed bundle is recoverable work: keep exactly what `list_recovery` lists.
if !has_sidecar && sidecarless_entry(recovery_dir, &path).is_none() && parts.iter().all(|p| untouched_for(p, min_age, true)) {
let _ = std::fs::remove_dir_all(&path);
+14 -7
View File
@@ -81,9 +81,7 @@ fn key4(s: &str) -> Result<[u8; 4]> {
unhex(s)?.try_into().map_err(|_| FormatError::corrupt(format!("bad 4-byte key `{s}`")))
}
pub(crate) fn is_valid_hash(h: &str) -> bool {
h.len() == 64 && h.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
pub(crate) use craft_pcraft_format::is_valid_hash;
/// Convert native-endian sample bytes to little-endian in place (and back:
/// the swap is an involution).
@@ -110,7 +108,7 @@ fn surface_m(s: &Surface, sink: &mut dyn Sink) -> SurfaceM {
let mut dp = vec![0u8; f.bytes_per_pixel()];
encode_pixel(&f, &s.default_pixel(), &mut dp);
swap_to_le(&mut dp, f.sample);
SurfaceM { format: f, default: hex(&dp), tiles: s.tiles().map(|(c, t)| TileRef { tx: c.tx, ty: c.ty, hash: sink.tile(f, t) }).collect() }
SurfaceM { format: f, default: hex(&dp), tiles: s.tiles().map(|(c, t)| TileRef::new(c.tx, c.ty, sink.tile(f, t))).collect() }
}
fn opt_blob(b: &Option<Arc<Vec<u8>>>, sink: &mut dyn Sink) -> Option<Hash> {
@@ -159,7 +157,16 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
psd_raw: opt_blob(&s.psd_raw, sink),
path: s.path.clone(),
stroke: s.stroke.clone(),
live: s.live.clone(),
// Older PhotoCraft versions cannot deserialize ArrowLine.
// The saved path preserves the arrow's visual appearance.
live: match &s.live {
Some(photocraft_doc::LiveShape::ArrowLine { .. }) => None,
other => other.clone(),
},
arrow_live: match &s.live {
Some(arrow @ photocraft_doc::LiveShape::ArrowLine { .. }) => Some(arrow.clone()),
_ => None,
},
density: s.density,
feather: s.feather,
},
@@ -480,11 +487,11 @@ impl Loader<'_> {
warp: warp.clone(),
})
}
ContentM::Shape { fill, cache, psd_raw, path, stroke, live, density, feather } => LayerContent::Shape(ShapeLayer {
ContentM::Shape { fill, cache, psd_raw, path, stroke, live, arrow_live, density, feather } => LayerContent::Shape(ShapeLayer {
path: path.clone(),
fill: fill.clone(),
stroke: stroke.clone(),
live: live.clone(),
live: arrow_live.as_ref().filter(|shape| matches!(shape, photocraft_doc::LiveShape::ArrowLine { .. })).cloned().or_else(|| live.clone()),
cache: self.opt_surface(cache)?,
psd_raw: self.opt_blob(psd_raw)?,
density: *density,
+19 -4
View File
@@ -50,7 +50,7 @@ pub use read::read_file;
pub use store::{ByteSource, DEFAULT_REVERIFY_BUDGET, PcraftWriter, SaveStats, read_entry};
/// File extension of the native format.
pub const EXTENSION: &str = "pcraft";
pub use craft_pcraft_format::EXTENSION;
#[derive(Debug, thiserror::Error)]
pub enum FormatError {
@@ -76,6 +76,20 @@ impl FormatError {
}
}
impl From<craft_pcraft_format::Error> for FormatError {
fn from(e: craft_pcraft_format::Error) -> Self {
use craft_pcraft_format::Error;
match e {
Error::Corrupt(m) => FormatError::Corrupt(m),
Error::Unsupported(m) => FormatError::Unsupported(m),
Error::TooNew { found, supported, .. } => FormatError::TooNew { found, supported },
Error::LimitExceeded(m) => FormatError::LimitExceeded(m),
Error::Json(e) => FormatError::Json(e),
other => FormatError::Corrupt(other.to_string()),
}
}
}
pub type Result<T> = std::result::Result<T, FormatError>;
/// Previews to embed. The format crate cannot render (it sits beside the
@@ -119,10 +133,11 @@ pub const MAX_CANVAS_PIXELS: u64 = MAX_CANVAS_SIDE as u64 * MAX_CANVAS_SIDE as u
impl Default for LoadOptions {
fn default() -> Self {
let limits = craft_pcraft_format::Limits::default();
LoadOptions {
max_manifest_bytes: 256 << 20,
max_blob_bytes: 1 << 30,
max_total_bytes: 16 << 30,
max_manifest_bytes: limits.max_manifest_bytes,
max_blob_bytes: limits.max_blob_bytes,
max_total_bytes: limits.max_total_bytes,
preserve_ids: true,
max_canvas_side: MAX_CANVAS_SIDE,
max_canvas_pixels: MAX_CANVAS_PIXELS,
+8 -24
View File
@@ -14,24 +14,11 @@ use photocraft_doc::{
use photocraft_geom::{Affine, Size};
use serde::{Deserialize, Serialize};
/// Current manifest version written by this build.
pub const FORMAT_VERSION: u32 = 1;
pub use craft_pcraft_format::{FORMAT_VERSION, Hash, TileRef};
/// Hex-encoded BLAKE3 hash (64 chars).
pub type Hash = String;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Manifest {
pub format_version: u32,
/// Free-form writer identification, e.g. `photocraft-format 0.1.0`.
pub generator: String,
pub document: DocM,
/// Optional previews present in the bundle.
#[serde(default)]
pub thumbnail: Option<String>,
#[serde(default)]
pub composite: Option<String>,
}
/// The manifest: craft-pcraft-format's envelope (`format_version`, `generator`, the optional
/// `thumbnail` and `composite` previews) around the document [`DocM`].
pub type Manifest = craft_pcraft_format::Manifest<DocM>;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DocM {
@@ -154,13 +141,6 @@ pub struct NamedPathM {
pub psd_raw: Option<Hash>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TileRef {
pub tx: i32,
pub ty: i32,
pub hash: Hash,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SurfaceM {
pub format: PixelFormat,
@@ -300,6 +280,10 @@ pub enum ContentM {
stroke: Option<ShapeStroke>,
#[serde(default)]
live: Option<LiveShape>,
/// Arrow parameters stored separately for backward compatibility.
/// Older PhotoCraft versions ignore this optional field.
#[serde(default, skip_serializing_if = "Option::is_none")]
arrow_live: Option<LiveShape>,
/// The path's density as the fill's mask; older files have none (100 %).
#[serde(default = "full_density")]
density: f32,
Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff. Show more